This is the full developer documentation for framefields # framefields docs > What framefields is, a complete first composition, and where to go next. framefields is a TypeScript library that renders video on the GPU, frame by frame, straight to MP4. A video is a `Composition`: a tree of layers with keyframed animation. It renders natively on WebGPU (Dawn → Metal / Vulkan) in Node.js — no browser, no Puppeteer, no screenshots. It is built to be driven by coding agents. Add the skills to your agent: ```bash npx skills add gatewai-dev/framefields ``` Works with Claude, Codex, Cursor, Hermes, Gemini CLI, GitHub Copilot, and 70+ others. More in [framefields for agents](/docs/agents/). Or write it yourself — this is a complete film: src/film.ts ```ts import { Composition, FontManager, Layer, LayerAnimation } from "framefields"; export async function buildFilm() { await FontManager.register({ family: "Inter", source: "assets/fonts/Inter.ttf" }); const film = new Composition({ width: 1920, height: 1080, fps: 30, durationMs: 3000, backgroundColor: "#0e0d0c", }); film.add( Layer.text("Hello, framefields", { position: "absolute", x: 0, y: 480, width: 1920, height: 120, fontFamily: "Inter", fontSize: 96, fontWeight: 700, fill: "#eee9e0", align: "center", }).animate( LayerAnimation.create() .fadeIn(0, 20, "power2.out") .fromTo("y", 520, 480, { start: 0, end: 30, ease: "expo.out" }), ), ); return film; } // elsewhere: await (await buildFilm()).renderVideo({ outputPath: "output/hello.mp4" }); ``` ## What it covers [Section titled “What it covers”](#what-it-covers) | Area | You get | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Layout & type | Flexbox (Yoga) boxes, GPU vector text (Slug), rich text, RTL, text animators | | Motion | Keyframes, 13 easing families, springs, wiggles, signals, scene transitions | | Effects | 54 GPU effects: grading, grain, blur, LUTs, keying, glass, trails, datamosh, relighting, audio DSP | | 3D | Cameras, lights, PBR environment, refracting glass/acrylic, shadows, bloom, primitives, glTF/OBJ/FBX/STL/PLY models | | Physics | Deterministic 2D & 3D rigid bodies (Rapier), live worlds, performer deflection, GPU compute particles | | Audio | Soundtracks, procedural SFX, audio-reactive signals | | Data | Animated line, area, bar, scatter, candlestick, pie and donut charts | | Vision | On-device detection, segmentation, pose and mattes driving layout and effects | | Delivery | PNG frames, contact-sheet grids, MP4 with built-in QA, live browser preview, [cloud rendering](/docs/guides/cloud-rendering/) on framefields GPUs with long films split across several | ## Examples & showcase [Section titled “Examples & showcase”](#examples--showcase) Explore open-source reference films in the [GitHub repository](https://github.com/gatewai-dev/framefields/tree/main/examples): * [**Physics dancer**](https://youtu.be/POC7rKnuoE4) (`examples/28_physics_dancer`) — 3D glass word cards, live Rapier rigid-body collisions against a tracked dancer’s limbs, and silhouette-deflected GPU embers. * [**Mac Keyboard**](https://youtu.be/k2lgbdL6_TA) (`examples/26_mac_keyboard_from_3d_primitives`) — Mechanical keyboard built entirely from 3D primitives, PBR materials, and camera rack focus. * [**Framefields launch**](https://youtu.be/FVXTqAozAv8) (`examples/22_framefields_launch`) — Lyric-driven launch film with tight BeatGrid audio synchronization. * [**Full Circle**](https://youtu.be/9BF1snfmg3o) (`examples/21_full_circle`) — Kinetic typography, 3D scenes, and camera trajectories. * [**Dancer showcase**](https://youtu.be/RQ3yi_lzPqI) (`examples/19_framefields_film`) — Multi-scene brand film with on-device vision mattes, audio reactive signals, and LUT grading. ## Start here [Section titled “Start here”](#start-here) [Getting started](/docs/getting-started/)Install, scaffold, and render your first MP4. [framefields for agents](/docs/agents/)Install the skills, the agent workflow, example prompts. [Core concepts](/docs/core-concepts/)Compositions, frames, layer trees, timing and layout. [Cloud rendering](/docs/guides/cloud-rendering/)Render from git on framefields GPUs by name; split long films across several. [Authoring rules](/docs/reference/rules/)The short list of rules that prevent most broken renders. ## For agents [Section titled “For agents”](#for-agents) Machine-readable docs See [Docs for agents](/docs/agents/llms/). Every page has a Markdown twin: swap the trailing `/` for `.md` (`/docs/guides/animation/` → `/docs/guides/animation.md`; this page is [`/docs/index.md`](/docs/index.md)). The whole site is in [`/docs/llms-full.txt`](/docs/llms-full.txt), a compact version in [`/docs/llms-small.txt`](/docs/llms-small.txt), and an index in [`/docs/llms.txt`](/docs/llms.txt). Requirements: **Node.js ≥ 22**, an ES module project, and a **WebGPU-capable GPU** (Metal on macOS, Vulkan on Linux/Windows). Without a GPU, Linux falls back to a much slower CPU driver. framefields is Apache-2.0 (v2.11). # Getting started > Create a framefields project with one command (or by hand), and verify a first render from the cheapest check to the final MP4. ## The quick way: `framefields init` [Section titled “The quick way: framefields init”](#the-quick-way-framefields-init) One command sets up everything this page describes: `package.json` (with the install-script approvals below, scripts, dependencies and `packageManager`), `tsconfig.json`, `src/theme.ts`, `film.ts` and `render.ts`, `assets/` with Git LFS rules, `.gitignore`, `framefields.json` (with a `film` render, so `framefields render film --cloud` works by name), and the Inter and JetBrains Mono fonts. ```bash pnpm dlx framefields init my-film --install # or: npx framefields init my-film --install cd my-film && pnpm frames -- 0 30 60 # first frames in output/ ``` * **Nothing to answer.** `init` asks no questions, so it runs the same in CI and on remote servers. * **Existing projects are safe.** Run it inside one to add framefields there. Files you have are left alone, and `package.json`, `.gitignore` and `.gitattributes` only gain what they lack. A `"type": "commonjs"` package is refused, because framefields needs ES modules. * **Fonts are pinned.** Inter and JetBrains Mono are downloaded from Google Fonts, checked by SHA-256 and saved in `assets/fonts/` with their OFL licenses. The generated `src/components/fonts.ts` registers them, and `theme.ts` calls it. The npm package ships no fonts. * **The AI gateway is optional.** To generate images, video, music, voice and 3D from code, create a key at [framefields.dev/dashboard](https://framefields.dev/dashboard), copy `.env.example` to `.env` and set `FRAMEFIELDS_API_KEY`. `npx framefields` loads `.env` from the project folder when it exists (variables already set win). See [Generative AI](/docs/guides/ai/). | Option | Effect | | --------------------------- | ------------------------------------------------------------- | | `--install` | Install dependencies afterwards | | `--pm npm\|pnpm\|yarn\|bun` | Package manager (default: the one running the command) | | `--emoji` | Also install Noto Color Emoji, so emoji in text draw in color | | `--no-fonts` | Skip Inter and JetBrains Mono | | `--no-git` | Don’t run `git init` | | `--name ` | Package name (default: the folder’s name) | Then jump to [4. Verify](#4-verify-cheapest-step-first). The steps below set up the same project by hand, for when you want to see each piece or merge into an unusual setup. ### More from the CLI [Section titled “More from the CLI”](#more-from-the-cli) ```bash npx framefields list # ready-made components, one line each npx framefields add chat-thread # copies a component's source into src/components/ npx framefields fonts add emoji # fonts on their own: emoji, sans (Inter), mono (JetBrains Mono) ``` Components that need a font bring it along: `chat-thread` and `captions` install the emoji font, `terminal` and `code-block` JetBrains Mono. Text with emoji but no emoji font draws nothing, so `comp.lint()` reports `missing_emoji_font` and the first render prints how to fix it. ## 1. Check the machine [Section titled “1. Check the machine”](#1-check-the-machine) ```bash node --version # must be v22 or later ``` * **A GPU, or a CPU renderer.** Rendering uses WebGPU via Dawn: Metal on macOS (every Mac has a Metal GPU), Vulkan on Linux, Direct3D 12 or Vulkan on Windows. Without a GPU it renders on the CPU, about 12× slower: on Linux install Mesa lavapipe (`apt-get install -y libvulkan1 mesa-vulkan-drivers`); Windows has WARP built in. See [Rendering without a GPU](/docs/guides/rendering/#rendering-without-a-gpu). * **ES modules.** `package.json` needs `"type": "module"`. ## 2. Write `package.json`, then install [Section titled “2. Write package.json, then install”](#2-write-packagejson-then-install) framefields needs exactly one dependency install script: `skia-canvas` downloads its native binary. npm 11, pnpm 10 and bun block install scripts unless approved, so approve that one and deny the rest **before** installing. package.json ```json { "name": "my-film", "private": true, "type": "module", "allowScripts": { "skia-canvas": true, "sharp": false, "webgpu": false, "onnxruntime-node": false, "node-av": false, "esbuild": false, "protobufjs": false }, "pnpm": { "onlyBuiltDependencies": ["skia-canvas"], "ignoredBuiltDependencies": ["sharp", "webgpu", "onnxruntime-node", "node-av", "esbuild", "protobufjs"] }, "trustedDependencies": ["skia-canvas"], "scripts": { "typecheck": "tsc --noEmit -p .", "frames": "tsx src/render.ts frames", "grid": "tsx src/render.ts grid", "preview": "framefields preview src/film.ts", "render": "framefields render src/film.ts" } } ``` `allowScripts` is read by npm, `pnpm` by pnpm, `trustedDependencies` by bun. Yarn needs none of them. Deny the rest: they fetch an ffmpeg CLI and CUDA libraries framefields doesn’t use, or do nothing it needs. Add `"packageManager"` with the manager and version you install with (e.g. `"pnpm@10.13.1"`; `pnpm --version` prints it), and commit the lockfile it writes. A [render worker](/docs/guides/render-service/) installs with exactly that version and lockfile. ```bash npm install framefields npm install --save-dev tsx typescript @types/node ``` Caution If you see `Cannot find module '.../skia.node'`, the `skia-canvas` script was skipped. Approve it as above, then run `npm rebuild skia-canvas` (or `pnpm rebuild skia-canvas`). tsconfig.json ```json { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "target": "ES2022", "strict": true, "skipLibCheck": true, "noEmit": true, "types": ["node"] }, "include": ["src/**/*"] } ``` ## 3. Scaffold [Section titled “3. Scaffold”](#3-scaffold) Keep the composition separate from the script that renders it, so tests, preview and export all build the same film. ```plaintext src/ theme.ts sizes, fps, colors, fonts — the only place for magic numbers film.ts buildFilm(): returns the Composition render.ts frames | grid (quick looks; render and preview are the CLI's) framefields.json named renders, and the media pinned on your bucket assets/ every input file: on your bucket, or in Git LFS fonts/ .ttf / .otf (text needs a real font file) footage/ .mp4 / .mov / .webm audio/ .mp3 / .wav images/ .png / .jpg / .webp output/ renders (gitignored, never committed) .gitattributes LFS rules for assets/ ``` src/theme.ts ```ts import path from "node:path"; import { fileURLToPath } from "node:url"; import { FontManager } from "framefields"; const HERE = path.dirname(fileURLToPath(import.meta.url)); export const W = 1920; export const H = 1080; export const FPS = 30; export const INK = "#0e0d0c"; export const PAPER = "#eee9e0"; export const SANS = "Inter"; export async function registerFonts(): Promise { // Resolve from the module URL so the browser preview finds the file too. await FontManager.register({ family: SANS, source: path.resolve(HERE, "../assets/fonts/Inter.ttf") }); } ``` src/film.ts ```ts import { Composition, Layer, LayerAnimation } from "framefields"; import { FPS, H, INK, PAPER, registerFonts, SANS, W } from "./theme.js"; const DURATION = 3 * FPS; // frames export async function buildFilm(): Promise { await registerFonts(); // before any text layer is built const film = new Composition({ width: W, height: H, fps: FPS, durationMs: (DURATION / FPS) * 1000, backgroundColor: INK, }); film.add( Layer.text("Hello, framefields", { id: "title", position: "absolute", x: 0, y: H / 2 - 60, width: W, height: 120, fontFamily: SANS, fontSize: 96, fontWeight: 700, fill: PAPER, align: "center", }).animate( LayerAnimation.create() .fadeIn(0, 20, "power2.out") .fromTo("y", H / 2 - 20, H / 2 - 60, { start: 0, end: 30, ease: "expo.out" }), ), ); return film; } ``` src/render.ts ```ts import fs from "node:fs/promises"; import path from "node:path"; import { HeadlessMediaRenderer, frameCount } from "framefields"; import { buildFilm } from "./film.js"; // Quick looks: `npm run frames -- 0 30 60` and `npm run grid`. The full render // and the preview are `framefields render film` and `framefields preview film`. const OUT = path.resolve(import.meta.dirname, "../output"); const [mode = "frames", ...args] = process.argv.slice(2).filter((a) => a !== "--"); const film = await buildFilm(); await fs.mkdir(OUT, { recursive: true }); if (mode === "grid") { const last = frameCount(film.durationMs ?? (await film.computeDuration()), film.fps) - 1; const png = await film.renderFrameGrid({ frames: args.length ? args.map(Number) : [0, Math.floor(last / 2), last], columns: 4, cellWidth: 480, }); await fs.writeFile(path.join(OUT, "grid.png"), png); } else { const renderer = new HeadlessMediaRenderer(); for (const frame of (args.length ? args : ["0"]).map(Number)) { const png = await film.renderFrame({ frame, renderer }); await fs.writeFile(path.join(OUT, `f${String(frame).padStart(4, "0")}.png`), png); } } // Native GPU and encoder threads keep Node alive: always exit explicitly. process.exit(0); ``` ## 4. Verify, cheapest step first [Section titled “4. Verify, cheapest step first”](#4-verify-cheapest-step-first) Each step catches in seconds what a full render takes minutes to show. | Step | Command | Look for | | ---- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | 1 | `npm run typecheck` | type errors | | 2 | `npm run frames -- 0 30 60` | PNGs in `output/`; a black frame usually means a missing font, an off-canvas layer, or opacity stuck at 0 | | 3 | `npm run grid` | smooth motion across the contact sheet | | 4 | `npm run preview` | a person watches it with sound ([Live preview](/docs/guides/preview/)) | | 5 | `npm run render` | the MP4, plus QA findings ([Rendering](/docs/guides/rendering/)) | | or | `npm run render:cloud` | the same MP4 rendered on framefields GPUs from your pushed commit, long films split across several ([Cloud rendering](/docs/guides/cloud-rendering/)) | ## 5. Store assets [Section titled “5. Store assets”](#5-store-assets) Keep every input file under `assets/`. Small files (a logo, a LUT, a short sound) can be committed as they are. Footage and long audio belong outside git, in one of two places. **On your own bucket (recommended).** Cloudflare R2 or any S3-compatible bucket: the files stay out of git, `framefields.json` pins each by sha256, and downloads cost nothing on R2, for clones, CI and every cloud render GPU. Add a remote to `framefields.json`, set its keys in `.env`, then: ```bash npx framefields assets add assets/footage # upload, pin, gitignore npx framefields assets pull # in a fresh clone; `framefields render` does it for you ``` The preview streams pinned files straight from the bucket, so a fresh clone or an agent sandbox previews without downloading them. Setup, custom domains and CORS: [Assets and storage](/docs/guides/assets/). **Or Git LFS**, when the repo already uses it. Every clone and every cloud render worker downloads LFS objects from your git host, which bills that bandwidth to the repo owner. Set it up before adding any media: ```bash git lfs install git lfs track "assets/fonts/**" "assets/footage/**" "assets/audio/**" "assets/images/**" \ "assets/luts/**" "assets/models/**" "assets/lottie/**" echo "output/" >> .gitignore git add .gitattributes .gitignore && git commit -m "Track assets with Git LFS" ``` **Push:** `git add assets/…`, commit and `git push` as usual; the media upload with the push. Run `git lfs ls-files` before committing to confirm each new file is listed. **Pull:** in a fresh clone, container or CI runner, run `git lfs pull` before rendering (in GitHub Actions, `actions/checkout` with `lfs: true`). Caution Until pulled, LFS files are \~130-byte pointers. framefields cannot decode them: fonts fail to register and media renders blank. Ignore `output/`, not `*.mp4`, or your footage disappears from Git too. Details, including fixing a file committed without LFS: [Assets and Git LFS](/docs/agents/workflow/#assets-and-git-lfs). Moving from LFS to a bucket: [Assets and storage](/docs/guides/assets/#git-lfs). ## Next [Section titled “Next”](#next) * [Core concepts](/docs/core-concepts/) — how frames, layers and timing fit together. * [framefields for agents](/docs/agents/) — install the skills so your agent knows all of this. * [Cloud rendering](/docs/guides/cloud-rendering/) — render on framefields GPUs by name, from the terminal, code or the dashboard. * [Render on a server](/docs/guides/render-service/) — run the render worker on your own GPU machines. # framefields for agents > Why framefields is built for coding agents, how to give your agent the skills in one command, and the loop it follows to ship a video. framefields is made to be driven by a coding agent. A film is a TypeScript file, every check is a function that returns data, and every review step produces a file the agent can open and look at. You describe the video; the agent writes, renders, inspects and fixes it. ## Install the skills [Section titled “Install the skills”](#install-the-skills) Add the skills to your agent: ```bash npx skills add gatewai-dev/framefields ``` Works with Claude, Codex, Cursor, Hermes, Gemini CLI, GitHub Copilot, Windsurf, OpenCode, Goose, Cline and 70+ others. Then ask for a video: ```text Set up framefields in this project and render a 3-second title card that says "Hello". ``` The skills are instructions only: no MCP servers, hooks or executables, and they send no data anywhere. Details per agent are on [Install the skills](/docs/agents/install/). ## Why it suits agents [Section titled “Why it suits agents”](#why-it-suits-agents) | | | | ---------------------- | --------------------------------------------------------------------------------------------------------------- | | **Plain code** | A video is a `Composition` in TypeScript. Diffs, reviews, tests and git all work. | | **Deterministic** | `(composition, frame) → pixels`. The same frame renders the same way every time, so checks are repeatable. | | **Checks return data** | `comp.lint()` and `renderVideo({ qa })` return `{ severity, code, message }` objects, not logs to parse. | | **Cheap feedback** | One PNG frame or a contact-sheet grid in seconds, long before a full render. | | **People in the loop** | The live preview saves notes a person pins on the picture to `notes.json` — exact feedback an agent can act on. | | **No creative suite** | One npm package; no browser, no desktop apps, no licenses. | ## The loop [Section titled “The loop”](#the-loop) 1. **Write** `film.ts` exporting `buildFilm()`. 2. **Check** — `tsc --noEmit`, then `comp.lint()`. 3. **Look** — render key frames to PNG and open them. 4. **Look at motion** — render a frame grid. 5. **Show** — start the live preview; read the person’s pinned notes. 6. **Ship** — `renderVideo({ qa: true })`; stop if `qa.passed` is false. Full detail in [The agent workflow](/docs/agents/workflow/). [Install the skills](/docs/agents/install/)Claude Code, Codex, Cursor, Gemini CLI, Copilot and more; project or global; team setup. [The skills](/docs/agents/skills/)What each of the four skills teaches and when it loads. [The agent workflow](/docs/agents/workflow/)Write → check → look → show → ship, with code. [Example prompts](/docs/agents/prompts/)Prompts that work well, from first render to vision effects. [Docs for agents](/docs/agents/llms/)llms.txt, Markdown pages, and an AGENTS.md snippet. # Core concepts > Compositions, the frame clock, layer trees, local timing, layout and coordinates — the model everything else builds on. ## Every frame is a function of its number [Section titled “Every frame is a function of its number”](#every-frame-is-a-function-of-its-number) A composition compiles to a deterministic program: `(composition, frame) → pixels`. There are no timers and no wall clock. Rendering frame 45 always produces the same image, in any order, on any run. This is what makes frames testable and renders parallel. ## Composition [Section titled “Composition”](#composition) ```ts import { Composition } from "framefields"; const comp = new Composition({ width: 1920, height: 1080, fps: 30, // default 60 durationMs: 10_000, // or durationFrames; omitted → computed from media backgroundColor: "#0e0d0c", // default "#000000" antialias3d: true, // 4x MSAA for 3D meshes; false saves GPU memory }); ``` | Method | Does | | ------------------------------------------------- | ------------------------------------------------------------------ | | `add(layer \| layer[])` | adds layers (or arrays, e.g. from `Lighting.studio()`) to the root | | `addAudio(Layer.audio(...))` | adds a soundtrack | | `apply(effect)` | applies an effect to the whole frame | | `addSignal(name, signal)` | registers a named signal layers can bind by name | | `withVision(options)` | runs vision on the composition, returns reactive signals | | `vision(source, options)` | on-demand clip vision for live physics and particles | | `lint()` | document checks, no GPU | | `toSpec()` | the plain-JSON program (validate with `CompositorProgramSchema`) | | `renderFrame` / `renderFrameGrid` / `renderVideo` | output, see [Rendering](/docs/guides/rendering/) | | `computeDuration()` | duration in ms, from options or media | ## Layers [Section titled “Layers”](#layers) Every `Layer.*` builder (boxes, shapes, text, media, 3D primitives, and `Layer.particles`) returns a node you can chain: `.animate()`, `.withEffect()`, `.withMatte()`, `.withVision()`, `.pinToObject()`. Layers nest through `children`. ```ts Layer.box({ width: 720, height: 380, padding: 32, background: "#141721", borderRadius: 24, borderColor: "#262b3d", borderWidth: 1.5, children: [ Layer.flex({ dir: "column", gap: 16, children: [ Layer.text("ENGINE", { fontSize: 16, fontWeight: 700, fill: "#6366f1", letterSpacing: 2 }), Layer.text("WebGPU motion", { fontSize: 48, fontWeight: 700, fill: "#f8fafc" }), ], }), ], }); ``` ## Time [Section titled “Time”](#time) * `startFrame` and `durationFrames` place a layer on its parent’s timeline. * **Keyframes are local**: frame 0 is the layer’s first visible frame. Never add the parent’s `startFrame` to keyframe times. * **Frames are integers.** Keyframe frames, start frames and durations must be whole numbers; `.keys()` rounds for you, other APIs reject decimals. * Keyframes past a layer’s `durationFrames` never play (lint/QA: `animation_truncated`). * Signals are sampled at the **composition** frame, not the layer’s local frame. A beat grid keeps timing musical and readable: ```ts export const FPS = 30; export const BPM = 100; export const BEAT = Math.round((FPS * 60) / BPM); // 18 frames export const beats = (n: number) => Math.round(n * BEAT); ``` ## Layout and position [Section titled “Layout and position”](#layout-and-position) * Containers lay children out with flexbox (Yoga): `Layer.flex({ dir, gap, justify, align, wrap, padding })`. * Setting `x` or `y` without `position: "relative"` makes a layer **absolute** — removed from flex flow, positioned in its parent. * **Animating `x`/`y` overrides layout.** A layer placed at `y: 400` animates with `fromTo("y", 440, 400)`, not `fromTo("y", 40, 0)`. * Borders are `borderColor` + `borderWidth`. A CSS shorthand like `border: "1px solid red"` is ignored. ## Coordinates [Section titled “Coordinates”](#coordinates) * 2D: pixels, origin top-left, y down. * 3D: the camera is calibrated so `z = 0` maps 1:1 onto canvas pixels. y is still down, so “up” is −y. See [3D](/docs/guides/3d/). ## Colors [Section titled “Colors”](#colors) Every color prop takes hex, `rgb()`, `hsl()`, `oklch()`, `oklab()` or a CSS name. Color keyframes blend in OKLab, so red → green passes through yellow. Gradients are CSS strings (`linear-`, `radial-`, `conic-gradient()`) usable as any `background` or shape `fill`. ## Project shape [Section titled “Project shape”](#project-shape) ```plaintext src/theme.ts tokens: size, fps, colors, fonts, beat grid src/scenes/*.ts one function per scene, each returns a full-frame box src/film.ts buildFilm(): fonts, Composition, Layer.sequence(scenes), grade src/render.ts frames | grid (render and preview: `framefields render|preview `) assets/ fonts, footage, audio, images, LUTs, models — on your bucket or in Git LFS output/ renders, gitignored ``` Media in `assets/` lives outside git: on your own bucket, pinned by sha256 in `framefields.json` (`npx framefields assets add`, then `assets pull` in a fresh checkout; [Assets and storage](/docs/guides/assets/)), or in Git LFS (`git lfs pull` in a fresh checkout; [Assets and Git LFS](/docs/agents/workflow/#assets-and-git-lfs)). # Authoring rules > The numbered rules that prevent most broken framefields renders. Read before writing a composition. 1. **Register fonts first.** Call `FontManager.register({ family, source })` for every family before building any text layer. There are no system fonts. Emoji need `FontManager.registerEmojiFont(...)` with a CBDT/CBLC color font. 2. **Keyframes are local.** Frame 0 is the layer’s first frame. Never add the parent’s `startFrame`. 3. **Frames are integers.** Keyframe frames, `startFrame`, `durationFrames` — whole numbers only. 4. **Animating `x`/`y` overrides layout.** Animate to the placed value: placed at `y: 400` → `fromTo("y", 440, 400)`. 5. **`x`/`y` make a layer absolute** unless `position: "relative"` is set. 6. **Borders are `borderColor` + `borderWidth`.** CSS `border` strings are ignored. 7. **Give text a width** when it can wrap; otherwise it may clip. 8. **Every `Layer.audio()` needs `durationFrames`.** 9. **Images are raster.** `.png/.jpg/.webp` → `Layer.image`; `.json/.lottie` → `Layer.lottie`. 10. **Effect strengths are often 0–100**, not 0–1 (`Vignette`, `FilmGrain`, `Blur`). Check the [Effects reference](/docs/reference/effects/). 11. **Grade, then optics, then grain.** `FilmGrain` is the outermost pass. 12. **PBR needs an environment.** `roughness`/`metallic` do nothing without `Layer.environment()` or a `Lighting` rig. 13. **One shadow light**, directional or spot. 14. **Signals sample the composition frame**, not the layer’s local frame. 15. **Vision trails by one frame.** Verify vision with the MP4 or consecutive frames, never with a frame grid. 16. **Resolve assets from `import.meta.url`** so the browser preview can load them. 17. **Assets live in `assets/`, outside git:** pinned on the project’s bucket (`framefields assets add`; `assets pull` in a fresh clone) or in Git LFS (`git lfs pull`; confirm new media appear in `git lfs ls-files`). Never commit `output/`. 18. **Verify cheapest first:** typecheck → `lint()` → `renderFrame` → `renderFrameGrid` → `renderVideo({ qa: true })`. Look at every image you render. 19. **End render scripts with `process.exit()`.** 20. **Tokens live in `theme.ts`.** No magic colors, sizes or timings in scenes. 21. **Ease with intent.** `back.out(1.4–1.7)` entrances, `expo.out`/`spring` decelerations, `power2.in` exits, `linear` only for loops and counters. 22. **Custom shaders output premultiplied alpha** and blend with `srcFactor: "one"`, never `"src-alpha"`. # Install the skills > Install the framefields agent skills in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot and 70+ other agents — per project, per user, or for a whole team. The skills live in [`plugins/framefields`](https://github.com/gatewai-dev/framefields/tree/main/plugins/framefields) in the framefields repo. They are Markdown instructions only. The engine itself is the `framefields` npm package, which the skills tell your agent to install into your project. ## Install [Section titled “Install”](#install) * Claude Code Inside an interactive `claude` session: ```text /plugin install framefields ``` Or from a shell: ```bash claude plugin install framefields@claude-plugins-official ``` It comes from Anthropic’s official plugin directory, which Claude Code adds for you, and updates automatically. Restart Claude Code or run `/reload-plugins` afterwards. In the desktop app’s Code tab, use the shell form or **+ → Plugins → Add plugin → Framefields**. **Track `main` instead of the directory release:** ```text /plugin marketplace add gatewai-dev/framefields /plugin install framefields@framefields-plugins ``` * Codex ```bash npx skills add gatewai-dev/framefields -a codex ``` * Cursor ```bash npx skills add gatewai-dev/framefields -a cursor ``` * Gemini CLI ```bash npx skills add gatewai-dev/framefields -a gemini-cli ``` * Copilot ```bash npx skills add gatewai-dev/framefields -a github-copilot ``` VS Code / Copilot can also load the portable [`plugin.json`](https://github.com/gatewai-dev/framefields/blob/main/plugins/framefields/plugin.json) through its plugin UI. * Other ```bash npx skills add gatewai-dev/framefields ``` The [`skills`](https://skills.sh) CLI detects the agents on your machine and asks where to install. Agent ids include `windsurf`, `opencode`, `goose`, `cline`, `roo`, `amp`, `kiro-cli` and `hermes-agent`. ## Choose the scope [Section titled “Choose the scope”](#choose-the-scope) | Goal | Command | | --------------------------------------------------- | ----------------------------------------------------------- | | This project only (default) | `npx skills add gatewai-dev/framefields` | | Every project, for your user | `npx skills add gatewai-dev/framefields -g` | | Several agents at once | `npx skills add gatewai-dev/framefields -a codex -a cursor` | | No prompts (CI, scripts, agents installing for you) | add `-y` | | One skill only | add `-s framefields-render` | | See what’s in the package first | `npx skills add gatewai-dev/framefields --list` | | Copy instead of symlink | add `--copy` | ## Set it up for a team [Section titled “Set it up for a team”](#set-it-up-for-a-team) **Claude Code.** Commit this to `.claude/settings.json`; Claude Code offers the plugin to teammates when they trust the folder: .claude/settings.json ```json { "enabledPlugins": { "framefields@claude-plugins-official": true } } ``` Or install with `claude plugin install framefields@claude-plugins-official --scope project`, which writes the same entry. **Other agents.** Install per project (no `-g`) and commit the skill folders the CLI creates (for example `.agents/skills/`), so everyone who clones the repo gets them. ## Keep them current [Section titled “Keep them current”](#keep-them-current) ```bash npx skills update # update installed skills npx skills ls # list what's installed npx skills remove # remove them ``` Claude Code updates plugins from the official directory automatically. The skills’ version follows the `framefields` npm package. ## Install by hand [Section titled “Install by hand”](#install-by-hand) Copy each folder from [`plugins/framefields/skills/`](https://github.com/gatewai-dev/framefields/tree/main/plugins/framefields/skills) into one of: * `.claude/skills/` (Claude Code, project) * `.agents/skills/` (project, most other agents) * `~/.agents/skills/` (your user) ## Check it worked [Section titled “Check it worked”](#check-it-worked) Ask your agent: *“Which framefields skills do you have?”* It should list `framefields`, `framefields-compose`, `framefields-effects`, `framefields-vision` and `framefields-render`. Skills load on their own when a task matches, so you never need to name them. ## Your project still needs the package [Section titled “Your project still needs the package”](#your-project-still-needs-the-package) The skills don’t install the engine. On the first task, the `framefields` skill has your agent add it to your project — Node.js 22+, an ES module `package.json`, and approval for the one install script it needs. You can do it yourself with [Getting started](/docs/getting-started/). # Docs for agents > Machine-readable versions of these docs (llms.txt, full and compact text, per-page Markdown) and an AGENTS.md snippet for your project. These docs are written to be read by agents as much as people. Every page is short, example-first, and available as plain text. ## URLs [Section titled “URLs”](#urls) | URL | Contents | | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | [`/llms.txt`](/llms.txt) | site-level pointer for agents | | [`/docs/llms.txt`](/docs/llms.txt) | index: summary, requirements, and every page with its Markdown link | | [`/docs/llms-full.txt`](/docs/llms-full.txt) | all pages in one file | | [`/docs/llms-small.txt`](/docs/llms-small.txt) | all pages, compact | | `/docs/.md` | one page as Markdown — swap the trailing `/` for `.md`, e.g. [`/docs/guides/animation.md`](/docs/guides/animation.md) | Each page also has a **Copy as Markdown** button under its title, for pasting into a chat. ## Tell your agent about them [Section titled “Tell your agent about them”](#tell-your-agent-about-them) Add this to your project’s `AGENTS.md` (or `CLAUDE.md`): AGENTS.md ```md ## Video (framefields) This project renders video with the `framefields` npm package. - Docs index: https://framefields.dev/docs/llms.txt — fetch a page's `.md` URL from it when you need details. - Rules to follow: https://framefields.dev/docs/reference/rules.md - Film entry: `src/film.ts` exports `buildFilm()`. Tokens live in `src/theme.ts`. - Input files live in `assets/`, outside git. With a `storage` remote in `framefields.json`: `npx framefields assets add ` pins new media, `npx framefields assets pull` restores them in a fresh checkout (`framefields render` does it itself; the preview streams them). With Git LFS: `git lfs pull` in a fresh checkout; a ~130-byte file starting with `version https://git-lfs` is an un-pulled pointer; check `git lfs ls-files` lists new media. Renders go to `output/` (gitignored). - Verify cheapest first: `npm run typecheck`, `comp.lint()`, `npm run frames -- `, `npm run grid`, then `npm run render` (`framefields render film`; QA must pass). - Renders are named in `framefields.json`: `npx framefields render ` here, the same with `--cloud` on framefields GPUs, `npx framefields preview ` to watch. For long films or no local GPU: commit, push, then `npx framefields render --cloud --plan` and show the estimate before rendering. - A 3D scene exports as glTF (3.1+): `npx framefields render --model --frame ` or `comp.exportModel({ frame, outputPath })` writes a `.glb` (meters, y up, camera and lights included) for Blender, Unreal, Unity or three.js. Report its `skipped` list to the user. - Open every PNG you render before claiming it looks right. - Preview notes from people are in `.framefields/preview-notes/notes.json`. ``` ## Pick the right file [Section titled “Pick the right file”](#pick-the-right-file) * **Starting cold?** `llms-small.txt` fits most context windows and covers everything. * **Working on one area?** Fetch just that page’s `.md` from the index. * **Need effect props?** [`/docs/reference/effects.md`](/docs/reference/effects.md) lists all 52 effects; the skills’ generated catalog has types, ranges and defaults. # Example prompts > Prompts that work well with framefields agents, from a first title card to data stories, 3D product shots and vision effects. Good prompts say **what** (content, length, size), **how it should feel** (pace, palette, type), and **how to check** (which frames to show you). The skills handle the API. ## Getting started [Section titled “Getting started”](#getting-started) ```text Set up framefields in this project and render a 3-second 1080p title card that says "Launch day". Show me frames 0, 30 and 89 before exporting. ``` ```text Add framefields to this repo with a theme.ts, film.ts and render.ts. Use the Inter font in assets/fonts. ``` ```text Set up Git LFS for assets/ (fonts, footage, audio, images, LUTs, models, Lottie), gitignore output/, then add and push the files I just dropped into assets/footage. Confirm they are in git lfs ls-files. ``` ```text This is a fresh clone: pull the LFS assets, check none are still pointers, then render frame 0. ``` ## Motion and type [Section titled “Motion and type”](#motion-and-type) ```text Make a 10-second 1920×1080 intro at 30 fps, 100 BPM. Four scenes on the beat: the headline rises glyph by glyph, three feature cards pop in, a stat counts up, the logo settles. Push transitions between scenes. Render a frame grid of each scene for me. ``` ```text The second card enters too early and feels stiff. Move it one beat later and give it back.out(1.5). ``` ## Data [Section titled “Data”](#data) ```text Turn data/revenue.csv into a 6-second animated bar chart, quarters on x, revenue in $ on y, bars growing in one after another. Use the colors in theme.ts. ``` ## 3D [Section titled “3D”](#3d) ```text Make a product shot: the word "framefields" extruded in yellow, studio lighting with a soft shadow, a slow turn over 4 seconds, light bloom on the edges. Show me the first and last frame. ``` ## Grading and effects [Section titled “Grading and effects”](#grading-and-effects) ```text Give the whole film a warm filmic grade with subtle grain and vignette. Keep it restrained. ``` ```text Key out the green screen in assets/footage/talent.mp4 and put her over the gradient background. ``` ## Vision [Section titled “Vision”](#vision) ```text Put the headline "MOVE" behind the dancer in assets/footage/dancer.mp4. Check it with the exported video, not a frame grid. ``` ```text Reframe assets/footage/interview.mp4 from 16:9 to 9:16, following the speaker. Blur any other faces. ``` ## Sound [Section titled “Sound”](#sound) ```text Add assets/audio/score.mp3 with a 2-second fade in and out, plus a whoosh on every scene change. Target -14 LUFS and fail if QA doesn't pass. ``` ## Review with a person [Section titled “Review with a person”](#review-with-a-person) ```text Start the preview and give me the link. I'll leave notes on the picture — read them and fix each one, then restart the preview so I can tick them off. ``` ## Ship [Section titled “Ship”](#ship) ```text Lint the film, fix any warnings, then export output/final.mp4 at high quality with QA and show me the report. ``` # The skills > What each of the five framefields skills teaches an agent, and the kind of request that loads it. Five skills, each loaded automatically when a request matches its description. They hand off to each other, so an agent starting a project ends up with all of them. | Skill | Teaches | Loads on requests like | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `framefields` | Checking Node/GPU, writing `package.json` with the right install-script approvals, installing, scaffolding `theme.ts` / `film.ts` / `render.ts`, media outside git (a bucket with `framefields assets`, or Git LFS), a first verified render | *“Make a video with framefields”*, *“set up framefields in this repo”* | | `framefields-compose` | Compositions and layer trees, flex layout, typography and fonts, keyframes and easing, text animators, scenes on a beat grid, transitions, mattes, 3D looks, charts | *“Add a title sequence”*, *“animate these cards in on the beat”*, *“make the logo spin in 3D”* | | `framefields-effects` | Attaching effects to layers, whole films and regions; grading, grain, blur, LUTs, keying; signals on effect props | *“Add film grain and a vignette”*, *“grade this like a 70s film”* | | `framefields-vision` | On-device vision: detection, cutouts, pose, and prompted tracking with SAM 2.1 / SAM 3 — which model to pick for a shot, one selection for a whole group, backends and costs | *“Put the headline behind the dancer”*, *“follow the man in the white shirt”*, *“cut out all the students”*, *“blur the faces”* | | `framefields-render` | The verification ladder: lint, single frames, frame grids, pixel tests, live preview and pinned notes, MP4 export with QA, diagnosing blank frames | *“Render a frame grid of the intro”*, *“why is frame 40 black?”*, *“export the final MP4”* | ## What they make an agent do differently [Section titled “What they make an agent do differently”](#what-they-make-an-agent-do-differently) * **Verify cheapest first.** Typecheck and `comp.lint()` before any GPU work; frames and grids before a full render. * **Look at its own output.** Render a PNG, open it, and compare against intent — not assume. * **Keep tokens in one place.** Colors, sizes, fonts and the beat grid live in `theme.ts`. * **Avoid the classic breakages.** Fonts registered first, local integer keyframes, absolute vs flex positioning, `durationFrames` on audio, `process.exit()` after rendering. See [Authoring rules](/docs/reference/rules/). * **Bring a person in before exporting.** Start the preview, share the URL, and act on pinned notes. ## Where they come from [Section titled “Where they come from”](#where-they-come-from) The skills are versioned with the `framefields` package and live in the framefields repo at [`plugins/framefields/skills/`](https://github.com/gatewai-dev/framefields/tree/main/plugins/framefields/skills). `framefields-effects` includes a generated catalog of every effect and prop. If a skill gets something wrong, [open an issue](https://github.com/gatewai-dev/framefields/issues). # The agent workflow > The write → check → look → show → ship loop an agent should follow with framefields, with the code for each step. Every step returns a file or data an agent can inspect. Go in order: each step catches in seconds what the next takes minutes to show. ## 0. Project shape [Section titled “0. Project shape”](#0-project-shape) ```plaintext src/theme.ts tokens: size, fps, colors, fonts, beat grid src/film.ts export async function buildFilm(): Promise src/render.ts frames | grid (render and preview: `framefields render|preview film`) assets/ every input file: on your bucket, or in Git LFS fonts/ .ttf .otf footage/ .mp4 .mov .webm audio/ .mp3 .wav images/ .png .jpg .webp luts/ .cube models/ .glb .gltf .obj .fbx lottie/ .json .lottie captions/ .srt (plain text, no LFS needed) output/ renders (gitignored, never committed) .gitattributes LFS rules for assets/ ``` Also commit the lockfile and pin `packageManager`. Keep `film.ts` free of side effects: it builds the film and renders nothing. That way the same repo renders on a [render worker](/docs/guides/render-service/#project-checklist) unchanged. `render.ts` is in [Getting started](/docs/getting-started/#3-scaffold). Keeping `buildFilm()` separate means tests, preview and export all build the same film. Reference assets from the module URL (`path.resolve(HERE, "../assets/…")`) so the [preview](/docs/guides/preview/) can load them too. ## Assets and Git LFS [Section titled “Assets and Git LFS”](#assets-and-git-lfs) Source media goes in `assets/`, outside git, so the repo stays small and clones stay fast. Renders go in `output/` and are never committed. **On a bucket.** When `framefields.json` has a `storage` remote, pin media with `npx framefields assets add ` (it uploads, records the sha256 and gitignores the file) and commit `framefields.json`. In a fresh checkout, `npx framefields assets pull` restores them; `framefields render` pulls what’s missing itself, and `framefields preview` streams them from the bucket without downloading. `npx framefields assets status` lists each as `ok`, `missing` or `changed`. Keys come from the environment (`FRAMEFIELDS_STORAGE__*`); never print or commit them. Setup: [Assets and storage](/docs/guides/assets/). **In Git LFS**, as below, when the repo uses it. ### Set up once per repo [Section titled “Set up once per repo”](#set-up-once-per-repo) ```bash git lfs install # once per machine git lfs track "assets/fonts/**" "assets/footage/**" "assets/audio/**" \ "assets/images/**" "assets/luts/**" "assets/models/**" "assets/lottie/**" echo "output/" >> .gitignore git add .gitattributes .gitignore git commit -m "Track assets with Git LFS" ``` `git lfs track` writes the rules to `.gitattributes` (`assets/footage/** filter=lfs diff=lfs merge=lfs -text`, and so on). Commit that file before adding any media. Ignore `output/`, never `*.mp4` — that would also hide your footage. ### Push assets [Section titled “Push assets”](#push-assets) Add and push as usual; Git uploads the LFS objects with the push. ```bash git add assets/footage/interview.mp4 git lfs ls-files # the new file must be listed — otherwise it is not in LFS git commit -m "Add interview footage" git push ``` If a file was committed before its rule existed, it went into normal Git. Fix it with `git rm --cached `, `git add ` and commit again. ### Pull assets [Section titled “Pull assets”](#pull-assets) A clone with LFS installed downloads assets automatically. Anywhere else — a fresh container, a CI runner, an agent sandbox, or a clone made with `GIT_LFS_SKIP_SMUDGE=1` — fetch them before rendering: ```bash git lfs install git lfs pull # all assets for the current commit git lfs pull --include="assets/fonts/**,assets/footage/intro.mp4" # or just what this render needs ``` Check nothing is still a pointer: in `git lfs ls-files`, `*` means the file is downloaded and `-` means it is still a pointer. Pointers render blank An un-pulled LFS file is a \~130-byte text pointer starting with `version https://git-lfs.github.com/spec/v1`. framefields cannot decode it: fonts fail to register, and videos, images and audio come out blank or throw. If a render shows missing media in a fresh checkout, run `git lfs pull` before changing any code. In GitHub Actions, check out with `lfs: true` (`actions/checkout`) so the runner has the real files. ## 1. Check without the GPU [Section titled “1. Check without the GPU”](#1-check-without-the-gpu) ```bash npx tsc --noEmit -p . ``` ```ts const film = await buildFilm(); for (const d of film.lint()) console.log(`${d.severity} ${d.code}: ${d.message}${d.layerId ? ` [${d.layerId}]` : ""}`); ``` Fix every error and warning before rendering. Codes and fixes: [Lint & QA codes](/docs/reference/qa-codes/). ## 2. Look at key frames [Section titled “2. Look at key frames”](#2-look-at-key-frames) ```bash npm run frames -- 0 30 60 89 ``` Open each PNG in `output/` and compare it to what was asked. A black frame usually means a font that isn’t registered, a layer off canvas, opacity stuck at 0, or an asset that is still a Git LFS pointer (`git lfs pull`) or a pinned asset not pulled yet (`npx framefields assets pull`). ## 3. Look at motion [Section titled “3. Look at motion”](#3-look-at-motion) ```bash npm run grid -- 0 6 12 18 24 30 36 42 ``` One image of the whole move: easing hitches, text that re-wraps, wrong z-order, missing cuts. Not for vision layers (they need frames in order). ## 4. Show a person [Section titled “4. Show a person”](#4-show-a-person) ```bash npm run preview # framefields preview film; run in the background; prints the URL ``` * Give the person the URL, or open it in your own browser pane. * Read the command’s output: page errors and lifecycle lines show up there. * When they say they left notes, read `.framefields/preview-notes/notes.json` and open each open note’s `note-.jpg` before editing. Each note has the frame, the spot (`x`, `y` as fractions) and the text. * Rerun the preview after changes; the open tab reloads at the same moment. Mark notes `"done": true` when addressed. ## 5. Ship with QA [Section titled “5. Ship with QA”](#5-ship-with-qa) ```ts import { formatQaReport } from "framefields"; const result = await film.renderVideo({ outputPath: "output/film.mp4", quality: "high", qa: { targetLufs: -14 } }); console.log(formatQaReport(result.qa!)); process.exit(result.qa!.passed ? 0 : 1); ``` `qa.passed` is false on any error or warning: dropped, black or frozen frames, clipping, loudness off target, plus every lint finding. Treat it as the gate. ## 6. Render in the cloud [Section titled “6. Render in the cloud”](#6-render-in-the-cloud) To render on framefields GPUs instead of locally, commit and push (LFS assets included), then render a named render from `framefields.json`: ```bash npx framefields render film --cloud --plan # GPUs, time and estimated cost; show this to the user first npx framefields render film --cloud # render and download ``` Add a named render per cut (teaser, vertical edit) instead of flags in `render.ts`, and run `npx framefields check ` before pushing. Long films with `"workers": "auto"` split across several GPUs. Go through the [project checklist](/docs/guides/render-service/#project-checklist) first. When a render fails, read its `code` and fix the project; the API retries infrastructure errors itself. Details: [Cloud rendering](/docs/guides/cloud-rendering/). To run the worker on your own GPUs, see [Render on a server](/docs/guides/render-service/). ## In CI [Section titled “In CI”](#in-ci) A runner without a GPU renders on the CPU: on Linux once Mesa lavapipe is installed (`apt-get install -y libvulkan1 mesa-vulkan-drivers`), on Windows through the built-in WARP. That is enough for frames and short exports; run long films on a GPU runner or with [cloud rendering](/docs/guides/cloud-rendering/) (`npx framefields render film --cloud`, with `FRAMEFIELDS_API_KEY` as a CI secret). On any runner you can also gate on types and `lint()` without rendering: scripts/check.ts ```ts import { CompositorProgramSchema } from "framefields"; import { buildFilm } from "../src/film.js"; const film = await buildFilm(); const bad = film.lint().filter((d) => d.severity !== "info"); const schema = CompositorProgramSchema.safeParse(film.toSpec()); if (bad.length || !schema.success) { for (const d of bad) console.error(`${d.code}: ${d.message}`); process.exit(1); } process.exit(0); ``` ## Habits that keep agents fast [Section titled “Habits that keep agents fast”](#habits-that-keep-agents-fast) * Change one scene at a time and re-render only its frames. * Keep all magic numbers in `theme.ts`; a tweak is then one line. * Name layers with `id` — lint, QA and chart children report by id. * Put asset paths through `import.meta.url` so the preview loads them too. # Make a 3D product video with TypeScript > Put a GLB model and an animated title in the same Framefields composition, then render the result to MP4. A spinning product and a title: a small scene, but a useful starting point for a launch video. With Framefields, you can put a 3D model and 2D text in the same composition and describe the animation in TypeScript. [![](/docs/blog-media/product.jpg)](/docs/blog-media/product.mp4) The finished scene uses a simple faceted gem as the model. An orange faceted 3D gem turns beside the title “Made to move” on a dark blue background. The video has no audio. [Open the MP4](/docs/blog-media/product.mp4) or [view a still frame](/docs/blog-media/product.jpg). ## Build the scene [Section titled “Build the scene”](#build-the-scene) This example uses Framefields 2.6.2, a GLB model at `assets/models/product.glb`, and a font at `assets/fonts/Inter.ttf`. Use a model you have permission to publish. Model dimensions vary, so expect to adjust the position and scale for yours. ```ts import { Composition, FontManager, Layer, LayerAnimation, Lighting } from "framefields"; await FontManager.register({ family: "Inter", source: "assets/fonts/Inter.ttf" }); const comp = new Composition({ width: 1920, height: 1080, fps: 30, durationMs: 4000, backgroundColor: "#102450", }); comp.add(Lighting.studio({ target: [960, 540, 0] })); comp.add( Layer.glb("assets/models/product.glb", { x: 1250, y: 540, z: 0, scale: 2, }).animate( LayerAnimation.create().fromTo("rotateY", -20, 20, { start: 0, end: 119, ease: "sine.inOut", }), ), ); comp.add( Layer.text("Made to move", { position: "absolute", x: 120, y: 420, width: 700, height: 180, fontFamily: "Inter", fontSize: 100, fill: "#ffffff", }).animate(LayerAnimation.create().fadeIn(0, 20, "power2.out")), ); console.log(comp.lint()); await comp.renderVideo({ outputPath: "output/product.mp4" }); ``` Create the `output` directory first. The lighting rig sets up an environment and lights; the model turns while the title fades in. If the model is tiny, enormous, or facing the wrong way, adjust its scale and rotation. 3D assets have a knack for arriving with their own ideas about size. ## Check the scene before exporting [Section titled “Check the scene before exporting”](#check-the-scene-before-exporting) Render a few frames first with `comp.renderFrameGrid()`. Check that the model stays in frame and that the title remains readable. You can also change the lighting rig or add bloom, but it’s worth getting the basic placement right first. Framefields supports several model formats, including GLB, glTF, OBJ and FBX. The [3D guide](/docs/guides/3d/#models) lists the loaders and documents glTF material and skeletal animation support. Shadows have a constraint: only the first shadow-casting directional or spot light casts a shadow. The same guide covers lighting, bloom and other settings. For setup and export options, start with [getting started](/docs/getting-started/) and [rendering](/docs/guides/rendering/). # Create animated explainer videos with Framefields and AI > Build a clear narrated explainer with diagrams, animated text and charts, using an AI assistant to write the composition. An explainer needs a visible chain of reasoning. A viewer should be able to connect the problem, the mechanism and the result. With Framefields, you can turn that chain into scene functions and revise one explanation without rebuilding the whole film. This is a useful workflow for YouTube video creation when your subject is easier to draw than to film: an API request, a delivery route, a scientific process or a business metric. ## Choose one question [Section titled “Choose one question”](#choose-one-question) For a first project, explain “What happens after you click Buy?” in 60 seconds. Gather the approved facts before asking an assistant to write narration. Decide which parts are simplified and keep the simplification consistent. | Time | Scene | Visual idea | | ------- | ------------ | ---------------------------------- | | 0–6 s | The question | Button and receipt | | 6–20 s | Payment | Request moving between two boxes | | 20–38 s | Fulfillment | Order passing through three stages | | 38–52 s | Delivery | Route and status changes | | 52–60 s | Recap | All stages in one diagram | Record or generate the approved narration before locking timing. A script that sounds short on paper can need more time when spoken. ## Compose diagrams that explain [Section titled “Compose diagrams that explain”](#compose-diagrams-that-explain) Make a 1920×1080 composition at 30 fps. Use boxes, paths and text for the diagram, with one visual vocabulary: for example, a yellow dot always means the order. Put persistent identifiers on layers so feedback can refer to a specific element. Animate the order between stages with [LayerAnimation](/docs/guides/animation/). Keep text stable while the viewer reads it. If you use `Layer.chart`, supply your real data and label its units; a chart should add evidence, not act as decoration. Join scenes with [Layer.sequence](/docs/guides/scenes-and-transitions/), deriving the composition length from `totalFrames`. Add the narration with `Layer.audio` and an explicit `durationFrames`. Match scene boundaries to the recorded explanation rather than stretching the voice to fit a preset template. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Prompt your assistant [Section titled “Prompt your assistant”](#prompt-your-assistant) ```text Create a 60-second, 1920x1080, 30 fps Framefields explainer: “What happens after you click Buy?” Use only assets/facts.md and assets/audio/narration.wav. Use one yellow dot to represent the order through payment, fulfillment and delivery. Keep each stage in a separate scene function. Label every arrow in plain language. Use assets/captions/narration.srt for subtitles. Flag facts that lack support. Render a contact sheet and a preview with narration, then wait for editorial feedback before the final export. ``` ## Review the reasoning as well as the render [Section titled “Review the reasoning as well as the render”](#review-the-reasoning-as-well-as-the-render) Ask someone unfamiliar with the subject to explain the diagram back to you. If they misunderstand an arrow, changing its label may help more than adding another animation. Check that narration does not mention a stage before it is visible. A Framefields project is especially useful when the same explanation needs new data or another language. Store narration, labels and timing as inputs. Allow different text lengths instead of forcing every translation into the original box. For a software walkthrough with real interface footage, use the [product demo workflow](/blog/saas-product-demo-videos/). # Build before-and-after transformation videos in Framefields > Show DIY, design and makeover results clearly with matched shots, a visible process and reusable comparison layouts. A before-and-after video works when the viewer can compare the same thing under understandable conditions. Match the viewpoint, show the important process and explain what changed. Framefields can turn that into a repeatable reveal or split-screen comparison. This format fits room makeovers, repaired objects, design revisions and restored furniture. It also works as a filmmaking exercise: the impact comes from matching shots as much as from the transition between them. ## Record comparable states [Section titled “Record comparable states”](#record-comparable-states) For a 24-second desk makeover, capture the messy and finished desk from the same camera position. Lock exposure where possible, and note any lighting or equipment changes. Record two process clips that explain how you reached the result. | Time | Shot | Message | | ------- | ------------------------- | ------------------------ | | 0–3 s | Before and after together | Establish the comparison | | 3–7 s | Before | Show the starting point | | 7–15 s | Two process steps | Explain the work | | 15–21 s | Matched after shot | Reveal the result | | 21–24 s | Labeled comparison | Let viewers inspect it | A costume or decoration transformation is a seasonal variation. [Google Trends featured Frightgeist 2026 on its homepage when checked on October 31](https://trends.google.com/trends/); check local timing before borrowing a seasonal angle. ## Build the comparison [Section titled “Build the comparison”](#build-the-comparison) Use the same dimensions and crop for the before and after media. Make two full-frame scene boxes and use `Transition.wipe` for a moving reveal, or place both images in labeled side-by-side boxes for a static comparison. The [scene guide](/docs/guides/scenes-and-transitions/) explains the supported transitions. Keep the “before” and “after” labels visible during the comparison. A dramatic grade on only the final shot can obscure what the work actually changed. If lighting differs, explain that difference rather than treating it as part of the result. Store media paths, labels, durations and the change description as inputs. You can then reuse the same composition for the next makeover without rebuilding its typography and timing. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Prompt the assistant [Section titled “Prompt the assistant”](#prompt-the-assistant) ```text Build a 24-second Framefields desk transformation at 1080x1920, 30 fps. Use the matched before and after images plus two supplied process clips. Start with a labeled comparison, show the process, then make a wipe reveal and hold the final comparison for 3 seconds. Use identical crops and neutral treatment for both states. Use assets/change-notes.md for factual labels. Do not exaggerate results or generate a replacement “before.” Inspect the reveal's start, middle and end, then show a preview before export. ``` ## Inspect the transition carefully [Section titled “Inspect the transition carefully”](#inspect-the-transition-carefully) At the middle of the wipe, the object should stay aligned. If it jumps, fix the crop or choose a split screen instead. Check that the final frame gives enough time to see the result without replaying the video. For design transformations, annotate the actual decisions: contrast, spacing or navigation. For DIY, show the action that produced the result. A visible process makes the video useful beyond the surprise of its reveal. To explain a longer process, expand the sequence into a [tutorial](/blog/tiktok-reels-youtube-shorts-tutorials/). # Make behind-the-scenes videos and short vlogs with Framefields > Shape real process footage into a short vlog with a clear story, time labels and a reusable Framefields edit. A behind-the-scenes video becomes a story when something changes. You try an approach, encounter a problem and show what happened next. Framefields can organize that story while leaving the real process visible. [TikTok’s 2026 outlook highlights process and unfiltered stories](https://ads.tiktok.com/business/en-US/next). For this workflow, use that as a creative direction: show a specific decision or setback instead of filming only the polished outcome. ## Film the change [Section titled “Film the change”](#film-the-change) For a 40-second studio vlog, document the process of making a small product photograph. Capture the initial setup, the lighting problem, an adjustment and the result. Record a few seconds of room sound, too. | Time | Footage | Story beat | | ------- | ----------------------------- | --------------------- | | 0–4 s | Failed shot beside final shot | Set up the question | | 4–12 s | First lighting setup | Establish the attempt | | 12–22 s | Glare or shadow problem | Show the obstacle | | 22–34 s | Changed light position | Explain the decision | | 34–40 s | Final photograph | Pay off the opening | A beginning-to-end record is useful even if the final edit opens on the result. Keep the order of cause and effect understandable. ## Edit with a light touch [Section titled “Edit with a light touch”](#edit-with-a-light-touch) Create a 1080×1920 composition at 30 fps. Use `Layer.video` for the recorded moments and scene functions to separate each beat. Use short text labels for facts the footage cannot explain on its own: time of day, setup number or the adjustment you made. Keep a visual distinction between a timestamp and spoken captions. Use the [audio guide](/docs/guides/audio-and-signals/) to add a quiet music bed while preserving room sound or narration. Set audio layer durations explicitly so the soundtrack covers the intended film. Simple cuts often keep process footage believable. If a transition draws more attention than the change you are explaining, simplify it. Keep a few moments long enough to see hands, tools or expressions doing their work. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Give your assistant the story notes [Section titled “Give your assistant the story notes”](#give-your-assistant-the-story-notes) ```text Create a 40-second behind-the-scenes Framefields vlog, portrait, 1080x1920 at 30 fps. Use assets/shots.json: failed photo, initial setup, glare problem, lighting adjustment, final photograph. Use only real footage and the provided factual labels. Preserve cause and effect. Add the supplied voiceover and clip-relative SRT. Keep music below speech. Use cuts and restrained text entrances. Show a contact sheet and playback preview before the MP4 export. ``` ## Keep the series recognizable [Section titled “Keep the series recognizable”](#keep-the-series-recognizable) Store the opening label, date, scene notes and media paths in a per-episode record. Share the typography, spacing and closing frame across episodes. That gives the series a recognizable identity without forcing every day into an identical narrative. Before export, ask whether the viewer can identify the obstacle and the decision that resolved it. If they cannot, another caption may be less useful than a clearer shot. Keep the final result on screen long enough to compare it with the opening. For a closer comparison between two states, use the [before-and-after guide](/blog/before-after-transformation-videos/). # Make workout videos with exercise labels and interval timers > Build a reusable Framefields workout layout with visible movement, explicit interval timing and readable exercise labels. A follow-along workout needs dependable timing and a clear view of the movement. Framefields can put exercise labels, progress indicators and countdowns around your recorded demonstration, with each interval defined in frames. The same approach works for a practice drill or a movement tutorial. Keep the workout plan and coaching cues supplied by the instructor; the editing assistant’s job is to present them accurately. ## Design a one-minute interval [Section titled “Design a one-minute interval”](#design-a-one-minute-interval) Start with one instructor-approved exercise and two recorded work intervals. At 30 fps, a 20-second work interval lasts 600 frames and a 10-second rest lasts 300 frames. Decide whether your timer shows the time remaining at the start of each second or counts down another way, then use that convention throughout. | Time | Scene | Overlay | | ------- | -------------------- | ------------------------------ | | 0–5 s | Demonstration | Exercise name and supplied cue | | 5–25 s | First work interval | 20-second countdown | | 25–35 s | Rest | Next interval label | | 35–55 s | Second work interval | 20-second countdown | | 55–60 s | End | Session complete | This is an editing example, not an exercise prescription. Use the actual approved plan for the final video. ## Make the timing explicit [Section titled “Make the timing explicit”](#make-the-timing-explicit) Build a 1080×1920 composition and keep the instructor’s full movement in frame. A portrait crop that cuts off feet or hands defeats the point of the demonstration. Use `fit: "contain"` when preserving the entire source frame is more useful than filling the canvas. Use `Layer.text` for the exercise name and an overlay derived from the current interval’s local frame for the countdown. Use [signals](/docs/guides/audio-and-signals/#signals) for a progress indicator; the data should come from the same interval durations as the timer so they cannot drift apart. Separate work, rest and instruction scenes with `Layer.sequence`. Make hard cuts at interval boundaries unless you deliberately account for transition overlaps. A crossfade should not accidentally shorten a promised work period. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Ask your assistant to build it [Section titled “Ask your assistant to build it”](#ask-your-assistant-to-build-it) ```text Build a 60-second Framefields workout layout, 1080x1920, 30 fps. Use assets/workout.json for a 5-second demo, 20-second work, 10-second rest, 20-second work and 5-second ending. Use only the supplied instructor footage and approved labels. Keep the complete movement visible. Derive countdown and progress from the same frame counts. Use cuts so intervals retain their exact lengths. Inspect frames before and after every interval boundary and preview sound. Do not invent coaching cues or make fitness outcome claims. ``` ## Verify the boundaries [Section titled “Verify the boundaries”](#verify-the-boundaries) Inspect frames 149 and 150, 749 and 750, 1049 and 1050, and 1649 and 1650 for the example above. Those pairs straddle the scene changes at 30 fps. Also play the video continuously to catch a late sound cue or a distracting timer jump. Once one interval works, store the exercise names, clip paths, durations and approved cues in a playlist. Reusing that data keeps the timer aligned with the instruction even when the order changes. For a shorter instructional cut, use the [vertical tutorial guide](/blog/tiktok-reels-youtube-shorts-tutorials/). # framefields 3: what's new since 2.2 > Twenty-five days and 29 releases after 2.2, framefields has a 3D world, a path tracer, physics, on-device tracking, your own shaders, a style library and renders that split across GPUs. Here's what changed and what to check before you upgrade. framefields 2.2 came out on 17 October. Since then we’ve shipped 29 releases, and today’s 3.0 rounds them off. It’s the same engine as before. You still write a composition in TypeScript and render it on WebGPU, and coding agents can still drive it. What’s new is how much you can put in that composition. This post walks through the main additions in the order you’ll probably meet them. If you’d rather watch than read, the [framefields 3 page](/v3/) shows each one in a film the engine rendered. [![](/v3/media/hero.jpg)](/v3/media/hero.mp4) A Schwarzschild black hole, ray traced in one `Layer.shader`, from `examples/41_hawking_radiation`. ## Write the pixel yourself [Section titled “Write the pixel yourself”](#write-the-pixel-yourself) New in 3.0, `Layer.shader` is a layer drawn by your own WGSL fragment function. Each uniform can be a number, a signal or a function of the frame, so a shader can follow the beat or a keyframed value without any extra plumbing. ```ts Layer.shader({ width: 1920, height: 1080, uniforms: { zoom: 2, pulse: kick, sweep: (ctx) => ctx.frame / 90 }, fragment: ` fn shade(uv : vec2) -> vec4 { let p = (uv - 0.5) * vec2(u.resolution.x / u.resolution.y, 1.0) * u.zoom; let ring = smoothstep(0.02, 0.0, abs(length(p) - 0.3 - 0.1 * u.pulse)); return vec4(vec3(ring) * u.sweep, 1.0); }`, }); ``` Once it’s on the timeline, it behaves like any other layer. You can animate its opacity, put effects on it or use it as a matte. If a fragment doesn’t compile, the error gives line numbers in your own source, not in the code the engine wraps around it. The [launch page](/v3/#shader) has an editor where you can try the same contract in your browser. ## A 3D engine moved in [Section titled “A 3D engine moved in”](#a-3d-engine-moved-in) Most of the work between 2.3 and 2.15 went into 3D. You can now build whole scenes in the same timeline as your type and footage: * **Worlds.** `Layer3D.terrain`, `Layer3D.sdf` and `Layer3D.scatter` build landscapes, smooth sculpted solids and wind-blown foliage. Any layer, including a video, can texture a mesh. * **Surfaces.** glTF models bring their own clearcoat, sheen, anisotropy and iridescence. Skin’s subsurface scattering now conserves energy, so skin looks less washed out, and glass bends the scene behind it using the IOR and thickness from the model file. * **Characters.** Clip blending, two-bone IK, look-at, spring bones, joint drivers and named morph targets. `Layer3D.instances` plays a skinned crowd in one draw call. * **Things breaking.** `world.fracture()` shatters a solid, a piece of extruded text or a model into pieces that break on impact. * **Lenses.** Per-object motion blur, outlines and toon lighting, 360° and fisheye cameras, and a relativistic camera that films the scene as it would look near the speed of light. [![](/v3/media/valley.jpg)](/v3/media/valley.mp4) Terrain, scatter and wind, all from TypeScript. A box with a fixed size that holds a camera is now its own scene. Its camera and lights see only its layers, and it runs on its own clock. So a `Layer.sequence` transition between two 3D scenes blends two finished pictures instead of drawing both through one camera. The [3D guide](/docs/guides/3d/) covers the details. ## Things fall, collide and scatter [Section titled “Things fall, collide and scatter”](#things-fall-collide-and-scatter) Version 2.3 added rigid-body physics. `Physics.world2d` and `Physics.world3d` simulate once while the composition is built, then replay frame by frame, so a render gives the same result every time and you can scrub through it. Each body exposes signals for impact, speed and pose, and you can connect them to anything. ```ts const world = await Physics.world2d({ fps: 24, frames: 150 }); world.walls({ width: W, height: H }); world.body(card, { restitution: 0.35 }); world.simulate(); glow.animate(LayerAnimation.create().signal("opacity", world.impact)); ``` GPU particles arrived in the same release. They run in a compute shader with emitters, flow fields, attractors and floors, and a performer’s silhouette can push them around. [![](/v3/media/dancer.jpg)](/v3/media/dancer.mp4) Here the words are physics bodies, and the dancer’s tracked silhouette knocks them about. See the [physics guide](/docs/guides/physics/). ## Follow anyone, cut anything out [Section titled “Follow anyone, cut anything out”](#follow-anyone-cut-anything-out) On-device vision got much stronger. `comp.vision(clip, { sam2 })` tracks a subject from a point or a box with SAM 2.1. `{ sam3: { text: "man in white shirt" } }` picks out people or objects from plain words, several at once if you need them, and catches new ones as they walk in. `matting: true` runs ViTMatte over the edge of the mask, so a cutout keeps hair and motion blur instead of a hard outline. Depth Anything lifts footage into a relief that a 3D camera can move around. All of this runs on your own machine. The models are pinned by SHA-256 and download the first time you use them. SAM 3’s weights download only after you accept Meta’s SAM License. Masks still aren’t perfect: fast movement and thin edges can trip them up, so check your frames. The [vision guide](/docs/guides/vision/) shows how. ## Twenty-one looks, one line each [Section titled “Twenty-one looks, one line each”](#twenty-one-looks-one-line-each) Thirteen new stylize effects (pixelate, posterize, dither, ASCII, toon, CRT, painterly, contour and more) and `Styles` presets that stack them into finished looks: ```ts clip.withEffects(Styles.vhs()); ``` [![](/v3/media/style-vhs.jpg)](/v3/media/style-vhs.mp4) There are also `gameBoy`, `ledWall`, `risograph`, `comic`, `thermal`, `oilPainting`, `holographic`, `noir` and a dozen others. `LayerAnimation.stepped(2)` puts any layer on twos. The [launch page](/v3/#looks) plays the same clip in each look. ## Type with every axis, paths as drawn [Section titled “Type with every axis, paths as drawn”](#type-with-every-axis-paths-as-drawn) Text now takes a variable font’s axes with `fontVariations: { wdth: 68 }`. Layout measures the text at those axes, and it draws the same way in 2D and 3D. A few long-standing path bugs are fixed too: * `strokeDashArray` renders. * Paths with several subpaths fill with their holes. * Keyframing a shape’s `d` morphs one path into another, even when the two have different point counts. * Strokes draw in one call per path, about twice as fast on a map with coastlines and a hundred circles. ## A brief, not a blank page [Section titled “A brief, not a blank page”](#a-brief-not-a-blank-page) The other headline in 3.0 is the style library. It’s creative direction as data: six looks, six formats, six genres, five ways to make the pictures, and presets that combine them. `combineStyles` turns one mix into a single brief: ```ts import { combineStyles, styleClashes } from "framefields/styles"; const brief = combineStyles({ look: "motion", format: "vertical", genre: "product-launch" }); const watch = styleClashes({ look: "blueprint", format: "ad-spot", genre: "brand-film" }); ``` The brief says which palette, type, pacing, music and grade to use, and how AI-generated clips should match the drawn graphics. It’s also what your agent reads when you ask for a video “in the style of” something. ## Your agent reads the manual that matches [Section titled “Your agent reads the manual that matches”](#your-agent-reads-the-manual-that-matches) The agent guides now ship inside the package, at `node_modules/framefields/dist/skills/`. Each release carries guides written for its own API, so an agent always reads the ones that match the framefields it has installed. Around them: * `framefields init` writes a working project and never prompts or overwrites. * `framefields add` copies any of 26 components into your project, along with the fonts they need. * `framefields check --json` returns schema, lint and timeline findings an agent can act on. * Render logs fit an agent’s context: about 15 lines, whatever the film’s length. * `import { ai } from "framefields"` reaches image, video, music and voice models with one key. See the [AI guide](/docs/guides/ai/). Start with [agents](/docs/agents/) to see how it fits together. ## One film, many GPUs [Section titled “One film, many GPUs”](#one-film-many-gpus) A long render can now split into chunks. Each chunk starts on a keyframe and renders on its own GPU, and the chunks are stitched back together without re-encoding. From the CLI it’s one flag, and `--plan` tells you the workers, time and estimated cost before anything renders: ```bash npx framefields render film --cloud --workers auto --plan ``` Named renders in `framefields.json` mean the CLI, `renderCloud` and the dashboard pick the same cut by name. `framefields assets` keeps footage out of git on any S3-compatible bucket, pinned by SHA-256. And `framefields preview` now streams those files and mixes the soundtrack in the browser, sample for sample the same as the export. Read the [cloud rendering guide](/docs/guides/cloud-rendering/) to set it up. ## Light, traced [Section titled “Light, traced”](#light-traced) framefields now has a path tracer (from 3.0.1). Add `pathTrace: true` to the environment and the scene’s 3D layers are traced instead of rasterized. Shadows soften with distance, reflections show things the camera can’t see, glass bends what’s behind it, and light bounces from surface to surface. A glowing mesh lights the room around it. ```ts Layer.environment("night", { floor: { y: 420, color: "#22252c", reflectivity: 0.35 }, pathTrace: true, }); ``` [![](/v3/media/glass.jpg)](/v3/media/glass.mp4) Glass, path traced: an iridescent lamp globe, two glasses of flowers and a mosquito in amber, lit by a studio’s window, from `examples/43_path_tracer`. Models from the Khronos glTF samples (Wayfair and Sketchfab, CC-BY 4.0; vase CC0), light from Poly Haven (CC0). It runs on WebGPU compute, like the rest of the engine, and uses the same lights, materials and tone mapping as the raster renderer. So a scene looks like itself with tracing on, only with the light worked out properly. A render takes the same number of samples per pixel on any GPU, so frames come out identical every time and split cloud renders join cleanly. The preview adapts to your GPU instead, so scrubbing stays responsive. It costs time. At the default quality a 1080p frame of a simpler scene, a character and a glowing ring, takes about 12 seconds on an M1 Pro, and this glass still life about 30, so iterate on `quality: "draft"` and switch back for the final render. Some features aren’t traced yet, including text on a 3D plane, toon shading and instanced crowds, and the render tells you which one it hit. The [3D guide](/docs/guides/3d/#path-tracing) has the presets and the rules. ## Sculpt in code [Section titled “Sculpt in code”](#sculpt-in-code) New in 3.1: `Layer3D.clay` is a sculpture you write as a list of moves, the way you’d work clay by hand. Solids and brush strokes add or carve material, with smooth joins where they meet. `grab`, `twist` and `bulge` push what’s already there around like an elastic solid. `inflate` swells a region, and `detail` adds stone or skin texture. `symmetry: "x"` mirrors everything you do on one side. ```ts Layer3D.clay({ symmetry: "x", ops: [ { type: "sphere", center: [0, -70, 0], radius: 72 }, { type: "stroke", path: [[0, -48, -48], [0, -38, -100]], radius: 34, smoothness: 20 }, // snout { type: "stroke", path: [[40, -122, 10], [72, -160, 30], [86, -200, 72], [72, -228, 110, 4]], radius: 16 }, // horn { type: "sphere", center: [30, -74, -66], radius: 15, mode: "carve" }, // eye socket { type: "grab", center: [0, -14, -104], radius: 26, delta: [0, 16, -6] }, // pull the chin { type: "detail", amplitude: 2.2, scale: 22, ridged: true }, // stone ], }); ``` [![](/v3/media/sculpt.jpg)](/v3/media/sculpt.mp4) The bust is built from the same list of moves, shown a few more at a time as the camera circles. The horns grow along their strokes with `progress`. The film is `examples/45_sculpture`, and it renders at 1080p in about 0.2 seconds a frame on an M1 Pro. The sculpture is never turned into polygons to be drawn. Each pixel is worked out from the moves themselves, so edges and texture stay sharp however close the camera gets, and there’s no polygon count to pick. It casts and catches shadows like any other mesh. Path tracing, glass and physics use a mesh made from the same moves. A finished sculpture can also leave framefields. `comp.exportModel({ frame, outputPath: "bust.glb" })` writes the frame’s 3D scene as glTF, with the camera and lights, and it opens as it rendered in Blender, Unreal, Unity or a web viewer. The [3D guide](/docs/guides/3d/#sculpting) lists every move. ## Before you upgrade [Section titled “Before you upgrade”](#before-you-upgrade) 3.0 is a major release for one visible change: **shape strokes now draw their outer half** instead of being cut off at the shape’s layout box. If a film relied on that clipping, outlines will look thicker in 3.0. Two earlier changes are also worth a look if you’re coming straight from 2.2: * Containers default to `overflow: "visible"`, as in CSS (since 2.14). Set `overflow: "hidden"` on a box whose children have to stay inside it, such as a rounded card holding a square image. * A keyframe track holds its first value until it’s reached (since 2.13.1). A fade that starts at frame 40 is now invisible until frame 40, rather than fully visible and then snapping out. Render a contact sheet before and after you bump the version, and compare them. The [full changelog](https://github.com/gatewai-dev/framefields/blob/main/packages/framefields/CHANGELOG.md) lists every change, release by release. ## Try it [Section titled “Try it”](#try-it) ```bash npx framefields init my-film ``` Or give the [agent prompt](/docs/agents/prompts/) to Claude Code, Codex or Cursor and let it install framefields, read the guides and render a first film. If you’d rather not use a terminal, the desktop app below does the same from a conversation. # Edit gaming highlights for Shorts and TikTok with Framefields > Build a gaming highlight around setup, action and payoff, with deliberate crops and readable context overlays. A gaming highlight needs context before the payoff. Show the situation, let the important action play and give the viewer a moment to understand what happened. Framefields can wrap that edit in reusable team colors, score labels and end cards. For creators used to CapCut, the workflow still starts with choosing a good moment. The reusable part is the composition around it: the same source clip and event notes can drive a vertical highlight and a landscape recap. ## Choose one complete moment [Section titled “Choose one complete moment”](#choose-one-complete-moment) For a 20-second highlight, pick a play with an understandable setup and result. Note the source timestamps, relevant player names and what viewers need to notice. Do not rely on an animated caption to explain a play that the crop makes impossible to see. | Time | Footage | Context | | ------- | ------------------------- | ----------------------------------- | | 0–3 s | Situation before the play | Short factual setup | | 3–13 s | Complete action | Keep important HUD elements visible | | 13–17 s | Outcome | Let the result register | | 17–20 s | Creator or team card | One next step | If the play takes longer, expand the edit. Trimming out the decisive action to hit an arbitrary length makes a weaker highlight. ## Build two intentional layouts [Section titled “Build two intentional layouts”](#build-two-intentional-layouts) Use `Layer.video` with an approved `trimStartSec` and duration. For the vertical version, choose between a close crop and a contained gameplay frame with designed space above and below. Inspect the HUD before deciding; some games lose essential information in a center crop. Add `Layer.text` for the situation and result. Keep names and scores sourced from the event notes. Preserve game audio and voice chat where appropriate, and avoid drowning the decisive moment in an added impact sound. For this workflow, use ordinary source playback and hard cuts. It does not require a speed-ramp API or automatic event detection. The [media guide](/docs/guides/charts-and-media/) documents footage placement and trimming, while the [animation guide](/docs/guides/animation/) covers overlay entrances. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Give the assistant an edit brief [Section titled “Give the assistant an edit brief”](#give-the-assistant-an-edit-brief) ```text Create a 20-second Framefields gaming highlight at 1080x1920, 30 fps, from the approved source interval in assets/highlight.json. Preserve setup, complete action and outcome. Use the event notes for names and score. Choose a layout that keeps the important HUD and action visible; do not assume a center crop is sufficient. Use original audio, restrained captions and a 3-second creator card. No invented game events or automatic highlight-detection claims. Render key frames, then preview the full action with sound. ``` ## Watch like someone new to the game [Section titled “Watch like someone new to the game”](#watch-like-someone-new-to-the-game) Can a new viewer tell what the objective is and whether the player achieved it? If not, add one factual context line before the action. Avoid covering a crosshair, map or score with that line. Keep the source interval and layout choice with each output. For the landscape version, rebuild the overlay positions around the wider frame rather than stretching the portrait export. Check the platform’s current upload requirements when publishing; Framefields produces the file, while upload and audience testing happen elsewhere. For a narrated breakdown of the play, expand it into an [explainer](/blog/animated-explainer-videos/). # Animate text letter by letter with TypeScript > Make a kinetic title with Framefields, inspect a few frames, and export it to MP4. Animate a title letter by letter in TypeScript, then render it to MP4 with Framefields. Change the words and the same animation works with the new text. [![](/docs/blog-media/title.jpg)](/docs/blog-media/title.mp4) The finished title, rendered from the code below. A white title reading “Make something move” appears letter by letter on a dark blue background. The video has no audio. [Open the MP4](/docs/blog-media/title.mp4) or [view a still frame](/docs/blog-media/title.jpg). ## Make a title [Section titled “Make a title”](#make-a-title) Start with a [Framefields project](/docs/getting-started/). The example uses Framefields 2.6.2 and a local font file at `assets/fonts/Inter.ttf`. Register the font before creating the text layer: Framefields doesn’t ship fonts or pick one from your system for headless rendering. ```ts import { Composition, FontManager, Layer, LayerAnimation, TextAnimator } from "framefields"; await FontManager.register({ family: "Inter", source: "assets/fonts/Inter.ttf" }); const comp = new Composition({ width: 1920, height: 1080, fps: 30, durationMs: 3000, backgroundColor: "#102450", }); const title = Layer.text("Make something move", { position: "absolute", x: 160, y: 420, width: 1600, height: 240, fontFamily: "Inter", fontSize: 120, fill: "#ffffff", animators: [TextAnimator.waveRise({ y: 60, rotationX: 45 })], }).animate(LayerAnimation.create().kineticSweep(-1, 1, 0, 40)); comp.add(title); console.log(comp.lint()); await comp.renderVideo({ outputPath: "output/title.mp4" }); ``` Create the `output` directory before running the script. At 30 frames per second, the sweep takes 40 frames, or about 1.3 seconds. Try a shorter sweep for a snappier entrance. If your title wraps, give it more width or reduce the font size. ## Check the in-between bits [Section titled “Check the in-between bits”](#check-the-in-between-bits) A title can look fine at the start and end but clip halfway through. Before a full export, render a contact sheet: ```ts await comp.renderFrameGrid({ frames: [0, 10, 20, 30, 40, 60], columns: 3, outputPath: "output/title-grid.png", }); ``` Look for cropped letters and awkward line breaks. If you want words or lines to move together, pass `unit: "word"` or `unit: "line"` to `waveRise`. The default is `"character"`. There are also presets for blur, flips, color sweeps and word pops in the [animation guide](/docs/guides/animation/#kinetic-typography). This is useful when the same title treatment needs to work across many names, headlines or languages. You still need to check the result: different text takes up different space, and fonts need to cover the characters you use. For font registration and text layout, see the [text guide](/docs/guides/layout-and-text/#text). For more ways to inspect a composition before export, see [rendering](/docs/guides/rendering/). # Create music visualizers and lyric videos with Framefields > Turn a track into an audio-reactive visualizer or timed lyric video with signals, typography and a reusable visual theme. A music visualizer gives a track a visual identity without requiring a new filmed scene for every section. A lyric video adds another job: words must arrive at the right moment and stay readable. Framefields supports both through audio layers, signals and animated text. Start with a track you can use and, for lyrics, the approved text and timings. Keep visual design separate from those source inputs so you can make another release in the same style. ## Plan a 30-second excerpt [Section titled “Plan a 30-second excerpt”](#plan-a-30-second-excerpt) Choose an excerpt with a clear build and a musical payoff. Mark its source in-point and the timing of each phrase before animating anything. For a lyric video, make an SRT relative to the excerpt rather than the full song. | Time | Visual | Intention | | ------- | -------------------------- | -------------------------- | | 0–5 s | Artwork and track title | Establish identity | | 5–12 s | Gentle motion | Leave room for the opening | | 12–24 s | Stronger response | Follow the musical build | | 24–28 s | Resolve the motion | Let the phrase finish | | 28–30 s | Artist and track reference | Close clearly | The visual intensity should follow what you hear. More particles or a bigger pulse are creative choices, not proof that the music has more energy. ## Drive motion from audio [Section titled “Drive motion from audio”](#drive-motion-from-audio) Use `Layer.audio` with an explicit duration covering the excerpt. You can precompute an amplitude envelope and feed it into `Signal.fromArray`, then bind that signal to scale, opacity or an effect parameter. The [audio and signals guide](/docs/guides/audio-and-signals/#audio-reactive-visuals) describes this approach and audio analysis options. A periodic signal at a known tempo is also useful, but it is a designed pulse rather than detected beats. Label your implementation correctly. Keep random motion seeded if you need repeatable renders. For line-based lyrics, use `Layer.caption` with the supplied SRT. For word animation, create explicitly timed text layers and use [TextAnimator](/docs/guides/animation/#kinetic-typography). A line-level subtitle file does not automatically contain word-level timing. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Prompt your assistant [Section titled “Prompt your assistant”](#prompt-your-assistant) ```text Create a 30-second Framefields music visualizer at 1920x1080, 30 fps, using assets/audio/excerpt.wav and assets/images/artwork.png. Use a precomputed amplitude envelope for restrained scale and glow changes. Keep title and artist readable. Add the approved lyrics from assets/captions/excerpt.srt with line-level timing; do not invent lyrics or claim word-level sync. Keep the full audio duration. Inspect quiet and loud sections, then preview the export with sound. Make a separate portrait layout after the landscape version is approved. ``` ## Review timing and intensity [Section titled “Review timing and intensity”](#review-timing-and-intensity) A contact sheet can show whether the design clips at its largest scale. Playback reveals whether the motion lags the music or the lyric changes happen early. Check the first and last audio samples so the excerpt does not start with a click or end halfway through a word. For a release series, keep artwork, metadata, audio paths, envelope data and caption paths in a track record. Reuse the composition while checking every new title and lyric for wrapping. For speech-led clips, follow the [podcast caption workflow](/blog/podcast-clips-with-captions/). # Turn podcast episodes into captioned vertical clips > Create podcast clips with deliberate excerpts, readable subtitles and speaker layouts using Framefields and an AI assistant. A podcast clip needs to make sense to someone who has never met the host. Choose a passage with a complete thought, include the context it needs and let the speaker finish. Framefields can turn those editorial decisions into a consistent vertical video layout. The source format has a substantial audience: [YouTube reported more than one billion monthly podcast viewers in May 2026](https://blog.youtube/news-and-events/new-youtube-premium-features-podcast-fans/). That does not guarantee demand for any individual clip, but it makes podcast repurposing a useful workflow to learn. ## Choose the excerpt before the layout [Section titled “Choose the excerpt before the layout”](#choose-the-excerpt-before-the-layout) Read a timestamped transcript alongside the recording. Pick a 35-second passage where a guest explains one mistake and how they fixed it. Keep the exact source in-point and out-point in your notes. If the answer relies on the host’s question, include it or provide a faithful context line. | Time | Layout | Editorial role | | ------- | -------------------------- | ------------------------------ | | 0–4 s | Speaker and short headline | Orient a new viewer | | 4–27 s | Speaker with captions | Deliver the complete idea | | 27–32 s | Same layout | Preserve the conclusion | | 32–35 s | Small episode reference | Point to the full conversation | Avoid opening on a dramatic sentence if the rest of the clip changes its meaning. ## Assemble the clip [Section titled “Assemble the clip”](#assemble-the-clip) Use `Layer.video` with `trimStartSec` for the source in-point, then set the excerpt duration. Crop deliberately for a single speaker. When two people speak, use a designed split layout or planned cuts; do not assume automatic speaker switching. Prepare an SRT whose timestamps start at the beginning of the exported clip. Subtract the source in-point from episode timestamps, remove cues outside the excerpt and proofread names. Use `Layer.caption` to display it. See [media and captions](/docs/guides/charts-and-media/) for supported layers. Keep the subtitle area away from faces and platform controls. Use short phrases that preserve meaning, and review the most text-heavy frame on a phone. Music is optional; clear dialogue matters more than filling silence. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Ask your assistant to edit [Section titled “Ask your assistant to edit”](#ask-your-assistant-to-edit) ```text Build a 35-second Framefields podcast clip at 1080x1920, 30 fps. Use assets/footage/episode.mp4 from the approved in-point in assets/clip.json. Use the clip-relative captions in assets/captions/. Preserve the speaker's complete argument. Use deliberate crops; show both speakers when the notes request a split layout. Add the approved headline and episode reference. No invented quotes, automatic speaker switching or generated transcript assumptions. Inspect subtitle-heavy frames and show a preview with dialogue. ``` ## Make the next excerpt easier [Section titled “Make the next excerpt easier”](#make-the-next-excerpt-easier) Store each clip’s source timestamps, title, speaker names, caption path and output ID together. A shared layout then supports a series without hiding which editorial decisions produced each clip. Check the first and last words against the original episode. Also listen for clipped consonants at the cut and watch for captions ending early. A contact sheet catches layout issues; only playback catches whether a sentence has room to land. For a clip built around music instead of speech, try [audio-reactive visualizers](/blog/music-visualizer-lyric-videos/). # Edit product review and unboxing videos with Framefields > Turn real product footage into a structured review with close-ups, test results, captions and a reusable verdict card. A useful product review answers a buying question with visible evidence. An unboxing can introduce the item, but the test is what makes the video useful: show what happened, under what conditions and who the product might suit. Framefields can organize your footage into a repeatable review format. Keep the actual observations in a data file and let the composition handle chapter cards, comparison labels and the final verdict. ## Start with one test [Section titled “Start with one test”](#start-with-one-test) For a 45-second desk microphone review, record the contents of the box, the setup and two audio samples. Use the same distance and room for both samples. Document the microphone settings before editing. | Time | Picture | Evidence | | ------- | -------------------- | ----------------------------- | | 0–4 s | Microphone in use | Preview the buying question | | 4–10 s | Box contents | Show what is included | | 10–18 s | Connection and setup | Reveal the practical friction | | 18–35 s | Two labeled samples | Let the viewer compare | | 35–45 s | Verdict card | Best use and one limitation | A portrait version works for a short review. If the comparison needs longer listening, make a landscape version with full samples instead of cutting away the evidence. ## Keep sound comparisons honest [Section titled “Keep sound comparisons honest”](#keep-sound-comparisons-honest) Use `Layer.video` for footage and `Layer.text` for test labels. During an audio comparison, remove the music bed and avoid processing one sample differently from the other. If you normalize samples, tell the viewer and apply the same stated method. Store the product name, test conditions and observations separately from the layout. Use [charts](/docs/guides/charts-and-media/#charts) only for measurements you actually made. A subjective impression should stay a labeled observation, not become a fabricated numerical score. For ordinary unboxing footage, cuts and restrained text animation are enough. A different effect on every shot can make the viewer work harder to inspect the product. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Give your assistant the evidence [Section titled “Give your assistant the evidence”](#give-your-assistant-the-evidence) ```text Build a 45-second Framefields microphone review, 1080x1920, 30 fps. Use assets/shots.json and assets/review-notes.md. Include unboxing, setup, two complete labeled audio samples, then a verdict with one strength and one limitation. Music must stop during the samples. Keep both samples at the supplied levels; do not add enhancement. Never invent measurements, prices or a recommendation absent from the notes. Include the supplied sponsorship disclosure if applicable. Show a preview with sound before exporting. ``` ## Review the verdict against the footage [Section titled “Review the verdict against the footage”](#review-the-verdict-against-the-footage) Play the samples on headphones and a phone speaker. Make sure the labels stay on the right sample after every cut. Confirm that the verdict follows the test rather than overstating it. When you review the next item, reuse the scene structure and swap the evidence. If your template assumes every product has three advantages, change the template; a review should fit what you found. For a brand-owned promotional version, use the separate [UGC-style ad workflow](/blog/ugc-style-video-ads/). # Create recipe and cooking videos with Framefields > Turn kitchen footage into a readable recipe video with ingredient cards, step labels and accurate cooking times. A recipe video should make the next action clear. Show the texture a cook is aiming for, put quantities where they are needed and distinguish elapsed cooking time from the duration of the edit. Framefields can keep those details consistent across a cooking series. Use your tested recipe as the source of truth. An assistant can organize the footage and labels, but quantities, temperatures and doneness cues should come from the recipe you actually cooked. ## Plan a short recipe edit [Section titled “Plan a short recipe edit”](#plan-a-short-recipe-edit) For a 35-second roasted vegetable video, film the finished plate, ingredients, preparation, tray going into the oven and the final texture. Capture the labels on measuring tools or keep a written record alongside the footage. | Time | Shot | On-screen information | | ------- | ---------------- | ------------------------------- | | 0–3 s | Finished dish | Recipe name | | 3–8 s | Ingredients | Exact quantities | | 8–17 s | Chop and season | Size and seasoning | | 17–25 s | Tray and oven | Tested temperature and duration | | 25–31 s | Finished texture | Doneness cue | | 31–35 s | Plate and recap | Where to find the full recipe | Shortening the edit does not shorten the cooking. A clear “roast for …” label helps viewers understand a jump cut over the oven stage. ## Assemble the recipe [Section titled “Assemble the recipe”](#assemble-the-recipe) Use `Layer.video` for each action and `Layer.text` for ingredient quantities. Make a scene for each recipe stage and join them with cuts using `Layer.sequence`. Put the step label away from the hands and utensils so it does not cover the action. Keep quantities in a recipe data file and format them into the scene. Do not ask the composition to guess amounts from the footage. If you offer metric and imperial variants, have both checked before exporting the versions. Preserve useful kitchen sound where it supports the action. If there is narration, use a proofread SRT with `Layer.caption`. An ingredient card can remain visible longer than a spoken caption; it needs enough time to be read and followed. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Prompt your assistant [Section titled “Prompt your assistant”](#prompt-your-assistant) ```text Build a 35-second Framefields cooking video, 1080x1920 at 30 fps. Use assets/recipe.json as the only source for quantities, temperature, cooking duration and doneness. Use assets/shots.json for the footage. Show the dish first, then ingredients, preparation, oven stage and final texture. Keep hands and food clear of text. Distinguish edit time from elapsed cooking time. Do not invent substitutions or nutrition claims. Preview ingredient-heavy frames and playback with sound before exporting the MP4. ``` ## Check the video while following the recipe [Section titled “Check the video while following the recipe”](#check-the-video-while-following-the-recipe) Pause at each stage and ask whether someone could perform the action using the information shown. Check all numbers against the written recipe, especially an oven temperature and its unit. Make sure a cut has not hidden a necessary step. For content creation at scale, keep the visual theme shared and the recipe facts separate. You can reuse title cards and timing patterns while giving a more complicated recipe the extra screen time it needs. See [media layers](/docs/guides/charts-and-media/) for footage and caption options, or the [tutorial workflow](/blog/tiktok-reels-youtube-shorts-tutorials/) for longer lessons. # Make SaaS product demo videos from real screen recordings > Combine screen recordings, feature callouts and a clear before-and-after workflow in a reusable Framefields demo. A product demo earns its running time by showing a real task getting easier. Choose one task, capture the actual interface and let the viewer see the result. Framefields adds framing, callouts, titles and timing around that evidence. For a team already editing demos in CapCut or Adobe Premiere Pro, the useful difference is repeatability. A feature name, screenshot or callout can live in a data file while the composition stays consistent across releases. ## Capture a complete task [Section titled “Capture a complete task”](#capture-a-complete-task) Use a fictional scheduling app as your example: create a booking link and share it. Record a clean walkthrough with example data. Keep a note of the source timestamps where each action starts and ends. | Time | Edit | Purpose | | ------- | ---------------------------- | ---------------------------- | | 0–4 s | Booking page already working | Establish the outcome | | 4–12 s | Set availability | Show the first action | | 12–23 s | Configure the link | Explain the main feature | | 23–33 s | Open the recipient view | Prove it works | | 33–40 s | One next step | Tell viewers where to try it | Choose a 1920×1080 master for a desktop product tour. Create a separate 1080×1920 layout for social feeds, with close crops and larger callouts. ## Build a reusable composition [Section titled “Build a reusable composition”](#build-a-reusable-composition) Use `Layer.video` with `trimStartSec` to start at each recorded action. Set a scene or layer duration to end that excerpt. Add callouts as text and shape layers, anchored to the visible feature rather than floating over unrelated controls. Keep the product recording recognizable. An animated pointer can help explain a click, but it should follow the recorded action. Drawn interface mockups are useful for an overview; label them as illustrations if you use them instead of real product footage. Separate a shot list from the theme: source path, in-point, duration, crop and callout text belong in the shot list. Font, color and spacing belong in the theme. See [media layers](/docs/guides/charts-and-media/) and [text layout](/docs/guides/layout-and-text/) for the building blocks. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Ask an assistant to assemble it [Section titled “Ask an assistant to assemble it”](#ask-an-assistant-to-assemble-it) ```text Create a 40-second Framefields product demo at 1920x1080, 30 fps. Use assets/footage/booking-demo.mp4 and assets/shots.json for approved in-points, durations, crops and callouts. Open with the completed booking page. Show availability, link setup and the recipient view. Do not invent product features. Preserve source action order. Add a single CTA from assets/copy.md. Export buildFilm(), inspect frames at every callout, and provide a preview with source audio. After review, create a separate portrait layout with readable crops. ``` ## Check for a usable demonstration [Section titled “Check for a usable demonstration”](#check-for-a-usable-demonstration) Watch for tiny interface text, a callout hiding the control, a cut that removes a required action, or a CTA with an outdated URL. Keep the product version with the source assets so you know when a recording needs replacing. Measure whether viewers reach the demonstrated result and take the intended next step. A view count alone cannot tell you whether the demo explained the product. For a physical item, follow the [product review and unboxing workflow](/blog/product-review-unboxing-videos/). # Framefields is the engine behind Gatewai Studio > The engine behind Framefields has been running in production at Gatewai Studio for six months. Here's where it comes from and what you can build with it. Framefields is the engine behind [Gatewai Studio](https://gatewai.studio), and it has been running there in production for six months. That experience has made it mature enough to use for real video projects today. Gatewai Studio is a visual workspace for building media workflows and compositions. People can bring together video, images, text and audio, then render the result. Framefields comes from the engine behind that work. It isn’t a brand-new rendering experiment we put together for a launch. ## From a visual studio to code [Section titled “From a visual studio to code”](#from-a-visual-studio-to-code) With Framefields, you can build a composition in TypeScript and render it with WebGPU. That makes the engine accessible to developers and coding agents as well as people working in a visual studio. You can animate text, combine 2D graphics with 3D models, apply effects, work with audio and use vision models. If you’d like to see the output before reading the API, start with our examples: [animated titles](/blog/kinetic-typography-typescript/), [a 3D scene](/blog/3d-product-video-typescript/) and [a segmented video](/blog/track-person-attach-graphics/). ## A practical way to work [Section titled “A practical way to work”](#a-practical-way-to-work) We know that making a video is rarely a one-render job. A title wraps, an asset is the wrong size, or the timing just feels a little off. Framefields lets you check a composition with `lint()`, render a single frame or a contact sheet, and use a [live preview](/docs/guides/preview/) before exporting the full video. The [rendering guide](/docs/guides/rendering/) covers the workflow. Six months in production gives the engine a real history. It doesn’t mean every composition or machine will behave perfectly. You’ll still need to register fonts, check your assets and inspect your output. Vision masks, for example, can miss parts of a subject or lag at moving edges. We think it’s better to show those details than pretend they don’t exist. If you’re curious, the [getting started guide](/docs/getting-started/) will take you through your first render. The [source is on GitHub](https://github.com/gatewai-dev/framefields), too. # Make tutorial videos for TikTok, Reels and YouTube Shorts > Turn one useful lesson into a vertical tutorial with timed steps, captions and a reusable Framefields project. A useful tutorial answers one question completely. Start with the finished result, show the actions that produce it, and leave enough time to read each step. Framefields lets you keep that structure in TypeScript so the next lesson uses the same layout, typography and timing rules. If you usually make cuts and add text in CapCut, think of this project as a reusable version of that edit: footage becomes video layers, instructions become text layers, and timing becomes frame numbers. You can still make creative decisions in a preview. ## Plan a 30-second lesson [Section titled “Plan a 30-second lesson”](#plan-a-30-second-lesson) Use a simple example: showing someone how to organize a messy desktop into three folders. Record the actual process first. A promise such as “Find any download in three clicks” gives the viewer something specific to judge. | Time | Picture | Message | | ------- | --------------------------- | -------------------- | | 0–3 s | Finished, organized desktop | Show the result | | 3–10 s | First action | Create three folders | | 10–18 s | Second action | Sort by file type | | 18–26 s | Third action | Save the search | | 26–30 s | Repeat the result | One sentence recap | These are editing targets, not a platform rule. If the task needs more explanation, make a longer lesson instead of speeding up every action. ## Build the edit in Framefields [Section titled “Build the edit in Framefields”](#build-the-edit-in-framefields) Start at 1080×1920 and 30 fps. Put the screen recording in `assets/footage/`, then make a scene function for each step. Use `Layer.video` for the recording and `Layer.text` for the instruction. A portrait canvas can make desktop interfaces tiny; crop to the relevant control or put a readable detail view above the step label. Use [Layer.sequence](/docs/guides/scenes-and-transitions/) to join the scenes with cuts. At 30 fps, a seven-second scene lasts 210 frames. Keep step numbers in the same place so viewers can follow the progression without searching the screen. For spoken instructions, prepare and proofread an SRT file and add it with `Layer.caption`. Captions and step labels have different jobs: captions follow speech; the step label tells the viewer where they are. Framefields can display the supplied SRT; this workflow does not assume automatic transcription. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Give your assistant this brief [Section titled “Give your assistant this brief”](#give-your-assistant-this-brief) ```text Build a 30-second Framefields tutorial at 1080x1920, 30 fps. Use assets/footage/desktop-demo.mp4 and the approved steps in assets/steps.json. Show the completed result first, then three numbered steps, then a recap. Crop each scene to its relevant control. Use readable text and the supplied SRT. Keep footage audio audible. Create scene functions and export buildFilm(). Inspect frames around each cut and show a preview before rendering the final MP4. Do not invent interface actions or omit a necessary step. ``` ## Check what a beginner actually sees [Section titled “Check what a beginner actually sees”](#check-what-a-beginner-actually-sees) Watch once with sound off and once with sound on. Pause at the most complicated step: the control, cursor and instruction should all be readable on a phone. Render frames immediately before and after cuts to catch a label appearing on the wrong action. For the next lesson, change the clip, step text and scene durations. Keep those inputs separate from the visual theme. You get a consistent series without treating every tutorial as a new video production project. Continue with [a longer animated explainer](/blog/animated-explainer-videos/) when the lesson needs diagrams rather than a screen recording. # Add a color overlay to a person in video with TypeScript > Use Framefields segmentation to add a blue overlay to a moving person while leaving the background alone. Use Framefields to segment a dancer and add a translucent blue overlay that moves with her, while keeping the background visible. [![](/docs/blog-media/tracked.jpg)](/docs/blog-media/tracked.mp4) The blue overlay follows the dancer and her dress as she turns. The video has no audio. [Open the MP4](/docs/blog-media/tracked.mp4) or [view a still frame](/docs/blog-media/tracked.jpg). ## Segment the dancer [Section titled “Segment the dancer”](#segment-the-dancer) This example uses Framefields 2.6.2 and a three-second clip at `assets/footage/person.mp4`. Start with a [Framefields project](/docs/getting-started/), create an `output` directory, and adjust the dimensions and duration to match your clip. ```ts import { Composition, Layer } from "framefields"; const comp = new Composition({ width: 1920, height: 1080, fps: 30, durationMs: 3000, backgroundColor: "#000000", }); // Both copies need the same size and fit so the matte lines up with the footage. const video = () => Layer.video("assets/footage/person.mp4", { position: "absolute", x: 0, y: 0, width: 1920, height: 1080, fit: "cover", muted: true, }); comp.add(video()); const personMatte = video().withVision({ mode: "matte", enableSegmentation: true, classes: ["person"], }); comp.add( Layer.box({ position: "absolute", x: 0, y: 0, width: 1920, height: 1080, background: "#1458ed", opacity: 0.55, }).withMatte(personMatte), ); console.log(comp.lint()); await comp.renderVideo({ outputPath: "output/segmented.mp4" }); ``` The first video is the untouched footage. The second is used as a matte, so it isn’t drawn as another visible copy. It limits the blue box to the detected subject. Change the box color or opacity to try a different look. ## Check the edges [Section titled “Check the edges”](#check-the-edges) Segmentation can miss hands or loose fabric, and the matte can spill onto the background. Watch the full clip, especially around fast movements and objects crossing in front of the subject. In this example, you can see some edge lag as the dress moves. Render-time vision uses the previous rendered frame, so frame 0 has no segmentation result. `renderVideo` processes frames in order. For stills, render at least two consecutive frames with the same renderer and inspect the last one. A frame grid jumps around and can give misleading results for vision layers. The [vision guide](/docs/guides/vision/#timing-the-one-frame-delay) has more on timing. Models download on first use and inference takes resources. Framefields uses WebGPU when available and can fall back to CPU. See the [vision guide](/docs/guides/vision/) for model options, masks and other ways to use them. # Create UGC-style video ads with reusable Framefields edits > Build a video marketing workflow around real demonstrations, three opening hooks and a consistent Framefields ad template. A creator-style ad can start with a recognizable problem, demonstrate a product and end with a clear next step. The important input is credible footage. Framefields gives you a way to assemble that footage into variations while keeping the offer, typography and end card consistent. Use footage from a creator who has agreed to the intended use. Write the ad around what the footage actually demonstrates. A scripted brand message should not be presented as an independent customer review. ## Plan one body and three openings [Section titled “Plan one body and three openings”](#plan-one-body-and-three-openings) For a cable organizer, keep the example simple: a cluttered desk becomes easier to use. Build a 25-second vertical ad, then test three different three-second introductions against the same remaining edit. | Time | Shot | Role | | ------- | --------------------------- | ----------------------- | | 0–3 s | Problem, result or question | Variable hook | | 3–8 s | Creator shows the desk | Establish context | | 8–18 s | Organizer being used | Demonstrate the benefit | | 18–22 s | Finished desk | Show the outcome | | 22–25 s | Product and approved CTA | Give one next step | Possible hooks include “My charger kept falling behind this desk,” a direct shot of the finished setup, and “Where does your charging cable disappear?” Treat these as creative options, not promised winners. ## Make variations controlled [Section titled “Make variations controlled”](#make-variations-controlled) Build hook, demonstration, result and end-card scene functions. Use `Layer.sequence` for the edit, `Layer.caption` for the approved SRT, and text layers for the offer. Keep a hook identifier with each output filename so performance data can be traced back to the correct version. Framefields is useful here because content creation becomes a small set of explicit inputs: clip, hook, offer, logo and CTA. Batch those inputs only after one complete version passes review. A mistake in the shared offer otherwise spreads to every export. If your workflow begins in CapCut, you can export creator footage there and use it as a media asset here. This is an MP4 handoff; it does not imply importing an editable CapCut project. ## Use Codex, ChatGPT, Claude, Cursor or Grok Bot [Section titled “Use Codex, ChatGPT, Claude, Cursor or Grok Bot”](#use-codex-chatgpt-claude-cursor-or-grok-bot) You can use **Codex, ChatGPT, Claude, Cursor, or Grok Bot** to plan the edit and write Framefields TypeScript. In a coding environment with project and terminal access, ask the assistant to implement the brief and run the checks. In a chat-only environment, ask for the source files, save them locally and run them in your Framefields project. Rendering needs Node.js 22+ and a supported WebGPU environment; see [getting started](/docs/getting-started/). For Codex or Cursor, install the [Framefields skills](/docs/agents/install/): ```bash npx skills add gatewai-dev/framefields -a codex -a cursor ``` For Claude Code, use `/plugin install framefields`. With ChatGPT or Grok Bot, supply the [agent reference](https://framefields.dev/docs/llms.txt), your brief and asset list; available execution tools depend on your environment. The workflow does not require a native integration in every assistant. Create a project with `npx framefields init my-video --install --pm npm`, then work inside `my-video`. Use the generated font setup and put your source media under `assets/`. Run `npm run typecheck`, inspect `comp.lint()` findings, render selected frames and a grid, then run `npm run preview` before `npm run render`. The [agent workflow](/docs/agents/workflow/) covers inspection and QA. Check portrait layouts against the destination app’s current controls before uploading. ## Prompt for the first edit [Section titled “Prompt for the first edit”](#prompt-for-the-first-edit) ```text Make a 25-second 1080x1920, 30 fps Framefields ad for a cable organizer using approved creator footage in assets/footage/. Read assets/brief.md for claims, offer, CTA and disclosure text. Create three 3-second hooks sharing the same 22-second body. Use only supplied claims and real demonstration footage. Keep captions clear of the product. Name outputs by hook ID. First build and preview one complete version with sound. After feedback, apply the shared corrections to all three variants. ``` ## Judge the whole path [Section titled “Judge the whole path”](#judge-the-whole-path) Check the opening without sound, then watch through the CTA. Does the demonstration support the hook? Does the offer match the landing page? Is the product visible while the caption is on screen? Compare variants against the same campaign objective and a comparable audience. Hold the body steady when testing the hook so you can learn which opening made a difference. Framefields produces the video files; upload and campaign management happen in your publishing tools. Use the [product demo guide](/blog/saas-product-demo-videos/) for a longer, feature-led explanation. # Why framefields works well with coding agents > Framefields gives coding agents a TypeScript workflow for creating, inspecting and rendering video, with a human in the loop. A coding agent can write a video in TypeScript, render a few frames, inspect the results and adjust the composition. Framefields gives it the tools to do that without opening a desktop editor. The engine renders compositions with WebGPU in Node.js. You describe layers, animation and timing in code, then render a single frame or an MP4. The same source can be read and edited by a person or an agent. ## Start with a frame, not a full export [Section titled “Start with a frame, not a full export”](#start-with-a-frame-not-a-full-export) A full video takes longer to render than a still. Framefields lets an agent work through smaller checks first: 1. Type-check the project and run `comp.lint()` to find common composition problems. 2. Render a frame at a useful moment and inspect it for layout, text and color. 3. Render a frame grid to check a sequence of moments. 4. Open the [live preview](/docs/guides/preview/) for playback, scrubbing and notes. 5. Export the video, with optional QA checks. The [rendering guide](/docs/guides/rendering/) shows the commands and code for each step. Frame grids are useful for ordinary animation, but not for render-time vision: that needs consecutive frames because its results lag by one frame. A human can pause the preview and leave a note on the picture, such as “move the title up.” The note is saved locally, so an agent can read it and update the composition. You’ll still want to check the result together. A successful render doesn’t automatically mean the timing feels right. ## Give the agent useful building blocks [Section titled “Give the agent useful building blocks”](#give-the-agent-useful-building-blocks) Framefields includes text animation, 2D layers, 3D models, effects, audio and vision. You can see the code and output in our examples: * [Animate text letter by letter](/blog/kinetic-typography-typescript/). * [Combine a 3D model and a title](/blog/3d-product-video-typescript/). * [Apply a color overlay to a segmented person](/blog/track-person-attach-graphics/). The engine is also behind [Gatewai Studio](https://gatewai.studio). Read more about [its background](/blog/six-months-building-framefields/). ## Give your agent the project instructions [Section titled “Give your agent the project instructions”](#give-your-agent-the-project-instructions) For Claude Code: ```text /plugin install framefields ``` For other coding agents that support the skills installer: ```bash npx skills add gatewai-dev/framefields ``` Then give the agent a specific brief, including the size, duration and moments you want to inspect. For example: ```text Create a five-second product teaser at 1080x1920 and 30 fps. Add an animated headline and a bar chart. Render frames at the start, middle and end so I can check the layout before export. ``` Framefields needs Node.js, project assets such as fonts, and a suitable rendering environment. CPU rendering is available on supported setups but is slower. See [getting started](/docs/getting-started/) for requirements and the [agent guide](/docs/agents/) for the workflow. # 3D > Cameras and camera moves, lights and lighting rigs, physically based environments, primitives, extruded text and models. 3D and 2D share one depth buffer. The camera is calibrated so **`z = 0` maps 1:1 onto canvas pixels**: a box at `x: 960, y: 540, z: 0` sits in the centre of a 1920×1080 frame. y points down, so “up” is −y. ## The fast path: a lighting rig [Section titled “The fast path: a lighting rig”](#the-fast-path-a-lighting-rig) ```ts import { Composition, Layer3D, LayerAnimation, Lighting } from "framefields"; const W = 1920, H = 1080; const comp = new Composition({ width: W, height: H, fps: 30, durationMs: 4000, backgroundColor: "#0b0b0c" }); comp.add(Lighting.studio({ target: [W / 2, H / 2, 0] })); // environment + key/rim/fill, soft shadow comp.add( Layer3D.text({ text: "framefields", fontFamily: "Archivo", fontWeight: 800, fontSize: 280, extrusionDepth: 26, fill: "#f5e300", bevelColor: "#6b6300", roughness: 0.35, x: W / 2, y: H / 2, z: 0, }).animate(LayerAnimation.create().keys("rotateY", [[0, -20], [120, 6, "sine.inOut"]])), ); ``` Rigs: `Lighting.studio`, `soft`, `sunset`, `dramatic`. Options: `target`, `distance`, `rotation`, `intensity`, `exposure` (stops), `toneMapping`, `shadows` (default on), `shadowSoftness`, `fog`, `bloom`. A rig returns an array; `comp.add` takes it, or spread it into `children`. ## Camera [Section titled “Camera”](#camera) ```ts import { CameraAnimation, Layer } from "framefields"; comp.add( Layer.camera({ x: 960, y: 540, z: -1000, targetX: 960, targetY: 540, targetZ: 0 }).animate( CameraAnimation.camera() .orbit({ azimuth: { from: -30, to: 30 }, elevation: { from: 15, to: 15 }, radius: { to: 1200 }, start: 0, end: 300, ease: "sine.inOut" }) .rackFocus({ fromDistance: 2000, toDistance: 1200, fromFStop: 1.8, toFStop: 4, start: 20, end: 60 }), ), ); ``` `CameraAnimation.camera()` moves: `orbit`, `dolly`, `truck`, `pedestal`, `pan`, `tilt`, `roll`, `rackFocus`, `handheld({ translationAmplitude, rotationAmplitude })`. Camera `mode` is `"lookAt"` (default), `"free"` or `"orbit"`. ## Lights by hand [Section titled “Lights by hand”](#lights-by-hand) ```ts import { Layer, Light } from "framefields"; comp.add([ Layer.environment("studio", { // presets: studio | soft | sunset | night | neutral exposure: 0.3, toneMapping: "neutral", // default; "agx" filmic, "aces" punchy, "none" rotation: 30, fog: { color: "#0b0b0c", start: 2000, end: 5000 }, bloom: true, // or { intensity, threshold, radius } }), Light.directional({ x: 400, y: -1200, z: -600, targetX: 960, targetY: 540, castShadow: true }), Light.ambient("#ffffff", 0.3), ]); ``` `Light.ambient`, `Light.directional`, `Light.point`, `Light.spot` (also `Layer.ambientLight`, `Layer.directionalLight`, `Layer.pointLight`, `Layer.spotLight`). | Rule | Why | | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | Add `Layer.environment(...)` for `roughness` / `metallic` to mean anything | Without it the scene uses classic Blinn-Phong (lint: `pbr_without_environment`) | | One `castShadow` light, directional or spot | Only the first casts (`multiple_shadow_lights`); point/ambient can’t (`shadow_unsupported_light`) | | Tone mapping `"neutral"` keeps brand colors as authored | `"agx"` rolls highlights off filmically | | Bloom only takes light well past white | Use `emissiveIntensity` ≳ 3 to make something glow | | Set `fog.color` to the background | Surfaces fade into it seamlessly | ## Path tracing [Section titled “Path tracing”](#path-tracing) From framefields 3.0.1, `pathTrace` on the environment traces the scene’s 3D layers instead of rasterizing them. Shadows, reflections (of things off screen too), refraction through glass, occlusion and light bouncing between surfaces are computed, not approximated, and glowing meshes light what is around them. Everything else stays as it was: the same lights, environment, floor, exposure, tone mapping, fog, bloom and motion blur. ```ts comp.add([ Layer.environment("night", { floor: { y: 420, color: "#22252c", reflectivity: 0.35, roughness: 0.25 }, pathTrace: true, // or { quality: "draft" } while you iterate }), Light.directional({ x: 0, y: -800, z: -400, targetX: 480, targetY: 300, castShadow: true }), Layer3D.torus({ x: 760, y: 260, z: 120, radius: 90, tubeRadius: 10, color: "#111", emissive: "#3fb6ff", emissiveIntensity: 4 }), ]); ``` [![](/v3/media/pathtrace.jpg)](/v3/media/pathtrace.mp4) `examples/43_path_tracer`, at the default preset. | Preset | Samples per pixel / bounces | Use | | ------------------ | --------------------------- | --------------------------------------- | | `"draft"` | 8 / 3, denoised | iterating; checking frames and grids | | `"standard"` | 32 / 5, denoised | quick finals of simple scenes | | `"high"` (default) | 128 / 8, denoised | finals: glass, interiors, product shots | | `"reference"` | 1024 / 16, no denoiser | the unbiased answer, to compare against | Override any part with `samples`, `bounces`, `transmissionBounces`, `denoise`, `clamp` (brightest bounced light per sample) and `filterGlossy`. At 1080p on an Apple M1 Pro, a frame with a character, a ball, a glowing ring and a floor takes about 12 s at `"high"`; desktop GPUs are several times faster. | Rule | Why | | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | A render takes exactly `samples` per pixel on any GPU | Frames are deterministic, so a [split cloud render](/docs/guides/cloud-rendering/) joins without seams | | The preview fits each frame to `previewBudgetMs` (33) of GPU time | Slower GPUs see fewer samples or a lower resolution while you scrub; the export doesn’t | | Sparkles on matte surfaces next to shiny ones: raise `filterGlossy` | Light bounced off a glossy floor or a chrome ball arrives through rare paths; `filterGlossy` (draft 0.7, standard 0.6, high 0.45) turns it into a soft glow | | Thick glass has its own bounce budget, `transmissionBounces` | Crossing a vase or a lamp globe takes four or more passes; draft allows 8, standard 12, high 16. Raise it if stacked glass turns dark | | Glass from a model keeps its roughness | Frosted where the model says so; `material: "glass"` on a primitive is clear unless you set `roughness` | | Glowing meshes emit from their front faces | As the raster draws them; set `twoSided` for both sides. `material: "unlit"` layers show their picture and light nothing | | Not with `ssr`, `gi`, `outlines`, `volumetricFog` or a cube camera | The tracer does reflections and bounce light itself; the others aren’t traced yet (`framefields check` flags each) | Not traced yet, and named in an error if a traced scene uses them: text drawn on a 3D plane (use `Layer3D.extrudedText`), toon, mattes, reliefs, triplanar textures, wireframes, instanced scatter, swarms and crowds, wind, and audio deformation. `subsurface` shades as plain diffuse. Point and directional lights cast hard shadows; rect lights cast soft ones. ## Primitives [Section titled “Primitives”](#primitives) Every `Layer3D` procedural mesh is centered on `x`/`y`/`z` (`y` is down, so the top face is at `-y`). Equal shapes share GPU buffers automatically. ```ts // Solids & motion-design primitives Layer3D.roundedBox({ x: 960, y: 540, z: 0, width: 300, height: 80, depth: 300, radius: 18, taper: 0.9, color: "#ff5a1f", roughness: 0.45 }); Layer3D.sphere({ x: 700, y: 540, z: 0, radius: 90, color: "#e8e8e8", metallic: 1, roughness: 0.15 }); Layer3D.cylinder({ x: 1200, y: 540, z: 0, radius: 12, height: 400, color: "#111", emissive: "#4da3ff", emissiveIntensity: 3 }); Layer3D.capsule({ x: 960, y: 240, z: 0, radius: 40, height: 80, color: "#22c55e" }); Layer3D.torus({ x: 300, y: 240, z: 0, radius: 68, tubeRadius: 24, arc: 360, color: "#ff5a1f" }); // partial arcs (e.g. arc: 250) are capped Layer3D.ring({ x: 1290, y: 240, z: 0, innerRadius: 36, outerRadius: 80, color: "#eab308", metallic: 0.6 }); // Solid capped polygonal prisms & pyramids (flat-shaded by default) Layer3D.prism({ x: 1620, y: 240, z: 0, sides: 6, radius: 66, height: 110, color: "#3b82f6" }); Layer3D.pyramid({ x: 300, y: 540, z: 0, sides: 4, radius: 76, height: 125, color: "#a855f7" }); // Polyhedra & geodesic icospheres Layer3D.polyhedron({ shape: "dodecahedron", radius: 74, color: "#c084fc" }); // "tetrahedron" | "octahedron" | "dodecahedron" | "icosahedron" Layer3D.icosahedron({ radius: 74, color: "#fbbf24" }); Layer3D.icosphere({ radius: 74, detail: 2, flatShaded: true, color: "#4ade80" }); // detail: 0..5, smooth or flat // 2D shape extrusion & lathe / revolve geometry Layer3D.extrude({ x: 630, y: 540, z: 0, d: "M -60 -60 L 60 -60 L 60 60 L -60 60 Z M 20 0 A 20 20 0 1 0 -20 0 A 20 20 0 1 0 20 0 Z", // SVG path with holes or contour array depth: 32, bevelThickness: 6, bevelSize: 4, bevelSegments: 3, color: "#f43f5e", bevelColor: "#fecdd3", // optional separate side-wall color }); Layer3D.lathe({ x: 960, y: 540, z: 0, points: [[0, -75], [52, -70], [58, -35], [20, 5], [15, 48], [48, 70], [0, 75]], // [r, y][] profile revolved around Y segments: 48, capped: true, color: "#06b6d4", }); // 3D curves, thick-walled hollow tubes, lines, and diagram points Layer3D.tube({ path: Path3D.catmullRom([[-70, 50, -15], [-25, -50, 25], [25, 50, -25], [70, -50, 15]]), radius: 24, innerRadius: 14, // hollow thick-walled pipe with annular end caps color: "#10b981", }); Layer3D.line({ points: [[0, 0, 0], [100, -50, 30], [200, 20, -10]], dashSize: 10, gapSize: 5, color: "#93c5fd", }); Layer3D.points({ points: [[0, 0, 0], [100, -50, 30], [200, 20, -10]], pointSize: 12, // perspective-scaled 3D sphere dots (or 0 for GPU pixel point-list) colors: ["#fde047", "#f472b6", "#60a5fa"], }); ``` | Builder | Description & Key Options | | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Layer3D.roundedBox` | `width`, `height`, `depth`, `radius`, `taper`, `segments` | | `Layer3D.sphere` | `radius`, `widthSegments`, `heightSegments` | | `Layer3D.cylinder` | `radius` or `radiusTop`/`radiusBottom`, `height`, `radialSegments`, `openEnded`, `flatShaded` | | `Layer3D.capsule` | `radius`, `height` (shaft) or `totalHeight`, `capSegments`, `radialSegments` | | `Layer3D.torus` | `radius`, `tubeRadius`, `arc` (degrees; capped when `< 360`), `radialSegments`, `tubularSegments` | | `Layer3D.ring` | `innerRadius`, `outerRadius`, `thetaSegments`, `phiSegments`, `thetaStart`, `thetaLength` | | `Layer3D.prism` | solid capped flat-shaded N-gon prism (`sides`, `radius`, `radiusTop`, `radiusBottom`, `height`, `openEnded`, `flatShaded`) or multi-panel container via `sideConfigs` | | `Layer3D.pyramid` | solid capped flat-shaded pyramid (`sides`, `radius`, `radiusTop`, `height`, `openEnded`, `flatShaded`) | | `Layer3D.polyhedron` | Platonic solids (`shape`: `"tetrahedron" \| "octahedron" \| "dodecahedron" \| "icosahedron" \| "icosphere"`, `radius`, `detail`, `flatShaded`) | | `Layer3D.icosahedron` | 20-sided regular polyhedron (`radius`, `detail`, `flatShaded`) | | `Layer3D.icosphere` | geodesic sphere with subdivision `detail` (`radius`, `detail`, `flatShaded`) | | `Layer3D.shard` | procedural flat-faceted crystal clipped against Fibonacci lattice normals (`radius`, `cuts`, `irregularity`, `seed`) | | `Layer3D.extrude` | extrudes an SVG path `d` (with curves and subpaths/holes) or 2D `contour`/`holes` (`depth`, `bevelThickness`, `bevelSize`, `bevelSegments`, `bevelColor`, `center`) | | `Layer3D.lathe` | revolves a 2D profile `points` `[r, y][]` around the Y axis (`segments`, `phiStart`, `phiLength`, `capped`, `flatShaded`) with crease-aware normal splitting | | `Layer3D.tube` | sweeps a solid or thick-walled pipe (`innerRadius`, `radiusTaper`, `closed`, `capped`) along a `Path3D` or 3D points using Rotation-Minimizing Frames | | `Layer3D.line` | 3D polyline/segment geometry (`line-list` topology) along 3D points or `Path3D`, with `dashSize`/`gapSize` dashing and vertex `colors` | | `Layer3D.points` | 3D point cloud (`pointSize: 0` for GPU point-list pixels, or `pointSize > 0` for perspective-scaled 3D sphere dots) with per-point `colors` | | `Layer3D.cube({ size, faces })` | a cube whose faces are 2D layers | | `Layer3D.carousel({ radius, items })` | 2D items on a ring | | `Layer3D.plane`, `Layer3D.grid` | flat cards, ground grids | | `Layer3D.text` / `Layer3D.extrudedText` | extruded, bevelled vector type from registered fonts | ### Materials & glass refraction [Section titled “Materials & glass refraction”](#materials--glass-refraction) Meshes take a `material`: `"pbr"` (default), `"unlit"`, `"glass"`, `"acrylic"` or `"frosted"`. `glass`, `acrylic` and `frosted` materials physically refract what is behind them on screen — with chromatic dispersion, slab thickness, tint, and studio reflections — instead of rendering as simple translucent plastic: ```ts Layer3D.roundedBox({ x: 960, y: 540, z: 0, width: 320, height: 200, depth: 36, radius: 18, material: "glass", color: "#eef5ff", roughness: 0.03, // smooth clear glass; higher roughness gives frosted glass }); ``` ### Materials from other tools [Section titled “Materials from other tools”](#materials-from-other-tools) From 3.0.1, `openPBR` takes [OpenPBR Surface](https://academysoftwarefoundation.github.io/OpenPBR/) parameters with the spec’s own names and linear colors, as Blender, Houdini, Maya or Substance show them, and returns surface props to spread into any mesh or model. `standardSurface` does the same for Autodesk Standard Surface. ```ts import { openPBR, parseMtlx } from "framefields"; Layer3D.sphere({ radius: 90, ...openPBR({ base_color: [0.6, 0.02, 0.02], coat_weight: 1, specular_roughness: 0.4 }) }); // lacquered red Layer3D.sphere({ radius: 90, ...openPBR({ base_color: [0.95, 0.64, 0.54], base_metalness: 1, specular_roughness_anisotropy: 0.8 }) }); // brushed copper const materials = parseMtlx(await fs.readFile("assets/table.mtlx", "utf8"), { baseDir: "assets" }); Layer.glb("assets/table.glb", { ...materials.M_table.props }); ``` Transmission above 0.5 becomes glass (frosted when rough), `emission_luminance` is read against a 100-nit white (300 nits is `emissiveIntensity: 3`), and thin-film thickness is in micrometres. `parseMtlx` reads a MaterialX document’s `open_pbr_surface` and `standard_surface` materials by name. A base color wired to an `image` node becomes the mesh’s `texture`. Other connected maps and parameters framefields has no lobe for are listed in each material’s `unsupported`, so nothing is dropped silently. Surface props on meshes: `color`, `tint` (animates as `color`), `roughness`, `metallic`, `emissive`, `emissiveIntensity`, `castShadow`. Flat layers cast shadows only with `castShadow: true`; meshes cast by default. ## Sculpting [Section titled “Sculpting”](#sculpting) From 3.1, `Layer3D.clay` is a sculpture written as a list of moves (`ops`) that run in order. It is drawn per pixel from those moves, so it stays sharp at any size and has no polygon count to choose. Local space is in px with up as -y, like the other primitives. ```ts Layer3D.clay({ x: 960, y: 420, symmetry: "x", color: "#cdbba6", roughness: 0.6, ops: [ { type: "stroke", path: [[-105, 88, 18], [0, 70, 6], [105, 88, 18]], radius: 48 }, // shoulders { type: "sphere", center: [0, -70, 0], radius: 72, smoothness: 22 }, // head { type: "sphere", center: [30, -74, -66], radius: 15, mode: "carve" }, // eye socket { type: "grab", center: [0, -14, -104], radius: 26, delta: [0, 16, -6] }, // pull the chin { type: "detail", amplitude: 2.2, scale: 22, ridged: true, seed: 7 }, // stone ], }); ``` | Move | What it does | | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `sphere` `box` `cylinder` `capsule` `torus` | Solids: `mode: "add"` (default), `"carve"` or `"intersect"`, `smoothness` (blend radius, px), `center`, `rotation`, `color` | | `stroke` | A brush stroke: a ball swept along a smooth curve through `path` (`[x, y, z]` or `[x, y, z, radius]`), `radius`, `progress` 0..1, plus the solids’ `mode`, `smoothness` and `color` | | `grab` `twist` `bulge` | Elastic brushes that move what is already sculpted: `center`, `radius`, and `delta`, `axis` + `angle`, or `amount` | | `inflate` | Swells (or with a negative `amount`, shrinks) a round region by `amount` px | | `detail` | Relief texture: `amplitude`, `scale`, `octaves`, `ridged`, `seed`, optionally limited to `center` + `radius`. It fades where it would be smaller than a pixel, so put it last | `symmetry: "x"` mirrors what you sculpt at positive x. Moves are fixed for a layer: animate the node, or show several layers in turn, as `examples/45_sculpture` does to film a sculpture being made. Path tracing, glass, blended and textured draws, physics and scatter use a mesh of the sculpture, built at `resolution` (16–1024, default 64). Raise it for a finer traced or exported mesh. `draw: "mesh"` draws that mesh for ordinary draws too. ## Models [Section titled “Models”](#models) ```ts comp.add(Layer.glb("assets/models/character.glb", { x: 960, y: 640, z: 0, scale: 2.5, loop: true })); ``` Loaders: `Layer.glb`, `gltf`, `obj`, `fbx`, `stl`, `ply`, `vox`, `threeDS`, `off` (also on `Layer3D`). glTF brings base color, normal, metallic-roughness, occlusion and emissive maps, and skeletal animation (up to 128 bones). Animate playback with `animationProgress`, `animationTime` or `animationSpeed`. The other way round, `comp.exportModel({ frame })` writes a frame’s 3D scene as a `.glb` for Blender, Unreal, Unity or the web: see [3D models (glTF)](/docs/guides/rendering/#6-3d-models-gltf). ## 3D rigid-body physics [Section titled “3D rigid-body physics”](#3d-rigid-body-physics) Animate primitives and models with deterministic 3D physics (Rapier) using `Physics.world3d`: collision responses, joints, and forces. See the [Physics & particles guide](/docs/guides/physics/#3d-rigid-bodies). ## Animatable 3D props [Section titled “Animatable 3D props”](#animatable-3d-props) `z`, `rotateX/Y/Z`, `scaleX/Y/Z`, `roughness`, `metallic`, `emissive`, `emissiveIntensity`, `exposure`, `intensity`, plus camera props (`cameraX/Y/Z`, `targetX/Y/Z`, `cameraFov`, `focusDistance`, `fStop`, `orbitRadius`, `orbitAzimuth`, `orbitElevation`). # Generative AI (ai) > Generate images, videos, sound and assets directly within framefields compositions using the AI gateway. `framefields` includes built-in generative AI capabilities via the `ai` module. One API key unlocks every supported generative model with unified credit billing and direct WebGPU composition integration. ```ts import { ai, Composition, Layer } from "framefields"; // Subscribe to a queue-based generation const { data } = await ai.subscribe("flux/schnell", { input: { prompt: "An atmospheric 35mm film still of a cinematic neon street", image_size: "landscape_16_9", }, }); console.log("Image URL:", data.images[0].url); ``` ## Setup & API Keys [Section titled “Setup & API Keys”](#setup--api-keys) You don’t need separate provider accounts or keys. 1. Sign in at [framefields.dev/dashboard](https://framefields.dev/dashboard). 2. Top up credits on the [Billing page](https://framefields.dev/dashboard/billing) with Dodo Payments. 3. Create an API key on the [API Keys page](https://framefields.dev/dashboard/keys). 4. Add the key to your project `.env`: ```bash FRAMEFIELDS_API_KEY=ff_live_... ``` A project made with `framefields init` already has a `.env.example` (commit it) and ignores `.env` (never commit that). Its `render.ts` loads `.env` when the file exists, so renders and scripts pick up the key without extra setup. Without a key everything else still works, including in CI: only `ai.*` calls need it. Or configure it in code: ```ts import { ai } from "framefields"; ai.config({ apiKey: process.env.FRAMEFIELDS_API_KEY, }); ``` ## Model Catalog [Section titled “Model Catalog”](#model-catalog) Explore available models in the [Model Catalog](https://framefields.dev/models), including text-to-image, image-to-video, voice synthesis, and upscaling models. You can also fetch the catalog programmatically for agentic workflows: ```bash curl https://api.framefields.dev/v1/models ``` ## API Methods [Section titled “API Methods”](#api-methods) ### `ai.subscribe` (Recommended) [Section titled “ai.subscribe (Recommended)”](#aisubscribe-recommended) Submits a request to the async processing queue, waits for completion, and returns the final output. Ideal for video and high-resolution rendering models. ```ts const { data } = await ai.subscribe("flux/schnell", { input: { prompt: "A neon geometric sculpture rotating in void, raytraced", }, pollInterval: 500, // poll status every 500ms }); ``` ### `ai.run` [Section titled “ai.run”](#airun) Executes synchronously over a single HTTP connection. Best for fast operations like prompt enhancements or micro-latencies. ```ts const { data } = await ai.run("flux/schnell", { input: { prompt: "Retro minimal typography background" }, }); ``` ### `ai.stream` [Section titled “ai.stream”](#aistream) Streams generation events (tokens or partial image steps) over Server-Sent Events (SSE). ```ts const stream = await ai.stream("flux/dev", { input: { prompt: "Cyberpunk cityscape" }, }); for await (const event of stream) { console.log("Progress:", event); } ``` ### `ai.storage.upload` [Section titled “ai.storage.upload”](#aistorageupload) Uploads local buffers or files to ephemeral CDN storage via presigned URLs so models can reference them as input parameters (e.g. image-to-video or style transfer). ```ts import fs from "node:fs"; const file = fs.readFileSync("input.png"); const fileUrl = await ai.storage.upload(new Blob([file], { type: "image/png" })); const { data } = await ai.subscribe("wan/video", { input: { image_url: fileUrl, prompt: "Slow cinematic camera pan forward", }, }); ``` ## Using Generated Assets in Compositions [Section titled “Using Generated Assets in Compositions”](#using-generated-assets-in-compositions) Download or stream generated assets directly into your `framefields` layer hierarchy: ```ts import { ai, Composition, Layer } from "framefields"; import fs from "node:fs/promises"; // 1. Generate an image asset const { data } = await ai.subscribe("flux/schnell", { input: { prompt: "Abstract glowing glass caustics, dark mode" }, }); // 2. Fetch image buffer const res = await fetch(data.images[0].url); const imageBuffer = Buffer.from(await res.arrayBuffer()); await fs.writeFile("assets/generated-bg.png", imageBuffer); // 3. Compose in WebGPU layer export default Composition.create({ width: 1920, height: 1080, fps: 60, durationInFrames: 300, children: [ Layer.image({ source: "assets/generated-bg.png", width: 1920, height: 1080, }), ], }); ``` ## Credits & Error Handling [Section titled “Credits & Error Handling”](#credits--error-handling) Credits are charged in micro-USD ($0.000001 resolution) based on model usage plus margin. When credits are depleted, requests will return HTTP `402 Payment Required`: ```ts try { await ai.subscribe("flux/schnell", { input: { prompt: "..." } }); } catch (err: any) { if (err.status === 402) { console.error("Credits depleted. Top up at https://framefields.dev/dashboard/billing"); } } ``` | HTTP Status | Error Type | Solution | | ----------- | ---------------------- | -------------------------------------------------------------------------------- | | `401` | `invalid_api_key` | Verify `FRAMEFIELDS_API_KEY` in `.env` | | `402` | `insufficient_credits` | Add credits in [Billing](https://framefields.dev/dashboard/billing) | | `402` | `key_limit_reached` | Increase key monthly limit in [API Keys](https://framefields.dev/dashboard/keys) | | `429` | `rate_limited` | Respect retry-after backoff (60 submits/min, 600 status/min) | See the [Privacy Policy](/privacy/) for what the gateway keeps and why. # Animation > Keyframes with LayerAnimation, easing, composing animations, procedural drivers, kinetic typography and 3D transforms on 2D layers. Animations are data. Build one with `LayerAnimation`, attach it with `.animate()`. All frames are **local to the layer** and **integers**. ## Two keyframes: `fromTo` [Section titled “Two keyframes: fromTo”](#two-keyframes-fromto) ```ts import { LayerAnimation } from "framefields"; const entrance = LayerAnimation.create() .fadeIn(0, 20, "power2.out") // opacity 0 → 1, frames 0–20 .fromTo("y", 460, 400, { start: 0, end: 24, ease: "expo.out" }) // to the layout y, not 0 .fromTo("scale", 0.95, 1, { start: 0, end: 30, ease: "back.out(1.4)" }); card.animate(entrance); ``` Shortcuts: `fadeIn(start, end, ease)`, `fadeOut(start, end, ease)`, `slideInX/slideInY(from, to, start, end, ease)`, `rotateX/rotateY/rotateZ`, `translateZ`, `perspective`, `letterSpacing`, `typewriter(start, end)`, `kineticSweep(fromOffset, toOffset, start, end, ease)`. ## Many keyframes: `keys` [Section titled “Many keyframes: keys”](#many-keyframes-keys) Each tuple is `[frame, value, ease?]`; the ease shapes motion **into** that key. Frames are rounded, so beat math can go straight in. ```ts const pop = LayerAnimation.create() .keys("scale", [[0, 0], [10, 1.12, "back.out(1.6)"], [16, 1, "power2.out"]]) .keys("opacity", [[0, 0], [6, 1]]); LayerAnimation.keys("rotation", [[0, -8], [20, 0, "expo.out"]]); // static form ``` Color props (`fill`, `color`, `borderColor`, …) keyframe too, blended in OKLab. ## Easing [Section titled “Easing”](#easing) `.` with optional parameters: `"expo.out"`, `"back.out(1.7)"`, `"power2.inOut"`. | Names | `none` `power1` `power2` `power3` `sine` `circ` `expo` `back` `elastic` `bounce` `spring` `cubic` `hold` | | ---------- | -------------------------------------------------------------------------------------------------------- | | Directions | `in` `out` `inOut` (`"linear"` is an alias for `none`) | | Use | Ease | | ------------------------- | ---------------------------------- | | Snap-overshoot entrances | `back.out(1.4–1.7)` | | Decelerating moves | `expo.out`, `power3.out`, `spring` | | Exits | `power2.in` | | Loops, counters, spinners | `linear` (and nothing else) | ## Composing animations [Section titled “Composing animations”](#composing-animations) `.animate()` **adds** to what a node has. Tracks on the same prop merge into one sorted track; a later key wins on a shared frame. ```ts const rainIn = LayerAnimation.keys("y", [[0, -300], [d, -300], [d + 12, 0, "back.out(1.5)"]]); const press = LayerAnimation.keys("y", [[40, 0], [42, 6, "power2.in"], [47, 0, "power2.out"]]); const glow = LayerAnimation.keys("color", [[42, "#ffd400"], [60, "#2a2b2d", "sine.inOut"]]); key.animate(rainIn).animate(press, glow); // or LayerAnimation.merge(rainIn, press, glow) ``` ## Procedural drivers [Section titled “Procedural drivers”](#procedural-drivers) ```ts LayerAnimation.create() .wiggle("x", { frequency: 1.5, amplitude: 25, seed: 3 }) // seeded noise, deterministic .spring("scale", { damping: 14, stiffness: 190, mass: 1 }); ``` Bind any prop to a signal with `.signal(prop, signal, { multiplier, offset, smoothing })` — see [Audio & signals](/docs/guides/audio-and-signals/) and [Physics & particles](/docs/guides/physics/). ## Kinetic typography [Section titled “Kinetic typography”](#kinetic-typography) Text animators work per glyph, word or line on the GPU. Add one to the text, then sweep its selection with `kineticSweep`. ```ts import { Layer, LayerAnimation, TextAnimator } from "framefields"; Layer.text("TypeScript in.", { fontFamily: "Archivo", fontWeight: 800, fontSize: 200, fill: "#e6e8e6", animators: [TextAnimator.waveRise({ y: 90, rotationX: 70 })], }).animate(LayerAnimation.create().kineticSweep(-1, 1, 0, 40)); ``` | Preset | Effect | | -------------------------------------------------------------- | -------------------------------- | | `TextAnimator.waveRise({ y, rotationX, opacity, blur, unit })` | glyphs rise and untilt in a wave | | `TextAnimator.wordPop({ scale, y })` | words pop in | | `TextAnimator.blurIn(...)` | glyphs resolve from blur | | `TextAnimator.flip3D(...)` | glyphs flip in around X | | `TextAnimator.colorSweep(...)` | color passes through the text | `unit` is `"character"` (default), `"word"` or `"line"`. For terminal-style typing use `.typewriter(start, end)`. ## 3D transforms on 2D layers [Section titled “3D transforms on 2D layers”](#3d-transforms-on-2d-layers) Any layer can tilt in perspective. ```ts Layer.box({ width: 600, height: 400, background: "#181715", borderRadius: 24, transformStyle: "preserve-3d", perspective: 1200, }).animate( LayerAnimation.create() .fromTo("rotateX", 25, 0, { start: 0, end: 30, ease: "expo.out" }) .fromTo("rotateY", -35, 0, { start: 0, end: 30, ease: "expo.out" }) .fromTo("translateZ", -200, 0, { start: 0, end: 30, ease: "expo.out" }), ); ``` For cameras, lights and meshes, see [3D](/docs/guides/3d/). ## Gotchas [Section titled “Gotchas”](#gotchas) * Keyframes past `durationFrames` never play (`animation_truncated`). * Animating `x`/`y` overrides the layout position. * A track whose keys all hold one value does nothing (`static_track`). # Assets and storage > Keep footage, audio and other media out of git on your own S3-compatible bucket (Cloudflare R2, S3, B2, MinIO), pinned by sha256 in framefields.json, served through a custom domain or CDN. Footage and audio are too big for git. framefields keeps them on a bucket you own and pins each file in `framefields.json` by its sha256, the way a lockfile pins packages: the repo stays small, every clone and every render gets exactly the same bytes, and nothing about your film’s code changes. ```bash npx framefields assets add assets/footage # upload, pin, gitignore npx framefields assets pull # in a fresh clone: download and verify ``` Any S3-compatible bucket works. **Cloudflare R2** is the one we recommend: it charges nothing for downloads, so cloning, CI and cloud renders cost you storage only. ## Set up a bucket [Section titled “Set up a bucket”](#set-up-a-bucket) 1. Create a bucket (in R2: **R2 → Create bucket**) and an API token that can read and write it (**Manage R2 API tokens**, Object Read & Write, scoped to the bucket). 2. Optionally, make it public through a **custom domain** (R2: bucket **Settings → Custom Domains**), or any CDN in front of it. Then anyone can pull your assets, and renders started from the dashboard can read them, without keys. 3. Add it to `framefields.json`: ```json { "storage": { "remotes": { "media": { "endpoint": "https://.r2.cloudflarestorage.com", "bucket": "films", "prefix": "launch/", "publicUrl": "https://media.example.com" } } } } ``` | Field | | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `endpoint` | The bucket’s S3 API URL. R2: `https://.r2.cloudflarestorage.com` (EU jurisdiction: `…eu.r2.cloudflarestorage.com`). AWS: `https://s3..amazonaws.com`. | | `bucket` | The bucket name. | | `region` | SigV4 region. Default `auto`, which R2 uses; AWS needs the bucket’s region. | | `prefix` | Optional folder inside the bucket, so several projects can share one. | | `publicUrl` | Optional public base URL: a custom domain, a CDN or the `r2.dev` URL. Reads use it without keys. | Several remotes are fine, for example a public one for media you’re happy to share and a private one for raw footage. `"default": "media"` names the one new assets go to; `--remote raw` picks another. 4. Give the CLI the keys through the environment, never the file: ```bash export FRAMEFIELDS_STORAGE_MEDIA_ACCESS_KEY_ID=… export FRAMEFIELDS_STORAGE_MEDIA_SECRET_ACCESS_KEY=… ``` The names follow the remote (`raw-footage` → `FRAMEFIELDS_STORAGE_RAW_FOOTAGE_…`). Without them, the standard `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` are used. ## Commands [Section titled “Commands”](#commands) | Command | | | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `npx framefields assets add ` | Hash files (a folder means every file in it), upload what the bucket lacks, pin them under `assets` and add them to `.gitignore`. Adding a changed file again pins the new version. | | `npx framefields assets pull` | Download missing assets and check every byte. Files you changed locally are left alone unless `--overwrite`. | | `npx framefields assets push` | Upload pinned assets the bucket lacks, from your local files. | | `npx framefields assets status` | Each asset: `ok`, `missing` or `changed`. `--json` for scripts. | `add` writes entries like this; commit `framefields.json` and `.gitignore`: ```json "assets": { "assets/footage/intro.mp4": { "sha256": "9f2c…", "size": 48213992 } } ``` An entry can also carry a fixed `url` instead of a remote, for public media you didn’t upload (stock footage, a sample): it is downloaded from there and checked against the same sha256. ## Custom domains and CDNs [Section titled “Custom domains and CDNs”](#custom-domains-and-cdns) Objects are stored by content, at `sha256//`, so they never change. Uploads are marked `Cache-Control: public, max-age=31536000, immutable` and carry their real `Content-Type`, so a custom domain or CDN can cache them forever and browsers can play them directly: `https://media.example.com/launch/sha256/9f/9f2c…`. Projects sharing a bucket and prefix store a file once, and uploading it again is skipped. ## Preview from the bucket [Section titled “Preview from the bucket”](#preview-from-the-bucket) `npx framefields preview` doesn’t need the files on disk. When a pinned asset is missing (a fresh clone, an agent working in a cloud sandbox), the preview sends the page to the bucket for it: the remote’s `publicUrl`, or a URL signed with the remote’s keys from the environment. The browser streams it from there, seeking with byte ranges, so nothing is downloaded into the project, and the soundtrack is mixed from the same URLs. The engine reads media with `fetch`, so the bucket must allow the preview’s origin (CORS). In R2: bucket **Settings → CORS policy**: ```json [ { "AllowedOrigins": ["*"], "AllowedMethods": ["GET", "HEAD"], "AllowedHeaders": ["Range"], "ExposeHeaders": ["Content-Length", "Content-Range", "Accept-Ranges", "ETag"], "MaxAgeSeconds": 86400 } ] ``` `"*"` suits a public bucket: anyone can read it anyway. For a private one, list exact origins instead: the preview’s (`http://127.0.0.1:`, printed when it starts; the port is stable per project) and your agent sandbox’s or tunnel’s. The policy covers the bucket’s custom domain and signed URLs alike. On S3 it is the same rules under **Permissions → CORS**. Without CORS the page shows a fetch error for the clip. `npx framefields assets pull` is the fallback: with the files on disk, the preview serves them itself. R2 signed URLs work only on the S3 API host (`.r2.cloudflarestorage.com`), not a custom domain: the custom domain is for public media, and private remotes are read through signatures. ## Render here or in the cloud [Section titled “Render here or in the cloud”](#render-here-or-in-the-cloud) `npx framefields render ` renders on this machine and first downloads pinned assets that are missing; `npx framefields render --cloud` renders the same named render on framefields GPUs, to the same output file. ## In cloud renders [Section titled “In cloud renders”](#in-cloud-renders) [Cloud renders](/docs/guides/cloud-rendering/) download pinned assets on every GPU before rendering: * `framefields render --cloud` and `renderCloud` first upload anything the bucket lacks, so a forgotten `push` doesn’t fail the render. * Assets on a remote with a `publicUrl` are read from it. Assets on a private remote get read URLs signed on your machine, valid for 24 hours; your keys are never sent. * Workers cache assets by hash, so a worker that renders the project again reuses them. On R2, the downloads every GPU of a split render makes cost nothing, unlike LFS bandwidth from a git host. * Renders started from the dashboard have no machine to sign from, so they read only remotes with a `publicUrl`. ## Git LFS [Section titled “Git LFS”](#git-lfs) Projects that already use Git LFS keep working: the render worker pulls LFS before it downloads pinned assets, and `framefields init` still writes LFS `.gitattributes`. LFS has two costs a bucket avoids: every clone and every render worker downloads the objects from your git host, which bills that bandwidth to the repo owner (an open-source film pays for everyone who clones it), and a clone without `git lfs pull` holds pointer files that decode as blank frames. To move, `npx framefields assets add` the LFS-tracked files, remove their patterns from `.gitattributes`, and `git rm --cached` them. ## When something fails [Section titled “When something fails”](#when-something-fails) | Code | Cause | Fix | | ------------------------ | ------------------------------------------------------------------- | --------------------------------------------------------- | | `ASSET_NOT_UPLOADED` | A pinned asset isn’t on the bucket | `npx framefields assets push` from a machine that has it | | `ASSET_HASH_MISMATCH` | The bucket or URL serves other bytes than `framefields.json` pins | Push the right file, or `assets add` the new version | | `ASSET_PRIVATE` | A dashboard render, and the remote has no `publicUrl` | Render from the CLI, or add a `publicUrl` | | `ASSET_FORBIDDEN` | The custom domain doesn’t serve the bucket, or a signed URL expired | Check the domain is connected to the bucket; render again | | `ASSET_MANIFEST_INVALID` | `storage` or `assets` is malformed | `npx framefields assets status` shows the error | # Audio & signals > Soundtracks, audio effects, deterministic procedural SFX, and signals that drive any prop or effect from time, data or sound. ## Soundtrack [Section titled “Soundtrack”](#soundtrack) ```ts import { Effect, Layer } from "framefields"; comp.addAudio( Layer.audio("assets/audio/score.mp3", { durationFrames: totalFrames, // required: without it audio can cut short volume: 0.9, }).apply(Effect.audioFade({ fadeInDuration: 2, fadeOutDuration: 2, fadeOutCurve: "scurve" })), ); ``` `Layer.audio` takes `volume`, `startFrame`, `durationFrames`, `muted`. Video layers carry their own sound (`muted`, `volume`, `trimStartSec`). Audio effects attach with `.apply()`: `Effect.audioFade`, `audioCompressor`, `audioParametricEq`, `audioReverb`, `audioDelay`, `audioNoiseGate`, `stereoPanning` (or the classes `AudioFade`, `AudioCompressor`, …). Props are in the [Effects reference](/docs/reference/effects/). ## Procedural SFX [Section titled “Procedural SFX”](#procedural-sfx) Whooshes, risers, impacts, downshifters and glitches are synthesized on the CPU, seeded, and placed on a bar grid — the same input always gives the same samples. ```ts import fs from "node:fs/promises"; import { encodeStereoWav, Layer, mixSfxInto, renderSfx, softLimit } from "framefields"; const sampleRate = 48_000; const seconds = totalFrames / FPS; const bed: [Float32Array, Float32Array] = [ new Float32Array(Math.ceil(seconds * sampleRate)), new Float32Array(Math.ceil(seconds * sampleRate)), ]; const ctx = { sampleRate, secondsPerBar: 2.4 }; // 100 BPM, 4/4 mixSfxInto(bed, [ renderSfx({ type: "riser", atBar: 0.5, volume: 0.4 }, { ...ctx, seed: 1 }), renderSfx({ type: "impact", atBar: 1, volume: 0.8 }, { ...ctx, seed: 2 }), renderSfx({ type: "whoosh", atBar: 2.75, volume: 0.5 }, { ...ctx, seed: 3 }), ]); softLimit(bed); await fs.writeFile("output/sfx.wav", encodeStereoWav(bed, { sampleRate })); comp.addAudio(Layer.audio("output/sfx.wav", { durationFrames: totalFrames })); ``` `atBar` is where the sound **starts** (fractional bars allowed); a riser that should land on a cut starts `durationSec` earlier. `mixAudioTracks` mixes several tracks headlessly. ## Signals [Section titled “Signals”](#signals) A signal is a value per frame. Bind one to any animatable prop, or pass it to any numeric effect prop. ```ts import { LayerAnimation, Signal } from "framefields"; const pulse = Signal.builder({ type: "sawtooth", frequency: 2, amplitude: 0.08, offset: 1 }); // 120 BPM card.animate( LayerAnimation.create().signal("scale", pulse, { multiplier: 1, offset: 0, smoothing: 2 }), ); ``` The prop becomes `value × multiplier + offset` each frame. Signals are sampled at the **composition** frame. | Constructor | Value | | --------------------------------------------------------------- | ------------------------------------------------------------------------------ | | `Signal.builder({ type, frequency, amplitude, offset })` | `sine`, `triangle`, `sawtooth`, `square`, `bounce`, or `custom` with `fn(ctx)` | | `Signal.sine({ frequency, min, max, phase })` / `Signal.cosine` | periodic wave; `frequency` in Hz | | `Signal.fromArray(values, fps)` | one sample per frame, e.g. a precomputed kick envelope | | `Signal.programmatic((ctx) => number)` | any function of `ctx.frame`, `ctx.time`, `ctx.progress` | | `Signal.frame` / `Signal.time` / `Signal.progress` | the clock itself, as signals (read `.value`) | | `Signal.state(v)` / `Signal.computed(() => …)` | reactive values, e.g. `Signal.computed(() => 55 - Signal.frame.value * 0.1)` | ### Shared signals by name [Section titled “Shared signals by name”](#shared-signals-by-name) ```ts comp.addSignal("kick", Signal.fromArray(kickEnvelope, FPS)); LayerAnimation.create().signal("opacity", "kick", { multiplier: 0.5, offset: 0.5 }); ``` A signal object is registered automatically; a string must match an `addSignal` name. Anything else throws. A signal can also set a video or audio layer’s playback speed or source time: see [time remapping](/docs/guides/charts-and-media/#driven-by-a-signal). ### Colors [Section titled “Colors”](#colors) `.colorSignal(prop, signal, options)` drives a color prop; modes are `interpolate`, `hueRotate` and `threshold`. ## Audio-reactive visuals [Section titled “Audio-reactive visuals”](#audio-reactive-visuals) Extract an envelope from audio with the `AudioSignalExtractor` effect (modes, attack/release, beat detection), or precompute one in Node and feed it through `Signal.fromArray`. Precomputing keeps the film a pure function of the frame and is the easiest to test. # Charts & media > Video, image, SVG, Lottie and caption layers, the Media chain, and animated charts built from native nodes. ## Media layers [Section titled “Media layers”](#media-layers) ```ts Layer.video("assets/footage/clip.mp4", { width: 1920, height: 1080, fit: "cover", trimStartSec: 2, muted: true }); Layer.image("assets/images/still.webp", { width: 800, height: 600, fit: "contain" }); // .png .jpg .webp Layer.svg("assets/images/logo.svg", { width: 400, height: 120, fit: "contain" }); Layer.lottie("assets/lottie/badge.json", { width: 400, height: 400, fit: "contain", loop: true }); // .json .lottie Layer.caption("assets/captions/subs.srt", { /* bottom-anchored, auto-wrapping cues */ }); ``` | Builder | Notes | | --------------- | -------------------------------------------------------------------------------------------------------- | | `Layer.video` | decoded with mediabunny/WebCodecs; `fit`, `trimStartSec`, `timeRemap`, `muted`, `volume` | | `Layer.image` | raster only. Passing `.json`/`.lottie`/video/audio is an error (`unsupported_image_format`) | | `Layer.svg` | vector image | | `Layer.lottie` | Lottie JSON and dotLottie via ThorVG; `fit: "contain" \| "cover" \| "fill"`, `loop`, `speed`, `autoplay` | | `Layer.caption` | SRT-driven subtitles | All of them position, animate, matte, take effects and tilt into 3D like any layer. Asset paths resolve from the working directory; build them from `import.meta.url` if the [preview](/docs/guides/preview/) must load them too. ## Time remapping [Section titled “Time remapping”](#time-remapping) Next release `timeRemap` ships in the release after framefields 2.6.2. `timeRemap` decides which moment of the source plays at each frame of a video or audio layer: slow motion, speed ramps, reverse, freeze frames. The layer needs an explicit `durationFrames`. Picture, embedded audio and `comp.vision(layer)` follow the same mapping. Effects stay on the composition clock. ```ts // Constant rate: half speed from 3 s in. A negative rate plays backwards. Layer.video("assets/footage/clip.mp4", { durationFrames: 96, timeRemap: { kind: "rate", sourceStartSec: 3, rate: 0.5 }, }); // Keyframes: layer frame → source second. Equal source times hold the frame. Layer.video("assets/footage/clip.mp4", { durationFrames: 90, timeRemap: { kind: "keyframes", keyframes: [ { frame: 0, sourceSec: 1, interpolation: "smooth" }, { frame: 30, sourceSec: 2 }, { frame: 45, sourceSec: 2 }, // hold { frame: 90, sourceSec: 1 }, // reverse back to 1 s ] }, }); ``` Keyframes start at frame 0, end at `durationFrames` and increase in frame. `interpolation` applies to the segment after a key: `"linear"` (default), `"ease-in"`, `"ease-out"` or `"smooth"`, all without overshoot. Audio is resampled, so its pitch follows the speed, and a hold is silent. Do not combine `timeRemap` with `trimStartSec`. A map that reaches outside the source fails before rendering. ### Driven by a signal [Section titled “Driven by a signal”](#driven-by-a-signal) A [signal](/docs/guides/audio-and-signals/#signals) can drive the source clock instead of a fixed map. ```ts import { Layer, Signal } from "framefields"; const speed = Signal.state(1); comp.onRequestFrame((ctx) => speed.set(ctx.frame < 48 ? 1 : 0.2)); comp.add(Layer.video("assets/footage/dancer.mp4", { durationFrames: 240, fit: "cover", timeRemap: { kind: "signal", mode: "speed", signal: speed }, })); ``` | Field | Meaning | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `mode: "speed"` | the signal is the playback rate (1 = real time, 0 = freeze, negative = reverse), integrated from `sourceStartSec` (default 0) | | `mode: "source-time"` | the signal is the absolute source second to show | | `signal` | a `Signal`, or the name of a signal registered with `comp.addSignal`, including analysis channels | The signal is read on the composition clock at every frame of the layer and interpolated between frames, so audio samples between frames stay smooth. * **No frame hooks:** the signal is sampled up front, and frames render in any order. * **With frame hooks** (`onRequestFrame`, `onPrepareFrame`, `comp.vision`, live physics): the signal is live. Each frame’s value is recorded once, after that frame’s hooks run. * A frame never reads a value ahead of itself. * Rendering a later frame first runs the skipped frames’ hooks in order. Going back reuses what was already recorded. * Source bounds are checked as each frame is recorded. * A layer that outlasts the composition holds its last speed. * A signal that reads its own layer’s current source time throws a circular-dependency error. ## Media chains [Section titled “Media chains”](#media-chains) Process a single clip outside the layer tree, e.g. to grade footage or extract a still. ```ts import { ApplyLUT, Media } from "framefields"; const graded = Media.video("assets/footage/raw_log.mp4").apply(new ApplyLUT({ lutUrl: "assets/luts/rec709.cube" })); await graded.renderFrame({ atMs: 1500 }); // PNG Buffer await graded.renderVideo({ outputPath: "output/graded.mp4" }); ``` `Media.video`, `Media.image`, `Media.lottie`, `Media.audio`; each has `apply`, `renderFrame`, `renderFrameGrid`, `renderVideo`. ## Charts [Section titled “Charts”](#charts) `Layer.chart(options, boxProps)` builds a chart out of ordinary boxes, paths and text — d3 does the scales and geometry, framefields draws it with your fonts. ```ts Layer.chart( { type: "bar", // line | area | bar | scatter | candlestick | pie | donut width: 900, height: 480, categories: ["Q1", "Q2", "Q3", "Q4"], series: [ { name: "Revenue", data: [12, 19, 24, 31] }, { name: "Costs", data: [8, 11, 13, 15] }, ], yAxis: { min: 0, ticks: 4, format: "$,.0f" }, // d3-format string or (v) => string fontFamily: "Inter", fontSize: 24, textColor: "#e6e8e6", gridColor: "#2a2b2d", animate: { start: 10, duration: 30, stagger: 6, ease: "power3.out" }, // or false }, { id: "revenue", position: "absolute", x: 120, y: 200 }, ); ``` | Option | Notes | | --------------------------------------------------------------------- | -------------------------------------------------------------------- | | `series: [{ name, data, color, type, curve, pointRadius }]` or `data` | `data` for pie/donut slices and candles | | `stacked` | stack bars/areas | | `xAxis`, `yAxis` | `min`, `max`, `ticks`, `grid`, `format` | | `legend`, `valueLabels` | booleans | | `colors`, `textColor`, `gridColor`, `background`, `cornerRadius` | style | | `innerRadius` | donut hole | | `upColor`, `downColor` | candlesticks | | `animate` | built-in reveal: lines draw on, bars grow, points and slices stagger | Children get stable ids — `-bar--`, `-line-`, `-slice-` — so you can find them in lint output. Keep scatter plots to a few hundred points: each point is a node. # Cloud rendering > Render a project on framefields GPUs from git, by name, from the CLI, code or the dashboard, and split long films across several GPUs. framefields renders your project on its own GPUs, straight from git: no GPU, Docker or render farm on your side. Name a render once in `framefields.json`, then start it from the terminal, from code or from the [dashboard](https://framefields.dev/dashboard/renders). Long films split across several GPUs and come back as one file. ```bash npx framefields render film --cloud --plan # Plan: 4 workers, 1 h 50 min of render work, ready in about 35 min, estimated $1.20. npx framefields render film --cloud # Done in 34 min: output/film.mp4 (412.3 MB), 6620 GPU seconds, $1.18. ``` ## Before you render [Section titled “Before you render”](#before-you-render) * **Push.** The cloud renders the **pushed commit**. Uncommitted changes are not rendered (the CLI warns), and a commit that isn’t on the remote is refused. * **An API key.** Renders bill the account behind `FRAMEFIELDS_API_KEY`, the same key as the [AI gateway](/docs/guides/ai/). Create one at [framefields.dev/dashboard/keys](https://framefields.dev/dashboard/keys) and add credit under [Billing](https://framefields.dev/dashboard/billing). * **Private repos:** connect GitHub once under [Settings → Connections](https://framefields.dev/dashboard/settings#connections). Install the framefields GitHub App on **all repositories**, so repos you create later render without another step. It only gets read access, and each render gets a token for its own repo that expires in an hour. Public repos need nothing. * **A render-ready project:** a committed lockfile, assets pinned with [`framefields assets`](/docs/guides/assets/) (or in Git LFS), and an entry that only builds the film. A project made with `framefields init` already is one; the full list is the [project checklist](/docs/guides/render-service/#project-checklist). * **Run from the project folder** (where `framefields.json` is). In a monorepo, that folder is what renders. ## Name your renders [Section titled “Name your renders”](#name-your-renders) `framefields.json` at the project root names what the project renders. `npx framefields init` writes `film`; add an entry for each cut. ```json { "components": "src/components", "renders": { "film": { "title": "Launch film", "entry": "src/film.ts", "export": "buildFilm", "workers": "auto", "output": "output/film.mp4" }, "teaser": { "title": "15 s teaser", "description": "Vertical cut for socials", "entry": "src/film.ts", "export": "buildTeaser", "codec": "vp9" } } } ``` | Field | | | ---------------------- | ------------------------------------------------------------------------------- | | `entry` | The module that builds the composition, relative to the project root. Required. | | `export` | A `Composition`, or a function returning one. Default `buildFilm`. | | `title`, `description` | Shown in the dashboard and `framefields renders`. | | `args` | Passed to the export when it is a function. | | `select` | When the export returns several compositions, the one to render. | | `workers` | `1` (default), a number, or `"auto"` to split long films. | | `maxWorkers` | Upper bound for `"auto"`. | | `codec` | `h264` (default, MP4) or `vp9` (WebM). | | `quality` | `very_low`, `low`, `high` or `very_high` (default). | | `output` | Where the CLI downloads the video. | Names use letters, digits, `-`, `_` and `.`. `npx framefields renders` lists them; `npx framefields check` checks every one, `npx framefields check teaser` one. ## From the terminal [Section titled “From the terminal”](#from-the-terminal) ```bash npx framefields render film --cloud --plan # workers, time and estimated cost; renders nothing npx framefields render film --cloud # render, then download to the render's output ``` Without `--cloud`, `npx framefields render film` renders the same named render on this machine, to the same file, and `npx framefields preview film` plays it in the browser: switching is the flag. Flags override the render’s fields (`--workers 4`, `--codec vp9`, `--output`). With a single named render, `npx framefields render --cloud` needs no name. A module renders without a manifest too: `npx framefields render src/film.ts --cloud --export buildFilm`. `--plan` probes the film and prints the GPUs, time and estimated cost, then the command that renders it; it renders nothing. While rendering, the CLI prints one line per phase and progress every 10 seconds with the cost so far. `--json` prints the final status as JSON. Ctrl-C cancels the render; GPU time already used is charged. ## From code [Section titled “From code”](#from-code) ```ts import { renderCloud } from "framefields/cloud"; const result = await renderCloud({ render: "film", outputPath: "output/film.mp4", onProgress: (s) => console.log(s.status, s.progress.frames), }); ``` `framefields/cloud` needs no GPU. Options passed here override the named render’s; `dryRun: true` returns the plan and estimate, and `signal` cancels. A failed render throws a `CloudRenderError` with the worker’s `code`. ### HTTP API [Section titled “HTTP API”](#http-api) The CLI and `renderCloud` call the same API, with `Authorization: Bearer $FRAMEFIELDS_API_KEY`: ```bash curl https://api.framefields.dev/v1/render \ -H "Authorization: Bearer $FRAMEFIELDS_API_KEY" -H "Content-Type: application/json" \ -d '{ "source": { "repo": "https://github.com/acme/launch-film", "ref": "main" }, "target": { "entry": "src/film.ts", "export": "buildFilm" }, "render": { "codec": "h264" }, "workers": "auto", "dry_run": false }' ``` `GET /v1/render/:id` returns its status (`probing`, `rendering`, `stitching`, then `completed` with `output.url`, or `planned`, `failed`, `cancelled`), progress, plan and cost so far. `DELETE /v1/render/:id` cancels it. Optional `source.commit` pins a commit and `source.workdir` a folder; optional `name` and `title` label it in the dashboard. ## From the dashboard [Section titled “From the dashboard”](#from-the-dashboard) [Connect GitHub](https://framefields.dev/dashboard/settings#connections) once, on all repositories, then **Renders → New render**: pick a repo and branch, and the dialog lists the renders its `framefields.json` names, with their titles and descriptions. Picking one applies its GPUs and format. **Plan** shows GPUs, time and cost before anything renders. Repos without named renders still render: choose **Another file in this repo** and pick the module and export. The Renders page lists every render, from the dashboard, the CLI or the API: live progress, cost so far against the estimate, Cancel, and the finished video. ## Splitting long films [Section titled “Splitting long films”](#splitting-long-films) `workers: "auto"` measures frame costs on one GPU first, then splits the film into as many chunks as stay efficient: a 5-minute film stays on one GPU, a 3-hour film spreads across up to 10. Each chunk renders on its own GPU, the audio renders once, and the chunks are joined without re-encoding. Effects with state (trails, datamosh, particles) replay earlier frames, so every chunk renders the same picture as a single render. ## Cost [Section titled “Cost”](#cost) You pay for GPU seconds actually used. When a render starts, a credit hold is placed on your balance; once the film is planned the hold is raised to the estimate, and when it finishes you are charged the GPU time used and the rest is released. Failed and cancelled renders charge the GPU time they used. `--plan` (or **Plan**) costs the few seconds of GPU time the probe takes. ## When a render fails [Section titled “When a render fails”](#when-a-render-fails) The error names the worker’s code. Fix the project, commit, push and render again; network errors, stalled workers and lost machines are retried by the API, and a straggling chunk gets a backup worker. | Code | Cause | Fix | | ----------------------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------- | | `REPO_NOT_FOUND`, `GIT_AUTH_FAILED` | A private repo the GitHub App can’t reach | Connect GitHub with access to this repo | | `REF_NOT_FOUND`, `COMMIT_MISMATCH` | The branch or commit isn’t on the remote | `git push` | | `LOCKFILE_MISSING`, `INSTALL_FAILED` | No committed lockfile, or it doesn’t install | Commit a pnpm, npm or yarn lockfile matching `package.json` | | `ENTRY_NOT_FOUND`, `EXPORT_NOT_FOUND` | `entry` or `export` is wrong | `npx framefields check ` | | `EXPORT_SIDE_EFFECT`, `COMPOSITION_BUILD_FAILED` | The entry renders or writes while building, or throws | Keep `film.ts` to building; `framefields check` reproduces it | | `ASSET_NOT_FOUND`, `LFS_OBJECT_MISSING`, `LFS_POINTER_UNRESOLVED` | An asset wasn’t committed or its LFS object wasn’t pushed | `git lfs ls-files`, `git lfs push --all origin` | | `ASSET_NOT_UPLOADED`, `ASSET_PRIVATE`, `ASSET_HASH_MISMATCH` | A pinned asset isn’t on the bucket, or the worker can’t read it | [Assets: when something fails](/docs/guides/assets/#when-something-fails) | | `ENGINE_UNSUPPORTED` | The project’s framefields is too old to split | Upgrade framefields, or use `--workers 1` | | `RENDER_TIMEOUT`, `RENDER_OOM` | One GPU can’t finish its part | `--workers auto`, or more workers | | `insufficient_credits` | The balance doesn’t cover the hold | Add funds under [Billing](https://framefields.dev/dashboard/billing) | All worker codes: [Render on a server](/docs/guides/render-service/#errors). # Effects > Attach GPU effects to layers, whole compositions, regions and media chains; order them; drive their props with signals. Effects are typed classes. Construct one with props, attach it, and the GPU runs it each frame. The full list with every prop is in the [Effects reference](/docs/reference/effects/). ```ts import { Blur, Curves, FilmGrain, Vignette } from "framefields"; // or "framefields/effects" ``` ## Where to attach [Section titled “Where to attach”](#where-to-attach) ```ts // 1. One layer (chain as many as you like, in order) Layer.video("assets/footage/plate.mp4", { fit: "cover" }) .withEffect(new Curves({ master: [{ x: 0, y: 0.05 }, { x: 0.5, y: 0.52 }, { x: 1, y: 0.95 }] })) .withEffect(new Vignette({ strength: 40, radius: 0.85, softness: 0.6 })); // 2. The whole frame comp.apply(new FilmGrain({ strength: 12, size: 1.5, animated: true })); // 3. A region of a plate (rectangle, rounded, or a tracked object) comp.section({ source: "assets/footage/interview.mp4", x: 400, y: 200, width: 300, height: 300, borderRadius: 150, effects: [new Blur({ strength: 25, blurType: "Gaussian" })], }); // 4. A clip outside the layer tree import { ApplyLUT, Crop, Media } from "framefields"; const clip = Media.video("assets/footage/raw_log.mp4") .apply(new ApplyLUT({ lutUrl: "assets/luts/cinematic.cube", intensity: 1 })) .apply(new Crop({ cropType: "rectangle", topPercentage: 10, heightPercentage: 80 })); await clip.renderFrame({ atMs: 1500 }); ``` `.withEffects([a, b])` attaches several at once. Lowercase factories work too: `Effect.blur({ strength: 9 })`. ## Value ranges [Section titled “Value ranges”](#value-ranges) Ranges come from each effect’s schema; out-of-range values warn (set `FRAMEFIELDS_STRICT_PROPS=1` to throw). Many “strength” props are **0–100**, not 0–1: | Effect | Prop | Range | Default | Tasteful | | -------------- | ----------------------------------------- | ---------- | -------- | -------- | | `Vignette` | `strength` | 0–100 | 50 | 20–45 | | `FilmGrain` | `strength` | 0–100 | 15 | 8–20 | | `FilmGrain` | `size` | 0.5–4 | 1.5 | 1.2–1.8 | | `Blur` | `strength` | 0–100 | 5 | — | | `ColorBalance` | `cyanRed` / `magentaGreen` / `yellowBlue` | −100–100 | 0 | ±4–12 | | `ColorKey` | `similarity`, `smoothness` | 0–1 | 0.4, 0.1 | — | | `Modulate` | `brightness`, `contrast`, `saturation` | multiplier | 1 | 0.9–1.2 | ## Order [Section titled “Order”](#order) 1. Tonal grading first: `Curves`, `Levels`, `ColorBalance`, `SelectiveColor`, `ApplyLUT`. 2. Then optics: `Blur`, `DepthOfField`, `Vignette`. 3. Grain last, as the outermost pass: `FilmGrain`. For a still export, set `animated: false` on `FilmGrain` so the frame is deterministic across renders of different lengths. ## Drive props with signals [Section titled “Drive props with signals”](#drive-props-with-signals) Any numeric effect prop accepts a signal instead of a number. The uniform updates per frame without rebuilding the pipeline. ```ts import { Blur, Layer, Signal } from "framefields"; const breathe = Signal.sine({ frequency: 0.5, min: 0, max: 20 }); // Hz, sampled at the composition frame Layer.image("assets/images/bg.jpg").withEffect(new Blur({ strength: breathe, blurType: "Gaussian" })); ``` Vision signals plug in the same way, e.g. `new Vignette({ strength: vision.segmentation.subject.coverage })`. See [Vision](/docs/guides/vision/). ## Temporal effects (`Trails`, `Datamosh`) [Section titled “Temporal effects (Trails, Datamosh)”](#temporal-effects-trails-datamosh) Temporal effects process frame history to create motion persistence, light painting, and optical flow artifacts: ```ts import { Datamosh, Layer, Trails } from "framefields"; // Motion echoes, feedback tunnels, and light painting Layer.video("assets/footage/dancer.mp4").withEffect( new Trails({ decay: 0.92, // history retained per frame (0.8 = short echoes, 0.97 = long light trails) mode: "blend", // "blend" | "over" | "add" (glow accumulation) | "max" zoom: 1.01, // history scale per frame (pulls past into a tunnel) rotation: 0.5, // history rotation per frame in degrees hueShift: 2, // psychedelic hue rotation per frame }), ); // Pixel smearing along motion vectors Layer.video("assets/footage/action.mp4").withEffect( new Datamosh({ keyframes: [0, 60, 120], // clean I-frames; pixels drag along optical flow between them strength: 1.5, // how far pixels are dragged along motion bleed: 0.04, // clean picture mixed back in each frame }), ); ``` ## Families [Section titled “Families”](#families) | Family | Effects | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Grading | `Curves`, `Levels`, `ColorBalance`, `SelectiveColor`, `GradientMap`, `ShadowsHighlights`, `ApplyLUT`, `ExtractLUT`, `Modulate`, `ChannelSplitter`, `ChannelMerger` | | Texture & lens | `FilmGrain`, `Vignette`, `Blur`, `MotionBlur`, `UnsharpMask`, `HighPass`, `HalftoneScreen`, `TileOffset`, `TemporalDeflicker` | | Distortion | `DisplacementMap`, `Liquify`, `MeshWarp`, `CornerPin`, `Rotate`, `Flip`, `KenBurns`, `ResizerScaler` | | Temporal | `Trails`, `Datamosh` | | 3D & light | `Relight3D`, `SSAO`, `PBRGlass`, `DepthOfField`, `RefractionCaustics3D`, `CameraParallax3D` | | Mattes & keying | `ColorKey`, `Crop`, `RefineEdge`, `MaskMath`, `PatchHeal` | | Generators & style | `NoiseGenerator`, `ProceduralVFX`, `Paint`, `LayerStyle` | | Audio | `AudioFade`, `AudioCompressor`, `AudioParametricEq`, `AudioReverb`, `AudioDelay`, `AudioNoiseGate`, `StereoPanning`, `AudioSignalExtractor` | | Vision | `Vision` (prefer `withVision`, see [Vision](/docs/guides/vision/)) | ## Restraint [Section titled “Restraint”](#restraint) Grain and vignette should be felt, not seen. If a viewer notices the effect before the content, halve it. # Layout & text > Boxes, flex layout, shapes, fonts, GPU text, rich text, measurement, colors, gradients and track mattes. ## Boxes and flex [Section titled “Boxes and flex”](#boxes-and-flex) ```ts import { Layer } from "framefields"; Layer.flex({ width: 1920, height: 1080, dir: "column", // "row" | "column" justify: "center", // start | center | end | space-between | space-around align: "center", // start | center | end | stretch gap: 24, padding: 80, wrap: false, background: "#0d0f12", children: [ Layer.box({ padding: 16, background: "#1e232d", borderRadius: 20, children: [/* … */] }), ], }); ``` | Prop | Notes | | -------------------------------------------- | --------------------------------------------------------------------------- | | `width`, `height` | px, `"auto"` (intrinsic), `"fit"` (shrink-wrap) or `"fill"` (parent extent) | | `position: "absolute"` + `x`, `y` | take the layer out of flow; `x`/`y` alone also make it absolute | | `background` | a color or a CSS gradient string | | `borderRadius`, `borderColor`, `borderWidth` | no CSS `border` shorthand | | `overflow: "hidden"` | clip children to the box | | `opacity`, `scale`, `rotation` | static or animated | | `startFrame`, `durationFrames` | when the layer is on screen | | `id` | stable name; used by lint/QA messages and chart children | ## Shapes [Section titled “Shapes”](#shapes) ```ts Layer.shape("circle", { width: 200, height: 200, fill: "#ff5a1f" }); Layer.shape("star", { width: 240, height: 240, fill: "radial-gradient(#fff, #ffb800)" }); Layer.shape("path", { d: "M0 0 L200 0 A100 100 0 0 1 0 0Z", strokeColor: "#fff", strokeWidth: 4, trimEnd: 0 }) .animate(LayerAnimation.create().fromTo("trimEnd", 0, 1, { start: 0, end: 30 })); // draw-on ``` Types: `rect`, `circle`, `ellipse`, `polygon`, `star`, `arrow`, `path`. Animate `trimStart` / `trimEnd` / `trimOffset` for stroke draw-ons. ## Fonts [Section titled “Fonts”](#fonts) There are no system fonts in headless WebGPU. Register every family before building any text layer. ```ts import { FontManager } from "framefields"; await FontManager.register({ family: "Inter", source: "assets/fonts/Inter.ttf" }); await FontManager.register({ family: "Inter", source: "assets/fonts/Inter-Bold.ttf", weight: 700 }); await FontManager.registerEmojiFont("assets/fonts/NotoColorEmoji.ttf"); // emoji need a CBDT/CBLC color font ``` ## Text [Section titled “Text”](#text) ```ts Layer.text("PRECISION MOTION", { fontFamily: "Inter", fontSize: 96, fontWeight: 700, fill: "#ffffff", letterSpacing: 2, lineHeight: 104, width: 1400, // wrap width; set it or text may clip align: "center", // "start" | "center" | "end" (follows text direction) verticalAlign: "middle", // "top" | "middle" | "bottom" inside the box height }); ``` Text is drawn by the Slug algorithm: glyph curves are evaluated per pixel in the shader, so it stays sharp at any size and under 3D camera moves. Arabic, Hebrew and Persian shape right-to-left automatically (`direction: "auto"`; force with `"rtl"` / `"ltr"`). ### Rich text [Section titled “Rich text”](#rich-text) ```ts import { Layer, bold, color, mark, rich } from "framefields"; Layer.text( rich`Scale ${bold("10x", { fill: "#6366f1" })} faster with ${mark("120 FPS", { bg: "#10b98133" })}`, { fontFamily: "Inter", fontSize: 56, fill: "#f8fafc" }, ); ``` Span helpers: `span`, `bold`, `italic`, `color`, `mark`, `size`, `sub`, `sup`. A span takes `fontFamily`, `fontSize`, `fontWeight`, `fill`, `letterSpacing`, `baselineShift`, `opacity`. ### Measure with the real font [Section titled “Measure with the real font”](#measure-with-the-real-font) ```ts const m = FontManager.measure("Hello, world", { fontFamily: "Inter", fontSize: 64 }); m.width; m.height; m.lines; m.caretX(5); m.glyphs[0].x; // px, relative to the text box ``` Use it to place carets, underline a word, or size a pill to its label instead of guessing. ## Color helpers [Section titled “Color helpers”](#color-helpers) Every helper returns a hex string. ```ts import { Color } from "framefields"; Color.oklch(0.72, 0.16, 250); // equal L = equal perceived brightness Color.mix("#ff5a1f", "#1f6bff", 0.5); // perceptual (OKLab) mix Color.ramp(["#3b82f6", "#8b5cf6", "#ec4899"])(0.3); Color.steps(["#0e0d0c", "#ff5a1f"], 5); // 5 swatches Color.lighten(c, 0.1); Color.darken(c, 0.1); Color.alpha("#000", 0.4); Color.contrast(fg, bg); // WCAG ratio: ≥ 4.5 body, ≥ 3 large Color.readableOn(bg); // black or white, whichever reads ``` ## Gradients [Section titled “Gradients”](#gradients) CSS strings, usable in any `background` and any shape `fill`. Linear, radial and conic, up to 8 stops, hard stops allowed. ```ts import { Gradient } from "framefields"; Layer.box({ background: "linear-gradient(135deg, #ff5a1f, #ffb800 60%, #7c3aed)" }); Layer.shape("circle", { fill: Gradient.radial(["#fff", "transparent"]) }); Layer.box({ background: Gradient.conic(["red", "yellow", "lime", "aqua", "blue", "magenta", "red"]) }); ``` A gradient that doesn’t parse draws nothing; `comp.lint()` reports it as `invalid_gradient`. ## Track mattes [Section titled “Track mattes”](#track-mattes) `node.withMatte(matte, mode)` shows `node` only where the matte is opaque (`"alpha"`, default), transparent (`"alpha-inverted"`), bright (`"luma"`) or dark (`"luma-inverted"`). The matte is laid out like a sibling and is never drawn itself. ```ts // Text revealed by a sliding bar Layer.text("LAUNCH", { position: "absolute", x: 560, y: 480, width: 800, height: 120, fontSize: 120 }) .withMatte( Layer.box({ position: "absolute", x: 560, y: 480, width: 800, height: 120, background: "#fff" }) .animate(LayerAnimation.keys("x", [[0, -240], [24, 560, "expo.out"]])), ); // Video inside type Layer.video("assets/footage/surf.mp4", { position: "absolute", x: 0, y: 0, width: 1920, height: 1080, fit: "cover" }) .withMatte(Layer.text("OCEAN", { position: "absolute", x: 0, y: 340, width: 1920, fontSize: 380, align: "center", fill: "#fff" })); ``` # Physics & particles > Deterministic 2D and 3D rigid-body simulation with Rapier, live performer collision, force fields, and WebGPU compute particles. framefields includes deterministic rigid-body physics powered by Rapier (compiled to WebAssembly) and high-density GPU particle systems simulated in WebGPU compute shaders. Physics simulates while the composition is built (or steps frame-by-frame in live mode) and replays as per-frame signals. Frame order does not affect the outcome: frame 80 always renders identically on every machine. ## 2D rigid bodies [Section titled “2D rigid bodies”](#2d-rigid-bodies) ```ts import { Composition, Layer, LayerAnimation, Physics } from "framefields"; const W = 1920, H = 1080, FPS = 30; const comp = new Composition({ width: W, height: H, fps: FPS, durationFrames: 120, backgroundColor: "#0b0c10" }); const world = await Physics.world2d({ fps: FPS, frames: 120, gravity: 2400 }); world.walls({ width: W, height: H }); const cardLayer = Layer.box({ width: 320, height: 200, background: "#1f2937", borderRadius: 16, position: "absolute", x: W / 2 - 160, y: 100, }); const card = world.body(cardLayer, { restitution: 0.4, friction: 0.6 }); world.simulate(); // Flash on impact const flash = Layer.box({ width: W, height: H, background: "#ffffff", opacity: 0 }); flash.animate(LayerAnimation.create().signal("opacity", card.impact, { multiplier: 0.8 })); comp.add([flash, cardLayer]); ``` `world.body(target, options)` creates a body from any layer with an absolute position (`x`, `y`) and size, or from a plain rectangle `{ x, y, width, height }` (useful for invisible funnels and deflectors). `world.simulate()` runs the simulation once and automatically binds each body’s layer `x`, `y`, and `rotation` to the simulated signals. ### Collider shapes [Section titled “Collider shapes”](#collider-shapes) By default (`shape: "auto"`), the collider is inferred from the layer: | Layer type | Inferred collider | | ------------------------------------------- | --------------------------------------------- | | `Layer.shape("circle", ...)` | Circle | | `Layer.box` with `borderRadius` | Rounded box matching corner radius | | \`Layer.shape(“polygon” | “star” | | `Layer.text` without explicit size | Box measured automatically with `FontManager` | | `Layer.box` / `Layer.image` / `Layer.video` | Rectangular box | Force a specific shape with `shape: "box" | "circle" | "hull"` or override dimensions with `size: [width, height]`. ### Body options [Section titled “Body options”](#body-options) | Option | Type | Default | Description | | ----------------- | ----------------------- | ----------- | ---------------------------------------------------------------------- | | `type` | \`“dynamic” | “fixed” | “kinematic”\` | | `restitution` | `number` | `0.3` | Bounciness, 0–1 | | `friction` | `number` | `0.6` | Surface friction, 0–1 | | `density` | `number` | `1.0` | Mass per unit area. Heavier bodies push lighter ones | | `velocity` | `[vx, vy]` | `[0, 0]` | Initial launch velocity in px/s | | `angularVelocity` | `number` | `0` | Initial spin in degrees/second | | `linearDamping` | `number` | `0` | Air resistance per second | | `angularDamping` | `number` | `0` | Spin resistance per second | | `gravityScale` | `number` | `1.0` | Multiplier for world gravity (0 makes body float) | | `lockRotation` | `boolean` | `false` | Disables rotation so the body remains upright | | `ccd` | `boolean` | `false` | Continuous collision detection for thin, fast-moving bodies | | `sensor` | `boolean` | `false` | Passes through bodies without collision while still reporting contacts | | `startFrame` | `number` | `0` | Simulation frame the body wakes up; holds start pose before | | `follow` | `{ x?, y?, rotation? }` | — | Kinematic driver: position and rotation each frame | | `output` | \`“signals” | “keyframes” | “none”\` | ## Signals & reactions [Section titled “Signals & reactions”](#signals--reactions) Every body produces frame-rate signals sampled at composition time: ```ts card.x; // layer top-left X every frame card.y; // layer top-left Y every frame card.rotation; // continuous degrees (no 360 wrap jump) card.centerX; // body center X in px card.centerY; // body center Y in px card.vx; // velocity X in px/s card.vy; // velocity Y in px/s card.speed; // speed hypot(vx, vy) in px/s card.angularVelocity; // degrees/s card.sleeping; // 1 when settled, 0 when moving card.impact; // exponential decay envelope on collision ``` ### Impact & collisions [Section titled “Impact & collisions”](#impact--collisions) `body.impact` jumps whenever the body suffers a collision and decays over `impactDecay` frames (default 8 frames). A 1500 px/s change in velocity produces an impact level of 1.0. `world.impact` produces the loudest impact across all bodies on each frame — perfect for triggering camera shake, lens flares, or audio whooshes. `world.collisions` and `body.collisions` return an array of first contact events: ```ts for (const contact of world.collisions) { // contact: { frame, body, with, speed } console.log(`Hit at frame ${contact.frame} with speed ${contact.speed} px/s`); } ``` Use `world.collisions` to place impact sound effects (`renderSfx({ type: "impact", ... })`) or particle explosions precisely on contact frames. ## Bounds & joints [Section titled “Bounds & joints”](#bounds--joints) Create boundaries with built-in helpers: ```ts // Ground floor sitting at y: 1000 world.ground({ y: 1000, friction: 0.8, restitution: 0.2 }); // Surrounding walls around the canvas box world.walls({ width: 1920, height: 1080, thickness: 400, ceiling: true }); ``` Connect bodies with joints: ```ts // Pin to swing around a world point (default: body center) world.pin(signpost, [960, 200]); // Hinge two bodies together at a world pivot world.hinge(bodyA, bodyB, [pivotX, pivotY]); // Weld bodies rigidly together world.weld(bodyParent, bodyChild); // Damped spring between two bodies or body and point world.spring(pendulum, [960, 100], { frequency: 2, dampingRatio: 0.2, length: 300 }); // Distance rope (slack when closer, taut at max length) world.rope(weight, [960, 100], { length: 450 }); ``` ## Driving the simulation [Section titled “Driving the simulation”](#driving-the-simulation) Beyond gravity and collisions, worlds can be influenced by forces, impulses, and spatial fields: ```ts // Steady acceleration (px/s², mass-independent) world.force(balloon, { y: -1200 }); // buoyant lift // Signal-driven acceleration (e.g. wind gusts from audio) world.force(banner, { x: audioSignal }); // Instant velocity kick at a specific frame world.impulse(ball, 30, [400, -800]); // kick at frame 30 ``` ### Force fields [Section titled “Force fields”](#force-fields) `world.field(callback, options)` is called every solver step for each awake body. The callback receives a `FieldSample2D` (`{ x, y, vx, vy, frame, body }`) and returns an acceleration `[ax, ay]` in px/s²: ```ts // Radial vortex pulling bodies into center world.field((s) => { const dx = 960 - s.x; const dy = 540 - s.y; const dist = Math.hypot(dx, dy); if (dist < 50 || dist > 600) return null; const pull = 1500 / dist; // Tangential swirl + inward pull return [-dy * pull + (dx / dist) * 200, dx * pull + (dy / dist) * 200]; }); ``` ## 3D rigid bodies [Section titled “3D rigid bodies”](#3d-rigid-bodies) `Physics.world3d` simulates rigid bodies in 3D for `Layer3D` primitives (`roundedBox`, `sphere`, `cylinder`, `capsule`, `torus`, `ring`, `prism`, `pyramid`, `polyhedron`, `icosphere`, `shard`), extruded text, and 3D models (`Layer.glb`, convex hull): ```ts import { Layer3D, Physics } from "framefields"; const world = await Physics.world3d({ fps: 30, frames: 150, gravity: 2600 }); world.ground({ y: 1000 }); const box = Layer3D.roundedBox({ width: 240, height: 160, depth: 32, radius: 12, x: 960, y: 200, z: 0, material: "glass", }); const body = world.body(box, { restitution: 0.3, // Lock rotation to keep cards facing the camera while spinning in the image plane lockRotation: { x: true, y: true, z: false }, }); world.simulate(); ``` Without a camera layer, the 3D scene’s `z = 0` plane maps 1:1 onto canvas pixels. Points from 2D video tracks or layout line up directly in the 3D simulation. 3D bodies expose `x`, `y`, `z`, `rotateX`, `rotateY`, `rotateZ`, `vx`, `vy`, `vz`, `speed`, and `impact` signals. ## Live worlds & performers [Section titled “Live worlds & performers”](#live-worlds--performers) Normally, `world.simulate()` computes the entire timeline up front when the composition is constructed. When bodies interact with performers tracked via `comp.vision(clip)`, use **`world.live(comp)`** instead. Live mode advances the physics simulation frame-by-frame as each composition frame is requested: ```ts const comp = new Composition({ width: W, height: H, fps: 30, durationFrames: 180 }); const dancer = comp.vision("assets/dancer.mp4"); const person = dancer.person.place({ width: W, height: H, fit: "cover" }); const world = await Physics.world3d({ fps: 30, frames: 180, gravity: 2400 }); world.ground({ y: H }); // Kinematic sphere colliders following dancer's wrists world.body({ x: 0, y: 0, z: 0, width: 60, height: 60, depth: 60 }, { type: "kinematic", shape: "sphere", follow: { x: (f) => person.point("rightWrist", f).x, y: (f) => person.point("rightWrist", f).y, z: 0, }, }); // Live mode: steps as frames render; preview starts instantly without up-front delay world.live(comp); ``` ### Silhouette deflection [Section titled “Silhouette deflection”](#silhouette-deflection) The tracked performer’s silhouette can deflect rigid bodies using `person.sample(frame, x, y)`: ```ts world.field((s) => { const sample = person.sample(s.frame, s.x, s.y); if (sample.alpha <= 0.1) return null; // Push outwards along the negative normal gradient return [-sample.gx * 8000, -sample.gy * 8000]; }); ``` ## Keyframe baking [Section titled “Keyframe baking”](#keyframe-baking) To export plain keyframe animations (inspectable in JSON or usable without the live physics runtime), use `bakeKeyframes` instead of `simulate`: ```ts world.bakeKeyframes({ tolerance: 0.25 }); ``` This applies Ramer–Douglas–Peucker trajectory simplification across each channel, leaving the minimum linear keyframes that stay within `tolerance` pixels of the simulation. *** ## GPU Particles (`Layer.particles`) [Section titled “GPU Particles (Layer.particles)”](#gpu-particles-layerparticles) `Layer.particles` simulates tens of thousands of particles in a WebGPU compute shader and draws them in a single instanced render call. Positions inside the particle layer are local layer pixels. ```ts comp.add(Layer.particles({ width: W, height: H, max: 20000, seed: 42, emitter: { shape: "rect", x: 0, y: H * 0.6, width: W, height: 200, rate: 3000, }, lifetime: [4, 6], speed: [20, 80], direction: -90, spread: 180, gravity: 30, drag: 1.2, noise: { strength: 240, scale: 160, speed: 0.3 }, // divergence-free curl noise attractors: [{ x: W / 2, y: H / 2, strength: 1200, radius: 300 }], floor: H - 40, bounce: 0.3, size: [10, 2], sizeJitter: 0.4, shape: "soft", color: ["#ffdd00", "#ff5a1f", "#4a1205"], blend: "add", prewarm: 3, // starts already full })); ``` ### Dynamic particle drivers [Section titled “Dynamic particle drivers”](#dynamic-particle-drivers) Emitter position (`emitter.x`, `emitter.y`), emission `rate`, `gravity`, `drag`, `noise.strength`, attractor positions, and `push` forces can be driven by a static number, a signal, or a per-frame function `(frame: number) => number`. This allows responsive particle effects: * **Light painting**: Move a point emitter with a tracked hand `(f) => person.point("rightWrist", f).x`. Births automatically interpolate along the path between frames to avoid gaps. * **Audio bursts**: Modulate `emitter.rate` with an audio drum signal. * **Explosions**: Trigger instant bursts at specific frames with `emitter.bursts: [{ frame: 30, count: 5000 }]`. ### Performer interaction [Section titled “Performer interaction”](#performer-interaction) Connect particles directly to tracked performers using `push`: ```ts const dancer = comp.vision("assets/dancer.mp4"); const person = dancer.person.place({ width: W, height: H, fit: "cover" }); comp.add(Layer.particles({ width: W, height: H, push: { person, strength: 9000, sweep: 120000, // extra force imparted by fast-sweeping limbs }, // ... })); ``` Layer a video cutout of the same clip (`Layer.video(src).withVision({ mode: "matte" })`) above the particles so they appear behind the performer while being swept aside. ### Particle options reference [Section titled “Particle options reference”](#particle-options-reference) | Prop | Type | Default | Description | | ---------------- | ------------------------------------ | ------------- | ---------------------------------------------------------------------------- | | `max` | `number` | `20000` | Maximum particle capacity. Only uses GPU memory, no cost when idle | | `emitter.shape` | \`“rect” | “point” | “line” | | `emitter.rate` | `PhysicsDriver` | `1000` | Particles emitted per second | | `emitter.bursts` | `Array<{ frame, count }>` | `[]` | Instant particle bursts at specific frames | | `lifetime` | \`number | \[min, max]\` | `[2, 4]` | | `speed` | \`number | \[min, max]\` | `[40, 160]` | | `direction` | `number` | `-90` | Launch direction angle in degrees (0 = right, -90 = up) | | `spread` | `number` | `360` | Angular spread around direction in degrees | | `gravity` | \`PhysicsDriver | \[gx, gy]\` | `0` | | `drag` | `PhysicsDriver` | `0.4` | Velocity damping per second | | `noise` | `{ strength?, scale?, speed? }` | — | Curl noise flow for turbulent smoke and fluid drifts | | `attractors` | `Array<{ x, y, strength, radius? }>` | `[]` | Points that pull (positive strength) or repel (negative strength) | | `floor` | `number` | — | Floor line in layer px where particles bounce | | `bounce` | `number` | `0.3` | Bounciness at floor and bouncing bounds | | `bounds` | \`“none” | “kill” | “bounce” | | `shape` | \`“circle” | “soft” | “square” | | `blend` | \`“normal” | “add” | “screen”\` | | `color` | \`string | string\[]\` | `"#ffffff"` | | `colorBySpeed` | `number` | — | When set, maps color gradient according to speed (px/s to reach final color) | | `prewarm` | `number` | `0` | Seconds simulated before frame 0 so the scene starts in mid-flight | ## Reference example: Physics dancer [Section titled “Reference example: Physics dancer”](#reference-example-physics-dancer) The [`examples/28_physics_dancer`](https://github.com/gatewai-dev/framefields/tree/main/examples/28_physics_dancer) reference film demonstrates 3D rigid-body physics, live vision tracking, and GPU compute particles working together in a single shot: * **3D glass cards:** `Layer3D.roundedBox({ material: "glass" })` cards thrown in on ballistic arcs that bounce off the performer. * **Kinematic performer tracking:** Kinematic sphere colliders follow arm and head keypoints from `comp.vision(clip).person`. * **Performer particle push:** 24,000 embers simulated with `Layer.particles` that part around the dancer’s silk dress via `push: { person }`. * **Live execution:** `world.live(comp)` advances physics as each frame renders, starting the preview immediately. Watch the render on [YouTube](https://youtu.be/POC7rKnuoE4). # Live preview > Serve a localhost WebGPU player that runs the composition itself, with sound, scrubbing, deep links, scripting and notes pinned on the picture. `startPreview` serves a page that loads your composition’s module and renders it live with WebGPU in the browser — not a video stream. The server only hands over the bundle and your assets. The page mixes the soundtrack itself, with the export engine’s mixer, two seconds at a time around the playhead, so sound starts at once and an edit remixes only where you are. src/render.ts (preview mode) ```ts import { startPreview } from "framefields"; const session = await startPreview( { entry: new URL("./film.ts", import.meta.url), export: "buildFilm" }, { title: "Launch film" }, ); console.log(`Preview at ${session.url}`); await session.closed; // "idle" | "replaced" | "closed" process.exit(0); ``` `export` names a function returning the `Composition` (may be async) or a `Composition` itself. ## Options [Section titled “Options”](#options) | Option | Default | Notes | | ------------- | ---------------------------------- | ------------------------------------------------------------------------------------------- | | `port` | derived from the project directory | one stable URL per project; a new run replaces the old server and open tabs reload in place | | `host` | `127.0.0.1` | never leaves the machine | | `open` | `false` | open the system browser; otherwise show `session.url` where you are | | `title` | — | page header | | `audio` | `true` | mix and play the soundtrack | | `idleCloseMs` | `5000` | stop after the last tab closes; `false` keeps serving until `close()` | | `root` | project of the entry | extra folders the page may load assets from | | `log` | stderr | where page errors and lifecycle lines go; `false` silences | | `notesDir` | `.framefields/preview-notes` | `false` turns notes off | ## Assets must resolve in the browser [Section titled “Assets must resolve in the browser”](#assets-must-resolve-in-the-browser) The browser runs `film.ts` itself. Build asset paths from the module URL, not `process.cwd()`: ```ts import path from "node:path"; import { fileURLToPath } from "node:url"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const FONTS = path.resolve(HERE, "../assets/fonts"); ``` `node:path`, `fileURLToPath` and synchronous `fs` reads work through shims; writes are skipped. ## For agents [Section titled “For agents”](#for-agents) * Run the preview as a **background** command and read its output: it reports when the page opened, each distinct page error (build failure, a frame that threw, missing font, no WebGPU), and why it stopped. * After editing, run it again — same URL, and the open tab reloads at the same moment. * Deep link: `#t=12.5` (seconds) or `#frame=750`. * Script it: `window.framefieldsPreview` has `seek(seconds)`, `seekFrame(n)`, `play()`, `pause()`, `notes()`, `state()`. `seek` resolves once the frame is drawn — screenshot after it. `` marks the first drawn frame. ## Notes pinned on the picture [Section titled “Notes pinned on the picture”](#notes-pinned-on-the-picture) Paused, a person clicks a spot (or drags an area) and writes what should change. Each note is printed in the preview output and saved: ```plaintext .framefields/preview-notes/ notes.json [{ id, frame, time, x, y, w?, h?, text, done }] note-.jpg the frame with the spot marked ``` To act on notes: read `notes.json`, open each open note’s picture, find the layer from the moment and the spot, edit, rerun the preview. Set `"done": true` yourself or let the person tick them off. ## Playback [Section titled “Playback”](#playback) Play runs in real time on the soundtrack’s clock and skips frames a slow device can’t draw; the page shows the frame rate it reaches. The soundtrack is the export’s: the same decoders, audio effects and signals, mixed on the page’s GPU from the sources themselves (pinned [assets](/docs/guides/assets/) stream straight from their bucket). Blocks continue the effect state of the block before, so reverbs, delays and compressors carry over exactly: from the film’s start the soundtrack is sample for sample the export’s. After a seek, the first block starts its effects from two seconds earlier (close, not exact, for long echoes), and the background pass, which runs through the whole film in order, replaces those blocks with exact ones. It also draws the waveform and sets the export’s master gain once the loudest moment is known. The mixing runs in a background worker with its own GPU device, so it never holds up the picture. If the worker can’t mix (a codec only the page’s decoder handles), the page mixes, and if that fails too, the preview server mixes the whole soundtrack. Paused, it draws the exact frame. Requires WebGPU (current Chrome, Edge or Safari). # Render on a server > Render a framefields project straight from git on a GPU worker (Docker, RunPod pod or serverless). Project checklist, job JSON, outputs and error codes. The **renderer worker** renders a project from its git repo: it fetches a commit, pulls Git LFS assets and downloads the assets `framefields.json` pins on a bucket (cached by hash), installs dependencies, renders an exported composition on a warm GPU, checks the file with ffprobe and uploads it. It runs as a Docker container on any NVIDIA host, a RunPod pod or a RunPod serverless endpoint. Deploying it: [renderer-service README](https://github.com/gatewai-dev/framefields/tree/main/apps/renderer-service). The worker has no engine of its own. It renders with the `framefields` version in the project’s lockfile. Don’t want to run it yourself? [Cloud rendering](/docs/guides/cloud-rendering/) runs this worker for you on framefields GPUs: `npx framefields render film --cloud`. It plans, splits and bills the render, and uses the same project checklist and error codes as this page. ## Project checklist [Section titled “Project checklist”](#project-checklist) A project that follows [Getting started](/docs/getting-started/) already meets most of this. Check every line before submitting a job. | Rule | Why | Fails with | | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `framefields` is a dependency, version 2.2 or newer | 2.2 adds progress, cancel, warm workers and safe video encoders | `ENGINE_NOT_FOUND`; 2.1 renders but without those | | A lockfile is committed and matches `package.json`: `pnpm-lock.yaml`, `package-lock.json` or `yarn.lock` | the worker installs with `--frozen-lockfile` / `npm ci`. Bun lockfiles aren’t supported | `LOCKFILE_MISSING`, `INSTALL_FAILED` | | `packageManager` is pinned, e.g. `"pnpm@10.13.1"` | the worker installs with that exact version | install differences | | Install-script approvals are in `package.json` (only `skia-canvas`) | the worker runs the same install as you | `Cannot find module '.../skia.node'` | | The entry module only **builds** the film: `film.ts` exports `buildFilm`, and `render.ts` does the rendering | the worker imports the entry. Rendering or `process.exit()` at import time is rejected | `EXPORT_SIDE_EFFECT`, `EXPORT_NOT_FOUND` | | Every input file is under `assets/`, and either pinned with `framefields assets add` and on the bucket, or stored with Git LFS and pushed (`git lfs ls-files`) | the worker downloads pinned assets from their remote’s `publicUrl` (or the signed URL the job carries) and pulls LFS objects for the commit | `ASSET_NOT_UPLOADED`, `ASSET_PRIVATE`, `LFS_POINTER_UNRESOLVED`, `LFS_OBJECT_MISSING`, `ASSET_NOT_FOUND` | | Asset paths are built from `import.meta.url`, never `process.cwd()` | the worker’s working directory isn’t your project | `ASSET_NOT_FOUND` | | Nothing writes into `node_modules` while rendering | the worker shares `node_modules` files read-only between projects | a permission error (`EACCES`/`EPERM`) with a hint | | Everything is committed and pushed | the worker renders the pushed commit, not your working tree | stale output | ## What the export can return [Section titled “What the export can return”](#what-the-export-can-return) src/film.ts ```ts // One video export async function buildFilm(args?: { locale?: string }): Promise { … } // Several named outputs export const cuts = () => ({ main: buildFilm(), teaser: buildTeaser() }); // A plan, with settings per output export const deliverables = () => ({ outputs: [ { name: "film", composition: buildFilm() }, { name: "sheet", composition: buildFilm(), render: { kind: "frameGrid", grid: { step: 30 } } }, ], }); ``` This is the same `{ entry, export }` convention as [`startPreview`](/docs/guides/preview/). `target.args` is passed to a function export. `target.select` picks names from a record or plan. ## Submit a job [Section titled “Submit a job”](#submit-a-job) ```bash curl -s "$WORKER/v2/jobs" -H "authorization: Bearer $RENDERER_API_KEY" -H "content-type: application/json" -d '{ "version": 2, "source": { "repo": "https://github.com/acme/films.git", "ref": "main", "workdir": "videos/launch" }, "target": { "entry": "src/film.ts", "export": "buildFilm" }, "render": { "kind": "video", "codec": "h264", "quality": "high" }, "output": { "type": "s3", "key": "launch/{shortSha}/{name}.{ext}" } }' # → {"id":"…","status":"IN_QUEUE"} ``` | Call | Returns | | --------------------------- | ----------------------------------------------------------------------------- | | `GET /v2/jobs/` | status and result: output URLs or keys, the rendered commit SHA, timings, GPU | | `GET /v2/jobs//events` | live progress (Server-Sent Events) | | `POST /v2/jobs//cancel` | stops the render between frames | On **RunPod serverless**, send the same JSON as `{"input": …}` to `https://api.runpod.ai/v2//run`. Then poll `/status/`, which includes progress. Useful job fields: | Field | Use | | -------------------- | --------------------------------------------------------------------------------------------------- | | `source.ref` | branch, tag or commit SHA. The result reports the SHA it rendered | | `source.commit` | fail if the ref has moved past this commit | | `source.workdir` | the package folder, for a monorepo | | `source.lfs.include` | pull only the assets this render needs | | `source.assets` | signed GET URLs for assets pinned on private remotes, by sha256 (the CLI signs them with your keys) | | `render.kind` | `video` (`h264`, `vp9`, `vp8`, `gif`), `audio` (`aac`, `mp3`, `opus`), `frames`, `frameGrid`, `lut` | | `render.qa.failOn` | QA codes that fail the job (`QA_FAILED`). The outputs still upload | | `output.type` | `s3` (key template), `presigned` (one URL per output), `local`, `inline` (base64) | | `idempotencyKey` | a retry of the same commit returns the earlier upload | Key templates can use `{jobId}`, `{sha}`, `{shortSha}`, `{ref}`, `{date}`, `{name}`, `{index}` and `{ext}`. ## Errors [Section titled “Errors”](#errors) A failed job returns `{ code, message, phase, retryable, hint }`. When `retryable` is true, resubmit the same job. Otherwise, fix the cause first: | Code | Fix | | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | `LOCKFILE_MISSING`, `INSTALL_FAILED` | commit a lockfile that matches `package.json` | | `EXPORT_NOT_FOUND`, `EXPORT_INVALID`, `EXPORT_SIDE_EFFECT` | export a builder from the entry; render only in `render.ts` | | `LFS_POINTER_UNRESOLVED`, `ASSET_NOT_FOUND` | push the LFS object, or widen `source.lfs.include` | | `ASSET_NOT_UPLOADED`, `ASSET_HASH_MISMATCH` | `npx framefields assets push` from a machine with the right file | | `ASSET_PRIVATE`, `ASSET_FORBIDDEN` | give the remote a `publicUrl`, or pass signed URLs in `source.assets` (the CLI does) | | `ASSET_MANIFEST_INVALID` | fix `storage` or `assets` in `framefields.json`; `npx framefields assets status` shows the error | | `REPO_NOT_ALLOWED`, `GIT_AUTH_FAILED`, `REPO_NOT_FOUND` | the worker’s allowlist or git token doesn’t cover the repo | | `REF_NOT_FOUND`, `REF_AMBIGUOUS` | push the branch, or pass a SHA | | `ENGINE_SWITCH` (retryable) | the worker loaded another framefields version and restarts. Keep projects on one version per worker to avoid it | | `GPU_UNAVAILABLE` (retryable) | the host’s GPU isn’t usable for WebGPU. Another worker takes the retry | | `RENDER_TIMEOUT` | raise `timeoutSec`, or the endpoint’s execution timeout on RunPod | ## Hardware [Section titled “Hardware”](#hardware) * **Drawing frames.** Frames are drawn with WebGPU on Vulkan. The `FF_GPU` setting: `auto` uses the GPU, or the CPU (lavapipe, much slower) when there is no GPU; `require` refuses to run without a GPU (used by the RunPod templates); `cpu` always draws on the CPU. * **Vision.** Vision models run on the same GPU through WebGPU. The log line `[vision] Inference on the GPU (WebGPU)` confirms it. * **Video encoding.** framefields encodes with NVENC when it works and falls back to libx264/libx265/libvpx/SVT-AV1 otherwise. NVENC needs NVIDIA driver 610 or newer. A100 and H100 have no NVENC. * **Picking a GPU.** RTX/L4/L40S-class cards suit rendering. AI-training GPUs cost more and encode on the CPU. # Rendering > Lint, single frames, contact-sheet grids, pixel tests and MP4 export with built-in QA — in the order that wastes the least time. ## The ladder [Section titled “The ladder”](#the-ladder) | Step | Call | Cost | | ---- | --------------------------------------------------------------------------------- | ------------------- | | 1 | `tsc --noEmit`, `comp.lint()`, `CompositorProgramSchema.safeParse(comp.toSpec())` | no GPU, instant | | 2 | `comp.renderFrame({ frame })` | one frame | | 3 | `comp.renderFrameGrid({ frames })` | a handful of frames | | 4 | Vitest pixel probes | per test | | 5 | `comp.renderVideo({ outputPath, qa: true })` | the whole film | ## 1. Check without rendering [Section titled “1. Check without rendering”](#1-check-without-rendering) ```ts import { CompositorProgramSchema } from "framefields"; const parsed = CompositorProgramSchema.safeParse(comp.toSpec()); if (!parsed.success) throw new Error(JSON.stringify(parsed.error.format())); for (const d of comp.lint()) console.log(`${d.severity} ${d.code}: ${d.message}${d.layerId ? ` (${d.layerId})` : ""}`); ``` `lint()` finds what renders without error but not as intended: unparseable colors and gradients, low-contrast text, off-canvas layers, truncated animations, PBR props without an environment. Codes are in [QA codes](/docs/reference/qa-codes/). ## 2. One frame [Section titled “2. One frame”](#2-one-frame) ```ts import fs from "node:fs/promises"; import { HeadlessMediaRenderer } from "framefields"; const renderer = new HeadlessMediaRenderer(); // reuse across frames const png = await comp.renderFrame({ frame: 45, renderer }); // PNG Buffer await fs.writeFile("output/f0045.png", png); ``` Render the key moments — entrance, peak, exit — and look at them. ## 3. Contact sheet [Section titled “3. Contact sheet”](#3-contact-sheet) ```ts const grid = await comp.renderFrameGrid({ frames: [0, 6, 12, 18, 24, 30, 36, 42], // or startFrame / endFrame / stepFrames, or timesMs columns: 4, cellWidth: 480, // 120–960, default 320 showLabels: true, // frame + time badge per cell (default) outputPath: "output/intro-grid.png", // optional: also write it }); ``` A grid shows easing hitches, wrap jumps, wrong z-order and missing cuts in one image. Default cap is 64 frames (`maxFrames`, hard max 120). Not for vision layers — see [Vision](/docs/guides/vision/#timing-the-one-frame-delay). ## 4. Pixel tests [Section titled “4. Pixel tests”](#4-pixel-tests) src/film.test.ts ```ts import { describe, expect, it } from "vitest"; import { HeadlessMediaRenderer } from "framefields"; import { buildFilm } from "./film.js"; describe("hero", () => { it("draws the title by frame 30", async () => { const comp = await buildFilm(); const png = await comp.renderFrame({ frame: 30, renderer: new HeadlessMediaRenderer() }); expect(png.length).toBeGreaterThan(1000); // decode with skia-canvas and sample pixels at known coordinates }); }); ``` ## 5. Export [Section titled “5. Export”](#5-export) For a render named in `framefields.json`, the CLI does this step: `npx framefields render film` renders it on this machine with QA (and pulls pinned assets that are missing first), printing the report and failing when QA fails; `npx framefields render film --cloud` renders the same thing on framefields GPUs, to the same file. From code: ```ts import { formatQaReport } from "framefields"; const result = await comp.renderVideo({ outputPath: "output/film.mp4", quality: "high", // "very_low" | "low" | "high" | "very_high" (default) codec: "h264", // default, MP4; "vp9" | "vp8" → WebM concurrency: 4, qa: { targetLufs: -14 }, // or true }); console.log(formatQaReport(result.qa!)); if (!result.qa!.passed) process.exitCode = 1; process.exit(); ``` | Option | Notes | | --------------------- | --------------------------------------------------------------------------------------- | | `outputPath` | written there; `result.filePath` is the final path | | `quality` | bitrate preset | | `codec`, `audioCodec` | `h264` → MP4 + AAC; `vp9`/`vp8` → WebM + Opus; `aac`/`mp3`/`opus` alone → audio-only | | `concurrency` | frames rendered in parallel | | `ringCapacity` | GPU→encoder staging depth, 2–8 (or `FRAMEFIELDS_RING_CAPACITY`) | | `qa` | measure frames and audio as they encode; returns `result.qa` | | `renderer` | share a `HeadlessMediaRenderer` | | `onProgress` | `({ phase, frame, totalFrames }) => void`; `phase` is `"render"`, then `"audio"` (2.2+) | | `signal` | an `AbortSignal`; stops between frames, rejects with its reason, leaves no file (2.2+) | QA thresholds: `minBlackSec` (0.5), `minFrozenSec` (2), `minSilenceSec` (2), `silenceDbfs` (−60), `targetLufs`, `lufsTolerance` (1). `qa.passed` is false on any error or warning. `qa.audio.integratedLufs` is BS.1770 loudness (streaming normalizes to about −14). Always exit Native GPU and encoder threads keep Node alive. End every render script with `process.exit()`. ## 6. 3D models (glTF) [Section titled “6. 3D models (glTF)”](#6-3d-models-gltf) From 3.1, a frame’s 3D scene exports as [glTF 2.0](https://www.khronos.org/gltf/) binary (`.glb`). glTF is the standard interchange format for 3D: Blender, Maya, Houdini, Unreal, Unity, three.js and every glTF viewer open it. Use it to hand a sculpture or a whole set to a 3D artist, put it in a game engine, or show it on a web page. ```bash npx framefields render film --model --frame 120 # output/film.glb ``` ```ts const { filePath, meshes, triangles, skipped } = await comp.exportModel({ frame: 120, // or atMs outputPath: "output/set.glb", metersPerPixel: 0.01, // default: 100 px is a meter // camera: false, lights: false, maxTextureSize: 4096 }); for (const what of skipped) console.warn("not in the file:", what); process.exit(); ``` The file holds what that frame draws: * **Meshes** in their pose at that frame, with morph targets and skins applied. Sculptures (`Layer3D.sdf`, terrain, extruded text) are written as their triangles. * **Layers on 3D planes** become textured quads. * **Scattered and instanced meshes** become one node per instance, all sharing one mesh. * **Materials** are PBR metallic-roughness with their texture maps, plus the Khronos extensions for glass (transmission, IOR, volume), clearcoat, sheen, iridescence and anisotropy. * **The camera and the directional, point and spot lights** are included, so the file opens framed and lit as the render shows. Nodes are named after layer ids. y is up and units are meters, so a model standing in the scene stands in the file. Light strengths keep the engine’s scale: a directional light of `intensity: 1` imports into Blender as 1 W/m². `skipped` lists what the frame drew that glTF cannot carry: * text drawn on a 3D plane (`Layer3D.extrudedText` exports) * rect area lights * the environment’s floor (an endless plane of the environment, not a mesh) * rounded corners and borders of layers on planes * motion computed on the GPU (wind, audio deformation, crowds), which is written at rest A file is one frame with no animation tracks. To export several poses, export several frames. `--model` runs on this machine, not with `--cloud`. To load an export back into a composition, turn it back to pixels and y down: ```ts Layer.glb("output/set.glb", { scale: 100, rotateX: 180 }); ``` ## Inspect a file from elsewhere [Section titled “Inspect a file from elsewhere”](#inspect-a-file-from-elsewhere) ```bash ffprobe -v error -show_entries stream=codec_name,width,height,duration,r_frame_rate output/film.mp4 ffmpeg -i output/film.mp4 -vf "blackdetect=d=0.5:pix_th=0.10" -f null - ffmpeg -i output/film.mp4 -af volumedetect -f null - ``` ## Encoders and GPU [Section titled “Encoders and GPU”](#encoders-and-gpu) * **Video encoder.** framefields 2.2 tests the hardware encoder (NVENC, VideoToolbox) once per codec and uses it only if it works. Otherwise it encodes with libx264, libx265, libvpx or SVT-AV1. The log says which one it picked (`[video-encoders]`). Set `FRAMEFIELDS_HW_CODECS=off` to always encode in software. * **Adapter.** `await describeGpu()` returns `{ vendor, architecture, device, description, software }`. `software: true` means frames are drawn on the CPU (lavapipe, SwiftShader), which is much slower. ## Rendering without a GPU [Section titled “Rendering without a GPU”](#rendering-without-a-gpu) Without a GPU (such as in headless CI runners, Docker containers, or cloud sandboxes), framefields renders on the CPU via software rasterization. The engine detects this automatically, and `await describeGpu()` reports `software: true`: | Platform | CPU renderer | How to install / enable | | -------- | ------------------------------ | ----------------------------------------------------- | | Linux | Mesa lavapipe (Vulkan) | `apt-get install -y libvulkan1 mesa-vulkan-drivers` | | Windows | WARP (Direct3D 12) or lavapipe | Built into Windows (WARP); or via Vulkan Mesa drivers | | macOS | Not needed | Every Mac and macOS VM provides a native Metal GPU | On Linux with lavapipe, the output is pixel-accurate and matches a GPU render across every feature: layout, typography, SVG paths, Lottie, media, 2D VFX shaders, 3D scenes with shadows/bloom, and on-device vision. ### How slow is it? [Section titled “How slow is it?”](#how-slow-is-it) Rendering on CPU is functional but significantly slower than a hardware GPU: * **Measured benchmark:** In test suite benchmarks (three 720p test films with 3D elements and three vision layers), rendering on CPU via lavapipe took **9.7 minutes** compared to **49 seconds** on an Apple M1 Pro GPU (\~**12× slower**). * **Desktop GPU comparison:** Compared to modern discrete GPUs (e.g. NVIDIA RTX 3070/4090 or L4), CPU software rendering is typically **10× to 100× slower**, depending on shader complexity, screen resolution, and scene composition. * **CPU scaling:** Performance scales directly with CPU core count. Mesa lavapipe multithreads fragment rasterization across available CPU cores, and software video encoding (`libx264`) uses thread pools. ### Subsystem fallbacks on CPU [Section titled “Subsystem fallbacks on CPU”](#subsystem-fallbacks-on-cpu) When running without a hardware GPU, framefields optimizes each subsystem to avoid unnecessary bottlenecks: * **WebGPU pipelines (Dawn):** Dawn binds to Mesa’s Vulkan software ICD (`lvp_icd.*.json`). All WGSL shaders, blend passes, and 3D pipelines execute on CPU worker threads. * **Vision inference:** When `describeGpu()` detects a software adapter (`software: true`), the vision subsystem automatically routes ONNX inference to the native CPU provider (`onnxruntime-node`). This avoids the extreme performance penalty of executing deep neural networks through a software GPU rasterizer. * **Video encoding:** The renderer automatically falls back from hardware encoders (NVENC, VideoToolbox) to multi-threaded CPU software encoders (`libx264`, `libx265`, `libvpx`, `svtav1`). ### Recommended workflow on CPU [Section titled “Recommended workflow on CPU”](#recommended-workflow-on-cpu) Because full video rendering on CPU takes minutes instead of seconds: * **Use the ladder:** Always run `comp.lint()`, then verify with single frames (`renderFrame`) and contact sheet grids (`renderFrameGrid`). Catch layout and visual defects in seconds before committing to a full export. * **For production films:** Keep CPU rendering for headless testing, CI sanity checks, and single-frame probes. Offload full-length exports and batch renders to [cloud rendering](/docs/guides/cloud-rendering/) (`npx framefields render film --cloud`), a GPU machine, or your own [render worker](/docs/guides/render-service/). ## Production rendering [Section titled “Production rendering”](#production-rendering) Measured worker memory, vision included: about 0.5 GB on an Apple Silicon Mac, 2–3 GB on Linux with an NVIDIA GPU, where driver memory counts too. To render projects from git on framefields’ GPUs, use [cloud rendering](/docs/guides/cloud-rendering/); to run that on your own GPU machines, with progress, cancel and uploads to S3, use the [render worker](/docs/guides/render-service/). In your own long-lived process, call `resetRenderCaches()` between jobs: the next job may have different files at the same paths. # Scenes & transitions > Split a film into scene functions on a beat grid and join them with Layer.sequence and Transition. ## One function per scene [Section titled “One function per scene”](#one-function-per-scene) Each scene returns a full-frame box. Children key from the scene’s own frame 0. src/scenes/hero.ts ```ts import { Layer, LayerAnimation } from "framefields"; import { H, PAPER, SANS, W } from "../theme.js"; export function hero() { return Layer.box({ id: "hero", position: "absolute", x: 0, y: 0, width: W, height: H, background: "#000", children: [ Layer.text("Every frame is a function of its number.", { position: "absolute", x: 140, y: 420, width: W - 280, fontFamily: SANS, fontSize: 120, fontWeight: 800, fill: PAPER, }).animate(LayerAnimation.create().fadeIn(0, 18)), ], }); } ``` ## Join them: `Layer.sequence` [Section titled “Join them: Layer.sequence”](#join-them-layersequence) `Layer.sequence` places scenes end to end, overlaps each pair by its transition, and sets every scene’s `startFrame` / `durationFrames` for you. src/film.ts ```ts import { Composition, Layer, Transition } from "framefields"; import { beats, FPS, H, W } from "./theme.js"; import { features, hero, outro, proof } from "./scenes/index.js"; const film = Layer.sequence( [ { scene: hero(), duration: beats(8) }, { scene: features(), duration: beats(12), transition: Transition.push("left", 18) }, { scene: proof(), duration: beats(8), transition: Transition.wipe("right", 16) }, { scene: outro(), duration: beats(6), transition: Transition.iris(20) }, ], { width: W, height: H }, ); const comp = new Composition({ width: W, height: H, fps: FPS, durationMs: (film.totalFrames / FPS) * 1000, // the sequence knows its length }); comp.add(film); ``` `duration` includes the transition. A missing `transition` is a cut. ## Transitions [Section titled “Transitions”](#transitions) | Call | Look | Defaults | | --------------------------------------- | --------------------------------- | -------------------------- | | `Transition.cut()` | hard cut | — | | `Transition.crossfade(frames, ease)` | new scene fades in over the old | 15, `sine.inOut` | | `Transition.fadeThrough(frames, ease)` | dip to background and back | 20, `sine.inOut` | | `Transition.push(dir, frames, ease)` | new pushes old out | `left`, 18, `power3.inOut` | | `Transition.slide(dir, frames, ease)` | new slides over old, which dims | `left`, 18, `power3.out` | | `Transition.zoom(frames, ease)` | old grows and fades, new settles | 18, `power2.inOut` | | `Transition.whip(dir, frames)` | fast motion-blurred push | `left`, 10 | | `Transition.wipe(dir, frames, ease)` | hard edge sweeps across (matte) | `left`, 18, `power2.inOut` | | `Transition.iris(frames, { at, ease })` | circle opens from a point (matte) | 20, centre | `dir` is `"left" | "right" | "up" | "down"`. `at` is `[x, y]` as fractions of the frame. ## Carry elements across cuts [Section titled “Carry elements across cuts”](#carry-elements-across-cuts) A badge, card or cursor that crosses a scene boundary with continuous position and velocity hides the cut. Put the carrier outside the sequence, on the composition, with its own keyframes spanning both scenes. # Vision > On-device detection, segmentation, pose and mattes, and prompted SAM 2.1 / SAM 3 tracking of one person, several, or a whole group, as reactive signals — pin layers to subjects, cut them out, reframe, blur, and analyze clips. framefields runs ONNX vision models locally and exposes the results as signals that layers and effects consume like any other. Every model is pinned to an immutable revision, verified by size and SHA-256, and downloaded lazily on first use. The built-in models are Apache-2.0; prompted tracking (SAM) is an optional package, covered [below](#select-specific-objects-with-sam). ## Turn it on [Section titled “Turn it on”](#turn-it-on) ```ts // Whole composition → a reactive bundle const vision = comp.withVision({ enableDetection: true, // default enableSegmentation: true, enablePose: true, variant: "s", // "t" | "s" | "m" confidence: 0.35, // default 0.3 classes: ["person"], // COCO filter }); // One layer → render it through a mode Layer.video("assets/footage/dancer.mp4").withVision({ mode: "matte", enableSegmentation: true }); ``` | Option | Model | Gives you | | -------------------- | -------------------------- | ------------------------------------------------------------------- | | `enableDetection` | RTMDet-Ins | COCO-80 boxes, tracked over time → `vision.objects` | | `enableSegmentation` | RTMDet-Ins (same pass) | soft per-instance masks → `vision.masks`, `vision.segmentation` | | `enablePose` | RTMO | 17 COCO keypoints per person → `track.pose`, `vision.poseLandmarks` | | `enableMatte` | MediaPipe Selfie Segmenter | fast person alpha → `vision.segmentation.matte` | Layer modes: `passthrough`, `mask`, `matte`, `crop`, `skeleton`, `boxes`, `tracking`. For cutouts, `matteSource: "instance"` (default; any class, merges attached parts like a dress or instrument) or `"selfie"` (people filling the frame only, fastest). `classes` picks which instance is the subject, not which parts merge into it. COCO has no clothing class, so a flowing dress may come back as a “kite” or “umbrella” and still joins a `classes: ["person"]` cutout (2.2+). ## On-demand clip vision (`comp.vision`) [Section titled “On-demand clip vision (comp.vision)”](#on-demand-clip-vision-compvision) For physics, particle deflection, and interactive layout, `comp.vision(source, options)` analyzes the raw clip frames **on demand** before drawing a frame. Unlike render-time `withVision` (which analyzes a layer’s previous rendered frame with a one-frame delay), clip vision decodes the source directly and makes poses and silhouettes available synchronously to the current frame: ```ts const dancer = comp.vision("assets/footage/dancer.mp4", { pose: true, // 17 COCO keypoints (default true) mask: true, // soft silhouette including dress/held objects (default true) maskCell: 8, // grid cell size in source px (default 8) smoothing: 2, // keypoint temporal averaging in frames (default 2) }); // Map into composition coordinates const person = dancer.person.place({ width: 1920, height: 1080, fit: "cover" }); // 1. Read coordinates at any frame const hand = person.point("rightWrist", 45); // { x, y, visibility } // 2. Reactive signals for layers const badge = Layer.box({ width: 80, height: 80, background: "#ff5a1f" }); badge.animate(LayerAnimation.create() .signal("x", person.signals("nose").x) .signal("y", person.signals("nose").y)); // 3. Silhouette alpha & gradient (for physics deflection & particles) const sample = person.sample(45, 960, 540); // { alpha, gx, gy } ``` ### Select specific objects with SAM [Section titled “Select specific objects with SAM”](#select-specific-objects-with-sam) Next release Prompted SAM tracking is part of the next minor release. It is not included in `framefields@2.8.1`. Automatic detection picks “the largest person”. Use SAM when you need **a specific** person or object, a description instead of a click, several people, or a whole group, and want that selection followed through the video, including crowded shots. Three models run locally through `comp.vision`: | | SAM 2.1 Tiny (`sam2`) | SAM 2.1 Small (`sam2: { model: "small" }`) | SAM 3 (`sam3`) | | -------------------------- | --------------------- | ------------------------------------------ | -------------------------------------------------------- | | Select by | points and boxes | points and boxes | points, boxes, or **text** | | Objects per clip | 1 | 1 | 1, up to `maxObjects`, or a whole group as one (`merge`) | | Model input | 512² | 1024² (SAM 2’s native size) | 1008² | | Per frame, M1 Pro (WebGPU) | \~0.27 s | \~1.1 s | \~3.6 s image encoder + \~0.7 s per tracked object | | Download | \~83 MB | \~112 MB | \~1.75 GB on a GPU, \~1.2 GB on the CPU | | Weights license | Apache-2.0 | Apache-2.0 | Meta SAM License | #### Install and license [Section titled “Install and license”](#install-and-license) ```sh pnpm add @framefields/vision-sam ``` SAM ships in `@framefields/vision-sam`, an optional, Apache-2.0 peer of `framefields`. `framefields` loads it only when a clip uses `sam2` or `sam3`; without it, such a clip fails with an install message, and nothing else changes. No model weights ship in any package: they download on first use. SAM 2.1’s weights are Apache-2.0 and need no acceptance. SAM 3’s weights are under Meta’s SAM License: accept it on the clip with `acceptSamLicense: true` (or `acceptLicense: true` inside `sam3`), or set `FRAMEFIELDS_ACCEPT_SAM_LICENSE=1`, before SAM 3 downloads or runs. `Sam2Tracker` and `Sam3Tracker`, for driving SAM on your own pixel buffers, are exported from `@framefields/vision-sam`. #### One object with points or a box (SAM 2.1) [Section titled “One object with points or a box (SAM 2.1)”](#one-object-with-points-or-a-box-sam-21) ```ts import { Composition, Layer, LayerAnimation } from "framefields"; const comp = new Composition({ width: 1920, height: 1080, fps: 25, durationFrames: 750, backgroundColor: "#151a23", }); const subject = Layer.video("assets/source.mp4", { position: "absolute", x: 0, y: 0, width: 1920, height: 1080, fit: "contain", muted: false, }).withVision({ mode: "matte" }); comp.add(subject); const tracked = comp.vision(subject, { sam2: { model: "tiny", // or "small" for small, thin or detailed subjects category: "person", prompts: [{ frame: 0, points: [ { x: 0.25, y: 0.10, label: 2 }, // box top-left { x: 0.70, y: 0.95, label: 3 }, // box bottom-right { x: 0.48, y: 0.50, label: 1 }, // foreground point ], }], }, pose: true, // optional RTMO pass matched to the selected silhouette }); // Request the stable signal bundle before rendering. const target = tracked.signals.objects.get(1); comp.add(Layer.box({ position: "absolute", x: 0, y: 0, width: 1, height: 1, background: "transparent", borderColor: "#00ffc3", borderWidth: 3, }).animate(LayerAnimation.create() .signal("x", target.bounds.screenX) .signal("y", target.bounds.screenY) .signal("width", target.bounds.screenWidth) .signal("height", target.bounds.screenHeight) .signal("opacity", target.active))); ``` **Tiny or Small.** Tiny is the fastest by far and suits a subject that is large in frame: a close-up, a dancer, a speaker. On such a subject its masks match Small’s closely (IoU 0.98 on a close-up). Pick Small, at about 4× the cost, when the subject is small, thin or detailed (a ball, hands, a bike, hair, a distant runner), or when Tiny latches onto a look-alike after a cut. If unsure, prototype with Tiny on a short trimmed stretch and switch if edges, small parts or identity fail. #### By description, several objects, or a whole group (SAM 3) [Section titled “By description, several objects, or a whole group (SAM 3)”](#by-description-several-objects-or-a-whole-group-sam-3) ```ts // One person, by description const hero = comp.vision(subject, { acceptSamLicense: true, sam3: { category: "person", text: "man in white shirt" }, }); // Every member as its own track, 1…N by score const crowd = comp.vision("assets/source.mp4", { acceptSamLicense: true, sam3: { category: "person", text: "student in blazer", maxObjects: 5 }, }); crowd.signals.objects.get(2); // the second-best match // A whole group as ONE object: one mask, one memory const students = Layer.video("assets/source.mp4", { width: 1920, height: 1080, fit: "contain" }) .withVision({ mode: "matte" }); // cuts the whole group out as one entity comp.add(students); comp.vision(students, { acceptSamLicense: true, sam3: { category: "person", text: "students in black jackets", merge: true }, }); ``` **Read the request’s number first.** “The man in white” is one object. “The students” or “everyone in black jackets” is a group: use **one** clip with **one** prompt and `merge: true`. Never select a group one member at a time, or through several clips with overlapping prompts. That re-detects the same people as duplicate, overlapping masks, at many times the cost. Use `maxObjects` (without `merge`) only when each member needs its own box or ID. How the group modes cost: * **`merge`:** finds every match in one pass of the text model, combines the masks into one seed, and tracks it as one object. A whole crowd costs the same as one person. In the test below that was 4.1 s per frame on an M1 Pro. * **`maxObjects`:** gives each member its own memory, at about 0.7 s per member per frame. Grammatical number in the prompt does not matter. “students in black jackets” and “student in black jacket” selected the same group (87% of the frame either way). **Text prompts are concepts:** name what sets the target apart *in that shot*. In a crowd where every student shows a white collar, “man in white shirt” picks a student. In the same film’s wide shot, where only the main character has no blazer, it picks him. Check the first frame of every prompt. Two clips in one shot can claim the same person, so write prompts that exclude each other (“students in black jackets” left out the main character in a white shirt). With several tracks, one image-encoder pass per frame serves every track, and where tracks overlap the more confident one keeps the pixel. `signals.objects.get(k)` and `signals.masks` carry tracks `1…N`, and the clip’s matte is all tracks merged. A later text prompt re-selects every track (IDs renumber). A points prompt with `object: k` seeds or corrects only track `k`; the next unused ID adds a track. On a text prompt’s frame, each selected object outputs and remembers the selection mask itself, as SAM does. #### Prompts and corrections [Section titled “Prompts and corrections”](#prompts-and-corrections) Coordinates are normalized to the original source image: `(0, 0)` is top-left and `(1, 1)` is bottom-right. They are independent of the layer’s placement. | Label | Meaning | | -------- | -------------------------------------------------------- | | `1` | Include this foreground point | | `0` | Exclude this background point | | `2`, `3` | A box’s top-left and bottom-right corners, in that order | Prompt frames must be nonnegative, unique, increasing integers inside the source video. They use the **source analysis clock** (`fps` in clip-vision options, default composition FPS), before trimming, start offsets or time remapping. A prompt at a later source frame corrects the selection and becomes the new conditioning frame. Frames before the first prompt are empty and are not analysed. To track only a stretch of a long clip, trim the layer (and pass `trimStartSec` to clips created from a path) and prompt on the stretch’s first source frame. Re-prompt across cuts or when identity is lost: appearance tracking cannot guarantee re-identification after occlusion. SAM supplies masks, not skeletons. Pose is off in SAM mode; `pose: true` runs RTMO and associates its result with the selection. `tracked.person.place(...)` maps silhouette sampling and optional pose landmarks into a layer’s placement. The object/mask bundle in `tracked.signals` uses source geometry on the composition clock, so the bounding-box example above assumes a full-frame layer at source dimensions. #### Frame clocks, masks and limits [Section titled “Frame clocks, masks and limits”](#frame-clocks-masks-and-limits) * The first request runs inference from the earliest prompt through every required intervening source frame, in order, so seeking forward can take time. Reverse playback, holds and time remapping read the cached source-frame results. * Lower analysis FPS repeats the preceding analysis mask at intermediate playback frames. Default smoothing is zero in SAM mode; an absent object remains empty instead of inheriting another person’s mask. * A default `withVision({ mode: "matte" })` layer of the same source reuses the selection’s masks; with several SAM clips of one source, it links to the first one created. Preserve the source aspect ratio through matting and crop afterward. An explicit selection fails clearly if its mask cannot align, rather than switching to automatic detection. * Masks are binary object masks, not alpha matting: fine hair, thin objects and heavy occlusion can need corrections, SAM 2.1 Small, or a higher-detail workflow. * Full-resolution masks are kept as compressed history and decoded lazily for signals. Cache identity includes the source file, options, all prompts, the pinned model revisions and the SAM 3 encoder precision. `tracked.release()` frees inference sessions while leaving analyzed results readable; further uncached requests replay temporal memory. #### Models, backends and cost [Section titled “Models, backends and cost”](#models-backends-and-cost) All SAM assets download lazily into the normal model cache, verified by size and SHA-256; `modelsDir`, `baseUrl` and the vision provider settings apply. SAM 3 downloads only the image encoder its backend runs fastest: | Backend | SAM 3 image encoder | Why | | -------------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | WebGPU (Macs, the preview) | fp16, 935 MB | Measured on an M1 Pro for one 1008² frame: fp16 3.65 s, q4f16 4.43 s, q4 6.63 s, int8 140 s (its ops fall back to the CPU). 4-bit weights are dequantized before every matmul on WebGPU, so they save memory, not time. | | CUDA (Linux, NVIDIA) | fp16 | fp16 is what NVIDIA’s tensor cores are built for | | CPU | q4, 369 MB | CPUs have no fast fp16 path; about 9× slower than WebGPU, so a last resort | Override with `sam3: { precision: "fp16" | "q4f16" | "q4" }`. Every SAM 3 clip in a process shares one image encoder and reuses its result per frame, so a main character and a crowd from one source cost one encoder pass. Setup takes about 2 minutes on an M1 Pro: loading the models, then text selection on the prompt frame. After that, measured on an M1 Pro: 20 frames with 6 tracks took about 5 minutes, and a whole group with `merge` took 4.1 s per frame. Prototype prompts on a short trimmed stretch; results are cached, so re-rendering after changing layout, colours or effects skips SAM entirely. SAM runs in the [preview](/docs/guides/preview/) too, on the browser’s WebGPU, with models served from the local cache. For a clip outside the project, add its folder to `startPreview(…, { root: [process.cwd(), dir] })`. `pnpm --filter @framefields/vision-sam test:sam2` (Tiny and Small) and `test:sam3` in the engine repository run opt-in native-Dawn tests with real weights and a moving target plus distractor. ### Caching to disk [Section titled “Caching to disk”](#caching-to-disk) Results are cached on disk in `~/.cache/framefields/vision` (or `$FRAMEFIELDS_VISION_CACHE_DIR`) keyed by file size, modification time, and options. A second run, or a final render after a browser preview, reuses cached results for frames already analyzed. SAM masks are stored separately from silhouette/pose data; new uncached frames may require replaying temporal memory. ### Integration with physics and particles [Section titled “Integration with physics and particles”](#integration-with-physics-and-particles) * **Live physics worlds:** When used with `world.live(comp)`, the simulation advances frame-by-frame alongside vision preparation, so preview starts immediately without waiting to analyze the whole video first. * **GPU particles:** Pass `push: { person, strength, sweep }` to `Layer.particles` to have the performer push particles away from their moving silhouette. * **Initial layout:** Call `await dancer.ready(0)` up front if you need the initial pose at frame 0 to position elements before the animation starts. ## Pin, drive, cut out [Section titled “Pin, drive, cut out”](#pin-drive-cut-out) ```ts // Pin a label to the main subject Layer.text("SUBJECT 01", { fontSize: 40, fill: "#f8fafc" }).pinToObject(vision.objects.primary, { anchor: "topCenter", offsetY: -48, smoothFrames: 5, hideWhenLost: true, }); // Drive an effect from mask coverage Layer.box({ width: 1920, height: 1080, background: "#000" }) .withEffect(new Vignette({ strength: vision.segmentation.subject.coverage, radius: 0.9 })); // Editorial one-liners comp.addSubjectSandwich({ source: "assets/footage/dancer.mp4", behind: [headline], feather: 4, fit: "cover" }); // text behind subject comp.addSmartFraming({ source: "assets/footage/action.mp4", target: vision.objects.primary, targetAspect: 9 / 16, damping: 0.15 }); comp.addSubjectOutline(vision.segmentation.subject, { source: "assets/footage/character.mp4", color: "#ff5a1f", width: 6, blur: 12 }); layer.blurRegion(vision.objects.byCategory("person"), { strength: 30 }); // anonymize ``` Anchors: `center`, `topCenter`, `bottomCenter`, `topLeft`, `topRight`, `bottomLeft`, `bottomRight`, `centerLeft`, `centerRight`. `pinToLandmark(coord, { offsetX, offsetY })` pins to a pose keypoint. ## Signals you get [Section titled “Signals you get”](#signals-you-get) | Group | Highlights | | ---------------------- | ---------------------------------------------------------------------------- | | `objects` | `primary`, `get(trackId)`, `byCategory(cat, rank)`, `count`, `hasCategory` | | `objects.*.bounds` | `x`, `y`, `width`, `height`, `screenX/Y/Width/Height`, `area`, `aspectRatio` | | `objects.*.kinematics` | `vx`, `vy`, `speed`, `acceleration`, `headingDeg` | | `objects.*.pose` | 17 keypoints, `hasPose`, `wristSpeed`, `handRaised`, `bodyTiltAngle` | | `masks` | `subject`, `get(trackId)`, `count`; per mask `area`, `coverage`, `solidity` | | `segmentation` | `subject`, `humanSilhouette`, `instanceMasks`, `matte.coverage` | | `classes` | per class `count`, `maxConfidence`, `present` | `vision.summary(frame)` returns a deterministic, serializable snapshot — safe inside a frame hook. ## Analyze before authoring [Section titled “Analyze before authoring”](#analyze-before-authoring) ```ts const report = await comp.analyzeVisionSequence("assets/footage/street.mp4", { tasks: ["detect", "pose"], categories: ["person"] }); report.tracks; // [{ trackId, category, frames: [start, end], centerPath, … }] ``` A zod-serializable report of what is in the clip, without ffmpeg — use it to decide where to place things. ## Timing: rendered-frame and source-frame analysis [Section titled “Timing: rendered-frame and source-frame analysis”](#timing-rendered-frame-and-source-frame-analysis) Unlinked render-time `withVision` reads each layer’s **previous** rendered frame. Frame 0 has no results, and masks trail the plate by one frame. The following rules apply to that path: * `renderVideo` renders in order and handles this. * For stills, render at least two **consecutive** frames with the same `HeadlessMediaRenderer` and keep the last. * **Don’t verify vision with `renderFrameGrid`**: jumping between frames cuts out pixels from another frame and shows a ghosted double. `comp.vision` analyzes the source before the current frame draws. A linked clip matte, including SAM, uses that frame’s cached mask without the one-frame delay. A cached absent subject is authoritative and renders empty. ## GPU or CPU [Section titled “GPU or CPU”](#gpu-or-cpu) On framefields 2.2+, detection, segmentation and pose can run through WebGPU (`onnxruntime-web`, installed with framefields) on the renderer’s device. Inputs that are already GPU textures can stay on the GPU for preprocessing. The automatic provider picks its backend once per process, before any model downloads: on Linux with the NVIDIA driver loaded it tries CUDA first (`onnxruntime-node`, needs CUDA 12 and cuDNN 9), then WebGPU, then the CPU. Clip vision decodes each clip’s source separately; SAM’s video pipeline keeps its temporal memory in bounded host arrays. To require WebGPU and surface initialization failures, set `FRAMEFIELDS_VISION_PROVIDER=webgpu`. The log tells you which backend runs and, on a fallback, why: ```plaintext {"backend":"webgpu","sharedDevice":true,"msg":"[vision] Inference on the GPU (WebGPU)"} ``` | Env | Effect | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `FRAMEFIELDS_VISION_PROVIDER` | `auto` (default: CUDA first on Linux with the NVIDIA driver, then WebGPU, then CPU), `webgpu`, `cpu`, or `cuda` (Linux x64; needs CUDA 12 and cuDNN 9). A forced backend that fails throws instead of falling back | | `FRAMEFIELDS_VISION_THREADS` | CPU threads per model (default on Linux: the CPUs the process may use) | Measured on the GPU, three vision layers, 60 frames at 1280×720: about 17 s on an M1 Pro, about 7 s on an RTX 3070. ## Choosing settings [Section titled “Choosing settings”](#choosing-settings) | Task (on the CPU, per \~2K frame) | `t` | `s` | `m` | | --------------------------------- | ---------- | ---------- | ---------- | | detect + segment (one pass) | 150–300 ms | 200–340 ms | 420–700 ms | | pose | \~50 ms | \~120 ms | \~280 ms | | matte | \~20 ms | \~20 ms | \~20 ms | * Start with `"s"`; use `"m"` for fast motion or busy backgrounds. * Raise `confidence` to \~0.5 on stylized footage; restrict `classes` to stop the subject switching. * Garment drops out of a cutout → `variant: "m"` or `keyBackground: true`. Halo on dark backgrounds → lower `featherRadius` or raise `maskThreshold`. ## Models offline [Section titled “Models offline”](#models-offline) Models cache in `$FRAMEFIELDS_MODELS_DIR` (default `~/.cache/framefields/models`). For CI or air-gapped renders, preload once or point `FRAMEFIELDS_MODELS_BASE_URL` at a mirror. ```ts import { VisionRunner } from "@framefields/vision"; const runner = VisionRunner.create({ variant: "s" }); // zero I/O until used await runner.preload(["detect", "pose"]); // downloads + verifies SHA-256 (~380 MB for all models) runner.close(); ``` For SAM model assets without creating inference sessions (here SAM 2.1 Tiny; `SAM_MODELS` lists every SAM file with its URL, size and SHA-256): ```ts import { VisionModelStore } from "@framefields/vision"; import { ensureSamModelsRegistered, SAM_MODELS } from "@framefields/vision-sam"; ensureSamModelsRegistered(); const store = new VisionModelStore({ acceptLicense: true }); for (const model of SAM_MODELS) { if (model.key.startsWith("sam2.1-tiny-")) await store.ensure(model.key); } ``` # API index > Every public entry point of the framefields package on one page — what it is and where it is documented. Everything imports from `"framefields"`. Subpaths exist for smaller imports: `framefields/effects`, `framefields/audio`, `framefields/signals`, `framefields/renderer`, `framefields/fonts`, `framefields/preview`. Vision runs standalone from `@framefields/vision` (and `@framefields/vision/web` in browsers). ## Composition [Section titled “Composition”](#composition) `new Composition({ width, height, fps = 60, durationMs | durationFrames, backgroundColor = "#000000", fonts, antialias3d = true })` | Member | Returns | Guide | | ----------------------------------------------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------- | | `add(layer \| layer[], …)` | `this` | [Core concepts](/docs/core-concepts/) | | `addAudio(audioLayer)` | `this` | [Audio](/docs/guides/audio-and-signals/) | | `addSignal(name, signal)` | `this` | [Signals](/docs/guides/audio-and-signals/#shared-signals-by-name) | | `apply(effect)` | `this` | [Effects](/docs/guides/effects/) | | `section({ source, x, y, width, height, borderRadius, effects })` | node | [Effects](/docs/guides/effects/#where-to-attach) | | `withVision(options)` | vision bundle | [Vision](/docs/guides/vision/) | | `vision(source, options)` | on-demand clip vision | [Vision](/docs/guides/vision/#on-demand-clip-vision-compvision) | | `onPrepareFrame(cb)` | async per-frame hook | [Physics](/docs/guides/physics/#live-worlds--performers) | | `addSubjectSandwich` / `addSmartFraming` / `addSubjectOutline` | `this` | [Vision](/docs/guides/vision/#pin-drive-cut-out) | | `analyzeVisionSequence(src, { tasks, categories })` | report | [Vision](/docs/guides/vision/#analyze-before-authoring) | | `registerFont(…)` / `registerEmojiFont(src)` | `this` | [Text](/docs/guides/layout-and-text/#fonts) | | `computeDuration()` | ms | — | | `lint()` | `{ severity, code, message, layerId }[]` | [QA codes](/docs/reference/qa-codes/) | | `toSpec()` | program JSON | [Rendering](/docs/guides/rendering/#1-check-without-rendering) | | `renderFrame({ frame, renderer })` | PNG `Buffer` | [Rendering](/docs/guides/rendering/) | | `renderFrameGrid(options)` | PNG `Buffer` | [Rendering](/docs/guides/rendering/#3-contact-sheet) | | `renderVideo(options)` | `{ filePath, cleanup, qa? }` | [Rendering](/docs/guides/rendering/#5-export) | | `exportModel({ frame, outputPath })` | `{ glb, filePath, meshes, triangles, skipped }` (3.1+) | [Rendering](/docs/guides/rendering/#6-3d-models-gltf) | | `onRequestFrame(ctx => …)` | `this` | per-frame hook | ## Layer builders [Section titled “Layer builders”](#layer-builders) | Builder | Kind | | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `Layer.box(opts)`, `Layer.flex(opts)` | containers | | `Layer.text(content \| spans, opts)` | GPU text | | `Layer.shape(type, opts)` | `rect` `circle` `ellipse` `polygon` `star` `arrow` `path` | | `Layer.video` `image` `svg` `lottie` `audio` `caption` `(src, opts)` | media | | `Layer.chart(options, boxProps)` | charts | | `Layer.particles(opts)` | GPU compute particles | | `Layer.sequence(entries, opts)` | scenes + transitions; has `totalFrames` | | `Layer.section(source, target?, opts)`, `Layer.trackedRegion`, `Layer.blurTrackedRegion` | regions | | `Layer.camera(opts)` | 3D camera | | `Layer.environment(preset, opts)` | PBR world; `pathTrace` traces its 3D layers (from 3.0.1, see [3D](/docs/guides/3d/#path-tracing)) | | `Layer.light`, `ambientLight`, `directionalLight`, `pointLight`, `spotLight` | lights | | `Layer.model(opts)`, `glb` `gltf` `obj` `fbx` `stl` `ply` `vox` `threeDS` `off` `(src, opts)` | models | | `Layer.cube` `carousel3d` `plane3d` `prism3d` | 3D layout (also on `Layer3D`) | ## Node methods [Section titled “Node methods”](#node-methods) Every builder’s result has: | Method | Does | | ---------------------------------------------------------------------------------------- | -------------------------------------------- | | `.animate(...animations)` | add keyframes/drivers (merges with existing) | | `.withEffect(fx)` / `.withEffects([...])` / `.apply(fx)` | effects | | `.withMatte(layer, mode)` / `.withMask(layer, mode)` | track mattes | | `.withCrop(crop)` | crop | | `.withVision(opts)` | per-layer vision mode | | `.pinToObject(track, opts)` / `.pinToLandmark(coord, opts)` | follow vision | | `.blurRegion(track, opts)` | blur a tracked object | | `.relight(opts)`, `.withDeflicker(opts)`, `.withPbrGlass(opts)`, `.deformWithAudio(cfg)` | specialised passes | ## Physics & particles [Section titled “Physics & particles”](#physics--particles) | Export | Members / Notes | Guide | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | `Physics` | `world2d(opts)`, `world3d(opts)` | [Physics](/docs/guides/physics/) | | `PhysicsWorld2D` | `body`, `ground`, `walls`, `pin`, `hinge`, `weld`, `spring`, `rope`, `force`, `field`, `impulse`, `simulate`, `bakeKeyframes`, `live` | [Physics](/docs/guides/physics/#2d-rigid-bodies) | | `PhysicsWorld3D` | `body`, `ground`, `walls`, `pin`, `hinge`, `weld`, `spring`, `rope`, `force`, `field`, `impulse`, `simulate`, `bakeKeyframes`, `live` | [Physics](/docs/guides/physics/#3d-rigid-bodies) | | `PhysicsBody2D / 3D` | `x`, `y`, `z`, `rotation`, `speed`, `vx`, `vy`, `vz`, `impact`, `collisions`, `center`, `localAnchor` | [Physics](/docs/guides/physics/#signals--reactions) | | `Layer.particles` | GPU compute-shader particles (emitters, noise, attractors, performer push) | [Particles](/docs/guides/physics/#gpu-particles-layerparticles) | ## 3D [Section titled “3D”](#3d) | Export | Members | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Layer3D` | `roundedBox` `sphere` `cylinder` `capsule` `torus` `ring` `prism` `pyramid` `polyhedron` `icosahedron` `icosphere` `shard` `extrude` `lathe` `tube` `line` `points` `cube` `carousel` `plane` `grid` `text` `extrudedText` `model` + model loaders | | `Light` | `ambient(color, intensity)` `directional` `point` `spot` `environment` | | `Lighting` | `studio` `soft` `sunset` `dramatic` `(rigOptions)` → array of layers | | `CameraAnimation.camera()` | `orbit` `dolly` `truck` `pedestal` `pan` `tilt` `roll` `rackFocus` `handheld` | ## Animation [Section titled “Animation”](#animation) | Export | Members | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `LayerAnimation` | `create()`, `fromTo`, `keys`, `fadeIn`, `fadeOut`, `slideInX`, `slideInY`, `rotateX/Y/Z`, `translateZ`, `perspective`, `letterSpacing`, `typewriter`, `kineticSweep`, `wiggle`, `spring`, `signal`, `colorSignal`, `followPath`, `merge` | | `TextAnimator` | `waveRise` `wordPop` `blurIn` `flip3D` `colorSweep` | | `Transition` | `cut` `crossfade` `fadeThrough` `push` `slide` `zoom` `whip` `wipe` `iris` | ## Signals [Section titled “Signals”](#signals) `Signal.builder`, `Signal.sine`, `Signal.cosine`, `Signal.fromArray`, `Signal.programmatic`, `Signal.state`, `Signal.computed`, `Signal.frame`, `Signal.time`, `Signal.progress`; also `sineSignal`, `cosineSignal`, `computed`. ## Text, color, fonts [Section titled “Text, color, fonts”](#text-color-fonts) | Export | Members | | ------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `FontManager` | `register({ family, source, weight, style })`, `registerEmojiFont`, `measure(text, opts)`, `get`, `has`, `getAll`, `clear` | | rich text | `rich` tagged template, `span`, `bold`, `italic`, `color`, `mark`, `size`, `sub`, `sup`, `parseMarkup` | | `Color` | `parse` `hex` `rgb` `hsl` `oklch` `mix` `ramp` `steps` `lighten` `darken` `saturate` `rotate` `alpha` `contrast` `readableOn` | | `Gradient` | `linear(stops, angle)` `radial(stops, { at, circle, radius })` `conic(stops)` | ## Audio [Section titled “Audio”](#audio) `renderSfx(trigger, ctx)`, `mixSfxInto(bed, sfx[])`, `softLimit(bed, knee?, ceiling?)`, `encodeStereoWav(channels, { sampleRate })`, `mixAudioTracks(...)`. ## Rendering & media [Section titled “Rendering & media”](#rendering--media) | Export | Notes | | -------------------------------------- | -------------------------------------------------------------------------------- | | `HeadlessMediaRenderer` | share one across `renderFrame` calls | | `Media.video` `image` `lottie` `audio` | single-clip chains with `apply`, `renderFrame`, `renderFrameGrid`, `renderVideo` | | `startPreview(entry, options)` | `{ url, close(), closed }` — [Preview](/docs/guides/preview/) | | `formatQaReport(qa)` | human-readable QA | | `CompositorProgramSchema` | zod schema of `toSpec()` | ## Effects [Section titled “Effects”](#effects) 54 classes, e.g. `Blur`, `Curves`, `FilmGrain`, `Vignette`, `ColorKey`, `ApplyLUT`, plus `Effect.(props)` factories. See the [Effects reference](/docs/reference/effects/). # Effects reference > All 54 effect classes grouped by family, with every prop name. Import from "framefields" or "framefields/effects". ```ts import { Blur, Curves, FilmGrain } from "framefields"; // same classes: import { … } from "framefields/effects"; // factory form: Effect.blur({ strength: 9 }) ``` Attach with `layer.withEffect(fx)`, `layer.withEffects([...])`, `comp.apply(fx)`, `comp.section({ effects })` or `Media.apply(fx)` — see [Effects](/docs/guides/effects/). Every prop is an `EffectProp`: a plain value, a signal, or a function hook. Out-of-range values warn; `FRAMEFIELDS_STRICT_PROPS=1` makes them throw. Types, ranges and defaults for every prop are in the generated [effect catalog](https://github.com/gatewai-dev/framefields/blob/main/plugins/framefields/skills/framefields-effects/references/effects-catalog.md). Scales Many strengths are **0–100**: `Vignette.strength` (default 50), `FilmGrain.strength` (15), `Blur.strength` (5). `ColorBalance` shifts are −100…100. Normalized positions and region radii (`centerX`, `centerY`, `radius`) are 0–1. ## Grading [Section titled “Grading”](#grading) | Effect | Props | | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `Curves` | `curveType`, `master`, `red`, `green`, `blue`, `hueVsHue`, `hueVsSat`, `lumVsSat`, `satVsSat` | | `Levels` | `master`, `red`, `green`, `blue` | | `ColorBalance` | `shadows`, `midtones`, `highlights`, `preserveLuminosity` | | `SelectiveColor` | `method`, `reds`, `yellows`, `greens`, `cyans`, `blues`, `magentas`, `whites`, `neutrals`, `blacks` | | `GradientMap` | `stops`, `smooth`, `dither`, `opacity` | | `ShadowsHighlights` | `shadowAmount`, `shadowTonalWidth`, `shadowRadius`, `highlightAmount`, `highlightTonalWidth`, `highlightRadius`, `colorCorrection`, `midtoneContrast` | | `ApplyLUT` | `lutUrl`, `intensity` | | `ExtractLUT` | `strategy`, `samplePoints` | | `Modulate` | `hue`, `brightness`, `contrast`, `exposure`, `saturation`, `sepia` | | `ChannelSplitter` | `colorSpace` | | `ChannelMerger` | `colorSpace`, `defaultChannel4` | ## Texture & lens [Section titled “Texture & lens”](#texture--lens) | Effect | Props | | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `FilmGrain` | `strength`, `size`, `monochrome`, `animated`, `speed`, `shadows`, `midtones`, `highlights` | | `Vignette` | `strength`, `radius`, `softness`, `roundness`, `centerX`, `centerY` | | `Blur` | `blurType`, `strength`, `angle`, `sigmaColor`, `centerX`, `centerY`, `partialBlur`, `radius`, `radiusY`, `shape`, `track` | | `MotionBlur` | `shutterAngle`, `samples`, `maxVelocity`, `shutterCurve`, `depthAware` | | `UnsharpMask` | `amount`, `radius`, `threshold` | | `HighPass` | `radius`, `contrastBoost`, `monochrome` | | `HalftoneScreen` | `mode`, `dotShape`, `frequency`, `angle`, `contrast`, `dotColor`, `paperColor`, `smooth`, `invert`, `cyanAngle`, `magentaAngle`, `yellowAngle`, `blackAngle`, `opacity` | | `TileOffset` | `offsetX`, `offsetY`, `wrap`, `edgeMode` | | `TemporalDeflicker` | `blendWeight`, `disocclusionThreshold`, `maxMotionPixels`, `scale`, `windowSize` | ## Distortion & framing [Section titled “Distortion & framing”](#distortion--framing) | Effect | Props | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `DisplacementMap` | `strengthX`, `strengthY`, `xChannel`, `yChannel`, `wrapMode` | | `Liquify` | `operations` | | `MeshWarp` | `cols`, `rows`, `points` | | `CornerPin` | `points` | | `Rotate` | `angle`, `fit`, `scale` | | `Flip` | `horizontal`, `vertical`, `diagonal`, `mode`, `symmetry` | | `KenBurns` | `keyframes`, `motionBlurSize`, `movementStyle`, `aspectRatio` | | `ResizerScaler` | `aspectRatioPreset`, `resolutionPreset`, `targetWidth`, `targetHeight`, `fitMode`, `zoom`, `offsetX`, `offsetY`, `backgroundMode`, `backgroundColor`, `backgroundColor2`, `blurRadius`, `backgroundBrightness`, `anchorX`, `anchorY` | | `Crop` | `cropType`, `leftPercentage`, `topPercentage`, `widthPercentage`, `heightPercentage`, `roundness`, `pathPoints`, `mode` | ## Temporal [Section titled “Temporal”](#temporal) | Effect | Props | | ---------- | ------------------------------------------------------------------------------- | | `Trails` | `decay`, `mode`, `zoom`, `rotation`, `offsetX`, `offsetY`, `hueShift`, `warmup` | | `Datamosh` | `keyframes`, `strength`, `bleed`, `warmup` | ## 3D & light [Section titled “3D & light”](#3d--light) | Effect | Props | | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Relight3D` | `lightType`, `intensity`, `lightPosX`, `lightPosY`, `lightPosZ`, `lightRadius`, `spotConeAngle`, `specularRoughness`, `specularStrength`, `metallic`, `ambientIntensity`, `volumetricDensity`, `depthScale`, `depthInvert`, `lightColor`, `ambientColor`, `normalMap` | | `SSAO` | `radius`, `bias`, `intensity`, `kernelSamples`, `blurRadius` | | `PBRGlass` | `ior`, `roughness`, `transmission`, `dispersion`, `fresnelPower`, `tintColor` | | `DepthOfField` | `focusDistance`, `focalLength`, `aperture`, `maxBlur`, `quality` | | `RefractionCaustics3D` | `ior`, `dispersion`, `refractionScale`, `causticBrightness`, `causticScale`, `fluidRipples`, `rippleSpeed`, `roughness`, `specularIntensity`, `lightPosX`, `lightPosY`, `tintColor`, `tintStrength`, `depthInvert`, `depthScale` | | `CameraParallax3D` | `motionPreset`, `panX`, `panY`, `dollyZ`, `fov`, `parallaxAmount`, `dofAperture`, `focusPlane`, `edgeDilation`, `depthInvert` | ## Mattes & keying [Section titled “Mattes & keying”](#mattes--keying) | Effect | Props | | ------------ | ------------------------------------------------------------------------------------------------------------------------------ | | `ColorKey` | `keyColor`, `similarity`, `smoothness`, `spillSuppression`, `colorSpace`, `spillSuppressionType` | | `RefineEdge` | `decontaminateAmount`, `radius`, `smooth`, `feather`, `shiftEdge`, `matteChannel`, `outputMode` | | `MaskMath` | `operation`, `radius`, `threshold`, `clampMin`, `clampMax`, `channelA`, `channelB`, `binarize`, `invertResult`, `outputFormat` | | `PatchHeal` | `patches`, `centerX`, `centerY`, `offsetX`, `offsetY`, `radius`, `sourceRadius`, `feather`, `opacity`, `mode` | ## Generators & style [Section titled “Generators & style”](#generators--style) | Effect | Props | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `NoiseGenerator` | `noiseType`, `outputType`, `width`, `height`, `scale`, `octaves`, `persistence`, `lacunarity`, `speed`, `colorStart`, `colorEnd`, `durationMs`, `fps` | | `ProceduralVFX` | `effectType`, `outputType`, `width`, `height`, `density`, `scale`, `speed`, `intensity`, `seed`, `colorStart`, `colorEnd`, `durationMs`, `fps` | | `Paint` | `width`, `height`, `maintainAspect`, `aspectRatio`, `backgroundColor`, `strokes` | | `LayerStyle` | `dropShadow`, `innerShadow`, `outerGlow`, `innerGlow`, `stroke`, `bevelEmboss`, `colorOverlay` | ## Audio [Section titled “Audio”](#audio) | Effect | Props | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `AudioFade` | `fadeInDuration`, `fadeOutDuration`, `fadeInCurve`, `fadeOutCurve` | | `AudioCompressor` | `threshold`, `ratio`, `attack`, `release`, `knee`, `makeupGain` | | `AudioParametricEq` | `type`, `frequency`, `gain`, `q` | | `AudioReverb` | `roomSize`, `damping`, `wet`, `dry`, `width` | | `AudioDelay` | `delayTime`, `feedback`, `wet`, `dry`, `pingPong` | | `AudioNoiseGate` | `threshold`, `attack`, `hold`, `release`, `range` | | `StereoPanning` | `pan` | | `AudioSignalExtractor` | `extractionMode`, `attackMs`, `releaseMs`, `sensitivity`, `noiseFloorDb`, `dynamicRangeDb`, `autoRange`, `smoothing`, `curve`, `beatThreshold`, `beatDecayMs`, `previewMode`, `nodeId` | ## Vision [Section titled “Vision”](#vision) | Effect | Props | | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Vision` | `enableDetection`, `enableSegmentation`, `enablePose`, `enableMatte`, `classes`, `confidence`, `variant`, `mode`, `matteSource`, `maxMissedFrames`, `modelsDir`, `baseUrl`, `maskThreshold`, `featherRadius`, `keyBackground`, `backgroundKeyThreshold`, `visionBundle` | ## Recipes [Section titled “Recipes”](#recipes) ```ts // Warm filmic grade for a whole film comp.apply(new ColorBalance({ shadows: { cyanRed: 4, yellowBlue: -6 }, highlights: { cyanRed: 2, yellowBlue: -4 } })); comp.apply(new Vignette({ strength: 30, radius: 0.9, softness: 0.65 })); comp.apply(new FilmGrain({ strength: 12, size: 1.5, animated: true })); // Greenscreen key Layer.video("assets/footage/green.mp4").withEffect(new ColorKey({ keyColor: "#00ff00", similarity: 0.4, smoothness: 0.1, spillSuppression: 0.3 })); // Print look layer.withEffect(new HalftoneScreen({ mode: "CMYK", dotShape: "Circle", frequency: 30 })); // Duotone layer.withEffect(new GradientMap({ stops: [{ position: 0, color: "#0e0d0c" }, { position: 1, color: "#ff5a1f" }] })); // Audio clean-up Layer.audio("assets/audio/vo.wav", { durationFrames }).apply(new AudioNoiseGate({ threshold: -45 })).apply(new AudioCompressor({ threshold: -18, ratio: 3 })); ``` # Lint & QA codes > Every code comp.lint() and renderVideo({ qa }) can report, its severity, and what to do about it. `comp.lint()` returns document findings before rendering. `renderVideo({ qa })` returns the same document findings plus measurements of the encoded frames and audio, in `result.qa.issues`. Each issue is `{ severity, code, message, layerId?, startSec?, endSec? }`. `qa.passed` is false if any **error** or **warning** is present. ## Document checks (lint and QA) [Section titled “Document checks (lint and QA)”](#document-checks-lint-and-qa) | Code | Severity | Means | Fix | | -------------------------- | -------- | ----------------------------------------------------------- | ------------------------------------------------------------- | | `invalid_gradient` | error | a `background`/`fill` gradient doesn’t parse; draws nothing | check the CSS syntax, ≤ 8 stops | | `unsupported_image_format` | error | `Layer.image` given `.json`/`.lottie`, video or audio | use `Layer.lottie` / `Layer.video` / `Layer.audio` | | `unknown_color` | warning | a color string that isn’t a color; draws transparent | use hex, `rgb()`, `hsl()`, `oklch()` or a CSS name | | `low_contrast_text` | warning | text below 3:1 against the solid color behind it | use the suggested color, or `Color.readableOn(bg)` | | `offscreen_layer` | warning | a static absolute layer entirely outside the canvas | fix `x`/`y` or remove it | | `animation_truncated` | warning | keyframes past the layer’s `durationFrames` never play | extend the layer or move the keys | | `shadow_unsupported_light` | warning | `castShadow` on a point or ambient light | use a directional or spot light | | `path_trace_screen_space` | error | `pathTrace` together with `ssr` or `gi` | drop `ssr`/`gi`: the tracer reflects and bounces light itself | | `path_trace_unsupported` | error | `pathTrace` together with `outlines` or `volumetricFog` | drop one of them | | `path_trace_cube_camera` | error | `pathTrace` with a 360° or fisheye camera | use a perspective camera for traced scenes | | `pbr_without_environment` | info | `roughness`/`metallic` set without `Layer.environment()` | add an environment or a `Lighting` rig | | `multiple_shadow_lights` | info | several `castShadow` lights; only the first casts | keep one | | `static_track` | info | every keyframe on a track holds the same value | remove the track or fix the values | ## Render measurements (QA only) [Section titled “Render measurements (QA only)”](#render-measurements-qa-only) | Code | Severity | Means | | --------------------- | -------- | ---------------------------------------------------------------------- | | `frames_missing` | error | fewer frames encoded than the composition has | | `black_frames` | warning | ≥ `minBlackSec` (0.5 s) of black; has `startSec`/`endSec` | | `audio_clipping` | warning | samples at or beyond full scale | | `loudness_off_target` | warning | integrated loudness more than `lufsTolerance` (1 LU) from `targetLufs` | | `frozen_video` | info | picture unchanged ≥ `minFrozenSec` (2 s); fine for a held title | | `audio_silence` | info | ≥ `minSilenceSec` (2 s) below `silenceDbfs` (−60) | | `audio_silent` | info | the whole track is silent | ## Use in CI or an agent loop [Section titled “Use in CI or an agent loop”](#use-in-ci-or-an-agent-loop) ```ts const result = await comp.renderVideo({ outputPath: "output/film.mp4", qa: { targetLufs: -14 } }); const blocking = result.qa!.issues.filter((i) => i.severity !== "info"); for (const i of blocking) console.error(`${i.code}${i.layerId ? ` [${i.layerId}]` : ""}: ${i.message}`); process.exit(result.qa!.passed ? 0 : 1); ``` # Troubleshooting > Symptoms, causes and fixes for install errors, blank frames, missing audio, hanging scripts, vision artifacts and preview problems. ## Install [Section titled “Install”](#install) | Symptom | Cause | Fix | | ------------------------------------ | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `Cannot find module '.../skia.node'` | `skia-canvas` install script was blocked | approve it ([Getting started](/docs/getting-started/#2-write-packagejson-then-install)), then `npm rebuild skia-canvas` | | Import fails immediately | Node < 22, or not an ES module project | upgrade Node; set `"type": "module"` | | No adapter / GPU error | no GPU and no Vulkan driver (VM, plain CI runner) | on Linux, `apt-get install -y libvulkan1 mesa-vulkan-drivers` to render on the CPU (Windows has WARP built in) | | Install fails on the render worker | lockfile missing or out of date, or a bun lockfile | commit a pnpm, npm or yarn lockfile that matches `package.json` | ## Picture [Section titled “Picture”](#picture) | Symptom | Cause | Fix | | --------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | Whole frame black | font not registered, or `NaN` from a signal | register every family before building text; keep signal outputs finite | | Text missing or tofu | family name doesn’t match a registered font | match `fontFamily` to the `family` you registered | | Emoji missing | no emoji font | `FontManager.registerEmojiFont(...)` | | Layer invisible | path wrong, opacity 0, off canvas, an LFS pointer, or a pinned asset not pulled | check `comp.lint()`; run `git lfs pull` or `npx framefields assets pull` | | Text clipped | box narrower than the text | set `width` (or `width: "fill"`) | | Animation stops early | keys past `durationFrames` | extend the layer (`animation_truncated`) | | Layer jumps to the corner when animated | animated `y` from 0 instead of its layout value | animate to the placed value | | Fades look murky grey | custom shader with straight alpha | output premultiplied alpha, blend with `srcFactor: "one"` | | Metal/rough looks flat | no environment | add `Layer.environment()` or `Lighting.studio()` | | Effect does nothing | strength on a 0–1 scale where it’s 0–100 | check ranges in the [Effects reference](/docs/reference/effects/) | ## Sound [Section titled “Sound”](#sound) | Symptom | Cause | Fix | | --------------------- | -------------------------------------- | ------------------------------------- | | Audio cuts out early | `Layer.audio` without `durationFrames` | set `durationFrames: totalFrames` | | `audio_clipping` | mix too hot | lower volumes; `softLimit` SFX beds | | `loudness_off_target` | mix level | adjust volume toward the `targetLufs` | ## Process [Section titled “Process”](#process) | Symptom | Cause | Fix | | ------------------------------------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | Script never exits after rendering | native GPU/encoder threads | `process.exit()` at the end | | Slow exports | too little parallelism or a shallow staging ring | raise `concurrency`; try `ringCapacity: 4` | | Very slow on a Linux server | frames drawn on the CPU | `describeGpu()` reports `software: true`: fix the GPU’s Vulkan driver (`vulkaninfo --summary`) | | Encoder fails to open (`h264_rkmpp`, NVENC) | framefields < 2.2 picks an encoder without testing it | upgrade to 2.2, or set `FRAMEFIELDS_HW_CODECS=off` | ## Vision [Section titled “Vision”](#vision) | Symptom | Cause | Fix | | ------------------------------ | ------------------------------------------ | -------------------------------------------------------------------------------------------------- | | Cutout empty on a single still | vision reads the previous frame | render two consecutive frames with one renderer, keep the last | | Ghosted double of the subject | frames rendered out of order (grid, jumps) | verify with the MP4 or consecutive frames | | Wrong object cut out | subject choice | `classes: ["person"]` | | Garment drops out | fast motion | `variant: "m"` or `keyBackground: true` | | Halo on dark backgrounds | feathering | lower `featherRadius` or raise `maskThreshold` | | Vision slow | inference on the CPU | look for `[vision] Inference on the GPU` in the log; needs framefields 2.2+ and a hardware adapter | | Fails offline / in CI | models not cached | preload into `$FRAMEFIELDS_MODELS_DIR` or set `FRAMEFIELDS_MODELS_BASE_URL` | ## Preview [Section titled “Preview”](#preview) | Symptom | Cause | Fix | | -------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------- | | Font or media 404 in the page | path built from `process.cwd()` | build paths from `import.meta.url`; pass `root` for folders outside the project | | “No WebGPU” | browser without WebGPU | current Chrome, Edge or Safari | | Preview stopped | last tab closed (5 s), or replaced | run it again; same URL | | Cutouts look wrong while playing | device skipped frames | check paused, or in the export | Render worker and cloud render error codes: [Render on a server](/docs/guides/render-service/#errors). Cloud-specific fixes (private repos, unpushed commits, credits): [Cloud rendering](/docs/guides/cloud-rendering/#when-a-render-fails). Still stuck? Open an issue at [github.com/gatewai-dev/framefields](https://github.com/gatewai-dev/framefields/issues) or ask on [Discord](https://discord.gg/cbqMGGme5).