Motion films that never cut to the next slide: every beat grows out of the one before, one continuous camera, continuity measured by an oracle. Product launch films and feature demos, made with a coding agent.
feat: open-source onetake, a motion-film skill for continuous launch films
feitangyuan79361d0f3acd
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..2348c91--- /dev/null+++ b/.gitignore@@ -0,0 +1,3 @@+.DS_Store+__pycache__/+*.pycdiff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..51071c3--- /dev/null+++ b/LICENSE@@ -0,0 +1,75 @@+Required Notice: Copyright (c) 2026 Patrick. onetake is free for noncommercial use only.++# PolyForm Noncommercial License 1.0.0++<https://polyformproject.org/licenses/noncommercial/1.0.0>++## Acceptance++In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.++## Copyright License++The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).++## Distribution License++The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).++## Notices++You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:++> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)++## Changes and New Works License++The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.++## Patent License++The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.++## Noncommercial Purposes++Any noncommercial purpose is a permitted purpose.++## Personal Uses++Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.++## Noncommercial Organizations++Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.++## Fair Use++You may have "fair use" rights for the software under the law. These terms do not limit them.++## No Other Rights++These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.++## Patent Defense++If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.++## Violations++The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.++## No Liability++***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***++## Definitions++The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.++**You** refers to the individual or entity agreeing to these terms.++**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.++**Your licenses** are all the licenses granted to you for the software under these terms.++**Use** means anything you do with the software requiring one of your licenses.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..b84f5f8--- /dev/null+++ b/README.md@@ -0,0 +1,227 @@+# onetake++> **Motion films that never cut to the next slide.** A Claude Agent Skill that makes product launch films, teasers and feature demos where every beat grows out of the one before — one continuous take, not a stack of scenes.+> **一镜到底的连贯动效。** 做产品发布片、预告片、功能演示:每一个画面都从上一个画面里长出来,是一整条连续的镜头,而不是一张张轮流出场的"PPT"。++[](LICENSE)+[](SKILL.md)+[](cases/)+[](scripts/verify_promo.py)++++<sub>From onetake's own launch film. A prompt bar opens into the ad it asked for; the next prompt collapses into a line that shoots across the desk and opens into a festival screen. No cut. [Full film with sound →](cases/onetake-launch-30s/onetake-launch.mp4)</sub>++---++[English](#english) | [中文说明](#chinese)++---++<a name="english"></a>+## English++### The problem: motion that falls apart++Most motion videos an AI makes today — and most template tools — come out **loose**. Title card, fade, UI shot, fade,+feature card, fade, logo. Each shot can look fine and the whole still reads like a slideshow, because nothing+connects one beat to the next: scenes *replace* each other.++### What onetake does differently: every beat is carried++onetake treats the boundary between two beats as the thing to design. At every boundary, **something on screen+survives and visibly becomes the next beat**:++- the prompt bar **opens into** the app window; the window **reflows into** the phone;+- a bar **collapses into a line**, the line **shoots across** the desk and **becomes the first grid line** of the next film;+- a card **grows into** the page; a stage **opens from** the character; the camera **pushes through** a card until it *is* the next scene;+- at the end, the cast **folds into** the lockup — in the launch film, the block cursor **writes the name** in one stroke.++And **one camera holds it all together**. It never cuts: it follows the subject a beat ahead, whips to where the next+thing will land, floats like a hand-held operator and shakes when something hits — then holds dead still, because rests+are what make the moves land.++### Continuity is measured, not hoped for++Every film is checked by an oracle before a human watches it. `probe.py` records what is on screen in every frame, finds+each boundary, and asks what carried across it. A film whose beats replace each other fails.++| film | verdict | continuity (carry score) |+|---|---|---|+| an earlier launch film, v1 — perfect rhythm, still a slideshow | rejected | **0.00** |+| the same film, v2 | rejected | **0.40** |+| the same film, v3 — every beat grows out of the last | accepted | **0.75** |+| onetake launch film | accepted | **0.83** |++The same oracle fails uniform cadence (shots all the same length), no stillness, clipped audio, fast moves without+motion blur, and a subject that leaves the frame.++### What makes it look finished++- **Real UI, rebuilt.** The product's interface is rebuilt in HTML from screenshots and sits on the camera's plane, so the camera can fly into it at any zoom. No screen recording.+- **Measured moves.** ~38 moves (springs, entrances, carries, contact, sims, camera, fluid grounds), each a pure function of time with its speed curve measured — never a hand-rolled ease.+- **Real motion blur.** Every moving frame is several captures across an open 180° shutter, averaged in linear light. Fast moves smear instead of strobing.+- **Sound in one room.** Foley and synthesis placed from the film's own events, in one reverb, ducking the music under the hits.+- **Deterministic.** Seek to any time, get the same frame. Drafts at 1080p30, finals at 4K60.++### 🌟 Films made with it++Every case ships the finished film and a breakdown (concept, beat sheet, numbers, what was rejected and why). The+films' source code is not included.++<table>+ <tr>+ <td width="50%" align="center"><b>onetake launch</b><br/><img src="assets/cases/onetake-launch.gif" width="100%"/><br/>+ <sub>Three prompts, three films, one take — each prompt visibly becomes its film</sub><br/>+ <a href="cases/onetake-launch-30s/onetake-launch.mp4">▶ Film</a> | <a href="cases/onetake-launch-30s/README.md">📖 Breakdown</a></td>+ <td width="50%" align="center"><b>one-dot</b><br/><img src="assets/cases/one-dot.gif" width="100%"/><br/>+ <sub>One dot is the whole film: caret → menu → loading ring → spring curve → the dot on the i</sub><br/>+ <a href="cases/one-dot-15s/one-dot.mp4">▶ Film</a> | <a href="cases/one-dot-15s/README.md">📖 Breakdown</a></td>+ </tr>+ <tr>+ <td align="center"><b>knockon</b><br/><img src="assets/cases/knockon.gif" width="100%"/><br/>+ <sub>A chain reaction: every beat is the collision that starts the next</sub><br/>+ <a href="cases/knockon-15s/knockon.mp4">▶ Film</a> | <a href="cases/knockon-15s/README.md">📖 Breakdown</a></td>+ <td align="center"><b>clearing</b><br/><img src="assets/cases/clearing.gif" width="100%"/><br/>+ <sub>One zoom from a year to a free half hour — 1× to 300× and back, never a cut</sub><br/>+ <a href="cases/clearing-15s/clearing.mp4">▶ Film</a> | <a href="cases/clearing-15s/README.md">📖 Breakdown</a></td>+ </tr>+ <tr>+ <td align="center"><b>pith</b><br/><img src="assets/cases/pith.gif" width="100%"/><br/>+ <sub>The window grows out of one phosphor pixel: 440× → 0.52× in one move</sub><br/>+ <a href="cases/pith-21s/pith.mp4">▶ Film</a> | <a href="cases/pith-21s/README.md">📖 Breakdown</a></td>+ <td align="center"><b>ebb</b><br/><img src="assets/cases/ebb.gif" width="100%"/><br/>+ <sub>A field of light carries the take through five places; each flood drains onto the next</sub><br/>+ <a href="cases/ebb-15s/ebb.mp4">▶ Film</a> | <a href="cases/ebb-15s/README.md">📖 Breakdown</a></td>+ </tr>+ <tr>+ <td align="center"><b>overlap</b><br/><img src="assets/cases/overlap.gif" width="100%"/><br/>+ <sub>Two print passes slide into register — and an & appears that was hidden in both</sub><br/>+ <a href="cases/overlap-15s/overlap.mp4">▶ Film</a> | <a href="cases/overlap-15s/README.md">📖 Breakdown</a></td>+ <td align="center"><b>unbroken</b><br/><img src="assets/cases/unbroken.gif" width="100%"/><br/>+ <sub>One ink stroke that is never lifted: procedural brush, no textures</sub><br/>+ <a href="cases/unbroken-15s/unbroken.mp4">▶ Film</a> | <a href="cases/unbroken-15s/README.md">📖 Breakdown</a></td>+ </tr>+ <tr>+ <td align="center"><b>motion-web</b><br/><img src="assets/cases/motion-web.gif" width="100%"/><br/>+ <sub>Where the rhythm rules came from: small UI, big ground, rests, then a burst</sub><br/>+ <a href="cases/motion-web-15s/motion-web.mp4">▶ Film</a> | <a href="cases/motion-web-15s/README.md">📖 Breakdown</a></td>+ <td align="center"><b>skill-demo</b><br/><img src="assets/cases/skill-demo.gif" width="100%"/><br/>+ <sub>An operation demo from nothing: the chosen menu row flies into the input as a chip, and on from there</sub><br/>+ <a href="cases/skill-demo-15s/skill-demo.mp4">▶ Film</a> | <a href="cases/skill-demo-15s/README.md">📖 Breakdown</a></td>+ </tr>+</table>++> one-dot and skill-demo were made when the skill was still called *ohmymotion*; the films show that name.++### How a film is made++1. **Deconstruct the reference in numbers:** how much of it is still, where it cuts, how its moves ease.+2. **Three concepts, pick one.** Each is one sentence about the *picture* — "one dot becomes everything", "one zoom through scale" — not three stories told with the same cards.+3. **A beat sheet for rhythm *and* carry.** Shot lengths vary by ≥ 4×, and every boundary names what survives it.+4. **Compose** one HTML file on the move library. **Render** with motion blur. **Score** the sound from the film's events.+5. **Verify**, then show a human.++### 📦 Installation++```bash+# Claude Code+git clone https://github.com/feitangyuan/onetake.git ~/.claude/skills/onetake+# Codex / other agents that read skills+git clone https://github.com/feitangyuan/onetake.git ~/.agents/skills/onetake+```++Then ask: *"Make a 15 s launch video for my app"*, *"a feature demo rebuilt from these screenshots, no screen+recording"*, *"my motion video feels like a slideshow — fix it"*.++**Requires** python3 with `playwright` (chromium), `numpy`, `scipy`, `Pillow`, `matplotlib` (`opencv-python` for+reference analysis), `ffmpeg`, `node`. Narration adds `faster-whisper` and Kokoro TTS. Music is royalty-free by default.++| | |+|---|---|+| `SKILL.md` | the protocol and the hard rules each rejected cut taught |+| `lib/motion.js` · `lib/ui_kit.js` | the move library; the UI-rebuild kit |+| `scripts/` | render (motion blur, 4K60), verify (the oracle), probe, stills, reference analysis, footage, narration, sound |+| `gallery/` | one live demo and one six-frame sheet per move |+| `references/` | rhythm, carry, composition, camera, sound, product demos — the method with its numbers |++### License++[PolyForm Noncommercial 1.0.0](LICENSE): free for personal, educational, research and other noncommercial use.+**Commercial use is not permitted.**++---++<a name="chinese"></a>+## 中文说明++### 问题:动效是散的++现在大多数 AI 做出来的动效视频,还有大多数模板工具做出来的,都是**散的**。+标题卡、淡出、界面镜头、淡出、功能卡片、淡出、Logo。每一镜单看也许都不错,合起来还是像在翻 PPT。+原因是画面和画面之间没有任何联系,后一个场景只是把前一个**替换**掉了。++### onetake 不一样:每个画面都被"接住"++onetake 把两个画面之间的交接处当成设计的重点。每一个交接处,**都有一个东西活下来,并且看得见地变成下一个画面**:++- 输入框**展开成** App 窗口,窗口再**重排成**手机界面;+- 输入框**压成一条线**,这条线**划过桌面**,**变成**下一条片子的第一根网格线;+- 卡片**长成**整个页面;舞台从角色身上**打开**;镜头**穿过**一张卡片,穿过去就是下一个场景;+- 结尾,所有元素**收拢成**标志。在 onetake 自己的发布片里,是光标一笔**写出**名字。++**把这一切串起来的是同一个镜头。** 它从不剪断:提前半拍跟着主体走,抢在下一个东西落地前甩过去,像手持一样轻微浮动,东西撞上来时跟着一震;+该停的时候又能完全静止,因为有停顿,动作才落得下来。++### 连贯是量出来的,不是靠感觉++每条片子给人看之前,先过一遍自动验收。`probe.py` 记录每一帧画面上有什么,找出每一个交接处,再判断有没有东西从这边带到那边。+画面互相替换的片子,直接判不合格。++| 片子 | 结果 | 连贯度(carry score) |+|---|---|---|+| 更早的一条发布片 v1:节奏完美,仍然像 PPT | 被否 | **0.00** |+| the same film, v2 | 被否 | **0.40** |+| 同一条片子 v3:每个画面从上一个里长出来 | 通过 | **0.75** |+| onetake 发布片 | 通过 | **0.83** |++同一套验收还会判掉这些问题:镜头长度全都一样、没有静止段落、音频爆音、快动作没有运动模糊、主体出画。++### 为什么看起来像成品++- **复刻的真实界面**:按截图用 HTML 重建产品界面,放在镜头所在的平面上,推到多近都清楚,不需要录屏。+- **实测过的动作**:约 38 个动作(弹簧、入场、衔接、碰撞、物理模拟、镜头、流体光场),每个都是时间的纯函数,速度曲线都实测过,不用随手写的缓动。+- **真实运动模糊**:每个运动帧都是快门张开期间的多次采样,在线性光下平均。快动作会拖出残影,而不是一格一格地闪。+- **同一个空间里的声音**:音效按片子里的事件摆放,放在同一个混响里,打点的地方音乐自动让位。+- **结果确定**:跳到任意时间,得到的都是同一帧。草稿 1080p30,成片 4K60。++### 案例++上面的表格里有 10 条用它做的片子,每条都附成片和拆解文档(概念、节拍表、数据、被否掉的版本和原因)。**不包含片子的源代码。**+其中 one-dot 和 skill-demo 做的时候 skill 还叫 *ohmymotion*,画面里是旧名字。++### 一条片子怎么做出来++1. **先把参考片拆成数字**:静止占多少、在哪里剪、动作怎么缓动。+2. **出三个概念,选一个**:每个概念是一句关于画面的话,比如"一个点变成一切""一个镜头穿过所有尺度",而不是同一套卡片换三种讲法。+3. **写节拍表,节奏和衔接都要写**:镜头长短相差 4 倍以上,每个交接处都写明是什么东西活下来。+4. **合成、渲染、配音**:在动作库上写一个 HTML 文件,带运动模糊渲染,按片子里的事件配声音。+5. **过验收,再给人看。**++### 安装++```bash+# Claude Code+git clone https://github.com/feitangyuan/onetake.git ~/.claude/skills/onetake+# Codex 等读取 skills 的 Agent+git clone https://github.com/feitangyuan/onetake.git ~/.agents/skills/onetake+```++然后直接说:「给我的 App 做个 15 秒发布视频」「按这几张截图复刻界面做功能演示,不录屏」「我的动效视频像 PPT,帮我改」。++**依赖**:python3(`playwright` + chromium、`numpy`、`scipy`、`Pillow`、`matplotlib`,分析参考片需要 `opencv-python`)、`ffmpeg`、`node`。+配音需要 `faster-whisper` 和 Kokoro TTS。音乐默认用免版权曲库。++### 许可证++[PolyForm Noncommercial 1.0.0](LICENSE):个人、学习、研究等**非商业用途免费使用,不允许商用**。diff --git a/SKILL.md b/SKILL.mdnew file mode 100644index 0000000..612f66c--- /dev/null+++ b/SKILL.md@@ -0,0 +1,249 @@+---+name: onetake+license: PolyForm Noncommercial 1.0.0 (free for noncommercial use; see LICENSE)+description: "Make short product / skill motion videos (10–30 s, narrated feature demos up to ~60 s) the way high-end launch clips are made — kinetic type, real UI as the material, a hand that causes every reaction, beats that carry into each other instead of replacing each other, hard cuts only where they mean something — without HyperFrames or Remotion. A single HTML composition where every value is a pure function of time, built from a library of measured moves (springs, entrances, carries, contact, camera), rendered frame by frame with real shutter motion blur (1080p30 drafts, 4K60 final), with synthesised sound effects that share one room and an oracle that fails a slideshow before a human has to watch it. Use for 做个动效短片 / 产品宣传片 / 介绍视频 / 发布视频 / 15 秒 launch video / 给 skill 或 app 做个视频 / promo / teaser, for turning real pages or screen recordings into a cut, for product feature demos (产品功能演示 / 功能展示动效) where the UI is rebuilt in HTML from screenshots instead of screen-recorded (不录屏 / 复刻界面 / 截图还原 UI), for narrated cuts with voice-over and subtitles (配音 / 字幕 / 换配音) and for the same film in other languages (日语版 / 多语言 / 本地化), for adding motion vocabulary (动效库 / 转场 / 衔接), and for auditing why a motion video reads as a slideshow (像 PPT / 没节奏 / 一个一个展示 / 转场生硬)."+---++# onetake++Short motion films about a product, built from the product. Not a video editor, not a slideshow+generator: a **composition** (one HTML file, `window.__seek(t)`), a **move library** (`lib/motion.js`),+**footage** recorded from the real thing, a **sound palette** that shares one room, and an **oracle**+that says whether the cut has a rhythm and whether it carries, before a human has to watch it.++Six films taught it. **motion-web** took three cuts: one and two were rejected as 「PPT 式一个一个展示」+for a uniform cadence — the rhythm half. **Pocket Weather Club** had the rhythm and was *still* PPT: its v1+passed every rhythm check and was rejected, because each beat replaced the one before. v3 was accepted when+every beat grew out of the last — the character lands on the headline, the page grows out of its card, a+stage opens from the character. That is the carry half. **One dot** added the operator: with a still camera it was+「就缺灵动的跟踪运镜」; with a camera that chases what each beat frames — lagging, leaning, settling — it was+「运镜、镜头和物理都没问题」. **knockon** carried by cause: a light tabletop machine where every beat is the collision+that starts the next. **clearing** carried by scale: one take from a year to a free half hour and back, a camera that+chases the anchor on screen so it lands the same at 1× and 300×. **overlap** was the meaning lesson: its first cut was+「美术挺棒但没看出来啥意思」, and adding labelled cursors made it worse; it read only once the idea was built into the+artwork — an & hidden in two noise plates that appears at the instant the passes come into register. Everything here+exists so the next film starts where those films ended.++## When this skill, and when not++- A launch / teaser / intro clip for an app, a page, a skill, a feature — **yes**.+- A narrated feature demo (30–60 s) that shows the product being used, possibly in several languages — **yes**:+ rebuild the UI instead of recording it (§4, `references/product-demo.md`).+- The user has a reference clip they want the *feel* of — **yes**, start at §1.+- Long-form, talking-head, editing existing footage with transitions — **no**.+- The user names HyperFrames or Remotion explicitly — use what they name. Otherwise this pipeline.++## The protocol — in this order, no skipping++### 1 · Deconstruct the reference before touching anything (硬规则)++```bash+python3 scripts/analyze_ref.py ref.mp4 --out ana/ # energy map, cuts, stillness, contact sheets, motion line+```++Read the energy map and the sheets and write down the numbers the film has to match. The energy map says *when*+the film moves; the `motion:` line says *how* —+median t80 (snaps or S-curves) and smear (rendered with motion blur or not). What decided the motion-web film:+the reference was **34 % dead-still**, had **7 hard cuts** in two bursts, and kept every element **small with a+lot of white space**. None of that is obvious from watching once, and a film built without measuring it came+out on a uniform cadence — twice. `references/reference-deconstruction.md`.++### 2 · Concept — three central ideas before any beat sheet (硬规则)++A concept is one sentence about the *picture*, not the product: the single idea the film is made of. Write three+that differ in that idea — not three stories told with the same cards:++- **one element transforms through everything** — a dot is the caret, splits into the skill list, hollows into a+ loading ring, unrolls into a spring curve, lands as the dot on the i of the wordmark;+- **one camera move through scale** — start inside the caret, pull out to the input, dive through the send button+ into the work, come out through the finished film (`cases/clearing-15s`: a year → one day → a half hour → back);+- **a before/after split** — the same beats as a slideshow on the left and carried on the right, until the right+ side breaks into the left;+- **a chain reaction** — every beat is the collision that starts the next (`cases/knockon-15s`);+- or a physical metaphor, one continuous surface, a typographic system…++For each: the hook frame, what carries every boundary, what it rules out (no cards? no cuts?). Show the three and+let the user pick. The template's story — kinetic words → typed prompt → ticking checklist → result → staccato+hits → black wordmark — is one concept, never the default: an operation demo built on it passed every oracle leg+(carry 1.00) and was sent back as 「和 motion web 很像…没有创造力」.++### 3 · Storyboard as rhythm *and* carry++Write the chosen concept as a **beat sheet**: `t · beat · what moves · what is still · what carries into the next+beat`.++**Rhythm.** Vary shot length by ≥ 4× (0.25 s words next to 2.5 s holds). At least one stretch of near-silence in+picture and sound. One story — the concept's — not a catalogue. Small elements, big ground.++**Carry.** At every section boundary, name the thing that survives it and moves: the hand, the subject, a+container that becomes the next scene (`morphRect`), a stage that opens from the subject (`iris`), a camera that+pushes into a card until it is the scene (`zoomThrough`), a cast that folds into the lockup (`gather` → `seal`).+If nothing survives, it is a slide change, whatever the rhythm. Bare cuts belong to bursts of hits and the end+card, when the concept has them. `references/rhythm.md`.++### 4 · Footage from the real thing — or the UI rebuilt from screenshots++```bash+python3 scripts/record_footage.py footage.json --out footage/+```++Real pages, driven in real time by Playwright (wall-clock-paced sweeps, wheel steps, clicks),+recorded at the size you will show them, with a magenta marker injected the instant the input starts+so the action frame is findable afterwards. Frames come out at 30 fps as JPEG; the pointer path is+saved so the composition can draw the hand back in — **the viewer must see the cause, not just the+effect**. Config format in the script's docstring.++**Or rebuild it.** When the film walks through an app's features (and above all when it has a voice or other+languages), the user screenshots or records only reference takes, and the UI is rebuilt in HTML in the reference's+own pixel frame. Every string lives in a table, every state is written by a pure `set(state)`, and the replica sits+on the plane where the camera can close in at any zoom. Highlights are measured from its DOM (`lib/ui_kit.js`).+Narration comes from `scripts/vo_tools.py`: audition, lines, word times, subtitles. A second language is `?lang=`+on the same comp, its VO mapped onto the authored timeline by `UIK.timeWarp` knots on words that mean the same+thing, checked pixel-identical for the source language with `scripts/frame_diff.py`. The content stays the product's+real output. Method, numbers and what bit: `references/product-demo.md`. It is a technique, not a look: palette,+stage, camera grammar and transitions are chosen fresh in §2 every time.++### 5 · Compose — one file, pure functions of time, moves from the library++```bash+mkdir -p cases/my-film && cp templates/comp.html lib/motion.js cases/my-film/ # the template loads motion.js → window.OM+python3 scripts/probe.py my-film/comp.html # as soon as it plays end to end: what carries each boundary, each move's curve+```++Pick moves by looking at `gallery/sheets/<move>.png` — six frames over the speed curve of what moves. The library+has 39: entrances, carries, contact and live sims, camera and its projection helpers, and a fluid set (a light field, ripples, silk, a belt, SwiftUI springs); each is a function of time returning numbers for a DOM+transform or a canvas call. Never re-derive a spring or an ease with fixed constants. The template is the+motion-web film (kinetic words, typed prompt, ticking checklist, fly-throughs, live sims, a hold, staccato hits,+one continuous hand path every sim reads from) — copy its beats only when that is the concept picked in §2;+otherwise keep its contract and helpers and write the concept's own beats. Everything is `f(t)`; sims are pre-simulated once at 240 Hz and+sampled. Preview `?play`, pin `?t=6.4&hud`. `references/motion-library.md`, `references/composition.md`.++**Camera: keyed, but operated.** `OM.camera(t, keys)` puts the camera where each beat needs it; the feel of an+operator comes from how the keys are placed: key the subject ~0.1 s ahead on `sineInOut` to follow it, key the landing+point before a snap on `expoInOut` to whip to it, add a hand (a slow two-sine float, zero in the holds) and `OM.shake`+on every landing. Draw a faint `OM.lattice` farther back, or on an empty ground the move doesn't read. With a camera,+`__track` returns screen boxes (`OM.projectBox`), `__motion` hands render.py the travel, and `__meta.inFrame` names+what must never leave the frame. The method, with code: `references/composition.md` → *A camera*.++### 6 · Render — 1080p30 drafts, 4K60 only after acceptance++```bash+python3 scripts/stills.py comp.html --times 0.7,2.4,3.8,6.2,9.9,12.7 --out stills.png # look before you render+python3 scripts/render.py comp.html --out draft.mp4 --sfx sfx.wav # 1920×1080 · 30 fps · 180° shutter+python3 scripts/render.py comp.html --out film.mp4 --final --sfx sfx.wav # 3840×2160 · 60 fps, once the cut is accepted+```++The shutter is real motion blur: each moving frame is several seeks across the open shutter, averaged in linear+light; holds are detected and skip it. A capture is a Chrome screenshot (~150 ms; the page itself draws in under 1 ms),+so render.py runs `--workers` browsers in parallel processes (default cores − 2, max 8). A page that defines+`window.__motion(t0, t1)` — the farthest anything travels on screen, camera included — gets as many captures per frame+as keep copies 6 px apart (4–48); a fixed 8 stepped the one-dot film's 633 px/frame opening into bands. Budget: the+one-dot camera cut took 103 s for 2,480 captures on 8 workers (one browser: ~0.2 s a capture, ~8.5 minutes) — tell+the user the estimate before starting a long render.++### 7 · Sound — a palette in a room, never one beep per event++```bash+python3 scripts/sfx_palette.py --demo demo.wav # quick pass: the synthetic palette (see templates/sfx_score.example.py)+python3 dump_events.py && python3 score.py # the films since one-dot: the comp's __events() → recorded + synthesised mix+```++Two ways, one rule. The **palette** is five synthesised materials (air, wood, glass, sub, bubble) in one reverb, peaks+at −8 dBFS so music can sit on top — enough for a draft. Every accepted film since one-dot uses a **score.py**: recorded+sources (Kenney's CC0 packs, UIowa MIS, Voxengo IRs — not shipped here; download them yourself) layered with synthesis, timed and panned+from `window.__events()`, convolution reverb, the music ducked under the hits, mastered to −16 LUFS with the ceiling+low enough (−3.5 to −4 dBTP) that the AAC render stays under verify's −3 dBFS. Fewer events than beats either way: the+first motion-web pass put a raw sine pop on every event and was rejected as 低劣 within a minute. Before shipping any+recorded source inside a product, check its licence (Mixkit's does not allow redistributing the files). `references/sound.md`.++**Music is royalty-free by default.** Look for a track licensed for reuse (NCS, Pixabay Music, the YouTube Audio+Library, Free Music Archive under a CC licence that allows it) and keep its source and licence next to the score. A+commercial or copyrighted track goes in only when the user supplies it and says so; never pull one in on your own.++### 8 · Verify before showing++```bash+python3 scripts/verify_promo.py draft.mp4 --comp comp.html --ref ref.mp4 --shots 0,1.6,3.0,4.8,7.0,9.6,12.1,13.25,14.3+```++Rhythm legs fail uniform shot lengths, no dead-still stretch, clipped or never-quiet audio. **burst** fails only+when `--ref` has one and the film doesn't; without a reference it is a warning — a concept without hits isn't wrong.+**continuity** fails beats that replace each other (carry score < 0.5) — the only leg that failed both rejected+Pocket Weather cuts (v1 0.00, v2 0.40) while the accepted films passed (v3 0.75; motion-web 0.56, a warning).+**curves** fails fast moves (> 80 px/frame) in a film without shutter blur. **framing** fails any frame where an id+in `__meta.inFrame` is off frame (or, marked `'whole'`, cut) — the one-dot film's first camera render lost its dot+behind a snap and nothing else noticed. With `--ref`, the reference's energy map and motion line print alongside.++## Hard rules (each one cost a cut)++- **Never default to the template's story.** Three concepts that differ in their central idea; the user picks+ (§2). A new film in the template's beats reads as the template, however good the craft.+- **Never carry the last film's look into the next.** Palette, stage, camera grammar, transitions: the tools+ (replica, narration, time warp) are reusable, the look is not. Name those choices in the concept round.+- **A second language never forks the composition.** `?lang=`, a time warp, and the source cut checked+ pixel-identical. A copied comp doubles every later fix.+- **Never cut on a metronome.** Equal shot lengths read as slides no matter how good each shot is.+- **Never replace a beat — carry it.** Something on screen survives every section boundary and visibly moves or+ scales into the next beat. Mutually exclusive scenes (`display:none` swaps) are slides even with perfect rhythm.+ The exceptions are a burst of hard-cut hits and the end card.+- **Never show a page as a thumbnail expecting its motion to read.** Either full-frame with the hand, or+ a *component* of it live in a card. Small cards of whole pages showed nothing.+- **Never let the frame be always in motion.** Rests are what make the bursts land; the reference is+ still a third of the time.+- **Small elements, big ground.** The genre's frame is 70 % white. Full-bleed footage is the exception+ (one calm hold), not the rule.+- **The cause must be visible.** The hand drawn from the recorded path, or the concept's own subject — a dot that+ splits, a ball that lands. A page reacting to nothing reads as a screensaver.+- **Moves from the library, curves chosen by t80.** One hand-rolled smootherstep everywhere makes every move the+ same soft S-curve; snaps (`ease.expoOut`, t80 .23) and springs are what lands.+- **Fast moves need the shutter.** Over 80 px/frame without motion blur strobes into copies. render.py's default+ shutter is the fix; CSS blur is not.+- **A camera that chases, and never loses the subject.** A still camera left the one-dot film 「就缺灵动的跟踪运镜」;+ a camera that chases what each beat frames was accepted. Declare `__meta.inFrame`; for a snap, key where it lands+ before it moves.+- **Drafts at 1080p30.** No 4K60 render before the cut is accepted.+- **No particles / confetti / speck bursts.** They read as a template. Let the type itself land with+ squash and wobble if a beat needs a flourish.+- **One material set for sound, one room.** Every event getting its own synth tone is the audio version+ of the slideshow.+- **Everything deterministic.** `__seek(t)` twice must give the same frame — the shutter depends on it; sims are+ precomputed from a fixed seed; no `Math.random()` on the render path (`OM.rng(seed)`).++## Files++| path | what |+|---|---|+| `lib/motion.js` | the move library → `window.OM`: curves, springs, entrances, carries, contact, sims, camera, fluid |+| `lib/ui_kit.js` | → `window.UIK`: a rebuilt UI on the plane (`stage`, `domLocal`, `rectCache`, `flow`), the content-hugging `glowRing`, legibility (`screenPx`, `zoomFor`), languages (`tr`, `loadFont`), `timeWarp` between a narration and the authored timeline, `subAt` |+| `gallery/gallery.html` | one live demo per move (`?demo=ribbon&play`); `gallery/sheets/<move>.png` six frames + speed graph |+| `scripts/analyze_ref.py` | reference → energy map, cuts, stillness, contact sheets, motion line (t80, smear), JSON |+| `scripts/record_footage.py` | config → real-time recordings with action marker → 30 fps frames + paths |+| `scripts/probe.py` | comp → what is on screen per frame → continuity per boundary, curves per move |+| `scripts/render.py` | comp → mp4: 1080p30 draft by default, `--final` 4K60, shutter motion blur sized by `__motion`, parallel `--workers`, `.render.json` |+| `scripts/stills.py` | comp → contact sheet of chosen times |+| `scripts/vo_tools.py` | narration: `tts` (Kokoro, English and Japanese via a kana reading, auditions), `words` (faster-whisper), `plan` (line starts), `subs` (chunked, timed) |+| `scripts/frame_diff.py` | two comps (or one with `?lang=`) at chosen times → identical or not, with diff images |+| `scripts/sfx_palette.py` | the sound materials, the room, `Score` helper, `--demo` |+| `scripts/verify_promo.py` | the acceptance oracle: rhythm legs, plus continuity, curves and framing with `--comp` |+| `scripts/gallery.py` | gallery demos → sheets |+| `scripts/test_motion.js` | `node scripts/test_motion.js` — the library's numbers |+| `templates/comp.html` | composition skeleton (the motion-web film) on the library |+| `templates/footage.example.json` | footage config used for the motion-web film |+| `templates/sfx_score.example.py` | the motion-web sound score |+| `references/reference-deconstruction.md` | how to read a reference in numbers |+| `references/rhythm.md` | rhythm (motion-web's three cuts) and carry (Pocket Weather's three) |+| `references/motion-library.md` | every move, applying it to DOM or canvas, the curve table, which carry for which boundary |+| `references/composition.md` | the `f(t)` architecture, primitives, hand path, probe, render and shutter |+| `references/sound.md` | palette, room, levels, what sounded cheap |+| `references/product-demo.md` | feature demos without a recording: the replica, legibility, highlights from the DOM, narration, languages and the time warp, brand end clips, what bit |+| `cases/motion-web-15s/README.md` | case 1: the rhythm film — beat sheet and numbers |+| `cases/one-dot-15s/README.md` | case 3: one dot is the whole film — the concept step, an operator's camera, recorded + synthesised sound |+| `cases/knockon-15s/README.md` | case 4: the light chain-reaction film — causal carry, height from shadows, sound placed from the comp's `__events()` |+| `cases/clearing-15s/README.md` | case 5: the one-take dive through scale — levels drawn in their own units, a screen-space camera for 1×–300×, sound driven by the zoom's speed |+| `cases/pith-21s/README.md` | case 6: the reverse dive — 440× → 0.52× out of one phosphor pixel, the product's own dark→light theme flip as the film's one transition, a mascot close-up used as the rhythm break, and a claim built from seven objects already on screen |+| `cases/ebb-15s/` | case 7: one take through five places, carried by a field of light — keyed camera with a hand, shake and depth, odometer digits, a flood that drains in rings onto the next scene, silk cards on belts at three depths |+| `cases/<film>/` | every film made with this skill: the film and a README (beat sheet, numbers, what was rejected and why). Also: overlap, unbroken, skill-demo, and onetake's own launch film. The films' source code is not included |++Requires: python3 with `playwright` (chromium), `numpy`, `scipy`, `Pillow`, `matplotlib`; `opencv-python` for the+motion line; `ffmpeg` / `ffprobe`; `node` for the library tests. Narration: `faster-whisper` (python3), and Kokoro+(`kokoro-onnx`, `soundfile`, plus `misaki[ja]` and `unidic-lite` for Japanese) in `~/.cache/kokoro/venv`.diff --git a/assets/cases/clearing.gif b/assets/cases/clearing.gifnew file mode 100644index 0000000..76aff45Binary files /dev/null and b/assets/cases/clearing.gif differdiff --git a/assets/cases/ebb.gif b/assets/cases/ebb.gifnew file mode 100644index 0000000..48537a9Binary files /dev/null and b/assets/cases/ebb.gif differdiff --git a/assets/cases/knockon.gif b/assets/cases/knockon.gifnew file mode 100644index 0000000..6e6b3f1Binary files /dev/null and b/assets/cases/knockon.gif differdiff --git a/assets/cases/motion-web.gif b/assets/cases/motion-web.gifnew file mode 100644index 0000000..50e868aBinary files /dev/null and b/assets/cases/motion-web.gif differdiff --git a/assets/cases/one-dot.gif b/assets/cases/one-dot.gifnew file mode 100644index 0000000..40215cdBinary files /dev/null and b/assets/cases/one-dot.gif differdiff --git a/assets/cases/onetake-launch.gif b/assets/cases/onetake-launch.gifnew file mode 100644index 0000000..a16c92dBinary files /dev/null and b/assets/cases/onetake-launch.gif differdiff --git a/assets/cases/overlap.gif b/assets/cases/overlap.gifnew file mode 100644index 0000000..682bc27Binary files /dev/null and b/assets/cases/overlap.gif differdiff --git a/assets/cases/pith.gif b/assets/cases/pith.gifnew file mode 100644index 0000000..08420ceBinary files /dev/null and b/assets/cases/pith.gif differdiff --git a/assets/cases/skill-demo.gif b/assets/cases/skill-demo.gifnew file mode 100644index 0000000..08c6344Binary files /dev/null and b/assets/cases/skill-demo.gif differdiff --git a/assets/cases/unbroken.gif b/assets/cases/unbroken.gifnew file mode 100644index 0000000..62b9c21Binary files /dev/null and b/assets/cases/unbroken.gif differdiff --git a/assets/hero.gif b/assets/hero.gifnew file mode 100644index 0000000..dd84983Binary files /dev/null and b/assets/hero.gif differdiff --git a/cases/clearing-15s/README.md b/cases/clearing-15s/README.mdnew file mode 100644index 0000000..f8656f0--- /dev/null+++ b/cases/clearing-15s/README.md@@ -0,0 +1,165 @@+# clearing-15s — the one-take dive through scale++> This folder ships the film only. Its source (the composition, the score, the sound sources) is not part of the+> public release; files named below describe how it was made.+>+> The film: `clearing.mp4`+++The fifth film: 15 s, 1920×1080, 30 fps draft, one canvas, zero assets, a fictional product (clearing, a calendar that+keeps time free). Made in Claude Code with this skill on 2026-09-14. The user left concept, palette, camera and visual+elements entirely to Claude; the first draft was accepted with 「牛逼牛逼 太牛逼了,你找到了技巧。神来之笔」.++Project: this folder.+- `comp.html` is the film; `clearing.mp4` is the film with sound.+- `dump_events.py` writes `events.json` and `zoom.json`; `score.py` turns them into `mix.wav`.+- `sfx-src` is a link to the one-dot film's sources.++In this folder:+- `comp.html` runs in place on the skill's `lib/motion.js`. Its frames at seven times and its `__events()` match the+ project's byte for byte.+- `clearing.mp4` is the accepted draft, with sound.+- `clearing.render.json` is its render record.++## Why it is a case++- **Carry by scale.** Case 2 carried by containers, case 3 by one element's identity, case 4 by cause. Here nothing is+ ever replaced because every level is inside the one before: the year holds the day, the day holds the gap, the gap+ holds the block. The yellow found at the bottom of the dive is the yellow the year ends in.+- **A camera that works at 1× and at 300×.** `OM.rig` chases the anchor's **screen position** and the log of the zoom,+ not a world position. At 300× a world-space spring swings the target a frame-width for every pixel of lag; a+ screen-space spring lags and settles the same at every scale. The camera is recovered from it (below).+- **Levels drawn in their own units.** A day is a 1440 px page inside a 24 px cell, drawn through a composed matrix+ `mul(VIEW, [s, 0, 0, s, ox, oy])`. Type is set at normal sizes and stays crisp at any zoom; detail fades in by the+ cell's size on screen (level of detail), so the year never draws 364 pages.+- **The camera is the instrument.** The comp exports the zoom's speed; the air under both dives and the whip out is as+ loud as that speed and as bright as the depth. Two held silences sit around the one landing.+- **The word was in the data.** CLEARING is a 5×7 pixel font laid over the year's grid; the kept days are those cells.+ The target day (col 30, row 2) happens to sit inside the R, so the first kept half hour is part of the name.++## Beat sheet++| t | beat | moves | carries into the next beat |+|---|---|---|---|+| 0.20–1.30 | the year fills | 364 days pop in, a wave left to right | the grid |+| 1.00–1.80 | 2027 · 2,184 events · 0 hours free | the header types; a hold | the grid |+| 1.80–3.60 | dive | the camera falls into Wed 28 Jul; the day's hours resolve | the day |+| 3.60–4.80 | scan | a yellow line sweeps the day, decelerating, and stops at 15:00 | the gap |+| 4.80–5.60 | the gap | a dashed outline and "15:00–15:30 · free"; a held breath | the gap |+| 5.60–7.00 | dive | into the half hour, 50× → 300× | the slot |+| 7.00–7.60 | inside | a minute ruler draws; near-silence | the slot |+| 7.60–9.00 | kept | a yellow block lands: "Clear. 30 min · kept for you"; the frame holds dead still | the yellow |+| 9.00–10.40 | out | the camera whips back to the year; the block stretches across the day as it goes | the yellow day |+| 10.40–11.67 | the name | kept days ripple out from it and spell CLEARING; the rest of the year dims 60 % | the word |+| 11.90–15.00 | Room, found in a full year. | "63.5 hours kept" types; the line rises; the first day pulses | end |++## Geometry++- **The year.** 52 × 7 cells, 24 px on a 30 px pitch; busy level per day from a hash, four alphas over the ground.+- **A day.** 1440 px page, scale 24/1440; 08:00–20:00 mapped to y 120–1320, so a half hour is 50 page px. Meetings from+ a hash; the target day is fully booked except 15:00–15:30.+- **Anchor A.** The day page's point (310, 15:15): the middle of the ruler-plus-block span, so both fit at 300×.+- **Level of detail**, by the cell's size on screen `sz = 24 · zoom`:++ | what | fades in over sz |+ |---|---|+ | a day's hours and meetings | 70 – 260 px |+ | meeting titles and times | 380 – 700 px |+ | the minute ruler; neighbours' text steps back to 25 % | 2,600 – 5,000 px |++## Camera++`RIG = OM.rig(want)` with `want(t)` returning where A should be on screen:++```js+const aim = (P, sP, z, w) => ({ x: sP[0] + (A[0] - P[0]) * z, y: sP[1] + (A[1] - P[1]) * z, zoom: z, w }); // put world P at screen sP+// camera from the rig's output r (screen shake added to r.x, r.y first):+CAM = { x: A[0] + (960 - r.x) / r.zoom, y: A[1] + (540 - r.y) / r.zoom, zoom: r.zoom, rot }+```++A dive eases log zoom on `cubicInOut` while the target's screen position moves linearly to the centre.++| until | frames | zoom | ω |+|---|---|---|---|+| 1.80 | the whole year | 1 → 1.03 | 6 |+| 3.60 | dive into the day | 1.03 → 40 | 9 |+| 4.80 | ride the scan down to the gap | 40 → 46 | 5 |+| 5.60 | the held breath | 46 → 50 | 5 |+| 7.00 | dive into the half hour | 50 → 300 | 9 |+| 8.95 | inside, dead still | 300 | 6 |+| 15.00 | whip out to the year, then hold | 1 | 5 |++- **Shake in screen space.** Hits `[t, px, decay]`: 7.60 [14, 8] the landing, 10.40 [4, 10] the ripple, 14.30 [3, 10] the+ pulse. `OM.rig`'s own hits divide x and y by zoom but add rotation unscaled, so they vanish at depth; here+ `OM.shake` is sampled per hit and added to the rig's screen output instead.+- **The whip** is a step in `want` at 8.95: the log-zoom spring covers 300× → 1× in about 0.6 s, peaking at −8.8 log+ units a second at 9.17 s.+- `__meta.inFrame = { day: [2.6, 5.6], slot: [6.4, 9.0], word: [10.6, 15, 'whole'] }`.++## Numbers (the accepted draft)++- **render.py**: 1080p30, 180° shutter sized by `__motion`, 8 workers.+ - 450 frames: 56 held, 42 kept a cut hard.+ - 7,422 captures in 331 s — three times case 4's, because the dives and the whip move every pixel.+- **verify_promo.py `--comp`**: PASS.++ | leg | result |+ |---|---|+ | cadence | CV 0.36 (first render; the beats did not change) |+ | rest | still 0.294, longest quiet 4.08 s |+ | burst | 2.33–3.5, 6.17–7.58, 7.58–9.0, 9.08–10.17 — the two dives and the whip |+ | not-flat | 0.59 |+ | audio | −3.5 dBFS, 0 clipped, quiet 0.244 |+ | continuity | 1.00 over 3 boundaries |+ | curves | peak 51,670 px/frame at 8.93 s — the year's box through the whip; shutter at its 48-capture cap |+ | framing | day (91 samples), slot (79), word whole (133) — all in frame |++## Sound++- **Sources.** `sfx-src` links to the one-dot film's sources: Kenney CC0, Mixkit, University of Iowa MIS (marimba,+ vibraphone, crotales) and Voxengo IRs. Nothing new was downloaded.+- **`score.py`.** It copies case 4's source, shaping, synthesis, bus and master code and adds a new score. Every time+ and pan comes from `events.json`; the camera's air from `zoom.json`.+- **`zoom_air(t0, t1)`.** Noise in three bands (150–600 Hz, 600–2,400 Hz, 2.4–9 kHz), crossfaded by depth+ `log(zoom) / log(300)` so closer is brighter, scaled by `|d log zoom / dt| ^ 1.3`.+- **Layers, in order.**+ - **The fill.** A tick per other column, rising in pitch and panned across the year, over a swell of air.+ - **2027.** Marimba C5; the header types one key in three.+ - **The dive.** The camera's air, a Mixkit whoosh on its fastest frame, a Shepard rise.+ - **The scan.** A thin FM tone that sinks as the line slows; a tick and a falling note (C5, A4, G4) each time it passes+ a meeting.+ - **Found.** Crotale A6 and a select. Then silence.+ - **Into the half hour.** Deeper air, a whoosh 4 dB under the landing, a rise; six ruler ticks in near-silence.+ - **Kept.** A soft heavy hit, the sub, a vibraphone Fmaj7 struck and held, crotale F6, a pad until the whip.+ - **Out.** The widest air, a whoosh on the fastest frame, a soft arrival at 9.62.+ - **The name.** Every fourth kept day plays the next note of an F pentatonic climbing F4 → C6, panned where it+ lights; when the word is whole the landing's Fmaj7 returns with the sub.+ - **The end.** Keys for "63.5 hours kept", crotale C6 under the tagline, one marimba note on the pulse.+- **Master.** −16.0 LUFS integrated, −3.5 dBTP; the limiter works hardest at 7.60 s (0.9 dB); quiet 0.240.++ K-weighted 400 ms loudness per beat:++ | t | 0.6 | 1.0 | 2.9 | 4.2 | 4.8 | 5.3 | 6.46 | 7.2 | 7.6 | 9.17 | 11.0 | 11.7 | 13.0 | 14.3 |+ |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|+ | LUFS | −31 | −23 | −17 | −22 | −24 | −39 | −16 | −43 | −14 | −15 | −16 | −12 | −16 | −20 |++ Energy by band:++ | band | < 100 Hz | 100–300 Hz | 300 Hz–2 kHz | 2–8 kHz | > 8 kHz |+ |---|---|---|---|---|---|+ | share | 6.1 % | 19.2 % | 68.6 % | 4.7 % | 1.4 % |++## What bit++- **Scale mismatch at the bottom.** At 230× the half hour was 192 px tall while the next meeting's title was 115 px, and+ the eye went to the neighbour. Fix: 300×, a narrower block (240 page px), neighbours' text down to 25 % at depth.+- **The word didn't read.** Yellow against days at 34–64 % white has too little luminance contrast. Fix: as the ripple+ passes, every other day dims 60 %.+- **The ruler fell off frame.** At 300× a page pixel is 5 screen px, so a ruler 200 page px left of A sat off screen.+ Fix: the ruler moved to the block's left edge and A to the middle of the pair.+- **The rest leg failed the first render: still 0.178.** Every hold had a slow push (the inside ×1.05, the end card+ 1 → 1.05), and at 320 px a push over a grid of cells is never dead still. The two rests were made truly still: 0.294.+- **The second dive was as loud as the landing** (−14 LUFS both). The dive's air came down 4 dB and its whoosh 4 dB, so+ the landing is the loudest moment until the name.+- **`fm_tone` takes a function of t** for its frequency, not a number.+diff --git a/cases/clearing-15s/clearing.mp4 b/cases/clearing-15s/clearing.mp4new file mode 100644index 0000000..61f3d44Binary files /dev/null and b/cases/clearing-15s/clearing.mp4 differdiff --git a/cases/ebb-15s/README.md b/cases/ebb-15s/README.mdnew file mode 100644index 0000000..1f5f037--- /dev/null+++ b/cases/ebb-15s/README.md@@ -0,0 +1,36 @@+# ebb 15s++> This folder ships the film only. Its source (the composition, the score, the sound sources) is not part of the+> public release; files named below describe how it was made.++The film: `ebb.mp4`++## How it was made (from the composition's header)++```text+CONCEPT — one take, and the light carries the camera. ebb is a focus timer (fictional); its one object is a field of warm+light that lives under everything and is time made visible. The camera never cuts: it starts inside the digits, pulls out+to the Mac app, rides the light up while a session runs, punches onto 00:00, and travels under the flood while it drains+in rings — the rings open on the phone, whose lock screen is the break in silk. It pushes onto the Live Activity, whips+down onto the day's sessions (three rows of silk at three depths, drifting against each other), dollies along them, and+pulls back while they fly into the week. The week sinks into the horizon as light, and the name rises out of it.++The camera is keyed (OM.camera) plus shake, parallax (OM.view depth) and a far lattice — no OM.rig, so it runs on lite.++ t beat camera what carries into the next beat+ 0.00–1.25 25:00, macro 3.6×, dead still the digits+ 1.25–2.10 the Mac window pull out to 1.12× (quintInOut) the window+ 2.20 start a tap of shake; the pill dips (.snappy), becomes the running dot+ 2.35–4.35 the session slow push to 1.5× with a 1.3° dutch; handheld the light+ odometer digits, light rising behind the glass, white where it passes; sidebar bar fills+ 4.35–4.95 00:00 punch to 3× on the colon (expoOut), hold the light+ 4.95–5.25 flood shake the light+ 5.25–6.75 drain → phone rings leave the colon; under them the camera travels 3× → 1× to the phone the silk+ 6.35–7.55 the break push to 2× on the Live Activity; break 4:59 ticks the silk+ 7.55–8.15 whip down onto the rows (expoInOut), landing shake the rows+ 8.15–9.70 the day dolly left along three rows at three depths the cards+ 9.70–10.75 the week pull back, rotate level; 21 cards fly to a 7 × 3 grid the grid+ 10.95–11.80 into the light crane down; the grid sinks column by column; the field rises the light+ 11.80–12.60 ebb the name drops, the line rises; belt and silk slow to a stop+ 12.60–15.00 rest dead still+```diff --git a/cases/ebb-15s/ebb.mp4 b/cases/ebb-15s/ebb.mp4new file mode 100644index 0000000..79fa412Binary files /dev/null and b/cases/ebb-15s/ebb.mp4 differdiff --git a/cases/knockon-15s/README.md b/cases/knockon-15s/README.mdnew file mode 100644index 0000000..5c61d7d--- /dev/null+++ b/cases/knockon-15s/README.md@@ -0,0 +1,170 @@+# knockon-15s — the chain-reaction film++> This folder ships the film only. Its source (the composition, the score, the sound sources) is not part of the+> public release; files named below describe how it was made.+>+> The film: `knockon.mp4`+++The fourth film and the first light one: 15 s, 1920×1080, 30 fps draft, one canvas, zero assets, a fictional product+(knockon). Made in Claude Code with this skill on 2026-09-14. The first draft was accepted with+「牛逼可以啊…把 html 玩得出神入化了」.++Project: this folder.+- `comp.html` is the film; `knockon.mp4` is the film with sound.+- `dump_events.py` writes `events.json` and `roll.json`; `score.py` turns them into `mix.wav`.+- `sfx-src` is a link to the one-dot film's sources.++In this folder:+- `comp.html` runs in place on the skill's `lib/motion.js`.+- `knockon.mp4` is the accepted draft, with sound.+- `knockon.render.json` is its render record.++## Why it is a case++- **The concept step, on demand.** The user wanted a light film and had no idea what it should be. Three pitches differed+ in the central idea: a chain reaction, a one-take dive through scale, and a comic page whose panel widths are the rhythm.+ The user picked the first. There was no reference film and no reference numbers.+- **Causal carry.** Case 2 carried by containers and case 3 by one element's identity. Here every boundary is a collision:+ - the key ejects the marble;+ - the marble flips the toggle;+ - the toggle tips the first card;+ - the last card presses Send;+ - Send throws the notification.++ Nothing is replaced, because each beat is caused by the one before.+- **A light tabletop seen from above.** Height is shown by the shadow: its offset and blur grow with z, and a flying card+ grows a little. The machine is laid along a pencil ↵, and the closing pull-out reveals it as the product's glyph.+- **Sound read from the picture.** The comp exports two things:+ - `__events()`: every contact's time, kind and on-screen pan;+ - `__marbleSpeed(t)`: the marble's speed.++ `score.py` places every sound from those, so a retimed beat takes its sound with it.++## Beat sheet++| t | beat | moves | carries into the next beat |+|---|---|---|---|+| 0.00–0.70 | a key on a table | the cursor arrives | the cursor |+| 0.70–0.95 | press | the key goes down, a marble pops out | the marble |+| 0.95–2.29 | down the slider, round the corner | the marble accelerates; the slider's fill is the marble | the marble |+| 2.29–3.30 | the bump | climbs, stops on top, teeters (a rest) | the marble |+| 3.30–3.86 | over | rolls off, bounces into the toggle: ON | the toggle's knob |+| 3.84–5.67 | ten tasks fall | cards tip in a quickening run, each landing face up with its task | the last card |+| 5.67–8.75 | Send | pressed; a notification is thrown up and hangs (a rest) | the notification |+| 8.75–9.90 | it lands | checks; the bell rings three times | the ink |+| 9.30–10.30 | the path inks | the pencil ↵ turns to ink; the camera rises | the ↵ |+| 10.90–15.00 | knockon | the name rises inside the ↵; one more tap on the key | end |++## The machine++- **The run.** Card i falls through an angle of π/2·u^2.2 over 0.40·0.9^i s, so it starts slowly like a real domino. It+ starts card i+1 once it has leant asin(112/170), which is far enough to reach it. The ten cards take 3.84–5.67 s,+ speeding up.+- **The marble.**+ - On the slider it falls under gravity: distance ∝ t².+ - Round the corner it keeps a constant ~1,100 px/s.+ - It decelerates evenly to rest on top of the bump.+ - It teeters there (`OM.ring`), rolls off the far side and bounces once into the knob.+- **The rest.**+ - The toggle's knob moves on `spring(ζ 0.7, ω 42)`.+ - The notification rises 440 px (cubicOut), hangs with a 1.7 s bob and a 1.25 s flutter, falls as u² and lands with+ `OM.impact`.++## Camera++| until | frames | zoom | ω |+|---|---|---|---|+| 0.80 | the key and the cursor | 1.75 | 6 |+| 2.15 | the marble, 0.14 s ahead, looking down the slider | 1.4 | 9 |+| 2.56 | the marble, 0.1 s ahead, round the corner and up | 1.5 | 9 |+| 3.30 | the bump, pushing in while it teeters | 1.6 → 2.1 | 5 |+| 3.84 | between the bump and the toggle — where the marble lands, before it rolls | 1.6 | 10 |+| 5.77 | the run's front, 0.15 s ahead | 1.45 → 1.2 | 8 |+| 8.20 | the notification and its shadow | 1.25 | 5 |+| 9.60 | the landing and the bell | 1.6 | 9 |+| 15.00 | the whole ↵ | 0.76 → 0.79 | 3.2 |++Hits `[t, px, decay]`:++| t | hit | px | decay |+|---|---|---|---|+| 0.70 | the press | 4 | 12 |+| 3.75 | the knock | 6 | 10 |+| 5.67 | Send | 5 | 10 |+| 8.75 | the landing | 12 | 8 |+| 9.15 | the first ring | 4 | 12 |++`__meta.inFrame = { marble: [0.95, 3.9], note: [5.95, 10.0], mark: [11.7, 15, 'whole'] }`.++## Numbers (the accepted draft)++- **render.py**: 1080p30, 180° shutter sized by `__motion`, 8 workers.+ - 450 frames: 38 held, 31 kept a cut hard.+ - 1,935 captures. Of the 412 moving frames, 341 took 4; none took more than 19.+ - 141 s; 2:25 including the encode.+- **verify_promo.py `--comp`**: PASS.++ | leg | result |+ |---|---|+ | cadence | CV 0.67 |+ | rest | still 0.272, longest quiet 3.42 s |+ | burst | WARN — none, and there is no reference |+ | not-flat | 0.55 |+ | audio | −3.5 dBFS, 0 clipped, quiet 0.239 |+ | continuity | 1.00 **over 0 boundaries** |+ | curves | peak 360 px/frame (the cursor arriving at 0.10 s); 46 % of travel on soft curves; median t80 .54 |+ | framing | marble (89 samples), note (122), mark (100) — all in frame |++- **The continuity pass is empty.** The probe found no boundary to judge in one continuous top-down world with a moving+ camera, so carry here was judged by eye.++## Sound++- **Sources.** `sfx-src` links to the one-dot film's sources: Kenney CC0 (impact, interface and UI packs), Mixkit,+ University of Iowa MIS (marimba, vibraphone, crotales) and Voxengo IRs. Nothing new was downloaded.+- **`score.py`.** It copies the one-dot film's source, shaping, synthesis, bus and master code and adds a new score. Every+ time and pan comes from `events.json`.+- **Layers, in order.**+ - **The key.** A thock (Kenney light wood, −5 st), a click and a short sub.+ - **The roll.** Noise band-passed to 140–1400 Hz plus a band above 2.5 kHz, both scaled by the marble's speed, with a+ seam once a turn. The slider ticks every 10 %, climbing in pitch.+ - **The teeter.** Silence.+ - **The toggle.** The knock (plank, +4 st); the switch lands ON on C5.+ - **Each card.** A wood clack rising in pitch, a paper slap, and the next note of an F pentatonic climbing F4 → D6.+ - **Send and the throw.** A click, a soft impact and a sub; then a whoosh and air, a crotale at the top, and a faint pad+ under the hang.+ - **The landing.** A soft heavy impact, the sub and marimba F3; a select tick on A4; the bell is crotales F6, A6, C6.+ - **The rise into the name.** A pen scratch, air, a Shepard riser and a pad.+ - **The name.** A soft heavy impact, the sub, a strummed vibraphone Fmaj7, marimba F4/F3 and a pad.+ - **The last tap.** The key again, plus C5.+- **Master.** −16.0 LUFS integrated, −3.5 dBTP; the limiter works hardest at 10.93 s (3.5 dB); quiet 0.235.++ K-weighted 400 ms loudness per beat:++ | t | 0.7 | 1.8 | 2.9 | 3.86 | 4.8 | 5.67 | 7.0 | 8.75 | 9.15 | 10.9 | 12.5 | 13.7 |+ |---|---|---|---|---|---|---|---|---|---|---|---|---|+ | LUFS | −21 | −19 | −53 | −20 | −17 | −17 | −32 | −15 | −16 | −11 | −14 | −21 |++ Energy by band:++ | band | < 100 Hz | 100–300 Hz | 300 Hz–2 kHz | 2–8 kHz | > 8 kHz |+ |---|---|---|---|---|---|+ | share | 11.5 % | 32.0 % | 51.7 % | 3.5 % | 1.2 % |++## What bit++- **Canvas shadows and filters ignore the transform.** `shadowBlur`, `shadowOffset*` and `filter: blur()` are measured in+ canvas pixels. Under a camera at DPR 2 they have to be multiplied by DPR × zoom by hand (`lift`, `softPoly`), or the+ shadows shrink as the camera pulls out.+- **Mud from a low arpeggio, not from the rumble.**+ - The first mix put 41.6 % of its energy in 100–300 Hz, and thinning the roll noise changed nothing.+ - Measuring energy per 0.5 s window found the source: 95 % of the window at 4.5 s was 100–300 Hz. The run's marimba+ started at F3, and its 1.8 s tails piled up.+ - Fix: an octave up, each note cut to 0.7 s. That window fell to 6 % and the whole mix to 32 %.+- **The run hides itself.** Seen from above, a card lying on the next one covers it, so the last card stays hidden under+ the ninth until its top edge clears it. That is physically right, but the last card's fall doesn't read.+- **Still open when accepted.**+ - At 5.6 s the camera chasing the end of the run blurs the whole frame.+ - Standing cards read more as pale strips with long shadows than as cards on edge.+diff --git a/cases/knockon-15s/knockon.mp4 b/cases/knockon-15s/knockon.mp4new file mode 100644index 0000000..1baf41eBinary files /dev/null and b/cases/knockon-15s/knockon.mp4 differdiff --git a/cases/motion-web-15s/README.md b/cases/motion-web-15s/README.mdnew file mode 100644index 0000000..1fa0588--- /dev/null+++ b/cases/motion-web-15s/README.md@@ -0,0 +1,43 @@+# motion-web-15s — the worked example++> This folder ships the film only. Its source (the composition, the score, the sound sources) is not part of the+> public release; files named below describe how it was made.+>+> The film: `motion-web.mp4`+++The film this skill was extracted from: 15 s, 3840×2160, 60 fps, H.264 + AAC. Accepted on the third cut.+Project (composition, footage, score, film): this folder.++## Reference+Daniel Ch's Shipper launch clip (https://x.com/chddaniel/status/2094883770164015174). Measured with+`analyze_ref.py`: 34 % dead-still frames, 7 hard cuts in two bursts, small elements on a white ground,+a narrative (prompt → work → result), a hand visible whenever the UI reacts.++## Beat sheet (what shipped)++| t | beat | moves | still |+|---|---|---|---|+| 0.15–1.55 | "Web motion is usually **decoration.**" three words spring in .35 s apart | words | everything else |+| 1.65–3.0 | wordmark letters drop in with landing squash; "makes it **move**" wobbles | type | ground |+| 3.0–4.75 | mark folds to top-left; prompt card; text types at 38 cps; hand enters, clicks send | caret, hand | card |+| 4.85–7.0 | build panel, 7 lines tick .24 s apart, last is `VERDICT: PASS` | checkboxes | panel |+| 7.05 / 7.95 / 8.85 | three real pages fly through tilted + blurred, each held .9 s (footage, hand from paths.json) | footage | — |+| 9.55–12.15 | four micro cards overlap: magnetic button (click 10.05), spring follow, jelly ring, Verlet string. The hand causes each | sims + hand | ground |+| 12.1–13.25 | browser window hold: char-curtain footage, slow push-in, hard out | footage | frame |+| 13.25–14.3 | staccato hard cuts: MOTION / IS / THE / MATERIAL at .22–.25 s | cuts | — |+| 14.3–15 | black, serif wordmark | — | all |++Shot lengths: 0.35 … 1.15 … 0.9 … 2.6 … 0.22 → CV 0.78. Stillness 31 %. One burst (13.25–14.3).++## Sound+Palette air / glass / wood / sub / bubble / wobble in one room (T60 1.1 s). 3 glass touches, a breath+for the wordmark, one key in three while typing, click down/up, a scale of glass ticks + a PASS chord,+travelling air + felt landing per page, one bubble per card, one wobble for the jelly, four subs for the+staccato, the deep one under black. Peak −8 dBFS. Score: `templates/sfx_score.example.py`.++## What was rejected on the way (see references/rhythm.md)+- v1: nine cards, 0.74 s each, one after another → 「PPT 式一个一个展示」.+- v2: full-frame footage shots, 1.55 s each → 「没有节奏变化 依然是 PPT」.+- SFX v1: sine pops per event → 低劣. Confetti specks at the wordmark → 低劣, removed.+diff --git a/cases/motion-web-15s/motion-web.mp4 b/cases/motion-web-15s/motion-web.mp4new file mode 100644index 0000000..7ba8596Binary files /dev/null and b/cases/motion-web-15s/motion-web.mp4 differdiff --git a/cases/one-dot-15s/README.md b/cases/one-dot-15s/README.mdnew file mode 100644index 0000000..293ba8b--- /dev/null+++ b/cases/one-dot-15s/README.md@@ -0,0 +1,158 @@+# one-dot-15s — the concept film++> This folder ships the film only. Its source (the composition, the score, the sound sources) is not part of the+> public release; files named below describe how it was made.+>+> The film: `one-dot.mp4`+++The skill's first launch film (made when it was still called ohmymotion — the film shows that name): 15 s, 1920×1080, 30 fps draft, one canvas, zero assets — no footage, no images. Made in+Claude Code with this skill over 2026-09-13/14; the camera cut was accepted. Project: this folder.+— `comp.html` and `one-dot-cam.mp4` are the accepted cut, `comp-v1.html` and `one-dot-v1.mp4` the still-camera+version, `one-dot-4k60.mp4` the 4K60 final, `score.py` → `mix.wav` the sound, `sfx-src/` its recorded sources.++In this folder: `comp.html` runs in place on the skill's `lib/motion.js` and renders the accepted frames exactly+(camera samples, `__motion`, `__track` and pixel hashes at six times compared). `one-dot-cam.mp4` is the accepted+render with sound; `one-dot-cam.render.json` is its render record, so verify_promo.py reads the shutter from it.++Why it is a case — three firsts:++- **Concept.** The zero-asset demo before it reused motion-web's skeleton and got 「和那个 motion web 的动效视频很像……+ 没有创造力吗」. This one came out of §2's three central ideas: one dot plays the whole film, so every boundary+ carries by construction (continuity 1.00, no edit cuts).+- **Camera.** The still-camera cut got 「很牛逼」 and then 「现在就缺灵动的跟踪运镜了」; the operator camera was accepted+ with 「细节都不用挑了 运镜 镜头和物理都没问题」. `OM.rig` and `OM.lattice` are that camera.+- **Sound.** Recorded CC0 / free sources layered with synthesis and mastered to a loudness target. The palette-only+ sound before it measured −21 LUFS with 58 % of its energy under 100 Hz.++## Beat sheet++| t | beat | the dot | carries into the next beat |+|---|---|---|---|+| 0.50 | a dot appears on black | pops (spring) | the dot |+| 1.00–1.50 | it finds its place, types "/" | glides left, stretches into a caret | the caret |+| 1.75–2.75 | "/" opens the skill list | contracts, splits into four dots + labels | the four dots |+| 2.50–3.35 | /ohmymotion is chosen | one pulses, three fall, it hops back | the label flies into the line; the dot is the caret again |+| 3.50–5.00 | "make a 15s film for Pocket Weather" types; a still beat | caret | the caret |+| 5.00–6.00 | send: the dot swallows the prompt | caret → dot, letters stream in, glides home | the dot, bigger |+| 6.00–7.25 | the skill loads | hollows into a ring, the ring fills | the ring |+| 7.25–8.00 | the math | the ring unrolls into `OM.spring`'s curve | the curve |+| 8.00–10.00 | it becomes a ball | a bead eats the curve, drops, bounces | the ball |+| 10.00–11.25 | the result | the second bounce opens a film; it is the sun | the sun |+| 11.25–12.00 | back to the dot | the film folds into the sun → dot; letters rise | the dot |+| 12.00–15.00 | ohmymotion | lands as the dot on the i; one wink | end |++Contacts sit on a 120 BPM grid (0.5 pop, 2.0 split, 6.0 home, 7.0 ready, 10.0 film, 12.0 land); the score cuts to it.++## Versions++| | what it was | verdict |+|---|---|---|+| v1 | still camera. 8 captures per moving frame: 590 s and 2,886 captures in one browser, and the film opening (633 px/frame) and closing (428) stepped, so a one-off refine pass (since folded into render.py's adaptive shutter) re-captured 35 frames at up to 48 (738 captures, 153 s) | 「很牛逼,就是时间有点太长了」; 「现在就缺灵动的跟踪运镜了」 |+| camera, render 1 | an operator over a far lattice; shutter sized by `__motion`, 8 workers: 106 s, 2,507 captures | lost the dot at 1.10 s — the glide's expoOut outran the spring. Every verify leg passed it; not shown |+| camera, render 2 | the camera leads the glide to the caret from 0.85 s; 103 s, 2,480 captures | accepted |++## Camera++`OM.rig(want, { dur: 15, hits: HITS })`: position springs at ζ 0.8, zoom in log space at ζ 0.95 and 0.8 ω, integrated+at 240 Hz once in `__ready`. The output is quantised (1/16 px, 0.05 % zoom), so a settled camera repeats its frame and+that frame skips the shutter. Behind the story sits `OM.lattice` at depth 1.2: a dot every 48 px, 1.4 px on screen, `C.dim`+at 0.9, under a screen-space vignette. Without it the dark ground gave the camera nothing to move against.++| until | frames | zoom | ω |+|---|---|---|---|+| 0.85 | the pop, centred | 2.4 | 6 |+| 1.85 | the line, 173 px ahead of where the caret lands — led from before the glide, which outruns a chase | 1.7 | 7 |+| 2.80 | the skill list | 1.55 | 6 |+| 3.50 | the line | 1.55 | 7 |+| 5.00 | rides with the caret: 42 % of its travel, 0.2 s ahead | 1.5 | 5 |+| 5.60 | pushes in on the swallow | 1.5 → 1.95 | 7 |+| 6.00 | whips home with the dot, 0.1 s ahead | 1.3 | 11 |+| 7.25 | leans in while the ring loads | 1.3 → 1.9 | 8 |+| 8.00 | pulls back for the curve | 1.35 | 8 |+| 8.80 | tracks the bead, 0.1 s ahead | 2.0 | 9 |+| 9.05 | holds on the hang | 2.2 | 8 |+| 10.00 | follows the drop, 0.1 s ahead | 1.6 | 8 |+| 11.25 | blown back by the film | 1 → 1.06 | 12 |+| 11.60 | dives into the sun | 1.7 | 10 |+| 12.00 | out to the name | 1.05 | 9 |+| 15.00 | a slow push on the name, 12.2–14.0 | 1.05 → 1.12 | 9 |++Hits `[t, px, decay]`: 6.00 [7, 9] home, 7.00 [5, 10] ready, 9.50 [9, 9] and 10.00 [16, 7] the bounces, 12.00 [10, 8]+the landing. `__meta.inFrame = { dot: [0.5, 15], mark: [12.2, 15, 'whole'] }`.++## Numbers (the accepted cut)++- render.py: 1080p30, 180° shutter sized by `__motion` (6 px gap, 4–48), 8 workers. 450 frames, 39 holds, 40 frames+ kept a cut hard (in v1 all such frames were letters appearing), 2,480 captures, 103 s. 293 of the 411 moving frames+ took 4 captures and three took 48; a fixed 8 would have taken 3,366 and stepped.+- verify_promo.py `--comp` on this mp4: PASS.++ | leg | result |+ |---|---|+ | cadence | CV 0.44 |+ | rest | still 0.389, longest quiet 2.75 s |+ | burst | 10.0–11.42 and 11.5–12.0 |+ | not-flat | 0.99 |+ | audio | peak −3.5 dBFS, 0 clipped, quiet 0.178 |+ | continuity | 1.00 over 6 boundaries |+ | curves | peak 935 px/frame at 10.00 s (on screen, camera included); 82 % of travel on soft curves; median t80 .80 |+ | framing | the dot in frame at all 431 samples from 0.5 s; the name whole at all 85 from 12.2 s |+- Frame by frame over the accepted camera, three counts, all zero:+ - the dot off frame;+ - its centre within 60 px of the edge;+ - the name cut.+- rest is nearly free for a minimal film. The energy map at 320 px can't see a small dot move on black, so v1 read+ still 0.844 and blank before 8 s. The camera and the lattice brought it to 0.389. Here it isn't rhythm evidence.++## What the film added to the skill++- **`lib/motion.js` 1.1.0.** Added `rig`, `lattice`, and `project` / `unproject` / `projectBox` / `screenTravel`. This is+ the comp's own camera, moved into the library after acceptance; the frames did not change. Gallery demo: `rig`.+- **render.py.**+ - `--workers`: one Chromium per process. A capture is a ~156 ms screenshot; the canvas draws in under 1 ms.+ - Captures per frame come from `window.__motion`.+ - v1's silent render took 590 s in one browser; the camera cut took 103 s.+- **probe.py / verify_promo.py.** The framing leg, from `__meta.inFrame`.++## Sound++`score.py` → `mix.wav`, 48 kHz stereo, built in 2.8 s. Recorded sources carry the detail synthesis can't; synthesis+carries what has to follow the picture exactly.++- **Sources.** In the project's `sfx-src/`, downloaded with the user's permission; not in the skill.++ | source | license | used for |+ |---|---|---|+ | Kenney | CC0 | clicks, ticks, soft impacts |+ | Mixkit | Mixkit Sound Effects Free License | whooshes |+ | University of Iowa MIS | free for any project | marimba, vibraphone, crotales in F major pentatonic |+ | Voxengo impulse responses | — | Nice Drum Room for the room, French 18th Century Salon for the hall |+- **Synthesis.**+ - a sub with harmonics under each landing, so it is heard on a phone speaker;+ - a Shepard riser into the ring closing;+ - an FM tone whose pitch follows `OM.spring`'s curve;+ - pads.+- **Mix.**+ - The dot's own sounds play alone until the music enters on the 6.00 downbeat.+ - The music is ducked 5 dB under the effects.+ - The whole mix is gated silent on the hang (8.83–9.17).+ - The vibraphone is choked when the film folds.+- **Master.**+ - BS.1770 −16.0 LUFS integrated, −3.5 dBTP.+ - A +3 dB shelf at 4 kHz, then an oversampled true-peak limiter: at most 3.3 dB at 10.00 s, over 1 dB for 0.11 s.+ - Mono fold-down −0.7 dB.++ | band | < 100 Hz | 100–300 Hz | 300 Hz–2 kHz | 2–8 kHz | above 8 kHz |+ |---|---|---|---|---|---|+ | share | 15.8 % | 23.7 % | 57.5 % | 2.6 % | 0.3 % |++ | beat (s) | 0.5 | 3.9 | 6.0 | 7.0 | 8.4 | 10.0 | 12.0 | 13.6 | 14.2 |+ |---|---|---|---|---|---|---|---|---|---|+ | K-weighted 400 ms loudness | −15 | −24 | −15 | −13 | −20 | −11 | −13 | −51 | −18 |+- **What bit.**+ - A −14 LUFS / −1 dBTP master failed the audio leg: peak −1.0 after AAC, quiet 0.089.+ - Mixkit whoosh 1465 peaks 1.57 s into its file, so aligning its peak started it 1.5 s early, over the rest after+ typing. `from_peak()` now cuts a source's run-up.+ - By RMS the opening pop sat within 1 dB of the climax. The arc is judged by K-weighted loudness per beat instead.+diff --git a/cases/one-dot-15s/one-dot.mp4 b/cases/one-dot-15s/one-dot.mp4new file mode 100644index 0000000..31fc3d5Binary files /dev/null and b/cases/one-dot-15s/one-dot.mp4 differdiff --git a/cases/onetake-launch-30s/README.md b/cases/onetake-launch-30s/README.mdnew file mode 100644index 0000000..753f38f--- /dev/null+++ b/cases/onetake-launch-30s/README.md@@ -0,0 +1,45 @@+# onetake launch 30s++> This folder ships the film only. Its source (the composition, the score, the sound sources) is not part of the+> public release; files named below describe how it was made.++The film: `onetake-launch.mp4`++## How it was made (from the composition's header)++```text+CONCEPT — three prompts, three films, one take. The prompt bar is the spine: typed three times, shorter each time+(a sentence → four words → one word), and each prompt visibly becomes a finished mini-film for a new fictional product,+in its own palette and motion vocabulary: bar 1 opens into the Mac window, bar 2 opens into the Hush frame, bar 3+collapses into a line that shoots across the desk and opens into the LED screen. The films sit on one warm paper desk;+the camera never cuts, and at the end it pulls back until all three are playing at once over the bar, whose block+cursor writes the name in one stroke.++v8 (after v7's 「看起来只有一个 prompt」): the camera lands on every bar, and every send is the birth of its film.+Richer films: Dayline gets an event sheet on iPhone, Hush a charging-case product shot, FRAME/26 a crowd in front of+its screen. The prompt glyph is a terminal's: a grey chevron and a solid block cursor.++ t beat camera carries into the next beat+ 0.00–4.40 prompt 1, no music macro, two dead-still holds, one glide the bar+ 4.40 ENTER → music pull out 2.25× → 0.93× the bar opens into the Mac window+ 5.10–9.50 Dayline (as v7) push, tilt, dive, pull + dutch the window reflows into the phone+ 9.52–10.40 tap: Launch day opens as a sheet settle on the phone; words; dead still —+ 10.95–11.30 to bar 2 travel right, land at 1.4× the bar+ 11.30–12.03 "concept ad — Hush earbuds" dead still —+ 12.08–12.75 the bar opens into the Hush frame pull to 1.2 (the frame fills) "Hush" flies to the corner+ 12.75–15.36 the city's noise piles up handheld creep —+ 15.36–16.14 earbud lands; noise drains; the case rises, takes it, snaps shut+ 16.00–16.92 "Hush." bar 3: "event" pull back to Hush + bar 3; dead still the bar+ 16.92 DROP: bar 3 → a line → the LED whip along the line the line is the promo's first grid line+ 17.28–21.10 FRAME/26 promo (as v7) pan down the poster it wipes back to its first frame+ 21.10–23.18 the loop, once; the crowd rises pull out to the screen in its room —+ 23.18–26.60 all three at once pull back over the strip the bar+ 26.835 the stop: everything freezes+ 27.357–28.45 the block cursor writes onetake push in, following the pen —+ 28.55 GitHub mark · open source dead still to the end+++Music: Dorothy & IamDayLight – Thief (instrumental), 115 BPM, bar 2.087 s. Film 4.40 = track 33.657 (a downbeat).+Track 42.005–46.179 is a two-bar breakdown (the Hush film); 46.179 is the drop (the event promo); spliced 52.440 → 58.701+at film 23.183 so the stop (62.35, a silent beat) lands at film 26.835 and the hit after it (62.874) at 27.357 carries the name.+```diff --git a/cases/onetake-launch-30s/onetake-launch.mp4 b/cases/onetake-launch-30s/onetake-launch.mp4new file mode 100644index 0000000..c516635Binary files /dev/null and b/cases/onetake-launch-30s/onetake-launch.mp4 differdiff --git a/cases/overlap-15s/README.md b/cases/overlap-15s/README.mdnew file mode 100644index 0000000..41901d6--- /dev/null+++ b/cases/overlap-15s/README.md@@ -0,0 +1,40 @@+# overlap 15s++> This folder ships the film only. Its source (the composition, the score, the sound sources) is not part of the+> public release; files named below describe how it was made.++The film: `overlap.mp4`++## How it was made (from the composition's header)++```text+CONCEPT — a two-colour risograph print, pulled by two people, with a message neither half carries. A pink cursor, "you",+and a blue one, "them", grab a drum each at opposite edges of one sheet and pull toward each other: pink lays "you" and+a circle of random dots, blue lays "them" and a second circle. The circles share one grid and one coin per cell: pink+inks heads; blue inks tails, except inside a hidden ampersand, where it inks heads too. Each plate alone is the same+noise; only exactly in register do the & cells land together and multiply to violet. The blue lands out of register, so+nothing shows. A loupe finds dots that miss each other and a doubled mark; "them" clicks beside the mark, the blue snaps+into register and "you & them" appears. The print run is every other pair it is for; "them" yanks the stack away; the two+pull the name, over + lap, and meet where the r crosses the l; the camera, locked off until then, pushes in on that+crossing and tilts down to the line. Fictional product (overlap, a shared canvas for two). Zero assets; one canvas; every+value a function of t.++ t beat moves carries into the next+ 0.18–1.25 the bed, out of focus the sheet slams in; the focus racks sharp the sheet+ 0.95–1.48 two people "you" and "them" arrive and grab a drum each the cursors+ 1.50–3.58 one pass, from both sides pulled in, let go, rolled out: only noise the cursors+ 3.58–4.20 a rest nothing moves: you ○○ them, something missing the overlap+ 4.20–5.78 the loupe the cursors make room; dots that miss, a doubled mark the loupe+ 6.00 in register "them" clicks; the blue snaps; the & appears the sheet+ 6.35–7.18 the loupe lifts "you & them" reads whole the sheet+ 7.18–8.50 the print run six sheets slam, each a different pair & pair the stack+ 8.62–9.67 a new sheet "them" yanks the stack away; a blank sheet slams in "them"+ 9.67–11.55 the name the same pull, over + lap; the cursors meet at r|l; the crossing+ the blue snaps into register+ 11.70–15.00 where they meet, the line, the card the camera pushes in on the r and the l, tilts down end+ to the line, pulls back out to the whole card+CAMERA — locked off (a copy stand over the press bed) until the name is in register, then one operator (OM.rig): into+the crossing of r and l, down to the line, back out to the card. Before that the optics are one rack focus and one loupe. MOTION — mechanical:+drums pulled in (u²) and rolled out (quadOut), feeds that slam, dots that grow in steps; two springs, both registrations.+PALETTE — cream stock on a warm grey bed; fluorescent pink and riso blue, overprinted by multiply.+```diff --git a/cases/overlap-15s/overlap.mp4 b/cases/overlap-15s/overlap.mp4new file mode 100644index 0000000..9a5fdccBinary files /dev/null and b/cases/overlap-15s/overlap.mp4 differdiff --git a/cases/pith-21s/README.md b/cases/pith-21s/README.mdnew file mode 100644index 0000000..40d2af8--- /dev/null+++ b/cases/pith-21s/README.md@@ -0,0 +1,155 @@+# pith-21s — the window grew out of the terminal++> This folder ships the film only. Its source (the composition, the score, the sound sources) is not part of the+> public release; files named below describe how it was made.+>+> The film: `pith.mp4`+++The sixth film: 21.5 s, 1920×1080, 30 fps draft, one canvas, one inlined bitmap font, zero footage. Made in Claude+Code with this skill on 2026-09-15 for **Pith**, a Tauri 2 desktop GUI that embeds the+`pi` coding agent's SDK in-process — "pi CLI 的一层皮肤,不是一个新的 agent".++Project: this folder.+- `comp.html` is the film and runs in place on the skill's `lib/motion.js`; `pith-21s.mp4` is the film with sound.+- `dump_events.py` writes `events.json` and `zoom.json`; `score.py` turns them into `mix.wav`.+- `sfx-src` is a link to the one-dot film's sources.++## Why it is a case++- **Carry by scale, pulling out.** clearing dived 1× → 300× → 1×. This one runs the technique in reverse and never+ comes back: 440× → 0.52× in one take. Nothing is replaced because everything is inside the frame that arrives+ around it — the pixel is in the caret, the caret is in the prompt, the prompt is in the stream, and the window draws+ its border around the stream that is already there.+- **The product's two themes are the film's one transition.** Pith ships a Platinum light default and an+ amber-phosphor dark theme. The film starts inside the dark one, and the title bar landing flips it to the light one+ in a single frame. The transition is not invented; it is `data-theme`.+- **The same bytes, rendered twice.** The lines that scroll as raw CLI output are the same lines the window then+ renders — same page positions, different presentation. The first thing the window does is fold nine of them away.+- **The claim is built out of the picture, not captioned over it.** pi 0.84.1 has exactly seven built-in tools —+ `read` `bash` `edit` `write` `grep` `find` `ls` — and the film's first turn runs every one of them. At 17.2 s those+ seven row squares leave the timeline on fanned arcs (`OM.gather`) and line up under the shrinking window, each+ naming itself. "This agent is seven tools" is the same seven objects that have been ticking since 3.8 s.+- **The mascot earns a close-up.** TopBar.tsx draws a pair of pixel eyes that blink and track the cursor on a 3 × 3+ pixel grid. At 1× they are four pixels nobody sees. The film pushes to 44× on them, holds dead still while they+ blink, then snaps their pupils toward the pointer — and the camera follows that gaze back out to the composer. The+ eyes are the beat that breaks the film's longest still stretch *and* the hand-off into the second turn.+- **The type is the product's type.** Fusion Pixel 12px, the app's own font, subset to the glyphs used and inlined as+ base64 (≈3.4 KB each) so the `file://` page render.py loads has it. One bitmap pixel is 1.5 page px, which is what+ makes "inside one pixel" a real place to put the camera.+- **No music until the window exists.** The first 7.8 s are a phosphor hum, coil whine and dry key clicks. The landing+ cuts the hum in 40 ms and the film's first note arrives in the silence after it.++## Beat sheet++| t | beat | moves | carries into the next beat |+|---|---|---|---|+| 0.00–1.55 | one phosphor pixel | a lit cell edge, dead still; one blink at 1.12 | the pixel |+| 1.55–3.30 | the caret | pull 440× → 9×; the prompt types in amber at 28 cps | the line |+| 3.30–6.30 | the wall | pull 9× → 3.2×; 24 lines of pi output stream up past a frame that stays low | the text |+| 6.30–7.55 | the frame arrives | pull 3.2× → 1.35×; a 1 px border draws itself clockwise from the corner | the text |+| 7.55–7.77 | the clamp | the title bar drops on a ζ .5 / ω 26 spring and lands | the window |+| 7.77 | **the flip** | amber → ink in one frame; `impact` squash, a 13 px shake, the hum cut | the window |+| 7.77–8.60 | the held breath | dead still | the window |+| 8.60–9.77 | the desk | nine detail lines fold away; the sidebar folds out on `backOut`; the 3 px hard shadow drops | the window |+| 9.77–10.34 | rest | dead still, silent | the title bar |+| 10.34–11.06 | **the eyes** | a push 1× → 44× into the title bar's left corner | the eyes |+| 11.06–12.14 | the close-up | dead still and silent; they blink at 11.58; at 11.88 the pupils snap to the pointer | the gaze |+| 12.14–12.87 | the gaze | the camera follows where they are looking, out and down to the composer, 44× → 1.85× | the pointer |+| 12.87–14.97 | the use | the hand clicks into the field, types, sends | the message |+| 14.97–16.99 | the answer | the message lifts out of the composer into the timeline; three rows tick in already collapsed | the window |+| 16.99–18.39 | out | pull 1.85× → 0.52×; the window settles into the top third | the window |+| 17.19–17.91 | **the seven** | the seven tool squares leave their rows on fanned arcs and line up | the row |+| 17.99–18.6 | they name themselves | each name rises beside its square; the label above | the row |+| 18.64–21.50 | the name | Pith drops letter by letter in lavender; the line types; a caret blinks | end |++## Geometry++- **The window.** 1010 × 639 world px at zoom 1 — 31 % of the frame. Its interior is a 1240 × 784 page drawn under+ `mul(VIEW, [S, 0, 0, S, WIN.x, WIN.y])` with `S = 1010/1240`, so type is set at 18 px and stays crisp at 440×.+- **The page.** Title bar 30, sidebar 210, timeline 1030 × 570, composer box at y 626. The terminal's layout already+ *is* the window's layout — output above, input at the bottom — which is why the chrome can arrive without moving a+ single line.+- **The caret.** `CARET.x` equals `TXT.x`, so the first character typed lands exactly where the caret was: the pixel+ the film opens inside becomes the first letter of the prompt.+- **The stream.** Bottom-anchored: each line's height is arrival × fold state, summed upward from the timeline's+ bottom edge, so a line arriving pushes the older ones up and a fold lets them settle back down. One pure function+ of t, and `layout(t)` is also what tells the gather where each square currently is.+- **The phosphor.** A grid in page units at `CELL = FS/12 = 1.5` page px: unlit cells hold a 5.5 % amber residue (so+ the deep camera has a ground to slide against), gaps are 16 % of a cell, scanlines darken every other row, and lit+ content carries a screen-constant `shadowBlur` bloom. All of it fades out over `CELL·S·zoom` = 13 → 3.5 screen px.++## Camera++`RIG = OM.rig(want, { zoomRate: 1.0 })` in screen space, `want(t)` returning where the beat's **subject** should sit.++| until | frames | zoom | ω |+|---|---|---|---|+| 1.55 | one lit pixel | 440 | 5 |+| 3.30 | out to the caret | 440 → 9 | 8 |+| 6.30 | the wall, frame settling to 0.86 H | 9 → 3.2 | 8 |+| 7.55 | the whole window | 3.2 → 1.35 | 7 |+| 8.60 | the clamp, dead still | 1.35 | 6 |+| 9.77 | the desk | 1.35 → 1 | 6 |+| 10.34 | rest | 1 | 6 |+| 11.06 | push into the title bar | 1 → 44 | 12 |+| 12.14 | the eyes, dead still | 44 | 6 |+| 12.87 | follow the gaze to the composer | 44 → 1.85 | 7 |+| 16.99 | the use and the answer | 1.85 → 1.74 | 6–7 |+| 18.39 | out to the lockup, window centred at (960, 300) | 1.74 → 0.52 | 5 |++- **Keep the eye where a terminal's eye is.** The wall beat's first cut framed the caret while the output built off+ screen above it — a second of nothing. Settling the subject to 0.86 H over the beat's first 0.9 s fixed it: the+ frame sits low and the output grows past it, which is what looking at a terminal is.+- **The anchor has to follow the subject.** clearing's rig chased one fixed world anchor, which works while+ everything framed is near it. Here the eyes are 524 world px from the caret: at 44× a fraction of a second of zoom+ lag put the frame in the *sidebar*, three lines away from the shot. `subj(t)` now travels caret → eyes → composer+ and both `aim()` and `camAt()` read it, so the residual shrinks exactly as the zoom grows.+- **A 3.8-log-unit zoom step needs time on both ends.** The first cut of the eyes beat wanted 1× → 44× in 0.54 s and+ the spring was still at 9× when the "hold" began, 16× a tenth of a second later. Fixes: `zoomRate` 0.8 → 1.0,+ ω 9 → 12 on the push, the push stretched to 0.72 s, and the hold given a full second so ~0.35 s of it is a settled,+ dead-still close-up. The pointer's click was moved behind the settle for the same reason.+- **Shake in screen space**: `[[7.77, 13, 9], [11.88, 5, 14], [14.64, 4, 12]]`.+- `__meta.inFrame = { caret: [0.2, 3], win: [8.67, 10.27, 'whole'], eye: [11.45, 12.10, 'whole'], row: [15.6, 16.9],+ tools: [18.2, 18.9, 'whole'], mark: [19.7, 21.5, 'whole'] }`.++## Sound++- **Sources.** `sfx-src` links to the one-dot film's (Kenney CC0, Mixkit, University of Iowa MIS, Voxengo IRs).+ Nothing new was downloaded. Mixkit's licence does not allow redistributing its files.+- **`score.py`** reuses clearing's source handling, shaping, synthesis, buses and master and adds a new score plus a+ `hum()` generator (60/120/180 Hz + an 8.1 kHz coil whine + 1.8–7 kHz screen hiss, killed in 40 ms).+- **`zoom_air(t0, t1)`** is clearing's, re-aimed: brightness from `log(zoom)/log(440)` so deeper is thinner and+ brighter, loudness from `|d log zoom / dt| ^ 1.3`.+- **The quiet is scored, not left over.** The first mix passed every leg but audio (quiet 0.10 against 0.15): the hum+ ran from frame 0 and a pad ran straight through the rest. Starting the hum at 0.34 s, holding 0.5 s of nothing+ after the landing, and putting *no* bed under the rest or the eye close-up took it to 0.186. Rests: 0.00–0.50,+ 11.00–11.83 (the close-up), 13.83–14.08, 15.08–15.58, 20.58–21.42.+- **The eyes get two pixels of sound**: two lid ticks for the blink, and one hard high tick plus a 120 Hz sub for the+ snap. The gather gets the same `tick_002` the rows have used all film, transposed up seven times.++## What the first cut (20.0 s) did not have++It passed all eight legs and was still missing two things the user named: the eyes were four pixels in a title bar+nobody would notice, and "pi is a very small agent" was nowhere in the picture. Both fixes are beats, not captions —+a close-up that doubles as the rhythm break and the hand-off, and seven objects that were already on screen lining+up. The film grew 1.5 s. (It also corrected the tool count: the user remembered four, pi 0.84.1 registers seven.)++## Numbers (the accepted draft)++- **render.py**: 1080p30, 180° shutter sized by `__motion`, 8 workers. 645 frames: 63 held, 97 kept a cut hard.+ 6,369 captures in 107 s.+- **probe.py**: continuity 1.00 over 3 boundaries, all carried. Peak 3,865 px/frame at 10.37 s (the push into the+ eyes), median t80 0.66.+- **verify_promo.py `--comp`**: PASS on all eight legs.++ | leg | result |+ |---|---|+ | cadence | CV 0.51, shot lengths 0.22–3.0 s |+ | rest | still 0.291, longest quiet 3.25 s |+ | burst | six, in the stream, at the landing and around the eyes |+ | not-flat | 0.76 |+ | audio | −3.5 dBFS, 0 clipped, quiet 0.186 |+ | continuity | 1.00 over 3 boundaries |+ | curves | peak 3,865 px/frame, shutter 180° |+ | framing | caret, win (whole), eye (whole), row, tools (whole), mark (whole) — all in frame |diff --git a/cases/pith-21s/pith.mp4 b/cases/pith-21s/pith.mp4new file mode 100644index 0000000..75249fbBinary files /dev/null and b/cases/pith-21s/pith.mp4 differdiff --git a/cases/skill-demo-15s/README.md b/cases/skill-demo-15s/README.mdnew file mode 100644index 0000000..755c040--- /dev/null+++ b/cases/skill-demo-15s/README.md@@ -0,0 +1,27 @@+# skill demo 15s++> This folder ships the film only. Its source (the composition, the score, the sound sources) is not part of the+> public release; files named below describe how it was made.++The film: `skill-demo.mp4`++## How it was made (from the composition's header)++```text+BEAT SHEET — an operation demo built from nothing: no footage, no images. Every pixel is DOM drawn here; every move is OM.*.+Rhythm from the measured Shipper reference (references/reference-deconstruction.md): ~1/3 still, hits in a burst, small UI on a big ground.++ t beat moves carries into the next beat+ 0.15–1.35 "A launch video from one prompt." wordRise ×3, a still hold "one prompt." slides into the input, the box grows around it (morphRect)+ 1.95–4.70 the input: focus, "/om", skill menu filters, cursor, press, popIn, spring reflow, the chosen row flies up into the input as a chip; send+ pick, prompt types, send typeOn+ 4.70–6.40 the input shrinks into the sent message; a card morphRect ×2, tick ×4, shimmer the card folds into one row (morphRect)+ grows out of the chip: skill loaded+ 6.40–8.30 the agent works: tool calls stream, render popIn, spinner → tick, progress the launch.mp4 chip grows into the player (morphRect)+ progress, verify PASS+ 8.30–11.95 the hand presses play: the result — a sun lands press, hop, impactSplit, iris, (hits)+ on the headline, the stage opens, folds into a gather, maskRise+ seal, the name rises; still hold+ 11.95–12.95 ONE PROMPT. / ONE SKILL. / ZERO ASSETS. staccato hard cuts (burst) (end card)+ 12.95–15.00 onetake — motion films from a prompt letterDrop, wordRise, still hold+```diff --git a/cases/skill-demo-15s/skill-demo.mp4 b/cases/skill-demo-15s/skill-demo.mp4new file mode 100644index 0000000..c4b9cc8Binary files /dev/null and b/cases/skill-demo-15s/skill-demo.mp4 differdiff --git a/cases/unbroken-15s/README.md b/cases/unbroken-15s/README.mdnew file mode 100644index 0000000..8433551--- /dev/null+++ b/cases/unbroken-15s/README.md@@ -0,0 +1,29 @@+# unbroken 15s++> This folder ships the film only. Its source (the composition, the score, the sound sources) is not part of the+> public release; files named below describe how it was made.++The film: `unbroken.mp4`++## How it was made (from the composition's header)++```text+CONCEPT — a before/after split. The same hour drawn twice as an ensō, the circle a brush makes in one breath. Left,+notifications on: every ping lifts the brush, and it comes down again a little behind where it was — the strokes get+shorter until the hour is a tangle. Right, notifications held: one stroke, the whole hour, a finished circle. Then the+left falls away, the camera pulls back, and the finished circle is the o in the name.+Fictional product (unbroken, a Mac menu bar app that holds notifications). Zero assets; one canvas; every value f(t).++ t beat moves carries into the next+ 0.50–1.40 the split a rule draws down the middle; both hours label the two halves+ 1.40–2.25 both brushes come down two strokes, in step the strokes+ 2.25–7.12 the pings 17 notifications, quickening; each lifts the left the left tangle, the right stroke+ 7.40 the hour ends right closes its circle; left: interrupted 17 the finished circle+ 7.40–8.45 a held breath nothing moves the circle+ 8.45–9.70 the left falls away fragments drop, the rule retracts, the camera finds the circle the circle+ 9.70–11.20 the name pull back 1 → 0.15; the circle is the o; letters rise around it the word+ 11.60–15.00 Finish the circle. the line; the notice; a seal stamps end+CAMERA — OM.rig in world space: settles in on the split, holds still through the hour and the breath, finds the circle,+then pulls back 6.7× until the circle is a letter. Left-half shake per ping is local, so the right never flinches.+PALETTE — ink-black ground, bone-white ink, a cold notification blue, one vermilion seal.+```diff --git a/cases/unbroken-15s/unbroken.mp4 b/cases/unbroken-15s/unbroken.mp4new file mode 100644index 0000000..08ffa9cBinary files /dev/null and b/cases/unbroken-15s/unbroken.mp4 differdiff --git a/gallery/gallery.html b/gallery/gallery.htmlnew file mode 100644index 0000000..d9aca6f--- /dev/null+++ b/gallery/gallery.html@@ -0,0 +1,306 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<title>onetake · gallery</title>+<style>+html,body{margin:0;width:1920px;height:1080px;overflow:hidden;background:#f8f8f6;font-family:Inter,system-ui,-apple-system,sans-serif}+canvas{position:absolute;left:0;top:0}+#dom{position:absolute;left:0;top:0;width:1920px;height:1080px;overflow:hidden}+#cap{position:absolute;left:48px;top:36px;font:22px ui-monospace,Menlo,monospace;color:#8f8f8b;white-space:nowrap}+#cap b{color:#161616;font-weight:600}+#index{position:absolute;inset:0;padding:60px 80px;font:20px/1.7 ui-monospace,Menlo,monospace;color:#161616;overflow:auto;display:none;background:#f8f8f6}+#index a{color:#161616}+#index h2{font:600 22px Inter,system-ui,sans-serif;margin:28px 0 6px}+</style>+</head>+<body>+<canvas id="c" width="1920" height="1080"></canvas>+<div id="dom"></div>+<div id="cap"></div>+<div id="index"></div>+<script src="../lib/motion.js"></script>+<script>+// onetake gallery — one demo per move in lib/motion.js.+// ?demo=<name> the demo, same contract as a composition (window.__seek / __track / __meta)+// ?demo=<name>&play loop it in real time ?demo=<name>&t=0.8 pin a frame (no query) the list+// scripts/gallery.py turns each demo into gallery/sheets/<name>.png. The demos are plain on purpose — grey ground,+// stand-in cards, a round subject — so a sheet shows the motion, not a style.+const c = document.getElementById('c'), g = c.getContext('2d'), dom = document.getElementById('dom'), W = 1920, H = 1080;+const C = { bg: '#f8f8f6', ink: '#161616', grey: '#8f8f8b', line: '#e8e8e4', green: '#17a05e', red: '#b42323', blue: '#2f6fb5', peach: '#f6c9ab', sun: '#f5d984', lilac: '#ded2ed', mint: '#c9dfcf', white: '#ffffff' };+const SANS = 'Inter,system-ui,-apple-system,sans-serif';+const { clamp, lerp, ease } = OM;++// ─────────────── drawing helpers (canvas; each multiplies the current globalAlpha) ───────────────+function clear(color = C.bg) { g.setTransform(1, 0, 0, 1, 0, 0); g.globalAlpha = 1; g.filter = 'none'; g.fillStyle = color; g.fillRect(0, 0, W, H); }+function rr(x, y, w, h, r) { g.beginPath(); g.roundRect(x, y, w, h, r); }+function card(x, y, w, h, { r = 18, fill = C.white, shadow = 1 } = {}) {+ g.save(); if (shadow > 0) { g.shadowColor = `rgba(20,20,20,${0.16 * shadow})`; g.shadowBlur = 44; g.shadowOffsetY = 18; }+ rr(x, y, w, h, r); g.fillStyle = fill; g.fill(); g.restore();+ g.save(); rr(x, y, w, h, r); g.strokeStyle = C.line; g.lineWidth = 1.5; g.stroke(); g.restore();+}+function text(s, x, y, { size = 64, weight = 500, color = C.ink, align = 'center', base = 'middle', font = SANS } = {}) {+ g.save(); g.fillStyle = color; g.font = `${weight} ${size}px ${font}`; g.textAlign = align; g.textBaseline = base; g.fillText(s, x, y); g.restore();+}+function bars(x, y, w, n, { gap = 30, h = 12, color = C.line } = {}) { for (let i = 0; i < n; i++) { rr(x, y + i * gap, w * (i % 3 === 2 ? 0.6 : 1), h, h / 2); g.fillStyle = color; g.fill(); } }+function subject(x, y, r, { color = C.sun, sx = 1, sy = 1, rot = 0 } = {}) {+ g.save(); g.translate(x, y); g.rotate(rot); g.scale(sx, sy); g.beginPath(); g.arc(0, 0, r, 0, Math.PI * 2); g.fillStyle = color; g.fill();+ g.beginPath(); g.arc(-r * 0.3, -r * 0.12, r * 0.08, 0, Math.PI * 2); g.arc(r * 0.3, -r * 0.12, r * 0.08, 0, Math.PI * 2); g.fillStyle = C.ink; g.fill(); g.restore();+}+function pointer(x, y, s = 1) {+ g.save(); g.translate(x, y); g.scale(s, s); g.beginPath(); g.moveTo(0, 0); g.lineTo(27, 20); g.lineTo(15, 22); g.lineTo(23, 38); g.lineTo(17, 41); g.lineTo(9, 25); g.lineTo(0, 34); g.closePath();+ g.fillStyle = C.ink; g.fill(); g.lineWidth = 2.5; g.strokeStyle = '#fff'; g.stroke(); g.restore();+}+function windowFrame(x, y, w, h, { tint = C.lilac } = {}) {+ card(x, y, w, h, { r: 16 }); g.save(); rr(x, y, w, 44, [16, 16, 0, 0]); g.fillStyle = '#f1f1ee'; g.fill();+ for (let i = 0; i < 3; i++) { g.beginPath(); g.arc(x + 24 + i * 20, y + 22, 6, 0, Math.PI * 2); g.fillStyle = '#d9d9d4'; g.fill(); }+ bars(x + 44, y + 84, w * 0.45, 2, { gap: 34, h: 14 }); rr(x + 44, y + 170, w - 88, h - 214, 12); g.fillStyle = tint; g.fill(); g.restore();+}+const apply = (m, x, y) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];+function glyphs(s, size, weight, font) { g.save(); g.font = `${weight} ${size}px ${font}`; let x = 960 - g.measureText(s).width / 2; const out = [...s].map(ch => { const w = g.measureText(ch).width, cx = x + w / 2; x += w; return [ch, cx]; }); g.restore(); return out; }++const DEMOS = {+ // ─────────────── enter ───────────────+ wordRise: { group: 'enter', from: 'motion-web', note: 'a word lands: spring rise + scale; opacity leads the spring so it never reads as a fade', dur: 1.8,+ words: [['Motion', 620, 0.15, C.ink], ['is the', 960, 0.5, C.ink], ['material.', 1330, 0.92, C.red]],+ draw(t) { clear(); for (const [s, x, t0, col] of this.words) { const w = OM.wordRise(t, t0, { dist: 40 }); g.save(); g.globalAlpha = w.op; g.translate(x, 560 + w.y); g.scale(w.s, w.s); text(s, 0, 0, { size: 104, color: col }); g.restore(); } },+ track(t) { const o = {}; for (const [s, x, t0] of this.words) o[s] = [x, 560 + OM.wordRise(t, t0, { dist: 40 }).y]; return o; } },++ letterDrop: { group: 'enter', from: 'motion-web', note: 'wordmark letters drop in; speed flattens each one, the spring restores it', dur: 1.6,+ setup() { this.gl = glyphs('onetake', 190, 400, 'Georgia,serif'); },+ draw(t) { clear(); this.gl.forEach(([ch, cx], i) => { const d = OM.letterDrop(t, 0.15, i, { dist: 70 }); g.save(); g.globalAlpha = d.op; g.translate(cx, 640 + d.y); g.scale(d.sx, d.sy); text(ch, 0, 0, { size: 190, weight: 400, font: 'Georgia,serif', base: 'alphabetic' }); g.restore(); }); },+ track(t) { return { o: [this.gl[0][1], 640 + OM.letterDrop(t, 0.15, 0, { dist: 70 }).y], t: [this.gl[5][1], 640 + OM.letterDrop(t, 0.15, 5, { dist: 70 }).y] }; } },++ popIn: { group: 'enter', from: 'motion-web', note: 'popIn: a card springs up · liftOut: it lifts, grows a touch and blurs away', dur: 2.0,+ draw(t) { clear(); const ei = OM.popIn(t, 0.2), eo = OM.liftOut(t, 1.35), op = ei.op * eo.op; if (op <= 0.001) return;+ g.save(); g.globalAlpha = op; g.filter = eo.blur > 0.2 ? `blur(${eo.blur.toFixed(1)}px)` : 'none'; g.translate(960, 540 + ei.dy + eo.dy); g.scale(ei.s * eo.s, ei.s * eo.s);+ card(-400, -120, 800, 240); text('make the hero feel alive', -350, -40, { size: 38, align: 'left' }); bars(-350, 20, 500, 2, { gap: 36, h: 14 }); g.restore(); },+ track(t) { const ei = OM.popIn(t, 0.2), eo = OM.liftOut(t, 1.35); return { card: { x: 960, y: 540 + ei.dy + eo.dy, w: 800 * ei.s * eo.s, h: 240 * ei.s * eo.s } }; } },++ maskRise: { group: 'enter', from: 'pocket-weather', note: 'lines rise into place from behind a clip mask, staggered', dur: 1.6,+ lines: ['Pocket', 'Weather', 'Club.'],+ draw(t) { clear(); this.lines.forEach((s, i) => { const m = OM.maskRise(t, 0.2, i, { dist: 170 }); g.save(); g.beginPath(); g.rect(520, 250 + i * 170, 900, 170); g.clip(); text(s, 560, 340 + i * 170 + m.y, { size: 150, weight: 650, align: 'left' }); g.restore(); }); },+ track(t) { const o = {}; this.lines.forEach((s, i) => { o[s] = [760, 340 + i * 170 + OM.maskRise(t, 0.2, i, { dist: 170 }).y]; }); return o; } },++ typeOn: { group: 'enter', from: 'motion-web', note: 'the prompt types at a steady cps; caret solid while typing, blinking after', dur: 2.0,+ str: 'make the hero feel alive — springs, not fades',+ caretX(n) { g.save(); g.font = `500 36px ${SANS}`; const w = g.measureText(this.str.slice(0, n)).width; g.restore(); return 522 + w; },+ draw(t) { clear(); card(480, 430, 960, 200); const ty = OM.typeOn(t, 0.2, this.str, { cps: 38 }); text(ty.str, 520, 490, { size: 36, align: 'left' });+ if (ty.caret) { g.fillStyle = C.ink; g.fillRect(this.caretX(ty.n), 470, 3, 40); } rr(1360, 560, 52, 52, 26); g.fillStyle = C.ink; g.fill(); },+ track(t) { return { caret: [this.caretX(OM.typeOn(t, 0.2, this.str, { cps: 38 }).n), 490] }; } },++ tick: { group: 'enter', from: 'motion-web', note: 'checklist lines tick one by one; each box pops from .8; the last line is the proof', dur: 2.2,+ items: ['Read handfeel.md', 'Spring k=90 · damp .86', 'Jelly wobble along the leap', 'Reduced-motion fallback', 'verify → PASS'],+ draw(t) { clear(); card(560, 250, 800, 110 + this.items.length * 64);+ this.items.forEach((s, i) => { const tk = OM.tick(t, 0.35 + i * 0.24), y = 330 + i * 64; g.save(); g.translate(610, y); g.scale(tk.s, tk.s); rr(-14, -14, 28, 28, 8);+ if (tk.on) { g.fillStyle = C.green; g.fill(); g.beginPath(); g.moveTo(-7, 0); g.lineTo(-2, 6); g.lineTo(8, -6); g.strokeStyle = '#fff'; g.lineWidth = 3; g.stroke(); } else { g.strokeStyle = '#cfcfca'; g.lineWidth = 2; g.stroke(); }+ g.restore(); text(s, 650, y, { size: 30, align: 'left', color: tk.on && i < this.items.length - 1 ? C.grey : C.ink }); }); },+ track(t) { const o = {}; this.items.forEach((s, i) => { const k = OM.tick(t, 0.35 + i * 0.24).s; o['box' + i] = { x: 610, y: 330 + i * 64, w: 28 * k, h: 28 * k }; }); return o; } },++ flyThrough: { group: 'enter', from: 'motion-web', note: 'a screen flies in tilted, holds, flies out (CSS 3D). Its blur is a filter; render with --shutter for the real smear', dur: 1.6, shots: [0.22, 0.3, 0.6, 1.12, 1.18, 1.24],+ setup() { dom.innerHTML = `<div id="fw" style="position:absolute;left:460px;top:228px;width:1000px;height:625px;border-radius:14px;overflow:hidden;background:#fff;box-shadow:0 40px 90px -30px rgba(20,20,20,.35),0 0 0 1px rgba(0,0,0,.05);transform-origin:50% 50%"><div style="height:44px;background:#f1f1ee"></div><div style="margin:36px 44px;height:22px;width:45%;background:#e8e8e4;border-radius:11px"></div><div style="margin:0 44px;height:430px;background:${C.lilac};border-radius:12px"></div></div>`; this.el = document.getElementById('fw'); },+ draw(t) { clear(); const f = OM.flyThrough(t, 0.2, 0.9), el = this.el; el.style.opacity = f.visible ? f.op : 0; el.style.filter = f.blur > 0.3 ? `blur(${f.blur.toFixed(1)}px)` : 'none';+ el.style.transform = `translate(${f.x.toFixed(1)}px,0px) perspective(2200px) rotateY(${f.rotY.toFixed(2)}deg) rotateX(${f.rotX}deg) scale(${f.s.toFixed(4)})`; },+ track(t) { const f = OM.flyThrough(t, 0.2, 0.9); return { screen: { x: 960 + f.x, y: 540, op: f.visible ? f.op : 0 } }; } },++ // ─────────────── carry — the next shot grows out of this one ───────────────+ morphRect: { group: 'carry', from: 'pocket-weather', note: 'container transform: the button the hand presses becomes the result window', dur: 2.2, shots: [0.3, 0.52, 0.58, 0.64, 0.72, 1.6],+ A: { x: 1300, y: 860, w: 320, h: 88, r: 44 }, B: { x: 360, y: 170, w: 1200, h: 720, r: 18 },+ hand: [{ t: 0, x: 1640, y: 1060 }, { t: 0.38, x: 1470, y: 912 }, { t: 0.6, x: 1470, y: 912 }, { t: 1.0, x: 1720, y: 1120 }],+ draw(t) { clear(); const m = OM.morphRect(t, 0.55, 1.25, this.A, this.B, { curve: ease.expoOut }), p = OM.press(t, 0.45);+ const s = m.k > 0 ? 1 : p.s, v = Math.round(lerp(22, 255, clamp(m.k * 2.5)));+ g.save(); g.translate(m.cx, m.cy); g.scale(s, s); g.translate(-m.cx, -m.cy); g.shadowColor = `rgba(20,20,20,${0.1 + 0.1 * m.k})`; g.shadowBlur = 20 + 40 * m.k; g.shadowOffsetY = 8 + 14 * m.k;+ rr(m.x, m.y, m.w, m.h, m.r); g.fillStyle = `rgb(${v},${v},${v})`; g.fill(); g.restore();+ g.save(); g.globalAlpha = 1 - clamp(m.k * 5); text('Generate', m.cx, m.cy, { size: 34, weight: 600, color: '#fff' }); g.restore();+ g.save(); g.globalAlpha = clamp((m.k - 0.55) / 0.45); bars(m.x + 60, m.y + 70, m.w * 0.4, 2, { gap: 40, h: 16 }); rr(m.x + 60, m.y + 170, m.w - 120, m.h - 230, 14); g.fillStyle = C.mint; g.fill(); g.restore();+ const cu = OM.cursor(t, this.hand, [0.45]); pointer(cu.x, cu.y, cu.s); },+ track(t) { const m = OM.morphRect(t, 0.55, 1.25, this.A, this.B, { curve: ease.expoOut }), cu = OM.cursor(t, this.hand, [0.45]); return { window: { x: m.cx, y: m.cy, w: m.w, h: m.h }, hand: [cu.x, cu.y] }; } },++ iris: { group: 'carry', from: 'pocket-weather', note: 'a circular stage opens from the subject until it covers the frame; the subject grows into it', dur: 1.8, shots: [0.3, 0.39, 0.45, 0.53, 0.7, 1.5],+ draw(t) { clear(); subject(700, 580, 90); text('Sunny', 700, 740, { size: 40, color: C.grey });+ const ir = OM.iris(t, 0.35, 1.05, 700, 580, { curve: ease.expoOut }); if (ir.r <= 0) return;+ g.save(); g.beginPath(); g.arc(ir.cx, ir.cy, ir.r, 0, Math.PI * 2); g.clip(); g.fillStyle = C.sun; g.fillRect(0, 0, W, H);+ subject(lerp(700, 960, ir.k), lerp(580, 520, ir.k), lerp(90, 250, ir.k), { color: '#fff4c8' });+ g.globalAlpha = clamp((ir.k - 0.7) / 0.3); text('A little brighter.', 960, 880, { size: 72, weight: 600 }); g.restore(); },+ track(t) { const ir = OM.iris(t, 0.35, 1.05, 700, 580, { curve: ease.expoOut }), r = lerp(90, 250, ir.k);+ return { stage: { x: 700, y: 580, w: 2 * ir.r, h: 2 * ir.r }, subject: { x: lerp(700, 960, ir.k), y: lerp(580, 520, ir.k), w: 2 * r, h: 2 * r } }; } },++ zoomThrough: { group: 'carry', from: 'library', note: 'the camera pushes into one card until its inside is the next scene (log-space zoom, expo in-out)', dur: 2.4, shots: [0.3, 0.8, 0.9, 0.95, 1.02, 1.9],+ tg: { x: 768, y: 570, w: 384, h: 216 },+ draw(t) { clear(); const z = OM.zoomThrough(t, 0.45, 1.45, this.tg); g.setTransform(...z.matrix);+ for (let row = 0; row < 2; row++) for (let col = 0; col < 3; col++) { const x = 324 + col * 444, y = 294 + row * 276, hit = col === 1 && row === 1;+ card(x, y, 384, 216, { r: 14, fill: hit ? C.mint : C.white, shadow: 1 - z.k });+ if (hit) { [60, 110, 80, 140, 100, 160, 120].forEach((h, b) => { rr(x + 40 + b * 46, y + 186 - h, 28, h, 5); g.fillStyle = 'rgba(22,22,22,.78)'; g.fill(); }); }+ else bars(x + 28, y + 36, 200, 3, { gap: 30, h: 12 }); }+ g.setTransform(1, 0, 0, 1, 0, 0); g.globalAlpha = clamp((z.k - 0.9) / 0.1); text('Weekly focus', 960, 120, { size: 60, weight: 600 }); g.globalAlpha = 1; },+ track(t) { const z = OM.zoomThrough(t, 0.45, 1.45, this.tg), tg = this.tg; return { card: { x: (tg.x + tg.w / 2) * z.s + z.tx, y: (tg.y + tg.h / 2) * z.s + z.ty, w: tg.w * z.s, h: tg.h * z.s } }; } },++ hop: { group: 'carry', from: 'pocket-weather', note: 'the subject hops to its next slot on an arc and lands with a ring', dur: 1.6,+ draw(t) { clear(); for (const x of [560, 1360]) { g.beginPath(); g.ellipse(x, 705, 110, 18, 0, 0, Math.PI * 2); g.fillStyle = 'rgba(20,20,20,.08)'; g.fill(); }+ const h = OM.hop(t, 0.3, 1.0, { x: 560, y: 600 }, { x: 1360, y: 600 }, { height: 260 }), im = OM.impact(t, 1.0);+ subject(h.x, h.y + (1 - im.sy) * 100, 100, { sx: im.sx, sy: im.sy }); },+ track(t) { const h = OM.hop(t, 0.3, 1.0, { x: 560, y: 600 }, { x: 1360, y: 600 }, { height: 260 }); return { subject: [h.x, h.y] }; } },++ gather: { group: 'carry', from: 'pocket-weather', note: 'the cast travels on arcs into a cluster, fanning by index, staggered', dur: 1.8,+ a: [{ x: 520, y: 560 }, { x: 960, y: 560 }, { x: 1400, y: 560 }], b: [{ x: 850, y: 600 }, { x: 960, y: 520 }, { x: 1070, y: 600 }], cols: [C.sun, C.lilac, C.mint],+ q(t, i) { return OM.gather(t, 0.3, 1.1, i, 3, this.a[i], this.b[i], { arc: 170, spin: 0.35 }); },+ draw(t) { clear(); for (let i = 0; i < 3; i++) { const q = this.q(t, i); subject(q.x, q.y, lerp(110, 80, q.k), { color: this.cols[i], rot: q.rot }); } },+ track(t) { const o = {}; for (let i = 0; i < 3; i++) { const q = this.q(t, i); o['s' + i] = [q.x, q.y]; } return o; } },++ ribbon: { group: 'carry', from: 'pocket-weather', note: 'an elastic rail: the hand pulls, the panel switches with a ring-out, the words lag behind', dur: 2.6,+ sw: [0.55, 1.5], cols: [C.sun, C.lilac, C.mint], words: ['Make room', 'Slow down', 'Start fresh'],+ hx(t) { const d = (a, b) => OM.tween(t, a, b, ease.cubicInOut); return t < 0.6 ? lerp(1500, 1080, d(0.2, 0.55)) : t < 1.1 ? lerp(1080, 1500, d(0.65, 1.05)) : t < 1.55 ? lerp(1500, 1080, d(1.15, 1.5)) : lerp(1080, 1500, d(1.6, 2.0)); },+ draw(t) { clear(); const rb = OM.ribbon(t, this.sw);+ for (let j = 0; j < 3; j++) { const x = 960 + (j - rb.shift) * 1280 + rb.wobble; if (x < -700 || x > W + 700) continue;+ g.save(); g.translate(x, 470); g.rotate(rb.rot * 0.4); g.scale(rb.sx, rb.sy); rr(-500, -290, 1000, 580, 40); g.fillStyle = this.cols[j]; g.fill(); subject(0, 10, 140, { color: '#fffaf0' }); g.restore();+ text(this.words[j], x + rb.textDx, 900, { size: 76, weight: 600 }); }+ const pressed = (t > 0.22 && t < 0.56) || (t > 1.17 && t < 1.51); pointer(this.hx(t), 640, pressed ? 0.84 : 1); },+ track(t) { const rb = OM.ribbon(t, this.sw), x = 960 + (1 - rb.shift) * 1280 + rb.wobble; return { panel: [x, 470], words: [x + rb.textDx, 900], hand: [this.hx(t), 640] }; } },++ seal: { group: 'carry', from: 'pocket-weather', note: 'lockup: the cast folds into a turning seal while the name rises from its mask', dur: 2.2,+ cols: [C.sun, C.lilac, C.mint],+ draw(t) { clear(); const sl = OM.seal(t, 0.2, 1.1, { r: 230 }), cx = 1330, cy = 540;+ g.save(); g.translate(cx, cy); g.rotate(sl.rot); g.beginPath(); g.arc(0, 0, sl.r, 0, Math.PI * 2); g.fillStyle = C.sun; g.fill();+ for (let k = 0; k < 12; k++) { g.rotate(Math.PI / 6); g.beginPath(); g.arc(sl.r * 0.82, 0, 6 * sl.k, 0, Math.PI * 2); g.fillStyle = 'rgba(22,22,22,.35)'; g.fill(); } g.restore();+ for (let i = 0; i < 3; i++) { const q = OM.gather(t, 0.2, 1.1, i, 3, { x: 520 + i * 440, y: 540 }, { x: cx + (i - 1) * 110, y: cy + (i === 1 ? -40 : 40) }, { arc: 140, spin: 0.4 }); subject(q.x, q.y, lerp(120, 64, q.k), { color: this.cols[i], rot: q.rot }); }+ ['Pocket', 'Weather', 'Club.'].forEach((s, i) => { const m = OM.maskRise(t, 1.15, i, { dist: 150 }); g.save(); g.beginPath(); g.rect(170, 250 + i * 150, 820, 150); g.clip(); text(s, 200, 330 + i * 150 + m.y, { size: 130, weight: 650, align: 'left' }); g.restore(); }); },+ track(t) { const sl = OM.seal(t, 0.2, 1.1, { r: 230 }); return { seal: { x: 1330, y: 540, w: 2 * sl.r, h: 2 * sl.r }, name: [480, 330 + OM.maskRise(t, 1.15, 0, { dist: 150 }).y] }; } },++ staccato: { group: 'carry', from: 'motion-web', note: 'hard cuts in a burst: the one place a cut may replace everything', dur: 1.4,+ list: [[0.2, 'MOTION'], [0.45, 'IS'], [0.67, 'THE'], [0.89, 'MATERIAL']], shots: [0.1, 0.3, 0.55, 0.75, 1.0, 1.3],+ draw(t) { clear(); const w = OM.staccato(t, this.list); if (w.word) text(w.word, 960, 560, { size: 120, weight: 800 }); },+ track() { return {}; } },++ // ─────────────── contact — one thing causes another ───────────────+ impactSplit: { group: 'contact', from: 'pocket-weather', note: 'the subject lands on the headline: glyphs split, bounce by distance, rejoin', dur: 2.2,+ setup() { this.gl = glyphs('A little brighter.', 124, 600, SANS); },+ pos(t) { const hit = 0.87; if (t < hit) { const h = OM.hop(t, 0, hit, { x: -200, y: 200 }, { x: 960, y: 560 }, { height: 260 }); return [h.x, h.y, 1, 1]; } const im = OM.impact(t, hit); return [960, 560 - Math.abs(im.r) * 90, im.sx, im.sy]; },+ draw(t) { clear(); for (const [ch, cx] of this.gl) { const sp = OM.impactSplit(t, 0.87, cx, 960); g.save(); g.translate(cx + sp.dx, 700 + sp.dy); g.rotate(sp.rot); text(ch, 0, 0, { size: 124, weight: 600 }); g.restore(); }+ const [x, y, sx, sy] = this.pos(t); subject(x, y, 110, { sx, sy }); },+ track(t) { const [x, y] = this.pos(t), a = this.gl[0], b = this.gl[9], sa = OM.impactSplit(t, 0.87, a[1], 960), sb = OM.impactSplit(t, 0.87, b[1], 960);+ return { subject: [x, y], A: [a[1] + sa.dx, 700 + sa.dy], b: [b[1] + sb.dx, 700 + sb.dy] }; } },++ press: { group: 'contact', from: 'motion-web', note: 'the hand arrives and clicks; the button rings, flashes and changes state', dur: 1.6,+ hand: [{ t: 0, x: 1500, y: 1000 }, { t: 0.55, x: 972, y: 552 }, { t: 1.0, x: 972, y: 552 }, { t: 1.5, x: 1260, y: 900 }],+ draw(t) { clear(); card(660, 340, 600, 400); const p = OM.press(t, 0.7, { flash: 0.5 });+ g.save(); g.translate(960, 540); g.scale(1 + p.sq, 1 - p.sq * 1.4); rr(-150, -40, 300, 80, 40); g.fillStyle = p.active ? C.green : C.ink; g.fill(); text(p.down ? 'Added' : 'Add to cart', 0, 2, { size: 30, weight: 600, color: '#fff' }); g.restore();+ const cu = OM.cursor(t, this.hand, [0.7]); pointer(cu.x, cu.y, cu.s); },+ track(t) { const cu = OM.cursor(t, this.hand, [0.7]), p = OM.press(t, 0.7); return { hand: [cu.x, cu.y], button: { x: 960, y: 540, w: 300 * (1 + p.sq), h: 80 * (1 - p.sq * 1.4) } }; } },++ squash: { group: 'contact', from: 'motion-web', note: 'stretch along the direction of travel, thin across it: velocity in, scale out', dur: 2.2,+ path: [{ t: 0, x: 420, y: 700 }, { t: 0.5, x: 900, y: 360 }, { t: 0.9, x: 1500, y: 640 }, { t: 1.4, x: 1000, y: 820 }, { t: 1.9, x: 560, y: 520 }, { t: 2.2, x: 620, y: 460 }],+ draw(t) { clear(); const p = OM.spline(this.path, t), q = OM.spline(this.path, t - 1 / 120), s = OM.squash((p[0] - q[0]) * 120, (p[1] - q[1]) * 120);+ g.save(); g.translate(p[0], p[1]); g.rotate(s.ang); g.scale(s.sx, s.sy); g.beginPath(); g.arc(0, 0, 60, 0, Math.PI * 2); g.fillStyle = C.blue; g.fill(); g.restore(); },+ track(t) { const p = OM.spline(this.path, t); return { ball: [p[0], p[1]] }; } },++ sims: { group: 'contact', from: 'motion-web', note: 'live mechanisms precomputed at 240 Hz — magnetic button, spring follow, jelly, verlet string — one hand drives all four', dur: 3.4,+ shots: [0.3, 0.75, 1.3, 1.95, 2.6, 3.1],+ setup() {+ const cards = this.cards = [{ kind: 'magnet', x: 420, y: 190, t: 0, out: 3.1 }, { kind: 'follow', x: 1040, y: 190, t: 0, out: 3.1 }, { kind: 'jelly', x: 420, y: 600, t: 0, out: 3.1 }, { kind: 'verlet', x: 1040, y: 600, t: 0, out: 3.1 }];+ const mc = (m, fx, fy) => ({ x: m.x + fx * 460, y: m.y + fy * 270 });+ this.hand = [{ t: 0, x: 960, y: 1150 }, { t: 0.35, ...mc(cards[0], 0.9, 1.1) }, { t: 0.62, ...mc(cards[0], 0.52, 0.6) }, { t: 0.66, ...mc(cards[0], 0.5, 0.58) }, { t: 0.95, ...mc(cards[0], 0.5, 0.58) },+ { t: 1.05, ...mc(cards[1], 0.18, 0.62) }, { t: 1.25, ...mc(cards[1], 0.8, 0.36) }, { t: 1.45, ...mc(cards[1], 0.3, 0.8) }, { t: 1.62, ...mc(cards[1], 0.6, 0.5) },+ { t: 1.85, ...mc(cards[2], 0.08, 0.62) }, { t: 2.0, ...mc(cards[2], 0.92, 0.46) }, { t: 2.2, ...mc(cards[2], 1.05, 0.4) },+ { t: 2.42, ...mc(cards[3], 0.12, 0.6) }, { t: 2.62, ...mc(cards[3], 0.88, 0.56) }, { t: 2.82, ...mc(cards[3], 0.4, 0.66) }, { t: 3.2, ...mc(cards[3], 0.45, 1.4) }];+ const hand = t => OM.spline(this.hand, t);+ for (const m of cards) m.sim = OM.sim[m.kind](m, hand);+ },+ draw(t) { clear(); const click = 0.66;+ for (const m of this.cards) { card(m.x, m.y, 460, 270); text(m.kind, m.x + 22, m.y + 30, { size: 19, align: 'left', color: C.grey, font: 'ui-monospace,Menlo,monospace' });+ g.save(); g.beginPath(); g.rect(m.x, m.y, 460, 270); g.clip(); g.translate(m.x, m.y);+ if (m.kind === 'magnet') { const [x, y] = m.sim.at(t), B = m.sim.B, p = OM.press(t, click, { depth: 0.1, flash: 0.35 }); g.translate(B.x + x, B.y + y); g.scale(1 + p.sq, 1 - p.sq * 1.4); rr(-92, -30, 184, 60, 30); g.fillStyle = p.active ? C.green : C.ink; g.fill(); text(p.down ? 'Added' : 'Add to cart', 0, 1, { size: 21, color: '#fff' }); }+ if (m.kind === 'follow') { const [x, y, vx, vy] = m.sim.at(t), q = OM.squash(vx, vy); g.translate(x, y); g.rotate(q.ang); g.scale(q.sx, q.sy); g.beginPath(); g.arc(0, 0, 26, 0, Math.PI * 2); g.fillStyle = C.blue; g.fill(); }+ if (m.kind === 'jelly') { const r = m.sim.at(t), { N, R0, C: cc } = m.sim, pts = []; for (let i = 0; i < N; i++) { const th = i / N * Math.PI * 2; pts.push([cc.x + Math.cos(th) * R0 * (1 + r[i]), cc.y + Math.sin(th) * R0 * (1 + r[i])]); }+ g.beginPath(); g.moveTo(pts[0][0], pts[0][1]); for (let i = 0; i < N; i++) { const p0 = pts[(i + N - 1) % N], p1 = pts[i], p2 = pts[(i + 1) % N], p3 = pts[(i + 2) % N]; g.bezierCurveTo(p1[0] + (p2[0] - p0[0]) / 6, p1[1] + (p2[1] - p0[1]) / 6, p2[0] - (p3[0] - p1[0]) / 6, p2[1] - (p3[1] - p1[1]) / 6, p2[0], p2[1]); }+ g.closePath(); g.fillStyle = C.peach; g.fill(); }+ if (m.kind === 'verlet') { const s = m.sim.at(t), N = m.sim.N; g.beginPath(); g.moveTo(s[0], s[1]); for (let i = 1; i < N; i++) g.lineTo(s[i * 2], s[i * 2 + 1]); g.strokeStyle = C.ink; g.lineWidth = 2.5; g.lineCap = 'round'; g.stroke();+ g.fillStyle = C.ink; for (let i = 0; i < N; i++) { g.beginPath(); g.arc(s[i * 2], s[i * 2 + 1], i === N - 1 ? 7 : 3.2, 0, Math.PI * 2); g.fill(); } }+ g.restore(); }+ const cu = OM.cursor(t, this.hand, [click]); pointer(cu.x, cu.y, cu.s); },+ track(t) { const cu = OM.cursor(t, this.hand, [0.66]), f = this.cards[1], [x, y] = f.sim.at(t); return { hand: [cu.x, cu.y], follow: [f.x + x, f.y + y] }; } },++ // ─────────────── camera ───────────────+ camera: { group: 'camera', from: 'library', note: 'one camera, three depths: the near layer moves most, the far least; depth of field from distance to focus', dur: 2.6,+ keys: [{ t: 0.3, x: 960, y: 540, zoom: 1 }, { t: 2.1, x: 1150, y: 600, zoom: 1.5 }],+ layer(t, depth, fn) { const cam = OM.camera(t, this.keys); g.save(); g.setTransform(...OM.view(cam, { depth })); g.filter = `blur(${OM.dof(depth, 0, { k: 5 }).toFixed(1)}px)`; fn(); g.restore(); },+ draw(t) { clear();+ this.layer(t, 1.5, () => { for (let i = 0; i < 7; i++) { g.beginPath(); g.arc(160 + i * 300, 300 + (i % 2) * 120, 110, 0, Math.PI * 2); g.fillStyle = [C.lilac, C.mint, C.sun][i % 3]; g.fill(); } });+ this.layer(t, 0, () => windowFrame(560, 250, 800, 520, { tint: C.mint }));+ this.layer(t, -0.35, () => { for (let i = 0; i < 4; i++) { card(380 + i * 380, 820 - (i % 2) * 60, 220, 80, { r: 40 }); text(['springs', 'carry', 'shutter', 'rest'][i], 490 + i * 380, 860 - (i % 2) * 60, { size: 30 }); } }); },+ track(t) { const cam = OM.camera(t, this.keys);+ return { far: apply(OM.view(cam, { depth: 1.5 }), 1060, 420), focus: apply(OM.view(cam, { depth: 0 }), 960, 510), near: apply(OM.view(cam, { depth: -0.35 }), 870, 860) }; } },++ whip: { group: 'camera', from: 'library', note: 'a whip: 1920 px in .35 s on expo in-out; it only reads with render.py --shutter', dur: 1.6, shots: [0.4, 0.69, 0.72, 0.75, 0.8, 1.3],+ draw(t) { clear(); const w = OM.whip(t, 0.55, 0.35, 1920); g.save(); g.translate(-w.d, 0);+ windowFrame(460, 230, 1000, 620, { tint: C.lilac }); text('before', 960, 940, { size: 56, color: C.grey });+ windowFrame(460 + 1920, 230, 1000, 620, { tint: C.sun }); text('after', 960 + 1920, 940, { size: 56, color: C.grey }); g.restore(); },+ track(t) { return { world: [960 - OM.whip(t, 0.55, 0.35, 1920).d, 540] }; } },++ shake: { group: 'camera', from: 'library', note: 'a word slams in and the frame shakes, decaying; deterministic and starting from zero', dur: 1.6,+ k(t) { return OM.tween(t, 0.3, 0.45, ease.expoIn); },+ draw(t) { clear(); const sh = OM.shake(t, 0.45, { amp: 16 }), k = this.k(t); g.save(); g.translate(960 + sh.x, 540 + sh.y); g.rotate(sh.rot);+ g.globalAlpha = clamp(k * 3); g.scale(lerp(2.4, 1, k), lerp(2.4, 1, k)); text('SHIP IT', 0, 0, { size: 150, weight: 800 }); g.restore(); },+ track(t) { const sh = OM.shake(t, 0.45, { amp: 16 }), s = lerp(2.4, 1, this.k(t)); return { word: { x: 960 + sh.x, y: 540 + sh.y, w: 620 * s, h: 150 * s } }; } },++ drift: { group: 'camera', from: 'motion-web', note: 'the calm hold: one window, a slow push from 1.00 to 1.07 — the rest before the hits', dur: 2.4,+ sc(t) { const w = OM.popIn(t, 0.1, { zeta: 0.7, omega: 16, rise: 40, s0: 0.96, ds: 0.04 }); return [w, w.s * OM.drift(t, 0.1, 2.3, 0.07)]; },+ draw(t) { clear(); const [w, s] = this.sc(t); g.save(); g.globalAlpha = w.op; g.translate(960, 540 + w.dy); g.scale(s, s); windowFrame(-700, -420, 1400, 840, { tint: C.peach }); g.restore(); },+ track(t) { const [w, s] = this.sc(t); return { window: { x: 960, y: 540 + w.dy, w: 1400 * s, h: 840 * s } }; } },++ // ─────────────── fluid — from ebb ───────────────+ swiftSpring: { group: 'fluid', from: 'ebb', note: "SwiftUI's named springs: .smooth, .snappy, .bouncy — Spring(duration, bounce) as ζ = 1 − b, ω = 2π/d", dur: 1.4,+ draw(t) { clear(); ['smooth', 'snappy', 'bouncy'].forEach((k, i) => { const v = OM.swiftSpring(t - 0.15, k), x = 460 + v * 1000, y = 360 + i * 180;+ g.fillStyle = '#e8e8e4'; g.fillRect(460, y - 2, 1000, 4); g.beginPath(); g.arc(x, y, 34, 0, 7); g.fillStyle = [C.ink, C.red, C.green][i] || C.ink; g.fill(); text('.' + k, 300, y, { size: 30, align: 'left' }); }); },+ track(t) { const o = {}; ['smooth', 'snappy', 'bouncy'].forEach((k, i) => { o[k] = [460 + OM.swiftSpring(t - 0.15, k) * 1000, 360 + i * 180]; }); return o; } },++ lightField: { group: 'fluid', from: 'ebb', note: 'a ground of light that is always there: it rises, floods the frame in ≤ 0.4 s, and drains — the same object moving, not a wipe', dur: 2.6,+ level(t) { return t < 1.2 ? 0.5 * OM.ease.smooth(OM.seg(t, 0.1, 1.1)) : t < 1.6 ? OM.lerp(0.5, 1.05, OM.ease.expoOut(OM.seg(t, 1.2, 1.5))) : 1.05 * (1 - OM.ease.smoother(OM.seg(t, 1.6, 2.5))); },+ draw(t) { clear(); g.fillStyle = '#fdfbf7'; g.fillRect(0, 0, 1920, 1080); const f = OM.lightField(this.level(t));+ g.save(); g.translate(f.cx, f.cy); g.rotate(f.tilt); g.scale(f.rx / f.ry, 1); const gr = g.createRadialGradient(0, 0, 0, 0, 0, f.ry);+ [[236, 104, 46, 1], [244, 150, 92, 1], [250, 204, 170, 1], [253, 236, 222, 0.75], [253, 236, 222, 0]].forEach((c, i) => gr.addColorStop(f.stops[i], `rgba(${c.join(',')})`));+ g.fillStyle = gr; g.fillRect(-f.ry, -f.ry, 2 * f.ry, 2 * f.ry); g.restore(); },+ track(t) { const f = OM.lightField(this.level(t)); return { horizon: [960, Math.max(0, f.horizon)] }; } },++ ripple: { group: 'fluid', from: 'ebb', note: 'a flood drains as three rings leaving one point, alternating tints; the world shows through the innermost', dur: 2.0,+ draw(t) { clear(); g.fillStyle = '#fdfbf7'; g.fillRect(0, 0, 1920, 1080); card(760, 330, 400, 420); const r = OM.ripple(t, 0.2).r, hole = R => { g.moveTo(960 + R, 540); g.arc(960, 540, Math.max(0.01, R), 0, 7, true); };+ g.beginPath(); g.rect(0, 0, 1920, 1080); hole(r[0]); g.fillStyle = 'rgb(240,120,60)'; g.fill('evenodd');+ g.beginPath(); g.arc(960, 540, r[0], 0, 7); hole(r[1]); g.fillStyle = 'rgb(248,196,158)'; g.fill('evenodd');+ g.beginPath(); g.arc(960, 540, r[1], 0, 7); hole(r[2]); g.fillStyle = 'rgb(252,226,206)'; g.fill('evenodd'); },+ track(t) { const r = OM.ripple(t, 0.2).r; return { ring0: { x: 960, y: 540, w: 2 * r[0], h: 2 * r[0] }, ring2: { x: 960, y: 540, w: 2 * r[2], h: 2 * r[2] } }; } },++ silk: { group: 'fluid', from: 'ebb', note: 'domain-warped noise on a 16×20 grid, ramped through a dark fold, drawn up with a blur, one pale wisp', dur: 3.0,+ setup() { this.c = document.createElement('canvas'); this.c.width = 16; this.c.height = 20; this.x = this.c.getContext('2d'); this.im = this.x.createImageData(16, 20); },+ draw(t) { clear(); [['peach', 3, 360], ['ember', 24, 800], ['dusk', 61, 1240]].forEach(([r, seed, x]) => {+ OM.silk(t * 1.5, seed, OM.silk.ramps[r], { out: this.im.data }); this.x.putImageData(this.im, 0, 0);+ g.save(); g.beginPath(); g.roundRect(x, 250, 320, 406, 30); g.clip(); g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high'; g.filter = 'blur(26px)'; g.drawImage(this.c, x - 37, 213, 394, 480); g.restore();+ text(r, x + 20, 700, { size: 26, align: 'left', color: C.grey }); }); },+ track(t) { return { card: { x: 520, y: 453, w: 320, h: 406 } }; } },++ carouselLoop: { group: 'fluid', from: 'ebb', note: 'a belt that never rests until told to: constant speed after a .smooth start; its clock slows every card with it', dur: 3.2,+ setup() { this.B = OM.carouselLoop({ dur: 3.4, start: 0.2, speed: 420, stop: [2.3, 2.8] }); },+ draw(t) { clear(); const b = this.B.at(t); for (let i = -2; i < 9; i++) { const x = ((i * 300 - b.x) % 3300 + 3300) % 3300 - 600; card(x, 400, 260, 300, { r: 26 });+ g.fillStyle = [C.lilac, C.red, C.green][((i % 3) + 3) % 3]; g.globalAlpha = 0.35; g.fillRect(x + 20, 420 + 120 * (0.5 + 0.5 * Math.sin(b.tau * 3 + i)), 220, 16); g.globalAlpha = 1; } },+ track(t) { const b = this.B.at(t); return { belt: [960 - (b.x % 300), 550] }; } },+};++const q = new URLSearchParams(location.search), name = q.get('demo');+window.__demos = Object.entries(DEMOS).map(([n, d]) => ({ name: n, group: d.group, from: d.from, note: d.note, dur: d.dur, shots: d.shots || null }));+if (!name || !DEMOS[name]) {+ const idx = document.getElementById('index'), groups = {};+ for (const d of window.__demos) (groups[d.group] = groups[d.group] || []).push(d);+ idx.innerHTML = `<div style="font:600 30px ${SANS}">onetake · gallery</div>` + Object.entries(groups).map(([gn, ds]) => `<h2>${gn}</h2>` ++ ds.map(d => `<div><a href="?demo=${d.name}&play">${d.name}</a> — ${d.note} <span style="color:#8f8f8b">(${d.from})</span></div>`).join('')).join('');+ idx.style.display = 'block'; window.__meta = { dur: 0 }; window.__ready = Promise.resolve();+} else {+ const D = DEMOS[name];+ document.getElementById('cap').innerHTML = `<b>OM.${name}</b> · ${D.group} · ${D.from}`;+ window.__meta = { dur: D.dur, fps: 60, demo: name, group: D.group, from: D.from, note: D.note };+ window.__seek = async t => { D.draw(t); return true; };+ window.__track = t => (D.track ? D.track(t) : {});+ window.__ready = document.fonts.ready.then(() => { if (D.setup) D.setup(); D.draw(0); });+ if (q.has('t')) window.__ready.then(() => D.draw(parseFloat(q.get('t'))));+ if (q.has('play')) window.__ready.then(() => { const t0 = performance.now(); (function loop() { D.draw(((performance.now() - t0) / 1000) % (D.dur + 0.6)); requestAnimationFrame(loop); })(); });+}+</script>+</body>+</html>diff --git a/gallery/sheets/camera.png b/gallery/sheets/camera.pngnew file mode 100644index 0000000..b7b1a0eBinary files /dev/null and b/gallery/sheets/camera.png differdiff --git a/gallery/sheets/carouselLoop.png b/gallery/sheets/carouselLoop.pngnew file mode 100644index 0000000..d824560Binary files /dev/null and b/gallery/sheets/carouselLoop.png differdiff --git a/gallery/sheets/drift.png b/gallery/sheets/drift.pngnew file mode 100644index 0000000..6f5ef58Binary files /dev/null and b/gallery/sheets/drift.png differdiff --git a/gallery/sheets/flyThrough.png b/gallery/sheets/flyThrough.pngnew file mode 100644index 0000000..0bae3eeBinary files /dev/null and b/gallery/sheets/flyThrough.png differdiff --git a/gallery/sheets/gather.png b/gallery/sheets/gather.pngnew file mode 100644index 0000000..2bb385bBinary files /dev/null and b/gallery/sheets/gather.png differdiff --git a/gallery/sheets/hop.png b/gallery/sheets/hop.pngnew file mode 100644index 0000000..05c65b5Binary files /dev/null and b/gallery/sheets/hop.png differdiff --git a/gallery/sheets/impactSplit.png b/gallery/sheets/impactSplit.pngnew file mode 100644index 0000000..9f5dbedBinary files /dev/null and b/gallery/sheets/impactSplit.png differdiff --git a/gallery/sheets/iris.png b/gallery/sheets/iris.pngnew file mode 100644index 0000000..d5decbcBinary files /dev/null and b/gallery/sheets/iris.png differdiff --git a/gallery/sheets/letterDrop.png b/gallery/sheets/letterDrop.pngnew file mode 100644index 0000000..cdbccceBinary files /dev/null and b/gallery/sheets/letterDrop.png differdiff --git a/gallery/sheets/lightField.png b/gallery/sheets/lightField.pngnew file mode 100644index 0000000..9a513efBinary files /dev/null and b/gallery/sheets/lightField.png differdiff --git a/gallery/sheets/maskRise.png b/gallery/sheets/maskRise.pngnew file mode 100644index 0000000..f9430f5Binary files /dev/null and b/gallery/sheets/maskRise.png differdiff --git a/gallery/sheets/morphRect.png b/gallery/sheets/morphRect.pngnew file mode 100644index 0000000..1943df6Binary files /dev/null and b/gallery/sheets/morphRect.png differdiff --git a/gallery/sheets/popIn.png b/gallery/sheets/popIn.pngnew file mode 100644index 0000000..d88bb67Binary files /dev/null and b/gallery/sheets/popIn.png differdiff --git a/gallery/sheets/press.png b/gallery/sheets/press.pngnew file mode 100644index 0000000..e8d505eBinary files /dev/null and b/gallery/sheets/press.png differdiff --git a/gallery/sheets/ribbon.png b/gallery/sheets/ribbon.pngnew file mode 100644index 0000000..a225eb5Binary files /dev/null and b/gallery/sheets/ribbon.png differdiff --git a/gallery/sheets/ripple.png b/gallery/sheets/ripple.pngnew file mode 100644index 0000000..06c5d6eBinary files /dev/null and b/gallery/sheets/ripple.png differdiff --git a/gallery/sheets/seal.png b/gallery/sheets/seal.pngnew file mode 100644index 0000000..909c3f3Binary files /dev/null and b/gallery/sheets/seal.png differdiff --git a/gallery/sheets/shake.png b/gallery/sheets/shake.pngnew file mode 100644index 0000000..8178ef1Binary files /dev/null and b/gallery/sheets/shake.png differdiff --git a/gallery/sheets/silk.png b/gallery/sheets/silk.pngnew file mode 100644index 0000000..aca1283Binary files /dev/null and b/gallery/sheets/silk.png differdiff --git a/gallery/sheets/sims.png b/gallery/sheets/sims.pngnew file mode 100644index 0000000..d5372adBinary files /dev/null and b/gallery/sheets/sims.png differdiff --git a/gallery/sheets/squash.png b/gallery/sheets/squash.pngnew file mode 100644index 0000000..beca373Binary files /dev/null and b/gallery/sheets/squash.png differdiff --git a/gallery/sheets/staccato.png b/gallery/sheets/staccato.pngnew file mode 100644index 0000000..34feb58Binary files /dev/null and b/gallery/sheets/staccato.png differdiff --git a/gallery/sheets/swiftSpring.png b/gallery/sheets/swiftSpring.pngnew file mode 100644index 0000000..425746fBinary files /dev/null and b/gallery/sheets/swiftSpring.png differdiff --git a/gallery/sheets/tick.png b/gallery/sheets/tick.pngnew file mode 100644index 0000000..399c2bdBinary files /dev/null and b/gallery/sheets/tick.png differdiff --git a/gallery/sheets/typeOn.png b/gallery/sheets/typeOn.pngnew file mode 100644index 0000000..8125a67Binary files /dev/null and b/gallery/sheets/typeOn.png differdiff --git a/gallery/sheets/whip.png b/gallery/sheets/whip.pngnew file mode 100644index 0000000..2f34ce3Binary files /dev/null and b/gallery/sheets/whip.png differdiff --git a/gallery/sheets/wordRise.png b/gallery/sheets/wordRise.pngnew file mode 100644index 0000000..120b3c8Binary files /dev/null and b/gallery/sheets/wordRise.png differdiff --git a/gallery/sheets/zoomThrough.png b/gallery/sheets/zoomThrough.pngnew file mode 100644index 0000000..e246e8dBinary files /dev/null and b/gallery/sheets/zoomThrough.png differdiff --git a/lib/motion.js b/lib/motion.jsnew file mode 100644index 0000000..96252b6--- /dev/null+++ b/lib/motion.js@@ -0,0 +1,500 @@+/* onetake · lib/motion.js — the genre's moves as pure functions of time.+ *+ * Numbers in, numbers out. Nothing here touches the DOM or a canvas, so one call drives+ * `el.style.transform` or `ctx.setTransform` alike. No state and no Math.random: the same arguments+ * always give the same answer, which is what `__seek(t)` needs. The four sims and the camera rig integrate, so+ * they run once at 240 Hz and are sampled by time.+ *+ * Every move comes from a film that was accepted — motion-web-15s (MW), pocket-weather-15s (PW), one-dot-15s (OD) —+ * and has a sheet in gallery/sheets/<name>.png. Catalogue, curve table, carry grammar:+ * references/motion-library.md.+ *+ * Classic script (file:// pages cannot import modules): <script src="motion.js"></script> → window.OM.+ * Node: const OM = require('./motion.js').+ *+ * curves ease.* · bezier · tween · t80 · spring · springVel · ring · settle · spline · rng+ * enter wordRise · letterDrop · popIn · liftOut · maskRise · typeOn · tick · flyThrough+ * carry morphRect · iris · zoomThrough · hop · gather · ribbon · seal · staccato+ * contact impact · impactSplit · press · cursor · squash · sim.{magnet, follow, jelly, verlet}+ * camera camera · view · dof · whip · shake · drift · lattice · project · unproject · projectBox · screenTravel+ * fluid swiftSpring · lightField · ripple · silk · carouselLoop+ */+(function (root) {+ 'use strict';++ // ─────────────────────────────── scalars ───────────────────────────────+ const clamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));+ const lerp = (a, b, k) => a + (b - a) * k;+ const seg = (t, t0, t1) => (t1 === t0 ? (t >= t1 ? 1 : 0) : clamp((t - t0) / (t1 - t0), 0, 1));+ const sstep = (e0, e1, x) => { const k = clamp((x - e0) / (e1 - e0), 0, 1); return k * k * (3 - 2 * k); };+ const ssstep = (e0, e1, x) => { const k = clamp((x - e0) / (e1 - e0), 0, 1); return k * k * k * (k * (k * 6 - 15) + 10); };++ // ─────────────────────────────── curves ───────────────────────────────+ // t80 = share of the duration spent before 80 % of the distance is covered. Low = snaps then settles+ // (launch-clip feel); ~.7 = symmetric S-curve (soft, reads as a web transition when used for travel).+ const powOut = n => u => 1 - Math.pow(1 - u, n);+ const powInOut = n => u => (u < 0.5 ? Math.pow(2, n - 1) * Math.pow(u, n) : 1 - Math.pow(-2 * u + 2, n) / 2);+ const EXPO = 1 - Math.pow(2, -10);+ const ease = {+ linear: u => u, // t80 .80+ smooth: u => u * u * (3 - 2 * u), // t80 .71 smoothstep+ smoother: u => u * u * u * (u * (u * 6 - 15) + 10), // t80 .67 smootherstep — PW's travel curve+ sineInOut: u => -(Math.cos(Math.PI * u) - 1) / 2,+ cubicInOut: powInOut(3), // camera legs that start and stop at rest+ quintInOut: powInOut(5),+ quadOut: powOut(2), // t80 .55+ cubicOut: powOut(3), // t80 .42+ quartOut: powOut(4), // t80 .33+ quintOut: powOut(5), // t80 .28+ expoOut: u => (u <= 0 ? 0 : u >= 1 ? 1 : (1 - Math.pow(2, -10 * u)) / EXPO), // t80 .23+ expoIn: u => (u <= 0 ? 0 : u >= 1 ? 1 : (Math.pow(2, 10 * u) - 1) / 1023),+ expoInOut: u => (u < 0.5 ? ease.expoIn(2 * u) / 2 : 1 - ease.expoIn(2 - 2 * u) / 2), // whips+ circOut: u => Math.sqrt(1 - Math.pow(1 - clamp(u), 2)),+ backOut: u => { const s = 1.70158; return 1 + (s + 1) * Math.pow(u - 1, 3) + s * Math.pow(u - 1, 2); },+ back: (s = 1.70158) => u => 1 + (s + 1) * Math.pow(u - 1, 3) + s * Math.pow(u - 1, 2),+ };++ // CSS cubic-bezier(x1, y1, x2, y2) as a function of u — for curves taken from a spec or a reference.+ function bezier(x1, y1, x2, y2) {+ const cx = 3 * x1, bx = 3 * (x2 - x1) - cx, ax = 1 - cx - bx, cy = 3 * y1, by = 3 * (y2 - y1) - cy, ay = 1 - cy - by;+ const sx = s => ((ax * s + bx) * s + cx) * s, sy = s => ((ay * s + by) * s + cy) * s, dsx = s => (3 * ax * s + 2 * bx) * s + cx;+ const solve = x => {+ let s = x;+ for (let i = 0; i < 8; i++) {+ const e = sx(s) - x; if (Math.abs(e) < 1e-7) return s;+ const d = dsx(s); if (Math.abs(d) < 1e-6) break;+ s -= e / d; if (s < 0 || s > 1) break;+ }+ let lo = 0, hi = 1; s = x;+ for (let i = 0; i < 60; i++) { const v = sx(s); if (Math.abs(v - x) < 1e-7) return s; if (x > v) lo = s; else hi = s; s = (lo + hi) / 2; }+ return s;+ };+ return u => (u <= 0 ? 0 : u >= 1 ? 1 : sy(solve(u)));+ }++ const tween = (t, t0, t1, curve = ease.expoOut) => curve(seg(t, t0, t1));++ function t80(curve, frac = 0.8, steps = 4000) {+ for (let i = 0; i <= steps; i++) { const u = i / steps; if (curve(u) >= frac) return u; }+ return 1;+ }++ // Damped spring step response 0 → 1 from rest. zeta < 1 overshoots (.4 bouncy … .8 firm), 1 is critical.+ function spring(tau, zeta = 0.6, omega = 20) {+ if (tau <= 0) return 0;+ if (zeta < 1) { const wd = omega * Math.sqrt(1 - zeta * zeta); return 1 - Math.exp(-zeta * omega * tau) * (Math.cos(wd * tau) + (zeta * omega / wd) * Math.sin(wd * tau)); }+ if (zeta === 1) return 1 - Math.exp(-omega * tau) * (1 + omega * tau);+ const q = omega * Math.sqrt(zeta * zeta - 1), r1 = -zeta * omega + q, r2 = -zeta * omega - q;+ return 1 - (r2 * Math.exp(r1 * tau) - r1 * Math.exp(r2 * tau)) / (r2 - r1);+ }++ // d/dtau of spring(): progress per second. Use it for squash-from-velocity.+ function springVel(tau, zeta = 0.6, omega = 20) {+ if (tau <= 0) return 0;+ if (zeta < 1) { const s = Math.sqrt(1 - zeta * zeta); return (omega / s) * Math.exp(-zeta * omega * tau) * Math.sin(omega * s * tau); }+ if (zeta === 1) return omega * omega * tau * Math.exp(-omega * tau);+ const q = omega * Math.sqrt(zeta * zeta - 1), r1 = -zeta * omega + q, r2 = -zeta * omega - q;+ return omega * omega * (Math.exp(r1 * tau) - Math.exp(r2 * tau)) / (r1 - r2);+ }++ // Decaying oscillation around 0 — a click, a landing, a wobble that rings out.+ function ring(tau, decay = 9, omega = 26) { return tau <= 0 ? 0 : Math.exp(-decay * tau) * Math.sin(omega * tau); }++ // Seconds until spring() stays within eps of 1 — for planning how long a beat must hold.+ function settle(zeta = 0.6, omega = 20, eps = 0.02) {+ let last = 0;+ for (let i = 1; i <= 20000; i++) { const t = i / 1000; if (Math.abs(1 - spring(t, zeta, omega)) > eps) last = t; }+ return last;+ }++ // Hermite curve through {t, x, y} knots — the hand path.+ function spline(knots, t) {+ if (t <= knots[0].t) return [knots[0].x, knots[0].y];+ const L = knots.length; if (t >= knots[L - 1].t) return [knots[L - 1].x, knots[L - 1].y];+ let i = 0; while (knots[i + 1].t < t) i++;+ const k0 = knots[i], k1 = knots[i + 1], h = k1.t - k0.t, u = (t - k0.t) / h, km = knots[Math.max(0, i - 1)], kp = knots[Math.min(L - 1, i + 2)];+ const m0x = (k1.x - km.x) / (k1.t - km.t) * h, m0y = (k1.y - km.y) / (k1.t - km.t) * h, m1x = (kp.x - k0.x) / (kp.t - k0.t) * h, m1y = (kp.y - k0.y) / (kp.t - k0.t) * h;+ const h00 = 2 * u ** 3 - 3 * u ** 2 + 1, h10 = u ** 3 - 2 * u ** 2 + u, h01 = -2 * u ** 3 + 3 * u ** 2, h11 = u ** 3 - u ** 2;+ return [h00 * k0.x + h10 * m0x + h01 * k1.x + h11 * m1x, h00 * k0.y + h10 * m0y + h01 * k1.y + h11 * m1y];+ }++ // xorshift32 — for layout jitter decided once in setup, never on the render path.+ function rng(seed = 1) {+ let s = (seed >>> 0) || 1;+ return () => { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; return (s >>> 0) / 4294967296; };+ }++ // ─────────────────────────────── enter ───────────────────────────────+ // MW · a word lands: spring rise + a little scale. Opacity leads the spring so it never reads as a fade.+ function wordRise(t, t0, { zeta = 0.6, omega = 22, dist = 26, s0 = 0.94, ds = 0.06, fade = 1.5 } = {}) {+ const k = spring(t - t0, zeta, omega);+ return { k, op: clamp(k * fade, 0, 1), y: (1 - k) * dist, s: s0 + ds * k };+ }++ // MW · wordmark letter i drops in; speed flattens it (sy) and widens it (sx), recovering as it settles.+ function letterDrop(t, t0, i, { stagger = 0.055, zeta = 0.5, omega = 26, dist = 46, squash = 0.0075, max = 0.22, widen = 0.6, fade = 1.6, h = 0.012 } = {}) {+ const tau = t - t0 - i * stagger;+ const k = spring(tau, zeta, omega), dk = (spring(tau, zeta, omega) - spring(tau - h, zeta, omega)) / h;+ const sq = clamp(Math.abs(dk) * squash, 0, max);+ return { k, sq, op: clamp(k * fade, 0, 1), y: (1 - k) * dist, sx: 1 + sq * widen, sy: 1 - sq };+ }++ // MW · card entrance: spring rise with scale.+ function popIn(t, t0, { zeta = 0.62, omega = 18, rise = 36, s0 = 0.94, ds = 0.06, fade = 1.5 } = {}) {+ const k = spring(t - t0, zeta, omega);+ return { k, op: clamp(k * fade, 0, 1), s: s0 + ds * k, dy: (1 - k) * rise };+ }++ // MW · card exit: lifts, grows a touch and blurs away over `dur`.+ function liftOut(t, t1, { dur = 0.22, dir = -1, dist = 90, blur = 10, grow = 0.03 } = {}) {+ const k = ssstep(t1, t1 + dur, t);+ return { k, op: 1 - k, dy: dir * k * dist, blur: k * blur, s: 1 + grow * k };+ }++ // PW · line i rises into place from behind a clip mask. y is a fraction of `dist` (pass the line height).+ function maskRise(t, t0, i = 0, { stagger = 0.13, zeta = 0.47, omega = 17, dist = 1 } = {}) {+ const k = spring(t - t0 - i * stagger, zeta, omega);+ return { k, y: (1 - k) * dist, visible: k > 0 };+ }++ // MW · typed prompt: characters at cps, caret solid while typing, blinking after.+ function typeOn(t, t0, text, { cps = 38, blink = 2.4 } = {}) {+ const n = clamp(Math.floor((t - t0) * cps), 0, text.length);+ return { n, str: text.slice(0, n), done: n >= text.length, caret: (n < text.length || Math.floor(t * blink) % 2 === 0) ? 1 : 0 };+ }++ // MW · checkbox tick at tl: pops from .8 with a spring.+ function tick(t, tl, { zeta = 0.5, omega = 28 } = {}) {+ const on = t >= tl, k = spring(t - tl, zeta, omega);+ return { on, k, s: on ? (0.8 + 0.2 * k + 0.25 * (1 - k)) : 1 };+ }++ // MW · a screen flies in tilted from the right, holds, flies out left. For CSS:+ // translate(x) perspective(2200px) rotateY(rotY) rotateX(rotX) scale(s), filter blur(blur).+ function flyThrough(t, t0, hold, { from = 1500, to = 0, exit = -1700, zeta = 0.78, omega = 14, out = 0.28,+ blurIn = 10, blurOut = 12, rotY0 = -18, rotY1 = -9, rotOut = 10, rotX = 4, s0 = 0.92, pre = 0.02, post = 0.35 } = {}) {+ const t1 = t0 + hold, visible = t >= t0 - pre && t < t1 + post;+ const kin = spring(t - t0, zeta, omega), kout = ssstep(t1, t1 + out, t), kc = Math.min(1, kin);+ return { visible, kin, kout, x: lerp(from, to, kin) + kout * exit, blur: Math.max((1 - kc) * blurIn, kout * blurOut),+ rotY: lerp(rotY0, rotY1, kc) + kout * rotOut, rotX, s: lerp(s0, 1, kc), op: 1 - kout };+ }++ // ─────────────────────────────── carry — the next shot grows out of this one ───────────────────────────────+ // PW · container transform: rect A (a card, a button) becomes rect B (the page). {x, y, w, h, r?}, x/y top-left.+ function morphRect(t, t0, t1, A, B, { curve = ease.expoOut, spring: sp = null } = {}) {+ const k = sp ? spring(t - t0, sp.zeta ?? 0.7, sp.omega ?? 16) : curve(seg(t, t0, t1));+ const x = lerp(A.x, B.x, k), y = lerp(A.y, B.y, k), w = lerp(A.w, B.w, k), h = lerp(A.h, B.h, k);+ return { k, x, y, w, h, r: lerp(A.r ?? 0, B.r ?? 0, k), cx: x + w / 2, cy: y + h / 2 };+ }++ // PW · a circular stage opens from the subject at (cx, cy) until it covers the whole frame.+ function iris(t, t0, t1, cx, cy, { W = 1920, H = 1080, curve = ease.expoOut, r0 = 0 } = {}) {+ const k = curve(seg(t, t0, t1));+ const far = Math.max(Math.hypot(cx, cy), Math.hypot(W - cx, cy), Math.hypot(cx, H - cy), Math.hypot(W - cx, H - cy)) + 2;+ return { k, cx, cy, r: lerp(r0, far, k), covered: k >= 1 };+ }++ // Camera pushes into `target` {x, y, w, h} until it fills the frame; its inside becomes the next scene.+ // screen = world·s + (tx, ty) → CSS matrix(...matrix) with transform-origin 0 0, or ctx.setTransform(...matrix).+ function zoomThrough(t, t0, t1, target, { W = 1920, H = 1080, curve = ease.expoInOut, fit = 'cover' } = {}) {+ const k = curve(seg(t, t0, t1));+ const sEnd = fit === 'contain' ? Math.min(W / target.w, H / target.h) : Math.max(W / target.w, H / target.h);+ const s = Math.exp(Math.log(sEnd) * k); // log space: the zoom reads as one speed+ const tcx = target.x + target.w / 2, tcy = target.y + target.h / 2;+ const px = lerp(tcx, W / 2, k), py = lerp(tcy, H / 2, k); // the target's centre travels to the frame centre+ const tx = px - s * tcx, ty = py - s * tcy;+ return { k, s, tx, ty, matrix: [s, 0, 0, s, tx, ty] };+ }++ // PW · the subject hops between slots on an arc.+ function hop(t, t0, t1, from, to, { height = 200, curve = ease.smoother } = {}) {+ const k = curve(seg(t, t0, t1));+ return { k, x: lerp(from.x, to.x, k), y: lerp(from.y, to.y, k) - Math.sin(k * Math.PI) * height };+ }++ // PW · item i of n travels on an arc to its new place, fanning by index; stagger per item.+ function gather(t, t0, t1, i, n, from, to, { stagger = 0.08, arc = 120, spin = 0.4, curve = ease.smoother } = {}) {+ const k = curve(seg(t, t0 + i * stagger, t1 + i * stagger)), o = i - (n - 1) / 2, bump = Math.sin(k * Math.PI);+ return { k, x: lerp(from.x, to.x, k), y: lerp(from.y, to.y, k) - bump * arc, rot: bump * o * spin };+ }++ // PW · an elastic rail of panels. Each switch time advances `shift` by one with a ring-out; text lags behind.+ // Panel j sits at x = centre + (j − shift)·width + wobble.+ function ribbon(t, switches, { dur = 0.35, amp = 55, decay = 7, omega = 22, tilt = 0.08, stretchX = 0.24, stretchY = 0.15, lag = 1.8, curve = ease.smoother } = {}) {+ let shift = 0, r = 0;+ for (const ts of switches) { shift += curve(seg(t, ts, ts + dur)); r += ring(t - ts, decay, omega); }+ const stretch = Math.abs(r);+ return { shift, index: Math.round(shift), wobble: r * amp, rot: r * tilt, sx: 1 + stretch * stretchX, sy: 1 - stretch * stretchY, textDx: -r * amp * lag };+ }++ // PW · the cast folds into a brand seal: a disc grows and turns.+ function seal(t, t0, t1, { r = 235, turns = 1, curve = ease.smoother } = {}) {+ const k = curve(seg(t, t0, t1));+ return { k, r: r * k, rot: k * turns * Math.PI * 2 };+ }++ // MW · staccato hits: the word whose time has come. list = [[t, word], …]. Hard cuts, in a burst.+ function staccato(t, list) {+ let word = '', i = -1;+ for (let j = 0; j < list.length; j++) if (t >= list[j][0]) { word = list[j][1]; i = j; }+ return { word, i };+ }++ // ─────────────────────────────── contact — one thing causes another ───────────────────────────────+ // PW · the ring of a landing. sx/sy squash the lander; feed r into whatever it lands on.+ function impact(t, tHit, { decay = 7, omega = 22, sqx = 0.13, sqy = 0.16 } = {}) {+ const r = ring(t - tHit, decay, omega);+ return { r, sx: 1 + r * sqx, sy: 1 - r * sqy };+ }++ // PW · a landing at cx splits the headline: the glyph at x is pushed apart, bounces by its distance, rejoins.+ function impactSplit(t, tHit, x, cx, { width = 600, spread = 65, bounce = 65, rot = 0.18, falloff = 3,+ open = [-0.01, 0.48], close = [0.63, 0.98], decay = 7, omega = 22, curve = ease.smoother } = {}) {+ const d = (x - cx) / width, r = ring(t - tHit, decay, omega);+ const apart = curve(seg(t, tHit + open[0], tHit + open[1])) * (1 - curve(seg(t, tHit + close[0], tHit + close[1])));+ return { dx: Math.sign(d) * apart * spread, dy: r * bounce * Math.exp(-d * d * falloff), rot: r * d * rot };+ }++ // MW · a button pressed at tc: rings in scale, `active` for the colour flash.+ function press(t, tc, { depth = 0.16, decay = 10, omega = 30, flash = 0.4 } = {}) {+ const cl = t - tc, sq = cl > 0 ? ring(cl, decay, omega) * depth : 0;+ return { s: 1 + sq, sq, down: cl > 0, active: cl > 0 && cl < flash };+ }++ // MW · the hand: spline through knots, dips to `down` for `hold` s at each click.+ function cursor(t, knots, clicks = [], { down = 0.84, hold = 0.14 } = {}) {+ const p = spline(knots, t); let s = 1;+ for (const c of clicks) { const d = t - c; if (d >= 0 && d < hold) s = down; }+ return { x: p[0], y: p[1], s };+ }++ // MW · stretch along the direction of travel, thin across it (velocity in px/s).+ function squash(vx, vy, { k = 0.0012, max = 0.45, kY = 0.0008, maxY = 0.3 } = {}) {+ const sp = Math.hypot(vx, vy);+ return { speed: sp, ang: Math.atan2(vy, vx), sx: 1 + clamp(sp * k, 0, max), sy: 1 - clamp(sp * kY, 0, maxY) };+ }++ // MW · live mechanisms inside a card, driven by the hand. card = {t, out, x, y} (top-left, 460×270 space);+ // the sim runs t … out + 0.3 once and `at(t)` samples it. Drawing stays in the composition.+ const SDT = 1 / 240;+ const sampler = (st, t0, per) => t => st[clamp(Math.floor((t - t0) / per), 0, st.length - 1)];+ const sim = {+ SDT,+ magnet(card, hand, { B = { x: 230, y: 158 }, R = 150, pull = 0.36, K = 120, damp = 0.85 } = {}) {+ const D = Math.pow(damp, SDT * 60); let x = 0, y = 0, vx = 0, vy = 0; const st = [];+ for (let t = card.t; t <= card.out + 0.3; t += SDT) {+ const h = hand(t); const dx = h[0] - (card.x + B.x), dy = h[1] - (card.y + B.y), d = Math.hypot(dx, dy); let tx = 0, ty = 0;+ if (d < R) { const f = pull * (1 - (d / R) ** 2); tx = dx * f; ty = dy * f; }+ vx += (tx - x) * K * SDT; vy += (ty - y) * K * SDT; vx *= D; vy *= D; x += vx * SDT; y += vy * SDT; st.push([x, y]);+ }+ return { st, per: SDT, B, at: sampler(st, card.t, SDT) };+ },+ follow(card, hand, { K = 70, damp = 0.88, home = [230, 140], box = [30, 430, 50, 240], reach = [40, 500, 40, 310] } = {}) {+ const D = Math.pow(damp, SDT * 60); let x = home[0], y = home[1], vx = 0, vy = 0; const st = [];+ for (let t = card.t; t <= card.out + 0.3; t += SDT) {+ const h = hand(t); let tx = clamp(h[0] - card.x, box[0], box[1]), ty = clamp(h[1] - card.y, box[2], box[3]);+ const inside = h[0] > card.x - reach[0] && h[0] < card.x + reach[1] && h[1] > card.y - reach[2] && h[1] < card.y + reach[3];+ if (!inside) { tx = home[0]; ty = home[1]; }+ vx += (tx - x) * K * SDT; vy += (ty - y) * K * SDT; vx *= D; vy *= D; x += vx * SDT; y += vy * SDT; st.push([x, y, vx, vy]);+ }+ return { st, per: SDT, at: sampler(st, card.t, SDT) };+ },+ // ring of radial springs with neighbour coupling, dented where the hand touches the surface+ jelly(card, hand, { N = 48, C = { x: 230, y: 150 }, R0 = 78, K = 42, CP = 1800, damp = 0.962, reach = 60, dent = 14 } = {}) {+ const D = Math.pow(damp, SDT * 60); const r = new Float32Array(N), v = new Float32Array(N); const st = []; let step = 0;+ for (let t = card.t; t <= card.out + 0.3; t += SDT, step++) {+ const h = hand(t); const hx = h[0] - (card.x + C.x), hy = h[1] - (card.y + C.y);+ for (let i = 0; i < N; i++) {+ const th = i / N * Math.PI * 2; const px = Math.cos(th) * R0 * (1 + r[i]), py = Math.sin(th) * R0 * (1 + r[i]); const d = Math.hypot(hx - px, hy - py);+ let push = 0; if (d < reach) { push = -(1 - d / reach) * dent; }+ const lap = r[(i + N - 1) % N] + r[(i + 1) % N] - 2 * r[i]; v[i] += (-r[i] * K + lap * CP + push) * SDT; v[i] *= D;+ }+ for (let i = 0; i < N; i++) r[i] += v[i] * SDT;+ if (step % 4 === 0) st.push(Float32Array.from(r));+ }+ return { st, per: SDT * 4, N, C, R0, at: sampler(st, card.t, SDT * 4) };+ },+ // N nodes hanging from (ax, ay), pushed aside by the hand; samples are [x0, y0, x1, y1, …]+ verlet(card, hand, { N = 16, L = 13, ax = 230, ay = 40, damp = 0.985, gravity = 1400, reach = 34, push = 2.2, iters = 3 } = {}) {+ const px = new Float32Array(N), py = new Float32Array(N), ox = new Float32Array(N), oy = new Float32Array(N);+ for (let i = 0; i < N; i++) { px[i] = ox[i] = ax; py[i] = oy[i] = ay + i * L; }+ const st = []; let step = 0;+ for (let t = card.t; t <= card.out + 0.3; t += SDT, step++) {+ const h = hand(t); const hx = h[0] - card.x, hy = h[1] - card.y;+ for (let i = 1; i < N; i++) {+ let vx = (px[i] - ox[i]) * damp, vy = (py[i] - oy[i]) * damp; ox[i] = px[i]; oy[i] = py[i]; px[i] += vx; py[i] += vy + gravity * SDT * SDT;+ const dx = px[i] - hx, dy = py[i] - hy, d = Math.hypot(dx, dy); if (d < reach && d > 0.01) { const f = (reach - d) / reach * push; px[i] += dx / d * f; py[i] += dy / d * f; }+ }+ for (let it = 0; it < iters; it++) {+ px[0] = ax; py[0] = ay;+ for (let i = 0; i < N - 1; i++) {+ const dx = px[i + 1] - px[i], dy = py[i + 1] - py[i], d = Math.hypot(dx, dy) || 1e-6, c = (d - L) / d * 0.5;+ if (i === 0) { px[1] -= dx * c * 2; py[1] -= dy * c * 2; } else { px[i] += dx * c; py[i] += dy * c; px[i + 1] -= dx * c; py[i + 1] -= dy * c; }+ }+ }+ if (step % 4 === 0) { const s = new Float32Array(N * 2); for (let i = 0; i < N; i++) { s[i * 2] = px[i]; s[i * 2 + 1] = py[i]; } st.push(s); }+ }+ return { st, per: SDT * 4, N, at: sampler(st, card.t, SDT * 4) };+ },+ };++ // ─────────────────────────────── camera ───────────────────────────────+ // Keys {t, x, y, zoom?, rot?, curve?}; (x, y) is the world point at the frame centre. Zoom interpolates in log space.+ function camera(t, keys, { curve = ease.cubicInOut, W = 1920, H = 1080 } = {}) {+ const pick = k => ({ x: k.x ?? W / 2, y: k.y ?? H / 2, zoom: k.zoom ?? 1, rot: k.rot ?? 0 });+ if (!keys.length) return { x: W / 2, y: H / 2, zoom: 1, rot: 0 };+ if (t <= keys[0].t) return pick(keys[0]);+ const L = keys.length; if (t >= keys[L - 1].t) return pick(keys[L - 1]);+ let i = 0; while (keys[i + 1].t < t) i++;+ const A = pick(keys[i]), B = pick(keys[i + 1]), k = (keys[i + 1].curve || curve)(seg(t, keys[i].t, keys[i + 1].t));+ return { x: lerp(A.x, B.x, k), y: lerp(A.y, B.y, k), zoom: Math.exp(lerp(Math.log(A.zoom), Math.log(B.zoom), k)), rot: lerp(A.rot, B.rot, k) };+ }++ // Affine matrix [a, b, c, d, e, f] for a layer at `depth` seen through `cam`: CSS matrix(...) / ctx.setTransform(...).+ // depth 0 = focus plane; > 0 farther (moves and zooms less); < 0 nearer (moves more).+ function view(cam, { W = 1920, H = 1080, depth = 0 } = {}) {+ const f = 1 / (1 + Math.max(-0.9, depth));+ const cx = W / 2 + (cam.x - W / 2) * f, cy = H / 2 + (cam.y - H / 2) * f;+ const z = Math.exp(Math.log(cam.zoom) * f), c = Math.cos(cam.rot * f) * z, s = Math.sin(cam.rot * f) * z;+ return [c, s, -s, c, W / 2 - (c * cx - s * cy), H / 2 - (s * cx + c * cy)];+ }++ // Depth-of-field blur in px for a layer at `depth` when the camera focuses at `focus`.+ const dof = (depth, focus = 0, { k = 10, max = 14 } = {}) => Math.min(max, Math.abs(depth - focus) * k);++ // A whip: all of `dist` in `dur` on an expo in-out. Only reads with shutter blur (render.py --shutter).+ function whip(t, t0, dur, dist, { curve = ease.expoInOut } = {}) {+ const k = curve(seg(t, t0, t0 + dur));+ return { k, d: dist * k };+ }++ // Camera shake after a hit: decaying, deterministic, starts from zero.+ function shake(t, tHit, { amp = 12, decay = 9, freq = 19, seed = 1 } = {}) {+ const tau = t - tHit; if (tau <= 0) return { x: 0, y: 0, rot: 0 };+ const r = rng(seed), fx = freq * (1 + 0.1 * r()), fy = freq * (1.31 + 0.1 * r()), fr = freq * (0.77 + 0.1 * r());+ const e = amp * Math.exp(-decay * tau), w = 2 * Math.PI * tau;+ return { x: e * Math.sin(w * fx), y: 0.7 * e * Math.sin(w * fy), rot: 0.0015 * e * Math.sin(w * fr) };+ }++ // MW · slow push during a hold: scale 1 → 1 + amount across t0 … t1.+ const drift = (t, t0, t1, amount = 0.07) => 1 + amount * seg(t, t0, t1);++ // Through a view() matrix M: world → screen, screen → world, and a world box's bounds on screen.+ const project = (M, x, y) => [M[0] * x + M[2] * y + M[4], M[1] * x + M[3] * y + M[5]];+ const unproject = (M, x, y) => { const d = M[0] * M[3] - M[1] * M[2], u = x - M[4], v = y - M[5]; return [(M[3] * u - M[2] * v) / d, (M[0] * v - M[1] * u) / d]; };+ function projectBox(M, b) {+ const P = [[b.x, b.y], [b.x + b.w, b.y], [b.x, b.y + b.h], [b.x + b.w, b.y + b.h]].map(p => project(M, p[0], p[1]));+ const xs = P.map(p => p[0]), ys = P.map(p => p[1]), x0 = Math.min(...xs), y0 = Math.min(...ys);+ return { x: x0, y: y0, w: Math.max(...xs) - x0, h: Math.max(...ys) - y0, op: b.op };+ }++ // How far the frame's corners move on screen between cameras c0 and c1 (following the world points under them at+ // cMid): the camera's share of a page's window.__motion, from which render.py sizes each frame's shutter.+ function screenTravel(c0, c1, cMid, { W = 1920, H = 1080, depth = 0 } = {}) {+ const M0 = view(c0, { W, H, depth }), M1 = view(c1, { W, H, depth }), Mm = view(cMid, { W, H, depth });+ let d = 0;+ for (const [sx, sy] of [[0, 0], [W, 0], [0, H], [W, H]]) {+ const [wx, wy] = unproject(Mm, sx, sy), p = project(M0, wx, wy), r = project(M1, wx, wy);+ d = Math.max(d, Math.hypot(p[0] - r[0], p[1] - r[1]));+ }+ return d;+ }++ // OD · an operator, not keyframes. want(t) → {x, y, zoom, w}: what to frame, how tight, how fast to chase (rad/s).+ // A spring per axis chases it — position ζ .8; zoom in log space, ζ .95 at .8 w — integrated once at `hz` and+ // sampled, so moves lag, lean and settle while every frame stays a function of t. hits [[t, px, decay], …] shake.+ // Output is quantised below what shows (1/16 px, 0.05 % zoom): a settled camera repeats its frame exactly and+ // render.py skips the shutter. A snap faster than the spring outruns it: want the landing point ~0.15 s before+ // the snap rather than chasing it (the one-dot film's first camera render lost its dot that way).++ // OD · a far grid seen through `cam`: under ctx.setTransform(...matrix), a dot of radius r at every lattice point from+ // (x0, y0) to (x1, y1) in steps of `spacing` — dots stay `px` on screen whatever the zoom. On an empty ground a+ // camera move doesn't read without something farther back to slide against (one-dot: 48, depth 1.2, 1.4 px).+ function lattice(cam, { depth = 1.2, spacing = 48, px = 1.4, W = 1920, H = 1080 } = {}) {+ const M = view(cam, { W, H, depth }), c = [[0, 0], [W, 0], [0, H], [W, H]].map(p => unproject(M, p[0], p[1]));+ const xs = c.map(p => p[0]), ys = c.map(p => p[1]);+ return { matrix: M, spacing, r: px / Math.hypot(M[0], M[1]),+ x0: Math.floor(Math.min(...xs) / spacing) * spacing, x1: Math.max(...xs), y0: Math.floor(Math.min(...ys) / spacing) * spacing, y1: Math.max(...ys) };+ }++ // ─────────────────────────────── fluid (FL · ebb) ───────────────────────────────+ // SwiftUI's named springs: Spring(duration d, bounce b) is ζ = 1 − b, ω = 2π / d. .smooth b 0, .snappy .15, .bouncy .3.+ const SWIFT = { smooth: 0, snappy: 0.15, bouncy: 0.3 };+ function swiftSpring(tau, kind = 'smooth', { duration = 0.5, bounce = null } = {}) {+ const b = bounce ?? SWIFT[kind] ?? 0;+ return spring(tau, 1 - b, 2 * Math.PI / duration);+ }++ // A persistent ground of light: level 0 = at rest (a low glow, horizon ≈ rest·H), 1 = the frame flooded. Returns the+ // ellipse (anchored below the frame) to fill with a radial gradient — `stops` are the reference's, warm or green — and+ // `core`, the half-radius contour where the light is bright enough to turn type white. Flood ≤ 0.4 s, drain ~1 s.+ function lightField(level, { W = 1920, H = 1080, rest = 0.84, top = -300, r0 = 660, r1 = 1500, tilt = 0.012 } = {}) {+ const ry = r0 + r1 * level, horizon = lerp(H * rest, top, level);+ return { cx: W / 2, cy: horizon + 0.62 * ry, rx: ry * 2.3, ry, tilt, horizon, core: 0.5, stops: [0, 0.36, 0.6, 0.8, 1] };+ }++ // A flood that drains as concentric rings: n radii leaving a point, `stagger` apart, each crossing the frame in `dur`.+ // Fill the flood outside ring 0, alternate two tints between the rings, and the world shows through the innermost.+ function ripple(t, t0, { n = 3, stagger = 0.16, dur = 1.25, rMax = 1160, curve = ease.smoother } = {}) {+ const r = []; for (let k = 0; k < n; k++) r.push(rMax * curve(seg(t, t0 + k * stagger, t0 + k * stagger + dur)));+ return { r, done: t >= t0 + (n - 1) * stagger + dur };+ }++ // silk — the "native MeshGradient" look: domain-warped value noise, two octaves, on a tiny grid, contrast-stretched and+ // ramped. Returns RGBA for gx × gy; putImageData it into a gx × gy canvas and draw that up to the card with blur(28 px at+ // 520 wide). A ramp whose lightness is not monotonic (a dark fold between two brights) is what reads as cloth.+ function silkHash(x, y, s) { let h = (x * 374761393 + y * 668265263 + s * 1442695041) | 0; h = Math.imul(h ^ (h >>> 13), 1274126177); return ((h ^ (h >>> 16)) >>> 0) / 4294967296; }+ function silkNoise(x, y, s) {+ const xi = Math.floor(x), yi = Math.floor(y), xf = x - xi, yf = y - yi, u = xf * xf * (3 - 2 * xf), v = yf * yf * (3 - 2 * yf);+ const a = silkHash(xi, yi, s), b = silkHash(xi + 1, yi, s), c = silkHash(xi, yi + 1, s), d = silkHash(xi + 1, yi + 1, s);+ return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;+ }+ const silkFbm = (x, y, s) => 0.5 * silkNoise(x, y, s) + 0.25 * silkNoise(x * 2.02, y * 2.02, s);+ function silkRamp(stops, k) {+ k = clamp(k, 0, 1);+ for (let i = 1; i < stops.length; i++) if (k <= stops[i][0]) { const [a, A] = stops[i - 1], [b, B] = stops[i], u = (k - a) / (b - a); return A.map((v, j) => v + (B[j] - v) * u); }+ return stops[stops.length - 1][1];+ }+ const SILK = {+ ember: [[0, [200, 120, 24]], [0.22, [236, 170, 34]], [0.42, [122, 96, 26]], [0.54, [160, 94, 32]], [0.74, [240, 74, 92]], [1, [252, 210, 198]]],+ peach: [[0, [240, 150, 92]], [0.24, [252, 204, 148]], [0.44, [190, 104, 66]], [0.58, [236, 124, 108]], [0.8, [250, 186, 172]], [1, [255, 240, 228]]],+ dusk: [[0, [118, 58, 94]], [0.24, [226, 98, 112]], [0.44, [88, 44, 68]], [0.58, [176, 74, 98]], [0.8, [246, 150, 122]], [1, [255, 224, 204]]],+ };+ function silk(tau, seed = 3, stops = SILK.peach, { gx = 16, gy = 20, contrast = 3.4, out = null } = {}) {+ const d = out || new Uint8ClampedArray(gx * gy * 4);+ for (let j = 0; j < gy; j++) for (let i = 0; i < gx; i++) {+ const u = i / gx * 1.1, v = j / gy * 1.4;+ const qx = silkFbm(u + 0.11 * tau, v - 0.07 * tau, seed), qy = silkFbm(u + 5.2 - 0.09 * tau, v + 1.3 + 0.05 * tau, seed);+ const k = 0.5 + (silkFbm(u + 1.8 * qx + 0.04 * tau, v + 1.8 * qy, seed) - 0.375) * contrast;+ const c = silkRamp(stops, k), n = (i + j * gx) * 4;+ d[n] = c[0]; d[n + 1] = c[1]; d[n + 2] = c[2]; d[n + 3] = 255;+ }+ return d;+ }+ silk.ramps = SILK; silk.ramp = silkRamp;++ // A belt that never rests until it is told to: position and a slowed clock, integrated once so the start (a .smooth+ // swiftSpring over `rampDur`) and the stop (a smoothstep over `stop`) stay pure functions of t. at(t) → {x, tau}: x in+ // px travelled at `speed` px/s, tau the clock to drive every card's own loop (silk, typing) so they slow with the belt.+ function carouselLoop({ dur, start = 0, speed = 204, rampDur = 1.0, stop = null, hz = 240 } = {}) {+ const n = Math.ceil(dur * hz) + 1, X = new Float64Array(n), TA = new Float64Array(n);+ let x = 0, tau = 0;+ for (let i = 0; i < n; i++) {+ const t = i / hz, k = stop ? 1 - ease.smooth(seg(t, stop[0], stop[1])) : 1;+ x += speed * swiftSpring(t - start, 'smooth', { duration: rampDur }) * k / hz; tau += k / hz; X[i] = x; TA[i] = tau;+ }+ return { at(t) { const f = clamp(t * hz, 0, n - 1), i = Math.floor(f), j = Math.min(n - 1, i + 1), u = f - i; return { x: lerp(X[i], X[j], u), tau: lerp(TA[i], TA[j], u) }; } };+ }++ const OM = {+ version: '1.1.0-lite',+ clamp, lerp, seg, sstep, ssstep, ease, bezier, tween, t80, spring, springVel, ring, settle, spline, rng,+ wordRise, letterDrop, popIn, liftOut, maskRise, typeOn, tick, flyThrough,+ morphRect, iris, zoomThrough, hop, gather, ribbon, seal, staccato,+ impact, impactSplit, press, cursor, squash, sim,+ camera, view, dof, whip, shake, drift, lattice, project, unproject, projectBox, screenTravel,+ swiftSpring, lightField, ripple, silk, carouselLoop,+ };+ root.OM = OM;+ if (typeof module === 'object' && module.exports) module.exports = OM;+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/lib/ui_kit.js b/lib/ui_kit.jsnew file mode 100644index 0000000..25be07d--- /dev/null+++ b/lib/ui_kit.js@@ -0,0 +1,94 @@+/* ui_kit.js — helpers for films that show a product's UI without a screen recording: the UI rebuilt in HTML,+ * placed on the composition's plane, highlighted from its own DOM, narrated, and cut in more than one language.+ * → window.UIK (or module.exports under node). Pure functions and small factories; no look is baked in —+ * colours, sizes and timings are always arguments. See references/product-demo.md.+ */+(function (root) {+ 'use strict';+ const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));+ const lerp = (a, b, k) => a + (b - a) * k;+ const seg = (t, a, b) => clamp((t - a) / (b - a));++ // ── the replica on the plane ──────────────────────────────────────────────────────────────────────────────────────+ // A replica is laid out in its reference's own pixel frame (e.g. a recording's 1918 × 1080) and shown scaled by `s`+ // inside a window at (x, y) on the plane, under a chrome bar `chrome` px tall. place(lx, ly) → plane point;+ // box(r) → plane rect for a replica-local rect.+ function stage({ x, y, s, chrome = 0 }) {+ const place = (lx, ly) => ({ x: x + lx * s, y: y + chrome + ly * s });+ const box = r => ({ x: x + r.x * s, y: y + chrome + r.y * s, w: r.w * s, h: r.h * s });+ return { place, box, s };+ }+ // An element's rect in the replica's own frame, by the offset chain up to `rootClass`. Not getBoundingClientRect:+ // that one already includes the camera's transform and changes every frame.+ function domLocal(el, rootClass) {+ let x = 0, y = 0, e = el;+ while (e && !(e.classList && e.classList.contains(rootClass))) { x += e.offsetLeft; y += e.offsetTop; e = e.offsetParent; }+ return { x, y, w: el.offsetWidth, h: el.offsetHeight };+ }+ // Remembers each key's last measured rect, so a highlight can keep fading out after its element is hidden.+ function rectCache() {+ const m = {};+ return (key, measure) => { const r = measure && measure(); if (r && r.w > 0) m[key] = r; return m[key] || null; };+ }+ // Lays items out left to right by their measured width (for strings whose width changes with the language);+ // a replica keeps the reference's fixed lefts for its source language and flows for every other one.+ function flow(items, x0, gap) { let x = x0; items.forEach(e => { e.style.left = x + 'px'; x += e.offsetWidth + gap; }); return x; }++ // ── highlight: a rounded rect hugging the content, drawn on, a soft glow, then out ────────────────────────────────+ // g: a 2D context already in plane coordinates · r: {x, y, w, h} · col: any CSS colour · zoom: the camera's, so the+ // line keeps its screen width. spring(t) is optional (pass OM.spring for a small pop). Returns nothing when off.+ function glowRing(g, r, t, t0, t1, col, { pad = 8, zoom = 1, out = 0.3, draw = 0.45, layers = [[10, 0.35, 14], [4, 0.6, 6], [2.4, 1, 0]], fill = 0.07, pop = null } = {}) {+ const o = 1 - clamp((t - t1) / out); if (t < t0 || o <= 0) return;+ const k = 1 - Math.pow(2, -10 * seg(t, t0, t0 + draw)); // expo-out draw-on+ const x = r.x - pad, y = r.y - pad, w = r.w + 2 * pad, h = r.h + 2 * pad, q = Math.min(12, h / 3, w / 3);+ const per = 2 * (w + h) - (8 - 2 * Math.PI) * q, sc = pop ? pop(t - t0) : 1;+ g.save(); g.translate(x + w / 2, y + h / 2); g.scale(sc, sc); g.translate(-(x + w / 2), -(y + h / 2));+ g.beginPath(); g.roundRect(x, y, w, h, q);+ if (fill) { g.globalAlpha = fill * k * o; g.fillStyle = col; g.fill(); }+ g.setLineDash([per * k, per + 10]); g.lineCap = 'round'; g.strokeStyle = col;+ layers.forEach(([lw, op, blur]) => { g.globalAlpha = op * o * clamp(k * 3); g.lineWidth = lw / zoom; g.shadowColor = blur ? col : 'transparent'; g.shadowBlur = blur; g.stroke(); });+ g.setLineDash([]); g.shadowColor = 'transparent'; g.restore();+ }+ // How big a replica's text is on screen: font px × replica scale × camera zoom. Aim ≥ 26 for anything the VO names.+ const screenPx = (fontPx, s, zoom) => fontPx * s * zoom;+ const zoomFor = (fontPx, s, targetPx = 26) => targetPx / (fontPx * s);++ // ── languages ─────────────────────────────────────────────────────────────────────────────────────────────────────+ // tr(lang)({en: '…', ja: '…'}) → that language's string, falling back to en; a plain string passes through.+ const tr = lang => o => (o == null || typeof o !== 'object' ? o : (o[lang] ?? o.en));+ // Registers a local font file only for the languages that need it and resolves when it has loaded (await it in+ // __ready). Keep the source language's page untouched: nothing is added when need is false.+ function loadFont(family, url, { weight = '100 900', need = true } = {}) {+ if (!need || typeof FontFace === 'undefined') return Promise.resolve();+ const f = new FontFace(family, `url(${url})`, { weight }); document.fonts.add(f); return f.load();+ }++ // ── time: one authored timeline, several narrations ───────────────────────────────────────────────────────────────+ // Beats, camera, hand and events are authored once, on the source VO. Another language's film maps its own clock onto+ // that authoring clock through knots [[filmT, authorT], …], set on words that mean the same thing (not just line+ // starts: word order moves). Linear between knots, 1:1 before the first and after the last. U: film → authoring,+ // Ui: authoring → film. Seek draws at U(t); subtitles and __meta.dur are film time; __events() maps back with Ui.+ function timeWarp(knots) {+ const K = [...knots].sort((p, q) => p[0] - q[0]);+ for (let i = 1; i < K.length; i++) if (!(K[i][0] > K[i - 1][0] && K[i][1] > K[i - 1][1])) throw new Error(`timeWarp: knots must rise on both clocks (at ${i})`);+ const map = (t, a, b) => {+ if (!K.length) return t; if (t <= K[0][a]) return K[0][b] + t - K[0][a];+ for (let i = 0; i < K.length - 1; i++) if (t < K[i + 1][a]) return K[i][b] + (t - K[i][a]) * (K[i + 1][b] - K[i][b]) / (K[i + 1][a] - K[i][a]);+ const q = K[K.length - 1]; return q[b] + t - q[a];+ };+ // slopes: authoring seconds per film second, per stretch — < 0.5 is slow motion, > 1.4 is a rush; check before rendering+ const slopes = K.slice(1).map((q, i) => ({ film: [K[i][0], q[0]], rate: (q[1] - K[i][1]) / (q[0] - K[i][0]) }));+ return { U: t => map(t, 0, 1), Ui: t => map(t, 1, 0), slopes };+ }+ const identity = { U: t => t, Ui: t => t, slopes: [] };++ // ── subtitles ─────────────────────────────────────────────────────────────────────────────────────────────────────+ // subs: [[t0, t1, text], …] in film time (scripts/vo_tools.py subs). → {text, a} with short fades, or null.+ function subAt(subs, t, fade = 0.08) {+ for (const q of subs) if (t >= q[0] && t < q[1]) return { text: q[2], a: clamp((t - q[0]) / fade) * clamp((q[1] - t) / fade) };+ return null;+ }++ const UIK = { stage, domLocal, rectCache, flow, glowRing, screenPx, zoomFor, tr, loadFont, timeWarp, identity, subAt, lerp };+ if (typeof module !== 'undefined' && module.exports) module.exports = UIK; else root.UIK = UIK;+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/references/composition.md b/references/composition.mdnew file mode 100644index 0000000..573dbec--- /dev/null+++ b/references/composition.md@@ -0,0 +1,233 @@+# The composition — one HTML file, every value a function of time++## Contract++```js+window.__seek = async (t) => { ... ; return true; } // sets every style for time t; resolves when images are decoded+window.__ready = document.fonts.ready.then(() => { measure(); simulate(); return seek(0); });+window.__meta = { dur: 15, fps: 30 }; // render.py reads dur; probe.py also reads cuts: [t, …] (bare cuts you mean) and inFrame: {id: [t0, t1] | [t0, t1, 'whole']}+window.__track = (t) => ({ hand: [x, y], card: { x, y, w, h, op } }); // optional — probe.py follows these instead of auto-tracking; with a camera, boxes on screen+window.__motion = (t0, t1) => px; // optional — farthest on-screen travel between t0 and t1 (elements + camera); render.py sizes each frame's shutter from it+```++Query flags: `?play` runs it live in a browser, `?t=6.4&hud` pins a frame and shows the HUD.++`seek(t)` must be **pure**: calling it with 6.4 then 2.0 then 6.4 gives identical frames. So:+no state that accumulates across calls; springs as closed forms; anything that genuinely needs+integration (soft bodies, Verlet strings, magnetic pulls that depend on the hand's history) is+simulated **once** at 240 Hz from a fixed seed and sampled by index — `OM.sim.*` does exactly that.+Purity is also what makes motion blur possible: render.py seeks between frames.++## Moves come from `lib/motion.js`++Copy it next to the composition; `templates/comp.html` already loads `motion.js` and takes its helpers from it:++```js+const {clamp, lerp, sstep, ssstep, spring: spr, ring, spline} = OM;+place(el, x, y, s, op, blur) // the template's one transform write per element per frame+```++Every move is a function of absolute time returning numbers — `OM.wordRise(t, 0.15)` → `{op, y, s}` — that you+write into a transform or a canvas call. Catalogue, curve table, DOM vs canvas: `references/motion-library.md`;+what each looks like: `gallery/sheets/<move>.png`. Don't hand-roll `ease` / `spring` with fixed constants:+Pocket Weather v3 did, and every move in it came out on the same symmetric S-curve.++## Primitives, and what each is for++| primitive | moves | genre role | knobs |+|---|---|---|---|+| kinetic words | `wordRise` | the setup line; one word per beat | word times, one accent colour |+| wordmark letters | `letterDrop` | the name; letters drop with **landing squash** (velocity → scaleY) | stagger 0.055 s, ζ 0.5 |+| prompt card | `popIn` · `typeOn` · `press` · `liftOut` | "what the user typed"; types at ~38 cps; hand clicks send | text, click time |+| checklist panel | `tick` | "what it does"; lines tick one by one; last line is the proof | lines, 0.24 s spacing |+| flying screens | `flyThrough` | outputs; 1000×625 tilted −18°→−9° Y, in from the right, out to the left | footage, hold 0.9 s |+| micro cards | `sim.magnet` · `sim.follow` · `sim.jelly` · `sim.verlet` · `press` · `squash` | mechanisms alive in 460×270 canvases; the hand pokes each | sim kind, position, window |+| browser hold | `popIn` × `drift` | the one calm beat; slow push-in 1.00→1.07 | footage, 1.2 s |+| staccato words | `staccato` | the hits; hard cut, uppercase, small | 0.22–0.36 s each |+| the hand | `cursor` on `spline` | the cause of every reaction | knots, click times |+| end card | — | black, wordmark | |++The template is the motion-web film, and that film has no carries. The moves that join one beat to the next —+`morphRect`, `iris`, `zoomThrough`, `hop`, `gather`, `ribbon`, `seal`, `impactSplit`, `camera` / `view` — are in the+library, from Pocket Weather. Which one for which boundary: motion-library.md → *carry*.++## The hand++One `HAND` array of `{t,x,y}` knots for the whole film; `hand(t)` is the spline through it. The cursor+SVG is drawn from it **and every sim reads from it**, so cause and effect agree by construction.+Clicks are a list of times; `OM.cursor` scales the pointer to 0.84 for 0.14 s at each.++For footage shots, the hand comes from `footage/paths.json` (what actually drove the page): rebuild+it as equal-time segments with smoothstep inside each, exactly as the recorder moved.++## Footage in the composition++Frames are `footage/frames/<name>/NNNN.jpg` at 30 fps. `info.json` gives `n` and `mark` (the frame+where input began). For a shot starting at `t0` that should show the reaction 0.2 s in:++```js+f = clamp(mark - round(0.2*30) + round((t - t0)*30), 0, n-1)+```++Set `img.src` only when the frame changes and push `img.decode()` into the pending list `seek`+returns — the renderer awaits it, so no frame is captured half-decoded.++## Probe — read the composition before rendering it++```bash+python3 scripts/probe.py comp.html # continuity per boundary + curves per move+python3 scripts/probe.py comp.html --out probe/ # + tracks.json and curves.png (speed of the top elements)+```++After every `__seek` it lists what is on screen — DOM elements by transformed rect and effective opacity, every+canvas `drawImage` / `fillText` / fill located through the context transform — so it needs no annotations. It+prints each beat boundary with what carried it (or `bare`), and each move with its t80 and peak px/frame. Run it+as soon as the storyboard plays end to end: a bare boundary is a comp edit, not a re-render. Thresholds and the+films they were calibrated on: rhythm.md → *carry*. `verify_promo.py --comp` turns the numbers into legs.++## Render++```bash+python3 scripts/stills.py comp.html --times 0.7,2.4,6.2 --out stills.png # look before you render+python3 scripts/render.py comp.html --out draft.mp4 --sfx sfx.wav # 1920×1080 · 30 fps · shutter 180° — every review round+python3 scripts/render.py comp.html --out film.mp4 --final --sfx sfx.wav # 3840×2160 · 60 fps — only after the cut is accepted+```++**Drafts until accepted.** A 4K60 render of a cut that gets rejected is minutes spent on nothing; every round+before acceptance is 1080p30.++**Shutter.** A screenshot is an instant, so a fast move strobes into sharp copies; a camera integrates while its+shutter is open. For each frame render.py seeks several times across the open shutter (180° = half a frame+interval, centred on the frame time) and averages the captures in linear light — `--samples` (8) of them, or, when+the page defines `__motion`, as many as keep neighbouring copies `--gap` (6) px apart on screen (4–48, set by+`--samples-min` / `--samples-max`). It captures the two ends first; if they are identical the frame is a hold and+is written as is. Because `__seek` is pure this is the real+integral, not a blur filter: a 100 px box moving 167 px/frame at 30 fps left a 173 px streak with a 27 px solid+core — what a 180° shutter predicts — and the holds stayed byte-identical to an unblurred render. It never+integrates across a cut: when one step between neighbouring captures carries the change, only the captures on the+frame time's side of it are averaged — Pocket Weather v3's hard cut at 11.5 s had become a one-frame dissolve+before that rule. `--shutter 0`+turns it off. CSS `filter: blur()` is not motion blur (it blurs across the motion as much as along it); keep it+for depth.++Cost is captures: a hold takes 2, a moving frame its sample count, and a hold has to be byte-identical — a canvas+comp whose springs are still ringing out rarely is (hold a key flat and keep the hand off it so a settled camera is). Pocket+Weather v3's 15 s draft, fixed at 8, had 93 holds in 450 frames: 3,042 captures, 7.4 minutes in one browser, where+motion-web's draft without shutter took 24 s. A streak is overlapping copies, so a fixed count shows its steps on+the fastest moves: v3's rail at ~340 px/frame smears 170 px in 8 copies 21 px apart, visible on text and edges in a+still, and the one-dot film's 633 px/frame opening stepped into bands. `__motion` puts the captures where the travel+is: the one-dot camera cut spent 4 on 293 of its 411 moving frames and 48 on three — 2,480 captures, where a fixed 8+would have taken 3,366 and still stepped. A capture costs ~0.2 s, most of it Chrome encoding the screenshot (156 ms;+the canvas draws in under 1 ms), so render.py deals the frames to `--workers` processes, each with its own Chromium+(default cores − 2, at most 8): that cut rendered in 103 s on 8 workers, ~8.5 minutes' work for one browser.+900 frames at 4K60 without shutter took 116 s.++render.py writes `<out>.render.json` (fps, scale, shutter, samples — a count, or `adaptive` with captures per moving+frame — workers, still and cut frames, captures, seconds); verify_promo.py reads it.+PNG frames, libx264 crf 16, `yuv420p`, SFX muxed in the same pass. Footage stays 30 fps inside a 60 fps render+(each frame shown twice); the composition's own motion is what gets the 60.++## A camera++One camera, keyed with `OM.camera`, and layers seen through it. Author in world coordinates (the 1920×1080 layout at+zoom 1) and set each layer's matrix before drawing it; the ground's gradient and vignette stay on screen. Keys say+where the camera is at a time and the curve that gets it there; the operator's feel comes from three layers on top:+a hand (a slow two-sine float, faded to zero in the holds), shakes on the landings, and a far lattice to slide against.++```js+KEYS = [ // in __ready, after measure()+ { t: 0, x: 540, y: 0, zoom: 2.3 },+ { t: 3.95, x: 1330, y: 2, zoom: 2.15, curve: OM.ease.sineInOut }, // riding the caret+ { t: 5.35, x: 0, y: -12, zoom: 0.93, rot: -0.008, curve: OM.ease.quintInOut },+];+HITS = [[4.4, 6, 10], [12.7, 10, 9]]; // [t, amp, decay]+const handEnv = t => OM.sstep(0.1, 0.6, t) * (1 - OM.sstep(15.5, 15.9, t)); // zero where the frame must be dead still+function camAt(t) {+ const c = OM.camera(t, KEYS), e = handEnv(t) * 4.2;+ let x = c.x + e * (Math.sin(1.7 * t) + 0.6 * Math.sin(2.9 * t + 1)) / c.zoom, y = c.y + e * (Math.sin(1.3 * t + 2) + 0.5 * Math.sin(3.3 * t)) / c.zoom;+ let rot = c.rot;+ for (const [th, amp, decay] of HITS) { const s = OM.shake(t, th, { amp, decay, seed: Math.round(th * 100) }); x += s.x / c.zoom; y += s.y / c.zoom; rot += s.rot; }+ return { x, y, zoom: c.zoom, rot };+}+function seek(t) {+ CAM = camAt(t);+ ground(); // screen space+ const G = OM.lattice(CAM, { depth: 1.2 }); mat(G.matrix); // a dot of radius G.r at every lattice point+ mat(OM.view(CAM)); // the world layer: everything the story draws+ TRACK = { dot: part(dot, t), … };+}+```++**Chase, don't follow.** A key that lands where the subject *will* be, reached on an `expoInOut`, reads as an operator+snapping to it; a key that trails the subject by ~0.1 s on `sineInOut` reads as one following it. For a snap faster+than the move, key the landing point before the subject gets there. Keep the hand off the holds: a floating camera is+never dead still, and the rests are what make the moves land.++**Report the screen, not the world.** With a camera, `__track` returns boxes on screen (`OM.projectBox(OM.view(CAM), box)`),+so probe measures what the viewer sees move. `__motion(t0, t1)` is the larger of `OM.screenTravel(cam(t0), cam(t1),+cam(mid))` and each box's edge travel between the two times; render.py sizes each frame's shutter from it (*Render*+above). `__meta.inFrame = { dot: [0.5, 15], mark: [12.2, 15, 'whole'] }`+makes verify fail any frame where the dot is off frame or the name is cut.++**Deep zoom: key the screen, not the world.** Past ~20× a world-space move swings the subject a frame-width for every+pixel of error. Key where an anchor A sits on screen and the log of the zoom instead, and recover the camera from that:++```js+const s = screenKeysAt(t); // { x, y, zoom }: A's screen position, log-eased zoom+CAM = { x: A[0] + (960 - s.x) / s.zoom, y: A[1] + (540 - s.y) / s.zoom, zoom: s.zoom, rot };+```++A dive eases log zoom on `cubicInOut` while the target's screen position moves linearly to the centre. Shakes divide x+and y by zoom, so they vanish at depth: add `OM.shake` to the screen position before recovering the camera. The+clearing film went 1× → 300× → 1× this way.++**Nested levels draw in their own units.** A day is a 1440 px page inside a 24 px cell: draw it under+`mul(VIEW, [s, 0, 0, s, ox, oy])` with type at normal sizes and it stays crisp at any zoom. Fade each level's detail in+by its parent's size on screen (`sstep(70, 260, 24 * zoom)`) and cull what is off frame, so the year never draws 364+pages.++**Canvas effects ignore the transform.** `shadowBlur`, `shadowOffsetX/Y` and `filter: blur()` are in device pixels.+Multiply them by DPR × zoom by hand, or shadows shrink as the camera pulls out (`cases/knockon-15s`, `lift`).++## Natural media — a brush++unbroken's ensō is procedural ink with no textures (`cases/unbroken-15s/`). A stroke is an arc sampled every ~4 px — position, radial normal, width,+dryness — drawn as 56 hair polylines spread across the width:++- **width** = a touch-down swell × a breathing body (`vnoise(d / 260)`) × a taper; a stroke cut short thins fast instead;+- **dryness** rises along the stroke. A hair skips where `0.72 · vnoise(i · 0.055) + 0.28 · vnoise(i · 0.45)` falls under+ `dry × (0.45 + 0.9·|o|^1.5 + 0.45·(1 − load))`, so edge hairs and thin-loaded hairs run out first and leave 飞白;+- **ends are round**: edge hairs touch down ~4 samples late and lift ~5 early (∝ o²);+- **drawn to k**: each hair to its own fraction with the head interpolated between samples, so the shutter smears it.++What didn't read: a few thick, even hairs (a plastic band); width swelling from zero at the touch-down (fans); strokes+under ~140 px (tufts).++## Fluid grounds — a light field and silk++`OM.lightField` and `OM.silk` are both pure functions of t. Two rules came out of matching them to the references:++- **Compute the fluid small and let the browser blur it.** A 16×20 field upscaled with smoothing and a canvas+ `blur()` is smoother than any full-resolution noise and costs nothing per frame, and it stays deterministic. The detail+ you are tempted to add is what turns silk into a contour map.+- **Silk needs a fold.** A ramp from dark to light reads as a gradient; put a darker band between two bright hues and+ one thin specular wisp on top, and it reads as cloth catching light.+- A light field works as punctuation only because it is *always there*: at rest it is a low glow under the content,+ so a flood that fills the frame and drains is the same object moving, not a wipe.++## Things that bit++- A `filter: blur()` on an element translated tens of thousands of pixels off-screen painted the+ whole frame **black**. Anything that has left the frame gets `display:none`.+- Fonts: subset and inline (`subset_fonts.py` from motion-web); `file://` pages and remote fonts do not mix,+ and a font that loads late shifts every measured position.+- Measure text positions (`getBoundingClientRect`) **after** `document.fonts.ready`, in `__ready`.+- Word beats written as `opacity` fades read as PowerPoint; write them as springs with translateY and+ a little scale so they *land* (`OM.wordRise`).+- **A dark gradient bands after encoding.** unbroken's radial ground came out of 8-bit `yuv420p` in visible rings. Draw a+ fixed 256² noise pattern (alpha ≤ 7/255, half white, half black) over the ground in device pixels. It is fixed, so+ still frames stay still.+- **A slow push is not a rest.** At 320 px a 1 → 1.05 push over a grid is never dead still: clearing's first render+ failed the rest leg at 0.178 because every hold pushed. With the holds truly still it passed at 0.294.+- A `__seek` that throws at some t is easy to miss in a film. Pocket Weather v2 threw+ `EncodingError: The source image cannot be decoded` from 12.8 s on; probe.py and verify print `__seek threw at N samples`.diff --git a/references/motion-library.md b/references/motion-library.mdnew file mode 100644index 0000000..ce1ca39--- /dev/null+++ b/references/motion-library.md@@ -0,0 +1,189 @@+# The motion library — `lib/motion.js`++Numbers, not styles. Every move is a pure function of absolute film time that returns plain values — offsets,+scales, opacity, radii, matrices — which you write into a DOM transform or a canvas call. No DOM access, no+dependencies, no build step: `<script src="motion.js">` gives `window.OM`; `require('./motion.js')` works in node.+`node scripts/test_motion.js` checks the numbers on this page.++**Look before you pick.** `gallery/sheets/<move>.png` is six frames of the move above the speed of what it moves+(px/frame at 60 fps, t80 per move). A few moves share a sheet: `liftOut` is on popIn's, `impact` on hop's and+impactSplit's, `cursor` on press's, `sim.*` on sims', `view` and `dof` on camera's. `gallery/gallery.html?demo=<move>&play`+loops it live; `python3 scripts/gallery.py` re-renders the sheets after a change to the library.++Two films are the source. **motion-web** (case 1) gave the entrances and the live mechanisms. **Pocket Weather+Club** (case 2) gave the carries — the moves that turned a rejected slideshow into an accepted film.++## Applying a move++```js+const w = OM.wordRise(t, 0.15);+// DOM+el.style.opacity = w.op;+el.style.transform = `translateY(${w.y}px) scale(${w.s})`;+// canvas+g.save(); g.globalAlpha = w.op; g.translate(x, y + w.y); g.scale(w.s, w.s); g.fillText(word, 0, 0); g.restore();++const z = OM.zoomThrough(t, 6.3, 7.3, card); // a matrix move: the same numbers either way+g.setTransform(...z.matrix); // canvas+layer.style.transform = `matrix(${z.matrix.join(',')})`; // DOM, with transform-origin: 0 0+```++Times are absolute seconds, so the timeline is a list of numbers at the top of the composition and any frame can+be sought. The sims, which need the hand's history, are built once in `__ready` (`OM.sim.jelly(card, hand)`) and+sampled with `.at(t)`. Utilities: `clamp`, `lerp`, `seg(t, t0, t1)`, `sstep` / `ssstep`, `spline(knots, t)` (Hermite+through `{t, x, y}` → `[x, y]`), `rng(seed)` for anything random.++## Curves — choose by t80++t80 = the share of a move's duration spent before 80 % of its travel is done. probe.py reports it for every move+in a composition and analyze_ref.py for a reference film, so a curve here, a move in your film and a move in the+reference compare on one number.++| curve | t80 | reads as |+|---|---|---|+| `ease.expoIn` | .97 | a launch; exits only |+| `ease.linear` | .80 | mechanical: a ticker, a tracking shot |+| `ease.smooth` · `sineInOut` | .71 · .71 | soft S |+| `ease.smoother` | .67 | the symmetric S Pocket Weather v3 used for every move |+| `ease.cubicInOut` · `quintInOut` · `expoInOut` | .63 · .58 · .57 | a camera move with weight (`whip`, `zoomThrough`) |+| `ease.quadOut` | .55 | a gentle arrival |+| `ease.cubicOut` · `circOut` | .42 · .40 | UI arrival |+| `ease.quartOut` · `quintOut` | .33 · .28 | a snap |+| `ease.backOut` | .24 | a snap past the mark and back |+| `ease.expoOut` | .23 | there almost at once, then settles (`tween`, `morphRect`, `iris` default to it) |++`OM.bezier(x1, y1, x2, y2)` turns any CSS cubic-bezier into a curve; `OM.t80(curve)` measures one;+`OM.tween(t, t0, t1, curve)` applies one between two times.++Springs are closed forms — `OM.spring(tau, zeta, omega)` — so they seek like a curve:++| ζ, ω | 80 % at | settles ±2 % | overshoot | used by |+|---|---|---|---|---|+| .5, 28 | 0.067 s | 0.29 s | 16 % | `tick` |+| .5, 26 | 0.073 s | 0.31 s | 16 % | `letterDrop` |+| .6, 22 | 0.093 s | 0.27 s | 9.5 % | `wordRise` |+| .47, 17 | 0.109 s | 0.49 s | 19 % | `maskRise` |+| .62, 18 | 0.116 s | 0.33 s | 8 % | `popIn` |+| .7, 16 | 0.140 s | 0.37 s | 5 % | the calm window hold |+| .78, 14 | 0.172 s | 0.26 s | 2 % | `flyThrough` |++A spring reaches 80 % within a quarter to a third of its settle time — a snap with an overshoot chosen by ζ.+`OM.settle(ζ, ω)` gives the settle time so the next beat can start on it; `OM.springVel` is its exact velocity+(× the distance, it feeds `squash`); `OM.ring(tau, decay, omega)` is the decaying wobble after a hit.++## enter — something arrives++| move | returns | what it is | from |+|---|---|---|---|+| `wordRise(t, t0, {zeta, omega, dist, s0, fade})` | `{op, y, s}` | a word lands: spring rise and scale; opacity leads the spring so it never reads as a fade | motion-web |+| `letterDrop(t, t0, i, {stagger, dist, squash})` | `{op, y, sx, sy}` | wordmark letters drop; speed flattens each, the spring restores it | motion-web |+| `popIn(t, t0, {rise, s0})` · `liftOut(t, t1, {dur, dist, blur})` | `{op, s, dy}` · `{op, dy, blur, s}` | a card springs up · lifts, grows a touch and blurs away | motion-web |+| `maskRise(t, t0, i, {stagger, dist})` | `{y, visible}` | lines rise into place from behind a clip | Pocket Weather |+| `typeOn(t, t0, text, {cps, blink})` | `{n, str, done, caret}` | typing at a steady rate, caret solid while typing | motion-web |+| `tick(t, tl)` | `{on, s}` | a checkbox pops from .8 when its line is reached | motion-web |+| `flyThrough(t, t0, hold, {from, exit, rotY0, blurIn})` | `{visible, x, rotY, rotX, s, op, blur}` | a screen flies in tilted, holds, flies out (CSS 3D) | motion-web |++## carry — the next beat grows out of this one++These make a boundary *carried* in probe.py's terms: something survives it and visibly moves or scales into the+next beat.++| move | returns | what it is | reach for it when |+|---|---|---|---|+| `morphRect(t, t0, t1, A, B, {curve})` | `{x, y, w, h, r, cx, cy}` | container transform: one rect becomes another | the thing pressed becomes the result (button → window, card → page) |+| `iris(t, t0, t1, cx, cy)` | `{r, covered}` | a circle opens from a point until it covers the frame | the subject opens its own world (Pocket Weather 6.95 s) |+| `zoomThrough(t, t0, t1, target, {curve, fit})` | `{s, tx, ty, matrix}` | log-space push until the target fills the frame | one card among many is the next scene |+| `hop(t, t0, t1, from, to, {height})` | `{x, y}` | an arc from one slot to the next; land it with `impact` | the subject picks the next thing (Pocket Weather 1.8 s) |+| `gather(t, t0, t1, i, n, from, to, {stagger, arc, spin})` | `{x, y, rot}` | the cast travels on fanned arcs into a cluster | many become one group (10.05 s) |+| `ribbon(t, switches, {amp, lag})` | `{shift, index, wobble, rot, sx, sy, textDx}` | an elastic rail: panels switch with a ring-out, words lag behind | options change under the hand (8.05, 8.95 s) |+| `seal(t, t0, t1, {r, turns})` | `{r, rot}` | a turning disc grows under the folding cast | the cast becomes the brand mark (11.5 s) |+| `staccato(t, list)` | `{word, i}` | hard-cut words | a burst of hits — the one place a bare cut is right |++A `camera` move over one continuous world (below) carries too: at its boundaries everything survives.++## contact — one thing causes another++| move | returns | what it is | from |+|---|---|---|---|+| `impact(t, tHit, {decay, omega, sqx, sqy})` | `{r, sx, sy}` | the landing: squash on the hit, ring out | both |+| `impactSplit(t, tHit, x, cx, {width, spread, bounce})` | `{dx, dy, rot}` | glyphs split by distance from the hit, bounce, rejoin | Pocket Weather |+| `press(t, tc, {depth, flash})` | `{s, sq, down, active}` | a click: dip, ring, state flip | motion-web |+| `cursor(t, knots, clicks)` | `{x, y, s}` | the pointer on the hand spline, shrinking at each click | motion-web |+| `squash(vx, vy, {k, max})` | `{ang, sx, sy}` | stretch along the velocity, thin across it | motion-web |+| `sim.magnet` · `follow` · `jelly` · `verlet` `(card, hand, opts)` | `{at(t), …}` | magnetic button, spring follower, jelly ring, Verlet string — precomputed at 240 Hz | motion-web |++## camera++| move | returns | what it is |+|---|---|---|+| `camera(t, keys)` | `{x, y, zoom, rot}` | keyed camera `{t, x, y, zoom, rot, curve}`, zoom interpolated in log space |+| `view(cam, {depth})` | `[a, b, c, d, e, f]` | the matrix for a layer at `depth` (0 = focus plane, + farther, − nearer): parallax from one camera |+| `dof(depth, focus, {k, max})` | px | blur by distance from the focus plane |+| `whip(t, t0, dur, dist)` | `{k, d}` | a whip pan |+| `shake(t, tHit, {amp, decay, freq, seed})` | `{x, y, rot}` | decaying, deterministic, zero before the hit |+| `drift(t, t0, t1, amount)` | scale | the slow push of a hold, 1 → 1 + amount — verify's rest leg counts it as motion, so keep it off the rests |+| `lattice(cam, {depth, spacing, px})` | `{matrix, r, spacing, x0, x1, y0, y1}` | OD · the visible points of a far grid through `cam`, dots a constant `px` on screen — something for a move to slide against |+| `project(M, x, y)` · `unproject(M, x, y)` · `projectBox(M, box)` | `[x, y]` · box | world ↔ screen through a `view()` matrix; `__track` boxes on screen |+| `screenTravel(c0, c1, cMid)` | px | how far the frame's corners move between two cameras — the camera's share of `__motion` |++**A keyed camera that feels operated.** Still, the one-dot film was 「就缺灵动的跟踪运镜」; with a camera that chases+what each beat frames it was 「运镜、镜头和物理都没问题」. Keys get you there: key the subject a little ahead+(~0.1 s) on `sineInOut` to follow it, key the landing point before a snap on `expoInOut` to whip to it, add a hand+(a slow two-sine float, zero in the holds) and `shake` on every landing (composition.md → *A camera*). ebb and the+onetake launch film were made this way. A move on an empty ground doesn't read: draw a `lattice` farther back+(depth 1.2). The camera's travel adds to every element's: the one-dot camera cut peaked at 935 px/frame at 30 fps.++## fluid — a ground of light, silk, a belt (ebb)++Promoted from `cases/ebb-15s` (accepted 2026-09-24), measured from David Ch's Shipper launch and Nazday's Elera carousel.+The comp is the worked example: the light field is time, the flood drains in rings onto the next scene, silk fills every+card, the belt slows with its own clock.++| move | returns | what it is | reach for it when |+|---|---|---|---|+| `swiftSpring(tau, kind, {duration, bounce})` | `number` | SwiftUI's `Spring(duration d, bounce b)` = `OM.spring` at ζ 1 − b, ω 2π/d; `.smooth` b 0, `.snappy` .15, `.bouncy` .3 | a UI should feel native (Apple) rather than "animated" |+| `lightField(level, {rest, top, r0, r1})` | `{cx, cy, rx, ry, tilt, horizon, core, stops}` | a persistent glow anchored below the frame: level 0 at rest (horizon 0.84 H), 1 flooded. Fill the ellipse with a radial gradient at `stops`; `core` (half radius) is where type turns white. Flood ≤ 0.4 s, drain ~1 s | the ground itself should be the punctuation: it rises, floods, and the next scene appears as it drains |+| `ripple(t, t0, {n, stagger, dur, rMax})` | `{r: [radii], done}` | n rings leave one point `stagger` apart; fill the flood outside r[0], alternate two tints between, the world shows inside the last | a flood has to end on a new scene without a wipe |+| `silk(tau, seed, stops, {gx, gy, contrast, out})` · `silk.ramps` · `silk.ramp` | RGBA `gx × gy` | domain-warped noise, two octaves, 16×20, ×3.4; putImageData, draw up with blur(28 px per 520 wide) and one pale screen wisp. Ramps `ember` `peach` `dusk` carry the dark fold between two brights | a card, wallpaper or lock screen should be alive without content |+| `carouselLoop({dur, start, speed, rampDur, stop})` | `{at(t) → {x, tau}}` | a belt at constant speed after a `.smooth` start, integrated once; `tau` is a clock that slows with it — drive each card's own loop from it | many items should flow past and settle together (Elera: 0.106 W/s) |++## Speed and the shutter++Peak speed decides whether a move needs motion blur. Measured in the gallery at 60 fps: `whip` 540 px/frame,+`iris` 206, `flyThrough` 189, `morphRect` 156, `ribbon` 118, `shake` 115, the follow sim 102, `zoomThrough` 72; the+entrances and the other carries stay under 50. **At 30 fps every number doubles**, so in a draft most carries+cross verify's 80. Render with render.py's default shutter and they smear as far as they travel. The `blur` that+`liftOut` and `flyThrough` return is a CSS filter for depth; it does not replace the shutter.++## Candidates — measured, not yet in a film++A move enters `lib/motion.js` only after a film that used it was accepted: it is written inside that film's+comp.html first, then promoted with a test, a gallery sheet and a row above. The+moves below were measured frame by frame from references and have not been in an accepted film of ours: **HF** — the+Higgsfield × Claude Opus 5.5 launch (41 s, 24 fps, x.com/higgsfield/status/2102451022216179935); **PK** — Pinckus's+part of Flatwhite Motion's Rednote Buildathon piece (7.5 s, 30 fps, x.com/Pinckus102xz/status/2101491848179331220, made+in Cavalry); **FL** — two fluid-ground references: David Ch's Shipper launch (49.9 s, 60 fps,+x.com/chhddavid/status/2102666619029999989) and Nazday's Elera post carousel (16 s, 60 fps, 1600×1200,+x.com/nazmijavierl/status/2102712897701097828) — the FL rows are promoted, see *fluid* above. Build them in the film from these numbers, not from memory; promote them when the film is accepted. Times+are the reference's, sizes at 1080p.++| candidate | what it is | measured |+|---|---|---|+| `glowPress` | a key lit from inside — no cursor; the lit state is the click | attack 1 frame, no ease-in; fill base → cream (rgb 212,122,102 → 250,208,193), brightest at +0.17 s; scale → 0.8 in 0.15 s; a radial halo in the base hue reaches 2.3× the key's width on the first frame, 2.7× at +0.17 s; hold 0.45 s while a white specular runs round the bevel; release 0.13 s back to base, left a shade lighter (219,142,121). 0.67 s in all, the camera drifting through it (8.29 s) |+| `glowBox` | an emphasis pill that lights the scene, then becomes the next one | born as a blurred glow at ~40 % width, full width in 0.2 s; label typed at ~23 cps, the newest glyph magenta for one frame; the whole ground takes a lime cast while it is on (spill); hard cut in to 2.9× with the ground defocused; a heartbeat to 0.8× and back (14.6 s); then it grows past 1.4× until its halo whites out the frame, and the next scene builds on that white (13.72–15.05 s). probe reads the bloom as a fade through the ground — list it in `__meta.cuts` |+| `contourGlow` | the model picks a part: a stroke that follows the silhouette, not a box | ~8–10 px; frame 1 soft amber, frame 2 crisp lime, then thins to nothing — 0.35 s; several parts at once, slightly staggered (16.08 s). Canvas: the cutout's alpha dilated, filled `source-in` |+| `heatType` | typing whose newest glyphs are hot and cool to ink; the line above cools to grey when the next begins | leading glyphs lime → magenta, ink after ~0.3 s (prompt 6.0–7.6 s); status lines reveal left to right with the same hot edge (9.1–10.0 s) |+| `focusIn` | rack-focus entrance: blur, a little extra scale and opacity settle together | the film's most used entrance — the big status text (10.6 s), the 4-up variants (28.3 s), the hero card |+| `wavefront` | stagger by position, not index: many items arrive as flat mattes along a front, then fill with texture | ~120 parts, magenta mattes sweeping in over ~0.5 s, texture following (15.1–15.7 s) |+| `scanBox` · `countUp` | a detection box: stroke, label typed, value counted up, colour = verdict | yellow 42 → 67 %, red 16 %, green 84 → 96 % whose tint fill blinks twice at 12 fps (17.0–19.5 s) |+| `punchLadder` | hard cuts in on one subject, each a step tighter | cuts at 16.08, 16.92, 17.75, 18.5 s through the parts field, each ~1.5–1.8× tighter; ANALYZE's 2.9× cut-in (14.26 s) is a one-step ladder |+| `exposure` | a flash to white that starts a `morphRect`: the photo is taken, then shrinks into the attachment | 5.38–6.0 s |+| `ghost` | a part arrives as a translucent tinted preview, then solidifies | orange ghost wheels (24.5–25.0 s) |+| `belt` (PK) | bands chase round a closed path — a conveyor that carries the title | boundaries along the arc length, each band a stroke with round caps (155 px on a 984 × 330 stadium); the ring unrolls from one point, runs on an expo start then creeps; one band laps and swallows the rest to end the beat (0–1.0 s). Code: `bandState` |+| `reel` (PK) | a slot reel with a pill as its window | index = Σ spring(t − tᵢ, .56, 34) over the step times; neighbours in the pill's colour one pitch above and below, fading by distance; the pill's width follows the fractional index; steps accelerate then brake (0.22 → 0.13 → 0.30 s) and land on the word the next beat needs (1.7–2.9 s). Code: `reelPos`, `reel` |+| `echo` (PK) | grey copies of the landed word stack above and below it, a staircase | copies spring out of the source (ζ .7, ω 26, 0.04 s apart) to ±1, ±2 rows with small x offsets, grey #3a3a3a under the source; retract into it before the next beat (2.9–3.3 s) |+| `lateType` (PK) | typing where one glyph arrives late (NEXT WRLD → WORLD) | ~14 cps, the late glyph ~0.25 s behind; reads as live input rather than a title (0.1–0.6 s) |+| `paintIn` (PK) | a part snaps in unpainted and takes its colour a beat later | grey #c2c2c2 at scale .55 and 0.35 rad, spring ζ .55 ω 20, colour at +0.09 s (3.4–4.0 s) |+| `iconCycle` (PK) | one part changes shape and icon on an accelerating cadence while a word cloud types out around it | swaps 0.26 → 0.16 s apart, each a 0.84 → 1 pop; new words take the current icon's colour, older ones dim to grey; for the last ~0.6 s rows fill the frame edge to edge, then a hard cut (4.4–6.0 s) |++`glowPress`, `glowBox` and `heatType` share one colour logic — hot when new, cooling to ink — so build them together.diff --git a/references/product-demo.md b/references/product-demo.mdnew file mode 100644index 0000000..9440cbd--- /dev/null+++ b/references/product-demo.md@@ -0,0 +1,164 @@+# Product demos without a screen recording — rebuild the UI, narrate it, cut it in any language++A **product feature demo** (产品功能演示 / 功能展示动效): the film shows the product being used — open it, pick a mode,+upload, get the result — usually with a voice and subtitles, 30–60 s. The obvious route is a screen recording; the+cheaper and more controllable one is to **rebuild the product's UI in HTML** from a few reference takes and drive it+from `seek(t)` like everything else in the composition. This page is the method; `lib/ui_kit.js`,+`scripts/vo_tools.py` and `scripts/frame_diff.py` are its tools. It carries no look — see the last section.++## Why a replica beats a recording++- **Every string is data.** A second language is a strings table, not a re-shoot; the product need not even ship that+ language's UI.+- **The camera can go anywhere.** A replica is vector and DOM: a 2.5× close-up on a dropdown is as sharp as the wide.+ A recording is capped by its pixels and its window size.+- **No account, no timing, no leaks.** Nobody waits for a slow run; there are no names, tokens or placeholder strings+ on screen by accident; nothing moves that the film didn't author.+- **It is cheaper than it sounds.** One app screen is a few hundred lines of absolutely positioned HTML, and it only+ needs the states the film shows.++What it costs: the replica must be checked against the real thing side by side, and **content must be real** (below).++## 1 · Reference takes: the smallest ask++The user records or screenshots only **reference takes** — the screens and states the film will show, at any quality.+Asking a non-technical user for a shot list fails (「看不懂让我录什么」). Ask for one concrete thing: "open X, click+Y, type /, screenshot each step". Pull frames from the takes (`ffmpeg -ss … -frames:v 1`), and note every state: the+default, the dropdown open, the menu, the chip after picking, the button lit.++**Content comes from the product's real output only.** The data on screen, the generated file names, the numbers in+the charts: all read by a script from the files the product actually produced (`gen_data.py` → `data.js`, "nothing+typed by hand"). Numbers invented because they look good are a claim the product never made.++## 2 · Build the replica++- **Lay it out in the reference's own pixel frame** (a Retina screenshot halved, e.g. 1918 × 1080), every element+ absolutely placed at its measured position; show it scaled by `s` inside a window on the plane+ (`UIK.stage({x, y, s, chrome})`).+- **Put every string in `STR[lang]` from the first line.** A `build({S})` writes the DOM once; a+ `set(el, state)` writer changes it per frame (mode, placeholder, menu open, hover row, chip shown, send lit) —+ pure, so `seek(t)` can call it at any t.+- **Namespace the CSS under one root class.** A generic class name in the replica (`.ph`) collided with the+ composition's own and painted dashed yellow boxes.+- **Build and measure while visible.** A `display:none` container measures zero; measure after fonts load.+- **Fixed lefts only fit one language.** Keep the reference's measured lefts for the source language, and lay rows+ out by measured width (`UIK.flow`) for every other one.+- **Hide what the client doesn't want seen**: account names, download buttons, workspace names.+- **Compare against the reference.** A `compare.html?s=<state>` shows the replica beside the reference frame at 1:1;+ go state by state until the only differences are deliberate.++## 3 · Show it so it reads++- **Legibility is arithmetic**: text on screen = font px × replica scale × camera zoom (`UIK.screenPx`). Anything+ the VO names should be ≥ 26 px. A 13 px dropdown label in a 0.75-scaled replica needs zoom ≈ 2.7+ (`UIK.zoomFor(13, 0.75)`). A window that must be read should be ~70–80 % of the frame width. Fitting cards, the+ window and a result into one wide shot made the UI unreadable and was sent back.+- **One close-up per operation**: each step (mode → pick → upload → send) gets its own framing, and the camera+ follows the hand between them. The wide shot is for moments where the relation *is* the point.+- **Highlights come from the DOM, drawn on the canvas.** `UIK.domLocal(el, rootClass)` walks the offset chain, not+ `getBoundingClientRect`, which already includes the camera. `stage.box()` turns that into a plane rect.+ `UIK.rectCache()` keeps the last rect so a ring can fade out after its element hides.+- **The user's standing highlight preference**: a glowing rounded rectangle sized to the content (`UIK.glowRing`,+ drawn on, then out) — never a thin frame, never a circle. For a menu row, ring the icon and name, not the whole row.+ Colour, padding, glow and timing are free per film.+- **The cause is visible.** A cursor clicks real element centres, with a press/release pair (~75 ms apart) on each click.++## 4 · Narration++```bash+KPY=~/.cache/kokoro/venv/bin/python+$KPY scripts/vo_tools.py tts vo/lines.txt --voice <v> --lang en-gb --lines 2,4 --sample --out vo/samples # audition voices on 2 lines+$KPY scripts/vo_tools.py tts vo/lines.txt --voice <v> --lang en-gb --out vo/<v>+python3 scripts/vo_tools.py words vo/<v> --lang en --lines vo/lines.txt+python3 scripts/vo_tools.py plan vo/<v> --lead 0.5 --breath 0.45 [--gap 7:2.45]+python3 scripts/vo_tools.py subs vo/lines.txt vo/<v>+```++- **Audition before you commit.** Render the same two lines in 5–8 voices and let the client pick. Clients change+ their mind: the timeline has to survive a voice swap (below).+- **Continuous narration**: 0.45 s breaths. A longer gap only where the picture carries on alone (a scroll with the+ music). Never space lines out to fill a length. The film's length follows the VO.+- **Beats sit on words**: `T.PICK: 15.3, // "select"`. Every beat names the word it lands on, so a new VO means+ re-reading `words.json`, not re-deciding the film.+- **Measure before promising a length.** "Cutting 8–10 words will do" was wrong once. TTS pauses at punctuation don't+ shrink with speed.+- **Music under a voice**: duck it under the VO envelope (fast attack, ~350 ms release), ~11 dB under the voice RMS.+ Cut the track on its beat grid so its drop lands on the film's big moment. A narrated film is never quiet, so+ verify's audio leg fails. That is structural: don't tune for it.++## 5 · Languages: one composition, many cuts++- **One file, `?lang=xx`.** No parameter means the source language, and it must stay **pixel-identical**. Freeze+ the accepted comp, then check it with `scripts/frame_diff.py frozen/comp.html comp.html --times …`. Byte-compare the+ source language's mix and events too. Render with the query in the path: `render.py "comp.html?lang=ja"`. Copying+ the comp per language means every later motion fix is made twice.+- **Write, don't translate.** Rewrite each VO line for the new language: the natural order and length of that+ language, about the same seconds. Any line that names a UI label must use the **localised** label the replica+ shows.+- **Text through one helper** (`UIK.tr(lang)` or `J(en, xx)`). Display names for products, channels and statuses+ map at draw time, and the data keeps its keys.+- **Localise the mess too.** If "messy data" is part of the story, make it messy the way that locale is messy.+ Japanese: half-width vs full-width katakana and digits, 9月15日 vs 2026/9/16. Values stay the same.+- **Currency follows the client's rule.** Switching the symbol without converting the numbers is a legitimate brief+ (¥12 where the source said £12); converting is a different claim. Ask if unstated.+- **Fonts**: a CJK face is local and loaded only for that language: `UIK.loadFont('Noto Sans JP',+ 'brand/fonts/…ttf', {need: lang === 'ja'})`, awaited in `__ready`. Put it second in the stack (`Inter, 'Noto Sans+ JP'`), so Latin keeps the house face.+- **Japanese TTS**: Kokoro's espeak path can't read kanji. Write a kana reading per line (`read.txt`, brand names as+ said: エクセル, エイチティーエムエル) and phonemise it with misaki[ja] (`--read`). Subtitles still use `lines.txt`.++### Timing another language: warp the clock, not the beats++The beats, camera keys, hand path and events are authored once, on the source VO. Another language gets+`const {U, Ui} = UIK.timeWarp(KNOTS)`: knots `[filmT, authorT]` placed on **words that mean the same thing**, not+just line starts. Word order moves: the Japanese says "Pro mode, switch", so the dropdown opens on 「プロ」 and Pro+is chosen on 「切り替え」.++- `seek(tf)` draws at `t = U(tf)`: the camera (`camAt(U(tf))`), scroll, every `T`. Subtitles use film time+ `tf`. `__meta.dur = Ui(authorDur)`. `__events()` maps each `t`+ through `Ui`, so sound lands in film time. `__motion(t0, t1)` samples `camAt(U(t))`.+- **Check `slopes`**: authoring s per film s. Keep it between ~0.5 and ~1.4. Below that a move plays in visible slow+ motion, above it the move rushes. Where one language talks longer before the payoff, let the payoff start earlier+ in the sentence rather than slowing a burst to a crawl.+- **A voice swap is a knot rewrite.** Take the new `words.json` and move each knot to the same word. Drop a knot when+ two anchors fall closer than the move between them needs; the new voice may not pause where the old one did.+- **Loudness per language.** A peak-normalised mix of a denser voice came out 5 LU louder than the source cut. Match+ each language's integrated loudness to the source mix's (ffmpeg `ebur128`) as the last step.+- **Per-language end clips.** Brand kits often ship one per market; extract the right one at the film's fps.++## 6 · Ending on the brand's own clip++Extract the official end clip to frames at the film's fps. From its first frame on, the composition draws those frames+full-screen. Before that, land the film's subject on the **exact screen spot** of the logo in frame 1 (`OM.unproject`+from that point), then cross over to a crop of that logo while the ground fades to the clip's background. The cut+into the clip is then invisible.++## 7 · Things that bit++- **A preview that cuts away and back is two cuts.** Showing the result early then returning made the base shot+ reappear, and each reappearance read as a cut. A lens or window *over* the base shot shows the future without+ leaving it.+- **Camera shake at 30 fps with a 180° shutter becomes double images.** Every letter in that frame ghosted. Narrated+ UI films want no shake.+- **`__motion` must track everything that moves**, including copies and scroll. Undercounting left fast tiles+ stepping in bands.+- **79 concurrent `img.decode()` calls reject in Chrome.** Wait on `onload` instead.+- **A `//` comment pasted mid-line swallows the rest of that line.** It ate a string (on screen as `undefined`) and+ two camera keys.+- **Whisper mishears brand names** (a made-up name comes back as a real word, or as an unrelated kanji). Use its times, the script's words.++## 8 · What is *not* in this method — decide it fresh every film++The replica, the narration pipeline and the warp are tools. They say nothing about how the film looks, so don't carry+the last demo's look into the next one:++- **the concept**, per §2 of SKILL.md: what the film is made of. "The data records are tiles that become the+ charts" was one film's idea. Others: the UI itself as the only material, a single object passed through the+ product, a before/after split, a scale dive into one control…;+- **the palette**: light or dark, one accent or tonal planes, how issues are coloured. Show 2–3 stills and pick;+- **the stage**: a window on an infinite plane, the UI full-frame, a device, several windows side by side;+- **the camera grammar**: an operator chasing the hand, locked close-ups with cuts, one continuous take;+- **the transitions**: an iris, a card that becomes the next scene, a lens over the base shot, a scroll;+- **type and captions**: the caption style, whether there are kinetic words at all.++Name these choices in the concept round and make them differ from the previous film's.diff --git a/references/reference-deconstruction.md b/references/reference-deconstruction.mdnew file mode 100644index 0000000..23d66b4--- /dev/null+++ b/references/reference-deconstruction.md@@ -0,0 +1,103 @@+# Reading a reference in numbers++You are not copying the reference. You are measuring the *rhythm* it has so yours is not uniform.++## Run++```bash+python3 scripts/analyze_ref.py ref.mp4 --out ana/+```++Produces `ana/energy.txt` (the map below), `ana/summary.json` (the flow fingerprint under `"flow"`),+`ana/sheet_NN.png` (4 fps contact sheets, 24 frames each), and 9 full frames spread across the clip.+The fingerprint needs `opencv-python`; `--no-flow` skips it.++## The energy map++One character per 1/12 s, rows of 4 s; ` .:-=+*#%@` from still to hard cut. The Shipper reference+(Daniel Ch, 26.6 s):++```+ 0.0s | . . . |+ 4.0s | . ..........:::... .....|+ 8.0s |...::::::::::::::::::::::::.... .::=*++=+|+ 12.0s |*@% ........:-::.. .|+ 16.0s |. @...:.:.::-:-:|+ 20.0s |-:=:=:-:-@ @ |+still (<0.5): 0.34 low (<2): 0.57 cuts: 11.6 12.0 12.1 12.2 18.8 20.8 23.4+```++What to read off it:++- **Stillness ratio.** 0.34 dead-still, 0.57 barely moving. The film breathes. The first motion-web+ cut measured 0.02 still — it never stopped moving, and that is exactly what felt like slides.+- **Where the bursts are.** Two: a 0.6 s flurry at 11.6–12.2 (UI cards flying with blur) and the word+ hits at 18.8–20.8. Everything else is small motion inside otherwise still frames.+- **The long quiet.** 15–18.8 s is one slow zoom on a monitor. 3.8 s of almost nothing, right before+ the hits. That contrast is the whole trick.+- **Cut count.** 7 in 26 s. A cut every second is not this genre.++## The motion line — how things move++The energy map says *when*. The `motion:` line says *how*, from optical flow at 30 fps, 320 px wide:++```+motion: peak 260 px/frame @30 · 15 moves · median t80 0.73 · soft curves 83 % of travel · smear 1.07 over 95 fast frames (sharp: no shutter blur)+```++(Pocket Weather v3.) Read off it:++- **t80** — the share of a move's duration spent before 80 % of its travel is done. .80 is linear, .67 a+ symmetric S-curve, .42 cubic-out, .23 an expo-out snap that arrives at once and settles for the rest. Both our+ films sit at .70–.73: everything eases in *and* out. A reference well below that moves on snaps and springs —+ pick `ease.expoOut` / `quartOut` and `OM.spring`, not `smoother` (curve table in motion-library.md).+- **smear** — whether fast frames are smeared *along* their motion. Under .78 the clip was rendered with motion+ blur (render.py's 180° shutter reads .64–.69; Pocket Weather v3 re-rendered with it .69); ~.9 and up are sharp+ copies (motion-web .88, v3 as drafted 1.07 — both strobe on their fastest moves). A smeared reference means: keep+ the shutter on, render.py's default.+- **peak** — px per frame, normalised to 1920 wide. It reads up to ~30 % low on fast, small objects; the exact+ number for a composition comes from probe.py.++It is a fingerprint of the dominant motion, not a track per element. `verify_promo.py draft.mp4 --ref ref.mp4`+prints yours next to the reference's.++## The contact sheets++Look for, and write down:++- **Element scale.** How much of the frame does the biggest thing take? (Shipper: cards ≈ 25 % width;+ only the monitor shot fills the frame.)+- **What actually moves inside a beat.** Typing, checkmarks ticking, a toggle, a cursor click — the+ product's own micro-interactions, not camera moves over static screenshots.+- **The narrative.** Shipper: problem words → logo → prompt typed → queue ticks → built site flies in →+ feature cards each with one click → product on a monitor → tagline → logo. One story.+- **Entrances/exits.** Spring pop-ins (overshoot), fly-throughs with blur and a few degrees of 3D tilt,+ hard cuts for words. No cross-fades.+- **Type.** Small, medium weight, one accent colour; a serif wordmark; uppercase bold only for the+ staccato beat.++## The beat sheet++Write it before composing. Columns: `t · beat · picture · what is still · sound`. Force the shot+lengths to vary by ≥ 4× and mark at least one rest. The one for motion-web is in+`cases/motion-web-15s/README.md`.++## Reading a style — take the rule, not the frames++A style reference is not a beat sheet. The part-kit study (Pinckus / Flatwhite Motion's Buildathon piece, 2026-09) was+stopped at draft 1: a new topic on the reference's beats was 「完全抄袭复刻没意义」. What transfers:++1. **The one rule every object obeys.** There: every word sits on a machined part — pills with two rivets, plates with+ four screws, hex nuts, brackets with holes, pipes in pairs, a cursor with a hole in its tail. Palette, grid and type+ follow from it. Copied parts without the rule read as clip-art; the rule applied to your own subject reads as the style.+2. **The tool behind the look.** Made in Cavalry, where path-offset bands, duplicator echoes and per-glyph typing are+ cheap — so the film is full of them. Knowing that separates the signature from what was merely easy there. In `f(t)`+ each is a few lines (motion-library.md → *Candidates*, PK rows).+3. **Numbers, not impressions.** Palette hex from full frames, grid pitch from one pixel row, type size from cap height+ at 1080p, rivet and screw radii as a share of the part. They go at the top of the comp.+4. **Its objects, our carries.** The reference hard-cuts between beats. The study carried every boundary with the+ style's own parts — the track's edges stretch into rails, the pill becomes the reel's window and then a plate, the+ rails thicken into pipes, the camera goes down a bolt hole. A reference's cuts are not part of its style.+5. **Its language, our meaning.** Make the rule say something about the new subject, and let the beats come from+ that through §2's three concepts — not from the reference's order of scenes.+diff --git a/references/rhythm.md b/references/rhythm.mdnew file mode 100644index 0000000..9e7db1b--- /dev/null+++ b/references/rhythm.md@@ -0,0 +1,135 @@+# Rhythm and carry — what the first two films taught++Two films, six cuts, one verdict for two different reasons: 「PPT」. motion-web failed on rhythm. Pocket+Weather had the rhythm and failed on carry.++# Rhythm — the three cuts of motion-web++The same nine pages, the same 15 seconds, three completely different results. Cut three shipped.++## Cut 1 — the card field (rejected: 「PPT 式一个一个展示」)++Nine pages as cards on a 2.5-D field, camera dollying past each for 0.74 s, depth blur, labels.+Measured: 0.02 still frames, camera never stopped, every card the same dwell.++Why it failed: **uniform cadence** and **thumbnails**. A page's motion does not survive being 700 px+wide and blurred for 0.7 s. The camera move made it *feel* like a gallery walk — which is a slideshow+with a dolly.++## Cut 2 — full-frame footage, hard cuts (rejected: 「也没有节奏变化 依然是 ppt」)++Seven pages full-frame, 1.55 s each, hand drawn back in, label pill, push-in per shot, spring settle+on cuts. Better legibility, still rejected.++Why it failed: **still a metronome**. Seven equal shots with the same shape (cut, push-in, label) is+seven slides even when each slide moves. No rests, no bursts, no story — a catalogue.++## Cut 3 — the reference's structure (accepted)++| t | beat | length | motion |+|---|---|---|---|+| 0–1.6 | three words | 0.4 s per word | pops only |+| 1.6–3.0 | wordmark letters drop and squash, tag wobbles | 1.4 s | small |+| 3.0–4.8 | prompt card types, hand clicks send | 1.8 s | typing |+| 4.8–7.0 | build panel ticks 7 lines | 2.2 s | ticks |+| 7.0–9.6 | three pages fly through tilted, blurred in/out | 0.9 s each | **burst** |+| 9.5–12.1 | four micro cards, live sims, hand pokes each | ~0.85 s, overlapping | short |+| 12.1–13.25 | browser window, slow push-in | 1.15 s | **rest** |+| 13.25–14.3 | MOTION · IS · THE · MATERIAL | 0.25 s each | **hits** |+| 14.3–15 | black, wordmark | 0.7 s | still |++Measured: 0.54 still frames, one burst, one rest, hits at the end. Shot lengths from 0.22 s to 2.2 s.++Why it worked: it **tells what the thing does** (the checklist is the skill's real workflow; the+micro cards are its mechanisms running live; the fly-throughs are its outputs) instead of showing+outputs one after another; and the **energy curve has shape**.++## The rules that fall out++- Shot lengths: coefficient of variation ≥ 0.25 or it is a metronome. `verify_promo.py --shots` checks.+- At least 25 % of frames dead-still; at least one ≥ 1 s stretch under the low threshold.+- If the reference hits, at least one burst (≥ 3 big changes inside 1.5 s), not at a uniform interval. A concept+ without hits — one element transforming, one continuous camera move — has none, and that is not a flaw.+- Show mechanisms as **components in cards** when the page's motion is too small to read at card size.+- Show pages **full-frame** only for a hold, with the hand visible.+- Never end a shot the same way twice in a row (spring-out, blur-out, hard cut — alternate).+- Kill any flourish that is not the product's own behaviour (confetti, specks, sparkles).++# Carry — the three cuts of Pocket Weather Club++Made in Codex with this skill, after motion-web. It had learned+the rhythm lesson: v1 passed every rhythm leg. It was still rejected as PPT.++## v1 — rhythm passed, rejected: 「像 PPT」++Key visual, character showcase, full-page recording, brand end card, 4K60. Cadence, rest, burst, not-flat and+audio all passed. The code shows what those legs cannot see: every beat is its own scene, and showing one sets+`display:none` on the rest. probe.py afterwards: **two boundaries, both bare — carry score 0.00.**++## v2 — the first 6 s accepted, the rest sent back++Re-cut as a 1080p30 draft. Sunny lands on the headline and knocks its letters apart, hops to its slot, the cards+spring up around it, the hand picks it, the page grows out of the card. Then three recorded pages one after+another and a pocket lockup. The user kept the first 6 s and sent back the rest. probe.py: **carry score 0.40** —+carried at 2.97 s (Sunny) and 11.60 (the lockup); bare at 6.03 (the page growing out of the card, a seam v3 kept),+8.13 and 9.83 — page replaced by page, in the rejected half.++## v3 — carried throughout, accepted++The first 6 s kept; the rest rebuilt so every beat grows out of the one before: a push into Sunny on the page, a+circular stage opening from Sunny until it is the frame, the hand dragging an elastic rail of moods while the words+lag, the cast gathering on arcs and folding into a turning seal as the name rises from its masks. probe.py:+**carry score 0.75** — carried at 2.97 (Sunny), 8.27 and 9.17 (the hand), 11.30 (the cast); anchored at 7.27+(Sunny, unmoved while the stage opens); bare at 6.03. It failed `not-flat` (0.33), the leg v1 had passed.++## The numbers++| film | verdict | carry score | carried · anchored · bare | rhythm legs |+|---|---|---|---|---|+| motion-web cut 3 | accepted | 0.56 | 5 · 0 · 4 | all pass |+| Pocket Weather v1 | rejected | **0.00** | 0 · 0 · 2 | all pass |+| Pocket Weather v2 | first 6 s accepted | **0.40** | 2 · 0 · 3 | all pass |+| Pocket Weather v3 | accepted | 0.75 | 4 · 1 · 1 | not-flat fails (0.33) |++Continuity separates the verdicts; no rhythm leg does. So verify fails a carry score under 0.5 and warns under+0.7. motion-web passes at 0.56 with four bare boundaries — the setup words giving way to the wordmark (1.6 s), the+checklist to the first fly-through (7.1), one fly-through to the next (8.0), the micro cards to the hold (12.3) —+and would be a better film carried.++Curves separated nothing: 57–72 % of all travel was on soft curves (t80 ≥ .55) in all four films, median t80+.64–.71. All four were rendered without motion blur, and three have moves far over 80 px/frame at 30 fps+(v2 664, motion-web 385, v3 354).++## How the probe decides, and where it is blind++A boundary is a 0.4 s window in which most of the on-screen area changes identity; fades through the ground are+bridged. **Carried**: something survives and moves ≥ 2 % of the frame diagonal or scales ≥ 10 %. **Anchored**:+the only survivor is large (≥ 3 % of the frame) and unchanged. **Bare**: nothing survives. Exempt: inside a burst+of hard cuts (≥ 3 within 1.5 s), the last 1.2 s, and times listed in `__meta.cuts`. Score = (carried ++anchored / 2) / boundaries considered.++It tracks identity, so a carry built from two elements is invisible to it. At Pocket Weather 6.03 s the page is a+*new* image fading in at the card's size while the card fades out: a viewer sees the card become the page, the+probe sees a replacement — and the user accepted that seam twice. Build a carry as one element changing+(`morphRect`, one layer scaled by `zoomThrough`), or list the time in `__meta.cuts` with the reason in the beat sheet.++Two more blind spots, from the camera films:++- **One continuous world has few or no boundaries.** knockon, a top-down machine under a moving camera, scored+ continuity 1.00 over 0 boundaries; clearing did it over 3 and unbroken's split over 1. There the carry was judged by+ eye. A PASS over fewer boundaries than the beat sheet has is not evidence.+- **rest reads energy at 320 px.** It over-reads small detail on a dark ground: a dot on black (one-dot v1, still+ 0.844) or bone-white brush strokes (unbroken, 0.628). It also counts any camera push as motion: clearing's first+ render failed at 0.178 because every hold had a slow push. Make the rests truly still; then the leg is honest.++## The rules that fall out++- Write the carry into the beat sheet: for each boundary, the element that survives it and what it does.+- The carries that worked: the thing pressed becomes the result, a stage opens from the subject, the hand drags the+ next option in, the cast folds into the lockup (motion-library.md → *carry*). A fade or a slide between unrelated+ scenes is not a carry.+- The hand is the cheapest carrier: keep it on screen across a boundary it caused.+- Page after page is a slideshow even when each page moves (v2 at 8.13 and 9.83, motion-web at 8.0).+- Bare cuts only in a burst of hits or into the end card.+- Run probe.py on the first playable storyboard. Its `bare` lines are the beats that will read as slides.+- Rests are dead still: no `drift`, no settling camera. A push in a hold is motion to verify.diff --git a/references/sound.md b/references/sound.mdnew file mode 100644index 0000000..400acba--- /dev/null+++ b/references/sound.md@@ -0,0 +1,85 @@+# Sound — a palette in a room++The first pass gave every visual event its own synthesised tone: sine pops for words, noise ticks for+letters, a "boing" for jelly. Rejected within a minute as 低劣. What was wrong is instructive:++- **raw sines** read as a chiptune; real objects have partials and a noise transient;+- **no space** — nothing shared a room, so the sounds sat on top of the picture instead of in it;+- **one sound per event** — 40 typing ticks plus 10 letter ticks plus 26 confetti pops is a+ slot machine;+- **flat dynamics** — everything at the same level, no rests.++## The palette (`scripts/sfx_palette.py`)++| material | how it is made | used for |+|---|---|---|+| `air(dur, f0, f1, q, shape)` | noise → resonant band-pass whose centre glides f0→f1, low-passed at 5.5 k, sine-shaped envelope | whooshes: cards in/out, screens flying (pan it with the picture) |+| `glass(f, dur, bright)` | fundamental + inharmonic partials (2.76 f, 5.4 f) with faster decays + a 2 k noise transient | ticks up a scale, PASS chord, word touches |+| `wood(f, dur)` | low body knock with a pitch drop + a 3.2 k filtered snap | keys (one in three, random velocity), mouse down/up as two hits 60 ms apart |+| `sub(f, dur)` | sine with a pitch drop, tanh-saturated, felt transient | hard-cut hits, landings; the deep one under black |+| `bubble(f, dur)` | a resonance rising as it "closes" + tiny noise | rounded pop when a card lands |+| `wobble(f, dur)` | FM'd tone, 8.5 Hz vibrato decaying | the one jelly flick |++`pan_of(x)` maps a screen x to ±0.6; `place(sig, t, gain, pan, send, pan_to)` puts a sound at a time+with an optional pan sweep, and sends a share to the room.++## The room++One synthetic impulse response for everything: 1.1 s T60, 12 ms pre-delay, three early reflections,+low-passed decorrelated stereo. Sent at 15–70 % depending on how far the object is (a key: 0.15; a+long air breath: 0.6). The room is what makes disparate sounds one film.++## Levels++- Palette: soft ceiling `tanh(1.3·x)` then normalise to **−8 dBFS peak**: loud enough alone, room for music.+- Mastered score.py (every accepted film since one-dot): **−16 LUFS integrated**, true-peak ceiling −3.5 dBTP, dropped+ to −4 when the AAC render reads above verify's −3 dBFS (overlap v4: −2.7 at −3.5, −3.8 at −4.0).+- Dynamics follow the picture's energy map: the quiet hold is *silent* after its one breath; the+ hits are the loudest thing in the film.+- Check with `verify_promo.py`: it reports peak, clipping, and the fraction of quiet frames.++## Scoring++`templates/sfx_score.example.py` is the motion-web score: import the palette, `place()` each event+at the composition's own constants (copy them; do not retype numbers), `write()`. Fewer events than+beats. If two sounds would land within 40 ms, keep one.++**Score from the comp, not from retyped times** (knockon, clearing, unbroken). The comp exports what the sound needs:++- `window.__events()` → `{T, events: [{t, kind, pan, v}]}`: every contact, its screen x through the camera at that+ instant as a pan from −1 to 1, and a strength;+- a continuous curve wherever a sound must follow the picture: the marble's speed (`__marbleSpeed`), the zoom's+ d log zoom / dt (`__zoomVel`), each brush's speed × pressure (`__brush` → `[left, right]`).++`dump_events.py` (Playwright) writes `events.json` and the curve at 240 Hz; `score.py` reads both, so a retimed beat+takes its sound with it. The recorded-palette `score.py` from one-dot splits into sources, shaping, synthesis, buses and+master, which each new film copies unchanged, plus the score itself (~60 lines).++Curves that became instruments:++- **the camera's air** (clearing): noise in three bands (150–600 Hz, 0.6–2.4 kHz, 2.4–9 kHz) crossfaded by depth+ `log(zoom) / log(300)`, so closer is brighter, and scaled by `|d log zoom / dt| ^ 1.3`;+- **hair on paper** (unbroken): a 1.8–7.5 kHz rasp over a 350–1,100 Hz body, each scaled by the brush's energy, with+ ~30 Hz fibre flutter; one per side of the split.++**Find mud per window.** knockon's first mix put 41.6 % of its energy in 100–300 Hz, and thinning the obvious suspect+(the rumble) changed nothing. Band shares per 0.5 s window found the cause: 95 % low-mid at 4.5 s, from a marimba run+starting on F3 whose 1.8 s tails piled up. An octave up with 0.7 s notes brought that window to 6 % and the mix to 32 %.+Keep pitched runs at F4 and above, and cut their tails.++**Judge the arc by K-weighted loudness per beat**, not by RMS. The landing has to read louder than the move into it:+clearing's second dive and its landing both measured −14 LUFS until the dive came down 4 dB.++**Current launch-film sound direction** (user correction, 2026-09-24). The Adventure and Getaway cuts were rejected:+the music was intrusive and the action sounds effectively inaudible. The earlier indie-dance / funk / future-house+recommendation is superseded for this film. The user wants the feel of Apple motion/product films; an exact reference+has not yet been supplied, so do not treat a genre label or a loudness target as proof of matching that taste.+Build the action score first: tactile contacts, paper/ink/brush detail, camera air driven by motion, and deliberate+rests. Use restrained music that leaves these sounds audible; avoid a full-density track playing continuously over+everything. Compare music and SFX in their actual event windows and shared frequency bands, then audition the mix.+In the rejected v3, SFX were 26.8–35.0 dB below music by event-window RMS and 17–23 dB below it at 800–4500 Hz;+normalising the whole mix to −19 LUFS did not repair that balance. Do not reuse whole case mixes and their repeated+end chords when combining films: reuse the independent sources, timing curves and material identities instead.++**Retired ending: the vibraphone chord + crotale shimmer.** three earlier films all resolved on it; the user+heard it as the stock ending 「好多视频都是这个音效」. End on the music's own cadence, or a hit that belongs to the film.diff --git a/scripts/analyze_ref.py b/scripts/analyze_ref.pynew file mode 100644index 0000000..0d85e77--- /dev/null+++ b/scripts/analyze_ref.py@@ -0,0 +1,153 @@+#!/usr/bin/env python3+"""analyze_ref.py — read a reference clip in numbers before composing anything.++ python3 scripts/analyze_ref.py ref.mp4 --out ana/+ python3 scripts/analyze_ref.py ref.mp4 --out ana/ --no-flow # rhythm only++Writes into --out:+ energy.txt one char per 1/12 s (' .:-=+*#%@'), rows of 4 s — where the film rests and where it hits+ summary.json duration, stillness ratios, cut times, burst windows, longest quiet stretch, and "flow"+ sheet_NN.png contact sheets at 4 fps, 24 frames each (6×4)+ frame_NN.png 9 full frames spread across the clip++The energy map says WHEN things move. "flow" (optical flow at 30 fps — or the source's own rate if slower, so a+24 fps clip is not padded with repeated frames — 320 px wide) says HOW: the dominant speed per frame (median flow+over moving edges, px per 1/30 s normalised to 1920 wide), the moves cut from it with their t80+(share of the move's duration before 80 % of its travel is done — .23 is an expo snap, .67 a symmetric S-curve),+and whether fast frames are smeared along their motion. Smear = gradient energy along the motion / across it, on+the pixels that changed: < .78 is shutter blur (render.py's 180° shutter: a linear test move .64, Pocket Weather v3+.69); sharp renders read ~.9 or more (the test move unblurred .99, v3 as drafted 1.07, motion-web .88 — its CSS+blur() on fly-throughs is not motion blur). It is a fingerprint of the dominant motion, not a per-element track:+speed reads up to ~30 % low on fast small objects (a 100 px box at 167 px/frame reads 121–155). probe.py measures+a composition exactly.++Then write the beat sheet (references/reference-deconstruction.md). Also works on your own render:+`verify_promo.py` prints the same map next to the reference's.+"""+import argparse, glob, json, math, os, shutil, subprocess+import numpy as np+from PIL import Image++CHARS = " .:-=+*#%@"+SMEAR_BLUR = 0.78 # fast frames smeared below this were rendered with motion blur++def energy(video, workdir, fps=12, width=320):+ d = os.path.join(workdir, "_e"); shutil.rmtree(d, ignore_errors=True); os.makedirs(d)+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", video, "-vf", f"fps={fps},scale={width}:-1", f"{d}/f_%05d.png"], check=True)+ prev = None; diffs = []+ for f in sorted(glob.glob(f"{d}/f_*.png")):+ a = np.asarray(Image.open(f).convert("L"), dtype=np.float32)+ diffs.append(0.0 if prev is None else float(np.abs(a - prev).mean())); prev = a+ shutil.rmtree(d, ignore_errors=True)+ return np.array(diffs), fps++def energy_map(d, fps, row_s=4):+ per = fps * row_s; lines = []+ for r in range(0, len(d), per):+ lines.append(f"{r/fps:5.1f}s |" + "".join(CHARS[min(9, int(v / 3))] for v in d[r:r + per]) + "|")+ return "\n".join(lines)++def stats(d, fps, cut_thr=18.0, still_thr=0.5, low_thr=2.0):+ cuts = [round(i / fps, 2) for i in range(1, len(d)) if d[i] > cut_thr]+ # bursts: windows of 1.5 s holding >= 3 big changes (> 8)+ big = [i for i in range(len(d)) if d[i] > 8]; bursts = []+ for i in big:+ win = [j for j in big if i <= j < i + int(1.5 * fps)]+ if len(win) >= 3 and (not bursts or i / fps > bursts[-1][1]): bursts.append((round(i / fps, 2), round(win[-1] / fps, 2)))+ # longest quiet stretch (below low_thr)+ best = cur = 0+ for v in d:+ cur = cur + 1 if v < low_thr else 0; best = max(best, cur)+ return {"duration_s": round(len(d) / fps, 2), "still_ratio": round(float((d < still_thr).mean()), 3),+ "low_ratio": round(float((d < low_thr).mean()), 3), "cuts": cuts, "bursts": bursts,+ "longest_quiet_s": round(best / fps, 2), "mean_energy": round(float(d.mean()), 3)}++def flow(video, fps=30, width=320, fast=24.0, vmin=2.0):+ try:+ import cv2+ except ImportError:+ return None+ wh = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,avg_frame_rate", "-of", "csv=p=0", video], capture_output=True, text=True).stdout.strip().split(",")+ h = int(round(int(wh[1]) * width / int(wh[0]) / 2) * 2)+ num, _, den = wh[2].partition("/")+ src = float(num) / float(den or 1) if float(den or 1) else 0.0+ # Resampling a slower source up to `fps` repeats frames (24 → 30 repeats every 4th): each repeat reads as a+ # zero-flow frame and splits every move in pieces. Sample slower sources at their own rate and rescale speeds+ # to px per 1/fps s, so peak, thresholds and the comparison with a render stay in one unit.+ sfps = src if 0 < src < fps else fps+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", video, "-vf", f"fps={sfps},scale={width}:{h}", "-f", "rawvideo", "-pix_fmt", "gray", "-"], capture_output=True, check=True).stdout+ frames = np.frombuffer(raw, np.uint8).reshape(-1, h, width)+ dis = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)+ norm = 1920.0 / width * sfps / fps+ speed = np.zeros(len(frames)); smear = []+ for i in range(1, len(frames)):+ a, b = frames[i - 1], frames[i]+ f = dis.calc(a, b, None)+ mag = np.hypot(f[..., 0], f[..., 1]); moving = mag > 0.5+ if moving.mean() < 0.002:+ continue+ g = b.astype(np.float32)+ gx = cv2.Sobel(g, cv2.CV_32F, 1, 0, ksize=3); gy = cv2.Sobel(g, cv2.CV_32F, 0, 1, ksize=3)+ edges = moving & (np.hypot(gx, gy) > 20) # flow is trustworthy where there is an edge to follow+ speed[i] = float(np.median(mag[edges] if edges.sum() > 20 else mag[moving])) * norm+ if speed[i] >= fast: # fast frame: is the changed content smeared along its motion?+ dx, dy = float(np.median(f[..., 0][moving])), float(np.median(f[..., 1][moving])); n = math.hypot(dx, dy)+ changed = moving & (np.abs(b.astype(np.int16) - a.astype(np.int16)) > 12)+ if n > 0.3 and changed.sum() > 20:+ ux, uy = dx / n, dy / n+ e_par = float(((gx * ux + gy * uy)[changed] ** 2).mean()); e_per = float(((-gx * uy + gy * ux)[changed] ** 2).mean())+ if e_per > 1.0:+ smear.append(e_par / e_per)+ moves, k = [], 1+ while k < len(speed):+ if speed[k] < vmin:+ k += 1; continue+ a = k+ while k < len(speed) and speed[k] >= vmin:+ k += 1+ path = speed[a:k]; L = float(path.sum()) * fps / sfps # px travelled: speeds are per 1/fps s, frames 1/sfps s apart+ if k - a >= 3 and L >= 40:+ k80 = int(np.searchsorted(np.cumsum(path), 0.8 * path.sum())) + 1+ moves.append({"t0": round(a / sfps, 2), "t1": round(k / sfps, 2), "path": round(L), "t80": round(k80 / (k - a), 2), "peak": round(float(path.max()))})+ total = sum(m["path"] for m in moves)+ med = None+ if moves:+ acc = 0.0+ for m in sorted(moves, key=lambda m: m["t80"]):+ acc += m["path"]+ if acc >= total / 2:+ med = m["t80"]; break+ return {"fps": fps, "sampled_fps": round(sfps, 3), "peak": round(float(speed.max())), "moves": moves, "t80_median": med,+ "soft_share": round(sum(m["path"] for m in moves if m["t80"] >= 0.55) / total, 2) if total else 0.0,+ "fast_frames": len(smear), "smear_median": round(float(np.median(smear)), 2) if smear else None}++def sheets(video, out, fps=4):+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", video, "-vf", f"fps={fps},scale=426:-1,tile=6x4", f"{out}/sheet_%02d.png"], check=True)+ dur = float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", video], capture_output=True, text=True).stdout.strip())+ for i in range(9):+ t = dur * (i + 0.5) / 9+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", f"{t:.2f}", "-i", video, "-frames:v", "1", f"{out}/frame_{i:02d}.png"], check=True)+ return dur++def main():+ ap = argparse.ArgumentParser(); ap.add_argument("video"); ap.add_argument("--out", default="ana"); ap.add_argument("--no-flow", action="store_true"); a = ap.parse_args()+ os.makedirs(a.out, exist_ok=True)+ d, fps = energy(a.video, a.out); m = energy_map(d, fps); s = stats(d, fps)+ fl = None if a.no_flow else flow(a.video)+ if fl: s["flow"] = fl+ open(os.path.join(a.out, "energy.txt"), "w").write(m + "\n" + json.dumps({k: v for k, v in s.items() if k != "flow"}) + "\n")+ json.dump(s, open(os.path.join(a.out, "summary.json"), "w"), indent=1)+ sheets(a.video, a.out)+ print(m); print()+ print(f"still (<0.5): {s['still_ratio']} low (<2): {s['low_ratio']} longest quiet: {s['longest_quiet_s']} s")+ print(f"cuts at: {s['cuts']}"); print(f"bursts: {s['bursts']}")+ if fl:+ blur = "no fast frames" if fl["smear_median"] is None else f"smear {fl['smear_median']} over {fl['fast_frames']} fast frames ({'smeared along the motion: shutter blur' if fl['smear_median'] < SMEAR_BLUR else 'sharp: no shutter blur'})"+ med = "—" if fl["t80_median"] is None else fl["t80_median"]+ print(f"motion: peak {fl['peak']} px/frame @{fl['fps']} · {len(fl['moves'])} moves · median t80 {med} · soft curves {fl['soft_share'] * 100:.0f} % of travel · {blur}")+ elif not a.no_flow:+ print("motion: skipped (opencv-python not installed)")+ print(f"\nsheets + frames in {a.out}/ — look at them before writing the beat sheet")++if __name__ == "__main__":+ main()diff --git a/scripts/frame_diff.py b/scripts/frame_diff.pynew file mode 100644index 0000000..c55de35--- /dev/null+++ b/scripts/frame_diff.py@@ -0,0 +1,44 @@+#!/usr/bin/env python3+"""frame_diff.py — do two compositions draw the same frames? For a change that must leave one version untouched+(a new language behind ?lang=, a refactor): freeze a copy of the accepted comp, then compare it with the working one.++ python3 scripts/frame_diff.py frozen/comp.html "comp.html" --times 0.3,9.5,15.1,25.6,36.4 [--out diff/]++A frozen copy needs its neighbours (motion.js, data, images) beside it: symlink them into its folder. Paths may carry a+query (comp.html?lang=ja). Prints the max channel difference and the changed-pixel count per time; exits 1 on any+difference. --out writes both frames and an amplified difference image for the times that differ.+"""+import argparse, asyncio, io, os, sys+import numpy as np+from PIL import Image+from playwright.async_api import async_playwright+++async def frames(url, ts, w, h):+ async with async_playwright() as p:+ b = await p.chromium.launch(); pg = await b.new_page(viewport={"width": w, "height": h})+ errs = []; pg.on("pageerror", lambda e: errs.append(str(e)))+ await pg.goto(url); await pg.evaluate("window.__ready"); out = []+ for t in ts:+ await pg.evaluate(f"window.__seek({t})"); out.append(np.asarray(Image.open(io.BytesIO(await pg.screenshot())).convert("RGB")))+ await b.close()+ if errs:+ print(url, "page errors:", errs[:3])+ return out+++def url(p):+ path, _, q = p.partition("?"); return "file://" + os.path.abspath(path) + ("?" + q if q else "")+++ap = argparse.ArgumentParser(); ap.add_argument("a"); ap.add_argument("b"); ap.add_argument("--times", required=True)+ap.add_argument("--width", type=int, default=1920); ap.add_argument("--height", type=int, default=1080); ap.add_argument("--out")+a = ap.parse_args(); ts = [float(x) for x in a.times.split(",")]+A = asyncio.run(frames(url(a.a), ts, a.width, a.height)); B = asyncio.run(frames(url(a.b), ts, a.width, a.height)); bad = 0+for t, x, y in zip(ts, A, B):+ d = np.abs(x.astype(int) - y.astype(int)); n = int((d.sum(2) > 0).sum()); bad += n > 0+ print(f"t={t:7.2f} max {d.max():3d} changed px {n}")+ if n and a.out:+ os.makedirs(a.out, exist_ok=True); Image.fromarray(x).save(f"{a.out}/{t:07.2f}_a.png"); Image.fromarray(y).save(f"{a.out}/{t:07.2f}_b.png")+ Image.fromarray(np.clip(d * 8, 0, 255).astype(np.uint8)).save(f"{a.out}/{t:07.2f}_diff.png")+print("identical" if not bad else f"{bad} of {len(ts)} times differ"); sys.exit(1 if bad else 0)diff --git a/scripts/gallery.py b/scripts/gallery.pynew file mode 100644index 0000000..62fa4f0--- /dev/null+++ b/scripts/gallery.py@@ -0,0 +1,72 @@+#!/usr/bin/env python3+"""gallery.py — render the motion library's sheets: frames of each move above its speed graph.++ python3 scripts/gallery.py # every demo in gallery/gallery.html → gallery/sheets/<name>.png+ python3 scripts/gallery.py --only ribbon,iris # some++A sheet is six frames of the demo (3×2) over the speed of every tracked element in px/frame at 60 fps, with each+move's t80 — the same numbers probe.py reports for a whole film. Look at the frames to pick a move; read the graph+for its curve: a tall spike at the start of a move is a snap (low t80), a symmetric hill is a soft S-curve.+The live demo is gallery/gallery.html?demo=<name>&play.+"""+import argparse, asyncio, io, os, sys+from PIL import Image, ImageDraw+from playwright.async_api import async_playwright+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import probe++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+PAGE = os.path.join(ROOT, "gallery", "gallery.html")+OUT = os.path.join(ROOT, "gallery", "sheets")+++async def run(only, fps):+ os.makedirs(OUT, exist_ok=True)+ async with async_playwright() as p:+ b = await p.chromium.launch(); pg = await b.new_page(viewport={"width": 1920, "height": 1080})+ errs = []; pg.on("pageerror", lambda e: errs.append(str(e)))+ await pg.goto("file://" + PAGE); await pg.evaluate("window.__ready")+ demos = await pg.evaluate("window.__demos")+ for d in demos:+ if only and d["name"] not in only:+ continue+ res = await probe.collect_page(pg, PAGE, fps=fps, query=f"?demo={d['name']}")+ res.update(W=1920, H=1080)+ cv = probe.curves(res)+ dur = d["dur"]; shots = d["shots"] or [round(dur * f, 3) for f in (0.08, 0.26, 0.42, 0.58, 0.76, 0.94)]+ tiles = []+ for t in shots:+ await pg.evaluate("t => window.__seek(t)", t)+ im = Image.open(io.BytesIO(await pg.screenshot())).convert("RGB").resize((640, 360), Image.LANCZOS)+ ImageDraw.Draw(im).text((12, 338), f"t={t:.2f}", fill=(180, 40, 40))+ tiles.append(im)+ graph = os.path.join(OUT, f"_{d['name']}.graph.png")+ if cv["tracks"] and cv["moves"]:+ probe.plot_speeds(res, cv, graph, title=f"OM.{d['name']} — speed of tracked elements (px/frame @{fps}), t80 per move", times=shots, size=(19.2, 3.0))+ gim = Image.open(graph).convert("RGB"); os.remove(graph)+ else:+ gim = Image.new("RGB", (1920, 300), (248, 248, 246))+ why = "moves in place (no tracked element travels 30 px)" if cv["tracks"] else "hard cuts: nothing travels"+ ImageDraw.Draw(gim).text((40, 140), f"OM.{d['name']} — {why}", fill=(90, 90, 90))+ sheet = Image.new("RGB", (1920, 720 + gim.height), (248, 248, 246))+ for i, im in enumerate(tiles):+ sheet.paste(im, ((i % 3) * 640, (i // 3) * 360))+ sheet.paste(gim, (0, 720))+ path = os.path.join(OUT, f"{d['name']}.png")+ sheet.quantize(colors=200, method=Image.FASTOCTREE, dither=Image.NONE).save(path, optimize=True)+ top = cv["moves"][0] if cv["moves"] else None+ print(f" {d['name']:13} {d['group']:8} {os.path.getsize(path) // 1024:4d} KB peak {cv['peak']:5.0f} px/frame"+ + (f" longest move t80 {top['t80']:.2f}" if top else ""))+ await b.close()+ print("page errors:", errs[:3] or "none")+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--only", default=""); ap.add_argument("--fps", type=int, default=60)+ a = ap.parse_args()+ asyncio.run(run([x for x in a.only.split(",") if x], a.fps))+++if __name__ == "__main__":+ main()diff --git a/scripts/probe.py b/scripts/probe.pynew file mode 100644index 0000000..5e1b3ec--- /dev/null+++ b/scripts/probe.py@@ -0,0 +1,449 @@+#!/usr/bin/env python3+"""probe.py — read a composition's motion in numbers: what is on screen, how it moves, what carries across beats.++ python3 scripts/probe.py comp.html # continuity + curves summary+ python3 scripts/probe.py comp.html --fps 30 --out probe/ # also probe/tracks.json and probe/curves.png++No annotations needed. After every __seek(t) the probe lists what is visible and where:+ DOM img / video / svg / canvas / text-bearing elements / painted boxes, by transformed rect and+ effective opacity (display, visibility, every ancestor's opacity);+ canvas every drawImage / fillText / fill / stroke, located through the context transform (the hooks are+ installed before the page's own scripts run). Full-canvas fills count as ground. Clip paths are not+ tracked: a line still hidden by its mask counts as visible.+A page that defines window.__track(t) → {id: [x, y] | {x, y, w, h, op}} is read from that instead.++Identity: a DOM element is its path (image sources with frame numbers folded, so footage stays one element);+a canvas draw is its image source / text / fill style, numbered by draw order within the frame.++continuity A boundary is a 0.4 s window in which most of the on-screen area changes identity (fades through+ the ground are bridged). It is CARRIED when something survives it and visibly moves or scales —+ the hand, the subject, a container becoming the next thing; ANCHORED when the only survivor is large+ and unchanged (a frame whose content swaps); BARE when nothing survives. Exempt: boundaries inside a+ burst of hard cuts (>= 3 cuts within 1.5 s — staccato hits), the last 1.2 s (end card), and times in+ window.__meta.cuts. score = (carried + anchored/2) / boundaries considered.+curves Each element's track is cut into moves. Per move: path, t80 (share of the move's duration spent+ before 80 % of the path is covered), peak px/frame at --fps (normalised to 1920 wide), overshoot.+ Film: the peak, and the share of all travel made on soft curves (t80 >= .55).+framing What the page says must stay in frame — window.__meta.inFrame = {id: [t0, t1] | [t0, t1, 'whole']} — read+ from its __track boxes, which a page with a camera reports on screen: the sampled times each id was+ entirely off frame, or for 'whole', not wholly inside.++verify_promo.py --comp runs this and turns the numbers into legs; gallery.py uses it for the speed graphs.+"""+import argparse, asyncio, json, math, os, sys+import numpy as np+from playwright.async_api import async_playwright++TRACKER_JS = r"""+(() => {+ if (window.__omTrack) return;+ const P = CanvasRenderingContext2D.prototype, draws = [], counts = new Map(), pb = new WeakMap();+ const fold = s => { s = String(s || ''); const q = s.indexOf('?'); if (q >= 0) s = s.slice(0, q); try { s = decodeURIComponent(s); } catch (e) {}+ return s.split('/').slice(-2).join('/').replace(/\d{2,}(?=\.[a-z0-9]+$)/i, '#'); };+ const idOf = base => { const n = counts.get(base) || 0; counts.set(base, n + 1); return n ? base + '#' + n : base; };+ const dev = (ctx, pts) => { const m = ctx.getTransform(); return pts.map(([x, y]) => [m.a * x + m.c * y + m.e, m.b * x + m.d * y + m.f]); };+ const bbox = pts => { let b = [Infinity, Infinity, -Infinity, -Infinity]; for (const [X, Y] of pts) { b = [Math.min(b[0], X), Math.min(b[1], Y), Math.max(b[2], X), Math.max(b[3], Y)]; } return b; };+ const rect = (x, y, w, h) => [[x, y], [x + w, y], [x, y + h], [x + w, y + h]];+ const push = (ctx, base, b, kind) => {+ const cv = ctx.canvas; if (!cv || !cv.isConnected || !b || !(b[2] > b[0]) || !(b[3] > b[1])) return;+ if (kind !== 'img' && b[2] - b[0] >= 0.9 * cv.width && b[3] - b[1] >= 0.9 * cv.height) return; // full-canvas fills are ground; a full-frame image is content+ draws.push({ id: idOf(base), b, alpha: ctx.globalAlpha, cv, kind });+ };+ const extend = (ctx, pts) => { const b = pb.get(ctx), n = bbox(dev(ctx, pts));+ pb.set(ctx, b ? [Math.min(b[0], n[0]), Math.min(b[1], n[1]), Math.max(b[2], n[2]), Math.max(b[3], n[3])] : n); };+ const wrap = (name, fn) => { const orig = P[name]; if (!orig) return;+ P[name] = function (...a) { try { fn(this, a); } catch (e) {} return orig.apply(this, a); }; };+ wrap('drawImage', (ctx, a) => {+ const img = a[0], iw = img.naturalWidth || img.videoWidth || img.width || 0, ih = img.naturalHeight || img.videoHeight || img.height || 0;+ let r, key = '';+ if (a.length === 3) r = rect(a[1], a[2], iw, ih); else if (a.length === 5) r = rect(a[1], a[2], a[3], a[4]);+ else { r = rect(a[5], a[6], a[7], a[8]); key = '@' + Math.round(a[1]) + ',' + Math.round(a[2]); }+ const src = img.currentSrc || img.src;+ push(ctx, (src ? 'img:' + fold(src) : (img.tagName || 'bitmap').toLowerCase()) + key, bbox(dev(ctx, r)), 'img');+ });+ const textRect = (ctx, s, x, y) => {+ const w = ctx.measureText(s).width, m = /(\d+(?:\.\d+)?)px/.exec(ctx.font), size = m ? parseFloat(m[1]) : 16, al = ctx.textAlign, bl = ctx.textBaseline;+ const xl = al === 'center' ? x - w / 2 : (al === 'right' || al === 'end') ? x - w : x;+ const yt = bl === 'middle' ? y - size / 2 : (bl === 'top' || bl === 'hanging') ? y : (bl === 'bottom' || bl === 'ideographic') ? y - size : y - size * 0.8;+ return rect(xl, yt, w, size);+ };+ for (const name of ['fillText', 'strokeText']) wrap(name, (ctx, a) => push(ctx, 'text:' + String(a[0]).slice(0, 40), bbox(dev(ctx, textRect(ctx, String(a[0]), a[1], a[2]))), 'text'));+ wrap('beginPath', ctx => pb.delete(ctx));+ wrap('moveTo', (ctx, a) => extend(ctx, [[a[0], a[1]]]));+ wrap('lineTo', (ctx, a) => extend(ctx, [[a[0], a[1]]]));+ wrap('bezierCurveTo', (ctx, a) => extend(ctx, [[a[0], a[1]], [a[2], a[3]], [a[4], a[5]]]));+ wrap('quadraticCurveTo', (ctx, a) => extend(ctx, [[a[0], a[1]], [a[2], a[3]]]));+ wrap('arcTo', (ctx, a) => extend(ctx, [[a[0], a[1]], [a[2], a[3]]]));+ wrap('arc', (ctx, a) => extend(ctx, rect(a[0] - a[2], a[1] - a[2], 2 * a[2], 2 * a[2])));+ wrap('ellipse', (ctx, a) => extend(ctx, rect(a[0] - a[2], a[1] - a[3], 2 * a[2], 2 * a[3])));+ for (const name of ['rect', 'roundRect']) wrap(name, (ctx, a) => extend(ctx, rect(a[0], a[1], a[2], a[3])));+ wrap('fill', (ctx, a) => { if (!(a[0] instanceof Path2D)) push(ctx, 'shape:' + String(ctx.fillStyle), pb.get(ctx), 'shape'); });+ wrap('stroke', (ctx, a) => { if (!(a[0] instanceof Path2D)) push(ctx, 'line:' + String(ctx.strokeStyle), pb.get(ctx), 'shape'); });+ wrap('fillRect', (ctx, a) => push(ctx, 'shape:' + String(ctx.fillStyle), bbox(dev(ctx, rect(a[0], a[1], a[2], a[3]))), 'shape'));+ wrap('strokeRect', (ctx, a) => push(ctx, 'line:' + String(ctx.strokeStyle), bbox(dev(ctx, rect(a[0], a[1], a[2], a[3]))), 'shape'));++ const snapshot = () => {+ const VW = innerWidth, VH = innerHeight, out = [], memo = new Map();+ const opac = el => {+ if (!el || el.nodeType !== 1) return 1; if (memo.has(el)) return memo.get(el);+ const cs = getComputedStyle(el); let o = (cs.display === 'none' || cs.visibility === 'hidden') ? 0 : parseFloat(cs.opacity);+ if (o > 0) o *= opac(el.parentElement); memo.set(el, o); return o;+ };+ const pathOf = el => {+ const parts = [];+ for (let e = el; e && e.nodeType === 1 && e !== document.body && e !== document.documentElement; e = e.parentElement) {+ let p = e.tagName.toLowerCase(); if (e.id) { parts.unshift(p + '#' + e.id); break; }+ const par = e.parentElement; if (par) { const sib = [...par.children].filter(x => x.tagName === e.tagName); if (sib.length > 1) p += ':' + sib.indexOf(e); }+ if (e.classList.length) p += '.' + e.classList[0]; parts.unshift(p);+ }+ return parts.join('>');+ };+ const add = (id, key, x0, y0, x1, y1, op, kind) => {+ const cx0 = Math.max(0, x0), cy0 = Math.max(0, y0), cx1 = Math.min(VW, x1), cy1 = Math.min(VH, y1);+ if (cx1 <= cx0 || cy1 <= cy0 || op < 0.05) return;+ out.push({ id, key, x: (x0 + x1) / 2, y: (y0 + y1) / 2, w: x1 - x0, h: y1 - y0, vis: (cx1 - cx0) * (cy1 - cy0), op, kind });+ };+ for (const el of document.body.querySelectorAll('*')) {+ const tag = el.tagName.toLowerCase();+ if (tag === 'script' || tag === 'style' || tag === 'link' || tag === 'template' || (tag !== 'svg' && el.closest('svg'))) continue;+ let kind = null, key = '';+ if (tag === 'img' || tag === 'video') { kind = 'img'; key = fold(el.currentSrc || el.src); }+ else if (tag === 'canvas') kind = 'canvas';+ else if (tag === 'svg') kind = 'svg';+ else {+ let own = ''; for (const n of el.childNodes) if (n.nodeType === 3) own += n.textContent;+ own = own.trim();+ if (own) { kind = 'text'; key = own.slice(0, 40); }+ else { const cs = getComputedStyle(el), bg = cs.backgroundColor;+ if ((bg && bg !== 'rgba(0, 0, 0, 0)' && bg !== 'transparent') || cs.backgroundImage !== 'none' || parseFloat(cs.borderTopWidth) > 0 || cs.boxShadow !== 'none') kind = 'box'; }+ }+ if (!kind) continue;+ const r = el.getBoundingClientRect(); if (r.width < 2 || r.height < 2) continue;+ if ((kind === 'box' || kind === 'canvas') && r.width * r.height >= 0.85 * VW * VH) continue; // backgrounds and full-frame layers are ground+ add(kind + ':' + pathOf(el), key, r.left, r.top, r.right, r.bottom, opac(el), kind);+ }+ for (const d of draws) {+ const r = d.cv.getBoundingClientRect(), sx = r.width / d.cv.width, sy = r.height / d.cv.height;+ add('draw:' + d.id, '', r.left + d.b[0] * sx, r.top + d.b[1] * sy, r.left + d.b[2] * sx, r.top + d.b[3] * sy, d.alpha * opac(d.cv), d.kind);+ }+ return out;+ };+ window.__omTrack = { reset() { draws.length = 0; counts.clear(); }, snapshot };+})();+"""++SAMPLE_AUTO = "async (t) => { window.__omTrack.reset(); await window.__seek(t); return window.__omTrack.snapshot(); }"+SAMPLE_ANNOTATED = """async (t) => { await window.__seek(t); const r = window.__track(t) || {};+ return Object.entries(r).map(([id, v]) => Array.isArray(v)+ ? { id, key: '', x: v[0], y: v[1], w: 0, h: 0, vis: 0, op: 1, kind: 'track' }+ : { id, key: v.key || '', x: v.x, y: v.y, w: v.w || 0, h: v.h || 0, vis: (v.w || 0) * (v.h || 0), op: v.op == null ? 1 : v.op, kind: 'track' }); }"""+++def comp_url(comp):+ return comp if comp.startswith(("file://", "http://", "https://")) else "file://" + os.path.abspath(comp)+++async def collect_page(pg, comp, fps=30, t0=0.0, t1=None, query=""):+ """Sample an already-open page (gallery.py reuses one browser across demos)."""+ await pg.goto(comp_url(comp) + query)+ await pg.evaluate("window.__ready")+ meta = await pg.evaluate("window.__meta || {}")+ annotated = await pg.evaluate("typeof window.__track === 'function'")+ dur = float(t1 if t1 is not None else meta.get("dur", 15))+ n = int(round((dur - t0) * fps))+ fn = SAMPLE_ANNOTATED if annotated else SAMPLE_AUTO+ samples, failed = [], []+ for i in range(n + 1):+ t = round(t0 + i / fps, 6)+ try:+ items = await pg.evaluate(fn, t)+ except Exception as e: # a frame the renderer would choke on too: keep what was drawn, report it+ failed.append((t, str(e).splitlines()[0][:120]))+ items = [] if annotated else await pg.evaluate("window.__omTrack.snapshot()")+ samples.append((t, items))+ return {"comp": comp, "meta": meta, "fps": fps, "dur": dur, "annotated": annotated, "samples": samples, "failed": failed}+++async def collect(comp, fps=30, t0=0.0, t1=None, width=1920, height=1080):+ async with async_playwright() as p:+ b = await p.chromium.launch()+ pg = await b.new_page(viewport={"width": width, "height": height})+ errs = []+ pg.on("pageerror", lambda e: errs.append(str(e)))+ await pg.add_init_script(TRACKER_JS)+ res = await collect_page(pg, comp, fps, t0, t1)+ await b.close()+ res.update(W=width, H=height, errors=errs)+ return res+++# ─────────────────────────────── continuity ───────────────────────────────+def _weight(it, area):+ return it["vis"] * it["op"] / area+++def _jaccard(A, B, area):+ inter = union = 0.0+ for k in set(A) | set(B):+ wa = _weight(A[k], area) if k in A else 0.0+ wb = _weight(B[k], area) if k in B else 0.0+ if k in A and k in B and A[k]["key"] == B[k]["key"]:+ inter += min(wa, wb); union += max(wa, wb)+ else:+ union += wa + wb+ return inter / union if union > 0 else 1.0+++def short(i):+ head, _, tail = i.partition(":")+ return head + ":" + tail.split(">")[-1][:34]+++def continuity(res, dt=0.4, j_max=0.2, cut_j=0.3, min_content=0.004):+ W, H, fps, dur = res["W"], res["H"], res["fps"], res["dur"]+ area = float(W * H)+ S = [{it["id"]: it for it in items} for _, items in res["samples"]]+ content = [sum(_weight(it, area) for it in s.values()) for s in S]+ lag, bridge, n = max(1, int(round(dt * fps))), int(1.5 * fps), len(S)++ # hard cuts between consecutive samples → bursts+ cuts = [i for i in range(n - 1) if content[i] >= min_content and content[i + 1] >= min_content and _jaccard(S[i], S[i + 1], area) < cut_j]+ bursts, group = [], []+ for i in cuts:+ if group and (i - group[-1]) / fps > 0.6: # gaps <= .6 s, so any 3 cuts in a group fall inside 1.5 s+ if len(group) >= 3:+ bursts.append((group[0] / fps - 0.25, group[-1] / fps + 0.25))+ group = []+ group.append(i)+ if len(group) >= 3: bursts.append((group[0] / fps - 0.25, group[-1] / fps + 0.25))++ # replacement windows, merged into boundaries+ events = []+ for i in range(n - lag):+ if content[i] < min_content:+ continue+ j = i + lag+ while j < n - 1 and content[j] < min_content and j - i < bridge:+ j += 1+ if content[j] < min_content:+ continue+ J = _jaccard(S[i], S[j], area)+ if J >= j_max:+ continue+ if events and i <= events[-1]["span"][1]:+ ev = events[-1]; ev["span"][1] = j+ if J < ev["J"]:+ ev.update(i=i, j=j, J=J)+ else:+ events.append({"i": i, "j": j, "J": J, "span": [i, j]})++ declared = [float(c) for c in (res["meta"].get("cuts") or [])]+ diag = math.hypot(W, H)+ for ev in events:+ A, B = S[ev["i"]], S[ev["j"]]+ ev["t"] = round((ev["i"] + ev["j"]) / 2 / fps, 2)+ strong, weak = [], []+ for k in set(A) & set(B):+ a, b = A[k], B[k]+ if min(a["op"], b["op"]) < 0.15:+ continue+ move = math.hypot(b["x"] - a["x"], b["y"] - a["y"]) / diag+ scale = abs(math.log(math.sqrt(max(b["w"] * b["h"], 1.0)) / math.sqrt(max(a["w"] * a["h"], 1.0))))+ big = min(a["vis"], b["vis"]) / area+ if move >= 0.02 or scale >= 0.1:+ strong.append((max(move, scale), k))+ elif big >= 0.03 and a["key"] == b["key"]:+ weak.append((big, k))+ ev["carriers"] = [short(k) for _, k in sorted(strong, reverse=True)[:3]]+ ev["anchors"] = [short(k) for _, k in sorted(weak, reverse=True)[:2]]+ ev["kind"] = "carried" if strong else "anchored" if weak else "bare"+ tb = ev["t"]+ ev["exempt"] = ("burst" if any(a0 <= tb <= a1 for a0, a1 in bursts) else+ "end" if tb >= dur - 1.2 else+ "declared" if any(abs(tb - c) <= 0.25 for c in declared) else "")+ top = lambda s: [short(k) for k, _ in sorted(s.items(), key=lambda kv: -_weight(kv[1], area))[:2]]+ ev["before"], ev["after"] = top(A), top(B)+ considered = [e for e in events if not e["exempt"]]+ score = 1.0 if not considered else sum(1.0 if e["kind"] == "carried" else 0.5 if e["kind"] == "anchored" else 0.0 for e in considered) / len(considered)+ return {"score": round(score, 2), "events": events, "considered": len(considered),+ "bare": sum(e["kind"] == "bare" for e in considered), "cuts": len(cuts), "bursts": [(round(a, 2), round(b, 2)) for a, b in bursts]}+++# ─────────────────────────────── curves ───────────────────────────────+def moves_of(track, fps, W, vmin=0.8, min_path=30.0, min_steps=4, gap=2):+ """track: {sample_index: item}. Returns the moves along this element's centre (px normalised to 1920 wide)."""+ runs, cur = [], []+ for i in sorted(track):+ if track[i]["op"] < 0.15 or (cur and i != cur[-1] + 1):+ if cur:+ runs.append(cur)+ cur = [] if track[i]["op"] < 0.15 else [i]+ continue+ cur.append(i)+ if cur:+ runs.append(cur)+ norm, out = 1920.0 / W, []+ for run in runs:+ if len(run) < min_steps + 1:+ continue+ xs = np.array([track[i]["x"] for i in run], float)+ ys = np.array([track[i]["y"] for i in run], float)+ ds = np.array([math.sqrt(max(track[i]["w"] * track[i]["h"], 1.0)) for i in run], float)+ step = (np.hypot(np.diff(xs), np.diff(ys)) + 0.5 * np.abs(np.diff(ds))) * norm+ for k in range(len(step)): # a lone jump between calm neighbours is a teleport, not travel+ prev = step[k - 1] if k > 0 else 0.0+ nxt = step[k + 1] if k + 1 < len(step) else 0.0+ if step[k] > 60 and prev < 0.1 * step[k] and nxt < 0.1 * step[k]:+ step[k] = 0.0+ active = step >= vmin+ k = 0+ while k < len(step):+ if not active[k]:+ k += 1; continue+ a = b = k+ while b < len(step):+ if active[b]:+ b += 1; continue+ nxt = b+ while nxt < len(step) and not active[nxt] and nxt - b < gap:+ nxt += 1+ if nxt < len(step) and active[nxt]:+ b = nxt; continue+ break+ k = b+ path = step[a:b]; L = float(path.sum())+ if b - a < min_steps or L < min_path:+ continue+ k80 = int(np.searchsorted(np.cumsum(path), 0.8 * L)) + 1+ net = np.array([xs[b] - xs[a], ys[b] - ys[a]]); nl = float(np.hypot(*net)); over = 0.0+ if nl > 20:+ u = net / nl+ proj = (xs[a:b + 1] - xs[a]) * u[0] + (ys[a:b + 1] - ys[a]) * u[1]+ over = max(0.0, float(proj.max() - proj[-1]) / nl)+ out.append({"t0": round(run[a] / fps, 3), "t1": round(run[b] / fps, 3), "path": round(L, 1), "t80": round(k80 / (b - a), 3),+ "peak": round(float(path.max()), 1), "overshoot": round(over, 3)})+ return out+++def curves(res, soft_t80=0.55):+ tracks = {}+ for i, (_, items) in enumerate(res["samples"]):+ for it in items:+ tracks.setdefault(it["id"], {})[i] = it+ moves = []+ for k, tr in tracks.items():+ for m in moves_of(tr, res["fps"], res["W"]):+ m["id"] = k+ moves.append(m)+ moves.sort(key=lambda m: -m["path"])+ total = sum(m["path"] for m in moves)+ soft = sum(m["path"] for m in moves if m["t80"] >= soft_t80) / total if total else 0.0+ order = sorted(moves, key=lambda m: m["t80"])+ acc, med = 0.0, None+ for m in order:+ acc += m["path"]+ if med is None and acc >= total / 2:+ med = m["t80"]+ top = max(moves, key=lambda m: m["peak"]) if moves else None+ return {"moves": moves, "tracks": tracks, "peak": top["peak"] if top else 0.0, "peak_at": (short(top["id"]), top["t0"]) if top else None,+ "soft_share": round(soft, 2), "t80_median": med, "count": len(moves)}+++def plot_speeds(res, cv, path, title="", times=None, top=8, size=(19.2, 3.2)):+ import matplotlib+ matplotlib.use("Agg")+ import matplotlib.pyplot as plt+ fps, norm = res["fps"], 1920.0 / res["W"]+ ranked, seen = [], set()+ for m in cv["moves"]:+ if m["id"] not in seen:+ seen.add(m["id"]); ranked.append(m["id"])+ if len(ranked) >= top:+ break+ fig, ax = plt.subplots(figsize=size, dpi=100)+ fig.patch.set_facecolor("#f8f8f6"); ax.set_facecolor("#f8f8f6")+ for idx, k in enumerate(ranked):+ tr = cv["tracks"][k]; ii = sorted(tr); ts, vs = [], []+ for a, b in zip(ii, ii[1:]):+ if b != a + 1 or min(tr[a]["op"], tr[b]["op"]) < 0.15:+ ts.append(np.nan); vs.append(np.nan); continue+ d = math.hypot(tr[b]["x"] - tr[a]["x"], tr[b]["y"] - tr[a]["y"]) + 0.5 * abs(math.sqrt(max(tr[b]["w"] * tr[b]["h"], 1)) - math.sqrt(max(tr[a]["w"] * tr[a]["h"], 1)))+ ts.append(b / fps); vs.append(d * norm)+ ax.plot(ts, vs, lw=1.6, label=short(k))+ for m in cv["moves"][:6]:+ ax.annotate(f"t80 {m['t80']:.2f}", (m["t0"], m["peak"]), fontsize=8, color="#555", xytext=(2, 2), textcoords="offset points")+ for t in (times or []):+ ax.axvline(t, color="#c9c9c4", lw=0.8, zorder=0)+ ax.set_xlim(0, res["dur"]); ax.set_ylabel(f"px / frame @{fps}"); ax.set_xlabel("s")+ ax.spines[["top", "right"]].set_visible(False)+ ax.legend(loc="upper right", fontsize=7, frameon=False, ncol=2)+ if title:+ ax.set_title(title, loc="left", fontsize=10)+ fig.tight_layout(); fig.savefig(path, facecolor=fig.get_facecolor()); plt.close(fig)+++def report(res, ct, cv):+ print(f"\n{os.path.basename(res['comp'])} — {len(res['samples'])} samples at {res['fps']} fps, {len(cv['tracks'])} tracked elements"+ f" ({'__track' if res['annotated'] else 'auto'}){'; page errors: ' + '; '.join(res['errors'][:2]) if res.get('errors') else ''}")+ if res.get("failed"):+ print(f" !! __seek threw at {len(res['failed'])} samples, first at t={res['failed'][0][0]}: {res['failed'][0][1]}")+ kinds = [e["kind"] for e in ct["events"] if not e["exempt"]]+ print(f"continuity score {ct['score']:.2f} — {ct['considered']} boundaries: {kinds.count('carried')} carried, {kinds.count('anchored')} anchored, "+ f"{kinds.count('bare')} bare; {len(ct['events']) - ct['considered']} exempt; hard cuts {ct['cuts']}, bursts {ct['bursts']}")+ for e in ct["events"]:+ why = e["exempt"] or e["kind"]+ via = ", ".join(e["carriers"] or e["anchors"]) or "—"+ print(f" t={e['t']:6.2f} J {e['J']:.2f} {why:9} via {via:48.48} before {', '.join(e['before'])} | after {', '.join(e['after'])}")+ if cv["peak_at"]:+ print(f"curves peak {cv['peak']:.0f} px/frame ({cv['peak_at'][0]} at {cv['peak_at'][1]:.2f} s) · travel on soft curves {cv['soft_share'] * 100:.0f} %"+ f" · median t80 {cv['t80_median']:.2f} · {cv['count']} moves")+ for m in cv["moves"][:8]:+ print(f" {short(m['id']):40.40} {m['t0']:6.2f}–{m['t1']:5.2f} s path {m['path']:6.0f} t80 {m['t80']:.2f} peak {m['peak']:5.0f} overshoot {m['overshoot']:.2f}")+ else:+ print("curves nothing moved")+++def framing(res):+ """Per id in window.__meta.inFrame ({id: [t0, t1] | [t0, t1, 'whole']}): the sampled times inside its window when its+ box was entirely off frame — or, for 'whole', not wholly inside. Samples where the id isn't drawn don't count."""+ spec = (res.get("meta") or {}).get("inFrame") or {}+ W, H, out = res.get("W", 1920), res.get("H", 1080), {}+ for name, win in spec.items():+ t0, t1, whole = float(win[0]), float(win[1]), len(win) > 2 and win[2] == "whole"+ bad, seen = [], 0+ for t, items in res["samples"]:+ if not t0 <= t <= t1:+ continue+ b = next((it for it in items if it["id"] == name and it.get("op", 1) > 0), None)+ if b is None:+ continue+ seen += 1; x0, y0, x1, y1 = b["x"], b["y"], b["x"] + b["w"], b["y"] + b["h"]+ off = (x0 < -0.5 or y0 < -0.5 or x1 > W + 0.5 or y1 > H + 0.5) if whole else (x1 < 0 or y1 < 0 or x0 > W or y0 > H)+ if off:+ bad.append(round(t, 3))+ out[name] = {"whole": whole, "window": [t0, t1], "samples": seen, "bad": bad}+ return out+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("comp"); ap.add_argument("--fps", type=int, default=30); ap.add_argument("--out", default=None)+ ap.add_argument("--from", dest="t0", type=float, default=0.0); ap.add_argument("--to", dest="t1", type=float, default=None)+ ap.add_argument("--width", type=int, default=1920); ap.add_argument("--height", type=int, default=1080)+ a = ap.parse_args()+ res = asyncio.run(collect(a.comp, a.fps, a.t0, a.t1, a.width, a.height))+ ct, cv = continuity(res), curves(res)+ report(res, ct, cv)+ for k, v in framing(res).items():+ print(f"framing {k}: {'wholly ' if v['whole'] else ''}in frame {v['window'][0]:g}–{v['window'][1]:g} s — off at {len(v['bad'])} of {v['samples']} samples{' ' + str(v['bad'][:8]) if v['bad'] else ''}")+ if a.out:+ os.makedirs(a.out, exist_ok=True)+ slim = {k: [[i / res["fps"], round(v["x"], 1), round(v["y"], 1), round(v["w"], 1), round(v["h"], 1), round(v["op"], 3)] for i, v in sorted(tr.items())] for k, tr in cv["tracks"].items()}+ json.dump({"fps": res["fps"], "dur": res["dur"], "continuity": {k: v for k, v in ct.items()}, "moves": cv["moves"], "tracks": slim},+ open(os.path.join(a.out, "tracks.json"), "w"))+ plot_speeds(res, cv, os.path.join(a.out, "curves.png"), title=os.path.basename(a.comp))+ print(f"\nwrote {a.out}/tracks.json and {a.out}/curves.png")+++if __name__ == "__main__":+ main()diff --git a/scripts/record_footage.py b/scripts/record_footage.pynew file mode 100644index 0000000..096943c--- /dev/null+++ b/scripts/record_footage.py@@ -0,0 +1,93 @@+#!/usr/bin/env python3+"""record_footage.py — drive real pages in real time, record them, mark where the input starts.++ python3 scripts/record_footage.py footage.json --out footage/++footage.json:+{+ "viewport": [1920, 1200], # record at the size you will show; frames are extracted 1:1+ "settle_ms": 1500, # after load, before anything+ "preroll_ms": 1400, # idle time recorded before the input starts (the page breathing)+ "tail_ms": 2000, # recorded after the input ends (the settle)+ "cases": [+ {"name": "critter", "url": "file:///…/index.html",+ "prep": [{"click_text": "Spring"}, {"wait": 300}], # optional: clicks / waits / key presses before the marker+ "drive": [{"sweep": [[720,450],[380,300],[1060,620]], "dur": 3.2}]}, # after the marker; coords in 1440×900 space if "coord_space": [1440,900]+ {"name": "press-stack", "url": "…", "drive": [{"wheel": {"n": 10, "dy": 260, "gap_ms": 220}}]},+ {"name": "demo", "url": "…", "drive": [{"wheel": {"n":1,"dy":600,"gap_ms":0}}, {"wait":1500}, {"wheel": {"n":1,"dy":600,"gap_ms":0}}]}+ ],+ "coord_space": [1440, 900] # optional: sweep points are scaled from this to the viewport+}++Sweeps are wall-clock paced: each segment gets its share of `dur`, moves are batched so the Playwright+round trip does not slow the hand (a naive per-step await ran 4× slow). A 24 px magenta square is+injected for 140 ms at bottom-left when the drive starts; extraction finds it → `mark`.++Writes: <out>/<name>.webm, <out>/frames/<name>/NNNN.jpg (30 fps), <out>/info.json {name:{n,mark}},+<out>/paths.json {name:{"pts":[[x,y]…],"dur":…} | {"wheel":[n,dy,gap]}} in viewport coordinates.+"""+import argparse, asyncio, glob, json, os, re, shutil, subprocess, time+from PIL import Image+from playwright.async_api import async_playwright++MARK = """(()=>{const d=document.createElement('div');d.id='__mark';d.style.cssText='position:fixed;left:0;bottom:0;width:24px;height:24px;background:#ff00ff;z-index:99999;pointer-events:none';document.body.appendChild(d);setTimeout(()=>d.remove(),140);})()"""++async def sweep(pg, pts, dur):+ n = len(pts) - 1; per = dur / n+ for i in range(n):+ (x0, y0), (x1, y1) = pts[i], pts[i + 1]; t0 = time.time(); sub = 6+ for s in range(1, sub + 1):+ k = s / sub; k = k * k * (3 - 2 * k)+ await pg.mouse.move(x0 + (x1 - x0) * k, y0 + (y1 - y0) * k, steps=4)+ dt = t0 + per * s / sub - time.time()+ if dt > 0: await pg.wait_for_timeout(int(dt * 1000))++async def run_steps(pg, steps, sc, log, name):+ for st in steps:+ if "sweep" in st:+ pts = [(x * sc[0], y * sc[1]) for x, y in st["sweep"]]; log[name] = {"pts": pts, "dur": st["dur"]}+ await sweep(pg, pts, st["dur"])+ elif "wheel" in st:+ w = st["wheel"]; log.setdefault(name, {}).setdefault("wheel", []).append([w["n"], w["dy"], w.get("gap_ms", 200)])+ for _ in range(w["n"]): await pg.mouse.wheel(0, w["dy"]); await pg.wait_for_timeout(w.get("gap_ms", 200))+ elif "wait" in st: await pg.wait_for_timeout(st["wait"])+ elif "click_text" in st: await pg.get_by_role("button", name=re.compile(st["click_text"])).click()+ elif "click" in st: x, y = st["click"]; await pg.mouse.click(x * sc[0], y * sc[1])+ elif "key" in st: await pg.keyboard.press(st["key"])+ elif "eval" in st: await pg.evaluate(st["eval"])++async def main():+ ap = argparse.ArgumentParser(); ap.add_argument("config"); ap.add_argument("--out", default="footage"); a = ap.parse_args()+ cfg = json.load(open(a.config)); out = os.path.abspath(a.out); os.makedirs(out, exist_ok=True)+ W, H = cfg.get("viewport", [1920, 1200]); cs = cfg.get("coord_space", [W, H]); sc = (W / cs[0], H / cs[1])+ log = {}+ async with async_playwright() as p:+ b = await p.chromium.launch()+ for c in cfg["cases"]:+ name = c["name"]; d = f"{out}/raw_{name}"; shutil.rmtree(d, ignore_errors=True)+ ctx = await b.new_context(viewport={"width": W, "height": H}, record_video_dir=d, record_video_size={"width": W, "height": H})+ pg = await ctx.new_page(); await pg.goto(c["url"], wait_until="load"); await pg.wait_for_timeout(cfg.get("settle_ms", 1500))+ await run_steps(pg, c.get("prep", []), sc, {}, name)+ await pg.mouse.move(W / 2, H / 2); await pg.wait_for_timeout(cfg.get("preroll_ms", 1400))+ await pg.evaluate(MARK); t0 = time.time()+ await run_steps(pg, c["drive"], sc, log, name)+ print(f"recorded {name} drive {time.time()-t0:.2f}s", flush=True)+ await pg.wait_for_timeout(cfg.get("tail_ms", 2000)); await ctx.close()+ v = [f for f in os.listdir(d) if f.endswith(".webm")][0]; os.replace(f"{d}/{v}", f"{out}/{name}.webm"); shutil.rmtree(d)+ await b.close()+ json.dump(log, open(f"{out}/paths.json", "w"), indent=1)+ info = {}+ for c in cfg["cases"]:+ name = c["name"]; d = f"{out}/frames/{name}"; os.makedirs(d, exist_ok=True)+ for f in glob.glob(f"{d}/*.jpg"): os.remove(f)+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", f"{out}/{name}.webm", "-vf", "fps=30", "-q:v", "2", f"{d}/%04d.jpg"], check=True)+ frames = sorted(glob.glob(f"{d}/*.jpg")); mark = None+ for i, f in enumerate(frames):+ px = Image.open(f).getpixel((6, H - 8))+ if px[0] > 180 and px[2] > 180 and px[1] < 90: mark = i; break+ info[name] = {"n": len(frames), "mark": mark}; print(f"{name}: {len(frames)} frames, mark {mark}")+ if mark is None: print(f" !! no marker found for {name} — the page may cover the bottom-left corner; check frames")+ json.dump(info, open(f"{out}/info.json", "w"), indent=1)++if __name__ == "__main__":+ asyncio.run(main())diff --git a/scripts/render.py b/scripts/render.pynew file mode 100644index 0000000..32217c3--- /dev/null+++ b/scripts/render.py@@ -0,0 +1,224 @@+#!/usr/bin/env python3+"""render.py — seek a composition frame by frame, screenshot, encode, mux the SFX.++ python3 scripts/render.py comp.html --out draft.mp4 --sfx sfx.wav # review draft: 1920×1080, 30 fps, shutter 180°+ python3 scripts/render.py comp.html --out film.mp4 --final --sfx sfx.wav # only after the cut is accepted: 3840×2160, 60 fps+ python3 scripts/render.py comp.html --out raw.mp4 --shutter 0 # no motion blur (to compare)++Drafts are the default: every round before acceptance is a draft, and a 4K60 render of a rejected cut is+wasted minutes. The composition is authored at --width×--height CSS px; --scale 2 captures it at 3840×2160.+Duration comes from window.__meta.dur if the page defines it, else --dur. Every capture awaits `__seek(t)`,+which must resolve only after that frame's images are decoded.++Workers. A capture is a Chrome screenshot, ~150 ms, of which the page's own drawing is under a millisecond. So+--workers browsers (default: cores − 2, at most 8) run in separate processes, each taking every n-th frame.++Motion blur (--shutter, degrees; 0 = off). A film camera integrates light while its shutter is open; a+screenshot is an instant, so a fast move strobes into separate copies. For each frame the renderer seeks+several times across the open shutter (centred on the frame time) and averages the captures in linear+light. It captures the two ends of the shutter first: if they are identical nothing moved, the frame is+written as is and the other samples are skipped, so holds cost nothing. __seek(t) is pure, so this is the+real integral, not a blur filter.++How many captures. A fixed count strobes fast moves anyway: 8 captures of the one-dot film's 633 px/frame+opening left 40 px between copies and its edges stepped. A page that defines window.__motion(t0, t1) → the+farthest anything travels on screen between two times (its elements and its camera, CSS px) gets enough+captures per frame to keep neighbours --gap px apart, between --samples-min and --samples-max. A page without+it gets --samples per moving frame.++A camera never exposes across an edit. When one step between neighbouring captures holds the change (>= 3x+any other step) — a hard cut, a word popping in, a typed character, a footage frame flipping — only the+captures on the frame time's side of it are averaged, so a cut stays a cut instead of a one-frame dissolve.++Writes <out>.render.json next to the film (fps, scale, shutter, samples, workers, frames, captures, cut frames,+seconds); verify_promo.py reads it to know whether fast moves were rendered with blur.+"""+import argparse, asyncio, io, json, math, multiprocessing, os, shutil, subprocess, time+from concurrent.futures import ProcessPoolExecutor, wait+import numpy as np+from PIL import Image+from playwright.async_api import async_playwright++_u = np.arange(256) / 255.0+SRGB_TO_LIN = np.where(_u <= 0.04045, _u / 12.92, ((_u + 0.055) / 1.055) ** 2.4).astype(np.float32)+_l = np.arange(65536) / 65535.0+LIN_TO_SRGB = np.clip(np.rint(np.where(_l <= 0.0031308, _l * 12.92, 1.055 * np.power(_l, 1 / 2.4) - 0.055) * 255.0), 0, 255).astype(np.uint8)+++def decode(png):+ return np.asarray(Image.open(io.BytesIO(png)).convert("RGB"))+++def cut_side(small):+ """Indices of the captures to integrate, given each one box-filtered to greyscale: all of them, unless one step+ between neighbours carries the change (a discontinuity, not motion) — then the side holding the frame time, the+ later side if the step straddles it."""+ n = len(small)+ if n < 4:+ return list(range(n))+ d = np.array([np.abs(small[k + 1] - small[k]).mean() for k in range(n - 1)])+ j = int(d.argmax())+ if d[j] <= 0 or d[j] < 3 * np.delete(d, j).max():+ return list(range(n))+ return list(range(j + 1, n)) if j < n // 2 else list(range(j + 1))+++def uncut(shots):+ """cut_side for decoded captures."""+ if len(shots) < 4:+ return list(range(len(shots)))+ return cut_side([np.asarray(Image.fromarray(s).convert("L").reduce(8), np.int16) for s in shots]) # box-filtered, so motion changes every step+++def integrate(shots):+ """Average decoded captures in linear light, leaving out the far side of a cut. Returns (image, cut)."""+ keep = uncut(shots)+ acc = np.zeros(shots[0].shape, np.float32)+ for k in keep:+ acc += SRGB_TO_LIN[shots[k]]+ idx = np.clip(np.rint(acc * (65535.0 / len(keep))), 0, 65535).astype(np.uint16)+ return LIN_TO_SRGB[idx], len(keep) < len(shots)+++def integrate_png(pngs):+ """integrate() over PNG bytes, decoding one capture at a time, so 48 captures of a 4K frame never sit in memory at once."""+ keep = cut_side([np.asarray(Image.open(io.BytesIO(p)).convert("L").reduce(8), np.int16) for p in pngs]) if len(pngs) >= 4 else list(range(len(pngs)))+ acc = None+ for k in keep:+ lin = SRGB_TO_LIN[decode(pngs[k])]+ if acc is None:+ acc = lin+ else:+ acc += lin+ idx = np.clip(np.rint(acc * (65535.0 / len(keep))), 0, 65535).astype(np.uint16)+ return LIN_TO_SRGB[idx], len(keep) < len(pngs)+++def work(job):+ """One browser in its own process, rendering the frames f ≡ job['k'] (mod job['n']). Returns its counters."""+ return asyncio.run(_work(job))+++async def _work(j):+ fps, dur, fr, sh = j["fps"], j["dur"], j["fr"], j["shutter"]+ st = {"captures": 0, "still": 0, "cuts": 0, "errors": [], "hist": {}}+ async with async_playwright() as p:+ B = {} # the live browser; relaunched every j["recycle"] frames++ async def launch():+ if B:+ await B["br"].close()+ B["br"] = br = await p.chromium.launch()+ B["pg"] = pg = await (await br.new_context(viewport={"width": j["width"], "height": j["height"]}, device_scale_factor=j["scale"])).new_page()+ pg.on("pageerror", lambda e: st["errors"].append(str(e))); pg.on("console", lambda m: st["errors"].append(m.text) if m.type == "error" else None)+ await pg.goto("file://" + j["comp"]); await pg.evaluate("window.__ready")++ await launch(); pg = B["pg"]+ adaptive = sh > 0 and await pg.evaluate("typeof window.__motion === 'function'")+ open_s = (sh / 360.0) / fps++ async def grab(t):+ await B["pg"].evaluate(f"window.__seek({t})"); st["captures"] += 1+ return await B["pg"].screenshot(type="png")++ done = 0+ for f in range(j["k"], j["N"], j["n"]):+ t = f / fps; path = f"{fr}/{f:05d}.png"+ if j.get("resume") and os.path.exists(path):+ continue+ if done and j.get("recycle") and done % j["recycle"] == 0:+ await launch() # a Chrome taking 4K screenshots for ~30 min grows until the OS closes it+ done += 1; pg = B["pg"]+ if sh <= 0:+ open(path, "wb").write(await grab(t))+ continue+ S = j["samples"]+ if adaptive:+ try:+ far = await pg.evaluate(f"window.__motion({max(t - open_s / 2, 0.0)}, {min(t + open_s / 2, dur - 1e-6)})")+ S = min(j["smax"], max(j["smin"], math.ceil(far * j["scale"] / j["gap"])))+ except Exception: # a page whose __motion throws keeps the fixed count+ S = j["samples"]+ times = [min(max(t + open_s * ((k + 0.5) / S - 0.5), 0.0), dur - 1e-6) for k in range(S)]+ first = await grab(times[0]); last = await grab(times[-1])+ if first == last: # nothing moved while the shutter was open+ open(path, "wb").write(first); st["still"] += 1+ continue+ pngs = [first] + [await grab(tk) for tk in times[1:-1]] + [last]+ img, cut = integrate_png(pngs); st["cuts"] += cut+ Image.fromarray(img).save(path, compress_level=1)+ st["hist"][S] = st["hist"].get(S, 0) + 1+ await B["br"].close()+ return st+++async def page_info(comp, width, height):+ async with async_playwright() as p:+ br = await p.chromium.launch()+ pg = await (await br.new_context(viewport={"width": width, "height": height})).new_page()+ await pg.goto("file://" + comp); await pg.evaluate("window.__ready")+ info = await pg.evaluate("({dur: (window.__meta && window.__meta.dur) || null, motion: typeof window.__motion === 'function'})")+ await br.close()+ return info+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("comp"); ap.add_argument("--out", default="draft.mp4")+ ap.add_argument("--fps", type=int, default=30); ap.add_argument("--scale", type=int, default=1)+ ap.add_argument("--final", action="store_true", help="3840×2160 at 60 fps (sets --fps 60 --scale 2) — only once the cut is accepted")+ ap.add_argument("--shutter", type=float, default=180.0, help="shutter angle in degrees; 0 = no motion blur")+ ap.add_argument("--samples", type=int, default=8, help="captures per moving frame when the page has no window.__motion")+ ap.add_argument("--gap", type=float, default=6.0, help="px between neighbouring captures, for a page with window.__motion")+ ap.add_argument("--samples-min", type=int, default=4); ap.add_argument("--samples-max", type=int, default=48)+ ap.add_argument("--workers", type=int, default=max(1, min(8, (os.cpu_count() or 3) - 2)), help="browsers rendering in parallel processes")+ ap.add_argument("--width", type=int, default=1920); ap.add_argument("--height", type=int, default=1080)+ ap.add_argument("--dur", type=float, default=None); ap.add_argument("--sfx", default=None); ap.add_argument("--crf", type=int, default=16)+ ap.add_argument("--keep-frames", action="store_true")+ ap.add_argument("--recycle", type=int, default=150, help="relaunch each worker's browser after this many frames (0 = never)")+ ap.add_argument("--resume", action="store_true", help="keep _frames/ from a run that died and render only the missing frames (counts in the log cover this run only)")+ a = ap.parse_args()+ if a.final:+ a.fps, a.scale = 60, 2+ comp = os.path.abspath(a.comp); out = os.path.abspath(a.out); fr = os.path.join(os.path.dirname(out), "_frames")+ if not a.resume:+ shutil.rmtree(fr, ignore_errors=True)+ os.makedirs(fr, exist_ok=True)+ info = asyncio.run(page_info(comp, a.width, a.height))+ dur = a.dur or info["dur"] or 15; N = int(round(dur * a.fps)); nw = max(1, min(a.workers, N))+ adaptive = a.shutter > 0 and info["motion"]+ how = "no shutter" if a.shutter <= 0 else f"shutter {a.shutter:g}°, " + (+ f"captures per frame sized by __motion (gap {a.gap:g} px, {a.samples_min}–{a.samples_max})" if adaptive else f"{a.samples} captures per moving frame")+ print(f"{N} frames on {nw} workers · {how}", flush=True)+ job = dict(comp=comp, fr=fr, fps=a.fps, dur=dur, N=N, n=nw, width=a.width, height=a.height, scale=a.scale, shutter=a.shutter,+ samples=max(2, a.samples), gap=a.gap, smin=max(2, a.samples_min), smax=max(2, a.samples_max), resume=a.resume, recycle=a.recycle)+ t0 = time.time()+ with ProcessPoolExecutor(max_workers=nw, mp_context=multiprocessing.get_context("spawn")) as ex:+ futs = [ex.submit(work, dict(job, k=k)) for k in range(nw)]+ while wait(futs, timeout=15).not_done:+ print(f" {len(os.listdir(fr))}/{N} {time.time() - t0:.0f}s", flush=True)+ res = [f.result() for f in futs]+ secs = time.time() - t0+ captures, still, cuts = (sum(r[k] for r in res) for k in ("captures", "still", "cuts"))+ errs = [e for r in res for e in r["errors"]]; hist = {}+ for r in res:+ for k, v in r["hist"].items():+ hist[k] = hist.get(k, 0) + v+ print(f"{N} frames, {captures} captures ({still} still frames skipped the shutter, {cuts} kept a cut hard) in {secs:.0f}s on {nw} workers; page errors: {errs[:3] or 'none'}")+ cmd = ["ffmpeg", "-v", "error", "-y", "-framerate", str(a.fps), "-i", f"{fr}/%05d.png"]+ if a.sfx: cmd += ["-i", os.path.abspath(a.sfx)]+ cmd += ["-c:v", "libx264", "-preset", "medium", "-crf", str(a.crf), "-pix_fmt", "yuv420p", "-profile:v", "high", "-level", "5.2", "-movflags", "+faststart"]+ if a.sfx: cmd += ["-c:a", "aac", "-b:a", "256k", "-shortest"]+ subprocess.run(cmd + [out], check=True)+ if not a.keep_frames: shutil.rmtree(fr, ignore_errors=True)+ meta = {"comp": comp, "fps": a.fps, "scale": a.scale, "size": [a.width * a.scale, a.height * a.scale], "shutter": a.shutter if a.shutter > 0 else 0,+ "samples": ("adaptive" if adaptive else max(2, a.samples)) if a.shutter > 0 else 1}+ if adaptive:+ meta.update(gap_px=a.gap, samples_per_moving_frame={str(k): hist[k] for k in sorted(hist)})+ meta.update(workers=nw, frames=N, still_frames=still, cut_frames=cuts, captures=captures, seconds=round(secs, 1), final=a.final)+ json.dump(meta, open(os.path.splitext(out)[0] + ".render.json", "w"), indent=1)+ print("wrote", out)+++if __name__ == "__main__":+ main()diff --git a/scripts/sfx_palette.py b/scripts/sfx_palette.pynew file mode 100644index 0000000..9608fa1--- /dev/null+++ b/scripts/sfx_palette.py@@ -0,0 +1,110 @@+#!/usr/bin/env python3+"""sfx_palette.py — the sound materials, one shared room, and a Score helper.++ import sys; sys.path.insert(0, "<skill>/scripts"); from sfx_palette import *+ s = Score(dur=15)+ s.place(glass(659, 0.8, 0.6), t=0.15, gain=0.16, send=0.45)+ s.place(air(0.5, 220, 3000, 1.3, 0.35), t=7.02, gain=0.55, pan=0.6, send=0.5, pan_to=-0.1)+ s.write("sfx.wav") # 48 kHz stereo, peak -8 dBFS, soft-limited++ python3 scripts/sfx_palette.py --demo demo.wav # every material once, to listen++Materials: air (whoosh), glass (struck tone), wood (key / click), sub (felt hit), bubble (rounded pop),+wobble (jelly). All return mono float arrays at SR; gains in Score.place set the level.+Design notes: references/sound.md.+"""+import numpy as np, wave, os+from scipy import signal++SR = 48000+_rng = np.random.default_rng(7)++def _t(n): return np.arange(n) / SR+def bp(x, f, q=1.0):+ f = float(np.clip(f, 30, SR / 2 - 100)); b, a = signal.iirpeak(f / (SR / 2), q); return signal.lfilter(b, a, x)+def lp(x, f, order=2):+ b, a = signal.butter(order, float(np.clip(f, 30, SR / 2 - 100)) / (SR / 2)); return signal.lfilter(b, a, x)+def hp(x, f, order=2):+ b, a = signal.butter(order, float(np.clip(f, 20, SR / 2 - 100)) / (SR / 2), "high"); return signal.lfilter(b, a, x)+def sweep_bp(x, f0, f1, q=1.0, blocks=24):+ n = len(x); out = np.zeros(n); L = n // blocks + 1+ for i in range(blocks):+ a = i * L; b = min(n, a + L); f = f0 * (f1 / f0) ** (i / (blocks - 1))+ out[a:b] = bp(x[max(0, a - 400):b], f, q)[-(b - a):]+ return out+def sat(x, k=1.6): return np.tanh(x * k) / np.tanh(k)++# ── materials ──────────────────────────────────────────────────────────────+def air(dur=0.45, f0=250, f1=2600, q=1.4, shape=0.45):+ """a soft whoosh: filtered air whose centre glides f0→f1; shape = where the envelope peaks (0..1)"""+ n = int(SR * dur); x = sweep_bp(_rng.standard_normal(n), f0, f1, q); x = lp(x, 5500)+ t = _t(n) / dur; e = np.sin(np.pi * np.clip(t, 0, 1)) ** 1.4 * np.where(t < shape, t / shape, 1)+ return x * e / (np.abs(x * e).max() + 1e-9)+def glass(f, dur=0.9, bright=1.0):+ """a small struck tone: fundamental + inharmonic partials + a fast noise transient"""+ n = int(SR * dur); t = _t(n)+ s = np.sin(2 * np.pi * f * t) * np.exp(-t * 6) + 0.35 * np.sin(2 * np.pi * f * 2.76 * t) * np.exp(-t * 14) * bright + 0.18 * np.sin(2 * np.pi * f * 5.4 * t) * np.exp(-t * 24) * bright+ tr = lp(hp(_rng.standard_normal(n), 2000), 9000) * np.exp(-t * 220) * 0.5+ return (s * 0.7 + tr) / 1.2+def wood(f=180, dur=0.12):+ """a muted knock: low body with a pitch drop + a short filtered snap (keys, mouse down/up)"""+ n = int(SR * dur); t = _t(n)+ body = np.sin(2 * np.pi * f * t * (1 + 0.3 * np.exp(-t * 90))) * np.exp(-t * 60)+ snap = bp(_rng.standard_normal(n), 3200, 2.2) * np.exp(-t * 380)+ return body * 0.9 + snap * 0.5+def sub(f=62, dur=0.7):+ """a felt low hit: sine with a pitch drop, gently saturated"""+ n = int(SR * dur); t = _t(n); ph = np.cumsum(2 * np.pi * (f + f * 2.2 * np.exp(-t * 28)) / SR)+ s = np.sin(ph) * np.exp(-t * 5.5); tr = lp(_rng.standard_normal(n), 500) * np.exp(-t * 90) * 0.8+ return sat(s * 1.1 + tr * 0.5, 1.8)+def bubble(f=520, dur=0.22):+ """a rounded pop: a resonance rising as it closes"""+ n = int(SR * dur); t = _t(n); ph = np.cumsum(2 * np.pi * (f * (1 + 0.9 * (1 - np.exp(-t * 30)))) / SR)+ return np.sin(ph) * np.exp(-t * 26) * 0.9 + bp(_rng.standard_normal(n), f * 3, 3) * np.exp(-t * 200) * 0.4+def wobble(f=150, dur=0.6):+ """jelly: an FM'd tone whose vibrato dies out"""+ n = int(SR * dur); t = _t(n); ph = np.cumsum(2 * np.pi * f * (1 + 0.10 * np.sin(2 * np.pi * 8.5 * t) * np.exp(-t * 3.5)) / SR)+ return lp(np.sin(ph) + 0.25 * np.sin(2 * ph), 1400) * np.exp(-t * 5.5)+def pan_of(x, width=1920): return float(np.clip((x - width / 2) / (width / 2) * 0.6, -0.7, 0.7))++# ── the room + the score ───────────────────────────────────────────────────+def impulse(T60=1.1):+ n = int(SR * T60 * 1.3); t = _t(n); ir = _rng.standard_normal((n, 2)) * np.exp(-6.9 * t / T60)[:, None]+ ir = np.stack([lp(ir[:, 0], 3800), lp(ir[:, 1], 3400)], 1); ir[:int(SR * 0.012)] *= 0+ for d, g in ((0.017, 0.5), (0.029, 0.35), (0.041, 0.25)): ir[int(d * SR):int(d * SR) + 2] += g * _rng.uniform(0.5, 1, (2, 2))+ return ir / np.abs(ir).sum(0).max() * 4++class Score:+ def __init__(self, dur=15.0, T60=1.1):+ self.dur = dur; n = int(SR * (dur + 2)); self.dry = np.zeros((n, 2)); self.wet = np.zeros((n, 2)); self.T60 = T60; self.events = []+ def place(self, sig, t, gain=1.0, pan=0.0, send=0.25, pan_to=None):+ sig = np.asarray(sig, dtype=float); i0 = int(t * SR); n = len(sig)+ p = np.linspace(pan, pan if pan_to is None else pan_to, n); L = np.sqrt(0.5 * (1 - p)); R = np.sqrt(0.5 * (1 + p))+ self.dry[i0:i0 + n, 0] += sig * gain * L; self.dry[i0:i0 + n, 1] += sig * gain * R+ self.wet[i0:i0 + n, 0] += sig * gain * send * L; self.wet[i0:i0 + n, 1] += sig * gain * send * R+ self.events.append(round(t, 3))+ def mix(self, peak_db=-8.0):+ ir = impulse(self.T60); rev = np.stack([signal.fftconvolve(self.wet[:, c], ir[:, c])[:len(self.dry)] for c in (0, 1)], 1)+ m = self.dry + rev * 0.9; m = np.stack([hp(m[:, c], 38) for c in (0, 1)], 1)+ m = sat(m / (np.abs(m).max() + 1e-9) * 0.9, 1.3); m = m / np.abs(m).max() * 10 ** (peak_db / 20)+ return m[:int(SR * self.dur)]+ def write(self, path, peak_db=-8.0):+ m = self.mix(peak_db)+ with wave.open(path, "wb") as w:+ w.setnchannels(2); w.setsampwidth(2); w.setframerate(SR); w.writeframes((m * 32767).astype(np.int16).tobytes())+ print(f"{path}: {len(self.events)} events, peak {peak_db} dBFS")++def demo(path):+ s = Score(dur=9)+ s.place(glass(659, 0.9), 0.3, 0.3, send=0.5); s.place(glass(1318, 1.2, 0.5), 1.0, 0.25, send=0.6)+ s.place(wood(180), 2.0, 0.4); s.place(wood(240, 0.08), 2.6, 0.4); s.place(wood(190, 0.07), 2.66, 0.3)+ s.place(air(0.5, 220, 3000), 3.3, 0.6, 0.6, 0.5, pan_to=-0.4)+ s.place(bubble(480), 4.5, 0.4, send=0.3); s.place(wobble(150), 5.3, 0.5, send=0.35)+ s.place(sub(70, 0.6), 6.4, 0.5); s.place(sub(48, 1.2), 7.3, 0.6, send=0.45)+ s.write(path)++if __name__ == "__main__":+ import argparse+ ap = argparse.ArgumentParser(); ap.add_argument("--demo", default=None); a = ap.parse_args()+ if a.demo: demo(a.demo)+ else: print(__doc__)diff --git a/scripts/stills.py b/scripts/stills.pynew file mode 100644index 0000000..17e8b39--- /dev/null+++ b/scripts/stills.py@@ -0,0 +1,28 @@+#!/usr/bin/env python3+"""stills.py — a contact sheet of chosen moments, to look before rendering.++ python3 scripts/stills.py comp.html --times 0.7,2.4,3.8,6.2,9.9,12.7 --out stills.png+"""+import argparse, asyncio, io, os+from PIL import Image, ImageDraw+from playwright.async_api import async_playwright++async def main():+ ap = argparse.ArgumentParser(); ap.add_argument("comp"); ap.add_argument("--times", required=True); ap.add_argument("--out", default="stills.png")+ ap.add_argument("--width", type=int, default=1920); ap.add_argument("--height", type=int, default=1080); ap.add_argument("--cols", type=int, default=3)+ a = ap.parse_args(); ts = [float(x) for x in a.times.split(",")]+ async with async_playwright() as p:+ b = await p.chromium.launch(); pg = await b.new_page(viewport={"width": a.width, "height": a.height})+ errs = []; pg.on("pageerror", lambda e: errs.append(str(e)))+ await pg.goto("file://" + os.path.abspath(a.comp) + "?hud=1"); await pg.evaluate("window.__ready")+ tiles = []+ for t in ts:+ await pg.evaluate(f"window.__seek({t})"); await pg.wait_for_timeout(30)+ im = Image.open(io.BytesIO(await pg.screenshot())).resize((640, 360)); ImageDraw.Draw(im).text((6, 6), f"t={t}", fill=(200, 0, 0)); tiles.append(im)+ await b.close()+ rows = (len(tiles) + a.cols - 1) // a.cols; sheet = Image.new("RGB", (640 * a.cols, 360 * rows), (0, 0, 0))+ for i, im in enumerate(tiles): sheet.paste(im, ((i % a.cols) * 640, (i // a.cols) * 360))+ sheet.save(a.out); print("wrote", a.out, "| page errors:", errs[:3] or "none")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/scripts/test_motion.js b/scripts/test_motion.jsnew file mode 100644index 0000000..0ea0c3f--- /dev/null+++ b/scripts/test_motion.js@@ -0,0 +1,126 @@+#!/usr/bin/env node+// test_motion.js — the library's math, checked before any film leans on it.+//+// node scripts/test_motion.js+//+// Endpoints and the t80 table the docs quote, the bezier solver against brute force, springs against their+// own derivative and across zeta = 1, bit-identity with the template's original spr(), the carry geometry+// (iris covers, zoomThrough fills, view() centres and parallaxes), sim determinism, project ∘ unproject, finite outputs everywhere.+'use strict';+const path = require('path');+const OM = require(path.join(__dirname, '..', 'lib', 'motion.js'));++let fails = 0;+const ok = (name, cond, detail = '') => { console.log(` ${cond ? 'PASS' : 'FAIL'} ${name}${detail ? ' ' + detail : ''}`); if (!cond) fails++; };+const near = (a, b, e = 1e-6) => Math.abs(a - b) <= e;+const finite = o => Object.values(o).every(v => typeof v !== 'number' || Number.isFinite(v));++// 1 · curves+const curves = Object.entries(OM.ease).filter(([, f]) => typeof f(0.5) === 'number');+const badEnds = curves.filter(([, f]) => !(near(f(0), 0, 1e-9) && near(f(1), 1, 1e-9))).map(([n]) => n);+ok('every ease maps 0 → 0 and 1 → 1', badEnds.length === 0, badEnds.join(', '));+const T80 = { linear: 0.8, smooth: 0.713, smoother: 0.674, quadOut: 0.553, cubicOut: 0.415, quartOut: 0.331, quintOut: 0.275, expoOut: 0.232 };+for (const [n, v] of Object.entries(T80)) { const got = OM.t80(OM.ease[n]); ok(`t80 ${n} = ${v}`, near(got, v, 0.002), got.toFixed(3)); }++const brute = (x1, y1, x2, y2, x) => {+ let best = 0, bd = 1e9;+ for (let i = 0; i <= 200000; i++) { const s = i / 200000, bx = 3 * (1 - s) ** 2 * s * x1 + 3 * (1 - s) * s * s * x2 + s ** 3, d = Math.abs(bx - x); if (d < bd) { bd = d; best = s; } }+ return 3 * (1 - best) ** 2 * best * y1 + 3 * (1 - best) * best * best * y2 + best ** 3;+};+let worst = 0;+for (const b of [[0.25, 0.1, 0.25, 1], [0.16, 1, 0.3, 1], [0.7, 0, 0.84, 0], [0.34, 1.56, 0.64, 1]]) {+ const f = OM.bezier(...b);+ for (const x of [0.05, 0.2, 0.5, 0.8, 0.95]) worst = Math.max(worst, Math.abs(f(x) - brute(...b, x)));+}+ok('bezier solver matches brute force', worst < 2e-4, `max err ${worst.toExponential(1)}`);++// 2 · springs+for (const z of [0.3, 0.6, 0.95, 1, 1.4]) {+ ok(`spring settles to 1 (zeta ${z})`, near(OM.spring(8, z, 20), 1, 1e-4));+ const h = 1e-5; let e = 0;+ for (const t of [0.02, 0.1, 0.3, 0.7]) e = Math.max(e, Math.abs((OM.spring(t + h, z, 20) - OM.spring(t - h, z, 20)) / (2 * h) - OM.springVel(t, z, 20)));+ ok(`springVel is the derivative of spring (zeta ${z})`, e < 1e-3, `max err ${e.toExponential(1)}`);+}+ok('spring is continuous across zeta = 1', [0.05, 0.2, 0.5].every(t => near(OM.spring(t, 0.9999, 20), OM.spring(t, 1, 20), 1e-3) && near(OM.spring(t, 1.0001, 20), OM.spring(t, 1, 20), 1e-3)));+const spr = (tau, z = 0.6, w = 20) => { if (tau <= 0) return 0; const wd = w * Math.sqrt(1 - z * z); return 1 - Math.exp(-z * w * tau) * (Math.cos(wd * tau) + (z * w / wd) * Math.sin(wd * tau)); };+const ts = []; for (let t = -0.1; t < 3; t += 0.0137) ts.push(t);+ok('spring() is bit-identical to the template spr()', ts.every(t => OM.spring(t, 0.6, 22) === spr(t, 0.6, 22) && OM.spring(t, 0.78, 14) === spr(t, 0.78, 14)));+const st = OM.settle(0.6, 22); ok('settle() gives a usable hold length', st > 0.1 && st < 1, `${st.toFixed(3)} s for zeta .6 omega 22`);++// 3 · carry geometry+const ir = OM.iris(1, 0, 1, 300, 200);+ok('iris covers the farthest corner at k = 1', ir.r >= Math.hypot(1920 - 300, 1080 - 200));+const tg = { x: 600, y: 400, w: 320, h: 180 }, zt = OM.zoomThrough(1, 0, 1, tg), mp = (x, y) => [x * zt.s + zt.tx, y * zt.s + zt.ty];+const [ax, ay] = mp(tg.x, tg.y), [bx, by] = mp(tg.x + tg.w, tg.y + tg.h);+ok('zoomThrough fills the frame with the target at k = 1', near(ax, 0) && near(ay, 0) && near(bx, 1920) && near(by, 1080));+const z0 = OM.zoomThrough(0, 0, 1, tg); ok('zoomThrough starts at identity', near(z0.s, 1) && near(z0.tx, 0) && near(z0.ty, 0));+const apply = (m, x, y) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];+ok('view() is identity for a centred camera', OM.view({ x: 960, y: 540, zoom: 1, rot: 0 }).every((v, i) => near(v, [1, 0, 0, 1, 0, 0][i])));+const c2 = apply(OM.view({ x: 1060, y: 540, zoom: 2, rot: 0.3 }), 1060, 540);+ok('view() puts the camera point at the frame centre', near(c2[0], 960) && near(c2[1], 540));+ok('view() parallax: a layer at depth 1 moves half as far', near(apply(OM.view({ x: 1060, y: 540, zoom: 1, rot: 0 }, { depth: 1 }), 960, 540)[0], 910));+const lat = OM.lattice({ x: 960, y: 540, zoom: 2, rot: 0 }, { depth: 0, spacing: 48, px: 1.4 });+ok('lattice() dots stay px on screen', near(lat.r * 2, 1.4));+ok('lattice() covers the frame', lat.x0 <= 480 && lat.x1 >= 1440 && lat.y0 <= 270 && lat.y1 >= 810);+const Mv = OM.view({ x: 1060, y: 500, zoom: 1.7, rot: 0.2 }), pr = OM.project(Mv, 321, 654), un = OM.unproject(Mv, pr[0], pr[1]);+ok('unproject() inverts project()', near(un[0], 321, 1e-9) && near(un[1], 654, 1e-9));+const still = { x: 960, y: 540, zoom: 1.4, rot: 0 };+ok('screenTravel() is 0 for a still camera', OM.screenTravel(still, still, still) === 0);+ok('screenTravel() of a 10 px pan at zoom 2 is 20 px', near(OM.screenTravel({ x: 960, y: 540, zoom: 2, rot: 0 }, { x: 970, y: 540, zoom: 2, rot: 0 }, { x: 965, y: 540, zoom: 2, rot: 0 }), 20, 1e-9));+const g1 = OM.gather(2, 0, 1, 0, 3, { x: 0, y: 0 }, { x: 100, y: 50 });+ok('gather lands on its target', near(g1.x, 100) && near(g1.y, 50) && near(g1.rot, 0));+const rb = OM.ribbon(5, [1, 2]); ok('ribbon settles on the last panel', near(rb.shift, 2) && rb.index === 2 && Math.abs(rb.wobble) < 1e-6);+const sp0 = OM.impactSplit(3, 0.87, 400, 960); ok('impactSplit rejoins after the hit', near(sp0.dx, 0) && Math.abs(sp0.dy) < 1e-3);+const ty = OM.typeOn(1, 0, 'hello', { cps: 3 }); ok('typeOn types at cps', ty.n === 3 && ty.str === 'hel' && ty.caret === 1);+ok('drift pushes by amount across the hold', near(OM.drift(5, 1, 2), 1.07) && near(OM.drift(1.5, 1, 2), 1.035));++// 4 · sims+const hand = t => [960 + 230 * Math.sin(t * 3), 540 + 90 * Math.cos(t * 2)], card = { t: 0, out: 1.2, x: 760, y: 420 };+for (const k of ['magnet', 'follow', 'jelly', 'verlet']) {+ const a = OM.sim[k](card, hand), b = OM.sim[k](card, hand), sa = Array.from(a.at(0.73)), sb = Array.from(b.at(0.73));+ ok(`sim.${k} is deterministic and finite`, JSON.stringify(sa) === JSON.stringify(sb) && sa.every(Number.isFinite));+}++// 5 · every move, everywhere+const calls = t => [OM.wordRise(t, 0.2), OM.letterDrop(t, 0.2, 3), OM.popIn(t, 0.2), OM.liftOut(t, 1), OM.maskRise(t, 0.2, 1), OM.tick(t, 0.5), OM.flyThrough(t, 0.2, 0.9),+ OM.morphRect(t, 0.2, 0.8, { x: 0, y: 0, w: 10, h: 10 }, { x: 5, y: 5, w: 100, h: 50, r: 8 }), OM.morphRect(t, 0.2, 0.8, { x: 0, y: 0, w: 10, h: 10 }, { x: 5, y: 5, w: 100, h: 50 }, { spring: { zeta: 0.6 } }),+ OM.iris(t, 0.2, 0.8, 900, 500), OM.zoomThrough(t, 0.2, 1, { x: 100, y: 100, w: 200, h: 120 }), OM.hop(t, 0, 1, { x: 0, y: 0 }, { x: 1, y: 1 }),+ OM.gather(t, 0, 1, 2, 3, { x: 0, y: 0 }, { x: 1, y: 1 }), OM.ribbon(t, [0.3, 0.9]), OM.seal(t, 0, 1), OM.impact(t, 0.3), OM.impactSplit(t, 0.3, 700, 960),+ OM.press(t, 0.4), OM.squash(300 * t, -200), OM.camera(t, [{ t: 0, x: 960, y: 540 }, { t: 1, x: 1200, y: 600, zoom: 1.6, rot: 0.1 }]),+ OM.whip(t, 0.2, 0.3, 1800), OM.shake(t, 0.5), { d: OM.dof(t, 0.5), p: OM.drift(t, 0, 1) },+ OM.lattice({ x: 960 + 100 * t, y: 540, zoom: 1.5 + 0.2 * Math.sin(t), rot: 0.1 * t })];+let bad = 0; for (let t = -1; t <= 4; t += 0.01) for (const o of calls(t)) if (!finite(o)) bad++;+ok('every move returns finite numbers from t = -1 to 4', bad === 0, bad ? `${bad} non-finite results` : '');++// fluid · the moves from the ebb film+ok('swiftSpring: .smooth is critically damped at ω 2π/d', near(OM.swiftSpring(0.3, 'smooth'), OM.spring(0.3, 1, 2 * Math.PI / 0.5)) && near(OM.swiftSpring(0.3, 'bouncy', { duration: 0.6 }), OM.spring(0.3, 0.7, 2 * Math.PI / 0.6)));+{ const a = OM.lightField(0), b = OM.lightField(1);+ ok('lightField: rest horizon at 0.84 H, flood above the frame', near(a.horizon, 1080 * 0.84) && b.horizon < 0 && b.cy - b.ry < 0 && b.rx > 1920); }+{ const r = OM.ripple(5.8, 5.25), e = OM.ripple(9, 5.25);+ ok('ripple: rings lead in order and all leave the frame', r.r[0] > r.r[1] && r.r[1] > r.r[2] && e.done && e.r.every(v => near(v, 1160))); }+{ const a = OM.silk(4.2, 3), b = OM.silk(4.2, 3), c = OM.silk(4.3, 3);+ ok('silk: 16×20 RGBA, deterministic, drifts with tau', a.length === 16 * 20 * 4 && a.every((v, i) => v === b[i]) && a.some((v, i) => v !== c[i]));+ const L = x => 0.3 * x[0] + 0.59 * x[1] + 0.11 * x[2], ramp = OM.silk.ramps.ember;+ ok('silk: the ember ramp has its dark fold between two brights', L(OM.silk.ramp(ramp, 0.42)) < L(OM.silk.ramp(ramp, 0.22)) && L(OM.silk.ramp(ramp, 0.42)) < L(OM.silk.ramp(ramp, 0.74))); }+{ const B = OM.carouselLoop({ dur: 6, start: 1, speed: 200, stop: [4, 4.5] }), s0 = B.at(0.9), m1 = B.at(3), m2 = B.at(3.1), e1 = B.at(5), e2 = B.at(5.5);+ ok('carouselLoop: still before start, ~speed in the run, stopped after', near(s0.x, 0) && Math.abs((m2.x - m1.x) / 0.1 - 200) < 3 && near(e1.x, e2.x) && near(e1.tau, e2.tau)); }++// ui_kit · the time warp between a narration and the authored timeline, languages, subtitles, the replica stage+{+const UIK = require(path.join(__dirname, '..', 'lib', 'ui_kit.js'));+const tw = UIK.timeWarp([[0, 0], [0.5, 0.5], [2.9, 2.88], [13.04, 12.49], [20.14, 18.3], [46.06, 42.76]]);+let twErr = 0; for (let t = -1; t < 60; t += 0.017) twErr = Math.max(twErr, Math.abs(tw.Ui(tw.U(t)) - t));+ok('timeWarp: Ui(U(t)) = t', twErr < 1e-9, twErr.toExponential(1));+ok('timeWarp: knots hit, 1:1 after the last', near(tw.U(20.14), 18.3) && near(tw.U(50), 46.7) && near(tw.Ui(46), 49.3));+let threw = false; try { UIK.timeWarp([[0, 0], [2, 3], [3, 2]]); } catch (e) { threw = true; }+ok('timeWarp: refuses knots that go back in time', threw);+ok('timeWarp: slopes report slow and fast stretches', tw.slopes.length === 5 && tw.slopes.every(q => q.rate > 0));+const trJ = UIK.tr('ja'); ok('tr: picks the language, falls back to en, passes strings', trJ({ en: 'a', ja: 'b' }) === 'b' && trJ({ en: 'a' }) === 'a' && trJ('c') === 'c');+const su = [[1, 2, 'x']]; ok('subAt: inside, fades, outside', UIK.subAt(su, 1.5).a === 1 && near(UIK.subAt(su, 1.04).a, 0.5) && UIK.subAt(su, 2) === null);+const stg = UIK.stage({ x: 100, y: 50, s: 0.5, chrome: 35 }); const bx = stg.box({ x: 20, y: 10, w: 40, h: 8 });+ok('stage: replica-local → plane', near(bx.x, 110) && near(bx.y, 90) && near(bx.w, 20) && near(stg.place(0, 0).y, 85));+ok('zoomFor: 13 px text at 0.75 needs ×2.67 for 26 px', near(UIK.zoomFor(13, 0.75), 2.6667, 1e-3) && near(UIK.screenPx(13, 0.75, 2.6667), 26, 1e-3));+}++console.log(fails ? `\n${fails} FAILED` : '\nALL PASS');+process.exit(fails ? 1 : 0);diff --git a/scripts/verify_promo.py b/scripts/verify_promo.pynew file mode 100644index 0000000..87a2347--- /dev/null+++ b/scripts/verify_promo.py@@ -0,0 +1,123 @@+#!/usr/bin/env python3+"""verify_promo.py — does the cut have a rhythm, and does it carry? The checks that fail a slideshow before a human has to.++ python3 scripts/verify_promo.py film.mp4 --comp comp.html --ref ref.mp4 --shots 0,1.6,3.0,4.8,7.0,9.6,12.1,13.25,14.3++Legs (each prints a number and PASS / WARN / FAIL; only FAIL fails the verdict):+ cadence shot lengths (from --shots) must vary: coefficient of variation >= 0.25. Equal shots = slides.+ rest >= 25 % of frames dead-still (<0.5 mean abs diff at 320 px) and one quiet stretch >= 1.0 s.+ burst a window of 1.5 s holding >= 3 big changes (> 8). FAIL only when --ref has a burst and the film has none;+ otherwise WARN — a concept without hits (one element transforming, one camera move) is not a defect.+ not-flat advisory: the energy map's row profile varies (std of row means / grand mean >= 0.35). It passed the+ rejected Pocket Weather v1 (0.54) and failed the accepted v3 (0.33), so it no longer decides.+ audio (if the file has audio) peak <= -3 dBFS, 0 clipped samples, >= 15 % of 1/12 s frames quiet.+ continuity (with --comp) probe.py's carry score: FAIL < 0.5, WARN < 0.7. Every rhythm leg above passed both rejected+ Pocket Weather cuts; this one fails them (v1 0.00, v2 0.40; accepted motion-web 0.56, v3 0.75).+ curves (with --comp) FAIL when something travels more than 80 px per frame (normalised to 1920 wide, at the+ film's fps) in a film without shutter blur: a render defect, fixed by rendering with render.py. Blur is+ read from <film>.render.json (render.py writes it), else from the film itself (analyze_ref.py smear+ < .78). Soft-curve share and median t80 are printed, not judged: they did not separate accepted from+ rejected cuts (motion-web 70 %, v1 72 %, v2 57 %, v3 69 % of travel on soft curves).+ framing (with --comp and window.__meta.inFrame) FAIL when a declared id is entirely off frame at any sampled frame+ inside its window, or — marked 'whole' — not wholly inside. The one-dot film's first camera render lost its+ dot behind a snap the camera's spring couldn't follow; nothing else caught it.+ reference (with --ref) both energy maps, then stillness, cuts and the flow fingerprint side by side; no verdict.+Exit code 1 if any leg fails.+"""+import argparse, asyncio, json, os, subprocess, sys, tempfile, wave+import numpy as np+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from analyze_ref import energy, energy_map, stats, flow, SMEAR_BLUR++PEAK_PX = 80++def audio_stats(video):+ tmp = tempfile.mkdtemp(); wav = os.path.join(tmp, "a.wav")+ r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", video, "-vn", "-ac", "2", "-ar", "48000", wav], capture_output=True)+ if r.returncode != 0 or not os.path.exists(wav): return None+ w = wave.open(wav); x = np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16).reshape(-1, 2) / 32767; w.close()+ n = 4000; rms = np.array([np.sqrt((x[i:i + n] ** 2).mean()) for i in range(0, len(x) - n, n)])+ return {"peak_db": round(20 * np.log10(np.abs(x).max() + 1e-9), 1), "clipped": int((np.abs(x) >= 0.999).sum()),+ "quiet_ratio": round(float((20 * np.log10(rms + 1e-9) < -40).mean()), 3)}++def leg(name, state, detail):+ print(f" {state:4} {name:10} {detail}"); return state != "FAIL"++def film_fps(video):+ r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=r_frame_rate", "-of", "csv=p=0", video], capture_output=True, text=True).stdout.strip()+ num, _, den = r.partition("/")+ try: return max(1, int(round(float(num) / float(den or 1))))+ except ValueError: return 30++def render_info(video):+ p = os.path.splitext(video)[0] + ".render.json"+ return json.load(open(p)) if os.path.exists(p) else None++def main():+ ap = argparse.ArgumentParser(); ap.add_argument("video"); ap.add_argument("--ref", default=None); ap.add_argument("--shots", default=None)+ ap.add_argument("--comp", default=None, help="the composition the film was rendered from — adds the continuity and curves legs")+ a = ap.parse_args()+ tmp = tempfile.mkdtemp(); d, fps = energy(a.video, tmp); s = stats(d, fps); m = energy_map(d, fps)+ print(f"\n{os.path.basename(a.video)} — energy map:\n{m}\n"); oks = []+ if a.shots:+ ts = sorted(float(x) for x in a.shots.split(",")); L = np.diff(ts + [s["duration_s"]]); cv = float(L.std() / L.mean())+ oks.append(leg("cadence", "PASS" if cv >= 0.25 else "FAIL", f"shot lengths {np.round(L,2).tolist()} CV {cv:.2f} (need >= 0.25)"))+ else: print(" skip cadence (pass --shots t0,t1,… to check shot-length variety)")+ oks.append(leg("rest", "PASS" if s["still_ratio"] >= 0.25 and s["longest_quiet_s"] >= 1.0 else "FAIL", f"still {s['still_ratio']} longest quiet {s['longest_quiet_s']} s"))+ dr = sr = None+ if a.ref: dr, _ = energy(a.ref, tmp); sr = stats(dr, fps)+ if s["bursts"]: oks.append(leg("burst", "PASS", f"bursts {s['bursts']}"))+ elif sr is not None and sr["bursts"]: oks.append(leg("burst", "FAIL", f"no burst; the reference has {len(sr['bursts'])} {sr['bursts']}"))+ else: oks.append(leg("burst", "WARN", "no burst — the reference has none either" if sr is not None else "no burst — fine for a concept without hits; --ref holds it to a reference"))+ rows = [d[i:i + fps * 4].mean() for i in range(0, len(d), fps * 4)]; flat = float(np.std(rows) / (np.mean(rows) + 1e-9))+ oks.append(leg("not-flat", "PASS" if flat >= 0.35 else "WARN", f"row-profile variation {flat:.2f} (advisory, >= 0.35)"))+ au = audio_stats(a.video)+ if au: oks.append(leg("audio", "PASS" if au["peak_db"] <= -3 and au["clipped"] == 0 and au["quiet_ratio"] >= 0.15 else "FAIL", f"peak {au['peak_db']} dBFS clipped {au['clipped']} quiet {au['quiet_ratio']}"))+ else: print(" skip audio (no audio track)")+ info = render_info(a.video)+ ff = flow(a.video) if a.ref or (a.comp and not info) else None+ if a.comp:+ import probe+ vfps = film_fps(a.video)+ res = asyncio.run(probe.collect(a.comp, fps=vfps)); ct = probe.continuity(res); cv = probe.curves(res)+ bare = [e["t"] for e in ct["events"] if not e["exempt"] and e["kind"] == "bare"]+ state = "FAIL" if ct["score"] < 0.5 else "WARN" if ct["score"] < 0.7 else "PASS"+ oks.append(leg("continuity", state, f"carry score {ct['score']:.2f} over {ct['considered']} boundaries; nothing carried at {bare or '—'} (probe.py lists each)"))+ if info:+ blurred = info.get("shutter", 0) > 0+ blur = f"shutter {info['shutter']:g}° (render.json)" if blurred else "rendered with --shutter 0"+ else:+ sm = ff["smear_median"] if ff else None+ blurred = sm is not None and sm < SMEAR_BLUR+ blur = ("no render.json and no opencv to read the film: assumed sharp" if ff is None else+ "no render.json, and no fast frames in the film to read blur from" if sm is None else+ f"no render.json, film smear {sm:g} ({'blurred' if blurred else 'sharp'})")+ state = "FAIL" if cv["peak"] > PEAK_PX and not blurred else "PASS"+ where = f" ({cv['peak_at'][0]} at {cv['peak_at'][1]:.2f} s)" if cv["peak_at"] else ""+ med = f"{cv['t80_median']:.2f}" if cv["t80_median"] is not None else "—"+ oks.append(leg("curves", state, f"peak {cv['peak']:.0f} px/frame @{vfps} fps{where}, {blur}; soft curves {cv['soft_share'] * 100:.0f} % of travel, median t80 {med}"))+ fr = probe.framing(res)+ if fr:+ off = {k: v["bad"] for k, v in fr.items() if v["bad"]}+ detail = ("; ".join(f"{k} off frame at {len(b)} samples {b[:6]}" for k, b in off.items()) if off else+ "; ".join(f"{k} {'wholly ' if v['whole'] else ''}in frame {v['window'][0]:g}–{v['window'][1]:g} s ({v['samples']} samples)" for k, v in fr.items()))+ oks.append(leg("framing", "FAIL" if off else "PASS", detail))+ else:+ print(" skip framing (declare window.__meta.inFrame = {id: [t0, t1] | [t0, t1, 'whole']} to check what must stay in frame)")+ if res.get("failed"):+ print(f" !! __seek threw at {len(res['failed'])} samples (first t={res['failed'][0][0]}): {res['failed'][0][1]}")+ if a.ref:+ print(f"\nreference — energy map:\n{energy_map(dr, fps)}")+ rows = [("still", s["still_ratio"], sr["still_ratio"]), ("low", s["low_ratio"], sr["low_ratio"]), ("cuts", len(s["cuts"]), len(sr["cuts"])),+ ("bursts", len(s["bursts"]), len(sr["bursts"])), ("quiet s", s["longest_quiet_s"], sr["longest_quiet_s"])]+ fr = flow(a.ref) if ff else None+ if ff and fr:+ rows += [("peak px/f", ff["peak"], fr["peak"]), ("t80 median", ff["t80_median"], fr["t80_median"]),+ ("soft %", round(ff["soft_share"] * 100), round(fr["soft_share"] * 100)), ("smear", ff["smear_median"], fr["smear_median"])]+ print(f"\n {'film':>8} {'reference':>10}")+ for k, x, y in rows:+ print(f" {k:11} {'—' if x is None else x:>8} {'—' if y is None else y:>10}")+ print("\nVERDICT:", "PASS" if all(oks) else "FAIL"); sys.exit(0 if all(oks) else 1)++if __name__ == "__main__":+ main()diff --git a/scripts/vo_tools.py b/scripts/vo_tools.pynew file mode 100644index 0000000..c18dc8b--- /dev/null+++ b/scripts/vo_tools.py@@ -0,0 +1,183 @@+#!/usr/bin/env python3+"""vo_tools.py — narration for a film: voice lines, word times, line starts, subtitles. One line of lines.txt = one VO line.++ KPY=~/.cache/kokoro/venv/bin/python+ $KPY vo_tools.py tts vo/lines.txt --voice bf_emma --lang en-gb --out vo/bf_emma # Kokoro, local; see --lang+ $KPY vo_tools.py tts vo/ja/lines.txt --read vo/ja/read.txt --voice jf_alpha --lang ja --out vo/ja/jf_alpha+ python3 vo_tools.py words vo/bf_emma --lang en --lines vo/lines.txt # faster-whisper → words.json+ python3 vo_tools.py plan vo/bf_emma --lead 0.5 --breath 0.45 --gap 7:2.45 # → plan.json: durs, VO starts+ python3 vo_tools.py subs vo/lines.txt vo/bf_emma --max 42 # → subs.json [[t0, t1, text], …]++tts each line → t<i>.wav (48 kHz mono), silence trimmed and inner pauses squeezed to --gap-in (Kokoro stops ~0.6 s at+ every full stop; 0.28 s reads as one speaker talking). `--lines 2,4` renders only those; `--sample` writes one+ joined <voice>.m4a instead of per-line files (auditions). Japanese: Kokoro's default espeak cannot read kanji —+ pass --read, a kana reading of each line (names spelled as they are said: エクセル, エイチティーエムエル),+ phonemised by misaki[ja] (+ unidic-lite) in the Kokoro venv. The subtitles still use lines.txt.+words word-level times per line (faster-whisper small, CPU). English: when the count matches the line, the line's own+ words replace whisper's spelling (it hears brand names wrong). Japanese comes back as characters in whatever+ script whisper chose (kana for a katakana name, even a wrong kanji) — use it to find anchors by ear-order, not text.+plan line starts: --lead before line 1, --breath between lines, --gap i:s for a longer music gap before line i.+ Continuous narration is the default; a gap is for a stretch where the picture carries on its own.+subs each line split at its punctuation into chunks of at most --max characters (Latin) / --max-cjk (CJK), timed+ from the words: by word index for English, for CJK by the reading's proportion snapped to the nearest pause.+"""+import argparse, json, os, re, subprocess, sys++SR = 48000+++def read_lines(p):+ return [l.strip() for l in open(p, encoding="utf-8") if l.strip()]+++def is_cjk(s):+ return bool(re.search(r"[-ヿ㐀-鿿가-]", s))+++# ── tts ──────────────────────────────────────────────────────────────────────────────────────────────────────────────+def trim(x, thr=10 ** (-45 / 20), gap=0.28):+ import numpy as np+ idx = np.where(np.abs(x) > thr)[0]+ x = x[max(0, idx[0] - 240): idx[-1] + 2400] if len(idx) else x+ env = np.convolve(np.abs(x), np.ones(480) / 480, "same") > thr+ out, i, n, keep = [], 0, len(x), int(gap * SR)+ while i < n:+ j = i+ while j < n and env[j] == env[i]:+ j += 1+ chunk = x[i:j]+ if not env[i] and len(chunk) > keep and 0 < i and j < n:+ h = keep // 2; chunk = np.concatenate([chunk[:h], chunk[-h:]])+ out.append(chunk); i = j+ return np.concatenate(out)+++def cmd_tts(a):+ import numpy as np, soundfile as sf+ from kokoro_onnx import Kokoro+ from scipy.signal import resample_poly+ K = os.path.expanduser("~/.cache/kokoro")+ tts = Kokoro(os.path.join(K, "kokoro-v1.0.onnx"), os.path.join(K, "voices-v1.0.bin"))+ lines = read_lines(a.read or a.lines)+ g2p = None+ if a.lang == "ja":+ from misaki import ja+ g2p = ja.JAG2P()+ pick = [int(i) for i in a.pick.split(",")] if a.pick else list(range(1, len(lines) + 1))+ os.makedirs(a.out, exist_ok=True); parts, durs = [], []+ for i in pick:+ if g2p:+ ph, _ = g2p(lines[i - 1]); x, sr = tts.create(ph, voice=a.voice, speed=a.speed, is_phonemes=True)+ else:+ x, sr = tts.create(lines[i - 1], voice=a.voice, speed=a.speed, lang=a.lang)+ x = trim(resample_poly(np.asarray(x, np.float64), SR, sr), gap=a.gap_in).astype(np.float32); durs.append(len(x) / SR)+ if not a.sample:+ sf.write(os.path.join(a.out, f"t{i}.wav"), x, SR)+ parts += [x, np.zeros(int(0.45 * SR), np.float32)]+ wav = os.path.join(a.out, f"{a.voice}.wav"); sf.write(wav, np.concatenate(parts), SR)+ subprocess.run(["ffmpeg", "-v", "quiet", "-y", "-i", wav, "-c:a", "aac", "-b:a", "160k", wav[:-4] + ".m4a"]); os.remove(wav)+ print(a.voice, "lines", pick, " ".join(f"{d:.2f}" for d in durs), f"total {sum(durs):.1f}s →", wav[:-4] + ".m4a")+++# ── words ────────────────────────────────────────────────────────────────────────────────────────────────────────────+def wavs(d):+ return sorted((int(m.group(1)), os.path.join(d, f)) for f in os.listdir(d) for m in [re.match(r"t(\d+)\.wav$", f)] if m)+++def cmd_words(a):+ from faster_whisper import WhisperModel+ m = WhisperModel(a.model, device="cpu", compute_type="int8")+ lines = read_lines(a.lines) if a.lines else None+ out = {}+ for i, p in wavs(a.dir):+ segs, _ = m.transcribe(p, language=a.lang, word_timestamps=True)+ w = [[x.word.strip(), round(x.start, 2), round(x.end, 2)] for s in segs for x in s.words]+ if lines and not is_cjk(lines[i - 1]):+ own = lines[i - 1].split()+ if len(own) == len(w):+ w = [[o, s, e] for o, (_, s, e) in zip(own, w)]+ else:+ print(f" line {i}: whisper heard {len(w)} words, the line has {len(own)} — kept whisper's spelling", file=sys.stderr)+ out[str(i)] = w+ print(i, " ".join(f"{x[0]}@{x[1]:.2f}" for x in w))+ json.dump(out, open(os.path.join(a.dir, "words.json"), "w"), ensure_ascii=False)+++# ── plan ─────────────────────────────────────────────────────────────────────────────────────────────────────────────+def dur(p):+ return float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", p], capture_output=True, text=True).stdout)+++def cmd_plan(a):+ gaps = {int(k): float(v) for k, v in (g.split(":") for g in a.gap)}+ ds = [dur(p) for _, p in wavs(a.dir)]; vo, t = [], a.lead+ for i, d in enumerate(ds, 1):+ if i > 1:+ t += gaps.get(i, a.breath)+ vo.append(round(t, 2)); t += d+ plan = {"durs": [round(d, 3) for d in ds], "VO": vo, "end": round(t, 2)}+ json.dump(plan, open(os.path.join(a.dir, "plan.json"), "w")); print(json.dumps(plan))+++# ── subs ─────────────────────────────────────────────────────────────────────────────────────────────────────────────+def clauses(line):+ cj = is_cjk(line)+ parts = re.findall(r"[^、。?!,.?!]+[、。?!,.?!」』]*\s*" if cj else r"[^,.?!;:]+[,.?!;:]*\s*", line)+ return [p.strip() for p in parts if p.strip()] or [line]+++def chunks(line, mx):+ """→ [(text, n_clauses)]: clauses merged left to right while they fit in mx and no sentence ends between them;+ a stub under mx/3 (「だから、」, "So,") joins the next clause even if that runs to 1.3 × mx."""+ cj, out = is_cjk(line), []+ for p in clauses(line):+ if out and not re.search(r"[。?!.?!]$", out[-1][0]) and (len(out[-1][0]) + len(p) <= mx or (len(out[-1][0]) < mx / 3 and len(out[-1][0]) + len(p) <= 1.3 * mx)):+ out[-1] = (out[-1][0] + ("" if cj else " ") + p, out[-1][1] + 1)+ else:+ out.append((p, 1))+ return out+++def morae(s):+ """rough spoken length of a Japanese string: kanji ~2 morae, small kana and punctuation ~0, the rest 1"""+ return sum(2 if "\u3400" <= ch <= "\u9fff" else 0 if ch in "ゃゅょャュョぁぃぅぇぉァィゥェォ、。?!「」 " else 1 for ch in s)+++def cmd_subs(a):+ lines = read_lines(a.lines); reads = read_lines(a.read) if a.read else lines+ words = json.load(open(os.path.join(a.dir, "words.json"))); plan = json.load(open(os.path.join(a.dir, "plan.json")))+ subs = []+ for i, line in enumerate(lines, 1):+ t0, d, w = plan["VO"][i - 1], plan["durs"][i - 1], words.get(str(i), [])+ cs, starts = chunks(line, a.max_cjk if is_cjk(line) else a.max), [0.0]+ if is_cjk(line):+ # the reading keeps the line's punctuation: the share of its morae spoken before a chunk says roughly+ # when the chunk starts; snap to the widest pause within 0.8 s of that, preferring the nearer+ rc = clauses(reads[i - 1]) if len(clauses(reads[i - 1])) == len(clauses(line)) else clauses(line)+ n, tot = 0, sum(morae(c) for c in rc)+ for _, k in cs[:-1]:+ n += k; est = d * sum(morae(c) for c in rc[:n]) / tot+ gaps = [(w[j][1] - w[j - 1][2] - 0.3 * abs(w[j][1] - est), w[j][1]) for j in range(1, len(w)) if abs(w[j][1] - est) < 0.8]+ starts.append(max(gaps)[1] if gaps else est)+ else:+ n = 0+ for c, _ in cs[:-1]:+ n += len(c.split()); starts.append(w[n][1] if n < len(w) else d * n / max(1, len(line.split())))+ for j, (c, _) in enumerate(cs):+ s0 = t0 + starts[j] - (0.05 if j == 0 else 0)+ e = t0 + starts[j + 1] if j + 1 < len(cs) else t0 + d + 0.05+ subs.append([round(s0, 2), round(e, 2), c])+ json.dump(subs, open(os.path.join(a.dir, "subs.json"), "w"), ensure_ascii=False)+ for q in subs:+ print(f"{q[0]:6.2f} {q[1]:6.2f} {q[2]}")+++ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter); sp = ap.add_subparsers(dest="cmd", required=True)+p = sp.add_parser("tts"); p.add_argument("lines"); p.add_argument("--voice", required=True); p.add_argument("--lang", default="en-us", help="en-us | en-gb | ja")+p.add_argument("--read", help="a reading per line to speak instead (Japanese: kana)"); p.add_argument("--speed", type=float, default=1.0); p.add_argument("--gap-in", type=float, default=0.28)+p.add_argument("--lines", dest="pick", default=""); p.add_argument("--sample", action="store_true"); p.add_argument("--out", required=True); p.set_defaults(f=cmd_tts)+p = sp.add_parser("words"); p.add_argument("dir"); p.add_argument("--lang", default="en"); p.add_argument("--lines"); p.add_argument("--model", default="small"); p.set_defaults(f=cmd_words)+p = sp.add_parser("plan"); p.add_argument("dir"); p.add_argument("--lead", type=float, default=0.5); p.add_argument("--breath", type=float, default=0.45)+p.add_argument("--gap", nargs="*", default=[], help="i:s — s seconds before line i instead of the breath"); p.set_defaults(f=cmd_plan)+p = sp.add_parser("subs"); p.add_argument("lines"); p.add_argument("dir"); p.add_argument("--read"); p.add_argument("--max", type=int, default=42); p.add_argument("--max-cjk", type=int, default=20); p.set_defaults(f=cmd_subs)+a = ap.parse_args(); a.f(a)diff --git a/templates/comp.html b/templates/comp.htmlnew file mode 100644index 0000000..bfd8d62--- /dev/null+++ b/templates/comp.html@@ -0,0 +1,235 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="utf-8">+<title>onetake · composition</title>+<!-- FONTS: the motion-web film shipped subset faces as faces.css (families 'Sans','Serif','Mono', generated with+ motion-web's subset_fonts.py pack --text-from). Without it the stacks below fall back to Inter / Georgia /+ system mono. Add <link rel="stylesheet" href="faces.css"> once you have real faces; the render waits on document.fonts.ready. -->+<style>+:root{ --bg:#f8f8f6; --ink:#161616; --grey:#8f8f8b; --green:#17a05e; --red:#b42323; --card:#fff; --line:#e8e8e4; }+html,body{margin:0;width:1920px;height:1080px;overflow:hidden;background:var(--bg)}+body{font-family:'Sans',Inter,system-ui,sans-serif;color:var(--ink);font-feature-settings:"ss01","cv11"}+#stage{position:absolute;inset:0;overflow:hidden;background:var(--bg)}+.abs{position:absolute;left:0;top:0;will-change:transform,opacity}+/* scene 1 words */+#w1{font-size:64px;font-weight:500;letter-spacing:-.02em;white-space:nowrap;left:0;right:0;top:430px;text-align:center}+#w1 span{display:inline-block;margin:0 .14em}+#w1 .red{color:var(--red)}+/* wordmark */+#mark{font-family:'Serif',Georgia,serif;font-size:132px;line-height:1;letter-spacing:-.01em;white-space:nowrap;transform-origin:50% 50%}+#mark span{display:inline-block;transform-origin:50% 88%}+#tag{font-size:30px;font-weight:500;color:var(--ink);white-space:nowrap;transform-origin:50% 50%}+#tag b{color:var(--green);font-weight:600;display:inline-block;transform-origin:50% 70%}+.dot{position:absolute;border-radius:50%;background:var(--ink)}+/* cards */+.card{position:absolute;background:var(--card);border:1px solid var(--line);border-radius:18px;+ box-shadow:0 24px 60px -24px rgba(20,20,20,.22),0 2px 6px rgba(20,20,20,.05);will-change:transform,opacity,filter;transform-origin:50% 50%}+#prompt{width:760px;height:168px;left:580px;top:456px}+#prompt .txt{position:absolute;left:34px;top:28px;font-size:29px;color:var(--ink);white-space:pre;font-weight:450}+#prompt .txt i{display:inline-block;width:2px;height:30px;background:var(--ink);vertical-align:-6px;margin-left:2px}+#prompt .row{position:absolute;left:24px;right:24px;bottom:20px;height:48px}+#prompt .pill{position:absolute;top:0;height:44px;padding:0 18px;border:1px solid var(--line);border-radius:999px;font-size:20px;line-height:44px;color:var(--grey)}+#prompt .send{position:absolute;right:0;top:0;width:44px;height:44px;border-radius:50%;background:var(--ink);will-change:transform,background}+#prompt .send:after{content:"";position:absolute;left:15px;top:13px;width:12px;height:12px;border-left:2.5px solid #fff;border-top:2.5px solid #fff;transform:rotate(45deg)}+#panel{width:820px;left:550px;top:300px;padding:26px 30px 22px}+#panel h4{margin:0 0 18px;font-size:22px;font-weight:600;letter-spacing:-.01em}+#panel h4 small{color:var(--grey);font-weight:500;margin-left:12px;font-family:'Mono',monospace;font-size:18px}+#panel .ln{display:flex;align-items:center;gap:16px;height:52px;font-size:24px;font-weight:450;border-top:1px solid var(--line)}+#panel .ln .bx{width:24px;height:24px;border-radius:7px;border:1.5px solid #cfcfca;position:relative;flex:none;will-change:transform,background}+#panel .ln .bx:after{content:"";position:absolute;left:7px;top:3px;width:6px;height:12px;border-right:2.5px solid #fff;border-bottom:2.5px solid #fff;transform:rotate(45deg);opacity:0}+#panel .ln.on .bx{background:var(--green);border-color:var(--green)}+#panel .ln.on .bx:after{opacity:1}+#panel .ln.on .t{color:var(--grey);text-decoration:line-through;text-decoration-color:#c9c9c4}+#panel .ln .t{font-family:'Mono',monospace;font-size:23.5px}+#panel .ln .t b{color:var(--green);font-weight:400}+#panel .ln.on.pass .t{text-decoration:none;color:var(--ink)}+/* flying screens */+.screen{position:absolute;width:1000px;height:625px;left:460px;top:228px;border-radius:14px;overflow:hidden;background:#fff;+ box-shadow:0 40px 90px -30px rgba(20,20,20,.35),0 0 0 1px rgba(0,0,0,.05);will-change:transform,filter,opacity;transform-origin:50% 50%}+.screen img{position:absolute;left:0;top:0;width:1000px;height:625px;display:block}+.screen .lab{position:absolute;left:0;right:0;bottom:-46px;text-align:center;font-family:'Mono',monospace;font-size:22px;color:var(--grey)}+/* micro cards */+.mini{width:460px;height:270px}+.mini canvas{position:absolute;left:0;top:0;width:460px;height:270px}+.mini .cap{position:absolute;left:22px;top:16px;font-family:'Mono',monospace;font-size:19px;color:var(--grey)}+/* hold beat: browser window */+#win{position:absolute;left:260px;top:120px;width:1400px;height:840px;border-radius:16px;overflow:hidden;background:#fff;+ box-shadow:0 50px 120px -40px rgba(20,20,20,.35),0 0 0 1px rgba(0,0,0,.06);transform-origin:50% 50%;will-change:transform,opacity}+#win .bar{position:absolute;left:0;right:0;top:0;height:44px;background:#f1f1ee;border-bottom:1px solid var(--line)}+#win .bar i{position:absolute;top:15px;width:12px;height:12px;border-radius:50%;background:#d9d9d4}+#win .bar .url{position:absolute;left:50%;top:10px;transform:translateX(-50%);width:420px;height:24px;border-radius:6px;background:#fff;font-family:'Mono',monospace;font-size:14px;color:var(--grey);text-align:center;line-height:24px}+#win img{position:absolute;left:0;top:44px;width:1400px;height:875px;display:block}+/* staccato + end */+#stac{left:0;right:0;top:500px;text-align:center;font-size:66px;font-weight:800;letter-spacing:.02em;text-transform:uppercase}+#end{position:absolute;inset:0;background:#0b0b0b;display:flex;align-items:center;justify-content:center;font-family:'Serif',Georgia,serif;font-size:128px;color:#fff;letter-spacing:-.01em}+/* cursor */+#cursor{position:absolute;left:0;top:0;width:30px;height:40px;will-change:transform;filter:drop-shadow(0 2px 5px rgba(0,0,0,.3))}+#hud{position:absolute;right:14px;bottom:10px;font:13px 'Mono',monospace;color:#c00;display:none}+</style>+</head>+<body>+<div id="stage">+ <div id="w1" class="abs"><span>Web motion</span><span>is usually</span><span class="red">decoration.</span></div>+ <div id="mark" class="abs"></div>+ <div id="tag" class="abs">makes it <b id="mv">move</b></div>+ <div id="prompt" class="card"><div class="txt"><span id="ptxt"></span><i id="caret"></i></div>+ <div class="row"><div class="pill" style="left:0">+</div><div class="pill" style="left:66px">motion-web</div><div class="send" id="send"></div></div></div>+ <div id="panel" class="card"><h4>Build<small>motion-web · handfeel-tune</small></h4><div id="lines"></div></div>+ <div id="screens"></div>+ <div id="minis"></div>+ <div id="win"><div class="bar"><i style="left:16px"></i><i style="left:36px"></i><i style="left:56px"></i><div class="url">localhost:5173 — char-curtain</div></div><img id="winimg" alt=""></div>+ <div id="stac" class="abs"></div>+ <div id="end">motion-web</div>+ <svg id="cursor" viewBox="0 0 34 44"><path d="M4 3 L30 22 L18 24 L26 40 L20 43 L12 27 L4 36 Z" fill="#111" stroke="#fff" stroke-width="2.5" stroke-linejoin="round"/></svg>+ <div id="hud"></div>+</div>+<script src="motion.js"></script><!-- lib/motion.js, copied next to this file → window.OM -->+<script>+// ══════════════════════════════════════════════════════════════════════════════════════════════+// onetake composition template — everything below is a pure function of t (seconds).+// Contract: window.__seek(t) → Promise (resolves after this frame's images are decoded), window.__ready,+// window.__meta {dur,fps,w,h}. Query: ?play (real-time loop) ?t=6.4&hud (pin a frame).+// EDIT HERE (in order): 1 INFO/FR after record_footage.py · 2 beats · 3 copy (PROMPT_TEXT, LINES, SCREENS,+// MINIS, STAC) · 4 the HAND knots so the pointer causes what the footage shows · 5 nothing else+// until stills.py looks right. The moves are OM.* from motion.js — call them, do not re-derive springs+// inline. Catalogue and sheets: references/motion-library.md, gallery/sheets/.+// ══════════════════════════════════════════════════════════════════════════════════════════════+// ────────────────────────────────────────── timeline ──────────────────────────────────────────+const FPS=30, DUR=15, FR='../footage/frames/'; // FPS = footage frame rate (record_footage.py extracts 30); DUR = film length+window.__meta={dur:DUR,fps:FPS,w:1920,h:1080}; // render.py reads dur from here+// from footage/info.json — n frames, mark = frame where the input began+const INFO={"critter":{"n":278,"mark":108},"demo-after":{"n":215,"mark":98},"press-stack":{"n":316,"mark":176},"char-curtain":{"n":247,"mark":98}};+// beats (seconds) — shot lengths vary ≥4× on purpose: words .35 s apart, holds 1.15 s, staccato .22 s. verify_promo.py checks CV ≥ .25+const W1=[0.15,0.50,0.92], W1_OUT=1.55;+const MARK_IN=1.65, TAG_IN=2.25, POP=2.32, MARK_UP=3.0;+const PROMPT_IN=2.95, TYPE0=3.15, TYPE_CPS=38, CLICK=4.45, PROMPT_OUT=4.75;+const PANEL_IN=4.85, LINE0=5.15, LINE_DT=0.24, PANEL_OUT=7.0;+const SCREENS=[ {name:'critter', label:'spring follow · velocity lean', t:7.05},+ {name:'demo-after', label:'jelly · velocity tilt', t:7.95},+ {name:'press-stack',label:'sticky stack · scroll choreography', t:8.85} ];+const SCREEN_HOLD=0.9;+const MINIS=[ {kind:'magnet', cap:'magnetic button', x:470, y:400, t:9.55, out:10.40},+ {kind:'follow', cap:'spring follow', x:1090, y:330, t:10.00,out:10.95},+ {kind:'jelly', cap:'jelly · soft body',x:700, y:520, t:10.75,out:11.60},+ {kind:'verlet', cap:'verlet string', x:1180, y:420, t:11.35,out:12.15} ];+const WIN_IN=12.1, WIN_OUT=13.25;+const STAC=[[13.25,'motion'],[13.50,'is'],[13.72,'the'],[13.94,'material']], STAC_END=14.3;+const END_T=14.3;++// ────────────────────────────────────────── math: motion.js ──────────────────────────────────────────+const {clamp, lerp, sstep, ssstep, spring:spr, ring, spline} = OM;++// ────────────────────────────────────────── DOM ──────────────────────────────────────────+const $=id=>document.getElementById(id);+const markEl=$('mark'); const MARKL=[...'motion-web'].map(ch=>{const s=document.createElement('span');s.textContent=ch;markEl.appendChild(s);return s;});+const PROMPT_TEXT='make the hero feel alive — springs, not fades';+const LINES=[['Intent: handfeel-tune'],['Read handfeel.md · §1 springs, §7 following'],['Render layer: canvas2d · web font, not the system stack'],['Spring k=90 · damp .86 · velocity coupling'],['Jelly wobble · squash along the leap'],['Reduced-motion fallback · nothing hidden'],['verify_case.py → <b>VERDICT: PASS</b>','pass']];+const lineEls=LINES.map(([html,cls])=>{const d=document.createElement('div');d.className='ln'+(cls?' '+cls:'');d.innerHTML=`<div class="bx"></div><div class="t">${html}</div>`;$('lines').appendChild(d);return d;});+const screenEls=SCREENS.map(s=>{const d=document.createElement('div');d.className='screen';d.innerHTML=`<img alt=""><div class="lab">${s.label}</div>`;$('screens').appendChild(d);s.el=d;s.img=d.querySelector('img');s.cur='';Object.assign(s,INFO[s.name]);return d;});+const miniEls=MINIS.map(m=>{const d=document.createElement('div');d.className='card mini';d.style.left=m.x+'px';d.style.top=m.y+'px';d.innerHTML=`<canvas width="920" height="540"></canvas><div class="cap">${m.cap}</div>`;$('minis').appendChild(d);m.el=d;m.cv=d.querySelector('canvas');m.ctx=m.cv.getContext('2d');return d;});+const WIN=INFO['char-curtain']; let winCur='';++// ────────────────────────────────────────── the hand ──────────────────────────────────────────+// one continuous path through the whole film; sims read the same spline so cause and effect agree+const SEND={x:580+760-24-22, y:456+168-20-22}; // centre of the send button+const M=MINIS; const mc=(m,fx,fy)=>({x:m.x+fx*460,y:m.y+fy*270});+const HAND=[+ {t:3.90,x:1750,y:1160},{t:4.30,x:SEND.x+2,y:SEND.y+2},{t:4.75,x:SEND.x+2,y:SEND.y+2},{t:5.30,x:1560,y:980},{t:9.40,x:1500,y:1000},+ // magnetic: approach from below-right, sit on the button, click at 10.05+ {t:9.70,...mc(M[0],.92,1.10)},{t:10.02,...mc(M[0],.56,.60)},{t:10.05,...mc(M[0],.5,.58)},{t:10.28,...mc(M[0],.5,.58)},+ // spring follow: a lazy figure inside the second card+ {t:10.32,...mc(M[1],.18,.62)},{t:10.50,...mc(M[1],.80,.36)},{t:10.66,...mc(M[1],.30,.80)},{t:10.82,...mc(M[1],.72,.50)},{t:10.92,...mc(M[1],.55,.55)},+ // jelly: one fast flick straight through the disc+ {t:11.00,...mc(M[2],.10,.62)},{t:11.13,...mc(M[2],.90,.48)},{t:11.40,...mc(M[2],1.02,.40)},+ // verlet: sweep through the hanging string and back+ {t:11.58,...mc(M[3],.12,.60)},{t:11.74,...mc(M[3],.88,.56)},{t:11.90,...mc(M[3],.40,.66)},{t:12.15,...mc(M[3],.45,1.3)},+ {t:12.40,x:1200,y:1250},+];+const hand=t=>spline(HAND,t);+const CLICKS=[CLICK,10.05];++// ────────────────────────────────────────── live sims (deterministic, precomputed at 240 Hz by OM.sim) ──────────────────────────────────────────+// magnetic button · spring-follow dot · jelly disc · verlet string — all driven by the same hand spline+function simulate(){ const [mg,fl,jl,vl]=M; mg.sim=OM.sim.magnet(mg,hand); fl.sim=OM.sim.follow(fl,hand); jl.sim=OM.sim.jelly(jl,hand); vl.sim=OM.sim.verlet(vl,hand); }++// ────────────────────────────────────────── drawing the minis ──────────────────────────────────────────+function drawMini(m,t){+ const c=m.ctx; c.setTransform(2,0,0,2,0,0); c.clearRect(0,0,460,270);+ const ink='#161616', green='#17a05e';+ if(m.kind==='magnet'){ const [x,y]=m.sim.at(t); const B=m.sim.B; const p=OM.press(t,CLICKS[1],{depth:0.10,flash:0.35}); const sq=p.sq;+ c.save(); c.translate(B.x+x,B.y+y); c.scale(1+sq,1-sq*1.4);+ c.fillStyle=p.active?green:ink; roundRect(c,-92,-30,184,60,30); c.fill();+ c.fillStyle='#fff'; c.font='500 21px Sans'; c.textAlign='center'; c.textBaseline='middle'; c.fillText(p.down?'Added':'Add to cart',0,1); c.restore(); }+ if(m.kind==='follow'){ const [x,y,vx,vy]=m.sim.at(t); const q=OM.squash(vx,vy);+ c.save(); c.translate(x,y); c.rotate(q.ang); c.scale(q.sx,q.sy); c.fillStyle='#2f6fb5'; c.beginPath(); c.arc(0,0,26,0,Math.PI*2); c.fill(); c.restore();+ // faint target ring where the hand is, so the lag reads+ const h=hand(t); if(h[0]>m.x&&h[0]<m.x+460&&h[1]>m.y&&h[1]<m.y+270){ c.strokeStyle='#d0d0cb'; c.lineWidth=1.5; c.beginPath(); c.arc(h[0]-m.x,h[1]-m.y,10,0,Math.PI*2); c.stroke(); } }+ if(m.kind==='jelly'){ const r=m.sim.at(t); const {N,R0,C}=m.sim; const pts=[]; for(let i=0;i<N;i++){const th=i/N*Math.PI*2; pts.push([C.x+Math.cos(th)*R0*(1+r[i]),C.y+Math.sin(th)*R0*(1+r[i])]);}+ c.fillStyle='#f6c9ab'; c.beginPath(); c.moveTo(pts[0][0],pts[0][1]); for(let i=0;i<N;i++){const p0=pts[(i+N-1)%N],p1=pts[i],p2=pts[(i+1)%N],p3=pts[(i+2)%N]; c.bezierCurveTo(p1[0]+(p2[0]-p0[0])/6,p1[1]+(p2[1]-p0[1])/6,p2[0]-(p3[0]-p1[0])/6,p2[1]-(p3[1]-p1[1])/6,p2[0],p2[1]);} c.closePath(); c.fill(); }+ if(m.kind==='verlet'){ const s=m.sim.at(t), N=m.sim.N; c.strokeStyle=ink; c.lineWidth=2.5; c.lineCap='round'; c.beginPath(); c.moveTo(s[0],s[1]); for(let i=1;i<N;i++) c.lineTo(s[i*2],s[i*2+1]); c.stroke();+ c.fillStyle=ink; for(let i=0;i<N;i++){ c.beginPath(); c.arc(s[i*2],s[i*2+1],i===N-1?7:3.2,0,Math.PI*2); c.fill(); } }+}+function roundRect(c,x,y,w,h,r){ c.beginPath(); c.moveTo(x+r,y); c.arcTo(x+w,y,x+w,y+h,r); c.arcTo(x+w,y+h,x,y+h,r); c.arcTo(x,y+h,x,y,r); c.arcTo(x,y,x+w,y,r); c.closePath(); }++// ────────────────────────────────────────── seek ──────────────────────────────────────────+function place(el,x,y,s=1,op=1,blur=0,extra=''){ el.style.opacity=op; el.style.transform=`translate(${x.toFixed(1)}px,${y.toFixed(1)}px) scale(${s.toFixed(4)}) ${extra}`; el.style.filter=blur>0.2?`blur(${blur.toFixed(1)}px)`:'none'; }+let markW=0, tagW=0;+function seek(t){+ const pending=[];+ // 1 · words+ const w1=$('w1'); const out1=sstep(W1_OUT,W1_OUT+0.22,t); w1.style.opacity=1-out1; w1.style.transform=`translateY(${(-out1*40).toFixed(1)}px)`;+ [...w1.children].forEach((s,i)=>{ const w=OM.wordRise(t,W1[i]); s.style.opacity=w.op; s.style.transform=`translateY(${w.y.toFixed(1)}px) scale(${w.s.toFixed(4)})`; });+ // 2 · wordmark types in, tag pops, confetti; then it shrinks to the top-left and stays as the header+ const up=ssstep(MARK_UP,MARK_UP+0.55,t);+ const mx=lerp(960-markW/2, 72, up), my=lerp(400, 44, up), ms=lerp(1,0.34,up);+ const markVis = t>=MARK_IN && t<END_T;+ place(markEl,mx,my,ms,markVis?1:0,0); markEl.style.transformOrigin='0 0';+ MARKL.forEach((s,i)=>{ const d=OM.letterDrop(t,MARK_IN,i);+ const sq=d.sq*(up<1?1:0); // moving fast = flattened; it recovers as the spring settles+ s.style.opacity=d.op; s.style.transform=`translateY(${d.y.toFixed(1)}px) scale(${(1+sq*0.6).toFixed(4)},${(1-sq).toFixed(4)})`; });+ const tg=OM.wordRise(t,TAG_IN,{zeta:0.55,omega:20,dist:18}); const tagOp = t<MARK_UP ? tg.op : 1-ssstep(MARK_UP,MARK_UP+0.3,t);+ place($('tag'),960-tagW/2,548+tg.y,1,tagOp);+ { const w=OM.impact(t,TAG_IN+0.12,{decay:7,omega:22,sqx:0.16,sqy:0.20}); $('mv').style.transform=`scale(${w.sx.toFixed(4)},${w.sy.toFixed(4)})`; }+ // 3 · prompt card: type, then the hand clicks send+ { const el=$('prompt'); const ei=OM.popIn(t,PROMPT_IN), eo=OM.liftOut(t,PROMPT_OUT); const vis=t>=PROMPT_IN-0.05&&t<PROMPT_OUT+0.3;+ place(el,0,ei.dy+eo.dy,ei.s*eo.s,vis?ei.op*eo.op:0,eo.blur);+ const ty=OM.typeOn(t,TYPE0,PROMPT_TEXT,{cps:TYPE_CPS}); $('ptxt').textContent=ty.str;+ $('caret').style.opacity = ty.caret;+ const p=OM.press(t,CLICK); $('send').style.transform=`scale(${p.s.toFixed(3)})`; $('send').style.background = p.active?'var(--green)':'var(--ink)'; }+ // 4 · build panel: lines check off one by one+ { const el=$('panel'); const ei=OM.popIn(t,PANEL_IN), eo=OM.liftOut(t,PANEL_OUT); const vis=t>=PANEL_IN-0.05&&t<PANEL_OUT+0.3;+ place(el,0,ei.dy+eo.dy,ei.s*eo.s,vis?ei.op*eo.op:0,eo.blur);+ lineEls.forEach((ln,i)=>{ const tk=OM.tick(t,LINE0+i*LINE_DT); ln.classList.toggle('on',tk.on); ln.querySelector('.bx').style.transform=`scale(${tk.s})`;+ const reveal=sstep(PANEL_IN+0.05+i*0.05,PANEL_IN+0.25+i*0.05,t); ln.style.opacity=reveal; }); }+ // 5 · three pages fly through, tilted, blurred on the way in and out+ SCREENS.forEach((s,i)=>{ const fly=OM.flyThrough(t,s.t,SCREEN_HOLD); if(!fly.visible){ s.el.style.opacity=0; return; }+ s.el.style.opacity=fly.op; s.el.style.filter=fly.blur>0.3?`blur(${fly.blur.toFixed(1)}px)`:'none';+ s.el.style.transform=`translate(${fly.x.toFixed(1)}px,0px) perspective(2200px) rotateY(${fly.rotY.toFixed(2)}deg) rotateX(${fly.rotX}deg) scale(${fly.s.toFixed(4)})`;+ const f=clamp(s.mark-8+Math.round((t-s.t)*FPS),0,s.n-1); const src=`${FR}${s.name}/${String(f+1).padStart(4,'0')}.jpg`;+ if(s.cur!==src){ s.cur=src; s.img.src=src; pending.push(s.img.decode().catch(()=>{})); } });+ // 6 · micro-interaction cards+ MINIS.forEach(m=>{ const vis=t>=m.t-0.02&&t<m.out+0.3; if(!vis){ m.el.style.opacity=0; return; } const ei=OM.popIn(t,m.t), eo=OM.liftOut(t,m.out);+ place(m.el,0,ei.dy+eo.dy,ei.s*eo.s*1.12,ei.op*eo.op,eo.blur); drawMini(m,clamp(t,m.t,m.out+0.29)); });+ // 7 · hold beat: the cloth page in a browser window, slow push in, hard out+ { const el=$('win'); const vis=t>=WIN_IN&&t<WIN_OUT; const w=OM.popIn(t,WIN_IN,{zeta:0.7,omega:16,rise:40,s0:0.96,ds:0.04});+ place(el,0,w.dy,w.s*OM.drift(t,WIN_IN,WIN_OUT,0.07),vis?w.op:0);+ if(vis){ const f=clamp(WIN.mark-4+Math.round((t-WIN_IN)*FPS),0,WIN.n-1); const src=`${FR}char-curtain/${String(f+1).padStart(4,'0')}.jpg`; if(winCur!==src){winCur=src;$('winimg').src=src;pending.push($('winimg').decode().catch(()=>{}));} } }+ // 8 · staccato words, then black + wordmark+ { const w=OM.staccato(t,STAC).word; const on=t>=STAC[0][0]&&t<STAC_END; $('stac').textContent=w; $('stac').style.opacity=on?1:0;+ $('end').style.opacity = t>=END_T?1:0; }+ // hand+ { const vis=t>=3.9&&t<12.3; const cu=OM.cursor(t,HAND,CLICKS);+ $('cursor').style.opacity=vis?1:0; $('cursor').style.transform=`translate(${(cu.x-4).toFixed(1)}px,${(cu.y-3).toFixed(1)}px) scale(${cu.s})`; }+ $('hud').textContent='t='+t.toFixed(3);+ return Promise.all(pending);+}+window.__seek=async t=>{ await seek(t); return true; };+window.__ready=document.fonts.ready.then(()=>{ markEl.style.transform='none'; markW=markEl.getBoundingClientRect().width; tagW=$('tag').getBoundingClientRect().width; simulate(); return seek(0); });+const q=new URLSearchParams(location.search);+if(q.has('t')) __ready.then(()=>seek(parseFloat(q.get('t'))));+if(q.has('hud')) $('hud').style.display='block';+if(q.has('play')) __ready.then(()=>{const t0=performance.now();(function loop(){seek(((performance.now()-t0)/1000)%DUR);requestAnimationFrame(loop);})();});+</script>+</body>+</html>diff --git a/templates/footage.example.json b/templates/footage.example.jsonnew file mode 100644index 0000000..deaee24--- /dev/null+++ b/templates/footage.example.json@@ -0,0 +1,19 @@+{+ "_comment": "footage config used for motion-web-15s. Sweep points are in 1440×900 space (the design viewport of the cases) and scaled to the recording viewport.",+ "viewport": [1920, 1200],+ "coord_space": [1440, 900],+ "settle_ms": 1500,+ "preroll_ms": 1400,+ "tail_ms": 2000,+ "cases": [+ {"name": "critter", "url": "file:///path/to/your-page-1/index.html",+ "drive": [{"sweep": [[720,450],[380,300],[1060,620],[520,260],[900,560],[720,450]], "dur": 3.2}]},+ {"name": "demo-after", "url": "file:///path/to/your-page-2/index.html",+ "drive": [{"wheel": {"n": 1, "dy": 600, "gap_ms": 0}}, {"wait": 1500}, {"wheel": {"n": 1, "dy": 600, "gap_ms": 0}}]},+ {"name": "press-stack", "url": "https://example.com/a-scrolling-page",+ "settle_ms": 2500,+ "drive": [{"wheel": {"n": 10, "dy": 260, "gap_ms": 220}}]},+ {"name": "char-curtain", "url": "https://example.com/a-hover-page",+ "drive": [{"sweep": [[180,470],[1260,430],[300,520]], "dur": 2.6}]}+ ]+}diff --git a/templates/sfx_score.example.py b/templates/sfx_score.example.pynew file mode 100644index 0000000..5da72c9--- /dev/null+++ b/templates/sfx_score.example.py@@ -0,0 +1,55 @@+#!/usr/bin/env python3+"""sfx_score.example.py — the motion-web-15s score, written on scripts/sfx_palette.py.++Copy next to your comp, edit the events, run: python3 sfx_score.py → sfx.wav (48 kHz, peak -8 dBFS)+Every `s.place(material, t, gain, pan, send, pan_to)` is a beat from the composition's timeline; pans come+from where the thing is on screen (pan_of(x)). Fewer events than beats. references/sound.md.+"""+import os, sys+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "scripts")) # or the skill's scripts dir+from sfx_palette import Score, air, glass, wood, sub, bubble, wobble, pan_of+import numpy as np+rng = np.random.default_rng(7)+s = Score(dur=15.0, T60=1.1)+place = s.place++# ── the score ──────────────────────────────────────────────────────────────+# 1 · words: three glass touches, low, spaced — the quiet opening+for t,f in zip((0.15,0.50,0.92),(659,784,523)): place(glass(f,0.8,0.6),t,0.16,0.0,0.45)+# 2 · wordmark: one rising breath of air as the letters drop in, a rounded pop when "move" wobbles+place(air(0.7,180,1800,1.2,0.6),1.62,0.28,-0.15,0.5,pan_to=0.15)+place(bubble(420,0.26),2.30,0.30,0.05,0.3)+place(air(0.35,1400,300,1.3),2.98,0.20,0.0,0.4) # the mark folds to the corner+# 3 · prompt: muted keys (about one in three, velocity varies), then a real click+TXT='make the hero feel alive — springs, not fades'+for i,ch in enumerate(TXT):+ if ch in ' —' or rng.uniform()<0.35: continue+ place(wood(170+rng.uniform(-20,20),0.09),3.15+i/38+rng.uniform(0,0.003),0.10*rng.uniform(0.7,1.3),-0.05,0.15)+place(wood(240,0.08),4.45,0.32,pan_of(1290),0.2); place(wood(190,0.07),4.51,0.22,pan_of(1290),0.2) # down / up+place(air(0.3,2200,400,1.5),4.75,0.18,0.0,0.4) # prompt leaves+# 4 · panel: seven glass ticks up a scale, PASS as a soft two-note chord+place(air(0.32,300,2400,1.3),4.85,0.18,0.0,0.4)+for i,f in enumerate((523,587,659,784,880,1046,1318)):+ place(glass(f,0.6,0.8),5.15+i*0.24,0.15 if i<6 else 0.0,-0.1,0.4)+place(glass(1318,1.3,0.5),6.59,0.16,-0.05,0.6); place(glass(1976,1.3,0.4),6.61,0.11,0.05,0.6) # PASS+place(air(0.3,2200,400,1.5),7.0,0.18,0.0,0.4)+# 5 · pages fly through: air that travels right→left with the picture, a felt landing as each settles+for t in (7.05,7.95,8.85):+ place(air(0.5,220,3000,1.3,0.35),t-0.03,0.55,0.6,0.5,pan_to=-0.1)+ place(sub(70,0.5),t+0.16,0.22,0.0,0.3)+ place(air(0.4,2600,260,1.4,0.3),t+0.88,0.35,-0.1,0.5,pan_to=-0.7)+# 6 · micro cards: a bubble as each lands; the mechanism gets exactly one sound+minis=[(9.55,10.40,700),(10.00,10.95,1320),(10.75,11.60,930),(11.35,12.15,1410)]+for t0,t1,x in minis: place(bubble(480+rng.uniform(-40,40),0.24),t0+0.02,0.26,pan_of(x),0.3); place(air(0.26,1600,300,1.4),t1,0.14,pan_of(x),0.4)+place(wood(240,0.08),10.05,0.30,pan_of(700),0.2); place(wood(190,0.07),10.11,0.20,pan_of(700),0.2) # magnetic button click+place(wobble(150,0.6),11.03,0.42,pan_of(930),0.35) # jelly+place(air(0.22,700,3200,2.0),11.60,0.18,pan_of(1410),0.4,pan_to=pan_of(1500)) # string swept+# 7 · the window: one long breath in, then silence+place(air(0.7,200,2000,1.1,0.5),12.08,0.40,0.0,0.6)+place(sub(58,0.8),12.22,0.20,0.0,0.4)+# 8 · hard cuts: four felt hits, then the deep one under black+for i,t in enumerate((13.25,13.50,13.72,13.94)): place(sub(72-i*3,0.5),t,0.40,0.0,0.25)+place(sub(48,1.2),14.30,0.58,0.0,0.45); place(glass(392,1.6,0.3),14.34,0.10,0.0,0.7)+++s.write(os.path.join(os.path.dirname(os.path.abspath(__file__)), "sfx.wav"))