mografy 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -9
- package/lib/node_modules/@mografy/cli/bin/locate.mjs +2 -22
- package/lib/node_modules/@mografy/cli/dist/add.d.ts +0 -1
- package/lib/node_modules/@mografy/cli/dist/add.js +6 -24
- package/lib/node_modules/@mografy/cli/dist/commands/help.js +5 -2
- package/lib/node_modules/@mografy/cli/dist/examples.js +4 -4
- package/lib/node_modules/@mografy/cli/dist/index.js +70 -16
- package/lib/node_modules/@mografy/cli/dist/mcp/hosts.d.ts +1 -1
- package/lib/node_modules/@mografy/cli/dist/mcp/hosts.js +6 -3
- package/lib/node_modules/@mografy/cli/dist/paths.d.ts +4 -3
- package/lib/node_modules/@mografy/cli/dist/paths.js +6 -5
- package/lib/node_modules/@mografy/cli/dist/project-args.d.ts +4 -3
- package/lib/node_modules/@mografy/cli/dist/project-args.js +7 -4
- package/lib/node_modules/@mografy/cli/dist/project-install.d.ts +44 -0
- package/lib/node_modules/@mografy/cli/dist/project-install.js +208 -0
- package/lib/node_modules/@mografy/cli/dist/showcase.js +4 -4
- package/lib/node_modules/@mografy/cli/dist/skill-hint.js +4 -2
- package/lib/node_modules/@mografy/cli/dist/templates.d.ts +1 -1
- package/lib/node_modules/@mografy/cli/dist/templates.js +17 -5
- package/lib/node_modules/@mografy/cli/package.json +1 -1
- package/lib/node_modules/@mografy/core/dist/guide.d.ts +12 -12
- package/lib/node_modules/@mografy/core/dist/guide.js +3 -3
- package/lib/node_modules/@mografy/core/dist/protocol.d.ts +6 -0
- package/lib/node_modules/@mografy/core/dist/skill-text.d.ts +22 -22
- package/lib/node_modules/@mografy/core/dist/skill-text.js +22 -22
- package/lib/node_modules/@mografy/core/package.json +1 -1
- package/lib/node_modules/@mografy/render/dist/ffmpeg.d.ts +1 -1
- package/lib/node_modules/@mografy/render/dist/ffmpeg.js +3 -2
- package/lib/node_modules/@mografy/render/package.json +1 -1
- package/lib/node_modules/@mografy/runtime/package.json +1 -1
- package/lib/node_modules/@mografy/server/dist/index.d.ts +1 -0
- package/lib/node_modules/@mografy/server/dist/index.js +1 -0
- package/lib/node_modules/@mografy/server/dist/installation.d.ts +31 -2
- package/lib/node_modules/@mografy/server/dist/installation.js +75 -5
- package/lib/node_modules/@mografy/server/dist/project.d.ts +5 -0
- package/lib/node_modules/@mografy/server/dist/project.js +2 -2
- package/lib/node_modules/@mografy/server/dist/workspace.d.ts +5 -0
- package/lib/node_modules/@mografy/server/dist/workspace.js +20 -6
- package/lib/node_modules/@mografy/server/package.json +1 -1
- package/lib/node_modules/@mografy/web/dist/app.css +1 -1
- package/lib/node_modules/@mografy/web/dist/app.js +26 -14
- package/lib/node_modules/@mografy/web/package.json +1 -1
- package/package.json +2 -1
- package/templates/README.md +35 -0
- package/templates/ai-chat-stream-wide.ts +132 -0
- package/templates/ai-chat-stream.ts +86 -0
- package/templates/before-after-wide.ts +120 -0
- package/templates/before-after.ts +111 -0
- package/templates/browser-window-wide.ts +155 -0
- package/templates/bullet-points-wide.ts +89 -0
- package/templates/callout-wide.ts +151 -0
- package/templates/callout.ts +135 -0
- package/templates/caption-highlight.ts +117 -0
- package/templates/caption-pop.ts +121 -0
- package/templates/caption-stack.ts +84 -0
- package/templates/caption-subtitle-wide.ts +86 -0
- package/templates/caption-subtitle.ts +115 -0
- package/templates/caption-word.ts +107 -0
- package/templates/catalog.json +2400 -0
- package/templates/chapter-title-wide.ts +62 -0
- package/templates/click-zoom.ts +139 -0
- package/templates/cta-endcard-wide.ts +127 -0
- package/templates/cta-endcard.ts +119 -0
- package/templates/desktop-follow.ts +198 -0
- package/templates/device-stack.ts +135 -0
- package/templates/editorial.ts +260 -0
- package/templates/feature-grid-wide.ts +109 -0
- package/templates/fonts/Anton-Regular.woff2 +0 -0
- package/templates/fonts/Inter-500-latin.ttf +0 -0
- package/templates/fonts/Inter-600-latin.ttf +0 -0
- package/templates/fonts/Inter-700-latin.ttf +0 -0
- package/templates/fonts/Inter-800-latin.ttf +0 -0
- package/templates/fonts/LICENSE-Inter.txt +133 -0
- package/templates/fonts/OFL-Anton.txt +93 -0
- package/templates/growth-bars-wide.ts +85 -0
- package/templates/hook-impact.ts +58 -0
- package/templates/hook-number.ts +90 -0
- package/templates/hook-question.ts +88 -0
- package/templates/kit.ts +140 -0
- package/templates/laptop-frame-wide.ts +163 -0
- package/templates/logo-tagline-wide.ts +81 -0
- package/templates/logo-tagline.ts +93 -0
- package/templates/logo-wall-wide.ts +65 -0
- package/templates/montage.ts +273 -0
- package/templates/multi-window-wide.ts +135 -0
- package/templates/name-lower-wide.ts +97 -0
- package/templates/phone-recording.ts +154 -0
- package/templates/product-hero-wide.ts +72 -0
- package/templates/push-transition-wide.ts +75 -0
- package/templates/push-transition.ts +83 -0
- package/templates/quote-wide.ts +92 -0
- package/templates/review-cards.ts +83 -0
- package/templates/stat-count-wide.ts +73 -0
- package/templates/stat-count.ts +100 -0
- package/templates/terminal-wide.ts +115 -0
- package/templates/three-steps.ts +92 -0
- package/templates/title-wide.ts +55 -0
- package/templates/tsconfig.json +17 -0
- package/templates/type-input.ts +107 -0
- package/lib/node_modules/@mografy/cli/dist/launcher.d.ts +0 -18
- package/lib/node_modules/@mografy/cli/dist/launcher.js +0 -126
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
// Generated from packages/core/skill/**/*.md by scripts/skill-text.mjs. Edit the Markdown, then run `pnpm build`.
|
|
2
2
|
export const SKILL_TEXT = {
|
|
3
3
|
"project-guide.md": "# Mografy project instructions\n\nThis folder is a Mografy animation project. Animation belongs only in scene modules; `mografy.json` contains settings. Use synchronous `renderFrame(ctx, time, params)` with deterministic seeking. Scenes run only in the browser; do not introduce GSAP, SVG scene layers, resvg, clocks, or previous-frame state. Use `ctx.draw` for common drawing and `ctx.withCanvas` for native Canvas scopes.\n\nRead the shared `mografy` Skill before scene work: its `SKILL.md`, then the references its table names for the task. Codex, Claude Code and other agents install it once with `npx skills add mografy/mografy -g`; with the Mografy MCP tools connected, `read_guide` serves the same files. Do not create Skill copies inside animation projects.\n\n`scenes/timeline.json` and `colors` in `mografy.json` hold the user's own changes from the editor: read them before changing the film, and never write them by hand. The project's `style.md` records its design and motion decisions; read it before every change.\n\nCodex storyboards use image generation; Claude uses Artifacts when available, otherwise a standalone HTML/Canvas preview. Write plans and prompts in English and save project-specific boards under `storyboards/`.\n\nOpen the player with `mografy dev`. After scene edits, run `mografy check --motion` and `mografy review`, then inspect the generated PNGs. Export with `mografy export --format mp4|webm|mov|lottie|svga` when requested.\n",
|
|
4
|
-
"references/animation-principles.md": "# The twelve principles of animation in Mografy\n\nUse these principles to give movement weight, intention, and personality. Choose the ones that support the scene; do not force all twelve into every shot or add perpetual motion to readable holds. Record the chosen principles and their purpose in the storyboard. Preserve existing typography, logos, and character identity.\n\n| Principle | Application in a Canvas scene | Review criterion |\n| --- | --- | --- |\n| 1. Squash and stretch | Deform a soft object around its contact or pivot point. Use reciprocal scale factors (sx = s, sy = 1/s) to approximately preserve area. Keep logos and text rigid unless deformation suits the brief. | The object conveys weight without unintended distortion. |\n| 2. Anticipation | Add a small opposite move, compression, or brief pause before the main action. Evaluate each phase from absolute time. | The viewer can predict what will happen without a distracting delay. |\n| 3. Staging | Use composition, contrast, negative space, and one dominant moving focus. Position secondary objects to support that focus. | The message is clear at key poses and throughout transitions. |\n| 4. Straight ahead action and pose to pose | Plan start, extreme, and settle poses; interpolate between them. For organic straight-ahead exploration, precompute seeded samples in setup and index/interpolate them by time. Never integrate from the previous rendered frame. | Random seeks and repeat renders preserve exactly the same pose. |\n| 5. Follow through and overlapping action | Let a tail, ribbon, or supporting element settle after the main body. Use delayed time windows or bounded damped oscillation with a defined start. | Parts share a cause but stop at different times; motion ends cleanly. |\n| 6. Slow in and slow out | Use `springs.out` for entrances, `keys` for moves that pass through several poses, and `cameraPath` for the camera; keep `ease.inOutCubic` for a single short move. Vary spacing to communicate acceleration and deceleration. | Speed changes feel intentional; related elements use coherent curves. |\n| 7. Arcs | Move subjects along analytic curved paths, such as quadratic Bezier positions or a bounded sine arc. Let rotation follow the tangent when useful. | Motion has a coherent path and clears safe margins. |\n| 8. Secondary action | Add a restrained blink, tilt, highlight, or small response that supports the primary action. Offset its timing and amplitude. | It reinforces emotion or meaning without competing with the main message. |\n| 9. Timing | Allocate anticipation, action, settle, reading hold, and exit in seconds. Use fps to judge frame spacing and ctx.beat(time) for musical cues when audio exists. | Weight, pacing, legibility, and beat alignment work at the requested fps. |\n| 10. Exaggeration | Selectively amplify a pose, trajectory, contrast, or overshoot to make the intent readable. Keep amplitudes adjustable and bounded. | The action is expressive without clipping or harming brand recognition. |\n| 11. Solid drawing | Keep pivots, proportions, perspective, overlap, and volume coherent with Canvas transforms, gradients, and consistent lighting. For flat graphics, maintain optical balance and silhouette. | Forms stay believable while moving, scaling, and overlapping. |\n| 12. Appeal | Build clear silhouettes, harmonious proportions, distinct pose rhythms, and a consistent palette. Use deliberate asymmetry when it adds character. | The scene feels intentional and engaging, with useful visual hierarchy. |\n\n## Deterministic follow-through example\n\nThe runtime's `settle(time, start, duration, amplitude, cycles?)` is a bounded wobble that is exactly 0 outside its window; `springs.out`, `springs.pop` and `spring()` cover entrances and overshoot. All are pure functions of time, so seek order never changes a pose:\n\n```ts\nimport { at, settle, springs } from '@mografy/runtime';\n// Evaluate inside renderFrame: the card pops in, then its ribbon lags behind and settles.\nconst scale = at(time, 0.4, 0.9, springs.pop);\nconst ribbonAngle = settle(time, 0.8, 1.2, 0.12);\n```\n\nStore motion only in scene modules. Do not add a live physics loop, unseeded randomness, a clock, or previous-frame state. Read [scene-authoring.md](scene-authoring.md) for the runtime and drawing contract.\n\nReview the start, extreme, settle, and final hold of each action, plus dense transition strips. Check repeated and out-of-order times with `mografy check`, and inspect both raw and post-processed frames with `mografy review`. When motion sampling, glow, or grain hides a pose or blurs important text, adjust the motion or output settings and review again.\n",
|
|
5
|
-
"references/built-in-components.md": "# Built-in component references\n\nThe sixteen built-in animations are working scene references for authoring and storyboards. Read the relevant scene entry and its imported modules before reusing a pattern. Paths below refer to the owning Mografy repository in [project.md](project.md). For an existing user project, inspect its local copies first; they may have been customized.\n\n## Source catalog\n\nThe reusable implementations live in [components.ts](__REPOSITORY__/packages/server/template/scenes/components.ts) and [social-components.ts](__REPOSITORY__/packages/server/template/scenes/social-components.ts). Each animation has a complete entry under `packages/server/template/scenes/`:\n\n| Component | Entry | Function | Authoring reference |\n| --- | --- | --- | --- |\n| Stagger text | [stagger-text.ts](__REPOSITORY__/packages/server/template/scenes/stagger-text.ts) | `staggerText` | Measured letters rise with staggered opacity and easing. |\n| Typewriter | [typewriter.ts](__REPOSITORY__/packages/server/template/scenes/typewriter.ts) | `typewriter` | Character reveal and a caret computed from time. |\n| Pop card | [pop-card.ts](__REPOSITORY__/packages/server/template/scenes/pop-card.ts) | `popCard` | Lift, scale, opacity, and local content drawing. |\n| Progress bar | [progress-bar.ts](__REPOSITORY__/packages/server/template/scenes/progress-bar.ts) | `progressBar` | Eased progress clipped inside a rounded track. |\n| Pulse dots | [pulse-dots.ts](__REPOSITORY__/packages/server/template/scenes/pulse-dots.ts) | `pulseDots` | Phase-offset loading motion from absolute time. |\n| Logo reveal | [logo-reveal.ts](__REPOSITORY__/packages/server/template/scenes/logo-reveal.ts) | `logoReveal` | Staged reveal of original Mografy Path2D artwork. |\n| Social card | [social-card.ts](__REPOSITORY__/packages/server/template/scenes/social-card.ts) | `socialCard` | A profile card with avatar, text, and a composed entrance. |\n| YouTube subscribe | [youtube-subscribe.ts](__REPOSITORY__/packages/server/template/scenes/youtube-subscribe.ts) | `youtubeSubscribe` | A button interaction with cursor and subscribed state. |\n| AI chat | [ai-chat.ts](__REPOSITORY__/packages/server/template/scenes/ai-chat.ts) | `aiChat` | Timed prompt/reply bubbles and text reveal. |\n| Like burst | [like-burst.ts](__REPOSITORY__/packages/server/template/scenes/like-burst.ts) | `likeBurst` | An expressive heart response with radial secondary motion. |\n| Follow badge | [follow-badge.ts](__REPOSITORY__/packages/server/template/scenes/follow-badge.ts) | `followBadge` | Profile identity and a follow-state transition. |\n| Notification toast | [notification-toast.ts](__REPOSITORY__/packages/server/template/scenes/notification-toast.ts) | `notificationToast` | A compact status message with staged reveal. |\n| Lower third | [lower-third.ts](__REPOSITORY__/packages/server/template/scenes/lower-third.ts) | `lowerThird` | A clipped title/subtitle reveal and clear hierarchy. |\n| Count up | [count-up.ts](__REPOSITORY__/packages/server/template/scenes/count-up.ts) | `countUp` | A deterministic numeric value transition. |\n| Toggle switch | [toggle-switch.ts](__REPOSITORY__/packages/server/template/scenes/toggle-switch.ts) | `toggleSwitch` | Coordinated knob position, track color, and cursor response. |\n| Audio wave | [audio-wave.ts](__REPOSITORY__/packages/server/template/scenes/audio-wave.ts) | `audioWave` | A procedural wave of bars; actual audio-reactive motion needs scene-specific audio or beat input. |\n\n[component-frame.ts](__REPOSITORY__/packages/server/template/scenes/component-frame.ts) supplies the shared 1920 × 1080, eight-second, 30fps scene contract, font selection, speed control, and drawing scopes. `componentFrame` evaluates `time * speed % 4`; account for that four-second reset before changing timing. `centeredComponent` retains the landscape design-space transform and uses component-specific widths around the exact canvas center in portrait. Installed built-in projects and their bundled thumbnails default to 9:16 portrait. All sixteen entries support both landscape and portrait canvases. Follow badges stack vertically; chat, notification, profile, and lower-third copy use measured wrapping or bounded single lines. Dots and bar thickness use the short edge to preserve spacing and proportions. Select Adapt layout when exporting to the other orientation. [brand-logo.ts](__REPOSITORY__/packages/server/template/scenes/brand-logo.ts) supplies the original mark geometry. [showcase.ts](__REPOSITORY__/packages/server/template/scenes/showcase.ts) demonstrates composition of all sixteen motifs.\n\n## Reuse in a project\n\n- The source library is `packages/server/template/`; editable installed copies are under the configured library's `.components/{id}/`. When running from source, the default library is `projects/`. Read `scenes/main.ts` and the manifest of the selected installed project rather than assuming it is identical to the template.\n- New projects receive the component modules and scene entries. Import the needed function from the project's local `scenes/components.ts` or `scenes/social-components.ts`. Preserve required imports, including brand geometry. Do not import files outside the animation project; compilation allows project-local modules and `@mografy/runtime` only.\n- Copy the useful motion and composition into the selected project's own scene modules. Adapt layout, copy, palette, scale, and timing to its brief. Keep pure time evaluation and isolated Canvas state; retain the project's existing assets and visual identity.\n- Use these examples to choose a motif in the storyboard and connect it to a concrete scene function. For a longer sequence with transitions and a brand ending, read [intro.md](intro.md).\n- Optional extras are not installed with Mografy; installation contains only the sixteen built-in components. They live in the repository's [extras/](__REPOSITORY__/extras/) folder on GitHub and are copied into a project when a brief needs them: camera moves and transitions for film-style sequences ([camera-transitions.md](camera-transitions.md)), Chinese / Japanese typography with OFL fonts ([cjk-typography.md](cjk-typography.md)), Three.js 3D layers ([three-d.md](three-d.md)), contextual music generated from the film's cues ([music.md](music.md)), and product walkthroughs that redraw an app's screens as simplified cards ([product-walkthrough.md](product-walkthrough.md)).\n- Keep important subtitle params distinct from ordinary scene copy. The source entries may contain string params that are edited by an agent in source rather than shown in the subtitle inspector.\n\n## Review\n\nOpen an installed example with `mografy dev [project]`. After adapting it, run `mografy check [project]` and `mografy review [project]`; inspect actual frames at the entrance, extreme, settle, hold, and any loop reset. Verify text measurement, safe margins, clipping, contrast, and out-of-order seeking. The catalog is a source reference, not an acceptance result for a modified scene. Read [scene-authoring.md](scene-authoring.md) and [animation-principles.md](animation-principles.md) for the contract and motion direction.\n",
|
|
6
|
-
"references/camera-transitions.md": "# Camera, transition and atmosphere helpers\n\n[cinema.ts](__REPOSITORY__/extras/cinema/cinema.ts) gives film-style scenes a shared vocabulary. Every helper is a pure function of time and options, uses `ctx.width` / `ctx.height`, and works in landscape and portrait. [cinema-demo.ts](__REPOSITORY__/extras/cinema/cinema-demo.ts) is a fourteen-second tour of six shots joined by six transitions.\n\n## Add to a project\n\nThe helpers are an optional extra, not part of the installed template. If the project already has `scenes/cinema.ts`, read and reuse that local copy; it may have been customized. Otherwise copy `extras/cinema/cinema.ts` from the current Mografy checkout into the project's `scenes/` folder, or download it from GitHub:\n\n```sh\
|
|
7
|
-
"references/cjk-typography.md": "# Chinese and Japanese typography\n\n[cjk.ts](__REPOSITORY__/extras/cjk/cjk.ts) sets Chinese and Japanese copy: vertical text (tategaki) and horizontal text with CJK line breaking. [cjk-demo.ts](__REPOSITORY__/extras/cjk/cjk-demo.ts) shows both.\n\n## Add to a project\n\nThe module and fonts are an optional extra, not part of the installed template. If the project already has `scenes/cjk.ts`, read and reuse that local copy. Otherwise copy from the current Mografy checkout (`extras/cjk/`) or download from GitHub:\n\n```sh\
|
|
8
|
-
"references/examples.md": "# Reference films\n\nReference films are finished films kept as references for quality. Before planning a new film, read the one whose brief is closest to yours, watch it in the player, and reuse its structure; then compare your own frames against it at review.\n\n- **In the repository's `examples/`**: `mografy-intro`, installed and listed in the player under Examples, and the ten `stage-*` films ([ui-stage.md](ui-stage.md)), listed in `examples/catalog.json` and downloaded from GitHub by `mografy add <name>` the first time (a full checkout has them locally).\n- **Showcase films** live on the website, not in the installation: watch them at **https://www.mografy.app/showcase** and download one by name with `mografy add <name> [folder]`. When a brief needs a longer film, a narrated explainer, 3D, or a model to start a multi-shot film from, fetch the showcase first: the page shows every film with its preview, and **https://www.mografy.app/showcase/films.json** lists the same films for agents (name, title, length, aspect ratio, what to read it for, where to look, download URL). Pick from that list, then download the closest one. The tables below describe the showcase films as of this Mografy version; the website's list wins when they differ.\n\nThey follow the [quality floor](../SKILL.md) and the [film architecture](film-architecture.md): drawing is a pure function of time, one table drives the shot times and `meta.shots`, and the runtime's `keys`, `cameraPath`, `layer`, `blurLayer`, `bloom` and `blurText` do the camera, fades, blur and glow. Each has a composed, sustained score in `music-src/` and its fonts and licences in `assets/`.\n\n## Copy one to work on\n\n```sh\nmografy add # list reference films, showcase films and helpers\nmografy add stage-invoices ./hero # copy a Stage film (downloaded from GitHub when not checked out)\nmografy add film-starter ~/Films/new # download a showcase film: the model for a new multi-shot film\nmografy add mografy-montage # into the library (projects/mografy-montage when running from source)\n```\n\nThe copy is an ordinary project: open it with `mografy dev <folder>`, and edit, check, review and export it like any other. Never edit the films in `examples/` themselves; they are the reference other agents read. Stage and showcase downloads need a network connection; if it fails, the same zip is on the film's showcase page.\n\n## The films\n\nInstalled films link to their source; showcase films are downloaded first, then read in the downloaded folder.\n\n| Film | Length and look | Read it for | Where to look |\n| --- | --- | --- | --- |\n| `film-starter` (showcase) | 20 s, 16:9, English, dark | The model every multi-shot film starts from (see [film-architecture.md](film-architecture.md)): one light the eye follows from a point to a line, a card that grows out of the line and plots an ease curve, a ring of light, the last line's full stop | `BEATS` (shot table), `camera`, `spine` (a line growing round the card), `cardFace` (glass card in a `layer`), `ring` (`bloom`), the `blurLayer` defocus in `world` |\n| `mografy-montage` (showcase) | 60 s, 16:9, English or Traditional Chinese (`lang` param); dark → light → neon | One continuous camera across three acts; one comet of light drawing every act I shape from shared geometry; a flat UI card turned into a 3D window; kinetic type that sharpens out of blur; a spiral galaxy; the logo drawn by the last dot | `cam1` / `cam2` (`cameraPath`), `headS` (`keys` along one path), `ACT1` / `joinSegs` (shared geometry), `kin` (blurText per glyph), `plane2` / `drawPlane` (3D card), `galaxy`, `logo`; `BEATS` → `SHOTS` |\n| `mografy-triangulum` (showcase) | 42 s, 16:9, Traditional Chinese, deep space | A launch teaser in ten beats linked by one light trail; Three.js point clouds composited between 2D layers; depth of field and rack focus with `blurLayer`; glass cards; champagne type with a specular sweep | `buildParticles` / `galaxyLayer` / `fieldLayer` (3D), `blurred` (depth of field), `comet` (light trail), `glass`, `title` (mask reveal), `sweepFill`; `SHOTS` → `BEATS` |\n| `mografy-story` (showcase) | 71 s, 16:9, Traditional Chinese captions, dark → light | A narrative film with a turn: twelve shots, captions on their own track, a black box that opens into the light world, product UI redrawn as cards, a brand-logo ending | `SHOTS` (design times, `sx` slow-down, `xf` overlap, `stop`), `frame` (shot lookup and crossfade), `s05` / `cube3` (the box), `s07` / `system` (UI cards and a slider), `caption`, `brandLogo` |\n| [mografy-intro](__REPOSITORY__/examples/mografy-intro/scenes/main.ts) | 12 s, 16:9, English | A short product intro in four beats; see [intro.md](intro.md) | `beatCode`, `beatScrub`, `beatChat`, `beatLogo` |\n| `analytics-product` (showcase) | 8 s loop, 16:9, English UI | A product UI moment: the cursor picks \"This week\", the number counts up and the bars regrow while the rest of the screen quiets | `focus` (push-in and dimming), the segmented control, the chart, `cursor` |\n| [stage-invoices](__REPOSITORY__/examples/stage-invoices/scenes/main.ts) | 7 s loop, 16:9, English UI, four looks | The Stage model ([ui-stage.md](ui-stage.md)): a window pinned off two edges, story words only, Mark paid flies the amount into a rolling total, camera leans in, Undo resets on screen. The `variant` param draws the five failures for comparison | `initial`, `layout`, the `play` script, `ui.window`, `ui.roll`, `ui.fly`, `ui.toast` |\n| [stage-phone](__REPOSITORY__/examples/stage-phone/scenes/main.ts) | 7.6 s loop, 9:16, English UI | A phone cropped by the frame and driven by taps: a notification grows into the thread as one object, typing, a reply that forms out of the field, a side-button lock | `ui.phone`, `ui.notification`, the container transform under `open`, `type`, `tap` |\n| [stage-dashboard](__REPOSITORY__/examples/stage-dashboard/scenes/main.ts) | 6.5 s loop, 16:9, dark | The newer macOS window (`tahoe`), one insight on a chart: hover, tooltip, one annotation, camera in and out | `ui.window` (`tahoe`), the chart, hover and note presence, `focus` |\n| `stage-bento`, `stage-calendar`, `stage-upload`, `stage-command`, `stage-checkout`, `stage-request`, `stage-snooze` | 5.7–10 s loops | The rest of the Stage set: a bento grid, a drag, a blueprint diagram with annotations, a keyboard-only palette, a checkout in a tabbed browser, two screens, a feature card. [ui-stage.md](ui-stage.md) says which to start from | each film's `scenes/main.ts` and `style.md` |\n| `follow-interaction` (showcase) | 8 s loop, 16:9, English UI | One micro-interaction done carefully: a button whose width and label spring between states, a ripple, a confirmation | `state` (spring), the button, the labels, `cursor` |\n| `mografy-brand` (showcase) | 8 s, 16:9, logo only | A logo reveal from the official paths: the ribbon drawn by one stroke, the arches rising, the wordmark letter by letter | the three numbered steps in `renderFrame`, `LOGO_PIECES` |\n\n## Paper theatre series\n\nFive narrated Traditional Chinese explainers (74–85 s, showcase films) set in one desk paper theatre built in Three.js: card puppets and props on strings, one brass lamp whose real shadows carry the idea, stop-motion on 2s with a seeded boil (param `motion`: `stop-motion` or `smooth`), three acts, full-frame 2D inserts, subtitles timed from the narration. Read them when a brief asks for 紙劇場, 紙偶, 定格, a psychology or concept explainer with narration, or a handmade look. Each has its rules in `style.md`, its shots in `storyboards/storyboard.md`, and `storyboards/timing.py` → `cues.json` for the narration timing (bring your own narration take). They have narration instead of music.\n\n| Film | The idea in props | Where to look |\n| --- | --- | --- |\n| `paper-theatre-shadow` (showcase) | 陰影心理學: one bulb moves and the shadow answers; four trait tokens live in the shadow's head. The first of the series: the theatre, lamp and post grade the others reuse | `world.ts` `buildWorld` (box, proscenium, lamp, desk), `makePost` (depth of field, ACES, grain), `step` (stop-motion), the shot table in `main.ts` |\n| `paper-theatre-gestalt` (showcase) | 格式塔心理學: card fragments whose shadows lock into a face from one lamp position only; six laws in an ink-papered Act II | `projPoint` and the lamp positions `L_FACE` / `L_RUBIN` / `L_PRAG` (real 3D projection), the six-law layout |\n| `paper-theatre-aesthetic-usability` (showcase) | 美即好用效應: two cardboard ATMs, 2D interfaces inside the screens, 3D reactions outside; the camera passes through a screen into full-frame 2D | `ui.ts` (`paintScreen`, `skin`, `wire`), `EYE` (the lamp at the viewer's eye) |\n| `paper-theatre-ringelmann` (showcase) | 林格曼效應: one rope, a brass dynamometer, a 3D needle against a 2D target needle; acts change under full-frame 2D, never in a blackout | `dialAngle`, `ROPE_*` / `MINI` (rope and dials), the 2D cover transitions |\n| `paper-theatre-adhd` (showcase) | 不聽使喚的燈 (ADHD): a spotlight on a brass track against a 2D ring where the puppet wants to look; the gap closes but never quite meets | `TRACK`, `tapePositions`, `bake` / `loadBaked` (texture cache) |\n\n\nTwo character films use the same paper theatre language with a printed puppet instead of narration: a flat card on a rod or threads, replacement animation (one card per pose or emotion, flips face → edge → back over three poses), things leave on their mechanism (pulled up on strings, slid into the wings, curtains), cuts on the bar grid of a composed score (`music-src/compose.py`). Read them for 角色, 偶像, 童話 or story briefs.\n\n| Film | Length and look | Where to look |\n| --- | --- | --- |\n| `paper-theatre-moon-rabbit-opera` (showcase) | 60 s, the theatre built in real 3D inside an opera house, cut against flat 2D inserts | `world3d.ts` (`resetWorld`, `setHouse`, drapes, shadows drawn once per frame), `paper.ts` (`dieCut`, `on2`, 2D inserts, `chapterCard`) |\n| `paper-theatre-sea-moon` (showcase) | 72 s, full 3D undersea castle; the puppet is a printed card on threads, swapped by emotion; real dissolves | `world.ts` (cards, rim and mask passes), `castle.ts`, `theatre.ts` (pearl shell theatre), `post.ts`, `DISSOLVE` in `main.ts` |\n\nTo make a new one: `mografy add paper-theatre-shadow <folder>` (or the closest film; it downloads from the showcase), keep the theatre, lamp, post and stop-motion rules, and replace the props, story, copy and narration with the new idea. For a character film start from the closer of the two and bring your own puppet art (one transparent PNG per pose). Re-subset the fonts after any copy change (`extras/cjk/subset-film-fonts.py`).\n\n## What to take from them\n\n- **Timing.** One table per film. Change a shot's end there and every key, shot stop and review time follows.\n- **Continuity.** Each shot ends on the geometry the next one starts from: the comet's head becomes the underline, the underline becomes the prompt pill, the pill becomes the window's field. Read the transitions in the montage (`mografy add mografy-montage`) before designing your own.\n- **Camera.** Moves start before the action, ease through every key and never stop on a pose that is not a story beat. Cards and windows have their own local transforms inside the camera.\n- **Cost.** Blur goes through layers or the text's shadow, glow through `bloom`, and buffers are pooled. Run `mografy check` on a copy to see what a frame costs, and keep your own film in the same range.\n- **Taste.** Calm pacing, big type, still holds, one logo at the end, and sustained music without sharp high sounds; the numbers are in [taste.md](taste.md). The project's `style.md` overrides them.\n\nDo not copy their copy, brand marks or music into another brand's film. Take the structure and the techniques, and build the new film from its own brief, assets and style.\n",
|
|
9
|
-
"references/film-architecture.md": "# Film architecture: one world, one camera, one table\n\nRead this before writing any animation with more than one shot or a moving camera. It is how a film stays continuous: the viewer follows one thing from the first frame to the last, and nothing resets between shots. The model is the `film-starter` showcase film (`scenes/main.ts`, about 270 lines; `mografy add film-starter <folder>` downloads the whole project, fonts included): read it before writing a new film and copy its structure, or start the new film from the download. For finished films at full length (a 60 s promo, a 42 s teaser, a 71 s story), see [examples.md](examples.md).\n\n## The shape of a film module\n\n```ts\nimport { beats, cameraPath, keys, layer, blurLayer, bloom, springs, at, withCamera } from '@mografy/runtime';\nimport type { Context2D, FrameContext, SetupContext } from '@mografy/runtime';\n\n// 1. Tokens: every colour, font, size and fixed duration once.\nconst C = { bg: '#0E1116', ink: '#EEF2F5', accent: '#1BC6B4' };\n\n// 2. One table for timing. Everything else reads its times from here.\nexport const BEATS = beats([\n { title: 'A point', end: 3.2, stop: 2.4, handoff: .8, note: 'A point draws a line.' },\n { title: 'One idea', end: 7.2, stop: 6.4, handoff: .8 },\n // …\n]);\nconst T = Object.fromEntries(BEATS.list.map(b => [b.title, b.start]));\nexport const meta = { width: 1920, height: 1080, duration: BEATS.duration, fps: 30, background: C.bg, shots: BEATS.shots };\n\n// 3. Shared geometry: the objects that travel between shots, in world coordinates.\nconst LINE = { x0: 760, x1: 1160, y: 600 };\nconst CARD = { x: 960, y: 540, w: 720, h: 420, r: 36 };\n\n// 4. One camera, keyed on the table.\nconst camera = cameraPath([[0, 760, 600, 2.4], [T['One idea'] + 1, 960, 575, 1], /* … */]);\n\n// 5. The world, drawn from time alone, on any context.\nexport function drawFilm(c: Context2D, t: number, data: FilmData) { withCamera(c, camera(t), w => world(w, t, data)); }\n\nexport function setup(ctx: SetupContext) { ctx.assets.film = prepare(); }\nexport function renderFrame(ctx: FrameContext, time: number) {\n ctx.withCanvas(c => drawFilm(c, time, ctx.assets.film as FilmData));\n}\n```\n\n`world(c, t)` draws every element of the film from `t`: each element computes its own state (position, size, opacity, morph) as a function of time over the whole duration, not as \"shot 3's version\". That is what makes the end of one shot and the start of the next the same picture.\n\n## Continuity rules\n\n**Shared geometry.** Name the objects the viewer follows and keep them in one place (`LINE`, `CARD`, `DOT` above). When a shot changes what an object is, build the next object out of it. Either grow it: in `film-starter` the underline is the middle of the card's top edge, and the outline draws out from it both ways (a window on the outline's evenly spaced points) until its ends meet at the bottom. Or morph it: sample both shapes with the same number of points, ordered so they correspond, and interpolate them; check the in-between frames, because a straight interpolation between unlike shapes passes through ugly ones. Never fade one object out and an unrelated one in at the same spot.\n\n**Overlap exits.** The outgoing element keeps drawing its exit while the incoming one enters: the headline blurs out over 0.7 s while the underline already grows into the card. Starting the next action 0.2–0.5 s before the previous exit ends removes the dead frame at every cut.\n\n**One camera.** `cameraPath([[t, x, y, zoom?, roll?], …])` gives one smooth camera for the whole film: positions and roll follow monotone cubic keys (velocity carries through every inner key, no overshoot) and zoom is interpolated in log space. `withCamera(c, camera(t), draw)` puts the camera's `(x, y)` at the frame centre. Put keys on the shot table (`T['Takes shape'] + 2.4`), start a move up to about 0.5 s before the action it serves, and never move the camera during a click or a reading hold. Cards, phones and UI panels get local transforms inside the world (`c.translate`, `c.scale`) and, if they need a push-in of their own, a local zoom about their own centre. They never get a second camera; two cameras make one card's push-in crop the next.\n\n**Keyed motion.** Long moves that pass through several poses use one `keys([[t, v], …])` curve, never a chain of separately eased segments (each one would come to rest at its end, and the viewer sees the stop). Entrances, pops and settles use `springs.out`, `springs.pop`, `springs.camera`, `spring()` and `settle()`.\n\n**Groups fade as one.** A card with its rows, a UI panel or a whole outgoing shot fades through `layer(c, name, alpha, draw)`. Drawn directly, their alphas multiply where parts overlap and the overlaps flash.\n\n**Deliberate breaks.** A hard cut, a dip to black or a wipe is fine when the story changes register (a new act, a drop in the music). Then make the change itself readable: a cut on the beat, a match on shape or colour. Do not use a transition to hide a jump between two unrelated layouts.\n\n## The shot table\n\n`beats([{ title, end, stop?, handoff?, note? }, …])` takes contiguous shots and returns:\n\n| Field | Use |\n| --- | --- |\n| `shots` | `meta.shots`: timeline marks and the review sheet of stop frames. |\n| `list[i].start / end / stop` | Times to build keys and windows from (`T[title]`). |\n| `reviewTimes`, `transitions` | Every stop plus the frames around each handoff; copy them into `mografy.json` `review.times` and `review.transitions`. |\n| `at(time)` | The shot at `time`, seconds since it started and its progress. |\n| `duration` | The film length for `meta.duration`. |\n\nWhen a shot is retimed, change its `end` in the table only; every key and window built from `T` moves with it. With music, build the `end` values from `tempoGrid(tempo).onBar(n)` so shots stay on bars.\n\n## Storyboard as code\n\nFor films longer than about 15 s, let the storyboard and the film share one source. `drawFilm(c, t, data)` above only needs a 2D context, so a storyboard page can draw the real film at each panel's time:\n\n1. Bundle the scene module for the page with esbuild from the checkout: `node -e \"require('esbuild').build({ entryPoints: ['storyboards/board.ts'], bundle: true, format: 'esm', outfile: 'storyboards/board.js', alias: { '@mografy/runtime': '<checkout>/packages/runtime/src/scene.ts' } })\"` (run it where `esbuild` resolves, such as `packages/runtime`).\n2. In `board.ts`, import `filmFrame` from `@mografy/runtime` and `drawFilm`, `prepare` and `BEATS` from the scene; for each panel, tag its canvas with `filmFrame(c, 1920, 1080)`, scale to the panel, and call `drawFilm(c, beat.stop, prepare())`.\n3. Inline `board.js` into the storyboard HTML (or an Artifact) together with the `note` of every beat.\n\nThe board then shows the actual pixels of the film at each stop, and the scene is never a second implementation of the board. Edit the scene and rebuild the board; never fork the drawing into the board.\n\n## Review\n\nAdd `BEATS.reviewTimes` to `review.times` and `BEATS.transitions` to `review.transitions` (step 0.033 s), run `mografy check` and `mografy review`, and look at every transition strip. For each handoff confirm: the followed object is visible in every frame of the strip, nothing jumps between consecutive frames, no frame is empty, and the camera does not stop at a key that is not a story beat.\n",
|
|
10
|
-
"references/how-to-film.md": "# How-to films: operate the product, film each step\n\nA how-to film teaches one task in a product (create a client, send a quote, edit a card) as a short animation, one shot per step. It is delivered as one clip per step, for help centres, in-app hints, onboarding and slides, plus a full cut that plays the steps in order. The picture is a simplified redraw of the real UI built with the walkthrough kit ([product-walkthrough.md](product-walkthrough.md)), never a screen recording.\n\nThe difference from a product walkthrough is the capture: when the user asks for it and gives you a test account, you operate the product yourself with the agent's built-in browser or computer-use tool and capture every state. Without that, ask for screenshots and start at step 3.\n\n## When to use it\n\nRequests such as 操作教學動畫, 教學影片, 使用教學, 新手引導, 說明中心的動畫, \"how-to video\", \"tutorial clips for our help centre\", \"show users how to do X\". For a launch ad or a feature teaser, use [product-walkthrough.md](product-walkthrough.md) instead; for a 4–12 s loop of one action, [ui-stage.md](ui-stage.md).\n\n## Deliverables\n\n| Output | Spec | Where it is used |\n| --- | --- | --- |\n| One clip per step | 4–8 s, starts and ends on a still frame, MP4 (`share`) and WebM, small | In-app hints, help-centre articles, onboarding |\n| Full cut | 45–90 s, 16:9 1080p, big numbered step titles (\"1 建立客戶\") | Website, slides, YouTube |\n| Mobile cut (optional) | 9:16 1080 × 1920, finger taps, captions in the top third | App help, social |\n| Step stills | One PNG per step, its result frame | Slides and documents |\n| Captions | One line per step, in the brief's language | Muted playback, accessibility |\n\n## Workflow\n\nTwo gates need the user's (or their client's) approval: the step script, and the screenshot | redraw sheet.\n\n1. **Brief and step script.** Ask which tasks to teach, the steps of each (3–8), where the clips will live, aspect ratios, language, brand colours and the logo as SVG. Write `brief.md` and `capture/steps.json`: per step a title, the control it touches, the demo data typed, and the expected result. **Gate A:** the user approves the script and gives a test or demo account. Never use a production account with real customers.\n2. **Operate and capture.** Only when the user asked you to operate the product and gave the account:\n - Use the agent's own tools, not a scripted browser: in Claude, the Claude app's built-in browser for web apps (`navigate`, `computer` clicks and typing, `screenshot`, `get_page_text` / `read_page`, `javascript_tool`) or computer use for desktop and mobile simulators; in Codex, its built-in browser or computer-use tool. The user signs in themselves; approve each site once when the browser asks.\n - Walk the script one step at a time. Screenshot every state the step passes through: empty, focus, typing, loading, result, success toast. Take each screenshot after the UI settles.\n - Read the exact labels, values and placeholders from the page text, not from the image. Read the tokens with a short script on the page: primary, ink, muted, borders, background, radius, font family. Save `capture/01.png…nn.png`, `capture/steps.json` (labels, values, URL per state) and `capture/tokens.json`.\n - Type only invented demo data (晨光設計, demo@example.com, 0912 000 000). Stop and ask before anything that pays, sends a message or email outside the product, deletes, invites people or changes permissions. When done, list what you created and offer to delete it.\n3. **Check the capture.** Make a contact sheet of every state per step. Each step needs a before and an after; recapture missing or blurred states. Note text too small to read and ask for it.\n4. **Redraw sheet.** Follow the simplified redraw in [product-walkthrough.md](product-walkthrough.md): per step the target, the context it needs, and everything else to drop; real labels and tokens; type at 1.3–1.6× the app's size. Render one still per step beside its screenshot. **Gate B:** the user approves what stays and what goes.\n5. **Storyboard and timing.** One step per shot, 4–8 s each: settle 0.4 s, the action, the result held for the times in [taste.md](taste.md), settle 0.4 s. A shot must make sense alone, so it starts on its own card at rest and ends on its result at rest; the hand-off to the next card begins only after that still. Step title per shot (\"1 建立客戶\"), held 0.5 s + characters ÷ 4.5. Put every shot in the beat table and `meta.shots`, so the editor shows one layer per step and `mografy review` writes the shot sheet.\n6. **Build.** `mografy add walkthrough <project>`; one card per step from the same kit parts, one action per card, the pressed control grows into the next card, a big cursor (or taps in 9:16), each card's local zoom pushes in on its control. Opener: brand plus the task name; ending: the result of the whole task plus the logo. Run `mografy check --motion` and `mografy review`, and look at every stop frame: it is the first and last frame of a clip.\n7. **Export and split.** Export the full cut once (`--preset share` for the web, the user's own preset otherwise). Cut it into step clips at the beat table's shot starts and ends with the FFmpeg Mografy uses (`mografy setup ffmpeg --check` prints its path), re-encoding so every clip starts on its first frame:\n\n ```sh\n ffmpeg -ss <start> -to <end> -i renders/<film>.mp4 -c:v libx264 -crf 18 -pix_fmt yuv420p -movflags +faststart -an renders/steps/01-<step>.mp4\n ```\n\n Name clips `NN-<step-slug>.mp4`, write the step stills from `mografy review`'s shot sheet times, and the captions as `renders/steps/captions.<lang>.srt`. Put everything in `renders/steps/` and list it for the user.\n\n## When the product changes\n\nA redesign touches some steps, not the film: recapture those steps (step 2), redraw them, and re-export. Keep each step's card in its own function so one step can change without moving the others; keep the beat table times when the new step fits the same length.\n\n## Pitfalls\n\n- A clip that starts mid-hand-off shows half of the previous card: keep the still frames at shot boundaries.\n- Captured text in a screenshot is a guess; the page text is the truth. Re-read labels after the product's language setting changes.\n- Popups, cookie banners and tours on first sign-in are not part of the task: dismiss them before capture, and leave them out of the redraw.\n- Never show real customer data, a working share link, a real phone number or an API key in a capture you keep or a frame you render.\n",
|
|
11
|
-
"references/intro.md": "# Mografy intro reference\n\nUse the existing intro as a reference for multi-shot storytelling, deterministic transitions, responsive text layout, and a branded ending. Read [the project settings](__REPOSITORY__/examples/mografy-intro/mografy.json), [scenes/main.ts](__REPOSITORY__/examples/mografy-intro/scenes/main.ts), and [scenes/logo.ts](__REPOSITORY__/examples/mografy-intro/scenes/logo.ts) before adapting it. The current source is a 1920 × 1080, twelve-second, 30fps Canvas scene on a paper-colored background with ink and teal accents.\n\n## Four implemented beats\n\n| Beat | Active source window | Function | What to learn |\n| --- | --- | --- | --- |\n| Code becomes an idea | 0.1–2.6 seconds | `beatCode` | Measured colored text segments, time-based typing/caret, and a caption. |\n| Playback and scrubbing | 2.4–6.9 seconds | `beatScrub` | A preview frame, playhead, and reverse scrubbing derived from the same absolute time. |\n| An external edit updates the player | 6.8–9.9 seconds | `beatChat` | Stable wrapping before typing, a reply, color/timing change, and an update toast. |\n| Brand ending | 9.85–12 seconds | `beatLogo` | Original logo pieces revealed with clipping, staggered wordmark letters, and a closing tagline. |\n\nThe active windows overlap deliberately during transitions. They describe this implementation rather than a mandatory storyboard schedule. `renderFrame` calls all four beat functions; each derives visibility and motion from time. `window_` combines entrance and exit curves, and `revealPiece` clips the original logo paths. Read the real source when deciding the pose or overlap at a particular instant.\n\n## Assets and copy\n\n- ABeeZee Regular is loaded through `mografy.json`; keep its bundled `assets/OFL.txt` when copying the font. The scene uses Canvas text measurement and `wrap` to fit longer copy.\n- The existing music file is `assets/intro-music.mp3`, with a 120 BPM grid, offset −0.1 seconds, four beats per bar, and gain 1. The logo entrance starts around the 9.9-second cue. Preserve the asset and settings when adapting this specific project unless the brief requests a change.\n- The five subtitle params are `codeCaption`, `playCaption`, `scrubCaption`, `chatCaption`, and `tagline`. `request` is ordinary scene copy. `accent`, `ink`, and `vignette` affect the image.\n- The current film's text mentions Claude. Read the exact scene copy before describing or translating it. For a new brief, adapt the script deliberately; the product workflow also supports Codex.\n\n## Apply the reference\n\nUse its sequence structure to plan setup, demonstration, change, and payoff. Retain relevant motion principles, clear focal points, readable holds, and continuity between shots. Reuse the technique in the selected project's own scene modules, with its assets and proportions. For small reusable motifs, read [built-in-components.md](built-in-components.md).\n\nSave a project-specific English storyboard under `storyboards/` when requested, following [storyboard.md](storyboard.md). Codex creates visual boards with image generation; Claude uses Artifacts or a standalone local HTML/Canvas preview. A new storyboard may require longer text holds than this existing twelve-second film.\n\n## Validation and review\n\nFrom the owning repository, use:\n\n```sh\
|
|
12
|
-
"references/layers.md": "# Layers\n\nA layer is one part of the film the user may want to retime, hide, copy, rename, lock or reorder in the timeline: a title, a card, a background, a subtitle. Declare the parts with `timeline(...)` from `@mografy/runtime`. The editor never edits scene code: it writes only its changes (the **edits**) to `scenes/timeline.json`, and the server compiles and trial-renders them like any other edit, so the player, review sheets and exports agree.\n\n## Declare from the beat table\n\nThe beat table stays the one source of time. Take each layer's `in` and `out` from `beats([...])`, never from separate numbers:\n\n```ts\nimport { beats, timeline } from '@mografy/runtime';\nimport edits from './timeline.json'; // create it as {}; the editor rewrites it\n\nexport const BEATS = beats([{ title: 'Open', end: 3 }, { title: 'Offer', end: 8 }, { title: 'Close', end: 12 }]);\nconst [open, offer, close] = BEATS.list;\nexport const TIMELINE = timeline([\n // top to bottom, as the timeline lists them\n { id: 'title', name: 'Title', in: open!.start + .4, out: offer!.end, enter: 'fade-up', exit: 'fade', subtitles: ['title'] },\n { id: 'card', name: 'Offer card', in: offer!.start, out: close!.end, enter: 'pop' },\n { id: 'logo', name: 'Logo', in: close!.start, out: close!.end, enter: 'blur-in' },\n { id: 'bg', name: 'Background', in: 0, out: BEATS.duration, still: true, locked: true },\n], edits);\nexport const meta = { /* width, height, duration, fps, background */ shots: BEATS.shots, layers: TIMELINE.meta };\n```\n\n- `id`: stable, `[\\w-]`, at most 64 characters. Once the project has edits, never rename an id: the user's changes to it would be orphaned.\n- `enter` / `exit`: `none`, `fade`, `fade-up`, `pop`, `blur-in`, `wipe` (see [motion-design.md](motion-design.md)). Each motion has a fixed length; lengthening a layer lengthens only its hold.\n- `locked: true` keeps the editor from moving it (a background, a camera bed). `hidden: true` starts it hidden.\n- `still: true` for a part that does not change with time while at rest (a background, a static panel): it is drawn once and its pixels are reused; its motions still apply.\n- `subtitles`: the `role: 'subtitle'` parameters the layer shows, so the subtitle list can jump to it.\n- `colour`: the layer's track colour in the editor (not the film).\n\n## Draw: pick one of three\n\n| Method | Use when | Editor's reorder applies |\n| --- | --- | --- |\n| `TIMELINE.draw(c, time, { title: (c, own, look) => …, … }, anchors)` | Each part can be drawn on its own; the usual choice | Yes |\n| `TIMELINE.drawFrame(ctx, time, { … }, anchors)` | The scene draws with the FrameContext (`ctx.draw`) | Yes |\n| `TIMELINE.each(c, 'title', time, (c, own, look) => …, anchor)` | Parts share a camera, a mask or one pass and must stay in the scene's own order | No |\n\n- The callbacks are keyed by the **base** id: a copy made in the editor has its own id but draws with its original's function.\n- `own` is the layer's own time: its declared window stretched onto where the editor put it, so a part keeps its internal timing when the user moves or retimes it. Animate inside a layer from `own`, not from film time.\n- `look` holds `opacity`, `y`, `scale`, `blur`, `reveal`, `local` and `progress`; the methods apply it for you (one `layer` so groups fade as one, `blurLayer` for blur, a clip for `wipe`). `anchors` (per base id) is where rise and scale happen; default the frame's centre.\n- `TIMELINE.time(id, t)` gives the own time for code outside the three methods; `TIMELINE.visible(t)` lists what is on screen.\n\n## Layering an existing film\n\n1. Name the parts the user would want to adjust; one layer each. Parts that cannot be separated stay one layer.\n2. Give each the window it is on screen, from the beat table.\n3. Wrap its existing drawing in `draw`, `drawFrame` or `each`, reading time from `own`.\n4. Verify the layered film is unchanged: with an empty `timeline.json`, compare frame hashes at 12 times spread over the film against the original (`mografy review` sheets side by side as a fallback). Every frame must match.\n\n## Films without layers\n\nA scene that declares no layers still gets editable layers: the build splits it into one layer per shot (from `meta.shots`, else the older `slides.shots` some `mografy.json` files still carry), and the editor can retime, reorder, copy and give each shot an enter and exit motion. Old projects get this without any change. When a multi-shot film has no `meta.shots`, add them from the beat table (`shots: BEATS.shots`) so the timeline shows its shots. Declare real layers when the user wants to adjust parts inside a shot.\n\n## Edits are the user's\n\n- Never write `timeline.json` by hand to animate. Change the declarations.\n- An edit wins over the declaration. When the user asks you to change a time they already dragged, the declaration alone will not show; say so, and tell them they can revert that layer in the editor.\n- Read `scenes/timeline.json` before changing a layered film, so you know what the user has adjusted.\n\n## Colours the user changed\n\nThe editor's **Design** tab (設計, in the right panel) shows the colours of the shot under the playhead and can swap any colour the film draws for another, without touching scene code. The swaps live in `mografy.json` as `\"colors\": { \"#12b5a5\": \"#e05d44\" }` (from → to, `#rrggbb`) and apply in the player, review sheets and every export. Alpha is kept, and gradients and shadows follow.\n\n- Read `colors` before changing a film's palette. A swap wins over the scene: when you change a colour the user already swapped, tell them, and leave the swap alone unless they ask you to fold it into the scene (then write the new value in the scene's tokens and delete that key).\n- Keep palette values as tokens in one place in the scene and in `style.md`, so each shot lists a short, clean palette.\n- The same tab edits `style.md` in place, and its **Open design system** page (設計系統) gathers the film's motions, colours, fonts and `timeline.json` in one view. Everything else the user decides about the look (motion, timing, type, rules) goes there, not into editor controls: read `style.md` again before every change, because the user may have edited it since your last turn, and apply new rules to the scene code.\n",
|
|
13
|
-
"references/mcp.md": "# The Mografy MCP tools\n\n`mografy mcp` runs a local MCP server over stdio, so an agent can make and check films through tool calls instead of a shell. Connect it once:\n\n```sh\nclaude mcp add mografy -- mografy mcp\ncodex mcp add mografy -- mografy mcp\n```\n\nEvery tool takes `project`: an absolute folder, or a folder name from `list_projects`; it defaults to `MOGRAFY_PROJECT` or the current folder. While the player has the project open, the tools work through the player, so the user sees each change there; otherwise the server opens the project itself and rebuilds it from disk before each call.\n\n## Tools and their commands\n\n| Tool | Command | Use it to |\n| --- | --- | --- |\n| `list_projects` | (the player's project list) | Find a project's folder; `include_builtin` adds the sixteen component projects |\n| `project_info` | (the player's inspector) | Read size, duration, shots, tempo, source files, params, settings and the last build error |\n| `create_project` | (the player's New project) | Start a project from the starter scene; `aspect_ratio: \"9:16\"` for a portrait film. Then write `style.md`, the scene, and check it |\n| `read_source` | (read the files) | Read the scene entry and every file of its current build |\n| `write_source` | (edit the files) | Replace scene files. They are compiled and trial-rendered first and written only if that passes; a failure returns the error and changes nothing |\n| `check` | `mografy check [--motion]` | Shot table, tempo, frame cost, `style.md`; `motion: true` adds the jump, hard start and hard stop scan |\n| `render_frame` | (none; `mografy review` writes sheets) | Look at one moment as a PNG; `kind: \"output\"` is the exported frame, `\"raw\"` the scene at exactly that time |\n| `review` | `mografy review` | Write the stop-frame and transition sheets to `renders/` and return them as images |\n| `open_player` | `mografy dev` | Show the project in the player, or switch the open player to it |\n| `export` | `mografy export` | Write a file to `renders/` (only when the user asks for one); `format`, `preset`, `codec`, `orientation`, `output` |\n| `read_guide` | (this Skill) | Read `SKILL.md` or a reference, when the Skill is not installed for the host |\n\n## How to work with them\n\n- Read the guide first: when the host has not installed this Skill, call `read_guide` (no topic) before writing a scene, then the references its table names.\n- Change scenes with `write_source` even when you also have file access, when you want the change checked before it lands. Send each file whole.\n- After every `write_source`, run `check` and fix its warnings; before delivery run `check` with `motion: true` and `review`, and look at every sheet it returns.\n- Never send `scenes/timeline.json` through `write_source`: it holds the user's edits from the editor (see [layers.md](layers.md)). `mografy.json` is settings, not source.\n- `export` blocks until the file is written and reports progress; cancelling the call cancels the export.\n",
|
|
14
|
-
"references/motion-design.md": "# Motion design decisions\n\nUse this when creating a Mografy animation or revising its visual concept, choreography, pacing, or transitions, in any host. A copy correction, asset swap, export, compression, or isolated timing fix needs only the relevant local check, not a new concept or storyboard. Preserve the user's chosen direction and requested scope. Continue authorized implementation without adding an approval gate.\n\n## Establish a visual idea before scene code\n\nWrite a compact direction in the existing `storyboards/storyboard.md` for a planned sequence, or in a short working note for a small animation. Reuse an existing plan rather than creating parallel briefs. Make these decisions concrete:\n\n- **Message and visual mechanism:** what should the viewer understand, and what visible change expresses it? For example, \"independent marks align into one readable signal\" defines an action; \"premium, smooth, dynamic\" does not.\n- **Graphic language:** describe the type hierarchy, shape proportions, palette roles, negative space, and framing at the actual aspect ratio. Use supplied artwork and the project's identity. Do not turn a real UI walkthrough into an abstract brand film or redraw a supplied logo to make a transition easier.\n- **Attention and rhythm:** name the focal subject and the moments of action, emphasis, and rest. Decide what stays still while the lead moves. Music can supply cues; a film does not need every element to move on every beat.\n- **Continuity:** identify what the viewer follows across a shot boundary: the same object, alignment, direction, contour, color field, or a deliberate contrasting cut. Specify its outgoing and incoming states.\n\nUse the nearest public [component](built-in-components.md) or [intro](intro.md), supplied reference, or existing project shot to answer a specific design question. Inspect its source and actual frames or playback when available. Note the useful relationship (such as a playhead causing a visible state change), then adapt it to this brief. A catalog of components is a technical vocabulary, not a shot list. Do not copy private project material into shared guidance.\n\nFor a new concept that needs shot planning, follow [storyboard.md](storyboard.md) (image generation in Codex, Artifacts or a local HTML board in Claude). Use those panels to choose composition and hierarchy; keep exact geometry, copy, and timing in the written plan. Generated imagery can suggest something the Canvas implementation never produces. Compare implemented frames with the intended key poses rather than treating the generated board as proof of quality.\n\n## Default taste\n\nWhen the project's `style.md` and the brief say nothing else, start from [taste.md](taste.md): hold times, type sizes, safe margins, still holds, one logo at the end and sustained sound, each with its reason. The project's own decisions always win.\n\n## Compose the key poses, then connect them\n\nFor each important action, define the before, decisive, and resolved compositions. Specify useful positions or proportions, the dominant scale, the supporting elements, and the held result. A paused key pose should communicate the intended message before decorative movement is added. Check it at the delivered viewing size, especially type and diagrams on a phone.\n\nTranslate the action into a causal phrase:\n\n> The leading bar travels to the shared baseline; the other marks align in its wake; their alignment opens space for the headline; the resolved line holds under the words.\n\nThis phrase determines order, overlap, and attention. Only then choose durations, paths, pivots, and curves. Write the choreography in scene modules as pure functions of absolute `time`; follow the existing runtime contract. Keep layout and motion data out of `mografy.json`.\n\n### Worked example: an eight-second \"Find your focus.\" bumper\n\nThis is an original teaching example, not a mandatory look, schedule, or component recipe. It needs only Canvas marks and typography. Use another mechanism when the brief calls for one.\n\nThe optional [scene source](../../../../extras/motion-design.ts) implements this example; inspect its [actual Chromium key poses](../../../../docs/motion-design/poses.png) alongside the code when using it as a reference. Resolve these files from the current checkout when available. These poses show the implemented Canvas scene, not an image-generated concept board. The example uses a generic system sans-serif; choose project fonts for production work.\n\n| Time | Composition and action | Design reason |\n| --- | --- | --- |\n| 0.0–1.8 | Three short strokes sit at different heights in the central half of the frame. A longer lead stroke moves toward a common baseline; the other strokes follow with small offsets. Resolve into a single horizontal line by 1.2 and hold it. | The graphic change expresses finding order. One lead attracts the eye; the followers share its cause. |\n| 1.8–4.6 | Keep that same line at the same position and thickness at the boundary. It lengthens to the measured headline width while \"Find your focus.\" is exposed directly above it. Settle by 2.8; hold the readable composition. | The existing object becomes typographic structure. The headline gets a distinct reveal and a quiet reading interval. |\n| 4.6–8.0 | Keep the headline stable. The line retracts toward its optical center, leaving a short accent; allow a restrained delayed settle in the accent, then hold the complete end composition. | The ending resolves the opening idea. The viewer gets closure without a second competing entrance. |\n\nA weaker version would fade out the strokes, slide in an unrelated title card, and bounce everything until the end. That loses the graphic relationship and the reading hold even if each tween is technically correct. Improve the relationship between states before adding more effects.\n\n## Choose motion by its job\n\n| Job | Decisions that matter | Failure to check in the render |\n| --- | --- | --- |\n| Reveal or emphasis | Choose what is discovered first: silhouette, word, number, relationship, or result. Use contrast, a mask, spatial change, or a cut when it serves that order. A simple fade is appropriate for a quiet reveal. | Every object fades/slides in with equal prominence, so nothing leads the eye. |\n| Explanation | A cause visibly changes its result: a cursor presses a control, a value changes a chart, an object assembles into a system. Preserve real product behavior. | A decorative cursor or chart animates independently of the event it supposedly explains. |\n| Typography | Measure and compose the complete text first. Animate words or glyphs only where their order or rhythm adds meaning; keep the reading pose stable. | Text keeps scaling or drifting during its reading hold; long words or CJK copy change wrapping mid-reveal. |\n| Transition | Hand over shared geometry: the outgoing shot's last object becomes the incoming shot's first (see [film-architecture.md](film-architecture.md)). Otherwise make a cut whose change in scale, direction, or meaning is intentional. Brief-specific hard cuts and fades remain valid. | Unrelated panels reset to the center and repeat the same entrance; a wipe conceals a jump instead of connecting the scenes. |\n| Weight or response | Choose the pivot, contact, acceleration, overshoot, and delayed secondary response for the material. Rigid type and logos usually need different treatment from soft characters. | Every object uses the same spring or sinusoidal bob regardless of weight, material, or story. |\n| Held result | Give the message a readable still interval; secondary movement should reinforce it. | Motion continues merely to avoid stillness and competes with the takeaway. |\n\nTreat the easing and text-duration estimates in scene authoring as starting heuristics. Judge actual spacing and reading at the requested pace; do not apply one curve, stagger interval, or shot duration mechanically to every action. If copy cannot be read in the requested duration, resolve that conflict explicitly rather than speeding up the whole film. Choose the relevant [animation principles](animation-principles.md) after deciding the action; listing their names is not a design rationale.\n\n## Review design separately from technical correctness\n\nRun the existing `mografy check` and `mografy review` workflow. Technical validity, deterministic seeking, loop equality, or successful encoding proves those properties only. Judge the actual rendered animation against the visual direction:\n\n| Criterion | Evidence to inspect |\n| --- | --- |\n| Hierarchy and composition | At the before, decisive, and held poses, the intended subject reads first; type, spacing, and contrast work at output size. |\n| Motion meaning | The viewer can follow the cause and result of the lead action without reading the implementation or an explanation of its intent. |\n| Continuity | Inspect the frame before, within, and after each boundary. The promised object or relationship survives the handoff, or the intended cut reads clearly. |\n| Rhythm | Inspect the whole sequence at normal speed when playback is available, then dense action/transition samples. Action, emphasis, and rest are distinguishable; the ending has time to resolve. |\n| Craft | Check measured text, pivots, paths, contacts, overlap, final poses, and unwanted drift. For characters, inspect contact and passing poses; for graphics, inspect alignment and optical balance. |\n\nRecord a concrete observation with a time or frame, its effect on the viewer, and the correction when a criterion fails. \"The headline and diagram start together at 2.0s, so neither leads; delay the supporting caption until the diagram resolves\" is useful. \"Looks premium; all twelve principles applied\" is not evidence. Fix the observed issue and review the affected sequence again.\n\nStills and transition strips show composition and sampled continuity; they do not by themselves establish the experience of continuous playback. If the available tools cannot inspect playback, say which frames and intervals were inspected and leave temporal quality unverified. Likewise, describe reference fidelity only after comparing the actual rendered output with the reference. Do not claim a visual-quality improvement from a successful build or a written plan alone.\n\n## Evaluate guidance changes on actual tasks\n\nWhen evaluating a Skill revision in either host, use the same brief, assets, dimensions, and time budget for the previous and revised guidance. Keep each run's source, plan, actual frames, playable output when available, and critique separate. Do not label the new version as the preferred answer for the reviewer. These focused briefs exercise different decisions:\n\n1. **Motion concept:** \"Create an eight-second 16:9 bumper for the fictional wordmark LUMA, using only typography and simple Canvas geometry. Communicate 'Many ideas. One direction.' End on the wordmark.\"\n2. **Explanatory causality:** \"Create a six-second 9:16 animation showing a task move from waiting to complete after a button press. Preserve the visible cause/result and let the result read at phone size.\"\n3. **Scope control:** \"In this existing animation, change only the last title and lengthen its final hold by half a second. Preserve its established composition and other timings.\"\n\nFor the first two, compare the five criteria above using actual frames and playback. Let a reviewer state which version communicates the brief more clearly and cite the moment that determined the choice; document ties or regressions. For the third, verify that the requested local edit did not trigger a redesign or an unnecessary storyboard/image-generation cycle. Keep prompt-following and technical checks separate from this visual judgment. A rubric or self-score alone does not establish an improvement, and a run in one host does not establish behavior in another or a general model ranking.\n",
|
|
15
|
-
"references/music.md": "# Contextual music\n\n[score.py](__REPOSITORY__/extras/music/score.py) generates a film's score from its context. Instead of finding a track and cutting the animation to it, the agent describes what each part of the film needs in a cue file, `music.json`, and the generator synthesises music that follows it: sections with a mood and an energy level, and hits on the exact seconds where something happens on screen. When the animation's timing changes, update the cues and generate again; the music stays in sync. [music-example.json](__REPOSITORY__/extras/music/music-example.json) scores the twelve-second intro.\n\n## When to use it\n\nUse it when the user wants music and has none, or asks for music that fits the film: product intros, logo stings, explainers, and abstract or particle pieces where atmosphere, rhythm and hits matter more than a memorable melody. If the user supplies a track, use theirs and align the scene to `ctx.beat(time)` instead. For a song with vocals or a strong hook, write the same cues as a text brief for an external music tool or library search, and use the generator only as a placeholder.\n\n## Add to a project\n\nThe generator is an optional extra, not part of the installed template. It needs Python 3 with numpy; MP3 output uses ffmpeg, and the timeline image uses Pillow. If the project already has `music-src/score.py`, reuse it. Otherwise copy it from the current Mografy checkout (`extras/music/`) or download it:\n\n```sh\
|
|
16
|
-
"references/output.md": "# Output: aspect ratio, portrait films and export\n\nRead this when the brief names an aspect ratio, a social platform, a portrait (9:16) video, or an export size or format.\n\n## Landscape and portrait compositions\n\nRead `mografy.json.aspectRatio` before planning or editing. It is `\"16:9\"` (landscape) or `\"9:16\"` (portrait); when absent, use the scene's `meta.width / meta.height`. This is canvas configuration only. The main player has no orientation switch: it previews the authored scene at its configured dimensions. Output orientation is chosen only in the Export dialog and never changes the project or the main preview.\n\nWhen the user requests a future 9:16 video, explicitly record **9:16 portrait** in the brief before authoring. Treat this as the intended composition, not merely an export setting. Create the scene natively in portrait, tell the user that the preview follows the authored scene, and do not rely on fitting or cropping a landscape scene to satisfy a portrait brief. For a native social video, author `meta = { width: 1080, height: 1920, ... }` and set `aspectRatio: \"9:16\"` in the project. A landscape scene normally uses 1920 × 1080. The shared Runtime applies the saved aspect ratio to the logical canvas before setup and rendering, preserving the scene's short edge; both `SetupContext` and `FrameContext` receive the effective dimensions. Use `ctx.width` and `ctx.height`, never imported meta dimensions, for layout, backgrounds, clipping, and camera bounds. Branch with `const portrait = ctx.height > ctx.width` when the compositions differ. Stack portrait elements vertically, wrap copy to available width, and reposition the focal subject and subtitles. Do not rotate, stretch, or merely shrink a complete landscape shot into the portrait canvas. Fixed-coordinate scenes need a scene-code layout pass; an orientation toggle cannot infer their intended design.\n\nFor portrait social layouts, use conservative guides: leave about 8% above, 18% below, 6% on the left, and 12% on the right clear of critical copy and logos. Platform overlays vary; treat these as planning margins, not platform guarantees. Inspect at phone size, including long subtitles, entrances, exits, and transitions. If both outputs are requested, review both complete compositions and random seeks.\n\nMP4, WebM and MOV exports have landscape 1280 × 720 / 1920 × 1080 and portrait 720 × 1280 / 1080 × 1920 presets, selected with orientation icons. If output orientation differs from the authored scene, show Fit: `contain` (Fit entire scene, the default) or `cover` (Fill and crop). These fit the existing artwork without reauthoring the canvas. The dialog shows an actual paused-frame preview of the output. Choose `reflow` (Adapt layout) for deliberately responsive scenes, including all sixteen built-in components: it passes the output canvas dimensions to scene code so portrait sizes, card arrangements, and text wrapping adapt. It is not a player orientation control. Export overrides do not change the saved canvas. CLI: `mografy export [project] --format mp4 --orientation portrait --resolution 1080p` (or `landscape`); without overrides it uses the saved canvas and render scale. WebM uses VP9 video and optional Opus audio, with constant quality (CRF 32) by default; MP4 uses 10-bit H.265 (HEVC, tagged `hvc1`) with 48 kHz AAC by default, about half the size of H.264 at the same look. `--preset share`, Encoder → Share in the Export dialog, `--codec h264` or `render.codec: \"h264\"` in `mografy.json` gives H.264 for a website `<video>`, Firefox or Windows PCs without HEVC support; ask which when the file is going somewhere other than QuickTime, a phone or a social upload. MP4 `crf` and `bitrate` are on the H.264 scale for both codecs. Use `--format webm` for WebM. Higher WebM CRF values produce smaller files with less detail. MP4 and VP9 CRF values are codec-specific. Both video formats support the same orientation, resolution, sampling, and output effects. Player, stills, thumbnails, review, and exports share the effective canvas and output effects.\n\n## Export\n\nExport with `mografy export [project] --format mp4|webm|mov|lottie|svga`, or `--preset share|high|fast|master`: `share` is H.264 for any player, `high` (the default) H.265 10-bit, `fast` the hardware H.265 encoder (VideoToolbox, NVENC, Quick Sync, AMF; software fallback), `master` ProRes 422 HQ in a MOV for editing. Ask which when the destination is unclear: a website, Firefox or an unknown Windows PC needs `share`. The command prints capture and encoding or packaging progress and writes the finished file under `renders/`. Press Ctrl+C to cancel a CLI export. When `mografy dev` is running, player exports also print progress in that terminal and can be stopped with `mografy export [project] --cancel`. Batch export: `mografy export <project> <project>...` or `mografy export --all [folder]` (default: the projects folder; `_`-prefixed folders skipped) exports each in turn with the same options, skips past failures and prints a summary; in the player, **Batch** next to **Export** opens the same as a dialog (format, encoder, resolution Own/720p/1080p by shorter side, frame rate, Use less memory). Export only when the user asks for a file.\n",
|
|
17
|
-
"references/performance.md": "# Performance: cheap frames and smooth motion\n\n\"It stutters\" (卡, 卡卡的, 不順) means one of two different problems. Find out which before changing anything:\n\n| Problem | What you see | How to find it | Fix with |\n| --- | --- | --- | --- |\n| **Slow frames** | The preview drops frames; the same film exported to MP4 plays smoothly | `mografy check`: frame cost, filters per frame, canvases per frame | The cost tables below |\n| **Choppy motion** | The exported MP4 also looks rough: something jumps, starts at full speed or stops dead | `mografy check --motion`: jumps, hard starts and hard stops with their times | **Smooth motion** below, [film-architecture.md](film-architecture.md) and [taste.md](taste.md) |\n\nMost stutter reports on finished films turn out to be choppy motion, not slow frames. Run both checks before delivery.\n\n## Checklist\n\nSlow frames:\n\n- [ ] `mografy check` shows no frame-cost warning: median well under 33 ms at 1920 × 1080 on a desktop, nothing over 100 ms, at most 8 filters per frame, no canvases created per frame.\n- [ ] No `ctx.filter` around a group of draws; groups go through `blurLayer`, type through `blurText` / `blurWords`, light through `bloom`.\n- [ ] Every `layer`, `blurLayer` and `bloom` smaller than about half the frame has `bounds`.\n- [ ] Everything that does not change is made once in `setup`: paths, text layout, UI card textures (cached per visual state), sprites, backgrounds, noise tiles.\n- [ ] No `getImageData` per frame; grain is a small tile drawn as a pattern, not a pixel loop.\n- [ ] One Three.js stage at most, skipped while hidden.\n\nChoppy motion:\n\n- [ ] `mografy check --motion` reports no jump, hard start or hard stop you did not intend.\n- [ ] Each followed object is one track across a handoff: where one shot's version ends, the next one's starts, at the same position, size and colour.\n- [ ] Moves through several poses are one `keys` curve, not separately eased segments.\n- [ ] Entrances use `springs.*` / `spring()` over their whole duration; no entrance moves on its first frame more than on its second.\n- [ ] Fades end at 0, never at a small alpha that then disappears; base colours switch before a wipe finishes covering them.\n- [ ] The camera does not reverse direction every second or two, and holds still during clicks and reading.\n- [ ] A move across more than half the frame takes at least 0.6 s, an exit at least 0.4 s ([taste.md](taste.md)).\n\n## What costs what on a 2D canvas\n\n| Operation | Cost | Use instead |\n| --- | --- | --- |\n| `ctx.canvas.filter = 'blur(…)'` around several draws | One blur pass per fill, stroke and glyph run, each over a large area. Dozens per frame takes seconds. | `blurLayer(c, name, radius, draw)`: draw once into a layer, blur the layer once. |\n| A filter blur per word or glyph | One pass per word | `blurText` / `blurWords`: the glyph's own shadow, about the cost of sharp text. |\n| `shadowBlur` on many shapes | One mask blur each; cheap for a few, costly for hundreds | `surface()` for cards; one shadow on a merged path; or a blurred layer of the silhouettes. |\n| Large-radius blur at full resolution | Grows with radius and area | Blur at half or quarter resolution (`blurLayer` does this automatically above 12 and 48 device pixels; `bloom` works at quarter resolution). |\n| A full-frame layer for a small object | A full 1920 × 1080 (or 4K) composite | Pass `bounds: [x, y, w, h]` to `layer`, `blurLayer` and `bloom`. |\n| `new OffscreenCanvas` / `document.createElement('canvas')` in `renderFrame` | Allocation and garbage collection every frame (33 MB per 4K canvas) | `buffer(name, w, h)` and the layer helpers reuse pooled memory. |\n| `getImageData` / `putImageData` per frame | A GPU → CPU copy and a full-frame loop | Precompute in `setup`; use compositing modes instead of pixel loops. |\n| `new Path2D(svgString)`, parsing, `measureText` of fixed copy each frame | Repeated parsing and layout | Build paths, glyph widths and layouts once in `setup` (or as module constants) and read them per frame. |\n| Thousands of separate `fill()` calls | Per-call overhead | Batch shapes of one style into one path; draw particles as a pre-rendered sprite with `drawImage`. |\n| A Three.js stage | A WebGL render plus a GPU → CPU copy into the 2D frame on CPU canvases | One stage per film; skip `stage()` while the 3D layer is invisible; keep its size to the area it covers. |\n| Re-drawing a static UI card (rows, icons, text) every frame | Dozens of fills and glyph runs per card per frame | Draw each card state once into a cached texture and `drawImage` it; a flat card is one draw. |\n| Per-pixel grain or noise each frame | A full-frame loop | A small noise tile as a pattern, offset by `Math.round(time * 30)`, at low alpha. |\n| `imageSmoothingQuality = 'high'` when scaling a soft buffer up | High-quality resampling of the whole frame | `'low'` for blurred or glow buffers (the layer helpers already do this). |\n\n## Opening and switching speed\n\nFrame cost decides playback; `setup` and the project's files decide how long a project takes to open. The player shows a project as soon as its scene module is read (its trial render runs in the background a few seconds later, and its result is kept in `.mografy/verified.json`, so an unchanged scene reopens without one). It keeps the last two projects loaded, so switching back to one is immediate; what remains is each project's first setup:\n\n| Cost on open | Fix |\n| --- | --- |\n| Every font in `mografy.json` is fetched and parsed. The CJK subsets are about 4–5 MB each. | `python3 extras/cjk/subset-film-fonts.py <project>` keeps only the characters the film draws (about 9.5 MB → 300 KB) and points `mografy.json` at the result. Run it again after every copy change; it always rebuilds from the original fonts. |\n| Procedural textures (paper, wood, noise) drawn pixel by pixel in `setup` | Draw each once and keep it: store the canvas as a PNG in Cache Storage under a key that includes a version number, decode it on later opens, and draw it again when the cache is empty (exports and checks start with none, so frames stay identical). Bump the version when the generator changes. |\n| `getImageData` on a canvas you just drew, to add noise | It waits for the GPU and copies the canvas back. Fill a `new ImageData(w, h)` yourself and `putImageData` it, or draw the noise with shapes. |\n| A 3D stage: shader compilation and texture uploads | See **Cost** in [three-d.md](three-d.md): keep the light count constant, `compileAsync` in setup, share textures. |\n\n## Coordinates and units\n\nThe runtime gives scenes a logical context (`ctx.canvas`, `ctx.withCanvas`) whose units are film pixels: it scales transforms, `shadowBlur`, shadow offsets and filter lengths by the output scale for you. Two things it cannot do:\n\n- **Offscreen contexts are native.** Lengths you set on your own offscreen context (`filter`, `shadowBlur`, `lineWidth` after `setTransform`) are device pixels. Multiply by `devScale(c)` of the context you are copying from, or use the layer helpers, which size and scale for you.\n- **Filters and shadows ignore the transform.** A blur set inside a camera zoom of 2 is not doubled. `blurLayer`, `blurText` and `bloom` take their radius in the current units and include the camera; when you set a filter yourself, multiply by `devScale(c)`.\n\nSize every offscreen buffer from the film frame (1920 × 1080 logical × output scale), never from `c.canvas.width`: the player may hand a canvas whose size differs from the frame's transform, and a buffer sized from it clips the picture to a square or a corner. `layer`, `blurLayer`, `bloom` and `buffer` all work in film coordinates; `outputScale(c)` and `devScale(c)` give the factors when you need them.\n\nInside a `layer`, `blurLayer` or `bloom` callback, draw with the context the callback receives. `blurWords`, `riseWords`, `text` and `surface` accept it as their first argument.\n\n## Smooth motion\n\n`mografy check --motion` draws the whole film at 30 frames per second at quarter size and compares each frame with the next. It reports:\n\n| Report | What it usually is | Fix |\n| --- | --- | --- |\n| **Jump**: one frame changes far more than the frames around it | Two tracks that do not meet at a handoff (a dot that ends at one place while the ring starts at another); a colour or element that switches in one frame; a hard cut | Make the followed object one track; animate the switch; keep a cut only when it is a deliberate break (a new act, a drop in the music) |\n| **Hard start**: motion leaves a still frame at full speed | An entrance with no ease-in; an element that appears already moving; a spring whose first frame jumps | `springs.out` / `spring()`; start the move from rest; let a camera move begin up to 0.5 s before the action |\n| **Hard stop**: motion halts at full speed | Separately eased segments chained together; a fade that stops at 0.1 and then vanishes; a spring cut off before it settles; content removed while it is still moving | One `keys` curve through the poses; fade to 0; let springs finish; overlap exits with the next entrance |\n\nEach line lists times: render those frames (`review.times`, or `review.transitions` around them) and look before changing anything. The detector cannot tell a deliberate cut from a mistake, so a cut it reports can stay. It measures change on screen, so a slow move of a large bright shape and a fast move of a small one can read the same; trust the frames, not the number.\n\nOther causes of choppy motion it cannot see: a spring that settles in a third of its duration (the object shoots off, then sits; use the runtime springs), a camera that reverses its zoom every 1.5 s, a ring or caret that hops from letter to letter instead of gliding on a continuous position.\n\n## Canvas gotchas\n\n- `ctx.filter` blur lengths are in destination (device) pixels: scale them by the transform you draw with, not by the buffer's own scale.\n- An opaque full-size `fillRect` on a pooled `OffscreenCanvas` can be dropped by Chromium; cap such a fill's alpha at 0.996.\n- When a wipe or flood changes the base colour, switch the colour slightly before the wipe reaches 1, or one frame flashes the old colour.\n\n## Measuring\n\n1. Run `mografy check [project]`. It prints `Frame cost at W×H (CPU canvas, N frames): median … ms, slowest … ms at …s` and the warnings. Add `--motion` to scan the motion as well; it draws every frame at quarter size (about 15 s for a 60 s film on a cloud CPU).\n2. For the slowest times, find the cause by switching parts off: comment out a layer, a blur or a particle system and check again. The cost is almost always one of the rows above.\n3. When the preview is slow but `mografy check` is fine, check the player: `MOGRAFY_HMR=0 mografy dev` serves the production build of the player instead of the development one.\n\nFrame cost in the cloud or in CI is several times higher than on a desktop GPU; compare numbers from the same machine, and look at the ratio between frames rather than the absolute value.\n",
|
|
18
|
-
"references/product-walkthrough.md": "# Product walkthroughs: redraw the app, film the action\n\n[walkthrough.ts](__REPOSITORY__/extras/walkthrough/walkthrough.ts) turns a product's screens into a film. Claude or Codex look at screenshots of each step that the user provides, redraw the real UI as large, simplified cards, and film only the action on each card. Every card grows out of the control that was just used, one film camera frames the whole piece while each card pushes in on its own control with a local zoom, and a big cursor (or a finger tap) does the clicking. [walkthrough-demo.ts](__REPOSITORY__/extras/walkthrough/walkthrough-demo.ts) is a twelve-second tour: a fictional quoting app goes from an empty list to an AI-drafted quote to a shared link in four cards.\n\n## When to use it\n\nUse it for any film made from a web or mobile app's screens (for step-by-step tutorial clips, one per step, also read [how-to-film.md](how-to-film.md)): product demos, feature explainers and tutorials, onboarding and help clips, what's-new shorts, mobile app previews, social cut-downs and landing-page loops. Typical requests: \"turn these screenshots into a walkthrough\", \"redraw the UI simpler and only film the interactions\" (重繪、介面簡化、只拍操作細節).\n\nFor a short loop of one to three actions (a landing-page hero, a feature card, a phone moment), use the Stage extra in [ui-stage.md](ui-stage.md) instead: a script over state, windows cropped by the frame, placeholder lines and a seamless loop.\n\nUse plates from `cinema.ts` ([camera-transitions.md](camera-transitions.md)) when the footage itself should stay a screen recording, and `three.ts` ([three-d.md](three-d.md)) when a device model must turn in 3D.\n\n## Add to a project\n\nThe helper is an optional extra, not part of the installed template. If the project already has `scenes/walkthrough.ts`, read and reuse it. Otherwise copy it from the current Mografy checkout (`extras/walkthrough/`) or download it:\n\n```sh\nmografy add walkthrough projects/<name>\n```\n\n`mografy add` copies from this checkout's `extras/` folder, or from GitHub when it is missing, keeps any project file that differs from the extra (`--force` replaces it), and prints the import line. Without the `mografy` command, download the same files from `https://raw.githubusercontent.com/mografy/mografy/main/extras/walkthrough/`.\n\nImport it locally (`import { createKit, camAt, withCamera as withCardZoom, cursorAt } from './walkthrough.js'`), and take `springs`, `cameraPath`, `withCamera`, `beats` and `blurText` from `@mografy/runtime`. The extra's `withCamera` is a card-local zoom, so rename it on import to keep it apart from the runtime's film camera. Copy `walkthrough-demo.ts` too when you want a working starting point; it shows every helper in context. For Chinese or Japanese UI copy, add the CJK fonts from [cjk-typography.md](cjk-typography.md) and put `\"Noto Sans TC\"` (or the project's CJK family) in the theme's `font` stack.\n\n## Choose the scenario first\n\nThe same kit serves every scenario; length, pacing, captions and the pointer change.\n\n| Scenario | Length and format | Shots | Pointer | Text on screen | Pace and sound |\n| --- | --- | --- | --- | --- | --- |\n| Product demo | 20–45 s, 16:9 | Brand title, 4–6 detail shots of the main flow, one result, logo end card | Big cursor | Little: the product's own copy is the text; title at the start, tagline and URL at the end | Calm; clicks on bar lines when there is music |\n| Feature explainer or tutorial | 45–90 s, 16:9 | One shot per step, 4–8 s each, every result held long enough to read | Cursor with slower moves (up to 1.1 s) | Big step titles beside or above the card (\"1 Describe the job\") | Calm; music optional and low |\n| What's new / single feature | 8–15 s, 16:9 or 1:1 | Before → the one action → result, two or three shots | Cursor | One headline plus a \"New\" chip | One musical hit on the result |\n| Mobile app preview | 15–30 s, 9:16 (1080 × 1920) or a phone inside 16:9 | Full-bleed screens or a phone frame (`kit.phone`), one gesture per shot | Taps (`tap`), no cursor | Short captions in the top third, inside social safe margins | Brisk; light score |\n| Social cut-down | 6–15 s, 9:16 or 1:1 | Show the result in the first second, then the one or two actions that cause it, then the logo | Cursor or taps | Large burned-in captions, since most viewers watch muted | Fast in, hold the payoff |\n| Loop for a landing page or docs | 4–10 s, any size | One action that resets: the last frame equals the first | Optional | None | No music; loop on a hold; export a small MP4 or WebM |\n\nWhen the brief is unclear, ask which scenario it is and for how long; otherwise infer it from the request and say which one you chose.\n\n## Workflow\n\n1. **Collect the screens.** Agree on the steps that tell the story (usually 3–6) and ask the user for a screenshot of every state, with the exact labels and values where they are hard to read; when the user asks you to operate the product yourself and gives a test account, capture the states as in [how-to-film.md](how-to-film.md) instead. Keep them in `capture/` (numbered PNGs plus a `steps.json` with labels and values). Read the UI tokens from the screenshots or ask for them (primary colour, ink, borders, radius, fonts), and ask for the logo as SVG. Do not operate the user's site or account unless they asked you to and gave you a test account.\n2. **Choose the fidelity.** A *faithful rebuild* draws the whole app as it looks and films it with a camera; use it when viewers must recognise the real screens. A *simplified redraw* is the default when the user asks to redraw, simplify, or film only the interactions. Both use the real product: its layout logic, labels, colours and the order of states. Never invent features or screens.\n3. **Inventory each screenshot.** For every step write three lists: the *target* (the control the action touches: a field, button, row, dialog), the *context* needed to understand it (the card title, one neighbouring row), and *everything else* (navigation, filters, footers, badges, extra columns, tooltips).\n4. **Redraw.** Keep the brand tokens, the logo, the real labels and values of the target, its proportions and its state sequence (empty → focus → typing → loading → result → success). Drop everything else, collapse lists to 3–4 rows and tables to the columns the story needs, and turn copy the action does not need into `skeleton` bars. Raise type to about 1.3–1.6× the app's size so it reads at 1080p, keep at least 48 px of padding inside a card, and use one card style throughout ([taste.md](taste.md)). Build every step from the same kit parts so the film stays consistent.\n5. **Approve before animating.** Render one still per step (from a storyboard page or `mografy review`) and put it beside its screenshot in a sheet: screenshot | redraw. Show it to the user and adjust what to keep or drop before the motion work.\n6. **Film one action per shot.** Show the action, not just its arrival: the caret typing, the button squashing, rows sliding in, numbers counting up, a check mark drawing, a status chip changing colour. Hold each result 0.6–1.0 s before the next move.\n7. **Hand off between shots.** The control that finished the step grows into the next card (`kit.grow`): a button into a dialog, the send button into the sent message, a picked row into the field it fills, a copied link into the phone that opens it. Avoid plain cuts and cross-dissolves of text over UI.\n8. **One film camera, a local zoom per card.** Lay the cards out in one world and move one `cameraPath` across it ([film-architecture.md](film-architecture.md)); it carries the hand-offs from card to card. Inside each card's own transform, give the card a local zoom from its own `camAt` keys: hold, push in on the control about to be used (zoom 1.3–1.9), click, then pull back as the next card arrives. The cursor keys use functions of time so the pointer stays on its target while either moves.\n9. **Opener and ending.** Open on the brand (icon, title) and let its logo match-cut into the logo on the first card. End on the logo, the tagline and the public URL. Ask the user for the official tagline and URL.\n10. **Music and timing.** Follow [music.md](music.md) when the film needs a score, and put the clicks on bar lines. To change the length without rushing actions, borrow time from holds.\n11. **Verify.** `mografy check`, then `mografy review` with a transition strip over every hand-off. Look for overlapping cards, a push-in that crops the control, blank frames during a camera move, text too small at 1080p, and a cursor that drifts off its target. Show the user a preview with music before the final export.\n\n## API\n\n| Helper | Use |\n| --- | --- |\n| `createKit(theme)` | Drawing helpers bound to a theme (`primary`, `primaryDark`, `primarySoft`, `ink`, `mute`, `faint`, `line`, `surface`, `card`, `skeleton`, `shadow`, `font`, `mono`, `radius`). Returns `card`, `skeleton`, `chip`, `button`, `field`, `text`, `wrap`, `reveal`, `blurText`, `icon`, `check`, `ring`, `toast`, `grow`, `phone` and primitives (`box`, `hair`, `line`, `dot`, `rr`, `measure`, `mix`). |\n| `kit.card(c, rect)` | A floating card: wide soft shadow, contact shadow, hairline. Shadows scale with the current transform. |\n| `kit.grow(c, from, to, k, { outgoing, incoming, fromColor, toColor, fromRadius, toRadius })` | Container transform between two screen-space rects. Drive `k` with `springs.pop`. |\n| `kit.button(c, rect, label, { kind, hover, time, pressAt, icon })` | Squashes and rings on `pressAt`; `hover` tints it before the click. |\n| `kit.field(c, rect, { value, placeholder, size, lines, focus, caret, mono })` | An input with wrapping, focus ring and caret; feed `typed(text, p)` for typing. |\n| `kit.reveal(c, s, x, y, size, time, start, span)` | Per-character blur-in for titles and replies (no `c.filter`). For words and lines outside the kit, use the runtime's `blurText` and `blurWords`. |\n| `kit.toast`, `kit.check`, `kit.chip`, `kit.skeleton`, `kit.icon` | Notices, a check that draws itself, status pills, stand-in bars, line icons. |\n| `kit.phone(c, screenRect, draw)` | A phone body; `draw` paints the screen in its own coordinates. |\n| `camAt(keys, time)`, `withCamera(c, view, cam, draw)` | A card's local zoom from `[time, x, y, zoom]` keys, interpolated by `zoomPath` (a pure scale about a fixed point) with `springs.camera`. Import it as `withCardZoom`; the film camera is the runtime's `cameraPath` and `withCamera`. |\n| `toScreen`, `rectToScreen`, `scaleRect` | Map layout points and rects through a camera, for hand-offs and cursor targets. |\n| `cursorAt(keys, time)`, `drawCursor`, `clickRing`, `tap` | The big cursor (keys may be functions of time), click rings, and finger taps for phone scenes. |\n| `springs`, `spring(stiffness, damping)`, `sineInOut`, `press`, `typed`, `countUp`, `blink`, `visible` | Motion values: `springs.out` entrances, `springs.pop` cards and buttons (about 1.5 % overshoot), `springs.camera`, `springs.cursor`. |\n| `fluid(c, view, time, colors)`, `flood(c, view, r)` | Brand-colour atmosphere behind the cards, and a soft disc to flood it in or out. |\n\n## Motion that feels calm and expensive\n\n- Springs everywhere, never linear: critically damped for entrances and cameras, a touch of overshoot only for cards and buttons. Keep sine in-out for slow drifts.\n- Zoom as a pure scale about one point (`zoomPath`), so the picture never swings sideways while it scales.\n- Start camera moves a little before the cursor arrives; never move the camera during a click.\n- Give the cursor up to 1.1 s per move on a gentle arc; hold it on the control for the click.\n- Hold titles and results for the times in [taste.md](taste.md), and borrow time from static holds rather than speeding up actions: a first cut usually reads as too fast, because the viewer sees the screen for the first time while you already know it.\n\n## Pitfalls\n\n- Hand-off rects are in world space under the film camera, and in screen space only inside a card's local zoom: evaluate the outgoing card's zoom at the click time and the incoming card's zoom at the current time.\n- Push-ins belong to the card (its local zoom), not to the film camera; a film camera that zooms into one card crops the next one when they overlap during a hand-off.\n- Fade a card with its content through one `layer`, so its rows and shadow do not flash where they overlap.\n- Do not use `c.filter` for blur in a scene; use `kit.blurText`, the runtime's `blurText` / `blurLayer`, and the card shadows. The only scratch canvas is `fluid`'s, created once and redrawn every frame; see [performance.md](performance.md).\n- Use invented share tokens and demo customers; never show a real customer's data or a working private link.\n- When the copy changes, re-subset the CJK fonts so every new character is covered.\n- For portrait, lay out in 1080 × 1920 with `Viewport` set to the scene size; cards about 960 px wide, captions in the top third.\n",
|
|
19
|
-
"references/scene-authoring.md": "# Mografy scene authoring guide\n\nThis folder is a Mografy project. Animation content lives only in scene modules (normally `scenes/main.ts`). `mografy.json` stores project settings; never put layers, keyframes, or animation data in it.\n\nRun `mografy dev` to open the player. After a file change passes compilation and a real Chromium trial render, the player switches to the new version and stays at the same time.\n\n## File format\n\nA scene module exports `meta`, `params`, optional `setup`, and synchronous `renderFrame`:\n\n```ts\nimport { lerp, at, springs } from '@mografy/runtime';\nimport type { FrameContext, SetupContext } from '@mografy/runtime';\n\nexport const meta = { width: 1920, height: 1080, duration: 8, fps: 30, background: '#0f1115' };\n\nexport const params = {\n subtitle: { name: 'Subtitle', type: 'string' as const, role: 'subtitle' as const, default: 'Hello' },\n accent: { name: 'Accent', type: 'color' as const, default: '#12b5a5' },\n energy: { name: 'Energy', type: 'number' as const, default: 1, min: 0, max: 2, step: 0.01 },\n layout: { name: 'Layout', type: 'enum' as const, default: 'center', options: ['center', 'left'] },\n};\n\nexport async function setup(ctx: SetupContext) { /* load images or prepare seeded data once */ }\n\nexport function renderFrame(ctx: FrameContext, time: number, p: any) {\n const mografy = ctx.draw;\n mografy.fill(p.accent);\n mografy.circle(ctx.width / 2, ctx.height / 2, lerp(20, 160, at(time, 0.2, 1.2, springs.out)));\n}\n```\n\nThis is the shape of a single shot. A film with several shots or a moving camera is one world drawn through one camera from one shot table: read [film-architecture.md](film-architecture.md) and start from the `film-starter` showcase film (`mografy add film-starter <folder>` downloads it).\n\n## Aspect ratio\n\nRead `mografy.json.aspectRatio` (`\"16:9\"` or `\"9:16\"`) before planning or editing; when absent, use the scene's `meta.width / meta.height`. The runtime applies the saved ratio before setup, so `SetupContext` and `FrameContext` both receive the effective dimensions: use `ctx.width` and `ctx.height`, never imported meta dimensions, for layout, backgrounds, clipping and camera bounds. A portrait brief is authored natively at 1080 × 1920, never fitted from a landscape scene. Read [output.md](output.md) for portrait layout, safe margins, export sizes and formats.\n\n## Required behavior\n\n1. Treat `renderFrame` as a pure function of `time`, resolved params, and assets prepared by `setup`. Do not read a previous frame, accumulate module state, or read a clock. The player may seek in any order, and validation renders the same time twice to detect state leaks.\n2. `Math.random`, `Date.now`, and `performance.now` throw inside `renderFrame`. Prepare random choices once with `ctx.random()` in `setup`, and use `ctx.noise(...coordinates)` only for values that must vary per frame (see Randomness below).\n3. The runtime resets and fills the canvas before every call. `renderFrame` must finish synchronously.\n4. Import only files inside the project and `@mografy/runtime`.\n5. Put fonts in `assets/`, list them in `mografy.json` under `fonts`, then select them with `mografy.textFont('Family', 400)`. Only loaded weights are reliable.\n6. Express effect distances such as `shadowBlur`, shadow offsets, and filter pixels in logical units on `ctx.canvas`; the runtime scales them for output resolution, but not for your own transforms (a camera zoom) and not on your own offscreen contexts. Never set `ctx.filter` around a group of draws: blur a layer with `blurLayer`, type with `blurText` / `blurWords`, light with `bloom` (see [performance.md](performance.md)). Use `ctx.vignette(strength)` for a canvas vignette.\n7. Never create a canvas in `renderFrame`. Use `layer`, `blurLayer`, `bloom` or `buffer(name, w, h)`, which reuse pooled memory sized in film coordinates.\n8. Expose only important subtitles as `type: 'string', role: 'subtitle'` params. Titles, chat text, buttons, hints, code examples, and brand copy should stay in the scene for the AI to edit. Do not turn every string into an inspector field. Every color or numeric param must control a visible result. Do not add a dot grid unless the user explicitly asks for one.\n\n## Randomness\n\nDecide random things once, in `setup`, and store them in `ctx.assets`: particle positions, sizes, colours, delays, star fields, the order of a scatter. `ctx.random()` is seeded by the project seed, so the same seed always gives the same film, and changing `seed` in mografy.json gives a new but equally stable variation. In `renderFrame`, read those values and move them with `time`:\n\n```ts\nimport { spring } from '@mografy/runtime';\n\nexport function setup(ctx: SetupContext) {\n ctx.assets.dots = Array.from({ length: 120 }, () => ({\n x: ctx.random() * ctx.width, y: ctx.random() * ctx.height,\n size: 4 + ctx.random() * 10, delay: ctx.random() * .6,\n }));\n}\nexport function renderFrame(ctx: FrameContext, time: number) {\n for (const d of ctx.assets.dots as { x: number; y: number; size: number; delay: number }[]) {\n const k = spring(time, .4 + d.delay);\n ctx.draw.circle(d.x, d.y - 40 * (1 - k), d.size * k);\n }\n}\n```\n\nUse `ctx.noise(...coordinates)` when a value must change over time or space and cannot be listed in advance: flicker, jitter, grain-like texture, shimmer. Pass whole-number or stepped coordinates (`ctx.noise(i, Math.floor(time * 12))` for a 12 fps flicker) and smooth between steps yourself when the motion should glide. Noise is order-independent, so seeking stays exact. Never keep a random generator in module scope and call it during frames.\n\n## Tempo and music\n\nWhen a film is cut to music, declare its grid once in the scene and build every timing constant from it:\n\n```ts\nimport { tempoGrid } from '@mografy/runtime';\nconst tempo = { bpm: 120, beatsPerBar: 4 };\nexport const grid = tempoGrid(tempo); // grid.beat = 0.5 s, grid.bar = 2 s\nexport const meta = { width: 1920, height: 1080, duration: grid.onBar(12), fps: 30, background: '#101114', tempo };\nconst LOGO_IN = grid.onBar(10, 2); // bar 10, beat 3\n```\n\n`grid.onBar(n, k)` is the start of bar `n` plus `k` beats, `grid.onBeat(n)` a beat, and `grid.snap(t)` the nearest beat to a hand-picked moment. `ctx.beat(time)` returns `{ beat, bar, beatInBar, phase, period }` from the project audio, or from `meta.tempo` when the project has no audio yet, so pulses written against it work before the music exists. Keep `audio.bpm`, `audio.offset` and `audio.beatsPerBar` in mografy.json equal to `meta.tempo`; `mografy check` reports any difference. When the tempo changes, change `meta.tempo` only and every cut moves with it.\n\n## FrameContext\n\n| Member | Purpose |\n| --- | --- |\n| `ctx.draw` | Common drawing API. Prefer `const mografy = ctx.draw`; methods may be destructured. |\n| `ctx.canvas` | Native 2D context in logical coordinates. |\n| `ctx.width`, `ctx.height` | Logical canvas dimensions. |\n| `ctx.noise(...n)` | Seeded 0–1 noise independent of call order. |\n| `ctx.beat(time)` | `{ beat, bar, beatInBar, phase, period }` from the project audio, or `meta.tempo` without audio; otherwise `undefined`. |\n| `ctx.shadow(color, blur, x?, y?)`, `ctx.blur(px)`, `ctx.vignette(strength)` | Visual effects. |\n| `ctx.withCanvas(canvas => { ... })` | Synchronous scope that restores native state and Mografy fill/stroke state, including after an error. |\n| `ctx.clip(path2d, () => { ... }, rule?)` | Synchronous Path2D clipping scope; default rule is `nonzero`. |\n| `ctx.assets` | Read-only assets prepared by `setup`. |\n| `ctx.seed`, `ctx.renderScale` | Project seed and output scale. |\n\n`SetupContext` provides `ctx.random()`, `ctx.loadImage('assets/x.png')`, `ctx.assets`, `ctx.seed`, `ctx.width`, and `ctx.height`.\n\n## Time and motion helpers\n\nAll are pure functions of absolute time, imported from `@mografy/runtime`. Use them instead of writing curves, springs and cameras in each project. Defaults: `springs.out` for entrances and moves, `springs.pop` for cards and buttons, `springs.camera` for camera-like moves, `keys` for any move through several poses, `ease.inOutCubic` for exits and `ease.inOutSine` only for deliberate loops.\n\n| Helper | Use |\n| --- | --- |\n| `pr(time, start, end)` | Map a time range to 0–1 (clamped). |\n| `lerp(a, b, p)`, `clamp(n, min?, max?)`, `colorLerp(a, b, p, 'srgb' or 'linear')`, `hashNoise(seed, ...n)` | Interpolation and seeded hashing. |\n| `ease.linear / inQuad / outCubic / inOutCubic / outExpo / outQuart / outQuint / inOutQuart / inOutSine` | Easing curves for p in 0–1. `outQuart` for entrances and moves, `outQuint` for word rises, `inOutCubic` for exits, `inOutSine` for loops and drifts. |\n| `at(time, start, end, curve?)` | Eased progress of a time window (default `ease.outCubic`). |\n| `win(time, a, b, c, d, enter?, exit?)` | In over [a, b], out over [c, d]: 0 → 1 → 0. |\n| `spring(time, start, duration?, bounce?)` | A spring from 0 to 1 that settles exactly on 1 by `start + duration × 1.6` (defaults 0.7 s, bounce 0.18; bounce 0 has no overshoot). |\n| `springEase(stiffness?, damping?)`, `springs.out / pop / camera / cursor` | Spring easing curves for p in 0–1, normalised to land on 1; pass them as `curve` to `at`. `pop` overshoots about 1.5 %. |\n| `settle(time, start, duration, amplitude, cycles?)` | Follow-through: a decaying wobble around 0 after a landing or impact. |\n| `pulse(time, at, width?)` | A bump that peaks at 1 at `at`: presses, flashes, highlights. |\n| `stagger(i, count, step, curve?)` | Delay for item `i`; with a curve, the group's delays are eased. |\n| `tempoGrid({ bpm, beatsPerBar?, offset? })` | Bar and beat times for timing constants (see Tempo and music). |\n| `keys([[t, v], …])` | One smooth curve through several keys (monotone cubic): velocity carries through inner keys, no overshoot. For long moves and camera paths. |\n| `cameraPath([[t, x, y, zoom?, roll?], …])`, `withCamera(c, camera, draw)` | The film's one camera: keyed position and roll, zoom in log space; `withCamera` puts the camera's (x, y) at the frame centre. |\n| `beats([{ title, end, stop?, handoff?, note? }, …])` | The shot table: `shots` for `meta.shots`, `list` start/end/stop times, `reviewTimes`, `transitions`, `at(time)`. |\n\n## Layer and text helpers\n\nCommon drawing patterns that would otherwise be copied into every film. Each runs in its own canvas scope and takes either the `FrameContext` or a native 2D context; inside a `layer`, `blurLayer` or `bloom` callback, pass the context the callback receives.\n\n| Helper | Use |\n| --- | --- |\n| `roundRect(x, y, w, h, radius or [tl, tr, br, bl])` | Rounded-rectangle `Path2D`; a single radius is clamped to half the shorter side. |\n| `surface(ctx, path, fill, { elevation?, tint? })` | Fill a path with a soft two-layer shadow: 0 flat, 1 resting card, 2 lifted. |\n| `text(ctx, value, x, y, style)`, `measure(ctx, value, style)` | One line with its own `size`, `color`, `family`, `weight`, `align`, `baseline`, `tracking` (letter spacing), `alpha` and `maxWidth`. |\n| `riseWords(ctx, line, x, y, style, time, start, { stagger?, duration?, curve?, exit?, colors?, separator? })` | Words rise into a mask one after another (0.07 s apart, 0.8 s each, `ease.outQuint`). Returns each word's `[left, right]` for underlines or cursors. `exit` 0–1 lifts the line out. |\n| `blurWords(ctx, line, x, y, style, time, start, { …, blur?, lift? })` | Words come into focus: blur, a small rise and opacity resolve together. Uses `blurText`, never a filter. |\n| `blurText(ctx, value, x, y, style, radius)` | One blurred line drawn through its shadow: about the cost of sharp text. |\n| `layer(c, name, alpha, draw, { res?, mode?, bounds? })` | Draw a group into a pooled layer and composite it once: group fades without flashing overlaps, blend modes, reduced resolution. |\n| `blurLayer(c, name, radius, draw, { alpha?, res?, mode?, bounds? })` | Blur a group in one pass; `radius` in current units (follows the camera); strong blurs drop resolution automatically. |\n| `bloom(c, draw, { radius?, strength?, halo?, mode?, res?, bounds? })` | Glow for lights and neon at quarter resolution: a tight glow and a wide halo. Draws only the glow. |\n| `buffer(name, w, h)` | A pooled, cleared offscreen canvas in device pixels, for custom effects. |\n| `devScale(c)`, `outputScale(c)`, `deviceTransform(c)` | Device pixels per current unit (with camera) and per film unit (output scale); multiply your own offscreen filter and shadow lengths by them. |\n| `filmFrame(c, width, height, base?)` | Tag a plain canvas (a storyboard page) with its film frame so the helpers above work on it. |\n\n`bounds: [x, y, w, h]` (current coordinates) limits a layer to the area it covers; use it for anything smaller than about half the frame.\n\nPass `separator: ''` to animate CJK copy character by character. For a family, use one registered under `fonts` in mografy.json.\n\n## Drawing API\n\n`ctx.draw` is a thin layer over the native Canvas context. Both APIs share styles, transforms, clipping, and resolution scaling. It is not a p5.js compatibility layer and does not create a draw loop.\n\n| Function | Behavior |\n| --- | --- |\n| `fill(color)`, `noFill()` | Set and enable or disable fill. A color may be a CSS color, CanvasGradient, or CanvasPattern. |\n| `stroke(color)`, `noStroke()` | Set and enable or disable stroke. |\n| `strokeWeight(px)`, `strokeCap(value)`, `strokeJoin(value)` | Logical line width and native cap/join values. |\n| `opacity(0..1)` | Set current alpha, clamped to 0–1. It does not multiply the previous value. |\n| `push()`, `pop()` | Save and restore native state plus Mografy fill/stroke state. Keep pairs balanced. |\n| `translate(x,y)`, `rotate(radians)`, `scale(x,y?)` | Transform the coordinate system; omitted `y` means uniform scale. |\n| `rect(x,y,w,h,radius?)` | Top-left coordinates, with an optional uniform corner radius. |\n| `circle(x,y,diameter)`, `ellipse(x,y,w,h)` | Center coordinates; circles use diameter. |\n| `arc(x,y,w,h,start,end)` | Center, size, and radians. An open arc closes implicitly only when filled. |\n| `line(x1,y1,x2,y2)` | Uses the active stroke. |\n| `triangle(...)`, `path(path2d,rule?)` | Fill and/or stroke. Path fill rule defaults to `nonzero`. |\n| `textFont(family,weight?)`, `textSize(px)` | Select loaded type and logical font size. |\n| `textAlign(align,baseline?)` | Native horizontal alignment and baseline. |\n| `text(value,x,y,maxWidth?)`, `textWidth(value)` | Draw or measure text. `maxWidth` condenses a line; it does not wrap. |\n| `image(source,x,y,w?,h?)` | Draw at top-left; provide both width and height or neither. |\n| `linearGradient(x1,y1,x2,y2,stops)`, `radialGradient(x,y,radius,stops,inner?)`, `conicGradient(x,y,angle,stops)` | Return a gradient to pass to `fill` or `stroke`. `stops` is `[[0, '#fff'], [1, '#000']]` or evenly spaced colours `['#fff', '#000']`. |\n| `background(color)` | Clear and repaint the logical canvas while preserving state. It still respects the current clip. |\n\nAt the start of every frame, fill is enabled and stroke is disabled. Call `fill` and `stroke` explicitly. Use the gradient helpers above for fills, and `ctx.canvas` for multiline layout, batched paths, and complex clipping. Do not cross-pair `mografy.push()` with `canvas.restore()`.\n\n```ts\nconst mografy = ctx.draw;\nmografy.push();\nmografy.opacity(ease.outCubic(pr(time, 0.2, 0.8)));\nmografy.fill(p.accent);\nmografy.rect(100, 100, 320, 180, 16);\nmografy.fill('#ffffff');\nmografy.textFont('ABeeZee', 400);\nmografy.textSize(44);\nmografy.textAlign('center', 'middle');\nmografy.text(p.subtitle, 260, 190);\nmografy.pop();\n```\n\n## Built-in scene components\n\nNew projects include `scenes/components.ts`, `scenes/social-components.ts`, and `scenes/showcase.ts`. Component functions are pure time functions that can be copied or edited; they do not add global runtime animation state.\n\n| Component | Additional options |\n| --- | --- |\n| `staggerText` | text,x,y,size?,color?,font?,start?,duration?,stagger?,lift? |\n| `typewriter` | text,x,y,size?,color?,font?,start?,duration?,caret? |\n| `popCard` | x,y,width,height,color?,radius?,start?,duration?,content?(ctx) |\n| `progressBar` | x,y,width,height?,target?,color?,track?,start?,duration? |\n| `pulseDots` | x,y,color?,diameter?,spacing?,period?,start? |\n| `logoReveal` | x,y,color?,ink?,width?,start?,duration? |\n| `socialCard` | x,y,color?,start?,name?,avatar?,caption? |\n| `youtubeSubscribe` | x,y,color?,start?,label?,subscribed? |\n| `aiChat` | x,y,color?,start?,prompt?,reply?,avatar? |\n| `likeBurst` | x,y,color?,start? |\n| `followBadge` | x,y,color?,start?,name?,avatar?,label?,following? |\n| `notificationToast` | x,y,color?,start?,message? |\n| `lowerThird` | x,y,color?,start?,name?,subtitle? |\n| `countUp` | x,y,color?,start?,value? |\n| `toggleSwitch` | x,y,color?,start? |\n| `audioWave` | x,y,color?,start?,bars? (3–40) |\n\n## Edit and visual-review workflow\n\nFor a new animation, create the project first with `mografy init projects/<name>` (an internal command for agents; it starts as a blank stage with the component modules), then replace `scenes/main.ts` and open it with `mografy dev projects/<name>` so the running player switches to it. `mografy dev` only opens existing projects and fails on a folder without `mografy.json`. Do not tell the user to run `init` themselves.\n\n1. Read `mografy.json`, the configured scene entry, and every local module it imports. Preserve the scene's existing visual language unless the user asks for a redesign.\n2. Edit scene source files directly. Keep animation data out of `mografy.json`; use it only for project, parameter, font, audio, render and review settings.\n3. Run `mografy check [project]`. This compiles the scene, trial-renders it in real Chromium and measures frame cost. Fix every reported error, and every `!` frame-cost warning, before judging the design.\n4. Run `mografy review [project]`. Inspect every generated PNG in `renders/`, including raw stills, output frames, and transition strips. Do not approve a scene from source code or a successful build alone.\n5. Judge the images for clipping, overlap, safe margins, legibility, hierarchy, spacing, contrast, consistent easing, transition continuity (the followed object is visible in every frame of a transition strip, nothing jumps, no frame is empty), and whether each important message stays visible long enough. Review the beginning, end, configured key times, and dense transition intervals. Check both raw stills and final output frames when glow, grain, or motion sampling is used.\n6. Iterate on the scene and repeat check plus review until the visual problems are resolved. Use `mografy dev [project]` when the user should watch the live result.\n7. Export with `mografy export [project] --format mp4|webm|lottie|svga` when the user asks for a file. The command prints capture and encoding or packaging progress and writes the finished file under `renders/`. Press Ctrl+C to cancel a CLI export. When `mografy dev` is running, player exports also print progress in that terminal and can be stopped with `mografy export [project] --cancel`.\n\n## Shots\n\nExport `meta.shots` (`[{ end, stop?, title? }, …]`, from the beat table) so the player's timeline marks each shot and `mografy review` writes `review-<version>-shots.png` with the frame each one settles on. `stop` is that settled frame; by default one frame before `end`. Video export ignores shots.\n\nOnly important subtitles belong in `role: 'subtitle'` params. Let the user edit those in Scene → Subtitles; make other copy changes in source when requested.\n\n## Motion direction\n\n- Show a meaningful element within the first 0.3 seconds.\n- Keep important text readable for at least the caption hold in [taste.md](taste.md).\n- Use `springs.out` (or `spring()`) for entrances, `springs.pop` for cards and buttons, `keys` / `cameraPath` for moves through several poses, and `ease.inOutCubic` for exits. Keep one vocabulary per film.\n- Use a consistent curve for related elements and fixed 0.05–0.08 second intervals for a text stagger.\n- Hold readable poses still: no idle drift or bobbing while the viewer reads.\n- Connect shots through shared geometry and overlapping exits (see [film-architecture.md](film-architecture.md)).\n- Preserve whitespace and keep one dominant moving focus at a time.\n- With music, declare `meta.tempo` and time major changes from `tempoGrid(tempo).onBar(n)`, so cuts stay on bar starts when the tempo changes; use `ctx.beat(time)` for pulses inside a bar.\n\n## Project style\n\nEvery project keeps its design and motion decisions in `style.md` at the project root, so every shot and every later session follows them. It lives in the project, never in `mografy.json` or a Skill. A new film writes it at the storyboard step; a project that has a scene but no `style.md` gets one written from the scene before the next change. Write it in English: do and don't rules, the motion character, palette, type, tempo and timing choices, composition habits, and reference stills (paths under `storyboards/` or `assets/`). Keep each rule short enough to check against a frame.\n\nValues themselves stay in scene code. Define each fixed value (a colour, font family, easing curve, duration, tempo) once, in the scene module or in a shared module the scenes already import, and change it there rather than inline in one shot. Font files are registered under `fonts` in `mografy.json`.\n\nWhen `style.md` exists, read it before planning a storyboard or editing a scene. Precedence: the user's current request, then `style.md`, then this Skill's default motion and design guidance. The scene contract above (deterministic `renderFrame`, browser-only code, check and review) always applies. If a request conflicts with the style, follow the request for that change and ask whether the style should change too.\n\nWhat goes in: the film's idea, its design system (type roles, palette, the layout repeated shots share, the travelling motif), its motion character and tempo, and every decision the user states or approves as lasting (\"always\", \"from now on\", \"use this for every shot\"). What stays out: one-off fixes and your passing preferences. When a decision is a value, also change it in the scene code. Mark rules you wrote yourself, before the user confirmed them, so they can be overruled without discussion. During review, check the frames against the `style.md` rules as well as the general criteria. To reuse a style in another project, copy `style.md` and adapt the values in that project's scene code.\n",
|
|
20
|
-
"references/storyboard.md": "# Storyboard planning for Mografy\n\nRead this reference when asked for a storyboard, shot list, or a new animation that needs shot planning. Read the project's scene entry, imported modules, assets, and settings first, including `style.md` when present. Reuse its visual language, dimensions, fonts, palette, and existing characters or brand assets. Write planning documents, shot labels, and tool prompts in English; preserve supplied dialogue and artwork unless translation or redesign is requested.\n\nFor a portrait brief, explicitly label the written plan and every image-generation prompt as **9:16 portrait**, and draw each storyboard panel as a tall 9:16 frame. Read the saved `aspectRatio`; design a vertical composition with stacked content, wrapped copy, and social safe margins. A landscape storyboard cropped into tall panels is not a portrait plan. When both ratios are needed, specify the layout changes for each shot and verify both versions against actual frames.\n\n## Deliverables\n\nSave a project-specific plan as `storyboards/storyboard.md`. Include the audience, message, aspect ratio, total duration, visual direction, asset inventory, and assumptions. Use one row per shot:\n\n| Shot | Time (seconds) | Purpose | Composition and assets | Action and poses | Camera | Copy / audio | Transition | Principles | Review times |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| S01 | 0.0–2.0 | Introduce the mark | Existing logo, centered, generous margins | Anticipation at 0.15; reveal at 0.4; settle by 1.1; hold | Static | Brief logo sound; no copy | Match logo position into S02 | Staging, anticipation, slow in/out | 0.15, 0.4, 1.1, 1.9 |\n\nNumber shots in order; make time ranges contiguous and cover the requested duration. The shot table becomes the scene's `beats([...])` table ([film-architecture.md](film-architecture.md)): give each shot a title, an end time, a settled stop frame and the handoff it uses, so the board and the code share one set of times. Specify entrance, action, settle, hold, and exit where useful. Describe start, extreme, and settle poses rather than writing vague directions such as \"make it dynamic.\" Give each shot a clear focal point and connect transitions through position, color, shape, or meaning: name the object each shot hands to the next (\"the underline becomes the card's top edge\"), and plan one continuous camera rather than a reset per shot. Allow reading time for the actual copy (the caption hold in [taste.md](taste.md)); lengthen a shot or shorten copy when the timing is unrealistic.\n\nLink each shot to existing or proposed scene functions and name the assets it needs. Mark missing assets and assumptions clearly. Keep shot descriptions and visual references out of `mografy.json`; only review times and transition sampling settings belong in its existing review fields. A storyboard is a planning document, not a runtime format.\n\n## Visual output by host\n\n### Codex: image generation\n\nWhen creating a storyboard in Codex, invoke the host's available image-generation tool to produce a storyboard contact sheet or individual key poses. Follow its image-generation skill when available. Supply project artwork as references for edits or identity continuity. Describe panel count, aspect ratio, ordered shot IDs, consistent palette and framing, key poses, and the action between panels. Match the board to the written shot list. Keep exact copy and timings in Markdown because generated image labels can be unreliable. Inspect generated panels for identity, composition, cropping, and consistency, then link the result from `storyboards/storyboard.md`; save a local copy under `storyboards/` when the host exposes one.\n\nGenerated panels are conceptual references. They do not prove that the implemented animation renders correctly. If image generation is unavailable, say so and provide the complete written plan plus ready-to-run English image prompts; never claim images were generated.\n\n### Claude: Artifacts\n\nWhen creating a storyboard in a Claude host with Artifacts, invoke its Artifact capability to present the same plan as an HTML storyboard. Use responsive shot cards with shot ID, time range, Canvas-drawn key poses or existing raster assets, action, transition, and motion notes. Use ordinary HTML/CSS and Canvas; do not add GSAP, SVG scene layers, or resvg. An optional playhead or shot selector may illustrate timing, but label it as a storyboard preview. Keep the artifact self-contained and avoid remote dependencies. Also save the English shot list to the project so Codex can continue from it.\n\nClaude Code environments may not expose Artifacts. Check tool availability; if absent, save `storyboards/storyboard.html` as a standalone local preview and report that fallback. Do not claim to have opened a Claude Artifact. The HTML storyboard is separate from the Mografy scene and is never imported by the Server.\n\n## Storyboard as code\n\nOnce a scene exists, or for films longer than about 15 s, draw the board's panels from the scene itself: export `drawFilm(c, t, data)` from the scene and render it at each beat's stop frame on a plain canvas, as described in [film-architecture.md](film-architecture.md). The board then shows the film's real pixels, and updating the scene updates the board.\n\n## From storyboard to animation\n\nRead [animation-principles.md](animation-principles.md) to choose motion that supports each shot. A storyboard-only request ends with the written and visual board. If implementation is also requested, continue into scene modules without inventing an approval step. Use analytic functions of `time` for all poses, camera transforms, secondary motion, and transitions. Validate using `mografy check`, then `mografy review`; inspect real raw and output frames at the shot's poses, holds, boundaries, and transition intervals against the storyboard. Update the plan if implementation changes timing or composition.\n",
|
|
21
|
-
"references/taste.md": "# Default taste\n\nRead this before a storyboard and again before delivery. These are Mografy's defaults when the project's `style.md` and the brief say nothing else; the project's own decisions always win. Each rule gives its reason, so apply the reason to cases the rule does not name. Sizes are for a 1920 × 1080 canvas unless stated.\n\n## Pacing: the viewer reads every word and sees every change\n\n- **Caption hold.** Keep a caption fully readable (after its reveal settles) for at least 0.5 s + characters ÷ 4.5 for Chinese or Japanese, or 0.5 s + words ÷ 3 for English. A 6-character line holds ≥ 1.8 s, a 12-character line ≥ 3.2 s, a 9-word line ≥ 3.5 s. Viewers meet the line for the first time while also watching the picture, and need a beat to take it in after reading it. When the hold does not fit the shot, cut copy before shortening the hold.\n- **Result hold.** After a state changes (a number lands, a check draws, a card arrives), hold 0.6–1.0 s before the next move. A change nobody had time to see did not happen.\n- **One action per shot**, 2.5–4 s per shot for UI and explanation, longer for a reading hold. Two actions at once split attention and neither reads.\n- **Length changes come from holds.** To hit a length, shorten or lengthen still holds; never speed up an action, because a rushed action looks like a glitch. If the copy cannot be read in the requested length, cut copy or say so; do not speed up the whole film.\n- **Camera and cursor.** Start a camera move up to 0.5 s before the action it serves; never move the camera during a click or a reading hold. Give a cursor up to 1.1 s per move on a gentle arc and let it rest on the control before clicking. The eye needs to arrive before the event.\n- **Smooth, not fast.** A move across more than half the frame takes at least 0.6 s, and an exit at least 0.4 s; ease through every key instead of stopping and starting again. A whip that crosses the frame in a few frames reads as a stutter on most screens, even when every frame renders on time. `mografy check --motion` finds the hard starts, hard stops and jumps ([performance.md](performance.md)).\n- **Overlap cuts.** Start the incoming action 0.2–0.5 s before the outgoing exit ends, so no frame is empty.\n\n## Type and layout: legible at the size it is watched\n\n- **Headlines 96–160 px, body copy ≥ 40 px, nothing under 24 px** except UI detail that is not meant to be read. A 1080p film is often watched in a small window or on a phone, where 24 px is already small.\n- **Portrait (1080 × 1920):** headlines ≥ 110 px, captions ≥ 44 px, captions in the top third. Phones are held at arm's length and the bottom is covered by platform UI.\n- **Redrawn UI at 1.3–1.6× the app's own type size,** with 3–4 rows per list. A real screen shrunk into a frame is unreadable.\n- **Few words at once:** at most about 12 English words or 20 CJK characters on screen outside the product UI. More is a slide, not a film.\n- **Safe margins:** keep copy and logos at least 96 px from the sides and 72 px from the top and bottom in 16:9; use the portrait margins in [output.md](output.md). Players and platforms crop and overlay the edges.\n- **One card style:** one corner radius, one shadow, one padding (≥ 48 px inside a card) across the film. Mixed styles read as different products.\n- **No text over text.** Captions never overlap UI or other captions, and text never cross-dissolves over UI. Overlapping type is unreadable for the overlap's whole duration.\n\n## Design system: decide it once, before the first shot\n\nA film looks designed when every shot is built from the same few decisions. Write them as tokens at the top of the scene (`const C = {…}`, one object per type role) before drawing anything, and draw every shot from them.\n\n- **Four type roles, no more.** A display face for headlines and item names (a serif, or a heavy sans) and a text face for everything else. Portrait sizes as a starting scale: kicker 40–48 px (text face 500, accent colour, tracking 8–12), headline 120–150 px (display 700, tracking 4–8), item name 100–120 px, descriptor 48–56 px (text face 500, muted colour). For 16:9 use about 0.8× these. Contrast between a big display line and a small, wide-tracked kicker is what reads as designed; five sizes that are all similar read as a document.\n- **A numbered kicker for lists.** When the film walks through items (products, steps, features), put `No.01`, `No.02`… or a short label above each name in the kicker role. It tells the viewer where they are and gives each shot the same structure.\n- **One fixed layout for repeated shots.** Shots that do the same job share one composition: the copy block at the same position (portrait: centred in the top third), the subject at the same spot (portrait: centred around 55–60 % height), the same subject size. Only the content changes, so the eye knows where to look and the cut feels like a page turn, not a new film.\n- **Palette: five roles.** A light or dark background with a slightly lighter centre (a soft radial gradient, never flat grey), an ink tinted towards the background's hue (never pure #000 on cream or #FFF on navy), a muted colour for secondary text, one accent for the kicker, highlights and the logo, and the subject colours from one family around the accent. A second accent splits attention.\n- **Leave about 40 % of the frame empty.** Big type and one subject on calm space look expensive; filling the frame with surfaces (a dark floor across the bottom third, panels behind every line) makes it look heavy and cheap.\n- **Simple, flat illustrations.** When you draw the product or objects yourself, use few geometric shapes, a flat fill or one gentle gradient, one soft contact shadow, and one recurring accent motif (a leaf, a spark, a dot) that can travel between shots. Detail belongs to the subject's one identifying feature (the latte art, the ice), not to everything.\n- **The ending is the biggest type in the film.** The wordmark at about 1.2–1.4× the headline size with wide tracking, a small Latin or secondary line under it, the tagline in the accent colour, and, when the film listed items, a small recap of them as a row of icons.\n\n## Look: nothing that competes with the message\n\n- **Still holds.** No idle drift, bobbing or slow zoom while the viewer reads; every motion has a cause and ends. Motion pulls the eye away from the words.\n- **No decoration for its own sake.** No dot grids or busy patterns; a quiet gradient, one glow or the brand's colour field. Texture behind type lowers its contrast.\n- **The logo once.** The brand mark lands at the end, about 20–30 % of the frame width, held still with the tagline for ≥ 1.5 s; it does not open the film or repeat in every shot. Repetition spends the payoff.\n- **On-screen language follows the brief.** Plans, shot labels and prompts stay in English; preserve supplied copy unless translation is requested.\n\n## Sound\n\n- **Sustained, warm music:** long pads, warm piano, one long bass note per bar, few hits on the moments that change the story. Busy patterns fight the picture.\n- **No sharp high sounds:** no bells, sparkles, ticks or pops; soft whooshes and low hits instead. They are tiring on repeat and on headphones. Details in [music.md](music.md).\n",
|
|
22
|
-
"references/templates.md": "# Mografy Templates\n\nMografy Templates is a free (MIT) library of finished, editable templates for product demo videos: hooks, captions,\nproduct screens, callouts, numbers, proof, slides, end cards and transitions. All copy is English. Each template has one\nnative aspect ratio and one look:\n\n| Aspect | Ids | Look | For |\n| --- | --- | --- | --- |\n| 9:16 | `hook-impact` … | **Editorial**: a white printed page, black type, one burnt-orange accent; tall Anton headlines that rise letter by letter, header and footer rules, quote marks, hand-drawn underlines, dark picture windows and a carousel swipe. Themes `light` (default) and `dark`. | Threads, Reels, Shorts |\n| 16:9 | end in `-wide` | **Montage**: night, light or neon grounds; kinetic Inter type that sharpens out of a blur; the Mografy spectrum (teal, sky, violet, coral, amber) on a word, a pill rim or a comet of light; product windows on tilted planes. | Landing pages, YouTube, Product Hunt, decks |\n\nA template that exists in both ratios has a `pair` (`stat-count` ↔ `stat-count-wide`). Never put a template into a film of\nthe other ratio. The sources live in [templates/](__REPOSITORY__/templates), with the catalog in\n[templates/catalog.json](__REPOSITORY__/templates/catalog.json); every template plays live at https://www.mografy.app/en/library/templates.\n\n## When to use them\n\nReach for a template when a brief needs a standard beat of a demo video (an opening hook, subtitles, a phone or laptop\nscreen, a callout on a feature, a before/after, numbers, testimonials, a closing card). Start from the template, then\nadapt its copy, colours and timing to the brief. Build new motion from scratch only when no template fits, or when the\nfilm needs its own visual concept. Use one look per film: the editorial templates for a 9:16 post, the montage templates for\na 16:9 film.\n\n## Add templates\n\n```sh\nmografy add hook-impact three-steps cta-endcard projects/<name>\n```\n\n- When the folder is not a project yet, `mografy add` creates it: a project with the templates' aspect ratio, a\n `scenes/main.ts` that plays the templates in the order given, output glow and grain off, and review times. This is a\n complete way to start a film; open it with `mografy dev projects/<name>`.\n- Without a folder, inside a project, the templates go into that project. Outside a project, the first template names a new\n project in the library. `mografy add` never falls back to another (last opened) project.\n- Each template lands in `scenes/templates/<id>.ts` with the shared `kit.ts`, `editorial.ts` and `montage.ts`. Inter\n (500–800) and Anton are copied to `assets/` with their licences and registered under `fonts` in `mografy.json`.\n Files the user changed are kept unless `--force` is passed. If the project already has `scenes/templates/`, read\n and reuse that local copy.\n- A project without a `tsconfig.json` gets one for editor support (strict, `@mografy/runtime` resolved to this\n installation's types), so templates open in an editor without \"Cannot find module\" or implicit `any` errors.\n- Templates set `render.glow` and `render.grain` to 0 in new projects: the light that belongs to the montage look is\n drawn in the scene. Keep them at 0 when a film is made of templates.\n\n## Use a template\n\n- **On its own:** set `\"scene\": \"scenes/templates/<id>.ts\"` and the matching `\"aspectRatio\"` in `mografy.json`.\n- **In a film:** import the module and play it on the film's timeline. `play` resolves the template's default params\n and applies your overrides; `backdrop: false` draws an overlay template (captions, callouts, lower thirds, end\n cards) over the film's own picture.\n\n```ts\nimport * as hook from './templates/hook-impact.js';\nimport * as caption from './templates/caption-highlight.js';\nimport { play } from './templates/kit.js';\n\nexport function renderFrame(ctx: FrameContext, time: number) {\n play(ctx, time, 0, hook, { text: 'Plan the week\\nin [one view.]' });\n drawProduct(ctx, time); // the film's own shot\n play(ctx, time, 4, caption, { backdrop: false });\n}\n```\n\nEvery template enters, holds still while it reads, and exits in its last ~0.5 s, so templates chain without empty frames.\nKeep the film's quality floor: one world and one camera for shots you write yourself, and hand geometry over at\ncuts.\n\n## Edit a template\n\n- Copy and colours are params: the template's strings, `theme` (editorial `light`/`dark`; montage `night`/`light`/`neon`)\n and, for editorial templates, `accent`. In editorial headlines, a word in `[brackets]` takes the accent; in montage\n headlines it takes the spectrum. Change timing and layout in the template file. Keep `renderFrame` pure, and keep\n critical copy inside `safeRect(aspect)` from the kit (`safeGuide: true` shows it in the preview, never in exports).\n- Screen templates draw a fictional stand-in product (\"Northwind\"): `editorialScreen` in 9:16, `appUI` in 16:9.\n Replace it with the real product: redraw the real screens in the same box (see\n [product-walkthrough.md](product-walkthrough.md)), or load a screenshot in `setup` and draw it there. Editorial\n templates that take pictures load `assets/<name>.jpg` with `loadPhoto` (black-and-white, like the look) when the file\n exists; the agent hint names the file.\n- Brand templates draw a placeholder mark. Replace it with the real logo (load `assets/logo.png` in `setup` and draw it\n in the same box).\n- The fonts are Latin subsets. For Chinese or Japanese copy, add `mografy add cjk` and a CJK font, and check the\n frames for fallback glyphs.\n- After editing, run `mografy check` and `mografy review` and look at the stills, as for any scene.\n\n## Catalog\n\n<!-- catalog:start -->\n| Template | Aspect | Category | Seconds | Use it for |\n| --- | --- | --- | --- | --- |\n| `hook-impact` Impact headline | 9:16 | hook | 4 | First 3–4 s of a post. Up to three lines of 1–3 short words, uppercase reads best; mark one word with [brackets]. Not for sentences longer than ~25 characters. |\n| `hook-number` Number hook | 9:16 | hook | 3.5 | Open on a single striking figure (1–4 characters: \"3\", \"24\", \"9.5\") with a short unit and a one-line caption under 30 characters. For several figures use stat-count. |\n| `hook-question` Question hook | 9:16 | hook | 3.5 | Opening 3–4 s that asks the viewer a pain-point question. Up to three short uppercase lines (≤ 14 characters each); mark the key words with [brackets]; the question mark is drawn for you. |\n| `caption-highlight` Highlight caption | 9:16 | caption | 4 | One statement of up to ~40 characters with the key words in [brackets]. Put assets/highlight.jpg in the project for the picture; with backdrop false the caption sits on a white panel over your own footage. |\n| `caption-pop` Pop captions | 9:16 | caption | 4 | Punchy spoken line of 2–8 short words; words of up to three letters ride with the next word. Put assets/pop.jpg in the project for the picture, or play it with backdrop false over your own footage (the strip carries the words). |\n| `caption-stack` Stacked caption | 9:16 | caption | 4 | A slogan of 2–5 very short lines (1 word each, up to ~6 letters), one per \"\\n\". Put assets/stack.jpg in the project for the picture strip; with backdrop false the stack sits on a white panel. |\n| `caption-subtitle` Speaker subtitle | 9:16 | caption | 4.5 | Interview or founder quote: one sentence up to ~60 characters (wraps to two lines) and a \"Name · Role\" line. Put assets/speaker.jpg in the project for the picture; with backdrop false it draws its own scrim over your footage. |\n| `caption-word` Word captions | 9:16 | caption | 5 | Spoken subtitles for a voice-over: 2–3 lines of up to ~24 characters, one per \"\\n\"; mark key words with [brackets] (default: the last word of each line). Put assets/caption.jpg in the project for the picture, or play it with backdrop false over your own footage. |\n| `ai-chat-stream` AI chat stream | 9:16 | screen | 6 | Show an AI feature answering. Prompt under ~60 characters, reply under ~200 (about 30 words; longer replies stream too fast to read). Speaker labels are SPEAKERS in the file. |\n| `click-zoom` Click zoom | 9:16 | screen | 4 | Highlight one button or control. Label 2–5 words. The editor in the window is a stand-in: redraw `editor` with the real screen and move BTN to the control (keep it in the top half so the leader stays short). |\n| `desktop-follow` Desktop follow | 9:16 | screen | 6 | Show a two-click desktop flow in a portrait post. Label 2–5 words, [brackets] mark the orange words. The app is a stand-in 1440 × 1000 dashboard: redraw `app` with the real product and move CLICKS to its targets (the camera follows them). |\n| `device-stack` Device stack | 9:16 | screen | 5 | Say the product works everywhere. Title 2–4 words ([brackets] mark orange words), detail one short line. Both screens come from `product` (landscape and portrait layouts of one stand-in dashboard): redraw it, or draw screenshots into the two screen rects. |\n| `phone-recording` Phone recording | 9:16 | screen | 5 | Show a mobile app in use. Title 2–4 words. The screen is a stand-in task list: put assets/screen.jpg (portrait, about 9:19) in the project to show a real recording frame, or redraw `phoneScreen`; the tap lands on the second row (TAP_ROW). |\n| `type-input` Typed input | 9:16 | screen | 4.5 | Show a prompt or search being typed and answered. Query up to ~60 characters (two lines). The three result rows are stand-ins in RESULTS: replace them with what the real product returns. |\n| `before-after` Before and after | 9:16 | explain | 5 | Contrast the old way with the product. Write each label as \"KICKER: HEADLINE\" (the part after the colon is the big line, 1–3 words). The twelve steps and the checked line are STEPS and RESULT in the file. |\n| `callout` Callout | 9:16 | explain | 4.5 | Point at one feature. Title 1–3 words ([brackets] mark orange words), detail one short sentence. Over a film picture (backdrop false) the whole frame dims around FOCUS and the label sits on a white panel; move FOCUS to the element in your picture. |\n| `three-steps` Three steps | 9:16 | explain | 7 | Explain a 3-step flow. Step titles 2–4 words, details one short line. The window shows a stand-in screen: put assets/step-1.jpg … step-3.jpg in the project (or redraw `screen`) to show the real product. |\n| `review-cards` Review carousel | 9:16 | proof | 6.5 | Social proof for a post: three reviews, one per line as \"quote | name | role\", quotes up to ~70 characters. Fictional people by default; use real reviews only with permission. |\n| `stat-count` Numbers table | 9:16 | data | 4.5 | Three key figures with short labels, one per line as \"value | label\" (a unit or suffix may follow the value: \"4.9/5\", \"3 MIN\"). Values up to 6 digits, labels under ~20 characters; the headline is one line of up to ~22 characters. |\n| `cta-endcard` Call to action | 9:16 | end | 5 | Last 3–4 s of a post: a call to action of 1–3 short words (mark one with [brackets]) and a name to search for, under ~16 characters. The picture above the sheet is a stand-in: put assets/endcard.jpg in the project, or play the template with backdrop: false over your own last shot. |\n| `logo-tagline` Logo and tagline | 9:16 | end | 5 | Closing logo of a 9:16 post. Brand 1–2 words, tagline under ~28 characters with one [marked] phrase. The N mark is a fictional stand-in: redraw `mark()` with your own logo as two or three flat strokes that grow in order. |\n| `push-transition` Vertical push | 9:16 | transition | 2.6 | Between two full-frame pictures or screens of a 9:16 film. Titles 1–4 words. The pictures are stand-in product screens: put assets/from.jpg and assets/to.jpg in the project (or redraw `picture`) so the push carries your own last and next shot. |\n| `product-hero-wide` Product hero | 16:9 | hook | 5 | Opening of a landing-page loop, Product Hunt or YouTube demo. Name 1–2 words, tagline under ~40 characters, button labels 1–3 words. The window is a stand-in: redraw it in `appUI` or draw a screenshot into the same 1400 × 860 card. |\n| `title-wide` Wide headline | 16:9 | hook | 5 | Opening statement for a landing page, YouTube or a talk: two short lines (under ~26 characters each), the [bracketed] words in the spectrum. Night or neon ground reads best. |\n| `caption-subtitle-wide` Wide subtitle | 16:9 | caption | 4 | Subtitle or pull quote over footage in a landscape film: one sentence (wraps to two lines past ~45 characters) and a speaker line. Play it with `backdrop: false` over your own picture; the product screen underneath is only a stand-in. |\n| `name-lower-wide` Wide lower third | 16:9 | caption | 4 | Name and role over an interview or talking-head shot in a landscape film. Name 1–3 words, role under ~40 characters. Play it with `backdrop: false` over your footage; the soft-focus speaker underneath is only a stand-in. |\n| `ai-chat-stream-wide` AI chat stream | 16:9 | screen | 6 | Show an AI feature answering. Prompt one line (under ~44 characters), reply 1–3 sentences (under ~190 characters). The chat window is a stand-in: restyle `chat()`; never use a real AI brand name or logo. |\n| `browser-window-wide` Browser | 16:9 | screen | 5 | Open a website or web-app demo. Keep the URL short (under ~24 characters, no https://). The page is a stand-in: redraw `page()` (1400 × 764 below the bar) or draw a screenshot there; avoid real browser or brand UI. |\n| `laptop-frame-wide` Laptop | 16:9 | screen | 5 | Show a desktop product in context. Title under ~26 characters; it breaks after a comma, and [bracketed] words (else the last line) take the spectrum. The screen is a stand-in: redraw `screen()` or draw a 1400 × 860 screenshot into it. |\n| `multi-window-wide` Multi-window | 16:9 | screen | 5 | Real-time sync or collaboration. Title under ~28 characters; [bracketed] words (else the last word) take the spectrum. The board is a stand-in: rename the columns and cards in `COLS`, or redraw `board()`. |\n| `terminal-wide` Terminal | 16:9 | screen | 5 | CLI, SDK or developer-tool launch. One command under ~34 characters. Output and success copy live in `OUTPUT` and `SUCCESS`; keep them to four short lines and one line. Neon ground reads best. |\n| `before-after-wide` Before and after | 16:9 | explain | 5 | Contrast the old way with the product in a landscape film. Write each label as \"Kicker: Headline\" (headline 1–3 words, under ~16 characters; [brackets] take the spectrum). The twelve steps and the result line are STEPS and the Result param; a full-frame explainer, not an overlay. |\n| `callout-wide` Callout | 16:9 | explain | 4.5 | Point at one feature of a product window. Title 1–3 words ([brackets] take the spectrum), detail one short sentence. With backdrop false the window is skipped and the frame dims around FOCUS over your own picture; move FOCUS (a rect in the 1400 × 860 window) to your element, or redraw the window in `appUI`. |\n| `feature-grid-wide` Feature grid | 16:9 | explain | 5.5 | Show what a product does in one frame: 3–6 features, one per line as \"Name: detail\" (name 1–3 words, detail under ~38 characters), headline under ~32 characters with [brackets] for the spectrum. Draw your own icons in `icon()` (one per card, by index). |\n| `logo-wall-wide` Logo wall | 16:9 | proof | 4 | Social proof in a landscape film or a talk. The twelve names are fictional stand-ins in `NAMES`: replace them with real customers you may name (or draw their logos inside the chips, keeping the chip and dot). The first number in the headline takes the spectrum. |\n| `growth-bars-wide` Growth bars | 16:9 | data | 5 | A single growth story (revenue, users, speed) in a landscape film or a talk. The twelve monthly values are constants in `DATA` and the end label in `LABEL`; keep the headline under ~34 characters. It is a mood chart, not an exact one: no axis values. |\n| `stat-count-wide` Wide numbers | 16:9 | data | 4.5 | Traction or results in a landscape film or a talk. Figures are the `stats` param, one \"value | label\" per line (\"4.9/5\", \"3 min\": the text after the number is its unit): keep three, labels under ~18 characters, values up to six digits. Digits sit in fixed slots, so numbers do not jitter while they count. |\n| `bullet-points-wide` Morphing points | 16:9 | slides | 6 | Three to four short points for a talk, a pitch or a product walkthrough, one per line (each 1–3 words, under ~18 characters); a fifth point reuses the pill. The shapes read as write (a field), tune (a slider), pulse (a wave) and present (play), so order the points to match. |\n| `chapter-title-wide` Chapter title | 16:9 | slides | 3.5 | Section divider for a talk, a course or a long demo: number 1–3 characters, title under ~28 characters, subtitle under ~50. Long titles shrink to fit. Neon or night reads best. |\n| `quote-wide` Quote pill | 16:9 | slides | 5.5 | One-sentence quote or principle for a talk, a launch film or a testimonial: under ~60 characters reads on one line, up to ~120 wraps to two. Leave the quote marks out; the template adds them. Neon or night reads best. |\n| `cta-endcard-wide` Website end card | 16:9 | end | 4.5 | Closing call to action of a landscape film or a talk: a headline under ~28 characters, an address under ~24 and a button label of 1–3 words. The QR pattern is a stand-in that does not scan: replace the modules in `qrCard()` with your real code image (load it in `setup`, draw it into the same square). |\n| `logo-tagline-wide` Logo and tagline | 16:9 | end | 4 | Closing logo of a landscape film. Brand 1–2 words, tagline under ~40 characters. The mark is a fictional stand-in: redraw `markPath()` (a centre line, traced then filled) and `ribbon()` with your own logo, keeping the trace → fill → letters order. Night or neon reads best. |\n| `push-transition-wide` Push transition | 16:9 | transition | 2.4 | Cut between two landscape shots. The pictures are stand-ins: draw the outgoing shot in `pictureA` and the incoming one in `pictureB` (each is already offset). With backdrop false only the light edge and its shade are drawn. Titles under ~30 characters; the template ends on picture B, so the next shot starts from it. |\n<!-- catalog:end -->\n",
|
|
23
|
-
"references/three-d.md": "# 3D layers with Three.js\n\n[three.ts](__REPOSITORY__/extras/three/three.ts) renders a [Three.js](https://threejs.org/) scene as a layer inside a normal Mografy frame: draw 2D backgrounds first, then the 3D layer, then type and overlays. [three-demo.ts](__REPOSITORY__/extras/three/three-demo.ts) is an eight-second tour: a device with a drawn screen orbits into a hero pose among floating shapes.\n\n## When to use it\n\nUse a 3D layer when the brief needs real depth: objects that turn and catch light, product or device models (glTF / GLB), orbiting cameras, depth between layers, reflective or glassy materials. For flat cards, type, UI, flips and parallax, stay in 2D Canvas with the built-in components and `cinema.ts`; they are lighter, sharper for text, and export faster.\n\n## Add to a project\n\nThe helper and library are an optional extra, not part of the installed template. If the project already has `scenes/three.ts` and `assets/three.module.js`, read and reuse those local copies. Otherwise copy from the current Mografy checkout (`extras/three/`) or download from GitHub:\n\n```sh\
|
|
24
|
-
"references/ui-stage.md": "# Product UI on a stage: simplified, framed, caused\n\n[stage.ts](__REPOSITORY__/extras/stage/stage.ts) makes short product UI films: hero loops for a landing page, feature cards, a phone moment for social, a dashboard insight. It is built around one sentence:\n\n**It reads as a real product, simplified to what the viewer needs, framed with intent, and every motion has a cause.**\n\nUse it when the brief is \"show how it feels to use\" in one to three actions, 4–12 s, often looping. Use [product-walkthrough.md](product-walkthrough.md) instead for a longer tour through several screens (4–8 steps, cards that grow into each other), and both together when a walkthrough needs a stage-style hero shot.\n\n## Five ways faux UI fails\n\nAgents drift toward the first one. Name the failure when you review a frame. To see each one next to the good version, open `stage-invoices` and switch its **Variant** parameter (`too-much`, `too-little`, `boxed`, `flat`, `bland`); hold your own stills against the pair you are closest to.\n\n| Failure | Looks like | Fix |\n| --- | --- | --- |\n| **Too much** | Real words in every cell, packed tight, every column filled | Only story strings are words; the rest are placeholder lines (`role: 'filler'`, `bar`, `bars`) |\n| **Too little** | A wireframe: grey boxes that do not read as any product | Keep the real chrome, the brand mark, real nav labels and one real number |\n| **Boxed** | The whole app shrunk into a floating card, like a pasted screenshot | `pin()` the window to a corner so it runs off two edges; decide the crop first |\n| **Flat** | Everything has the same weight | One focal element per beat; everything else quieter (mute type, lines, `recede`) |\n| **Bland** | The brief's brand never shows | A look and its tokens: the product's accent, radius, font, light or dark |\n\n## Workflow\n\nMost of it happens before any code. Write the answers at the top of `storyboards/storyboard.md`.\n\n1. **Medium.** Still or animation, loop or play once, where it sits (hero, feature card, social 9:16) and the design size: 1280 × 720 for 16:9, 720 × 1280 for 9:16. `withStage(c, s, draw, ctx.width / designWidth)` scales it to the film, so the kit's sizes read as real UI at about 1.5×.\n2. **Look.** `look('light' | 'dark' | 'blueprint' | 'minimal', overrides)`: one accent or mono; the chrome the product really has (`chrome: 'app' | 'browser' | 'tabs' | 'tahoe' | 'card'`), its real icons. Map the product's own tokens (accent, radius, font) onto the look instead of inventing colours.\n3. **Story.** How it feels to use, a flow through the app, or what the system does on its own. Three to five beats, one sentence each. The last beat undoes the first **on screen, with a cause** (an Undo, a back tap, a lock button), so a loop has no seam.\n4. **Example.** Copy the closest reference film (`mografy add <name> <folder>`, table below) and make it the brief's product: what is cropped, what overlaps what, one gutter. Copying an example that runs a window off the edge works far better than a rule that says to.\n5. **Screen.** List the few real strings the story needs; everything else becomes lines. A dashboard needs about six words, an inbox one real row.\n6. **Choreograph.** The script decides the timing: holds before actions, overlapping changes, one camera push at most per beat, a loop that ends where it began.\n7. **Rehearse.** `mografy check --motion`, `mografy review` with transition strips over every action and the loop seam, then hold your stills next to the example's.\n\n## Reference films\n\n| Film | Shows | Start from it for |\n| --- | --- | --- |\n| `stage-invoices` | Web app window off two edges, a flight into a rolling total, camera push, toast Undo; four looks; the five failure variants | Any web app hero |\n| `stage-phone` | 9:16, a cropped phone driven by taps, a notification that grows into the thread, typing | Mobile and social clips |\n| `stage-dashboard` | Dark, the newer macOS window, hover tooltip, one annotation, camera push | Analytics, one insight |\n| `stage-bento` | A bento section planned as one picture: one UI tile, a stat, an object, a diagram; no cursor | Homepage feature grids |\n| `stage-calendar` | `drag()`: lift, a target that jumps cell to cell, landing, staggered confirmations | Anything dragged: cards, slots, files |\n| `stage-upload` | Blueprint diagram, packets per hop, `ui.callout` annotations; no cursor | API docs, architecture, \"how it works\" |\n| `stage-command` | Keyboard only: keycaps as the cause, a filtering palette, ⌘Z | Command palettes, shortcuts |\n| `stage-checkout` | Browser with tabs, typing, a spinner, a check that draws | Forms, sign-up, payments |\n| `stage-request` | Web and phone in one frame, `recede`, cursor and taps together | Anything that crosses devices |\n| `stage-snooze` | Quiet card chrome, hover actions, a menu, a row leaving and the list closing up | Small feature cards |\n\n## Build\n\n```ts\nimport { play, wait, set, click, tap, type, drag, move, focus, cursor, mark, withStage, createKit, look, pin } from './stage.js';\n\nconst W = 1280, H = 720, START: Point = [880, 640];\nconst initial = { paid: false, total: 18400, toast: false }; // everything that changes is state\nconst WIN = pin([W, H], [1260, 760], 'tl', [92, 72]); // crop first: runs off right and bottom\nconst layout = (s: typeof initial) => ({ markPaid: [1006, 465, 128, 38], total: [354, 290, 220, 58], ...(s.toast ? { undo: UNDO } : {}) });\n\nconst show = play(initial, [\n mark('Mark paid'), wait(0.9),\n click('markPaid', { paid: true }), // the change lands on the press\n wait(0.42), set({ total: 22600, toast: true }),\n focus('total', 1.5, 1.1), wait(2.1), focus(null, 1, 1),\n mark('Undo'), wait(0.5),\n click('undo', { paid: false, total: 18400, toast: false }), // the cause of the reset\n wait(0.5), move(START), wait(0.7),\n], { size: [W, H], layout, start: START, loop: true, cursors: { markPaid: 'pointer' } });\n\nexport const meta = { width: 1920, height: 1080, duration: show.duration, fps: 30, background: '#efeeec', shots: show.shots, loop: true };\n\nexport function renderFrame(ctx: FrameContext, time: number, p: Values) {\n const ui = createKit(look('light', { accent: p.accent })), s = show.at(time);\n ctx.withCanvas(c => {\n ui.backdrop(c, ctx.width, ctx.height);\n withStage(c, s, g => {\n ui.window(g, WIN, { chrome: 'app', sidebar: 200 }, (w, body) => { /* draw from s.value / s.on / s.is / s.num */ });\n ui.pointer(g, s.cursor);\n }, ctx.width / W);\n });\n}\n```\n\n### Script steps\n\n| Step | Takes time | Use |\n| --- | --- | --- |\n| `wait(s)` | yes | Holds: before the first action (0.6–1 s), after a payoff (1.5–2.5 s) |\n| `click(name, then?)` | yes (move by distance + 0.1 s dwell + hold) | A cursor click; `then` is applied as the press lands |\n| `tap(name, then?)` | yes | Phones: no travelling cursor, a press dot appears |\n| `drag(from, to, then?)` | yes | Cards and calendar slots; the cursor closes while carrying |\n| `type(key, text, cps?)` | yes | Typing into a state string (22 characters per second) |\n| `move(target)` | yes | Back to the start, or to a hover target |\n| `set(values, { duration?, curve? })` | no | A change with no click (a reply arrives, a total updates after a flight) |\n| `focus(name \\| null, zoom?, duration?)` | no | Camera push in on a rect and back; runs beside the next steps |\n| `cursor(visible)` | no | Hide the cursor for a beat that runs by itself |\n| `mark(title)` | no | Starts a shot for `meta.shots` and review |\n\nCursor moves take 0.3–0.95 s by distance on a shallow arc, like a hand; never time them by hand. `layout(state)` is the single source of rects: the cursor aims at them, the camera focuses on them, and the drawing should use the same constants.\n\n### Sampling state in renderFrame\n\n`s.value(key)` the current value; `s.on(key)` / `s.is(key, v)` 0..1 presence that springs in (0.42 s) and eases out (0.28 s), so parts move instead of popping; `s.num(key)` a number springing between values; `s.pair(key)` for `ui.roll`; `s.since(key)` seconds since the last change, for one-off motions such as a flight; `s.cursor` (`x`, `y`, `press`, `shape`, `visible`, `touch`); `s.camera`. While a `drag()` carries something, `s.cursor.dragging` is true and `s.cursor.lift` (0..1) rises and lands: draw the carried object at the cursor, scaled and tilted by `lift`, and a ghost at home (`stage-calendar`). Taps never move the cursor; their press shows at `s.cursor.tx`, `ty`. `play(..., { pointer: false })` hides the cursor for a film about what the system does on its own.\n\n### Kit\n\n| Part | Use |\n| --- | --- |\n| `look(name, overrides)`, `LOOKS` | Tokens: backgrounds, window, sidebar, surface, ink / mute / faint, line, accent, bar, shadow, radius, font, `words` |\n| `ui.window(c, rect, { chrome, url, tabs, sidebar, recede }, draw)` | The chrome follows from what you pass; `tahoe` is the newer macOS window (large lights, floating sidebar, tall toolbar). `draw` gets `body.content` and `body.sidebar`. Never put an address bar on a native Mac app |\n| `pin(size, box, corner, inset)` | A rect pinned to a corner that runs off the opposite edges |\n| `ui.nav`, `ui.text`, `ui.bar`, `ui.bars` | Sidebar with brand and real labels; text that becomes a line when the look keeps fewer words; placeholder lines |\n| `ui.button`, `ui.badge`, `ui.field`, `ui.menu`, `ui.avatar`, `ui.icon`, `ui.toast` | Controls; pass `press: s.cursor.press` to the pressed one, `k: s.on(...)` to anything that enters |\n| `ui.roll(c, from, to, k, x, y, o)` | A number that rolls only the digits that changed |\n| `ui.fly(c, fromRect, toRect, k, draw)` | An object flying into a slot on a shallow arc, landing with a settle |\n| `ui.phone(c, rect, draw, { time, dark, island })`, `ui.lockScreen`, `ui.notification` | Phones from real proportions; pass a rect that crosses the frame edge so the phone is cropped |\n| `ui.shadow`, `ui.card` | Layered shadow (hairline, mid, long soft), cheap under camera zoom; a surface card with hairline and optional lift |\n| `ui.key(c, x, y, label, { press })` | A keycap; draw keycaps outside the camera when keys are the cause (`stage-command`) |\n| `ui.callout(c, from, to, label, k, { side })` | An annotation: a dashed leader that draws first, then a one-line label |\n| `ui.pointer(c, s.cursor, { style })` | `arrow` (default), `large`, `circle`; shapes change over named rects (`cursors` option) |\n\n`words` in a look: `story` (default) draws `ui` and `keep` text, turns `filler` text into lines; `lines` (minimal) turns everything but `keep` into lines; `all` draws every word; `none` is a wireframe, the failure *too little*, kept only for comparisons.\n\n## Rules that hold up\n\n- **Crop first.** Decide what is cut off before drawing anything; do not build what will not be seen. Windows run off two edges; phones off the bottom or a side, never shown whole.\n- **Few words.** Real strings only where the story is. A full inbox reads as full with one real row and lines for the rest.\n- **One accent, real chrome, real icons.** No fake iOS status bar on a desktop scene; no browser chrome on a native app.\n- **Every change has a cause.** A click, a tap, a drag, a typed character, an arriving message. Nothing changes by itself unless the story is \"what the system does on its own\"; then hide the cursor (`cursor(false)`).\n- **Hold the payoff.** 1.5–2.5 s on the result; holds before actions read as intention.\n- **One camera move per beat**, in on the thing that changed, back out before the next action.\n- **Short transitions.** Most parts enter in 0.3–0.5 s; containers and flights 0.6 s; overshoot only on pops and landings.\n- **Loops end where they began.** `play(..., { loop: true })` refuses a script whose final state, cursor or camera differs from the start; add `loop: true` to `meta` so `mografy check --motion` compares the last frame with the first.\n- **Text must fit.** `ui.text` with `max` throws when copy overflows its box (the error names the string and both widths); shorten it, widen the box, or pass `fit: 'ellipsis'` on purpose.\n- Invent the product, people and figures, as in the reference films. Never draw a real company's interface, mark or customer data.\n\n## Review checklist\n\n- [ ] The first frame says which product this is in one glance (chrome, brand, one real number or row).\n- [ ] At most one focal element per beat; everything else is quieter.\n- [ ] Count the words: are they all needed by the story?\n- [ ] The window or phone is cropped by the frame; nothing floats whole in the middle.\n- [ ] Each change in a transition strip follows a visible cause.\n- [ ] `mografy check --motion`: no jumps, hard starts or stops, and \"loop seam clean\" for a loop.\n- [ ] Watch it at phone size (a 9:16 export or a 360 px wide preview): the story still reads.\n",
|
|
4
|
+
"references/animation-principles.md": "# The twelve principles of animation in Mografy\n\nUse these principles to give movement weight, intention, and personality. Choose the ones that support the scene; do not force all twelve into every shot or add perpetual motion to readable holds. Record the chosen principles and their purpose in the storyboard. Preserve existing typography, logos, and character identity.\n\n| Principle | Application in a Canvas scene | Review criterion |\n| --- | --- | --- |\n| 1. Squash and stretch | Deform a soft object around its contact or pivot point. Use reciprocal scale factors (sx = s, sy = 1/s) to approximately preserve area. Keep logos and text rigid unless deformation suits the brief. | The object conveys weight without unintended distortion. |\n| 2. Anticipation | Add a small opposite move, compression, or brief pause before the main action. Evaluate each phase from absolute time. | The viewer can predict what will happen without a distracting delay. |\n| 3. Staging | Use composition, contrast, negative space, and one dominant moving focus. Position secondary objects to support that focus. | The message is clear at key poses and throughout transitions. |\n| 4. Straight ahead action and pose to pose | Plan start, extreme, and settle poses; interpolate between them. For organic straight-ahead exploration, precompute seeded samples in setup and index/interpolate them by time. Never integrate from the previous rendered frame. | Random seeks and repeat renders preserve exactly the same pose. |\n| 5. Follow through and overlapping action | Let a tail, ribbon, or supporting element settle after the main body. Use delayed time windows or bounded damped oscillation with a defined start. | Parts share a cause but stop at different times; motion ends cleanly. |\n| 6. Slow in and slow out | Use `springs.out` for entrances, `keys` for moves that pass through several poses, and `cameraPath` for the camera; keep `ease.inOutCubic` for a single short move. Vary spacing to communicate acceleration and deceleration. | Speed changes feel intentional; related elements use coherent curves. |\n| 7. Arcs | Move subjects along analytic curved paths, such as quadratic Bezier positions or a bounded sine arc. Let rotation follow the tangent when useful. | Motion has a coherent path and clears safe margins. |\n| 8. Secondary action | Add a restrained blink, tilt, highlight, or small response that supports the primary action. Offset its timing and amplitude. | It reinforces emotion or meaning without competing with the main message. |\n| 9. Timing | Allocate anticipation, action, settle, reading hold, and exit in seconds. Use fps to judge frame spacing and ctx.beat(time) for musical cues when audio exists. | Weight, pacing, legibility, and beat alignment work at the requested fps. |\n| 10. Exaggeration | Selectively amplify a pose, trajectory, contrast, or overshoot to make the intent readable. Keep amplitudes adjustable and bounded. | The action is expressive without clipping or harming brand recognition. |\n| 11. Solid drawing | Keep pivots, proportions, perspective, overlap, and volume coherent with Canvas transforms, gradients, and consistent lighting. For flat graphics, maintain optical balance and silhouette. | Forms stay believable while moving, scaling, and overlapping. |\n| 12. Appeal | Build clear silhouettes, harmonious proportions, distinct pose rhythms, and a consistent palette. Use deliberate asymmetry when it adds character. | The scene feels intentional and engaging, with useful visual hierarchy. |\n\n## Deterministic follow-through example\n\nThe runtime's `settle(time, start, duration, amplitude, cycles?)` is a bounded wobble that is exactly 0 outside its window; `springs.out`, `springs.pop` and `spring()` cover entrances and overshoot. All are pure functions of time, so seek order never changes a pose:\n\n```ts\nimport { at, settle, springs } from '@mografy/runtime';\n// Evaluate inside renderFrame: the card pops in, then its ribbon lags behind and settles.\nconst scale = at(time, 0.4, 0.9, springs.pop);\nconst ribbonAngle = settle(time, 0.8, 1.2, 0.12);\n```\n\nStore motion only in scene modules. Do not add a live physics loop, unseeded randomness, a clock, or previous-frame state. Read [scene-authoring.md](scene-authoring.md) for the runtime and drawing contract.\n\nReview the start, extreme, settle, and final hold of each action, plus dense transition strips. Check repeated and out-of-order times with `npx mografy check`, and inspect both raw and post-processed frames with `npx mografy review`. When motion sampling, glow, or grain hides a pose or blurs important text, adjust the motion or output settings and review again.\n",
|
|
5
|
+
"references/built-in-components.md": "# Built-in component references\n\nThe sixteen built-in animations are working scene references for authoring and storyboards. Read the relevant scene entry and its imported modules before reusing a pattern. Paths below refer to the owning Mografy repository in [project.md](project.md). For an existing user project, inspect its local copies first; they may have been customized.\n\n## Source catalog\n\nThe reusable implementations live in [components.ts](__REPOSITORY__/packages/server/template/scenes/components.ts) and [social-components.ts](__REPOSITORY__/packages/server/template/scenes/social-components.ts). Each animation has a complete entry under `packages/server/template/scenes/`:\n\n| Component | Entry | Function | Authoring reference |\n| --- | --- | --- | --- |\n| Stagger text | [stagger-text.ts](__REPOSITORY__/packages/server/template/scenes/stagger-text.ts) | `staggerText` | Measured letters rise with staggered opacity and easing. |\n| Typewriter | [typewriter.ts](__REPOSITORY__/packages/server/template/scenes/typewriter.ts) | `typewriter` | Character reveal and a caret computed from time. |\n| Pop card | [pop-card.ts](__REPOSITORY__/packages/server/template/scenes/pop-card.ts) | `popCard` | Lift, scale, opacity, and local content drawing. |\n| Progress bar | [progress-bar.ts](__REPOSITORY__/packages/server/template/scenes/progress-bar.ts) | `progressBar` | Eased progress clipped inside a rounded track. |\n| Pulse dots | [pulse-dots.ts](__REPOSITORY__/packages/server/template/scenes/pulse-dots.ts) | `pulseDots` | Phase-offset loading motion from absolute time. |\n| Logo reveal | [logo-reveal.ts](__REPOSITORY__/packages/server/template/scenes/logo-reveal.ts) | `logoReveal` | Staged reveal of original Mografy Path2D artwork. |\n| Social card | [social-card.ts](__REPOSITORY__/packages/server/template/scenes/social-card.ts) | `socialCard` | A profile card with avatar, text, and a composed entrance. |\n| YouTube subscribe | [youtube-subscribe.ts](__REPOSITORY__/packages/server/template/scenes/youtube-subscribe.ts) | `youtubeSubscribe` | A button interaction with cursor and subscribed state. |\n| AI chat | [ai-chat.ts](__REPOSITORY__/packages/server/template/scenes/ai-chat.ts) | `aiChat` | Timed prompt/reply bubbles and text reveal. |\n| Like burst | [like-burst.ts](__REPOSITORY__/packages/server/template/scenes/like-burst.ts) | `likeBurst` | An expressive heart response with radial secondary motion. |\n| Follow badge | [follow-badge.ts](__REPOSITORY__/packages/server/template/scenes/follow-badge.ts) | `followBadge` | Profile identity and a follow-state transition. |\n| Notification toast | [notification-toast.ts](__REPOSITORY__/packages/server/template/scenes/notification-toast.ts) | `notificationToast` | A compact status message with staged reveal. |\n| Lower third | [lower-third.ts](__REPOSITORY__/packages/server/template/scenes/lower-third.ts) | `lowerThird` | A clipped title/subtitle reveal and clear hierarchy. |\n| Count up | [count-up.ts](__REPOSITORY__/packages/server/template/scenes/count-up.ts) | `countUp` | A deterministic numeric value transition. |\n| Toggle switch | [toggle-switch.ts](__REPOSITORY__/packages/server/template/scenes/toggle-switch.ts) | `toggleSwitch` | Coordinated knob position, track color, and cursor response. |\n| Audio wave | [audio-wave.ts](__REPOSITORY__/packages/server/template/scenes/audio-wave.ts) | `audioWave` | A procedural wave of bars; actual audio-reactive motion needs scene-specific audio or beat input. |\n\n[component-frame.ts](__REPOSITORY__/packages/server/template/scenes/component-frame.ts) supplies the shared 1920 × 1080, eight-second, 30fps scene contract, font selection, speed control, and drawing scopes. `componentFrame` evaluates `time * speed % 4`; account for that four-second reset before changing timing. `centeredComponent` retains the landscape design-space transform and uses component-specific widths around the exact canvas center in portrait. Installed built-in projects and their bundled thumbnails default to 9:16 portrait. All sixteen entries support both landscape and portrait canvases. Follow badges stack vertically; chat, notification, profile, and lower-third copy use measured wrapping or bounded single lines. Dots and bar thickness use the short edge to preserve spacing and proportions. Select Adapt layout when exporting to the other orientation. [brand-logo.ts](__REPOSITORY__/packages/server/template/scenes/brand-logo.ts) supplies the original mark geometry. [showcase.ts](__REPOSITORY__/packages/server/template/scenes/showcase.ts) demonstrates composition of all sixteen motifs.\n\n## Reuse in a project\n\n- The source library is `packages/server/template/`; editable installed copies are under the configured library's `.components/{id}/`. When running from source, the default library is `projects/`. Read `scenes/main.ts` and the manifest of the selected installed project rather than assuming it is identical to the template.\n- New projects receive the component modules and scene entries. Import the needed function from the project's local `scenes/components.ts` or `scenes/social-components.ts`. Preserve required imports, including brand geometry. Do not import files outside the animation project; compilation allows project-local modules and `@mografy/runtime` only.\n- Copy the useful motion and composition into the selected project's own scene modules. Adapt layout, copy, palette, scale, and timing to its brief. Keep pure time evaluation and isolated Canvas state; retain the project's existing assets and visual identity.\n- Use these examples to choose a motif in the storyboard and connect it to a concrete scene function. For a longer sequence with transitions and a brand ending, read [intro.md](intro.md).\n- Optional extras are not installed with Mografy; installation contains only the sixteen built-in components. They live in the repository's [extras/](__REPOSITORY__/extras/) folder on GitHub and are copied into a project when a brief needs them: camera moves and transitions for film-style sequences ([camera-transitions.md](camera-transitions.md)), Chinese / Japanese typography with OFL fonts ([cjk-typography.md](cjk-typography.md)), Three.js 3D layers ([three-d.md](three-d.md)), contextual music generated from the film's cues ([music.md](music.md)), and product walkthroughs that redraw an app's screens as simplified cards ([product-walkthrough.md](product-walkthrough.md)).\n- Keep important subtitle params distinct from ordinary scene copy. The source entries may contain string params that are edited by an agent in source rather than shown in the subtitle inspector.\n\n## Review\n\nOpen an installed example with `npx mografy dev [project]`. After adapting it, run `npx mografy check [project]` and `npx mografy review [project]`; inspect actual frames at the entrance, extreme, settle, hold, and any loop reset. Verify text measurement, safe margins, clipping, contrast, and out-of-order seeking. The catalog is a source reference, not an acceptance result for a modified scene. Read [scene-authoring.md](scene-authoring.md) and [animation-principles.md](animation-principles.md) for the contract and motion direction.\n",
|
|
6
|
+
"references/camera-transitions.md": "# Camera, transition and atmosphere helpers\n\n[cinema.ts](__REPOSITORY__/extras/cinema/cinema.ts) gives film-style scenes a shared vocabulary. Every helper is a pure function of time and options, uses `ctx.width` / `ctx.height`, and works in landscape and portrait. [cinema-demo.ts](__REPOSITORY__/extras/cinema/cinema-demo.ts) is a fourteen-second tour of six shots joined by six transitions.\n\n## Add to a project\n\nThe helpers are an optional extra, not part of the installed template. If the project already has `scenes/cinema.ts`, read and reuse that local copy; it may have been customized. Otherwise copy `extras/cinema/cinema.ts` from the current Mografy checkout into the project's `scenes/` folder, or download it from GitHub:\n\n```sh\nnpx mografy add cinema projects/<name>\n```\n\n`npx mografy add` copies from this checkout's `extras/` folder, or from GitHub when it is missing, keeps any project file that differs from the extra (`--force` replaces it), and prints the import line. Without the `mografy` command, download the same files from `https://raw.githubusercontent.com/mografy/mografy/main/extras/cinema/`.\n\nImport it locally (`import { plate, move, particleWipe } from './cinema.js'`). Copy `cinema-demo.ts` too only when the user wants the tour.\n\n## Continuity first\n\nThese transitions are deliberate breaks: use them between acts, on a musical change, or when the film moves from one plate to another. Within a scene drawn on canvas, prefer a shared-geometry handoff and one film camera ([film-architecture.md](film-architecture.md)); a dissolve or wipe between two unrelated layouts hides a jump instead of making it readable. For a camera over drawn (not plate) content, use the runtime's `cameraPath` and `withCamera`; `move` is for framing a still plate.\n\n## Plates and camera\n\n| Helper | Use |\n| --- | --- |\n| `preparePlate(ctx, path, softWidth?)` | In `setup`: load an image and prepare a blurred highlights copy for bloom. Store the result in `ctx.assets`. |\n| `plate(ctx, plate, camera, { crop?, alpha?, bloom? })` | Draw a plate covering the canvas. `crop` selects a source rectangle for a close-up. |\n| `move(time, start, end, from, to, curve?)` | Ease between two framings. A camera is `{ zoom, focusX, focusY, panX, panY }`; `zoom ≥ 1` scales about the focus (0–1 of the canvas); pans are canvas pixels. |\n\nCamera direction: give each shot one motivated move (push in, pull out, pan, tilt) with `ease.inOutCubic` or `ease.outCubic`. Keep zoom ranges small (for example 1.0 → 1.08 over three or four seconds). Pans are clamped to the image, so add zoom headroom before panning. Avoid roll, shake, and bounce unless the brief asks for energy; natural camera work reads as one continuous, decelerating move. Flat key art cannot blink or move limbs; motion comes from camera, light, particles, and type.\n\n## Transitions\n\nEach transition takes `{ start, end, from, to }`. `from` and `to` are callbacks that draw complete frames; the transition calls them inside clips and transforms. Before `start` it draws `from`, after `end` it draws `to`. Clamp each callback's time to its own shot, for example `from: () => shotA(ctx, Math.min(time, cut))`, so the outgoing shot does not continue past its end.\n\n| Helper | Effect | Good for |\n| --- | --- | --- |\n| `crossfade` | Dissolve; the incoming frame goes through one pooled buffer, so overlaps do not flash | Quiet changes, a breath between sections. |\n| `dipTo({ color })` | Fade through a colour, cut at the midpoint | Section changes; a dip to dark when the music drops. |\n| `flash(ctx, time, at, { strength, decay })` | Exposure flash overlay (draw after the frame) | Downbeats and hard cuts. |\n| `iris({ x, y })` | A circle opens from a point with a glowing rim | Moving from a motif (a moon, an eye, a logo) into the next shot. |\n| `slash({ slant })` | A slanted light band wipes across | Bright, energetic cuts. |\n| `whip({ direction })` | Both shots travel together with motion smear | Implied camera movement, for example tilting from a face to the feet. |\n| `particleWipe({ direction, shape, count, color })` | A gust of growing petals, stars, circles or hearts becomes windows onto the next shot | Sakura-style transitions and themed changes. |\n\nKeep transitions between roughly 0.3 and 0.8 seconds. Place the cut on a beat or bar with `ctx.beat(time)` when the project has audio. Use two or three transition types per film; repeating one signature transition (such as `particleWipe`) ties a piece together better than using every type.\n\n## Atmosphere\n\n| Helper | Use |\n| --- | --- |\n| `glow(ctx, x, y, radius, color, alpha)` | Soft screen-mode light, for a moon halo or stage light. |\n| `drift(ctx, time, { shape, count, amount, wind, fall, size, color })` | Wrapping particles: falling sakura, snow, or sparks. |\n| `twinkle(ctx, time, { area, count, size, color })` | Four-point stars that twinkle independently. |\n| `lightSweep(ctx, time, { start, end, width, slant, alpha })` | One slanted sheet of light crossing the frame. |\n| `smear(ctx, amount, axis)` | Brief directional motion smear of the current frame. |\n\n## Review\n\nAdd each transition window to `review.transitions` in `mografy.json` with a small step (0.033–0.05 s) and inspect the strips. Check that clamped shots do not jump at the cut, that particle rims fade before shapes grow large, that flashes do not wash out type, and that the frame never shows an image edge during a move.\n",
|
|
7
|
+
"references/cjk-typography.md": "# Chinese and Japanese typography\n\n[cjk.ts](__REPOSITORY__/extras/cjk/cjk.ts) sets Chinese and Japanese copy: vertical text (tategaki) and horizontal text with CJK line breaking. [cjk-demo.ts](__REPOSITORY__/extras/cjk/cjk-demo.ts) shows both.\n\n## Add to a project\n\nThe module and fonts are an optional extra, not part of the installed template. If the project already has `scenes/cjk.ts`, read and reuse that local copy. Otherwise copy from the current Mografy checkout (`extras/cjk/`) or download from GitHub:\n\n```sh\nnpx mografy add cjk projects/<name>\n```\n\n`npx mografy add` copies from this checkout's `extras/` folder, or from GitHub when it is missing, keeps any project file that differs from the extra (`--force` replaces it), and prints the import line. It also copies both font subsets with their licence and registers them under `fonts` in `mografy.json`; remove the one the design does not use. Without the `mografy` command, download the same files from `https://raw.githubusercontent.com/mografy/mografy/main/extras/cjk/`.\n\nCopy only the font the design uses when one is enough. Keep the licence file with the fonts.\n\n## Fonts\n\nThe repository provides two OFL-licensed subsets in [extras/cjk/fonts/](__REPOSITORY__/extras/cjk/fonts/): `NotoSansCJKtc-Medium-subset.otf` (family `Noto Sans CJK TC`, weight 500) and `NotoSerifCJKtc-Bold-subset.otf` (family `Noto Serif CJK TC`, weight 700). They cover ASCII, kana, CJK punctuation, full-width and vertical presentation forms, 5,401 common Traditional Chinese characters (Big5 level 1), 6,355 Japanese kanji (JIS levels 1–2), and 3,755 Simplified characters (GB2312 level 1). Together they are about 9.5 MB, so they are fetched per project rather than installed. After copying, register them in `mografy.json`:\n\n```json\n\"fonts\": [\n { \"family\": \"Noto Sans CJK TC\", \"path\": \"assets/NotoSansCJKtc-Medium-subset.otf\", \"weight\": 500 },\n { \"family\": \"Noto Serif CJK TC\", \"path\": \"assets/NotoSerifCJKtc-Bold-subset.otf\", \"weight\": 700 }\n]\n```\n\nUse the exported `CJK_SANS` and `CJK_SERIF` names with the registered weights. Without registration, the browser falls back to system fonts, so previews may differ between computers and exports. Serif (Mincho / Song) suits titles, poetry and Japanese PV copy; Sans suits subtitles and UI. For a character outside the subsets, or JP / SC / KR glyph forms, regenerate a subset with [subset-cjk-fonts.py](__REPOSITORY__/extras/cjk/subset-cjk-fonts.py) from the [Noto CJK](https://github.com/notofonts/noto-cjk) sources (`--extra` adds characters). Check unusual names and rare characters in actual frames.\n\nThe 9.5 MB of subsets load every time the project opens. Once the copy is settled, shrink them to the film's own characters:\n\n```sh\npython3 extras/cjk/subset-film-fonts.py projects/my-film\n```\n\nIt reads `scenes/`, `mografy.json` and the JSON, Markdown, text and CSV files in `assets/` and `storyboards/`, writes `<font>-film.otf` beside each registered font (about 100–170 KB), and points `mografy.json` at those files. The originals stay; running it again always rebuilds from them, so run it after every copy change, and before delivery. Characters it lists as missing from a font were already missing before (fine when they only appear in code comments). Copy built at runtime from character codes is not seen: pass it with `--extra \"字元\"`.\n\n## Vertical text\n\n`verticalText(ctx, time, { text, x, y, size, columnHeight?, tracking?, columnGap?, font?, weight?, color?, glow?, outline?, start?, stagger?, duration?, lift?, end?, out? })` draws columns top to bottom and right to left. `x` is the centre of the first (rightmost) column, `y` its top. `columnHeight` wraps automatically; `\\n` starts a new column. It returns the layout (`glyphs`, `columns`, `width`, `height`) for placing rules or ornaments; `verticalLayout` returns the same without drawing.\n\nCanvas has no vertical writing mode, so the helper:\n\n- swaps punctuation and brackets for Unicode vertical presentation forms (、。,:;!?「」『』()【】《》〈〉…);\n- rotates long marks and dashes (ー, 〜, ―) and single Latin letters by 90°;\n- nudges small kana (っ, ゃ, ョ…) toward the upper right of their cell;\n- sets one or two consecutive digits horizontally in one cell (tate-chu-yoko), for dates such as 10月17日;\n- applies kinsoku when wrapping: closing punctuation, small kana and ー never start a column, and opening brackets never end one.\n\nLonger Latin words read poorly in vertical copy; prefer a separate horizontal label.\n\n## Horizontal text\n\n`cjkText(ctx, time, { text, x, y, size, maxWidth?, lineHeight?, tracking?, align?, ... })` wraps with the same kinsoku rules while keeping Latin words and numbers whole, then reveals characters with the shared stagger options. `wrapCJK` returns the lines without drawing, for layout. `y` is the first baseline; lines advance by `size * lineHeight` (default 1.5).\n\n## Direction\n\n- Keep important copy readable for at least the caption hold in [taste.md](taste.md) (characters ÷ 4.5 + 0.5 s); CJK characters carry more meaning per glyph than Latin letters, so long lines need longer holds.\n- Use `stagger` of 0.04–0.08 s for titles and 0.015–0.03 s for longer captions.\n- On bright or busy images, add a dark gradient scrim or `outline` (about 0.1 × size) rather than relying on glow alone.\n- In portrait, wrap captions to the social safe area and shorten columns with `columnHeight`.\n- Expose only important subtitles as `role: 'subtitle'` params; editable copy must stay within the font subset.\n\n## Review\n\nInspect actual frames: punctuation position in columns, wrapped column starts, digit pairs, long-mark rotation, glyph fallback (a different-looking character usually means it is missing from the subset), contrast, and reading time.\n",
|
|
8
|
+
"references/examples.md": "# Reference films\n\nReference films are finished films kept as references for quality. Before planning a new film, read the one whose brief is closest to yours, watch it in the player, and reuse its structure; then compare your own frames against it at review.\n\n- **In the repository's `examples/`**: `mografy-intro`, installed and listed in the player under Examples, and the ten `stage-*` films ([ui-stage.md](ui-stage.md)), listed in `examples/catalog.json` and downloaded from GitHub by `npx mografy add <name>` the first time (a full checkout has them locally).\n- **Showcase films** live on the website, not in the installation: watch them at **https://www.mografy.app/showcase** and download one by name with `npx mografy add <name> [folder]`. When a brief needs a longer film, a narrated explainer, 3D, or a model to start a multi-shot film from, fetch the showcase first: the page shows every film with its preview, and **https://www.mografy.app/showcase/films.json** lists the same films for agents (name, title, length, aspect ratio, what to read it for, where to look, download URL). Pick from that list, then download the closest one. The tables below describe the showcase films as of this Mografy version; the website's list wins when they differ.\n\nThey follow the [quality floor](../SKILL.md) and the [film architecture](film-architecture.md): drawing is a pure function of time, one table drives the shot times and `meta.shots`, and the runtime's `keys`, `cameraPath`, `layer`, `blurLayer`, `bloom` and `blurText` do the camera, fades, blur and glow. Each has a composed, sustained score in `music-src/` and its fonts and licences in `assets/`.\n\n## Copy one to work on\n\n```sh\nnpx mografy add # list reference films, showcase films and helpers\nnpx mografy add stage-invoices ./hero # copy a Stage film (downloaded from GitHub when not checked out)\nnpx mografy add film-starter ~/Films/new # download a showcase film: the model for a new multi-shot film\nnpx mografy add mografy-montage # into examples/ of the workspace (projects/mografy-montage in a checkout)\nnpx mografy add stage-phone projects/my-app # a copy of your own, to build on\n```\n\nThe copy is an ordinary project: open it with `npx mografy dev <folder>`, and edit, check, review and export it like any other. Never edit the films in `examples/` themselves; they are the reference other agents read. Stage and showcase downloads need a network connection; if it fails, the same zip is on the film's showcase page.\n\n## The films\n\nInstalled films link to their source; showcase films are downloaded first, then read in the downloaded folder.\n\n| Film | Length and look | Read it for | Where to look |\n| --- | --- | --- | --- |\n| `film-starter` (showcase) | 20 s, 16:9, English, dark | The model every multi-shot film starts from (see [film-architecture.md](film-architecture.md)): one light the eye follows from a point to a line, a card that grows out of the line and plots an ease curve, a ring of light, the last line's full stop | `BEATS` (shot table), `camera`, `spine` (a line growing round the card), `cardFace` (glass card in a `layer`), `ring` (`bloom`), the `blurLayer` defocus in `world` |\n| `mografy-montage` (showcase) | 60 s, 16:9, English or Traditional Chinese (`lang` param); dark → light → neon | One continuous camera across three acts; one comet of light drawing every act I shape from shared geometry; a flat UI card turned into a 3D window; kinetic type that sharpens out of blur; a spiral galaxy; the logo drawn by the last dot | `cam1` / `cam2` (`cameraPath`), `headS` (`keys` along one path), `ACT1` / `joinSegs` (shared geometry), `kin` (blurText per glyph), `plane2` / `drawPlane` (3D card), `galaxy`, `logo`; `BEATS` → `SHOTS` |\n| `mografy-triangulum` (showcase) | 42 s, 16:9, Traditional Chinese, deep space | A launch teaser in ten beats linked by one light trail; Three.js point clouds composited between 2D layers; depth of field and rack focus with `blurLayer`; glass cards; champagne type with a specular sweep | `buildParticles` / `galaxyLayer` / `fieldLayer` (3D), `blurred` (depth of field), `comet` (light trail), `glass`, `title` (mask reveal), `sweepFill`; `SHOTS` → `BEATS` |\n| `mografy-story` (showcase) | 71 s, 16:9, Traditional Chinese captions, dark → light | A narrative film with a turn: twelve shots, captions on their own track, a black box that opens into the light world, product UI redrawn as cards, a brand-logo ending | `SHOTS` (design times, `sx` slow-down, `xf` overlap, `stop`), `frame` (shot lookup and crossfade), `s05` / `cube3` (the box), `s07` / `system` (UI cards and a slider), `caption`, `brandLogo` |\n| [mografy-intro](__REPOSITORY__/examples/mografy-intro/scenes/main.ts) | 12 s, 16:9, English | A short product intro in four beats; see [intro.md](intro.md) | `beatCode`, `beatScrub`, `beatChat`, `beatLogo` |\n| `analytics-product` (showcase) | 8 s loop, 16:9, English UI | A product UI moment: the cursor picks \"This week\", the number counts up and the bars regrow while the rest of the screen quiets | `focus` (push-in and dimming), the segmented control, the chart, `cursor` |\n| [stage-invoices](__REPOSITORY__/examples/stage-invoices/scenes/main.ts) | 7 s loop, 16:9, English UI, four looks | The Stage model ([ui-stage.md](ui-stage.md)): a window pinned off two edges, story words only, Mark paid flies the amount into a rolling total, camera leans in, Undo resets on screen. The `variant` param draws the five failures for comparison | `initial`, `layout`, the `play` script, `ui.window`, `ui.roll`, `ui.fly`, `ui.toast` |\n| [stage-phone](__REPOSITORY__/examples/stage-phone/scenes/main.ts) | 7.6 s loop, 9:16, English UI | A phone cropped by the frame and driven by taps: a notification grows into the thread as one object, typing, a reply that forms out of the field, a side-button lock | `ui.phone`, `ui.notification`, the container transform under `open`, `type`, `tap` |\n| [stage-dashboard](__REPOSITORY__/examples/stage-dashboard/scenes/main.ts) | 6.5 s loop, 16:9, dark | The newer macOS window (`tahoe`), one insight on a chart: hover, tooltip, one annotation, camera in and out | `ui.window` (`tahoe`), the chart, hover and note presence, `focus` |\n| `stage-bento`, `stage-calendar`, `stage-upload`, `stage-command`, `stage-checkout`, `stage-request`, `stage-snooze` | 5.7–10 s loops | The rest of the Stage set: a bento grid, a drag, a blueprint diagram with annotations, a keyboard-only palette, a checkout in a tabbed browser, two screens, a feature card. [ui-stage.md](ui-stage.md) says which to start from | each film's `scenes/main.ts` and `style.md` |\n| `follow-interaction` (showcase) | 8 s loop, 16:9, English UI | One micro-interaction done carefully: a button whose width and label spring between states, a ripple, a confirmation | `state` (spring), the button, the labels, `cursor` |\n| `mografy-brand` (showcase) | 8 s, 16:9, logo only | A logo reveal from the official paths: the ribbon drawn by one stroke, the arches rising, the wordmark letter by letter | the three numbered steps in `renderFrame`, `LOGO_PIECES` |\n\n## Paper theatre series\n\nFive narrated Traditional Chinese explainers (74–85 s, showcase films) set in one desk paper theatre built in Three.js: card puppets and props on strings, one brass lamp whose real shadows carry the idea, stop-motion on 2s with a seeded boil (param `motion`: `stop-motion` or `smooth`), three acts, full-frame 2D inserts, subtitles timed from the narration. Read them when a brief asks for 紙劇場, 紙偶, 定格, a psychology or concept explainer with narration, or a handmade look. Each has its rules in `style.md`, its shots in `storyboards/storyboard.md`, and `storyboards/timing.py` → `cues.json` for the narration timing (bring your own narration take). They have narration instead of music.\n\n| Film | The idea in props | Where to look |\n| --- | --- | --- |\n| `paper-theatre-shadow` (showcase) | 陰影心理學: one bulb moves and the shadow answers; four trait tokens live in the shadow's head. The first of the series: the theatre, lamp and post grade the others reuse | `world.ts` `buildWorld` (box, proscenium, lamp, desk), `makePost` (depth of field, ACES, grain), `step` (stop-motion), the shot table in `main.ts` |\n| `paper-theatre-gestalt` (showcase) | 格式塔心理學: card fragments whose shadows lock into a face from one lamp position only; six laws in an ink-papered Act II | `projPoint` and the lamp positions `L_FACE` / `L_RUBIN` / `L_PRAG` (real 3D projection), the six-law layout |\n| `paper-theatre-aesthetic-usability` (showcase) | 美即好用效應: two cardboard ATMs, 2D interfaces inside the screens, 3D reactions outside; the camera passes through a screen into full-frame 2D | `ui.ts` (`paintScreen`, `skin`, `wire`), `EYE` (the lamp at the viewer's eye) |\n| `paper-theatre-ringelmann` (showcase) | 林格曼效應: one rope, a brass dynamometer, a 3D needle against a 2D target needle; acts change under full-frame 2D, never in a blackout | `dialAngle`, `ROPE_*` / `MINI` (rope and dials), the 2D cover transitions |\n| `paper-theatre-adhd` (showcase) | 不聽使喚的燈 (ADHD): a spotlight on a brass track against a 2D ring where the puppet wants to look; the gap closes but never quite meets | `TRACK`, `tapePositions`, `bake` / `loadBaked` (texture cache) |\n\n\nTwo character films use the same paper theatre language with a printed puppet instead of narration: a flat card on a rod or threads, replacement animation (one card per pose or emotion, flips face → edge → back over three poses), things leave on their mechanism (pulled up on strings, slid into the wings, curtains), cuts on the bar grid of a composed score (`music-src/compose.py`). Read them for 角色, 偶像, 童話 or story briefs.\n\n| Film | Length and look | Where to look |\n| --- | --- | --- |\n| `paper-theatre-moon-rabbit-opera` (showcase) | 60 s, the theatre built in real 3D inside an opera house, cut against flat 2D inserts | `world3d.ts` (`resetWorld`, `setHouse`, drapes, shadows drawn once per frame), `paper.ts` (`dieCut`, `on2`, 2D inserts, `chapterCard`) |\n| `paper-theatre-sea-moon` (showcase) | 72 s, full 3D undersea castle; the puppet is a printed card on threads, swapped by emotion; real dissolves | `world.ts` (cards, rim and mask passes), `castle.ts`, `theatre.ts` (pearl shell theatre), `post.ts`, `DISSOLVE` in `main.ts` |\n\nTo make a new one: `npx mografy add paper-theatre-shadow <folder>` (or the closest film; it downloads from the showcase), keep the theatre, lamp, post and stop-motion rules, and replace the props, story, copy and narration with the new idea. For a character film start from the closer of the two and bring your own puppet art (one transparent PNG per pose). Re-subset the fonts after any copy change (`extras/cjk/subset-film-fonts.py`).\n\n## What to take from them\n\n- **Timing.** One table per film. Change a shot's end there and every key, shot stop and review time follows.\n- **Continuity.** Each shot ends on the geometry the next one starts from: the comet's head becomes the underline, the underline becomes the prompt pill, the pill becomes the window's field. Read the transitions in the montage (`npx mografy add mografy-montage`) before designing your own.\n- **Camera.** Moves start before the action, ease through every key and never stop on a pose that is not a story beat. Cards and windows have their own local transforms inside the camera.\n- **Cost.** Blur goes through layers or the text's shadow, glow through `bloom`, and buffers are pooled. Run `npx mografy check` on a copy to see what a frame costs, and keep your own film in the same range.\n- **Taste.** Calm pacing, big type, still holds, one logo at the end, and sustained music without sharp high sounds; the numbers are in [taste.md](taste.md). The project's `style.md` overrides them.\n\nDo not copy their copy, brand marks or music into another brand's film. Take the structure and the techniques, and build the new film from its own brief, assets and style.\n",
|
|
9
|
+
"references/film-architecture.md": "# Film architecture: one world, one camera, one table\n\nRead this before writing any animation with more than one shot or a moving camera. It is how a film stays continuous: the viewer follows one thing from the first frame to the last, and nothing resets between shots. The model is the `film-starter` showcase film (`scenes/main.ts`, about 270 lines; `npx mografy add film-starter <folder>` downloads the whole project, fonts included): read it before writing a new film and copy its structure, or start the new film from the download. For finished films at full length (a 60 s promo, a 42 s teaser, a 71 s story), see [examples.md](examples.md).\n\n## The shape of a film module\n\n```ts\nimport { beats, cameraPath, keys, layer, blurLayer, bloom, springs, at, withCamera } from '@mografy/runtime';\nimport type { Context2D, FrameContext, SetupContext } from '@mografy/runtime';\n\n// 1. Tokens: every colour, font, size and fixed duration once.\nconst C = { bg: '#0E1116', ink: '#EEF2F5', accent: '#1BC6B4' };\n\n// 2. One table for timing. Everything else reads its times from here.\nexport const BEATS = beats([\n { title: 'A point', end: 3.2, stop: 2.4, handoff: .8, note: 'A point draws a line.' },\n { title: 'One idea', end: 7.2, stop: 6.4, handoff: .8 },\n // …\n]);\nconst T = Object.fromEntries(BEATS.list.map(b => [b.title, b.start]));\nexport const meta = { width: 1920, height: 1080, duration: BEATS.duration, fps: 30, background: C.bg, shots: BEATS.shots };\n\n// 3. Shared geometry: the objects that travel between shots, in world coordinates.\nconst LINE = { x0: 760, x1: 1160, y: 600 };\nconst CARD = { x: 960, y: 540, w: 720, h: 420, r: 36 };\n\n// 4. One camera, keyed on the table.\nconst camera = cameraPath([[0, 760, 600, 2.4], [T['One idea'] + 1, 960, 575, 1], /* … */]);\n\n// 5. The world, drawn from time alone, on any context.\nexport function drawFilm(c: Context2D, t: number, data: FilmData) { withCamera(c, camera(t), w => world(w, t, data)); }\n\nexport function setup(ctx: SetupContext) { ctx.assets.film = prepare(); }\nexport function renderFrame(ctx: FrameContext, time: number) {\n ctx.withCanvas(c => drawFilm(c, time, ctx.assets.film as FilmData));\n}\n```\n\n`world(c, t)` draws every element of the film from `t`: each element computes its own state (position, size, opacity, morph) as a function of time over the whole duration, not as \"shot 3's version\". That is what makes the end of one shot and the start of the next the same picture.\n\n## Continuity rules\n\n**Shared geometry.** Name the objects the viewer follows and keep them in one place (`LINE`, `CARD`, `DOT` above). When a shot changes what an object is, build the next object out of it. Either grow it: in `film-starter` the underline is the middle of the card's top edge, and the outline draws out from it both ways (a window on the outline's evenly spaced points) until its ends meet at the bottom. Or morph it: sample both shapes with the same number of points, ordered so they correspond, and interpolate them; check the in-between frames, because a straight interpolation between unlike shapes passes through ugly ones. Never fade one object out and an unrelated one in at the same spot.\n\n**Overlap exits.** The outgoing element keeps drawing its exit while the incoming one enters: the headline blurs out over 0.7 s while the underline already grows into the card. Starting the next action 0.2–0.5 s before the previous exit ends removes the dead frame at every cut.\n\n**One camera.** `cameraPath([[t, x, y, zoom?, roll?], …])` gives one smooth camera for the whole film: positions and roll follow monotone cubic keys (velocity carries through every inner key, no overshoot) and zoom is interpolated in log space. `withCamera(c, camera(t), draw)` puts the camera's `(x, y)` at the frame centre. Put keys on the shot table (`T['Takes shape'] + 2.4`), start a move up to about 0.5 s before the action it serves, and never move the camera during a click or a reading hold. Cards, phones and UI panels get local transforms inside the world (`c.translate`, `c.scale`) and, if they need a push-in of their own, a local zoom about their own centre. They never get a second camera; two cameras make one card's push-in crop the next.\n\n**Keyed motion.** Long moves that pass through several poses use one `keys([[t, v], …])` curve, never a chain of separately eased segments (each one would come to rest at its end, and the viewer sees the stop). Entrances, pops and settles use `springs.out`, `springs.pop`, `springs.camera`, `spring()` and `settle()`.\n\n**Groups fade as one.** A card with its rows, a UI panel or a whole outgoing shot fades through `layer(c, name, alpha, draw)`. Drawn directly, their alphas multiply where parts overlap and the overlaps flash.\n\n**Deliberate breaks.** A hard cut, a dip to black or a wipe is fine when the story changes register (a new act, a drop in the music). Then make the change itself readable: a cut on the beat, a match on shape or colour. Do not use a transition to hide a jump between two unrelated layouts.\n\n## The shot table\n\n`beats([{ title, end, stop?, handoff?, note? }, …])` takes contiguous shots and returns:\n\n| Field | Use |\n| --- | --- |\n| `shots` | `meta.shots`: timeline marks and the review sheet of stop frames. |\n| `list[i].start / end / stop` | Times to build keys and windows from (`T[title]`). |\n| `reviewTimes`, `transitions` | Every stop plus the frames around each handoff; copy them into `mografy.json` `review.times` and `review.transitions`. |\n| `at(time)` | The shot at `time`, seconds since it started and its progress. |\n| `duration` | The film length for `meta.duration`. |\n\nWhen a shot is retimed, change its `end` in the table only; every key and window built from `T` moves with it. With music, build the `end` values from `tempoGrid(tempo).onBar(n)` so shots stay on bars.\n\n## Storyboard as code\n\nFor films longer than about 15 s, let the storyboard and the film share one source. `drawFilm(c, t, data)` above only needs a 2D context, so a storyboard page can draw the real film at each panel's time:\n\n1. Bundle the scene module for the page with esbuild from the checkout: `node -e \"require('esbuild').build({ entryPoints: ['storyboards/board.ts'], bundle: true, format: 'esm', outfile: 'storyboards/board.js', alias: { '@mografy/runtime': '<checkout>/packages/runtime/src/scene.ts' } })\"` (run it where `esbuild` resolves, such as `packages/runtime`).\n2. In `board.ts`, import `filmFrame` from `@mografy/runtime` and `drawFilm`, `prepare` and `BEATS` from the scene; for each panel, tag its canvas with `filmFrame(c, 1920, 1080)`, scale to the panel, and call `drawFilm(c, beat.stop, prepare())`.\n3. Inline `board.js` into the storyboard HTML (or an Artifact) together with the `note` of every beat.\n\nThe board then shows the actual pixels of the film at each stop, and the scene is never a second implementation of the board. Edit the scene and rebuild the board; never fork the drawing into the board.\n\n## Review\n\nAdd `BEATS.reviewTimes` to `review.times` and `BEATS.transitions` to `review.transitions` (step 0.033 s), run `npx mografy check` and `npx mografy review`, and look at every transition strip. For each handoff confirm: the followed object is visible in every frame of the strip, nothing jumps between consecutive frames, no frame is empty, and the camera does not stop at a key that is not a story beat.\n",
|
|
10
|
+
"references/how-to-film.md": "# How-to films: operate the product, film each step\n\nA how-to film teaches one task in a product (create a client, send a quote, edit a card) as a short animation, one shot per step. It is delivered as one clip per step, for help centres, in-app hints, onboarding and slides, plus a full cut that plays the steps in order. The picture is a simplified redraw of the real UI built with the walkthrough kit ([product-walkthrough.md](product-walkthrough.md)), never a screen recording.\n\nThe difference from a product walkthrough is the capture: when the user asks for it and gives you a test account, you operate the product yourself with the agent's built-in browser or computer-use tool and capture every state. Without that, ask for screenshots and start at step 3.\n\n## When to use it\n\nRequests such as 操作教學動畫, 教學影片, 使用教學, 新手引導, 說明中心的動畫, \"how-to video\", \"tutorial clips for our help centre\", \"show users how to do X\". For a launch ad or a feature teaser, use [product-walkthrough.md](product-walkthrough.md) instead; for a 4–12 s loop of one action, [ui-stage.md](ui-stage.md).\n\n## Deliverables\n\n| Output | Spec | Where it is used |\n| --- | --- | --- |\n| One clip per step | 4–8 s, starts and ends on a still frame, MP4 (`share`) and WebM, small | In-app hints, help-centre articles, onboarding |\n| Full cut | 45–90 s, 16:9 1080p, big numbered step titles (\"1 建立客戶\") | Website, slides, YouTube |\n| Mobile cut (optional) | 9:16 1080 × 1920, finger taps, captions in the top third | App help, social |\n| Step stills | One PNG per step, its result frame | Slides and documents |\n| Captions | One line per step, in the brief's language | Muted playback, accessibility |\n\n## Workflow\n\nTwo gates need the user's (or their client's) approval: the step script, and the screenshot | redraw sheet.\n\n1. **Brief and step script.** Ask which tasks to teach, the steps of each (3–8), where the clips will live, aspect ratios, language, brand colours and the logo as SVG. Write `brief.md` and `capture/steps.json`: per step a title, the control it touches, the demo data typed, and the expected result. **Gate A:** the user approves the script and gives a test or demo account. Never use a production account with real customers.\n2. **Operate and capture.** Only when the user asked you to operate the product and gave the account:\n - Use the agent's own tools, not a scripted browser: in Claude, the Claude app's built-in browser for web apps (`navigate`, `computer` clicks and typing, `screenshot`, `get_page_text` / `read_page`, `javascript_tool`) or computer use for desktop and mobile simulators; in Codex, its built-in browser or computer-use tool. The user signs in themselves; approve each site once when the browser asks.\n - Walk the script one step at a time. Screenshot every state the step passes through: empty, focus, typing, loading, result, success toast. Take each screenshot after the UI settles.\n - Read the exact labels, values and placeholders from the page text, not from the image. Read the tokens with a short script on the page: primary, ink, muted, borders, background, radius, font family. Save `capture/01.png…nn.png`, `capture/steps.json` (labels, values, URL per state) and `capture/tokens.json`.\n - Type only invented demo data (晨光設計, demo@example.com, 0912 000 000). Stop and ask before anything that pays, sends a message or email outside the product, deletes, invites people or changes permissions. When done, list what you created and offer to delete it.\n3. **Check the capture.** Make a contact sheet of every state per step. Each step needs a before and an after; recapture missing or blurred states. Note text too small to read and ask for it.\n4. **Redraw sheet.** Follow the simplified redraw in [product-walkthrough.md](product-walkthrough.md): per step the target, the context it needs, and everything else to drop; real labels and tokens; type at 1.3–1.6× the app's size. Render one still per step beside its screenshot. **Gate B:** the user approves what stays and what goes.\n5. **Storyboard and timing.** One step per shot, 4–8 s each: settle 0.4 s, the action, the result held for the times in [taste.md](taste.md), settle 0.4 s. A shot must make sense alone, so it starts on its own card at rest and ends on its result at rest; the hand-off to the next card begins only after that still. Step title per shot (\"1 建立客戶\"), held 0.5 s + characters ÷ 4.5. Put every shot in the beat table and `meta.shots`, so the editor shows one layer per step and `npx mografy review` writes the shot sheet.\n6. **Build.** `npx mografy add walkthrough <project>`; one card per step from the same kit parts, one action per card, the pressed control grows into the next card, a big cursor (or taps in 9:16), each card's local zoom pushes in on its control. Opener: brand plus the task name; ending: the result of the whole task plus the logo. Run `npx mografy check --motion` and `npx mografy review`, and look at every stop frame: it is the first and last frame of a clip.\n7. **Export and split.** Export the full cut once (`--preset share` for the web, the user's own preset otherwise). Cut it into step clips at the beat table's shot starts and ends with the FFmpeg Mografy uses (`npx mografy setup ffmpeg --check` prints its path), re-encoding so every clip starts on its first frame:\n\n ```sh\n ffmpeg -ss <start> -to <end> -i renders/<film>.mp4 -c:v libx264 -crf 18 -pix_fmt yuv420p -movflags +faststart -an renders/steps/01-<step>.mp4\n ```\n\n Name clips `NN-<step-slug>.mp4`, write the step stills from `npx mografy review`'s shot sheet times, and the captions as `renders/steps/captions.<lang>.srt`. Put everything in `renders/steps/` and list it for the user.\n\n## When the product changes\n\nA redesign touches some steps, not the film: recapture those steps (step 2), redraw them, and re-export. Keep each step's card in its own function so one step can change without moving the others; keep the beat table times when the new step fits the same length.\n\n## Pitfalls\n\n- A clip that starts mid-hand-off shows half of the previous card: keep the still frames at shot boundaries.\n- Captured text in a screenshot is a guess; the page text is the truth. Re-read labels after the product's language setting changes.\n- Popups, cookie banners and tours on first sign-in are not part of the task: dismiss them before capture, and leave them out of the redraw.\n- Never show real customer data, a working share link, a real phone number or an API key in a capture you keep or a frame you render.\n",
|
|
11
|
+
"references/intro.md": "# Mografy intro reference\n\nUse the existing intro as a reference for multi-shot storytelling, deterministic transitions, responsive text layout, and a branded ending. Read [the project settings](__REPOSITORY__/examples/mografy-intro/mografy.json), [scenes/main.ts](__REPOSITORY__/examples/mografy-intro/scenes/main.ts), and [scenes/logo.ts](__REPOSITORY__/examples/mografy-intro/scenes/logo.ts) before adapting it. The current source is a 1920 × 1080, twelve-second, 30fps Canvas scene on a paper-colored background with ink and teal accents.\n\n## Four implemented beats\n\n| Beat | Active source window | Function | What to learn |\n| --- | --- | --- | --- |\n| Code becomes an idea | 0.1–2.6 seconds | `beatCode` | Measured colored text segments, time-based typing/caret, and a caption. |\n| Playback and scrubbing | 2.4–6.9 seconds | `beatScrub` | A preview frame, playhead, and reverse scrubbing derived from the same absolute time. |\n| An external edit updates the player | 6.8–9.9 seconds | `beatChat` | Stable wrapping before typing, a reply, color/timing change, and an update toast. |\n| Brand ending | 9.85–12 seconds | `beatLogo` | Original logo pieces revealed with clipping, staggered wordmark letters, and a closing tagline. |\n\nThe active windows overlap deliberately during transitions. They describe this implementation rather than a mandatory storyboard schedule. `renderFrame` calls all four beat functions; each derives visibility and motion from time. `window_` combines entrance and exit curves, and `revealPiece` clips the original logo paths. Read the real source when deciding the pose or overlap at a particular instant.\n\n## Assets and copy\n\n- ABeeZee Regular is loaded through `mografy.json`; keep its bundled `assets/OFL.txt` when copying the font. The scene uses Canvas text measurement and `wrap` to fit longer copy.\n- The existing music file is `assets/intro-music.mp3`, with a 120 BPM grid, offset −0.1 seconds, four beats per bar, and gain 1. The logo entrance starts around the 9.9-second cue. Preserve the asset and settings when adapting this specific project unless the brief requests a change.\n- The five subtitle params are `codeCaption`, `playCaption`, `scrubCaption`, `chatCaption`, and `tagline`. `request` is ordinary scene copy. `accent`, `ink`, and `vignette` affect the image.\n- The current film's text mentions Claude. Read the exact scene copy before describing or translating it. For a new brief, adapt the script deliberately; the product workflow also supports Codex.\n\n## Apply the reference\n\nUse its sequence structure to plan setup, demonstration, change, and payoff. Retain relevant motion principles, clear focal points, readable holds, and continuity between shots. Reuse the technique in the selected project's own scene modules, with its assets and proportions. For small reusable motifs, read [built-in-components.md](built-in-components.md).\n\nSave a project-specific English storyboard under `storyboards/` when requested, following [storyboard.md](storyboard.md). Codex creates visual boards with image generation; Claude uses Artifacts or a standalone local HTML/Canvas preview. A new storyboard may require longer text holds than this existing twelve-second film.\n\n## Validation and review\n\nFrom the owning repository, use:\n\n```sh\nnpx mografy dev examples/mografy-intro\nnpx mografy check examples/mografy-intro\nnpx mografy review examples/mografy-intro\n```\n\nThe existing review times are 1.8, 3.6, 5.4, 8.9, and 11.8 seconds. Transition strips cover 2.0–3.2, 8.4–9.4, and 9.8–11.4 seconds at 0.1-second steps. Inspect the generated PNGs, including output frames with sampling or effects. Validate repeat and random seeks, caption layout, chat-bubble stability, logo identity, and the final hold. Export only when requested, using `npx mografy export examples/mografy-intro --format mp4|webm|lottie|svga`.\n",
|
|
12
|
+
"references/layers.md": "# Layers\n\nA layer is one part of the film the user may want to retime, hide, copy, rename, lock or reorder in the timeline: a title, a card, a background, a subtitle. Declare the parts with `timeline(...)` from `@mografy/runtime`. The editor never edits scene code: it writes only its changes (the **edits**) to `scenes/timeline.json`, and the server compiles and trial-renders them like any other edit, so the player, review sheets and exports agree.\n\n## Declare from the beat table\n\nThe beat table stays the one source of time. Take each layer's `in` and `out` from `beats([...])`, never from separate numbers:\n\n```ts\nimport { beats, timeline } from '@mografy/runtime';\nimport edits from './timeline.json'; // create it as {}; the editor rewrites it\n\nexport const BEATS = beats([{ title: 'Open', end: 3 }, { title: 'Offer', end: 8 }, { title: 'Close', end: 12 }]);\nconst [open, offer, close] = BEATS.list;\nexport const TIMELINE = timeline([\n // top to bottom, as the timeline lists them\n { id: 'title', name: 'Title', in: open!.start + .4, out: offer!.end, enter: 'fade-up', exit: 'fade', subtitles: ['title'] },\n { id: 'card', name: 'Offer card', in: offer!.start, out: close!.end, enter: 'pop' },\n { id: 'logo', name: 'Logo', in: close!.start, out: close!.end, enter: 'blur-in' },\n { id: 'bg', name: 'Background', in: 0, out: BEATS.duration, still: true, locked: true },\n], edits);\nexport const meta = { /* width, height, duration, fps, background */ shots: BEATS.shots, layers: TIMELINE.meta };\n```\n\n- `id`: stable, `[\\w-]`, at most 64 characters. Once the project has edits, never rename an id: the user's changes to it would be orphaned.\n- `enter` / `exit`: `none`, `fade`, `fade-up`, `pop`, `blur-in`, `wipe` (see [motion-design.md](motion-design.md)). Each motion has a fixed length; lengthening a layer lengthens only its hold.\n- `locked: true` keeps the editor from moving it (a background, a camera bed). `hidden: true` starts it hidden.\n- `still: true` for a part that does not change with time while at rest (a background, a static panel): it is drawn once and its pixels are reused; its motions still apply.\n- `subtitles`: the `role: 'subtitle'` parameters the layer shows, so the subtitle list can jump to it.\n- `colour`: the layer's track colour in the editor (not the film).\n\n## Draw: pick one of three\n\n| Method | Use when | Editor's reorder applies |\n| --- | --- | --- |\n| `TIMELINE.draw(c, time, { title: (c, own, look) => …, … }, anchors)` | Each part can be drawn on its own; the usual choice | Yes |\n| `TIMELINE.drawFrame(ctx, time, { … }, anchors)` | The scene draws with the FrameContext (`ctx.draw`) | Yes |\n| `TIMELINE.each(c, 'title', time, (c, own, look) => …, anchor)` | Parts share a camera, a mask or one pass and must stay in the scene's own order | No |\n\n- The callbacks are keyed by the **base** id: a copy made in the editor has its own id but draws with its original's function.\n- `own` is the layer's own time: its declared window stretched onto where the editor put it, so a part keeps its internal timing when the user moves or retimes it. Animate inside a layer from `own`, not from film time.\n- `look` holds `opacity`, `y`, `scale`, `blur`, `reveal`, `local` and `progress`; the methods apply it for you (one `layer` so groups fade as one, `blurLayer` for blur, a clip for `wipe`). `anchors` (per base id) is where rise and scale happen; default the frame's centre.\n- `TIMELINE.time(id, t)` gives the own time for code outside the three methods; `TIMELINE.visible(t)` lists what is on screen.\n\n## Layering an existing film\n\n1. Name the parts the user would want to adjust; one layer each. Parts that cannot be separated stay one layer.\n2. Give each the window it is on screen, from the beat table.\n3. Wrap its existing drawing in `draw`, `drawFrame` or `each`, reading time from `own`.\n4. Verify the layered film is unchanged: with an empty `timeline.json`, compare frame hashes at 12 times spread over the film against the original (`npx mografy review` sheets side by side as a fallback). Every frame must match.\n\n## Films without layers\n\nA scene that declares no layers still gets editable layers: the build splits it into one layer per shot (from `meta.shots`, else the older `slides.shots` some `mografy.json` files still carry), and the editor can retime, reorder, copy and give each shot an enter and exit motion. Old projects get this without any change. When a multi-shot film has no `meta.shots`, add them from the beat table (`shots: BEATS.shots`) so the timeline shows its shots. Declare real layers when the user wants to adjust parts inside a shot.\n\n## Edits are the user's\n\n- Never write `timeline.json` by hand to animate. Change the declarations.\n- An edit wins over the declaration. When the user asks you to change a time they already dragged, the declaration alone will not show; say so, and tell them they can revert that layer in the editor.\n- Read `scenes/timeline.json` before changing a layered film, so you know what the user has adjusted.\n\n## Colours the user changed\n\nThe editor's **Design** tab (設計, in the right panel) shows the colours of the shot under the playhead and can swap any colour the film draws for another, without touching scene code. The swaps live in `mografy.json` as `\"colors\": { \"#12b5a5\": \"#e05d44\" }` (from → to, `#rrggbb`) and apply in the player, review sheets and every export. Alpha is kept, and gradients and shadows follow.\n\n- Read `colors` before changing a film's palette. A swap wins over the scene: when you change a colour the user already swapped, tell them, and leave the swap alone unless they ask you to fold it into the scene (then write the new value in the scene's tokens and delete that key).\n- Keep palette values as tokens in one place in the scene and in `style.md`, so each shot lists a short, clean palette.\n- The same tab edits `style.md` in place, and its **Open design system** page (設計系統) gathers the film's motions, colours, fonts and `timeline.json` in one view. Everything else the user decides about the look (motion, timing, type, rules) goes there, not into editor controls: read `style.md` again before every change, because the user may have edited it since your last turn, and apply new rules to the scene code.\n",
|
|
13
|
+
"references/mcp.md": "# The Mografy MCP tools\n\n`npx mografy mcp` runs a local MCP server over stdio, so an agent can make and check films through tool calls instead of a shell. Connect it once:\n\n```sh\nclaude mcp add mografy -- npx mografy mcp\ncodex mcp add mografy -- npx mografy mcp\n```\n\nEvery tool takes `project`: an absolute folder, or a folder name from `list_projects`; it defaults to `MOGRAFY_PROJECT` or the current folder. While the player has the project open, the tools work through the player, so the user sees each change there; otherwise the server opens the project itself and rebuilds it from disk before each call.\n\n## Tools and their commands\n\n| Tool | Command | Use it to |\n| --- | --- | --- |\n| `list_projects` | (the player's project list) | Find a project's folder; `include_builtin` adds the sixteen component projects |\n| `project_info` | (the player's inspector) | Read size, duration, shots, tempo, source files, params, settings and the last build error |\n| `create_project` | (the player's New project) | Start a project from the starter scene; `aspect_ratio: \"9:16\"` for a portrait film. Then write `style.md`, the scene, and check it |\n| `read_source` | (read the files) | Read the scene entry and every file of its current build |\n| `write_source` | (edit the files) | Replace scene files. They are compiled and trial-rendered first and written only if that passes; a failure returns the error and changes nothing |\n| `check` | `npx mografy check [--motion]` | Shot table, tempo, frame cost, `style.md`; `motion: true` adds the jump, hard start and hard stop scan |\n| `render_frame` | (none; `npx mografy review` writes sheets) | Look at one moment as a PNG; `kind: \"output\"` is the exported frame, `\"raw\"` the scene at exactly that time |\n| `review` | `npx mografy review` | Write the stop-frame and transition sheets to `renders/` and return them as images |\n| `open_player` | `npx mografy dev` | Show the project in the player, or switch the open player to it |\n| `export` | `npx mografy export` | Write a file to `renders/` (only when the user asks for one); `format`, `preset`, `codec`, `orientation`, `output` |\n| `read_guide` | (this Skill) | Read `SKILL.md` or a reference, when the Skill is not installed for the host |\n\n## How to work with them\n\n- Read the guide first: when the host has not installed this Skill, call `read_guide` (no topic) before writing a scene, then the references its table names.\n- Change scenes with `write_source` even when you also have file access, when you want the change checked before it lands. Send each file whole.\n- After every `write_source`, run `check` and fix its warnings; before delivery run `check` with `motion: true` and `review`, and look at every sheet it returns.\n- Never send `scenes/timeline.json` through `write_source`: it holds the user's edits from the editor (see [layers.md](layers.md)). `mografy.json` is settings, not source.\n- `export` blocks until the file is written and reports progress; cancelling the call cancels the export.\n",
|
|
14
|
+
"references/motion-design.md": "# Motion design decisions\n\nUse this when creating a Mografy animation or revising its visual concept, choreography, pacing, or transitions, in any host. A copy correction, asset swap, export, compression, or isolated timing fix needs only the relevant local check, not a new concept or storyboard. Preserve the user's chosen direction and requested scope. Continue authorized implementation without adding an approval gate.\n\n## Establish a visual idea before scene code\n\nWrite a compact direction in the existing `storyboards/storyboard.md` for a planned sequence, or in a short working note for a small animation. Reuse an existing plan rather than creating parallel briefs. Make these decisions concrete:\n\n- **Message and visual mechanism:** what should the viewer understand, and what visible change expresses it? For example, \"independent marks align into one readable signal\" defines an action; \"premium, smooth, dynamic\" does not.\n- **Graphic language:** describe the type hierarchy, shape proportions, palette roles, negative space, and framing at the actual aspect ratio. Use supplied artwork and the project's identity. Do not turn a real UI walkthrough into an abstract brand film or redraw a supplied logo to make a transition easier.\n- **Attention and rhythm:** name the focal subject and the moments of action, emphasis, and rest. Decide what stays still while the lead moves. Music can supply cues; a film does not need every element to move on every beat.\n- **Continuity:** identify what the viewer follows across a shot boundary: the same object, alignment, direction, contour, color field, or a deliberate contrasting cut. Specify its outgoing and incoming states.\n\nUse the nearest public [component](built-in-components.md) or [intro](intro.md), supplied reference, or existing project shot to answer a specific design question. Inspect its source and actual frames or playback when available. Note the useful relationship (such as a playhead causing a visible state change), then adapt it to this brief. A catalog of components is a technical vocabulary, not a shot list. Do not copy private project material into shared guidance.\n\nFor a new concept that needs shot planning, follow [storyboard.md](storyboard.md) (image generation in Codex, Artifacts or a local HTML board in Claude). Use those panels to choose composition and hierarchy; keep exact geometry, copy, and timing in the written plan. Generated imagery can suggest something the Canvas implementation never produces. Compare implemented frames with the intended key poses rather than treating the generated board as proof of quality.\n\n## Default taste\n\nWhen the project's `style.md` and the brief say nothing else, start from [taste.md](taste.md): hold times, type sizes, safe margins, still holds, one logo at the end and sustained sound, each with its reason. The project's own decisions always win.\n\n## Compose the key poses, then connect them\n\nFor each important action, define the before, decisive, and resolved compositions. Specify useful positions or proportions, the dominant scale, the supporting elements, and the held result. A paused key pose should communicate the intended message before decorative movement is added. Check it at the delivered viewing size, especially type and diagrams on a phone.\n\nTranslate the action into a causal phrase:\n\n> The leading bar travels to the shared baseline; the other marks align in its wake; their alignment opens space for the headline; the resolved line holds under the words.\n\nThis phrase determines order, overlap, and attention. Only then choose durations, paths, pivots, and curves. Write the choreography in scene modules as pure functions of absolute `time`; follow the existing runtime contract. Keep layout and motion data out of `mografy.json`.\n\n### Worked example: an eight-second \"Find your focus.\" bumper\n\nThis is an original teaching example, not a mandatory look, schedule, or component recipe. It needs only Canvas marks and typography. Use another mechanism when the brief calls for one.\n\nThe optional [scene source](../../../../extras/motion-design.ts) implements this example; inspect its [actual Chromium key poses](../../../../docs/motion-design/poses.png) alongside the code when using it as a reference. Resolve these files from the current checkout when available. These poses show the implemented Canvas scene, not an image-generated concept board. The example uses a generic system sans-serif; choose project fonts for production work.\n\n| Time | Composition and action | Design reason |\n| --- | --- | --- |\n| 0.0–1.8 | Three short strokes sit at different heights in the central half of the frame. A longer lead stroke moves toward a common baseline; the other strokes follow with small offsets. Resolve into a single horizontal line by 1.2 and hold it. | The graphic change expresses finding order. One lead attracts the eye; the followers share its cause. |\n| 1.8–4.6 | Keep that same line at the same position and thickness at the boundary. It lengthens to the measured headline width while \"Find your focus.\" is exposed directly above it. Settle by 2.8; hold the readable composition. | The existing object becomes typographic structure. The headline gets a distinct reveal and a quiet reading interval. |\n| 4.6–8.0 | Keep the headline stable. The line retracts toward its optical center, leaving a short accent; allow a restrained delayed settle in the accent, then hold the complete end composition. | The ending resolves the opening idea. The viewer gets closure without a second competing entrance. |\n\nA weaker version would fade out the strokes, slide in an unrelated title card, and bounce everything until the end. That loses the graphic relationship and the reading hold even if each tween is technically correct. Improve the relationship between states before adding more effects.\n\n## Choose motion by its job\n\n| Job | Decisions that matter | Failure to check in the render |\n| --- | --- | --- |\n| Reveal or emphasis | Choose what is discovered first: silhouette, word, number, relationship, or result. Use contrast, a mask, spatial change, or a cut when it serves that order. A simple fade is appropriate for a quiet reveal. | Every object fades/slides in with equal prominence, so nothing leads the eye. |\n| Explanation | A cause visibly changes its result: a cursor presses a control, a value changes a chart, an object assembles into a system. Preserve real product behavior. | A decorative cursor or chart animates independently of the event it supposedly explains. |\n| Typography | Measure and compose the complete text first. Animate words or glyphs only where their order or rhythm adds meaning; keep the reading pose stable. | Text keeps scaling or drifting during its reading hold; long words or CJK copy change wrapping mid-reveal. |\n| Transition | Hand over shared geometry: the outgoing shot's last object becomes the incoming shot's first (see [film-architecture.md](film-architecture.md)). Otherwise make a cut whose change in scale, direction, or meaning is intentional. Brief-specific hard cuts and fades remain valid. | Unrelated panels reset to the center and repeat the same entrance; a wipe conceals a jump instead of connecting the scenes. |\n| Weight or response | Choose the pivot, contact, acceleration, overshoot, and delayed secondary response for the material. Rigid type and logos usually need different treatment from soft characters. | Every object uses the same spring or sinusoidal bob regardless of weight, material, or story. |\n| Held result | Give the message a readable still interval; secondary movement should reinforce it. | Motion continues merely to avoid stillness and competes with the takeaway. |\n\nTreat the easing and text-duration estimates in scene authoring as starting heuristics. Judge actual spacing and reading at the requested pace; do not apply one curve, stagger interval, or shot duration mechanically to every action. If copy cannot be read in the requested duration, resolve that conflict explicitly rather than speeding up the whole film. Choose the relevant [animation principles](animation-principles.md) after deciding the action; listing their names is not a design rationale.\n\n## Review design separately from technical correctness\n\nRun the existing `npx mografy check` and `npx mografy review` workflow. Technical validity, deterministic seeking, loop equality, or successful encoding proves those properties only. Judge the actual rendered animation against the visual direction:\n\n| Criterion | Evidence to inspect |\n| --- | --- |\n| Hierarchy and composition | At the before, decisive, and held poses, the intended subject reads first; type, spacing, and contrast work at output size. |\n| Motion meaning | The viewer can follow the cause and result of the lead action without reading the implementation or an explanation of its intent. |\n| Continuity | Inspect the frame before, within, and after each boundary. The promised object or relationship survives the handoff, or the intended cut reads clearly. |\n| Rhythm | Inspect the whole sequence at normal speed when playback is available, then dense action/transition samples. Action, emphasis, and rest are distinguishable; the ending has time to resolve. |\n| Craft | Check measured text, pivots, paths, contacts, overlap, final poses, and unwanted drift. For characters, inspect contact and passing poses; for graphics, inspect alignment and optical balance. |\n\nRecord a concrete observation with a time or frame, its effect on the viewer, and the correction when a criterion fails. \"The headline and diagram start together at 2.0s, so neither leads; delay the supporting caption until the diagram resolves\" is useful. \"Looks premium; all twelve principles applied\" is not evidence. Fix the observed issue and review the affected sequence again.\n\nStills and transition strips show composition and sampled continuity; they do not by themselves establish the experience of continuous playback. If the available tools cannot inspect playback, say which frames and intervals were inspected and leave temporal quality unverified. Likewise, describe reference fidelity only after comparing the actual rendered output with the reference. Do not claim a visual-quality improvement from a successful build or a written plan alone.\n\n## Evaluate guidance changes on actual tasks\n\nWhen evaluating a Skill revision in either host, use the same brief, assets, dimensions, and time budget for the previous and revised guidance. Keep each run's source, plan, actual frames, playable output when available, and critique separate. Do not label the new version as the preferred answer for the reviewer. These focused briefs exercise different decisions:\n\n1. **Motion concept:** \"Create an eight-second 16:9 bumper for the fictional wordmark LUMA, using only typography and simple Canvas geometry. Communicate 'Many ideas. One direction.' End on the wordmark.\"\n2. **Explanatory causality:** \"Create a six-second 9:16 animation showing a task move from waiting to complete after a button press. Preserve the visible cause/result and let the result read at phone size.\"\n3. **Scope control:** \"In this existing animation, change only the last title and lengthen its final hold by half a second. Preserve its established composition and other timings.\"\n\nFor the first two, compare the five criteria above using actual frames and playback. Let a reviewer state which version communicates the brief more clearly and cite the moment that determined the choice; document ties or regressions. For the third, verify that the requested local edit did not trigger a redesign or an unnecessary storyboard/image-generation cycle. Keep prompt-following and technical checks separate from this visual judgment. A rubric or self-score alone does not establish an improvement, and a run in one host does not establish behavior in another or a general model ranking.\n",
|
|
15
|
+
"references/music.md": "# Contextual music\n\n[score.py](__REPOSITORY__/extras/music/score.py) generates a film's score from its context. Instead of finding a track and cutting the animation to it, the agent describes what each part of the film needs in a cue file, `music.json`, and the generator synthesises music that follows it: sections with a mood and an energy level, and hits on the exact seconds where something happens on screen. When the animation's timing changes, update the cues and generate again; the music stays in sync. [music-example.json](__REPOSITORY__/extras/music/music-example.json) scores the twelve-second intro.\n\n## When to use it\n\nUse it when the user wants music and has none, or asks for music that fits the film: product intros, logo stings, explainers, and abstract or particle pieces where atmosphere, rhythm and hits matter more than a memorable melody. If the user supplies a track, use theirs and align the scene to `ctx.beat(time)` instead. For a song with vocals or a strong hook, write the same cues as a text brief for an external music tool or library search, and use the generator only as a placeholder.\n\n## Add to a project\n\nThe generator is an optional extra, not part of the installed template. It needs Python 3 with numpy; MP3 output uses ffmpeg, and the timeline image uses Pillow. If the project already has `music-src/score.py`, reuse it. Otherwise copy it from the current Mografy checkout (`extras/music/`) or download it:\n\n```sh\nnpx mografy add music projects/<name>\n```\n\n`npx mografy add` copies from this checkout's `extras/` folder, or from GitHub when it is missing, keeps any project file that differs from the extra (`--force` replaces it), and prints the import line. It copies `music-src/score.py` and, when the project has none, an example `music-src/music.json` to rewrite for this film. Without the `mografy` command, download the same files from `https://raw.githubusercontent.com/mografy/mografy/main/extras/music/`.\n\n`music-src/` is outside `scenes/` and `assets/`: the scene never imports it, and only the generated audio file goes in `assets/`.\n\n## Default taste\n\nUnless the project's `style.md` or the user says otherwise:\n\n- Prefer sustained, flowing music (`rhythm: \"flowing\"`): long pads, warm piano, one long bass note per bar. Avoid busy, fragmented patterns.\n- Avoid sharp, high, piercing sounds: no `sparkle`, `ticks` or `pop` hits, and no bell leads. Mark events with soft `whoosh`, `sweep`, `gather` and low `impact` hits instead.\n- Use few hits, on the moments that change the story, and let the score breathe under reading holds.\n\n## Workflow\n\n1. **Storyboard first.** Write the cues after the shot plan (or after reading an existing scene), so every time comes from the actual animation. For a finished scene, read its source for the real transition and event times rather than the storyboard's approximations.\n2. **Write `music-src/music.json`.** One section per shot or phase; choose its mood and energy from the shot's purpose. Add one hit for every on-screen event the audience should hear, at the scene's exact second, with a `note` naming the event. Put the main changes on bar starts where the scene allows it.\n3. **Generate:** `python3 music-src/score.py music-src/music.json assets/music.mp3 --timeline storyboards/music-timeline.png`. The output is deterministic for the same cues and seed.\n4. **Connect it** in `mografy.json` so the player, `ctx.beat(time)` and exports use it. Copy `bpm`, `offset` and `beatsPerBar` from the cues:\n\n```json\n\"audio\": { \"path\": \"assets/music.mp3\", \"bpm\": 120, \"offset\": 0, \"beatsPerBar\": 4, \"gain\": 1 }\n```\n\n5. **Check the timeline image.** Each section is a block whose colour is its mood and height its energy; white lines are hits; the waveform is underneath. Confirm that swells and impacts land on the hit lines and that the loudest passages match the film's climax. You cannot hear the result: say so, and ask the user to listen with the animation in the player.\n6. **Iterate from the cues, never the audio file.** When the user says it is too busy, too dark or too loud, or when the scene's timing changes, edit `music.json` and regenerate. Keep the previous audio file under a new name if the user may want to compare.\n\n## Cue file\n\n| Field | Meaning |\n| --- | --- |\n| `duration`, `bpm`, `beatsPerBar`, `offset` | Length and beat grid; keep them equal to the scene duration and `mografy.json` audio settings. |\n| `key`, `mode` | `C` … `B`; `major` or `minor`. One chord per bar. |\n| `mood` | Default mood for sections that do not set one. |\n| `rhythm` | `pulse` (default): beat pulses and eighth or sixteenth arpeggios. `flowing`: half and quarter notes, one long bass note per bar, soft bells for ticks. Prefer `flowing` for calm, cinematic or particle pieces, and when the user finds the music busy or choppy. |\n| `texture` | `particles` adds a shimmer of tiny grains on the chord tones, denser with energy. A section can set its own. |\n| `seed` | Fixes the random choices. |\n| `sections[]` | `name`, `start`, `end`, `mood`, `energy`, `texture?`, `note`. |\n| `hits[]` | `at`, `kind`, `strength?` (1 is normal), kind-specific fields, `note`. |\n\n**Energy** is 0–1, or `[from, to]` for a ramp across the section. Below 0.3 there is only a pad and a sparse motif; from 0.3 bass and a quarter-note pattern enter; from 0.5 eighths (quarters in `flowing`); from 0.75 sixteenths in `pulse`.\n\n**Moods:** `calm`, `warm`, `hopeful`, `playful`, `tech`, `tense` (minor harmony), `cosmic`, `epic`. Each sets the lead instrument (felt piano, pluck or bell), register, pad brightness and reverb.\n\n| Hit | Use for | Fields |\n| --- | --- | --- |\n| `pop` | Something appears | |\n| `burst` | A burst or big transition; includes a riser | `build` (seconds, default 1.5) |\n| `impact` | A collision or collapse | `build` (default 0) |\n| `gather` | Scattered elements converge on `at` | `length` |\n| `swirl` | Elements stream round or morph | `length` |\n| `sweep` | A light or wipe crosses the frame | `length` |\n| `whoosh` | A camera move or cut | `length` |\n| `fall` | Something drops | |\n| `sparkle` | Highlights, small reveals | `count`, `every` |\n| `ticks` | Typing, letters landing one by one | `count`, `every` |\n| `resolve` | The final chord; only its ring-out follows | |\n\nThe rhythm drops out for half a second before each `burst` and `impact`, so they land with more weight. Use few hits: one per event the audience should notice, not one per moving element.\n",
|
|
16
|
+
"references/output.md": "# Output: aspect ratio, portrait films and export\n\nRead this when the brief names an aspect ratio, a social platform, a portrait (9:16) video, or an export size or format.\n\n## Landscape and portrait compositions\n\nRead `mografy.json.aspectRatio` before planning or editing. It is `\"16:9\"` (landscape) or `\"9:16\"` (portrait); when absent, use the scene's `meta.width / meta.height`. This is canvas configuration only. The main player has no orientation switch: it previews the authored scene at its configured dimensions. Output orientation is chosen only in the Export dialog and never changes the project or the main preview.\n\nWhen the user requests a future 9:16 video, explicitly record **9:16 portrait** in the brief before authoring. Treat this as the intended composition, not merely an export setting. Create the scene natively in portrait, tell the user that the preview follows the authored scene, and do not rely on fitting or cropping a landscape scene to satisfy a portrait brief. For a native social video, author `meta = { width: 1080, height: 1920, ... }` and set `aspectRatio: \"9:16\"` in the project. A landscape scene normally uses 1920 × 1080. The shared Runtime applies the saved aspect ratio to the logical canvas before setup and rendering, preserving the scene's short edge; both `SetupContext` and `FrameContext` receive the effective dimensions. Use `ctx.width` and `ctx.height`, never imported meta dimensions, for layout, backgrounds, clipping, and camera bounds. Branch with `const portrait = ctx.height > ctx.width` when the compositions differ. Stack portrait elements vertically, wrap copy to available width, and reposition the focal subject and subtitles. Do not rotate, stretch, or merely shrink a complete landscape shot into the portrait canvas. Fixed-coordinate scenes need a scene-code layout pass; an orientation toggle cannot infer their intended design.\n\nFor portrait social layouts, use conservative guides: leave about 8% above, 18% below, 6% on the left, and 12% on the right clear of critical copy and logos. Platform overlays vary; treat these as planning margins, not platform guarantees. Inspect at phone size, including long subtitles, entrances, exits, and transitions. If both outputs are requested, review both complete compositions and random seeks.\n\nMP4, WebM and MOV exports have landscape 1280 × 720 / 1920 × 1080 and portrait 720 × 1280 / 1080 × 1920 presets, selected with orientation icons. If output orientation differs from the authored scene, show Fit: `contain` (Fit entire scene, the default) or `cover` (Fill and crop). These fit the existing artwork without reauthoring the canvas. The dialog shows an actual paused-frame preview of the output. Choose `reflow` (Adapt layout) for deliberately responsive scenes, including all sixteen built-in components: it passes the output canvas dimensions to scene code so portrait sizes, card arrangements, and text wrapping adapt. It is not a player orientation control. Export overrides do not change the saved canvas. CLI: `npx mografy export [project] --format mp4 --orientation portrait --resolution 1080p` (or `landscape`); without overrides it uses the saved canvas and render scale. WebM uses VP9 video and optional Opus audio, with constant quality (CRF 32) by default; MP4 uses 10-bit H.265 (HEVC, tagged `hvc1`) with 48 kHz AAC by default, about half the size of H.264 at the same look. `--preset share`, Encoder → Share in the Export dialog, `--codec h264` or `render.codec: \"h264\"` in `mografy.json` gives H.264 for a website `<video>`, Firefox or Windows PCs without HEVC support; ask which when the file is going somewhere other than QuickTime, a phone or a social upload. MP4 `crf` and `bitrate` are on the H.264 scale for both codecs. Use `--format webm` for WebM. Higher WebM CRF values produce smaller files with less detail. MP4 and VP9 CRF values are codec-specific. Both video formats support the same orientation, resolution, sampling, and output effects. Player, stills, thumbnails, review, and exports share the effective canvas and output effects.\n\n## Export\n\nExport with `npx mografy export [project] --format mp4|webm|mov|lottie|svga`, or `--preset share|high|fast|master`: `share` is H.264 for any player, `high` (the default) H.265 10-bit, `fast` the hardware H.265 encoder (VideoToolbox, NVENC, Quick Sync, AMF; software fallback), `master` ProRes 422 HQ in a MOV for editing. Ask which when the destination is unclear: a website, Firefox or an unknown Windows PC needs `share`. The command prints capture and encoding or packaging progress and writes the finished file under `renders/`. Press Ctrl+C to cancel a CLI export. When `npx mografy dev` is running, player exports also print progress in that terminal and can be stopped with `npx mografy export [project] --cancel`. Batch export: `npx mografy export <project> <project>...` or `npx mografy export --all [folder]` (default: the projects folder; `_`-prefixed folders skipped) exports each in turn with the same options, skips past failures and prints a summary; in the player, **Batch** next to **Export** opens the same as a dialog (format, encoder, resolution Own/720p/1080p by shorter side, frame rate, Use less memory). Export only when the user asks for a file.\n",
|
|
17
|
+
"references/performance.md": "# Performance: cheap frames and smooth motion\n\n\"It stutters\" (卡, 卡卡的, 不順) means one of two different problems. Find out which before changing anything:\n\n| Problem | What you see | How to find it | Fix with |\n| --- | --- | --- | --- |\n| **Slow frames** | The preview drops frames; the same film exported to MP4 plays smoothly | `npx mografy check`: frame cost, filters per frame, canvases per frame | The cost tables below |\n| **Choppy motion** | The exported MP4 also looks rough: something jumps, starts at full speed or stops dead | `npx mografy check --motion`: jumps, hard starts and hard stops with their times | **Smooth motion** below, [film-architecture.md](film-architecture.md) and [taste.md](taste.md) |\n\nMost stutter reports on finished films turn out to be choppy motion, not slow frames. Run both checks before delivery.\n\n## Checklist\n\nSlow frames:\n\n- [ ] `npx mografy check` shows no frame-cost warning: median well under 33 ms at 1920 × 1080 on a desktop, nothing over 100 ms, at most 8 filters per frame, no canvases created per frame.\n- [ ] No `ctx.filter` around a group of draws; groups go through `blurLayer`, type through `blurText` / `blurWords`, light through `bloom`.\n- [ ] Every `layer`, `blurLayer` and `bloom` smaller than about half the frame has `bounds`.\n- [ ] Everything that does not change is made once in `setup`: paths, text layout, UI card textures (cached per visual state), sprites, backgrounds, noise tiles.\n- [ ] No `getImageData` per frame; grain is a small tile drawn as a pattern, not a pixel loop.\n- [ ] One Three.js stage at most, skipped while hidden.\n\nChoppy motion:\n\n- [ ] `npx mografy check --motion` reports no jump, hard start or hard stop you did not intend.\n- [ ] Each followed object is one track across a handoff: where one shot's version ends, the next one's starts, at the same position, size and colour.\n- [ ] Moves through several poses are one `keys` curve, not separately eased segments.\n- [ ] Entrances use `springs.*` / `spring()` over their whole duration; no entrance moves on its first frame more than on its second.\n- [ ] Fades end at 0, never at a small alpha that then disappears; base colours switch before a wipe finishes covering them.\n- [ ] The camera does not reverse direction every second or two, and holds still during clicks and reading.\n- [ ] A move across more than half the frame takes at least 0.6 s, an exit at least 0.4 s ([taste.md](taste.md)).\n\n## What costs what on a 2D canvas\n\n| Operation | Cost | Use instead |\n| --- | --- | --- |\n| `ctx.canvas.filter = 'blur(…)'` around several draws | One blur pass per fill, stroke and glyph run, each over a large area. Dozens per frame takes seconds. | `blurLayer(c, name, radius, draw)`: draw once into a layer, blur the layer once. |\n| A filter blur per word or glyph | One pass per word | `blurText` / `blurWords`: the glyph's own shadow, about the cost of sharp text. |\n| `shadowBlur` on many shapes | One mask blur each; cheap for a few, costly for hundreds | `surface()` for cards; one shadow on a merged path; or a blurred layer of the silhouettes. |\n| Large-radius blur at full resolution | Grows with radius and area | Blur at half or quarter resolution (`blurLayer` does this automatically above 12 and 48 device pixels; `bloom` works at quarter resolution). |\n| A full-frame layer for a small object | A full 1920 × 1080 (or 4K) composite | Pass `bounds: [x, y, w, h]` to `layer`, `blurLayer` and `bloom`. |\n| `new OffscreenCanvas` / `document.createElement('canvas')` in `renderFrame` | Allocation and garbage collection every frame (33 MB per 4K canvas) | `buffer(name, w, h)` and the layer helpers reuse pooled memory. |\n| `getImageData` / `putImageData` per frame | A GPU → CPU copy and a full-frame loop | Precompute in `setup`; use compositing modes instead of pixel loops. |\n| `new Path2D(svgString)`, parsing, `measureText` of fixed copy each frame | Repeated parsing and layout | Build paths, glyph widths and layouts once in `setup` (or as module constants) and read them per frame. |\n| Thousands of separate `fill()` calls | Per-call overhead | Batch shapes of one style into one path; draw particles as a pre-rendered sprite with `drawImage`. |\n| A Three.js stage | A WebGL render plus a GPU → CPU copy into the 2D frame on CPU canvases | One stage per film; skip `stage()` while the 3D layer is invisible; keep its size to the area it covers. |\n| Re-drawing a static UI card (rows, icons, text) every frame | Dozens of fills and glyph runs per card per frame | Draw each card state once into a cached texture and `drawImage` it; a flat card is one draw. |\n| Per-pixel grain or noise each frame | A full-frame loop | A small noise tile as a pattern, offset by `Math.round(time * 30)`, at low alpha. |\n| `imageSmoothingQuality = 'high'` when scaling a soft buffer up | High-quality resampling of the whole frame | `'low'` for blurred or glow buffers (the layer helpers already do this). |\n\n## Opening and switching speed\n\nFrame cost decides playback; `setup` and the project's files decide how long a project takes to open. The player shows a project as soon as its scene module is read (its trial render runs in the background a few seconds later, and its result is kept in `.mografy/verified.json`, so an unchanged scene reopens without one). It keeps the last two projects loaded, so switching back to one is immediate; what remains is each project's first setup:\n\n| Cost on open | Fix |\n| --- | --- |\n| Every font in `mografy.json` is fetched and parsed. The CJK subsets are about 4–5 MB each. | `python3 extras/cjk/subset-film-fonts.py <project>` keeps only the characters the film draws (about 9.5 MB → 300 KB) and points `mografy.json` at the result. Run it again after every copy change; it always rebuilds from the original fonts. |\n| Procedural textures (paper, wood, noise) drawn pixel by pixel in `setup` | Draw each once and keep it: store the canvas as a PNG in Cache Storage under a key that includes a version number, decode it on later opens, and draw it again when the cache is empty (exports and checks start with none, so frames stay identical). Bump the version when the generator changes. |\n| `getImageData` on a canvas you just drew, to add noise | It waits for the GPU and copies the canvas back. Fill a `new ImageData(w, h)` yourself and `putImageData` it, or draw the noise with shapes. |\n| A 3D stage: shader compilation and texture uploads | See **Cost** in [three-d.md](three-d.md): keep the light count constant, `compileAsync` in setup, share textures. |\n\n## Coordinates and units\n\nThe runtime gives scenes a logical context (`ctx.canvas`, `ctx.withCanvas`) whose units are film pixels: it scales transforms, `shadowBlur`, shadow offsets and filter lengths by the output scale for you. Two things it cannot do:\n\n- **Offscreen contexts are native.** Lengths you set on your own offscreen context (`filter`, `shadowBlur`, `lineWidth` after `setTransform`) are device pixels. Multiply by `devScale(c)` of the context you are copying from, or use the layer helpers, which size and scale for you.\n- **Filters and shadows ignore the transform.** A blur set inside a camera zoom of 2 is not doubled. `blurLayer`, `blurText` and `bloom` take their radius in the current units and include the camera; when you set a filter yourself, multiply by `devScale(c)`.\n\nSize every offscreen buffer from the film frame (1920 × 1080 logical × output scale), never from `c.canvas.width`: the player may hand a canvas whose size differs from the frame's transform, and a buffer sized from it clips the picture to a square or a corner. `layer`, `blurLayer`, `bloom` and `buffer` all work in film coordinates; `outputScale(c)` and `devScale(c)` give the factors when you need them.\n\nInside a `layer`, `blurLayer` or `bloom` callback, draw with the context the callback receives. `blurWords`, `riseWords`, `text` and `surface` accept it as their first argument.\n\n## Smooth motion\n\n`npx mografy check --motion` draws the whole film at 30 frames per second at quarter size and compares each frame with the next. It reports:\n\n| Report | What it usually is | Fix |\n| --- | --- | --- |\n| **Jump**: one frame changes far more than the frames around it | Two tracks that do not meet at a handoff (a dot that ends at one place while the ring starts at another); a colour or element that switches in one frame; a hard cut | Make the followed object one track; animate the switch; keep a cut only when it is a deliberate break (a new act, a drop in the music) |\n| **Hard start**: motion leaves a still frame at full speed | An entrance with no ease-in; an element that appears already moving; a spring whose first frame jumps | `springs.out` / `spring()`; start the move from rest; let a camera move begin up to 0.5 s before the action |\n| **Hard stop**: motion halts at full speed | Separately eased segments chained together; a fade that stops at 0.1 and then vanishes; a spring cut off before it settles; content removed while it is still moving | One `keys` curve through the poses; fade to 0; let springs finish; overlap exits with the next entrance |\n\nEach line lists times: render those frames (`review.times`, or `review.transitions` around them) and look before changing anything. The detector cannot tell a deliberate cut from a mistake, so a cut it reports can stay. It measures change on screen, so a slow move of a large bright shape and a fast move of a small one can read the same; trust the frames, not the number.\n\nOther causes of choppy motion it cannot see: a spring that settles in a third of its duration (the object shoots off, then sits; use the runtime springs), a camera that reverses its zoom every 1.5 s, a ring or caret that hops from letter to letter instead of gliding on a continuous position.\n\n## Canvas gotchas\n\n- `ctx.filter` blur lengths are in destination (device) pixels: scale them by the transform you draw with, not by the buffer's own scale.\n- An opaque full-size `fillRect` on a pooled `OffscreenCanvas` can be dropped by Chromium; cap such a fill's alpha at 0.996.\n- When a wipe or flood changes the base colour, switch the colour slightly before the wipe reaches 1, or one frame flashes the old colour.\n\n## Measuring\n\n1. Run `npx mografy check [project]`. It prints `Frame cost at W×H (CPU canvas, N frames): median … ms, slowest … ms at …s` and the warnings. Add `--motion` to scan the motion as well; it draws every frame at quarter size (about 15 s for a 60 s film on a cloud CPU).\n2. For the slowest times, find the cause by switching parts off: comment out a layer, a blur or a particle system and check again. The cost is almost always one of the rows above.\n3. When the preview is slow but `npx mografy check` is fine, check the player: `MOGRAFY_HMR=0 npx mografy dev` serves the production build of the player instead of the development one.\n\nFrame cost in the cloud or in CI is several times higher than on a desktop GPU; compare numbers from the same machine, and look at the ratio between frames rather than the absolute value.\n",
|
|
18
|
+
"references/product-walkthrough.md": "# Product walkthroughs: redraw the app, film the action\n\n[walkthrough.ts](__REPOSITORY__/extras/walkthrough/walkthrough.ts) turns a product's screens into a film. Claude or Codex look at screenshots of each step that the user provides, redraw the real UI as large, simplified cards, and film only the action on each card. Every card grows out of the control that was just used, one film camera frames the whole piece while each card pushes in on its own control with a local zoom, and a big cursor (or a finger tap) does the clicking. [walkthrough-demo.ts](__REPOSITORY__/extras/walkthrough/walkthrough-demo.ts) is a twelve-second tour: a fictional quoting app goes from an empty list to an AI-drafted quote to a shared link in four cards.\n\n## When to use it\n\nUse it for any film made from a web or mobile app's screens (for step-by-step tutorial clips, one per step, also read [how-to-film.md](how-to-film.md)): product demos, feature explainers and tutorials, onboarding and help clips, what's-new shorts, mobile app previews, social cut-downs and landing-page loops. Typical requests: \"turn these screenshots into a walkthrough\", \"redraw the UI simpler and only film the interactions\" (重繪、介面簡化、只拍操作細節).\n\nFor a short loop of one to three actions (a landing-page hero, a feature card, a phone moment), use the Stage extra in [ui-stage.md](ui-stage.md) instead: a script over state, windows cropped by the frame, placeholder lines and a seamless loop.\n\nUse plates from `cinema.ts` ([camera-transitions.md](camera-transitions.md)) when the footage itself should stay a screen recording, and `three.ts` ([three-d.md](three-d.md)) when a device model must turn in 3D.\n\n## Add to a project\n\nThe helper is an optional extra, not part of the installed template. If the project already has `scenes/walkthrough.ts`, read and reuse it. Otherwise copy it from the current Mografy checkout (`extras/walkthrough/`) or download it:\n\n```sh\nnpx mografy add walkthrough projects/<name>\n```\n\n`npx mografy add` copies from this checkout's `extras/` folder, or from GitHub when it is missing, keeps any project file that differs from the extra (`--force` replaces it), and prints the import line. Without the `mografy` command, download the same files from `https://raw.githubusercontent.com/mografy/mografy/main/extras/walkthrough/`.\n\nImport it locally (`import { createKit, camAt, withCamera as withCardZoom, cursorAt } from './walkthrough.js'`), and take `springs`, `cameraPath`, `withCamera`, `beats` and `blurText` from `@mografy/runtime`. The extra's `withCamera` is a card-local zoom, so rename it on import to keep it apart from the runtime's film camera. Copy `walkthrough-demo.ts` too when you want a working starting point; it shows every helper in context. For Chinese or Japanese UI copy, add the CJK fonts from [cjk-typography.md](cjk-typography.md) and put `\"Noto Sans TC\"` (or the project's CJK family) in the theme's `font` stack.\n\n## Choose the scenario first\n\nThe same kit serves every scenario; length, pacing, captions and the pointer change.\n\n| Scenario | Length and format | Shots | Pointer | Text on screen | Pace and sound |\n| --- | --- | --- | --- | --- | --- |\n| Product demo | 20–45 s, 16:9 | Brand title, 4–6 detail shots of the main flow, one result, logo end card | Big cursor | Little: the product's own copy is the text; title at the start, tagline and URL at the end | Calm; clicks on bar lines when there is music |\n| Feature explainer or tutorial | 45–90 s, 16:9 | One shot per step, 4–8 s each, every result held long enough to read | Cursor with slower moves (up to 1.1 s) | Big step titles beside or above the card (\"1 Describe the job\") | Calm; music optional and low |\n| What's new / single feature | 8–15 s, 16:9 or 1:1 | Before → the one action → result, two or three shots | Cursor | One headline plus a \"New\" chip | One musical hit on the result |\n| Mobile app preview | 15–30 s, 9:16 (1080 × 1920) or a phone inside 16:9 | Full-bleed screens or a phone frame (`kit.phone`), one gesture per shot | Taps (`tap`), no cursor | Short captions in the top third, inside social safe margins | Brisk; light score |\n| Social cut-down | 6–15 s, 9:16 or 1:1 | Show the result in the first second, then the one or two actions that cause it, then the logo | Cursor or taps | Large burned-in captions, since most viewers watch muted | Fast in, hold the payoff |\n| Loop for a landing page or docs | 4–10 s, any size | One action that resets: the last frame equals the first | Optional | None | No music; loop on a hold; export a small MP4 or WebM |\n\nWhen the brief is unclear, ask which scenario it is and for how long; otherwise infer it from the request and say which one you chose.\n\n## Workflow\n\n1. **Collect the screens.** Agree on the steps that tell the story (usually 3–6) and ask the user for a screenshot of every state, with the exact labels and values where they are hard to read; when the user asks you to operate the product yourself and gives a test account, capture the states as in [how-to-film.md](how-to-film.md) instead. Keep them in `capture/` (numbered PNGs plus a `steps.json` with labels and values). Read the UI tokens from the screenshots or ask for them (primary colour, ink, borders, radius, fonts), and ask for the logo as SVG. Do not operate the user's site or account unless they asked you to and gave you a test account.\n2. **Choose the fidelity.** A *faithful rebuild* draws the whole app as it looks and films it with a camera; use it when viewers must recognise the real screens. A *simplified redraw* is the default when the user asks to redraw, simplify, or film only the interactions. Both use the real product: its layout logic, labels, colours and the order of states. Never invent features or screens.\n3. **Inventory each screenshot.** For every step write three lists: the *target* (the control the action touches: a field, button, row, dialog), the *context* needed to understand it (the card title, one neighbouring row), and *everything else* (navigation, filters, footers, badges, extra columns, tooltips).\n4. **Redraw.** Keep the brand tokens, the logo, the real labels and values of the target, its proportions and its state sequence (empty → focus → typing → loading → result → success). Drop everything else, collapse lists to 3–4 rows and tables to the columns the story needs, and turn copy the action does not need into `skeleton` bars. Raise type to about 1.3–1.6× the app's size so it reads at 1080p, keep at least 48 px of padding inside a card, and use one card style throughout ([taste.md](taste.md)). Build every step from the same kit parts so the film stays consistent.\n5. **Approve before animating.** Render one still per step (from a storyboard page or `npx mografy review`) and put it beside its screenshot in a sheet: screenshot | redraw. Show it to the user and adjust what to keep or drop before the motion work.\n6. **Film one action per shot.** Show the action, not just its arrival: the caret typing, the button squashing, rows sliding in, numbers counting up, a check mark drawing, a status chip changing colour. Hold each result 0.6–1.0 s before the next move.\n7. **Hand off between shots.** The control that finished the step grows into the next card (`kit.grow`): a button into a dialog, the send button into the sent message, a picked row into the field it fills, a copied link into the phone that opens it. Avoid plain cuts and cross-dissolves of text over UI.\n8. **One film camera, a local zoom per card.** Lay the cards out in one world and move one `cameraPath` across it ([film-architecture.md](film-architecture.md)); it carries the hand-offs from card to card. Inside each card's own transform, give the card a local zoom from its own `camAt` keys: hold, push in on the control about to be used (zoom 1.3–1.9), click, then pull back as the next card arrives. The cursor keys use functions of time so the pointer stays on its target while either moves.\n9. **Opener and ending.** Open on the brand (icon, title) and let its logo match-cut into the logo on the first card. End on the logo, the tagline and the public URL. Ask the user for the official tagline and URL.\n10. **Music and timing.** Follow [music.md](music.md) when the film needs a score, and put the clicks on bar lines. To change the length without rushing actions, borrow time from holds.\n11. **Verify.** `npx mografy check`, then `npx mografy review` with a transition strip over every hand-off. Look for overlapping cards, a push-in that crops the control, blank frames during a camera move, text too small at 1080p, and a cursor that drifts off its target. Show the user a preview with music before the final export.\n\n## API\n\n| Helper | Use |\n| --- | --- |\n| `createKit(theme)` | Drawing helpers bound to a theme (`primary`, `primaryDark`, `primarySoft`, `ink`, `mute`, `faint`, `line`, `surface`, `card`, `skeleton`, `shadow`, `font`, `mono`, `radius`). Returns `card`, `skeleton`, `chip`, `button`, `field`, `text`, `wrap`, `reveal`, `blurText`, `icon`, `check`, `ring`, `toast`, `grow`, `phone` and primitives (`box`, `hair`, `line`, `dot`, `rr`, `measure`, `mix`). |\n| `kit.card(c, rect)` | A floating card: wide soft shadow, contact shadow, hairline. Shadows scale with the current transform. |\n| `kit.grow(c, from, to, k, { outgoing, incoming, fromColor, toColor, fromRadius, toRadius })` | Container transform between two screen-space rects. Drive `k` with `springs.pop`. |\n| `kit.button(c, rect, label, { kind, hover, time, pressAt, icon })` | Squashes and rings on `pressAt`; `hover` tints it before the click. |\n| `kit.field(c, rect, { value, placeholder, size, lines, focus, caret, mono })` | An input with wrapping, focus ring and caret; feed `typed(text, p)` for typing. |\n| `kit.reveal(c, s, x, y, size, time, start, span)` | Per-character blur-in for titles and replies (no `c.filter`). For words and lines outside the kit, use the runtime's `blurText` and `blurWords`. |\n| `kit.toast`, `kit.check`, `kit.chip`, `kit.skeleton`, `kit.icon` | Notices, a check that draws itself, status pills, stand-in bars, line icons. |\n| `kit.phone(c, screenRect, draw)` | A phone body; `draw` paints the screen in its own coordinates. |\n| `camAt(keys, time)`, `withCamera(c, view, cam, draw)` | A card's local zoom from `[time, x, y, zoom]` keys, interpolated by `zoomPath` (a pure scale about a fixed point) with `springs.camera`. Import it as `withCardZoom`; the film camera is the runtime's `cameraPath` and `withCamera`. |\n| `toScreen`, `rectToScreen`, `scaleRect` | Map layout points and rects through a camera, for hand-offs and cursor targets. |\n| `cursorAt(keys, time)`, `drawCursor`, `clickRing`, `tap` | The big cursor (keys may be functions of time), click rings, and finger taps for phone scenes. |\n| `springs`, `spring(stiffness, damping)`, `sineInOut`, `press`, `typed`, `countUp`, `blink`, `visible` | Motion values: `springs.out` entrances, `springs.pop` cards and buttons (about 1.5 % overshoot), `springs.camera`, `springs.cursor`. |\n| `fluid(c, view, time, colors)`, `flood(c, view, r)` | Brand-colour atmosphere behind the cards, and a soft disc to flood it in or out. |\n\n## Motion that feels calm and expensive\n\n- Springs everywhere, never linear: critically damped for entrances and cameras, a touch of overshoot only for cards and buttons. Keep sine in-out for slow drifts.\n- Zoom as a pure scale about one point (`zoomPath`), so the picture never swings sideways while it scales.\n- Start camera moves a little before the cursor arrives; never move the camera during a click.\n- Give the cursor up to 1.1 s per move on a gentle arc; hold it on the control for the click.\n- Hold titles and results for the times in [taste.md](taste.md), and borrow time from static holds rather than speeding up actions: a first cut usually reads as too fast, because the viewer sees the screen for the first time while you already know it.\n\n## Pitfalls\n\n- Hand-off rects are in world space under the film camera, and in screen space only inside a card's local zoom: evaluate the outgoing card's zoom at the click time and the incoming card's zoom at the current time.\n- Push-ins belong to the card (its local zoom), not to the film camera; a film camera that zooms into one card crops the next one when they overlap during a hand-off.\n- Fade a card with its content through one `layer`, so its rows and shadow do not flash where they overlap.\n- Do not use `c.filter` for blur in a scene; use `kit.blurText`, the runtime's `blurText` / `blurLayer`, and the card shadows. The only scratch canvas is `fluid`'s, created once and redrawn every frame; see [performance.md](performance.md).\n- Use invented share tokens and demo customers; never show a real customer's data or a working private link.\n- When the copy changes, re-subset the CJK fonts so every new character is covered.\n- For portrait, lay out in 1080 × 1920 with `Viewport` set to the scene size; cards about 960 px wide, captions in the top third.\n",
|
|
19
|
+
"references/scene-authoring.md": "# Mografy scene authoring guide\n\nThis folder is a Mografy project. Animation content lives only in scene modules (normally `scenes/main.ts`). `mografy.json` stores project settings; never put layers, keyframes, or animation data in it.\n\nRun `npx mografy dev` to open the player. After a file change passes compilation and a real Chromium trial render, the player switches to the new version and stays at the same time.\n\n## File format\n\nA scene module exports `meta`, `params`, optional `setup`, and synchronous `renderFrame`:\n\n```ts\nimport { lerp, at, springs } from '@mografy/runtime';\nimport type { FrameContext, SetupContext } from '@mografy/runtime';\n\nexport const meta = { width: 1920, height: 1080, duration: 8, fps: 30, background: '#0f1115' };\n\nexport const params = {\n subtitle: { name: 'Subtitle', type: 'string' as const, role: 'subtitle' as const, default: 'Hello' },\n accent: { name: 'Accent', type: 'color' as const, default: '#12b5a5' },\n energy: { name: 'Energy', type: 'number' as const, default: 1, min: 0, max: 2, step: 0.01 },\n layout: { name: 'Layout', type: 'enum' as const, default: 'center', options: ['center', 'left'] },\n};\n\nexport async function setup(ctx: SetupContext) { /* load images or prepare seeded data once */ }\n\nexport function renderFrame(ctx: FrameContext, time: number, p: any) {\n const mografy = ctx.draw;\n mografy.fill(p.accent);\n mografy.circle(ctx.width / 2, ctx.height / 2, lerp(20, 160, at(time, 0.2, 1.2, springs.out)));\n}\n```\n\nThis is the shape of a single shot. A film with several shots or a moving camera is one world drawn through one camera from one shot table: read [film-architecture.md](film-architecture.md) and start from the `film-starter` showcase film (`npx mografy add film-starter <folder>` downloads it).\n\n## Aspect ratio\n\nRead `mografy.json.aspectRatio` (`\"16:9\"` or `\"9:16\"`) before planning or editing; when absent, use the scene's `meta.width / meta.height`. The runtime applies the saved ratio before setup, so `SetupContext` and `FrameContext` both receive the effective dimensions: use `ctx.width` and `ctx.height`, never imported meta dimensions, for layout, backgrounds, clipping and camera bounds. A portrait brief is authored natively at 1080 × 1920, never fitted from a landscape scene. Read [output.md](output.md) for portrait layout, safe margins, export sizes and formats.\n\n## Required behavior\n\n1. Treat `renderFrame` as a pure function of `time`, resolved params, and assets prepared by `setup`. Do not read a previous frame, accumulate module state, or read a clock. The player may seek in any order, and validation renders the same time twice to detect state leaks.\n2. `Math.random`, `Date.now`, and `performance.now` throw inside `renderFrame`. Prepare random choices once with `ctx.random()` in `setup`, and use `ctx.noise(...coordinates)` only for values that must vary per frame (see Randomness below).\n3. The runtime resets and fills the canvas before every call. `renderFrame` must finish synchronously.\n4. Import only files inside the project and `@mografy/runtime`.\n5. Put fonts in `assets/`, list them in `mografy.json` under `fonts`, then select them with `mografy.textFont('Family', 400)`. Only loaded weights are reliable.\n6. Express effect distances such as `shadowBlur`, shadow offsets, and filter pixels in logical units on `ctx.canvas`; the runtime scales them for output resolution, but not for your own transforms (a camera zoom) and not on your own offscreen contexts. Never set `ctx.filter` around a group of draws: blur a layer with `blurLayer`, type with `blurText` / `blurWords`, light with `bloom` (see [performance.md](performance.md)). Use `ctx.vignette(strength)` for a canvas vignette.\n7. Never create a canvas in `renderFrame`. Use `layer`, `blurLayer`, `bloom` or `buffer(name, w, h)`, which reuse pooled memory sized in film coordinates.\n8. Expose only important subtitles as `type: 'string', role: 'subtitle'` params. Titles, chat text, buttons, hints, code examples, and brand copy should stay in the scene for the AI to edit. Do not turn every string into an inspector field. Every color or numeric param must control a visible result. Do not add a dot grid unless the user explicitly asks for one.\n\n## Randomness\n\nDecide random things once, in `setup`, and store them in `ctx.assets`: particle positions, sizes, colours, delays, star fields, the order of a scatter. `ctx.random()` is seeded by the project seed, so the same seed always gives the same film, and changing `seed` in mografy.json gives a new but equally stable variation. In `renderFrame`, read those values and move them with `time`:\n\n```ts\nimport { spring } from '@mografy/runtime';\n\nexport function setup(ctx: SetupContext) {\n ctx.assets.dots = Array.from({ length: 120 }, () => ({\n x: ctx.random() * ctx.width, y: ctx.random() * ctx.height,\n size: 4 + ctx.random() * 10, delay: ctx.random() * .6,\n }));\n}\nexport function renderFrame(ctx: FrameContext, time: number) {\n for (const d of ctx.assets.dots as { x: number; y: number; size: number; delay: number }[]) {\n const k = spring(time, .4 + d.delay);\n ctx.draw.circle(d.x, d.y - 40 * (1 - k), d.size * k);\n }\n}\n```\n\nUse `ctx.noise(...coordinates)` when a value must change over time or space and cannot be listed in advance: flicker, jitter, grain-like texture, shimmer. Pass whole-number or stepped coordinates (`ctx.noise(i, Math.floor(time * 12))` for a 12 fps flicker) and smooth between steps yourself when the motion should glide. Noise is order-independent, so seeking stays exact. Never keep a random generator in module scope and call it during frames.\n\n## Tempo and music\n\nWhen a film is cut to music, declare its grid once in the scene and build every timing constant from it:\n\n```ts\nimport { tempoGrid } from '@mografy/runtime';\nconst tempo = { bpm: 120, beatsPerBar: 4 };\nexport const grid = tempoGrid(tempo); // grid.beat = 0.5 s, grid.bar = 2 s\nexport const meta = { width: 1920, height: 1080, duration: grid.onBar(12), fps: 30, background: '#101114', tempo };\nconst LOGO_IN = grid.onBar(10, 2); // bar 10, beat 3\n```\n\n`grid.onBar(n, k)` is the start of bar `n` plus `k` beats, `grid.onBeat(n)` a beat, and `grid.snap(t)` the nearest beat to a hand-picked moment. `ctx.beat(time)` returns `{ beat, bar, beatInBar, phase, period }` from the project audio, or from `meta.tempo` when the project has no audio yet, so pulses written against it work before the music exists. Keep `audio.bpm`, `audio.offset` and `audio.beatsPerBar` in mografy.json equal to `meta.tempo`; `npx mografy check` reports any difference. When the tempo changes, change `meta.tempo` only and every cut moves with it.\n\n## FrameContext\n\n| Member | Purpose |\n| --- | --- |\n| `ctx.draw` | Common drawing API. Prefer `const mografy = ctx.draw`; methods may be destructured. |\n| `ctx.canvas` | Native 2D context in logical coordinates. |\n| `ctx.width`, `ctx.height` | Logical canvas dimensions. |\n| `ctx.noise(...n)` | Seeded 0–1 noise independent of call order. |\n| `ctx.beat(time)` | `{ beat, bar, beatInBar, phase, period }` from the project audio, or `meta.tempo` without audio; otherwise `undefined`. |\n| `ctx.shadow(color, blur, x?, y?)`, `ctx.blur(px)`, `ctx.vignette(strength)` | Visual effects. |\n| `ctx.withCanvas(canvas => { ... })` | Synchronous scope that restores native state and Mografy fill/stroke state, including after an error. |\n| `ctx.clip(path2d, () => { ... }, rule?)` | Synchronous Path2D clipping scope; default rule is `nonzero`. |\n| `ctx.assets` | Read-only assets prepared by `setup`. |\n| `ctx.seed`, `ctx.renderScale` | Project seed and output scale. |\n\n`SetupContext` provides `ctx.random()`, `ctx.loadImage('assets/x.png')`, `ctx.assets`, `ctx.seed`, `ctx.width`, and `ctx.height`.\n\n## Time and motion helpers\n\nAll are pure functions of absolute time, imported from `@mografy/runtime`. Use them instead of writing curves, springs and cameras in each project. Defaults: `springs.out` for entrances and moves, `springs.pop` for cards and buttons, `springs.camera` for camera-like moves, `keys` for any move through several poses, `ease.inOutCubic` for exits and `ease.inOutSine` only for deliberate loops.\n\n| Helper | Use |\n| --- | --- |\n| `pr(time, start, end)` | Map a time range to 0–1 (clamped). |\n| `lerp(a, b, p)`, `clamp(n, min?, max?)`, `colorLerp(a, b, p, 'srgb' or 'linear')`, `hashNoise(seed, ...n)` | Interpolation and seeded hashing. |\n| `ease.linear / inQuad / outCubic / inOutCubic / outExpo / outQuart / outQuint / inOutQuart / inOutSine` | Easing curves for p in 0–1. `outQuart` for entrances and moves, `outQuint` for word rises, `inOutCubic` for exits, `inOutSine` for loops and drifts. |\n| `at(time, start, end, curve?)` | Eased progress of a time window (default `ease.outCubic`). |\n| `win(time, a, b, c, d, enter?, exit?)` | In over [a, b], out over [c, d]: 0 → 1 → 0. |\n| `spring(time, start, duration?, bounce?)` | A spring from 0 to 1 that settles exactly on 1 by `start + duration × 1.6` (defaults 0.7 s, bounce 0.18; bounce 0 has no overshoot). |\n| `springEase(stiffness?, damping?)`, `springs.out / pop / camera / cursor` | Spring easing curves for p in 0–1, normalised to land on 1; pass them as `curve` to `at`. `pop` overshoots about 1.5 %. |\n| `settle(time, start, duration, amplitude, cycles?)` | Follow-through: a decaying wobble around 0 after a landing or impact. |\n| `pulse(time, at, width?)` | A bump that peaks at 1 at `at`: presses, flashes, highlights. |\n| `stagger(i, count, step, curve?)` | Delay for item `i`; with a curve, the group's delays are eased. |\n| `tempoGrid({ bpm, beatsPerBar?, offset? })` | Bar and beat times for timing constants (see Tempo and music). |\n| `keys([[t, v], …])` | One smooth curve through several keys (monotone cubic): velocity carries through inner keys, no overshoot. For long moves and camera paths. |\n| `cameraPath([[t, x, y, zoom?, roll?], …])`, `withCamera(c, camera, draw)` | The film's one camera: keyed position and roll, zoom in log space; `withCamera` puts the camera's (x, y) at the frame centre. |\n| `beats([{ title, end, stop?, handoff?, note? }, …])` | The shot table: `shots` for `meta.shots`, `list` start/end/stop times, `reviewTimes`, `transitions`, `at(time)`. |\n\n## Layer and text helpers\n\nCommon drawing patterns that would otherwise be copied into every film. Each runs in its own canvas scope and takes either the `FrameContext` or a native 2D context; inside a `layer`, `blurLayer` or `bloom` callback, pass the context the callback receives.\n\n| Helper | Use |\n| --- | --- |\n| `roundRect(x, y, w, h, radius or [tl, tr, br, bl])` | Rounded-rectangle `Path2D`; a single radius is clamped to half the shorter side. |\n| `surface(ctx, path, fill, { elevation?, tint? })` | Fill a path with a soft two-layer shadow: 0 flat, 1 resting card, 2 lifted. |\n| `text(ctx, value, x, y, style)`, `measure(ctx, value, style)` | One line with its own `size`, `color`, `family`, `weight`, `align`, `baseline`, `tracking` (letter spacing), `alpha` and `maxWidth`. |\n| `riseWords(ctx, line, x, y, style, time, start, { stagger?, duration?, curve?, exit?, colors?, separator? })` | Words rise into a mask one after another (0.07 s apart, 0.8 s each, `ease.outQuint`). Returns each word's `[left, right]` for underlines or cursors. `exit` 0–1 lifts the line out. |\n| `blurWords(ctx, line, x, y, style, time, start, { …, blur?, lift? })` | Words come into focus: blur, a small rise and opacity resolve together. Uses `blurText`, never a filter. |\n| `blurText(ctx, value, x, y, style, radius)` | One blurred line drawn through its shadow: about the cost of sharp text. |\n| `layer(c, name, alpha, draw, { res?, mode?, bounds? })` | Draw a group into a pooled layer and composite it once: group fades without flashing overlaps, blend modes, reduced resolution. |\n| `blurLayer(c, name, radius, draw, { alpha?, res?, mode?, bounds? })` | Blur a group in one pass; `radius` in current units (follows the camera); strong blurs drop resolution automatically. |\n| `bloom(c, draw, { radius?, strength?, halo?, mode?, res?, bounds? })` | Glow for lights and neon at quarter resolution: a tight glow and a wide halo. Draws only the glow. |\n| `buffer(name, w, h)` | A pooled, cleared offscreen canvas in device pixels, for custom effects. |\n| `devScale(c)`, `outputScale(c)`, `deviceTransform(c)` | Device pixels per current unit (with camera) and per film unit (output scale); multiply your own offscreen filter and shadow lengths by them. |\n| `filmFrame(c, width, height, base?)` | Tag a plain canvas (a storyboard page) with its film frame so the helpers above work on it. |\n\n`bounds: [x, y, w, h]` (current coordinates) limits a layer to the area it covers; use it for anything smaller than about half the frame.\n\nPass `separator: ''` to animate CJK copy character by character. For a family, use one registered under `fonts` in mografy.json.\n\n## Drawing API\n\n`ctx.draw` is a thin layer over the native Canvas context. Both APIs share styles, transforms, clipping, and resolution scaling. It is not a p5.js compatibility layer and does not create a draw loop.\n\n| Function | Behavior |\n| --- | --- |\n| `fill(color)`, `noFill()` | Set and enable or disable fill. A color may be a CSS color, CanvasGradient, or CanvasPattern. |\n| `stroke(color)`, `noStroke()` | Set and enable or disable stroke. |\n| `strokeWeight(px)`, `strokeCap(value)`, `strokeJoin(value)` | Logical line width and native cap/join values. |\n| `opacity(0..1)` | Set current alpha, clamped to 0–1. It does not multiply the previous value. |\n| `push()`, `pop()` | Save and restore native state plus Mografy fill/stroke state. Keep pairs balanced. |\n| `translate(x,y)`, `rotate(radians)`, `scale(x,y?)` | Transform the coordinate system; omitted `y` means uniform scale. |\n| `rect(x,y,w,h,radius?)` | Top-left coordinates, with an optional uniform corner radius. |\n| `circle(x,y,diameter)`, `ellipse(x,y,w,h)` | Center coordinates; circles use diameter. |\n| `arc(x,y,w,h,start,end)` | Center, size, and radians. An open arc closes implicitly only when filled. |\n| `line(x1,y1,x2,y2)` | Uses the active stroke. |\n| `triangle(...)`, `path(path2d,rule?)` | Fill and/or stroke. Path fill rule defaults to `nonzero`. |\n| `textFont(family,weight?)`, `textSize(px)` | Select loaded type and logical font size. |\n| `textAlign(align,baseline?)` | Native horizontal alignment and baseline. |\n| `text(value,x,y,maxWidth?)`, `textWidth(value)` | Draw or measure text. `maxWidth` condenses a line; it does not wrap. |\n| `image(source,x,y,w?,h?)` | Draw at top-left; provide both width and height or neither. |\n| `linearGradient(x1,y1,x2,y2,stops)`, `radialGradient(x,y,radius,stops,inner?)`, `conicGradient(x,y,angle,stops)` | Return a gradient to pass to `fill` or `stroke`. `stops` is `[[0, '#fff'], [1, '#000']]` or evenly spaced colours `['#fff', '#000']`. |\n| `background(color)` | Clear and repaint the logical canvas while preserving state. It still respects the current clip. |\n\nAt the start of every frame, fill is enabled and stroke is disabled. Call `fill` and `stroke` explicitly. Use the gradient helpers above for fills, and `ctx.canvas` for multiline layout, batched paths, and complex clipping. Do not cross-pair `mografy.push()` with `canvas.restore()`.\n\n```ts\nconst mografy = ctx.draw;\nmografy.push();\nmografy.opacity(ease.outCubic(pr(time, 0.2, 0.8)));\nmografy.fill(p.accent);\nmografy.rect(100, 100, 320, 180, 16);\nmografy.fill('#ffffff');\nmografy.textFont('ABeeZee', 400);\nmografy.textSize(44);\nmografy.textAlign('center', 'middle');\nmografy.text(p.subtitle, 260, 190);\nmografy.pop();\n```\n\n## Built-in scene components\n\nNew projects include `scenes/components.ts`, `scenes/social-components.ts`, and `scenes/showcase.ts`. Component functions are pure time functions that can be copied or edited; they do not add global runtime animation state.\n\n| Component | Additional options |\n| --- | --- |\n| `staggerText` | text,x,y,size?,color?,font?,start?,duration?,stagger?,lift? |\n| `typewriter` | text,x,y,size?,color?,font?,start?,duration?,caret? |\n| `popCard` | x,y,width,height,color?,radius?,start?,duration?,content?(ctx) |\n| `progressBar` | x,y,width,height?,target?,color?,track?,start?,duration? |\n| `pulseDots` | x,y,color?,diameter?,spacing?,period?,start? |\n| `logoReveal` | x,y,color?,ink?,width?,start?,duration? |\n| `socialCard` | x,y,color?,start?,name?,avatar?,caption? |\n| `youtubeSubscribe` | x,y,color?,start?,label?,subscribed? |\n| `aiChat` | x,y,color?,start?,prompt?,reply?,avatar? |\n| `likeBurst` | x,y,color?,start? |\n| `followBadge` | x,y,color?,start?,name?,avatar?,label?,following? |\n| `notificationToast` | x,y,color?,start?,message? |\n| `lowerThird` | x,y,color?,start?,name?,subtitle? |\n| `countUp` | x,y,color?,start?,value? |\n| `toggleSwitch` | x,y,color?,start? |\n| `audioWave` | x,y,color?,start?,bars? (3–40) |\n\n## Edit and visual-review workflow\n\nFor a new animation, create the project first with `npx mografy init projects/<name>` (an internal command for agents; it starts as a blank stage with the component modules), then replace `scenes/main.ts` and open it with `npx mografy dev projects/<name>` so the running player switches to it. `npx mografy dev` only opens existing projects and fails on a folder without `mografy.json`. Do not tell the user to run `init` themselves.\n\n1. Read `mografy.json`, the configured scene entry, and every local module it imports. Preserve the scene's existing visual language unless the user asks for a redesign.\n2. Edit scene source files directly. Keep animation data out of `mografy.json`; use it only for project, parameter, font, audio, render and review settings.\n3. Run `npx mografy check [project]`. This compiles the scene, trial-renders it in real Chromium and measures frame cost. Fix every reported error, and every `!` frame-cost warning, before judging the design.\n4. Run `npx mografy review [project]`. Inspect every generated PNG in `renders/`, including raw stills, output frames, and transition strips. Do not approve a scene from source code or a successful build alone.\n5. Judge the images for clipping, overlap, safe margins, legibility, hierarchy, spacing, contrast, consistent easing, transition continuity (the followed object is visible in every frame of a transition strip, nothing jumps, no frame is empty), and whether each important message stays visible long enough. Review the beginning, end, configured key times, and dense transition intervals. Check both raw stills and final output frames when glow, grain, or motion sampling is used.\n6. Iterate on the scene and repeat check plus review until the visual problems are resolved. Use `npx mografy dev [project]` when the user should watch the live result.\n7. Export with `npx mografy export [project] --format mp4|webm|lottie|svga` when the user asks for a file. The command prints capture and encoding or packaging progress and writes the finished file under `renders/`. Press Ctrl+C to cancel a CLI export. When `npx mografy dev` is running, player exports also print progress in that terminal and can be stopped with `npx mografy export [project] --cancel`.\n\n## Shots\n\nExport `meta.shots` (`[{ end, stop?, title? }, …]`, from the beat table) so the player's timeline marks each shot and `npx mografy review` writes `review-<version>-shots.png` with the frame each one settles on. `stop` is that settled frame; by default one frame before `end`. Video export ignores shots.\n\nOnly important subtitles belong in `role: 'subtitle'` params. Let the user edit those in Scene → Subtitles; make other copy changes in source when requested.\n\n## Motion direction\n\n- Show a meaningful element within the first 0.3 seconds.\n- Keep important text readable for at least the caption hold in [taste.md](taste.md).\n- Use `springs.out` (or `spring()`) for entrances, `springs.pop` for cards and buttons, `keys` / `cameraPath` for moves through several poses, and `ease.inOutCubic` for exits. Keep one vocabulary per film.\n- Use a consistent curve for related elements and fixed 0.05–0.08 second intervals for a text stagger.\n- Hold readable poses still: no idle drift or bobbing while the viewer reads.\n- Connect shots through shared geometry and overlapping exits (see [film-architecture.md](film-architecture.md)).\n- Preserve whitespace and keep one dominant moving focus at a time.\n- With music, declare `meta.tempo` and time major changes from `tempoGrid(tempo).onBar(n)`, so cuts stay on bar starts when the tempo changes; use `ctx.beat(time)` for pulses inside a bar.\n\n## Project style\n\nEvery project keeps its design and motion decisions in `style.md` at the project root, so every shot and every later session follows them. It lives in the project, never in `mografy.json` or a Skill. A new film writes it at the storyboard step; a project that has a scene but no `style.md` gets one written from the scene before the next change. Write it in English: do and don't rules, the motion character, palette, type, tempo and timing choices, composition habits, and reference stills (paths under `storyboards/` or `assets/`). Keep each rule short enough to check against a frame.\n\nValues themselves stay in scene code. Define each fixed value (a colour, font family, easing curve, duration, tempo) once, in the scene module or in a shared module the scenes already import, and change it there rather than inline in one shot. Font files are registered under `fonts` in `mografy.json`.\n\nWhen `style.md` exists, read it before planning a storyboard or editing a scene. Precedence: the user's current request, then `style.md`, then this Skill's default motion and design guidance. The scene contract above (deterministic `renderFrame`, browser-only code, check and review) always applies. If a request conflicts with the style, follow the request for that change and ask whether the style should change too.\n\nWhat goes in: the film's idea, its design system (type roles, palette, the layout repeated shots share, the travelling motif), its motion character and tempo, and every decision the user states or approves as lasting (\"always\", \"from now on\", \"use this for every shot\"). What stays out: one-off fixes and your passing preferences. When a decision is a value, also change it in the scene code. Mark rules you wrote yourself, before the user confirmed them, so they can be overruled without discussion. During review, check the frames against the `style.md` rules as well as the general criteria. To reuse a style in another project, copy `style.md` and adapt the values in that project's scene code.\n",
|
|
20
|
+
"references/storyboard.md": "# Storyboard planning for Mografy\n\nRead this reference when asked for a storyboard, shot list, or a new animation that needs shot planning. Read the project's scene entry, imported modules, assets, and settings first, including `style.md` when present. Reuse its visual language, dimensions, fonts, palette, and existing characters or brand assets. Write planning documents, shot labels, and tool prompts in English; preserve supplied dialogue and artwork unless translation or redesign is requested.\n\nFor a portrait brief, explicitly label the written plan and every image-generation prompt as **9:16 portrait**, and draw each storyboard panel as a tall 9:16 frame. Read the saved `aspectRatio`; design a vertical composition with stacked content, wrapped copy, and social safe margins. A landscape storyboard cropped into tall panels is not a portrait plan. When both ratios are needed, specify the layout changes for each shot and verify both versions against actual frames.\n\n## Deliverables\n\nSave a project-specific plan as `storyboards/storyboard.md`. Include the audience, message, aspect ratio, total duration, visual direction, asset inventory, and assumptions. Use one row per shot:\n\n| Shot | Time (seconds) | Purpose | Composition and assets | Action and poses | Camera | Copy / audio | Transition | Principles | Review times |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| S01 | 0.0–2.0 | Introduce the mark | Existing logo, centered, generous margins | Anticipation at 0.15; reveal at 0.4; settle by 1.1; hold | Static | Brief logo sound; no copy | Match logo position into S02 | Staging, anticipation, slow in/out | 0.15, 0.4, 1.1, 1.9 |\n\nNumber shots in order; make time ranges contiguous and cover the requested duration. The shot table becomes the scene's `beats([...])` table ([film-architecture.md](film-architecture.md)): give each shot a title, an end time, a settled stop frame and the handoff it uses, so the board and the code share one set of times. Specify entrance, action, settle, hold, and exit where useful. Describe start, extreme, and settle poses rather than writing vague directions such as \"make it dynamic.\" Give each shot a clear focal point and connect transitions through position, color, shape, or meaning: name the object each shot hands to the next (\"the underline becomes the card's top edge\"), and plan one continuous camera rather than a reset per shot. Allow reading time for the actual copy (the caption hold in [taste.md](taste.md)); lengthen a shot or shorten copy when the timing is unrealistic.\n\nLink each shot to existing or proposed scene functions and name the assets it needs. Mark missing assets and assumptions clearly. Keep shot descriptions and visual references out of `mografy.json`; only review times and transition sampling settings belong in its existing review fields. A storyboard is a planning document, not a runtime format.\n\n## Visual output by host\n\n### Codex: image generation\n\nWhen creating a storyboard in Codex, invoke the host's available image-generation tool to produce a storyboard contact sheet or individual key poses. Follow its image-generation skill when available. Supply project artwork as references for edits or identity continuity. Describe panel count, aspect ratio, ordered shot IDs, consistent palette and framing, key poses, and the action between panels. Match the board to the written shot list. Keep exact copy and timings in Markdown because generated image labels can be unreliable. Inspect generated panels for identity, composition, cropping, and consistency, then link the result from `storyboards/storyboard.md`; save a local copy under `storyboards/` when the host exposes one.\n\nGenerated panels are conceptual references. They do not prove that the implemented animation renders correctly. If image generation is unavailable, say so and provide the complete written plan plus ready-to-run English image prompts; never claim images were generated.\n\n### Claude: Artifacts\n\nWhen creating a storyboard in a Claude host with Artifacts, invoke its Artifact capability to present the same plan as an HTML storyboard. Use responsive shot cards with shot ID, time range, Canvas-drawn key poses or existing raster assets, action, transition, and motion notes. Use ordinary HTML/CSS and Canvas; do not add GSAP, SVG scene layers, or resvg. An optional playhead or shot selector may illustrate timing, but label it as a storyboard preview. Keep the artifact self-contained and avoid remote dependencies. Also save the English shot list to the project so Codex can continue from it.\n\nClaude Code environments may not expose Artifacts. Check tool availability; if absent, save `storyboards/storyboard.html` as a standalone local preview and report that fallback. Do not claim to have opened a Claude Artifact. The HTML storyboard is separate from the Mografy scene and is never imported by the Server.\n\n## Storyboard as code\n\nOnce a scene exists, or for films longer than about 15 s, draw the board's panels from the scene itself: export `drawFilm(c, t, data)` from the scene and render it at each beat's stop frame on a plain canvas, as described in [film-architecture.md](film-architecture.md). The board then shows the film's real pixels, and updating the scene updates the board.\n\n## From storyboard to animation\n\nRead [animation-principles.md](animation-principles.md) to choose motion that supports each shot. A storyboard-only request ends with the written and visual board. If implementation is also requested, continue into scene modules without inventing an approval step. Use analytic functions of `time` for all poses, camera transforms, secondary motion, and transitions. Validate using `npx mografy check`, then `npx mografy review`; inspect real raw and output frames at the shot's poses, holds, boundaries, and transition intervals against the storyboard. Update the plan if implementation changes timing or composition.\n",
|
|
21
|
+
"references/taste.md": "# Default taste\n\nRead this before a storyboard and again before delivery. These are Mografy's defaults when the project's `style.md` and the brief say nothing else; the project's own decisions always win. Each rule gives its reason, so apply the reason to cases the rule does not name. Sizes are for a 1920 × 1080 canvas unless stated.\n\n## Pacing: the viewer reads every word and sees every change\n\n- **Caption hold.** Keep a caption fully readable (after its reveal settles) for at least 0.5 s + characters ÷ 4.5 for Chinese or Japanese, or 0.5 s + words ÷ 3 for English. A 6-character line holds ≥ 1.8 s, a 12-character line ≥ 3.2 s, a 9-word line ≥ 3.5 s. Viewers meet the line for the first time while also watching the picture, and need a beat to take it in after reading it. When the hold does not fit the shot, cut copy before shortening the hold.\n- **Result hold.** After a state changes (a number lands, a check draws, a card arrives), hold 0.6–1.0 s before the next move. A change nobody had time to see did not happen.\n- **One action per shot**, 2.5–4 s per shot for UI and explanation, longer for a reading hold. Two actions at once split attention and neither reads.\n- **Length changes come from holds.** To hit a length, shorten or lengthen still holds; never speed up an action, because a rushed action looks like a glitch. If the copy cannot be read in the requested length, cut copy or say so; do not speed up the whole film.\n- **Camera and cursor.** Start a camera move up to 0.5 s before the action it serves; never move the camera during a click or a reading hold. Give a cursor up to 1.1 s per move on a gentle arc and let it rest on the control before clicking. The eye needs to arrive before the event.\n- **Smooth, not fast.** A move across more than half the frame takes at least 0.6 s, and an exit at least 0.4 s; ease through every key instead of stopping and starting again. A whip that crosses the frame in a few frames reads as a stutter on most screens, even when every frame renders on time. `npx mografy check --motion` finds the hard starts, hard stops and jumps ([performance.md](performance.md)).\n- **Overlap cuts.** Start the incoming action 0.2–0.5 s before the outgoing exit ends, so no frame is empty.\n\n## Type and layout: legible at the size it is watched\n\n- **Headlines 96–160 px, body copy ≥ 40 px, nothing under 24 px** except UI detail that is not meant to be read. A 1080p film is often watched in a small window or on a phone, where 24 px is already small.\n- **Portrait (1080 × 1920):** headlines ≥ 110 px, captions ≥ 44 px, captions in the top third. Phones are held at arm's length and the bottom is covered by platform UI.\n- **Redrawn UI at 1.3–1.6× the app's own type size,** with 3–4 rows per list. A real screen shrunk into a frame is unreadable.\n- **Few words at once:** at most about 12 English words or 20 CJK characters on screen outside the product UI. More is a slide, not a film.\n- **Safe margins:** keep copy and logos at least 96 px from the sides and 72 px from the top and bottom in 16:9; use the portrait margins in [output.md](output.md). Players and platforms crop and overlay the edges.\n- **One card style:** one corner radius, one shadow, one padding (≥ 48 px inside a card) across the film. Mixed styles read as different products.\n- **No text over text.** Captions never overlap UI or other captions, and text never cross-dissolves over UI. Overlapping type is unreadable for the overlap's whole duration.\n\n## Design system: decide it once, before the first shot\n\nA film looks designed when every shot is built from the same few decisions. Write them as tokens at the top of the scene (`const C = {…}`, one object per type role) before drawing anything, and draw every shot from them.\n\n- **Four type roles, no more.** A display face for headlines and item names (a serif, or a heavy sans) and a text face for everything else. Portrait sizes as a starting scale: kicker 40–48 px (text face 500, accent colour, tracking 8–12), headline 120–150 px (display 700, tracking 4–8), item name 100–120 px, descriptor 48–56 px (text face 500, muted colour). For 16:9 use about 0.8× these. Contrast between a big display line and a small, wide-tracked kicker is what reads as designed; five sizes that are all similar read as a document.\n- **A numbered kicker for lists.** When the film walks through items (products, steps, features), put `No.01`, `No.02`… or a short label above each name in the kicker role. It tells the viewer where they are and gives each shot the same structure.\n- **One fixed layout for repeated shots.** Shots that do the same job share one composition: the copy block at the same position (portrait: centred in the top third), the subject at the same spot (portrait: centred around 55–60 % height), the same subject size. Only the content changes, so the eye knows where to look and the cut feels like a page turn, not a new film.\n- **Palette: five roles.** A light or dark background with a slightly lighter centre (a soft radial gradient, never flat grey), an ink tinted towards the background's hue (never pure #000 on cream or #FFF on navy), a muted colour for secondary text, one accent for the kicker, highlights and the logo, and the subject colours from one family around the accent. A second accent splits attention.\n- **Leave about 40 % of the frame empty.** Big type and one subject on calm space look expensive; filling the frame with surfaces (a dark floor across the bottom third, panels behind every line) makes it look heavy and cheap.\n- **Simple, flat illustrations.** When you draw the product or objects yourself, use few geometric shapes, a flat fill or one gentle gradient, one soft contact shadow, and one recurring accent motif (a leaf, a spark, a dot) that can travel between shots. Detail belongs to the subject's one identifying feature (the latte art, the ice), not to everything.\n- **The ending is the biggest type in the film.** The wordmark at about 1.2–1.4× the headline size with wide tracking, a small Latin or secondary line under it, the tagline in the accent colour, and, when the film listed items, a small recap of them as a row of icons.\n\n## Look: nothing that competes with the message\n\n- **Still holds.** No idle drift, bobbing or slow zoom while the viewer reads; every motion has a cause and ends. Motion pulls the eye away from the words.\n- **No decoration for its own sake.** No dot grids or busy patterns; a quiet gradient, one glow or the brand's colour field. Texture behind type lowers its contrast.\n- **The logo once.** The brand mark lands at the end, about 20–30 % of the frame width, held still with the tagline for ≥ 1.5 s; it does not open the film or repeat in every shot. Repetition spends the payoff.\n- **On-screen language follows the brief.** Plans, shot labels and prompts stay in English; preserve supplied copy unless translation is requested.\n\n## Sound\n\n- **Sustained, warm music:** long pads, warm piano, one long bass note per bar, few hits on the moments that change the story. Busy patterns fight the picture.\n- **No sharp high sounds:** no bells, sparkles, ticks or pops; soft whooshes and low hits instead. They are tiring on repeat and on headphones. Details in [music.md](music.md).\n",
|
|
22
|
+
"references/templates.md": "# Mografy Templates\n\nMografy Templates is a free (MIT) library of finished, editable templates for product demo videos: hooks, captions,\nproduct screens, callouts, numbers, proof, slides, end cards and transitions. All copy is English. Each template has one\nnative aspect ratio and one look:\n\n| Aspect | Ids | Look | For |\n| --- | --- | --- | --- |\n| 9:16 | `hook-impact` … | **Editorial**: a white printed page, black type, one burnt-orange accent; tall Anton headlines that rise letter by letter, header and footer rules, quote marks, hand-drawn underlines, dark picture windows and a carousel swipe. Themes `light` (default) and `dark`. | Threads, Reels, Shorts |\n| 16:9 | end in `-wide` | **Montage**: night, light or neon grounds; kinetic Inter type that sharpens out of a blur; the Mografy spectrum (teal, sky, violet, coral, amber) on a word, a pill rim or a comet of light; product windows on tilted planes. | Landing pages, YouTube, Product Hunt, decks |\n\nA template that exists in both ratios has a `pair` (`stat-count` ↔ `stat-count-wide`). Never put a template into a film of\nthe other ratio. The sources live in [templates/](__REPOSITORY__/templates), with the catalog in\n[templates/catalog.json](__REPOSITORY__/templates/catalog.json); every template plays live at https://www.mografy.app/en/library/templates.\n\n## When to use them\n\nReach for a template when a brief needs a standard beat of a demo video (an opening hook, subtitles, a phone or laptop\nscreen, a callout on a feature, a before/after, numbers, testimonials, a closing card). Start from the template, then\nadapt its copy, colours and timing to the brief. Build new motion from scratch only when no template fits, or when the\nfilm needs its own visual concept. Use one look per film: the editorial templates for a 9:16 post, the montage templates for\na 16:9 film.\n\n## Add templates\n\n```sh\nnpx mografy add hook-impact three-steps cta-endcard projects/<name>\n```\n\n- When the folder is not a project yet, `npx mografy add` creates it: a project with the templates' aspect ratio, a\n `scenes/main.ts` that plays the templates in the order given, output glow and grain off, and review times. This is a\n complete way to start a film; open it with `npx mografy dev projects/<name>`.\n- Without a folder, inside a project, the templates go into that project. Outside a project, the first template names a new\n project in the library. `npx mografy add` never falls back to another (last opened) project.\n- Each template lands in `scenes/templates/<id>.ts` with the shared `kit.ts`, `editorial.ts` and `montage.ts`. Inter\n (500–800) and Anton are copied to `assets/` with their licences and registered under `fonts` in `mografy.json`.\n Files the user changed are kept unless `--force` is passed. If the project already has `scenes/templates/`, read\n and reuse that local copy.\n- A project without a `tsconfig.json` gets one for editor support (strict, `@mografy/runtime` resolved to this\n installation's types), so templates open in an editor without \"Cannot find module\" or implicit `any` errors.\n- Templates set `render.glow` and `render.grain` to 0 in new projects: the light that belongs to the montage look is\n drawn in the scene. Keep them at 0 when a film is made of templates.\n\n## Use a template\n\n- **On its own:** set `\"scene\": \"scenes/templates/<id>.ts\"` and the matching `\"aspectRatio\"` in `mografy.json`.\n- **In a film:** import the module and play it on the film's timeline. `play` resolves the template's default params\n and applies your overrides; `backdrop: false` draws an overlay template (captions, callouts, lower thirds, end\n cards) over the film's own picture.\n\n```ts\nimport * as hook from './templates/hook-impact.js';\nimport * as caption from './templates/caption-highlight.js';\nimport { play } from './templates/kit.js';\n\nexport function renderFrame(ctx: FrameContext, time: number) {\n play(ctx, time, 0, hook, { text: 'Plan the week\\nin [one view.]' });\n drawProduct(ctx, time); // the film's own shot\n play(ctx, time, 4, caption, { backdrop: false });\n}\n```\n\nEvery template enters, holds still while it reads, and exits in its last ~0.5 s, so templates chain without empty frames.\nKeep the film's quality floor: one world and one camera for shots you write yourself, and hand geometry over at\ncuts.\n\n## Edit a template\n\n- Copy and colours are params: the template's strings, `theme` (editorial `light`/`dark`; montage `night`/`light`/`neon`)\n and, for editorial templates, `accent`. In editorial headlines, a word in `[brackets]` takes the accent; in montage\n headlines it takes the spectrum. Change timing and layout in the template file. Keep `renderFrame` pure, and keep\n critical copy inside `safeRect(aspect)` from the kit (`safeGuide: true` shows it in the preview, never in exports).\n- Screen templates draw a fictional stand-in product (\"Northwind\"): `editorialScreen` in 9:16, `appUI` in 16:9.\n Replace it with the real product: redraw the real screens in the same box (see\n [product-walkthrough.md](product-walkthrough.md)), or load a screenshot in `setup` and draw it there. Editorial\n templates that take pictures load `assets/<name>.jpg` with `loadPhoto` (black-and-white, like the look) when the file\n exists; the agent hint names the file.\n- Brand templates draw a placeholder mark. Replace it with the real logo (load `assets/logo.png` in `setup` and draw it\n in the same box).\n- The fonts are Latin subsets. For Chinese or Japanese copy, add `npx mografy add cjk` and a CJK font, and check the\n frames for fallback glyphs.\n- After editing, run `npx mografy check` and `npx mografy review` and look at the stills, as for any scene.\n\n## Catalog\n\n<!-- catalog:start -->\n| Template | Aspect | Category | Seconds | Use it for |\n| --- | --- | --- | --- | --- |\n| `hook-impact` Impact headline | 9:16 | hook | 4 | First 3–4 s of a post. Up to three lines of 1–3 short words, uppercase reads best; mark one word with [brackets]. Not for sentences longer than ~25 characters. |\n| `hook-number` Number hook | 9:16 | hook | 3.5 | Open on a single striking figure (1–4 characters: \"3\", \"24\", \"9.5\") with a short unit and a one-line caption under 30 characters. For several figures use stat-count. |\n| `hook-question` Question hook | 9:16 | hook | 3.5 | Opening 3–4 s that asks the viewer a pain-point question. Up to three short uppercase lines (≤ 14 characters each); mark the key words with [brackets]; the question mark is drawn for you. |\n| `caption-highlight` Highlight caption | 9:16 | caption | 4 | One statement of up to ~40 characters with the key words in [brackets]. Put assets/highlight.jpg in the project for the picture; with backdrop false the caption sits on a white panel over your own footage. |\n| `caption-pop` Pop captions | 9:16 | caption | 4 | Punchy spoken line of 2–8 short words; words of up to three letters ride with the next word. Put assets/pop.jpg in the project for the picture, or play it with backdrop false over your own footage (the strip carries the words). |\n| `caption-stack` Stacked caption | 9:16 | caption | 4 | A slogan of 2–5 very short lines (1 word each, up to ~6 letters), one per \"\\n\". Put assets/stack.jpg in the project for the picture strip; with backdrop false the stack sits on a white panel. |\n| `caption-subtitle` Speaker subtitle | 9:16 | caption | 4.5 | Interview or founder quote: one sentence up to ~60 characters (wraps to two lines) and a \"Name · Role\" line. Put assets/speaker.jpg in the project for the picture; with backdrop false it draws its own scrim over your footage. |\n| `caption-word` Word captions | 9:16 | caption | 5 | Spoken subtitles for a voice-over: 2–3 lines of up to ~24 characters, one per \"\\n\"; mark key words with [brackets] (default: the last word of each line). Put assets/caption.jpg in the project for the picture, or play it with backdrop false over your own footage. |\n| `ai-chat-stream` AI chat stream | 9:16 | screen | 6 | Show an AI feature answering. Prompt under ~60 characters, reply under ~200 (about 30 words; longer replies stream too fast to read). Speaker labels are SPEAKERS in the file. |\n| `click-zoom` Click zoom | 9:16 | screen | 4 | Highlight one button or control. Label 2–5 words. The editor in the window is a stand-in: redraw `editor` with the real screen and move BTN to the control (keep it in the top half so the leader stays short). |\n| `desktop-follow` Desktop follow | 9:16 | screen | 6 | Show a two-click desktop flow in a portrait post. Label 2–5 words, [brackets] mark the orange words. The app is a stand-in 1440 × 1000 dashboard: redraw `app` with the real product and move CLICKS to its targets (the camera follows them). |\n| `device-stack` Device stack | 9:16 | screen | 5 | Say the product works everywhere. Title 2–4 words ([brackets] mark orange words), detail one short line. Both screens come from `product` (landscape and portrait layouts of one stand-in dashboard): redraw it, or draw screenshots into the two screen rects. |\n| `phone-recording` Phone recording | 9:16 | screen | 5 | Show a mobile app in use. Title 2–4 words. The screen is a stand-in task list: put assets/screen.jpg (portrait, about 9:19) in the project to show a real recording frame, or redraw `phoneScreen`; the tap lands on the second row (TAP_ROW). |\n| `type-input` Typed input | 9:16 | screen | 4.5 | Show a prompt or search being typed and answered. Query up to ~60 characters (two lines). The three result rows are stand-ins in RESULTS: replace them with what the real product returns. |\n| `before-after` Before and after | 9:16 | explain | 5 | Contrast the old way with the product. Write each label as \"KICKER: HEADLINE\" (the part after the colon is the big line, 1–3 words). The twelve steps and the checked line are STEPS and RESULT in the file. |\n| `callout` Callout | 9:16 | explain | 4.5 | Point at one feature. Title 1–3 words ([brackets] mark orange words), detail one short sentence. Over a film picture (backdrop false) the whole frame dims around FOCUS and the label sits on a white panel; move FOCUS to the element in your picture. |\n| `three-steps` Three steps | 9:16 | explain | 7 | Explain a 3-step flow. Step titles 2–4 words, details one short line. The window shows a stand-in screen: put assets/step-1.jpg … step-3.jpg in the project (or redraw `screen`) to show the real product. |\n| `review-cards` Review carousel | 9:16 | proof | 6.5 | Social proof for a post: three reviews, one per line as \"quote | name | role\", quotes up to ~70 characters. Fictional people by default; use real reviews only with permission. |\n| `stat-count` Numbers table | 9:16 | data | 4.5 | Three key figures with short labels, one per line as \"value | label\" (a unit or suffix may follow the value: \"4.9/5\", \"3 MIN\"). Values up to 6 digits, labels under ~20 characters; the headline is one line of up to ~22 characters. |\n| `cta-endcard` Call to action | 9:16 | end | 5 | Last 3–4 s of a post: a call to action of 1–3 short words (mark one with [brackets]) and a name to search for, under ~16 characters. The picture above the sheet is a stand-in: put assets/endcard.jpg in the project, or play the template with backdrop: false over your own last shot. |\n| `logo-tagline` Logo and tagline | 9:16 | end | 5 | Closing logo of a 9:16 post. Brand 1–2 words, tagline under ~28 characters with one [marked] phrase. The N mark is a fictional stand-in: redraw `mark()` with your own logo as two or three flat strokes that grow in order. |\n| `push-transition` Vertical push | 9:16 | transition | 2.6 | Between two full-frame pictures or screens of a 9:16 film. Titles 1–4 words. The pictures are stand-in product screens: put assets/from.jpg and assets/to.jpg in the project (or redraw `picture`) so the push carries your own last and next shot. |\n| `product-hero-wide` Product hero | 16:9 | hook | 5 | Opening of a landing-page loop, Product Hunt or YouTube demo. Name 1–2 words, tagline under ~40 characters, button labels 1–3 words. The window is a stand-in: redraw it in `appUI` or draw a screenshot into the same 1400 × 860 card. |\n| `title-wide` Wide headline | 16:9 | hook | 5 | Opening statement for a landing page, YouTube or a talk: two short lines (under ~26 characters each), the [bracketed] words in the spectrum. Night or neon ground reads best. |\n| `caption-subtitle-wide` Wide subtitle | 16:9 | caption | 4 | Subtitle or pull quote over footage in a landscape film: one sentence (wraps to two lines past ~45 characters) and a speaker line. Play it with `backdrop: false` over your own picture; the product screen underneath is only a stand-in. |\n| `name-lower-wide` Wide lower third | 16:9 | caption | 4 | Name and role over an interview or talking-head shot in a landscape film. Name 1–3 words, role under ~40 characters. Play it with `backdrop: false` over your footage; the soft-focus speaker underneath is only a stand-in. |\n| `ai-chat-stream-wide` AI chat stream | 16:9 | screen | 6 | Show an AI feature answering. Prompt one line (under ~44 characters), reply 1–3 sentences (under ~190 characters). The chat window is a stand-in: restyle `chat()`; never use a real AI brand name or logo. |\n| `browser-window-wide` Browser | 16:9 | screen | 5 | Open a website or web-app demo. Keep the URL short (under ~24 characters, no https://). The page is a stand-in: redraw `page()` (1400 × 764 below the bar) or draw a screenshot there; avoid real browser or brand UI. |\n| `laptop-frame-wide` Laptop | 16:9 | screen | 5 | Show a desktop product in context. Title under ~26 characters; it breaks after a comma, and [bracketed] words (else the last line) take the spectrum. The screen is a stand-in: redraw `screen()` or draw a 1400 × 860 screenshot into it. |\n| `multi-window-wide` Multi-window | 16:9 | screen | 5 | Real-time sync or collaboration. Title under ~28 characters; [bracketed] words (else the last word) take the spectrum. The board is a stand-in: rename the columns and cards in `COLS`, or redraw `board()`. |\n| `terminal-wide` Terminal | 16:9 | screen | 5 | CLI, SDK or developer-tool launch. One command under ~34 characters. Output and success copy live in `OUTPUT` and `SUCCESS`; keep them to four short lines and one line. Neon ground reads best. |\n| `before-after-wide` Before and after | 16:9 | explain | 5 | Contrast the old way with the product in a landscape film. Write each label as \"Kicker: Headline\" (headline 1–3 words, under ~16 characters; [brackets] take the spectrum). The twelve steps and the result line are STEPS and the Result param; a full-frame explainer, not an overlay. |\n| `callout-wide` Callout | 16:9 | explain | 4.5 | Point at one feature of a product window. Title 1–3 words ([brackets] take the spectrum), detail one short sentence. With backdrop false the window is skipped and the frame dims around FOCUS over your own picture; move FOCUS (a rect in the 1400 × 860 window) to your element, or redraw the window in `appUI`. |\n| `feature-grid-wide` Feature grid | 16:9 | explain | 5.5 | Show what a product does in one frame: 3–6 features, one per line as \"Name: detail\" (name 1–3 words, detail under ~38 characters), headline under ~32 characters with [brackets] for the spectrum. Draw your own icons in `icon()` (one per card, by index). |\n| `logo-wall-wide` Logo wall | 16:9 | proof | 4 | Social proof in a landscape film or a talk. The twelve names are fictional stand-ins in `NAMES`: replace them with real customers you may name (or draw their logos inside the chips, keeping the chip and dot). The first number in the headline takes the spectrum. |\n| `growth-bars-wide` Growth bars | 16:9 | data | 5 | A single growth story (revenue, users, speed) in a landscape film or a talk. The twelve monthly values are constants in `DATA` and the end label in `LABEL`; keep the headline under ~34 characters. It is a mood chart, not an exact one: no axis values. |\n| `stat-count-wide` Wide numbers | 16:9 | data | 4.5 | Traction or results in a landscape film or a talk. Figures are the `stats` param, one \"value | label\" per line (\"4.9/5\", \"3 min\": the text after the number is its unit): keep three, labels under ~18 characters, values up to six digits. Digits sit in fixed slots, so numbers do not jitter while they count. |\n| `bullet-points-wide` Morphing points | 16:9 | slides | 6 | Three to four short points for a talk, a pitch or a product walkthrough, one per line (each 1–3 words, under ~18 characters); a fifth point reuses the pill. The shapes read as write (a field), tune (a slider), pulse (a wave) and present (play), so order the points to match. |\n| `chapter-title-wide` Chapter title | 16:9 | slides | 3.5 | Section divider for a talk, a course or a long demo: number 1–3 characters, title under ~28 characters, subtitle under ~50. Long titles shrink to fit. Neon or night reads best. |\n| `quote-wide` Quote pill | 16:9 | slides | 5.5 | One-sentence quote or principle for a talk, a launch film or a testimonial: under ~60 characters reads on one line, up to ~120 wraps to two. Leave the quote marks out; the template adds them. Neon or night reads best. |\n| `cta-endcard-wide` Website end card | 16:9 | end | 4.5 | Closing call to action of a landscape film or a talk: a headline under ~28 characters, an address under ~24 and a button label of 1–3 words. The QR pattern is a stand-in that does not scan: replace the modules in `qrCard()` with your real code image (load it in `setup`, draw it into the same square). |\n| `logo-tagline-wide` Logo and tagline | 16:9 | end | 4 | Closing logo of a landscape film. Brand 1–2 words, tagline under ~40 characters. The mark is a fictional stand-in: redraw `markPath()` (a centre line, traced then filled) and `ribbon()` with your own logo, keeping the trace → fill → letters order. Night or neon reads best. |\n| `push-transition-wide` Push transition | 16:9 | transition | 2.4 | Cut between two landscape shots. The pictures are stand-ins: draw the outgoing shot in `pictureA` and the incoming one in `pictureB` (each is already offset). With backdrop false only the light edge and its shade are drawn. Titles under ~30 characters; the template ends on picture B, so the next shot starts from it. |\n<!-- catalog:end -->\n",
|
|
23
|
+
"references/three-d.md": "# 3D layers with Three.js\n\n[three.ts](__REPOSITORY__/extras/three/three.ts) renders a [Three.js](https://threejs.org/) scene as a layer inside a normal Mografy frame: draw 2D backgrounds first, then the 3D layer, then type and overlays. [three-demo.ts](__REPOSITORY__/extras/three/three-demo.ts) is an eight-second tour: a device with a drawn screen orbits into a hero pose among floating shapes.\n\n## When to use it\n\nUse a 3D layer when the brief needs real depth: objects that turn and catch light, product or device models (glTF / GLB), orbiting cameras, depth between layers, reflective or glassy materials. For flat cards, type, UI, flips and parallax, stay in 2D Canvas with the built-in components and `cinema.ts`; they are lighter, sharper for text, and export faster.\n\n## Add to a project\n\nThe helper and library are an optional extra, not part of the installed template. If the project already has `scenes/three.ts` and `assets/three.module.js`, read and reuse those local copies. Otherwise copy from the current Mografy checkout (`extras/three/`) or download from GitHub:\n\n```sh\nnpx mografy add three projects/<name>\n```\n\n`npx mografy add` copies from this checkout's `extras/` folder, or from GitHub when it is missing, keeps any project file that differs from the extra (`--force` replaces it), and prints the import line. It copies `scenes/three.ts`, `assets/three.module.js` and its licence. Without the `mografy` command, download the same files from `https://raw.githubusercontent.com/mografy/mografy/main/extras/three/`.\n\n`three.module.js` is a single minified Three.js r186 bundle (about 0.8 MB, MIT) that also exports `GLTFLoader`, `RoomEnvironment` and `RoundedBoxGeometry`. It lives in `assets/` because scene modules may import only project sources and `@mografy/runtime`; `prepareStage` loads it at runtime from the project. Import the helper locally (`import { prepareStage, stage, orbit } from './three.js'`). Copy `three-demo.ts` too only when the user wants the tour.\n\n## Contract\n\nThe scene contract still holds; Three.js only adds where state lives.\n\n- **Build in `setup`, pose in `renderFrame`.** Create every mesh, geometry, material, light, texture and loaded model inside `prepareStage`'s `build` callback and store the stage in `ctx.assets`. In `renderFrame`, only set properties (positions, rotations, scales, colours, opacity, camera) from `time` and params. Creating Three.js objects in `renderFrame` throws, because their ids use `Math.random`.\n- **Set everything you animate, every frame.** The scene graph persists between frames, so a property that is only set in some time ranges keeps a stale value after seeking. Write each animated value from `time` on every call, as with any Mografy pose.\n- **No animation mixers, clocks or physics.** Do not use `AnimationMixer.update(delta)`, `Clock` or simulation steps. For a glTF animation clip, set `mixer.setTime(time)` from absolute time.\n- **Randomness** comes from `ctx.random()` in setup or `ctx.noise()` per frame, never `Math.random`.\n\n## API\n\n| Helper | Use |\n| --- | --- |\n| `prepareStage(ctx, build, { fov?, width?, height?, antialias?, toneMapping?, exposure?, library? })` | In `setup`: load Three.js, create the WebGL layer, and call `build({ THREE, scene, camera, renderer, setup })`. Whatever `build` returns becomes `stage.objects`. The camera starts at (0, 0, 10) looking at the origin. Tone mapping defaults to ACES filmic. |\n| `stage(ctx, stage, pose, { x?, y?, width?, height?, alpha? })` | In `renderFrame`: `pose({ THREE, scene, camera, objects })` sets this frame, then the layer renders at output resolution and is drawn into the frame (default: covering the canvas). |\n| `orbit(camera, yaw, pitch, distance, target?)` | Place the camera on a sphere around a target, in radians. Ease yaw, pitch and distance for camera moves. |\n| `studioLight(build, intensity?)` | Soft studio reflections (RoomEnvironment) so metal, glass and clearcoat read well without an HDR file. Add one key and one rim `DirectionalLight` for shape. |\n| `loadModel(build, path)` | Load an uncompressed glTF / GLB from `assets/`; returns `{ scene, animations }`. Add `scene` to the stage; for a clip, create an `AnimationMixer` in setup and call `mixer.setTime(time)` in the pose. Draco or Meshopt compressed files are not supported. |\n| `canvasTexture(THREE, width, height, draw)` | Draw a 2D canvas once in setup and use it as a texture: screens, labels, posters. It uses the project's registered fonts. |\n\n```ts\nexport async function setup(ctx: SetupContext) {\n ctx.assets.stage = await prepareStage(ctx, b => {\n const { THREE, scene } = b;\n studioLight(b);\n const cube = new THREE.Mesh(new THREE.RoundedBoxGeometry(2, 2, 2, 6, 0.2), new THREE.MeshPhysicalMaterial({ color: 0x7c5cff, roughness: 0.3, clearcoat: 1 }));\n scene.add(cube);\n return { cube };\n });\n}\n\nexport function renderFrame(ctx: FrameContext, time: number) {\n const s = ctx.assets.stage as Stage<{ cube: ThreeModule }>;\n stage(ctx, s, ({ camera, objects }) => {\n orbit(camera, 0.3 * Math.sin(time * 0.5), 0.15, 8);\n objects.cube.rotation.y = ease.inOutCubic(pr(time, 0, 2)) * Math.PI;\n });\n}\n```\n\n## Direction\n\n- Keep one hero object and a motivated camera: a slow orbit, a push-in, or a reveal swing that settles. Key the 3D camera on the film's shot table with `keys` (or read the 2D film camera's `cameraPath` so both move as one), and do not let objects drift during reading holds.\n- Put headlines and subtitles in 2D after the 3D layer, not on 3D surfaces; Canvas text is sharper and easier to edit. Use `canvasTexture` for text that belongs to an object, such as a phone screen.\n- Leave layout room for type: frame the object with the camera target and distance rather than by moving the object off-centre.\n- In portrait (1080 × 1920) the layer follows `ctx.width` / `ctx.height`; pull the camera back or narrow the composition so objects fit the width.\n\n## Rendering and review\n\n- 3D renders with WebGL 2 in the player and in exports, so MP4, WebM, Lottie and SVGA all include it. Exports render each sample on the GPU when Chromium has one; on machines without a GPU, Chromium falls back to software rendering, which is correct but slower.\n- Review the camera's extreme poses and the first frames of a reveal, check that objects never clip the frame edge or the type, and seek out of order to confirm every animated property is set from time.\n\n## Cost\n\n- A stage costs a WebGL render plus a copy into the 2D frame on every frame it is drawn. Use one stage per film and reuse it across shots; skip `stage()` entirely while the 3D layer is fully hidden.\n- Size the layer to the area it covers (`width`, `height`, `x`, `y`) instead of the full frame when the object is small.\n- Keep geometry and materials built in `setup`; per frame, only set transforms and uniforms. Large particle fields belong in one `Points` geometry whose positions a shader or one buffer update moves, not in thousands of meshes.\n- **Opening cost** is shader compilation and texture upload, paid once in setup and again whenever the shader set changes:\n - Never toggle a light's `visible`, add or remove lights, or switch `castShadow` during the film: a different light count recompiles every material, a pause of seconds on the first frame of that shot. Fade a light with `intensity` (0 when off) instead; keep `castShadow` fixed.\n - End the `build` callback with `await renderer.compileAsync?.(scene, camera)` (make `build` async) so shaders compile in parallel during setup rather than on the first frames.\n - Create one texture for identical objects and share it; keep repeating textures at the size they are seen (256–512 px for small props). Set `generateMipmaps = false` on canvas textures that are redrawn during the film.\n - Move objects offstage instead of toggling `visible` when they leave for a few shots, if toggling changes what is compiled.\n- Bloom and glow around 3D objects go through the runtime's `bloom` on the 2D side, or a single post pass; see [performance.md](performance.md). Run `npx mografy check` after adding the stage and compare the frame cost with and without it.\n",
|
|
24
|
+
"references/ui-stage.md": "# Product UI on a stage: simplified, framed, caused\n\n[stage.ts](__REPOSITORY__/extras/stage/stage.ts) makes short product UI films: hero loops for a landing page, feature cards, a phone moment for social, a dashboard insight. It is built around one sentence:\n\n**It reads as a real product, simplified to what the viewer needs, framed with intent, and every motion has a cause.**\n\nUse it when the brief is \"show how it feels to use\" in one to three actions, 4–12 s, often looping. Use [product-walkthrough.md](product-walkthrough.md) instead for a longer tour through several screens (4–8 steps, cards that grow into each other), and both together when a walkthrough needs a stage-style hero shot.\n\n## Five ways faux UI fails\n\nAgents drift toward the first one. Name the failure when you review a frame. To see each one next to the good version, open `stage-invoices` and switch its **Variant** parameter (`too-much`, `too-little`, `boxed`, `flat`, `bland`); hold your own stills against the pair you are closest to.\n\n| Failure | Looks like | Fix |\n| --- | --- | --- |\n| **Too much** | Real words in every cell, packed tight, every column filled | Only story strings are words; the rest are placeholder lines (`role: 'filler'`, `bar`, `bars`) |\n| **Too little** | A wireframe: grey boxes that do not read as any product | Keep the real chrome, the brand mark, real nav labels and one real number |\n| **Boxed** | The whole app shrunk into a floating card, like a pasted screenshot | `pin()` the window to a corner so it runs off two edges; decide the crop first |\n| **Flat** | Everything has the same weight | One focal element per beat; everything else quieter (mute type, lines, `recede`) |\n| **Bland** | The brief's brand never shows | A look and its tokens: the product's accent, radius, font, light or dark |\n\n## Workflow\n\nMost of it happens before any code. Write the answers at the top of `storyboards/storyboard.md`.\n\n1. **Medium.** Still or animation, loop or play once, where it sits (hero, feature card, social 9:16) and the design size: 1280 × 720 for 16:9, 720 × 1280 for 9:16. `withStage(c, s, draw, ctx.width / designWidth)` scales it to the film, so the kit's sizes read as real UI at about 1.5×.\n2. **Look.** `look('light' | 'dark' | 'blueprint' | 'minimal', overrides)`: one accent or mono; the chrome the product really has (`chrome: 'app' | 'browser' | 'tabs' | 'tahoe' | 'card'`), its real icons. Map the product's own tokens (accent, radius, font) onto the look instead of inventing colours.\n3. **Story.** How it feels to use, a flow through the app, or what the system does on its own. Three to five beats, one sentence each. The last beat undoes the first **on screen, with a cause** (an Undo, a back tap, a lock button), so a loop has no seam.\n4. **Example.** Copy the closest reference film (`npx mografy add <name> <folder>`, table below) and make it the brief's product: what is cropped, what overlaps what, one gutter. Copying an example that runs a window off the edge works far better than a rule that says to.\n5. **Screen.** List the few real strings the story needs; everything else becomes lines. A dashboard needs about six words, an inbox one real row.\n6. **Choreograph.** The script decides the timing: holds before actions, overlapping changes, one camera push at most per beat, a loop that ends where it began.\n7. **Rehearse.** `npx mografy check --motion`, `npx mografy review` with transition strips over every action and the loop seam, then hold your stills next to the example's.\n\n## Reference films\n\n| Film | Shows | Start from it for |\n| --- | --- | --- |\n| `stage-invoices` | Web app window off two edges, a flight into a rolling total, camera push, toast Undo; four looks; the five failure variants | Any web app hero |\n| `stage-phone` | 9:16, a cropped phone driven by taps, a notification that grows into the thread, typing | Mobile and social clips |\n| `stage-dashboard` | Dark, the newer macOS window, hover tooltip, one annotation, camera push | Analytics, one insight |\n| `stage-bento` | A bento section planned as one picture: one UI tile, a stat, an object, a diagram; no cursor | Homepage feature grids |\n| `stage-calendar` | `drag()`: lift, a target that jumps cell to cell, landing, staggered confirmations | Anything dragged: cards, slots, files |\n| `stage-upload` | Blueprint diagram, packets per hop, `ui.callout` annotations; no cursor | API docs, architecture, \"how it works\" |\n| `stage-command` | Keyboard only: keycaps as the cause, a filtering palette, ⌘Z | Command palettes, shortcuts |\n| `stage-checkout` | Browser with tabs, typing, a spinner, a check that draws | Forms, sign-up, payments |\n| `stage-request` | Web and phone in one frame, `recede`, cursor and taps together | Anything that crosses devices |\n| `stage-snooze` | Quiet card chrome, hover actions, a menu, a row leaving and the list closing up | Small feature cards |\n\n## Build\n\n```ts\nimport { play, wait, set, click, tap, type, drag, move, focus, cursor, mark, withStage, createKit, look, pin } from './stage.js';\n\nconst W = 1280, H = 720, START: Point = [880, 640];\nconst initial = { paid: false, total: 18400, toast: false }; // everything that changes is state\nconst WIN = pin([W, H], [1260, 760], 'tl', [92, 72]); // crop first: runs off right and bottom\nconst layout = (s: typeof initial) => ({ markPaid: [1006, 465, 128, 38], total: [354, 290, 220, 58], ...(s.toast ? { undo: UNDO } : {}) });\n\nconst show = play(initial, [\n mark('Mark paid'), wait(0.9),\n click('markPaid', { paid: true }), // the change lands on the press\n wait(0.42), set({ total: 22600, toast: true }),\n focus('total', 1.5, 1.1), wait(2.1), focus(null, 1, 1),\n mark('Undo'), wait(0.5),\n click('undo', { paid: false, total: 18400, toast: false }), // the cause of the reset\n wait(0.5), move(START), wait(0.7),\n], { size: [W, H], layout, start: START, loop: true, cursors: { markPaid: 'pointer' } });\n\nexport const meta = { width: 1920, height: 1080, duration: show.duration, fps: 30, background: '#efeeec', shots: show.shots, loop: true };\n\nexport function renderFrame(ctx: FrameContext, time: number, p: Values) {\n const ui = createKit(look('light', { accent: p.accent })), s = show.at(time);\n ctx.withCanvas(c => {\n ui.backdrop(c, ctx.width, ctx.height);\n withStage(c, s, g => {\n ui.window(g, WIN, { chrome: 'app', sidebar: 200 }, (w, body) => { /* draw from s.value / s.on / s.is / s.num */ });\n ui.pointer(g, s.cursor);\n }, ctx.width / W);\n });\n}\n```\n\n### Script steps\n\n| Step | Takes time | Use |\n| --- | --- | --- |\n| `wait(s)` | yes | Holds: before the first action (0.6–1 s), after a payoff (1.5–2.5 s) |\n| `click(name, then?)` | yes (move by distance + 0.1 s dwell + hold) | A cursor click; `then` is applied as the press lands |\n| `tap(name, then?)` | yes | Phones: no travelling cursor, a press dot appears |\n| `drag(from, to, then?)` | yes | Cards and calendar slots; the cursor closes while carrying |\n| `type(key, text, cps?)` | yes | Typing into a state string (22 characters per second) |\n| `move(target)` | yes | Back to the start, or to a hover target |\n| `set(values, { duration?, curve? })` | no | A change with no click (a reply arrives, a total updates after a flight) |\n| `focus(name \\| null, zoom?, duration?)` | no | Camera push in on a rect and back; runs beside the next steps |\n| `cursor(visible)` | no | Hide the cursor for a beat that runs by itself |\n| `mark(title)` | no | Starts a shot for `meta.shots` and review |\n\nCursor moves take 0.3–0.95 s by distance on a shallow arc, like a hand; never time them by hand. `layout(state)` is the single source of rects: the cursor aims at them, the camera focuses on them, and the drawing should use the same constants.\n\n### Sampling state in renderFrame\n\n`s.value(key)` the current value; `s.on(key)` / `s.is(key, v)` 0..1 presence that springs in (0.42 s) and eases out (0.28 s), so parts move instead of popping; `s.num(key)` a number springing between values; `s.pair(key)` for `ui.roll`; `s.since(key)` seconds since the last change, for one-off motions such as a flight; `s.cursor` (`x`, `y`, `press`, `shape`, `visible`, `touch`); `s.camera`. While a `drag()` carries something, `s.cursor.dragging` is true and `s.cursor.lift` (0..1) rises and lands: draw the carried object at the cursor, scaled and tilted by `lift`, and a ghost at home (`stage-calendar`). Taps never move the cursor; their press shows at `s.cursor.tx`, `ty`. `play(..., { pointer: false })` hides the cursor for a film about what the system does on its own.\n\n### Kit\n\n| Part | Use |\n| --- | --- |\n| `look(name, overrides)`, `LOOKS` | Tokens: backgrounds, window, sidebar, surface, ink / mute / faint, line, accent, bar, shadow, radius, font, `words` |\n| `ui.window(c, rect, { chrome, url, tabs, sidebar, recede }, draw)` | The chrome follows from what you pass; `tahoe` is the newer macOS window (large lights, floating sidebar, tall toolbar). `draw` gets `body.content` and `body.sidebar`. Never put an address bar on a native Mac app |\n| `pin(size, box, corner, inset)` | A rect pinned to a corner that runs off the opposite edges |\n| `ui.nav`, `ui.text`, `ui.bar`, `ui.bars` | Sidebar with brand and real labels; text that becomes a line when the look keeps fewer words; placeholder lines |\n| `ui.button`, `ui.badge`, `ui.field`, `ui.menu`, `ui.avatar`, `ui.icon`, `ui.toast` | Controls; pass `press: s.cursor.press` to the pressed one, `k: s.on(...)` to anything that enters |\n| `ui.roll(c, from, to, k, x, y, o)` | A number that rolls only the digits that changed |\n| `ui.fly(c, fromRect, toRect, k, draw)` | An object flying into a slot on a shallow arc, landing with a settle |\n| `ui.phone(c, rect, draw, { time, dark, island })`, `ui.lockScreen`, `ui.notification` | Phones from real proportions; pass a rect that crosses the frame edge so the phone is cropped |\n| `ui.shadow`, `ui.card` | Layered shadow (hairline, mid, long soft), cheap under camera zoom; a surface card with hairline and optional lift |\n| `ui.key(c, x, y, label, { press })` | A keycap; draw keycaps outside the camera when keys are the cause (`stage-command`) |\n| `ui.callout(c, from, to, label, k, { side })` | An annotation: a dashed leader that draws first, then a one-line label |\n| `ui.pointer(c, s.cursor, { style })` | `arrow` (default), `large`, `circle`; shapes change over named rects (`cursors` option) |\n\n`words` in a look: `story` (default) draws `ui` and `keep` text, turns `filler` text into lines; `lines` (minimal) turns everything but `keep` into lines; `all` draws every word; `none` is a wireframe, the failure *too little*, kept only for comparisons.\n\n## Rules that hold up\n\n- **Crop first.** Decide what is cut off before drawing anything; do not build what will not be seen. Windows run off two edges; phones off the bottom or a side, never shown whole.\n- **Few words.** Real strings only where the story is. A full inbox reads as full with one real row and lines for the rest.\n- **One accent, real chrome, real icons.** No fake iOS status bar on a desktop scene; no browser chrome on a native app.\n- **Every change has a cause.** A click, a tap, a drag, a typed character, an arriving message. Nothing changes by itself unless the story is \"what the system does on its own\"; then hide the cursor (`cursor(false)`).\n- **Hold the payoff.** 1.5–2.5 s on the result; holds before actions read as intention.\n- **One camera move per beat**, in on the thing that changed, back out before the next action.\n- **Short transitions.** Most parts enter in 0.3–0.5 s; containers and flights 0.6 s; overshoot only on pops and landings.\n- **Loops end where they began.** `play(..., { loop: true })` refuses a script whose final state, cursor or camera differs from the start; add `loop: true` to `meta` so `npx mografy check --motion` compares the last frame with the first.\n- **Text must fit.** `ui.text` with `max` throws when copy overflows its box (the error names the string and both widths); shorten it, widen the box, or pass `fit: 'ellipsis'` on purpose.\n- Invent the product, people and figures, as in the reference films. Never draw a real company's interface, mark or customer data.\n\n## Review checklist\n\n- [ ] The first frame says which product this is in one glance (chrome, brand, one real number or row).\n- [ ] At most one focal element per beat; everything else is quieter.\n- [ ] Count the words: are they all needed by the story?\n- [ ] The window or phone is cropped by the frame; nothing floats whole in the middle.\n- [ ] Each change in a transition strip follows a visible cause.\n- [ ] `npx mografy check --motion`: no jumps, hard starts or stops, and \"loop seam clean\" for a loop.\n- [ ] Watch it at phone size (a 9:16 export or a 360 px wide preview): the story still reads.\n",
|
|
25
25
|
"references/video-compression.md": "# Compress an exported video\n\nUse this workflow when a finished render is too large to upload or share, or when the user requests a smaller video. Work from the actual exported video (normally in the project's `renders/` folder). Scene edits, a new render, and a storyboard are unnecessary for compression alone. This helper outputs H.265 MP4 (tagged `hvc1`) by default, or H.264 with `--codec h264`; it does not compress Lottie JSON or SVGA packages, and does not preserve transparency or HDR. Use H.264 when the file goes into a website `<video>`, to Firefox users or to Windows PCs without HEVC support.\n\n## Run the bundled Python helper\n\nRequires Python 3.10+ and FFmpeg with `libx265` (or `libx264` for `--codec h264`), AAC, and `ffprobe` on PATH; the helper stops with a clear message when libx265 is missing. No pip packages are needed. On macOS, `brew install ffmpeg` supplies FFmpeg and ffprobe. The helper accepts `--ffmpeg` / `--ffprobe` or `MOGRAFY_FFMPEG` / `MOGRAFY_FFPROBE` executable overrides; it does not automatically discover Mografy's bundled FFmpeg. If a dependency is absent, report it and use the environment's normal installation process.\n\nResolve `../scripts/compress-video.py` relative to this reference's local Skill directory, not the animation project's directory. From the owning repository root, these commands invoke the shared Skill copy (quote paths containing spaces):\n\n```sh\n# Balanced quality, same dimensions and frame timing; keeps audio when present.\npython3 .agents/skills/mografy/scripts/compress-video.py \"projects/my-animation/renders/film.mp4\"\n\n# Better detail retention; optionally trade encoding time for compression.\npython3 .agents/skills/mografy/scripts/compress-video.py \"projects/my-animation/renders/film.mp4\" --crf 20 --preset slow -o \"projects/my-animation/renders/film-share.mp4\"\n\n# Fit a landscape video within 1280 x 720 without upscaling or cropping.\npython3 .agents/skills/mografy/scripts/compress-video.py \"projects/my-animation/renders/film.mp4\" --max-width 1280 --max-height 720\n\n# Target a 10 MB upload limit (decimal MB), using two-pass encoding.\npython3 .agents/skills/mografy/scripts/compress-video.py \"projects/my-animation/renders/film.mp4\" --target-mb 10\n```\n\nThe maintained source is [scripts/compress-video.py](__REPOSITORY__/scripts/compress-video.py); `pnpm sync:skills` copies it into the shared Skill's `scripts/` directory. Edit the repository source, then sync, rather than editing the generated copy. For an animation outside this repository, use the absolute path to the loaded Skill's helper and the actual input video.\n\n## Choose settings and verify\n\n- Default: H.265, CRF 23 on the H.264 scale, medium preset, AAC 128 kbps, original frame timing and dimensions (rounded down to even pixels). It preserves the first video and first audio stream; additional streams, selectable subtitles, and attachments are omitted. Burned-in captions remain visible.\n- CRF 18–20 keeps more detail; 26–28 trades detail for smaller files. CRF is lossy and does not guarantee a file size or reduction. `--crf` and `--target-mb` are mutually exclusive.\n- Use `--target-mb` for a stated upload limit. The budget reserves space for audio and container overhead, then checks actual bytes. An impossible budget or oversize result fails without publishing an output; report that failure rather than promising the limit was met.\n- Change resolution only when appropriate to the request. For portrait 720p, use `--max-width 720 --max-height 1280`. Both caps preserve aspect ratio without cropping or upscaling. Small text and fine artwork may need a higher resolution or lower CRF.\n- Audio stays unless `--no-audio` is explicitly appropriate; `--audio-kbps 96` can reduce its budget. Do not silently remove narration or music to hit a limit.\n\nThe helper never overwrites any existing file or the original export. It defaults to `<stem>-compressed.mp4` beside the input; pass a new `-o` path for another attempt. It encodes in a temporary folder, verifies duration/audio and decodes the result before publishing. Failed or cancelled operations clean up temporary output. If the candidate is larger than or equal to the source, it is discarded and stdout JSON reports `status: \"skipped\"`, `output: null`, and a reason; no compressed file exists in that case.\n\nRead the stdout JSON and report the actual output path, original/result bytes, and percentage saved. For a skipped result, explain that the original is already smaller with these settings. Inspect the compressed video for text legibility, banding, motion artifacts, and audio sync before delivery; automated decoding does not prove visual quality. Keep the original as the master. Do not automatically replace a website asset or upload a file unless that is part of the user's request.\n\nOption semantics: [FFmpeg documentation](https://ffmpeg.org/ffmpeg.html), [libx265](https://ffmpeg.org/ffmpeg-codecs.html#libx265) and [libx264 encoder options](https://ffmpeg.org/ffmpeg-codecs.html#libx264_002c-libx264rgb).\n",
|
|
26
|
-
"SKILL.md": "---\nname: mografy\ndescription: Make, edit, review and export Mografy Canvas animations (projects with mografy.json), plan their storyboards and scores, and compress exported videos with the bundled Python helper; also develop the Mografy repository. Use when a folder has mografy.json, the Mografy MCP tools are connected, or the user asks for a motion graphic, product demo from screenshots, how-to or tutorial clips, teaser, logo reveal, explainer, paper theatre (紙劇場、紙偶、定格), or social video, or says 做動畫、動態影片、宣傳片、產品示範、操作教學動畫、分鏡、配樂、圖層、時間軸、設計系統、匯出 MP4、壓縮影片.\n---\n\n# Mografy\n\nMografy films are TypeScript scene modules drawn on a Canvas as a pure function of time, previewed in the Mografy player and exported to video, Lottie or SVGA. This file holds the hard rules, the vocabulary, the tools, which reference to read for which job, and the steps. Details live in `references/`; read a reference when its step comes up, not before.\n\nPrecedence: the user's request in this conversation, then the project's `style.md`, then a local skill whose folder ends in `-ref` under `.agents/skills/` (read its `SKILL.md` after this one when the checkout has one), then the defaults here and in [references/taste.md](references/taste.md). Nothing overrides **Never**, the **Contract** or the **Quality floor**.\n\n## Never\n\n- Put animation, layout or shot descriptions in `mografy.json`. It holds settings, audio, colour swaps and review times; animation lives in scene modules, because the server never evaluates scene code.\n- Read a clock, keep state between frames, or use unseeded randomness, GSAP, SVG scene layers or resvg. The player seeks in any order, and `mografy check` renders each time twice to catch state.\n- Set `ctx.filter` around many draws or create a canvas in `renderFrame`. Each costs a full pass per draw or per frame; use `blurLayer`, `blurText`, `bloom`, `layer` and `buffer`.\n- Write `scenes/timeline.json` or `colors` in `mografy.json` by hand to animate or restyle. They hold the user's own edits from the editor; change the scene instead ([layers.md](references/layers.md)).\n- Rename or remove a layer `id` that has edits in `scenes/timeline.json`: the user's work on it would be orphaned.\n- Operate the user's website or account unless they asked you to and gave you a test account ([how-to-film.md](references/how-to-film.md)); otherwise work from screenshots the user provides. Never show real customer data or a working private link; use invented demo data.\n- Copy another brand's copy, marks or music, or edit the films in `examples/` (they are the reference other agents read). Copy one with `mografy add <name>` (showcase films download the same way) and change the copy.\n- Export, or overwrite a file in `renders/`, unless the user asks for a file.\n\n## Terms\n\n- **film**: the whole animation. **scene**: the module that draws it (`scenes/main.ts` and its imports).\n- **shot**: one idea or composition, one row of the shot table. **beat table**: `beats([...])`, the single source of shot times, `meta.shots`, layer windows and review times.\n- **handoff**: the object that ends one shot and starts the next. **hold**: time when nothing moves so the viewer can read. **stop frame**: a shot's settled frame, shown in review.\n- **layer**: one part the user can retime, hide, copy, rename, lock or reorder in the editor's timeline, declared with `timeline([...])`. **edits**: the user's changes to layers, in `scenes/timeline.json`; they win over the declarations. **shot layer**: the layer per shot the build gives a scene that declares none.\n- **card**: one UI panel or piece of content drawn in the film's world. **extra**: an optional helper module added with `mografy add <extra>`. **template**: a ready-made beat added the same way. **reference film**: a finished film to learn from: installed in `examples/`, or a showcase film on https://www.mografy.app/showcase, downloaded with `mografy add <name>`.\n\n## Tools\n\nDrive Mografy with the `mografy` command in a shell, or with the Mografy MCP tools when the host has connected `mografy mcp`; both act on the same project, and while the player has it open they work through the player, so the user sees each change. With the MCP tools, change a scene through `write_source` (it compiles and trial-renders first and writes nothing on failure), look with `render_frame` and `review`, and check with `check` (`motion: true`). [references/mcp.md](references/mcp.md) maps each tool to its command. Open the player with `mografy dev` or `open_player`.\n\n## Choose the path\n\nFind the job, read its references, start where it says. When a request fits more than one row, read every matching reference; when it fits none, follow the steps below with the **New film** references.\n\n| Job | Read | Start from |\n| --- | --- | --- |\n| **Fix or tweak** an existing film: copy, one timing, an asset, an export | [scene-authoring.md](references/scene-authoring.md); also [layers.md](references/layers.md) when the project has `scenes/timeline.json` or `colors` | The existing scene; no new concept or storyboard |\n| **New film** from a brief, or redesigning a film's motion | [film-architecture.md](references/film-architecture.md), [motion-design.md](references/motion-design.md), [taste.md](references/taste.md), [examples.md](references/examples.md) | `mografy add film-starter <folder>`, or the closest reference film from examples.md |\n| **Product film** from an app's screens | The row in **Product films** below | As that row says |\n| **Craft** a specific look or medium | The row in **Craft** below | As that row says |\n| **Round trip with the editor**: the user changed the timeline, colours or subtitles, or wants a film made editable; 圖層、時間軸、設計、設計系統 | [layers.md](references/layers.md) | `scenes/timeline.json`, `colors` in `mografy.json`, `style.md` |\n| **Output and speed** | The row in **Output and speed** below | As that row says |\n| **Changing Mografy itself** | [project.md](references/project.md) | The current checkout |\n\n**Product films**\n\n| Situation | Read | Start from |\n| --- | --- | --- |\n| Short UI loop or hero (4–12 s, one to three actions): landing-page hero, feature card, phone moment, dashboard insight; 假介面、產品動態、UI 動畫、介面舞台 | [ui-stage.md](references/ui-stage.md) | The closest of the ten `stage-*` reference films (`mografy add stage-invoices <folder>`), or `mografy add stage <project>` |\n| Demo, what's new, mobile preview from screenshots; 重繪、介面簡化、只拍操作細節 | [product-walkthrough.md](references/product-walkthrough.md) | `mografy add walkthrough <project>` |\n| How-to or tutorial clips, one per step; 操作教學動畫、教學影片、使用教學、新手引導 | [how-to-film.md](references/how-to-film.md), [product-walkthrough.md](references/product-walkthrough.md) | `mografy add walkthrough <project>` |\n| Social or product video from standard beats: hook, subtitles, device screen, numbers, end card | [templates.md](references/templates.md) | `mografy add <template...> <project>` |\n\n**Craft**\n\n| Situation | Read | Start from |\n| --- | --- | --- |\n| Camera moves on stills or key art, wipes, atmosphere | [camera-transitions.md](references/camera-transitions.md) | `mografy add cinema <project>` |\n| Chinese or Japanese copy, vertical text | [cjk-typography.md](references/cjk-typography.md) | `mografy add cjk <project>` |\n| Real 3D: a product that turns, depth, an orbiting camera | [three-d.md](references/three-d.md) | `mografy add three <project>` |\n| Logo sting or short intro; borrowing a built-in motif | [intro.md](references/intro.md), [built-in-components.md](references/built-in-components.md) | The component's source file |\n| Paper theatre, 紙劇場, 紙偶, 定格, a narrated concept explainer (心理學、效應), a character puppet story | [examples.md](references/examples.md) (Paper theatre series) | `mografy add paper-theatre-shadow <folder>` for an explainer, `paper-theatre-moon-rabbit-opera` or `paper-theatre-sea-moon` for a character film: study it, then build your own |\n| Music wanted and no track supplied | [music.md](references/music.md) | `mografy add music <project>` |\n\n**Output and speed**\n\n| Situation | Read | Start from |\n| --- | --- | --- |\n| Aspect ratio, 9:16, export sizes and formats | [output.md](references/output.md) | `aspectRatio` in `mografy.json` |\n| Exported file too large to share | [video-compression.md](references/video-compression.md) | `scripts/compress-video.py` |\n| Slow or choppy playback (卡, 不順, 掉幀), or `mografy check` warns about frame cost or motion | [performance.md](references/performance.md) | `mografy check --motion`: the slowest frames and the choppy moments it prints |\n\n## Steps for a new film\n\nEach step names its output. Skip steps the request does not need, and say which ones you skipped.\n\n1. **Read the project.** `mografy.json` (including `colors`), the scene entry and its imports, `scenes/timeline.json` (what the user adjusted in the timeline), `style.md`, `assets/`. If a project with an existing scene has no `style.md`, write one first from what the scene already does (its colour and type tokens, layout, motion character, timing), so your changes keep its look; tell the user you added it. Pick the closest reference film from [examples.md](references/examples.md) (fetch the showcase list it links when the installed films do not fit), add it, and read the files its table names.\n2. **Brief.** Message, audience, length, aspect ratio, language of the on-screen copy (follow the brief; write plans in English), music. Infer what the request implies and state the assumptions. Output: the top of `storyboards/storyboard.md`.\n3. **Storyboard.** Read [storyboard.md](references/storyboard.md) and [animation-principles.md](references/animation-principles.md). First write the film's idea in one sentence: one visual thing that travels through every shot and causes each change (a thread of light that fills each cup in turn, a line that becomes every card's edge). A row of separate cards with crossfades is not an idea; a film without one looks like a template. Then fix the design system (type roles, palette, the layout repeated shots share) as tokens, following [taste.md](references/taste.md), and record it with the film's idea in `style.md`. Output: `style.md`, the shot table in `storyboards/storyboard.md` and a visual board (image generation in Codex, an Artifact or `storyboards/storyboard.html` in Claude). **Stop** here when the user asked only for a storyboard; when they asked for the film, continue without an approval step.\n4. **Build.** One world, one camera, one beat table ([film-architecture.md](references/film-architecture.md)). Declare every part the user may want to adjust as a layer whose `in` and `out` come from the beat table ([layers.md](references/layers.md)). Take motion from `@mografy/runtime` and parts from the extras and templates above. Output: `scenes/`, `mografy.json` with `review.times` and `review.transitions` from the beat table.\n5. **Music** (only when wanted). Output: `music-src/music.json`, `assets/music.mp3`, `audio` in `mografy.json`.\n6. **Check and review.** Run `mografy check --motion [project]` (or `check` with `motion: true`) and fix every warning (a deliberate cut it reports may stay); run `mografy review [project]` (or `review`) and look at every PNG, including each transition strip. Walk **Before delivery**. Output: the review PNGs and a short note of what you checked.\n7. **Export** only when asked: `mografy export [project] --format mp4|webm|mov|lottie|svga` (or `export`; settings in [output.md](references/output.md)). Output: a file in `renders/`.\n\nTo iterate on a weak range, render it frame by frame, name the problem with a time, fix it and review the same range again. To change the length, take time from holds, never from actions.\n\n## Quality floor\n\nEvery film, from a 5 s bumper to a 2 min story, meets these; each can be checked against a frame or a `mografy check` line.\n\n1. **One world, one camera.** One `cameraPath` for the whole film; cards get local transforms inside it, never a second camera; no shot resets to an empty centre.\n2. **Every cut hands something over.** The line, card, dot or word a shot ends on is what the next starts from. A wipe or dissolve is a deliberate break, not a cover for a jump.\n3. **No empty frames.** The outgoing element finishes its exit under the incoming one (overlap 0.2–0.5 s).\n4. **One motion vocabulary.** Long moves and the camera use `keys` / `cameraPath`; entrances use `springs.*` or `spring`; holds do not drift.\n5. **Blur a layer, never a group of draws:** `blurLayer`, `blurText` / `blurWords`, `bloom`.\n6. **Pooled buffers in film coordinates:** `layer`, `buffer`, `blurLayer`, `bloom`; never sized from the player's canvas.\n7. **Groups fade as one** through one `layer`, so overlaps do not flash.\n8. **One beat table.** Layers, `meta.shots`, review times and handoffs all come from `beats([...])`.\n9. **Parts are layers.** Every part a user would want to adjust is a layer drawn from its own time; parts that share a camera or a pass are drawn in place with `each`.\n\n## Before delivery\n\n- [ ] `mografy check` passes with no warnings (frame cost under 100 ms, at most 8 filters per frame, no per-frame canvases).\n- [ ] `mografy check --motion` reports no jump, hard start or hard stop except deliberate cuts.\n- [ ] No text overlaps other text or UI, and copy stays inside the safe margins in [taste.md](references/taste.md).\n- [ ] Every caption and result meets the hold times in [taste.md](references/taste.md).\n- [ ] Every transition strip shows the handoff object in every frame, with no jump and no empty frame.\n- [ ] Fonts cover every character of the final copy (re-subset after the last copy change).\n- [ ] `review.times` match the current beat table.\n- [ ] Every id in `scenes/timeline.json` still names a declared layer, and colours the user swapped in `colors` still appear in the film.\n- [ ] Your note names any layer that starts hidden, and any of the user's edits or swaps that affect what you changed.\n- [ ] The project has a `style.md` that matches what the film now does.\n\n## Contract\n\nAnimation content belongs only in scene modules. Build motion and effects from `@mografy/runtime` (`at`, `win`, `spring`, `springs`, `settle`, `keys`, `cameraPath`, `withCamera`, `beats`, `timeline`, `layer`, `blurLayer`, `bloom`, `blurText`, `riseWords`, `blurWords`, `surface`, `tempoGrid`) instead of re-implementing curves, cameras, layers and text reveals per project; the helpers also run on a plain canvas, so a storyboard page can draw the real film. Render synchronously from absolute `time`, resolved params and prepared assets; scene code runs only in the browser. For a requested 9:16 video, author a native portrait scene (1080 × 1920), respect any saved `aspectRatio`, and plan vertical layout and social safe margins. The main preview follows the scene; orientation icons and Fit belong only to export. A generated storyboard is a concept reference; validate the actual scene separately.\n",
|
|
26
|
+
"SKILL.md": "---\nname: mografy\ndescription: Make, edit, review and export Mografy Canvas animations (projects with mografy.json), plan their storyboards and scores, and compress exported videos with the bundled Python helper; also develop the Mografy repository. Use when a folder has mografy.json, the Mografy MCP tools are connected, or the user asks for a motion graphic, product demo from screenshots, how-to or tutorial clips, teaser, logo reveal, explainer, paper theatre (紙劇場、紙偶、定格), or social video, or says 做動畫、動態影片、宣傳片、產品示範、操作教學動畫、分鏡、配樂、圖層、時間軸、設計系統、匯出 MP4、壓縮影片.\n---\n\n# Mografy\n\nMografy films are TypeScript scene modules drawn on a Canvas as a pure function of time, previewed in the Mografy player and exported to video, Lottie or SVGA. This file holds the hard rules, the vocabulary, the tools, which reference to read for which job, and the steps. Details live in `references/`; read a reference when its step comes up, not before.\n\nPrecedence: the user's request in this conversation, then the project's `style.md`, then a local skill whose folder ends in `-ref` under `.agents/skills/` (read its `SKILL.md` after this one when the checkout has one), then the defaults here and in [references/taste.md](references/taste.md). Nothing overrides **Never**, the **Contract** or the **Quality floor**.\n\n## Never\n\n- Put animation, layout or shot descriptions in `mografy.json`. It holds settings, audio, colour swaps and review times; animation lives in scene modules, because the server never evaluates scene code.\n- Read a clock, keep state between frames, or use unseeded randomness, GSAP, SVG scene layers or resvg. The player seeks in any order, and `npx mografy check` renders each time twice to catch state.\n- Set `ctx.filter` around many draws or create a canvas in `renderFrame`. Each costs a full pass per draw or per frame; use `blurLayer`, `blurText`, `bloom`, `layer` and `buffer`.\n- Write `scenes/timeline.json` or `colors` in `mografy.json` by hand to animate or restyle. They hold the user's own edits from the editor; change the scene instead ([layers.md](references/layers.md)).\n- Rename or remove a layer `id` that has edits in `scenes/timeline.json`: the user's work on it would be orphaned.\n- Operate the user's website or account unless they asked you to and gave you a test account ([how-to-film.md](references/how-to-film.md)); otherwise work from screenshots the user provides. Never show real customer data or a working private link; use invented demo data.\n- Copy another brand's copy, marks or music, or edit the films in `examples/` (they are the reference other agents read). Copy one with `npx mografy add <name>` (showcase films download the same way) and change the copy.\n- Export, or overwrite a file in `renders/`, unless the user asks for a file.\n\n## Terms\n\n- **film**: the whole animation. **scene**: the module that draws it (`scenes/main.ts` and its imports).\n- **shot**: one idea or composition, one row of the shot table. **beat table**: `beats([...])`, the single source of shot times, `meta.shots`, layer windows and review times.\n- **handoff**: the object that ends one shot and starts the next. **hold**: time when nothing moves so the viewer can read. **stop frame**: a shot's settled frame, shown in review.\n- **layer**: one part the user can retime, hide, copy, rename, lock or reorder in the editor's timeline, declared with `timeline([...])`. **edits**: the user's changes to layers, in `scenes/timeline.json`; they win over the declarations. **shot layer**: the layer per shot the build gives a scene that declares none.\n- **card**: one UI panel or piece of content drawn in the film's world. **extra**: an optional helper module added with `npx mografy add <extra>`. **template**: a ready-made beat added the same way. **reference film**: a finished film to learn from: installed in `examples/`, or a showcase film on https://www.mografy.app/showcase, downloaded with `npx mografy add <name>`.\n\n## Tools\n\nDrive Mografy with the `mografy` command in a shell, or with the Mografy MCP tools when the host has connected `npx mografy mcp`; both act on the same project, and while the player has it open they work through the player, so the user sees each change. With the MCP tools, change a scene through `write_source` (it compiles and trial-renders first and writes nothing on failure), look with `render_frame` and `review`, and check with `check` (`motion: true`). [references/mcp.md](references/mcp.md) maps each tool to its command. Open the player with `npx mografy dev` or `open_player`.\n\n## Choose the path\n\nFind the job, read its references, start where it says. When a request fits more than one row, read every matching reference; when it fits none, follow the steps below with the **New film** references.\n\n| Job | Read | Start from |\n| --- | --- | --- |\n| **Fix or tweak** an existing film: copy, one timing, an asset, an export | [scene-authoring.md](references/scene-authoring.md); also [layers.md](references/layers.md) when the project has `scenes/timeline.json` or `colors` | The existing scene; no new concept or storyboard |\n| **New film** from a brief, or redesigning a film's motion | [film-architecture.md](references/film-architecture.md), [motion-design.md](references/motion-design.md), [taste.md](references/taste.md), [examples.md](references/examples.md) | `npx mografy add film-starter <folder>`, or the closest reference film from examples.md |\n| **Product film** from an app's screens | The row in **Product films** below | As that row says |\n| **Craft** a specific look or medium | The row in **Craft** below | As that row says |\n| **Round trip with the editor**: the user changed the timeline, colours or subtitles, or wants a film made editable; 圖層、時間軸、設計、設計系統 | [layers.md](references/layers.md) | `scenes/timeline.json`, `colors` in `mografy.json`, `style.md` |\n| **Output and speed** | The row in **Output and speed** below | As that row says |\n| **Changing Mografy itself** | [project.md](references/project.md) | The current checkout |\n\n**Product films**\n\n| Situation | Read | Start from |\n| --- | --- | --- |\n| Short UI loop or hero (4–12 s, one to three actions): landing-page hero, feature card, phone moment, dashboard insight; 假介面、產品動態、UI 動畫、介面舞台 | [ui-stage.md](references/ui-stage.md) | The closest of the ten `stage-*` reference films (`npx mografy add stage-invoices <folder>`), or `npx mografy add stage <project>` |\n| Demo, what's new, mobile preview from screenshots; 重繪、介面簡化、只拍操作細節 | [product-walkthrough.md](references/product-walkthrough.md) | `npx mografy add walkthrough <project>` |\n| How-to or tutorial clips, one per step; 操作教學動畫、教學影片、使用教學、新手引導 | [how-to-film.md](references/how-to-film.md), [product-walkthrough.md](references/product-walkthrough.md) | `npx mografy add walkthrough <project>` |\n| Social or product video from standard beats: hook, subtitles, device screen, numbers, end card | [templates.md](references/templates.md) | `npx mografy add <template...> <project>` |\n\n**Craft**\n\n| Situation | Read | Start from |\n| --- | --- | --- |\n| Camera moves on stills or key art, wipes, atmosphere | [camera-transitions.md](references/camera-transitions.md) | `npx mografy add cinema <project>` |\n| Chinese or Japanese copy, vertical text | [cjk-typography.md](references/cjk-typography.md) | `npx mografy add cjk <project>` |\n| Real 3D: a product that turns, depth, an orbiting camera | [three-d.md](references/three-d.md) | `npx mografy add three <project>` |\n| Logo sting or short intro; borrowing a built-in motif | [intro.md](references/intro.md), [built-in-components.md](references/built-in-components.md) | The component's source file |\n| Paper theatre, 紙劇場, 紙偶, 定格, a narrated concept explainer (心理學、效應), a character puppet story | [examples.md](references/examples.md) (Paper theatre series) | `npx mografy add paper-theatre-shadow <folder>` for an explainer, `paper-theatre-moon-rabbit-opera` or `paper-theatre-sea-moon` for a character film: study it, then build your own |\n| Music wanted and no track supplied | [music.md](references/music.md) | `npx mografy add music <project>` |\n\n**Output and speed**\n\n| Situation | Read | Start from |\n| --- | --- | --- |\n| Aspect ratio, 9:16, export sizes and formats | [output.md](references/output.md) | `aspectRatio` in `mografy.json` |\n| Exported file too large to share | [video-compression.md](references/video-compression.md) | `scripts/compress-video.py` |\n| Slow or choppy playback (卡, 不順, 掉幀), or `npx mografy check` warns about frame cost or motion | [performance.md](references/performance.md) | `npx mografy check --motion`: the slowest frames and the choppy moments it prints |\n\n## Steps for a new film\n\nEach step names its output. Skip steps the request does not need, and say which ones you skipped.\n\n1. **Read the project.** `mografy.json` (including `colors`), the scene entry and its imports, `scenes/timeline.json` (what the user adjusted in the timeline), `style.md`, `assets/`. If a project with an existing scene has no `style.md`, write one first from what the scene already does (its colour and type tokens, layout, motion character, timing), so your changes keep its look; tell the user you added it. Pick the closest reference film from [examples.md](references/examples.md) (fetch the showcase list it links when the installed films do not fit), add it, and read the files its table names.\n2. **Brief.** Message, audience, length, aspect ratio, language of the on-screen copy (follow the brief; write plans in English), music. Infer what the request implies and state the assumptions. Output: the top of `storyboards/storyboard.md`.\n3. **Storyboard.** Read [storyboard.md](references/storyboard.md) and [animation-principles.md](references/animation-principles.md). First write the film's idea in one sentence: one visual thing that travels through every shot and causes each change (a thread of light that fills each cup in turn, a line that becomes every card's edge). A row of separate cards with crossfades is not an idea; a film without one looks like a template. Then fix the design system (type roles, palette, the layout repeated shots share) as tokens, following [taste.md](references/taste.md), and record it with the film's idea in `style.md`. Output: `style.md`, the shot table in `storyboards/storyboard.md` and a visual board (image generation in Codex, an Artifact or `storyboards/storyboard.html` in Claude). **Stop** here when the user asked only for a storyboard; when they asked for the film, continue without an approval step.\n4. **Build.** One world, one camera, one beat table ([film-architecture.md](references/film-architecture.md)). Declare every part the user may want to adjust as a layer whose `in` and `out` come from the beat table ([layers.md](references/layers.md)). Take motion from `@mografy/runtime` and parts from the extras and templates above. Output: `scenes/`, `mografy.json` with `review.times` and `review.transitions` from the beat table.\n5. **Music** (only when wanted). Output: `music-src/music.json`, `assets/music.mp3`, `audio` in `mografy.json`.\n6. **Check and review.** Run `npx mografy check --motion [project]` (or `check` with `motion: true`) and fix every warning (a deliberate cut it reports may stay); run `npx mografy review [project]` (or `review`) and look at every PNG, including each transition strip. Walk **Before delivery**. Output: the review PNGs and a short note of what you checked.\n7. **Export** only when asked: `npx mografy export [project] --format mp4|webm|mov|lottie|svga` (or `export`; settings in [output.md](references/output.md)). Output: a file in `renders/`.\n\nTo iterate on a weak range, render it frame by frame, name the problem with a time, fix it and review the same range again. To change the length, take time from holds, never from actions.\n\n## Quality floor\n\nEvery film, from a 5 s bumper to a 2 min story, meets these; each can be checked against a frame or a `npx mografy check` line.\n\n1. **One world, one camera.** One `cameraPath` for the whole film; cards get local transforms inside it, never a second camera; no shot resets to an empty centre.\n2. **Every cut hands something over.** The line, card, dot or word a shot ends on is what the next starts from. A wipe or dissolve is a deliberate break, not a cover for a jump.\n3. **No empty frames.** The outgoing element finishes its exit under the incoming one (overlap 0.2–0.5 s).\n4. **One motion vocabulary.** Long moves and the camera use `keys` / `cameraPath`; entrances use `springs.*` or `spring`; holds do not drift.\n5. **Blur a layer, never a group of draws:** `blurLayer`, `blurText` / `blurWords`, `bloom`.\n6. **Pooled buffers in film coordinates:** `layer`, `buffer`, `blurLayer`, `bloom`; never sized from the player's canvas.\n7. **Groups fade as one** through one `layer`, so overlaps do not flash.\n8. **One beat table.** Layers, `meta.shots`, review times and handoffs all come from `beats([...])`.\n9. **Parts are layers.** Every part a user would want to adjust is a layer drawn from its own time; parts that share a camera or a pass are drawn in place with `each`.\n\n## Before delivery\n\n- [ ] `npx mografy check` passes with no warnings (frame cost under 100 ms, at most 8 filters per frame, no per-frame canvases).\n- [ ] `npx mografy check --motion` reports no jump, hard start or hard stop except deliberate cuts.\n- [ ] No text overlaps other text or UI, and copy stays inside the safe margins in [taste.md](references/taste.md).\n- [ ] Every caption and result meets the hold times in [taste.md](references/taste.md).\n- [ ] Every transition strip shows the handoff object in every frame, with no jump and no empty frame.\n- [ ] Fonts cover every character of the final copy (re-subset after the last copy change).\n- [ ] `review.times` match the current beat table.\n- [ ] Every id in `scenes/timeline.json` still names a declared layer, and colours the user swapped in `colors` still appear in the film.\n- [ ] Your note names any layer that starts hidden, and any of the user's edits or swaps that affect what you changed.\n- [ ] The project has a `style.md` that matches what the film now does.\n\n## Contract\n\nAnimation content belongs only in scene modules. Build motion and effects from `@mografy/runtime` (`at`, `win`, `spring`, `springs`, `settle`, `keys`, `cameraPath`, `withCamera`, `beats`, `timeline`, `layer`, `blurLayer`, `bloom`, `blurText`, `riseWords`, `blurWords`, `surface`, `tempoGrid`) instead of re-implementing curves, cameras, layers and text reveals per project; the helpers also run on a plain canvas, so a storyboard page can draw the real film. Render synchronously from absolute `time`, resolved params and prepared assets; scene code runs only in the browser. For a requested 9:16 video, author a native portrait scene (1080 × 1920), respect any saved `aspectRatio`, and plan vertical layout and social safe margins. The main preview follows the scene; orientation icons and Fit belong only to export. A generated storyboard is a concept reference; validate the actual scene separately.\n",
|
|
27
27
|
};
|
|
28
28
|
//# sourceMappingURL=skill-text.js.map
|