Skip to content

Code-first video & image, rendered natively on WebGPU.

add 3d animation showcase

okanasl011db64846d4
diff --git a/.gitignore b/.gitignore
index 432ddb5b..ecd00483 100644
--- a/.gitignore
+++ b/.gitignore
@@ -33,7 +33,7 @@ assets/fonts/
examples/25_bakery
# Soundfonts
*.sf2
-assets
+assets/soundfonts/
# Heavy Media, Video, Audio & Images
*.mp4
diff --git a/README.md b/README.md
index a4cdea9a..36d4752c 100644
--- a/README.md
+++ b/README.md
@@ -29,17 +29,24 @@ Every frame of these films is rendered by framefields from TypeScript in [`examp
<table>
<tr>
- <td width="33%" align="center">
+ <td width="50%" align="center">
+ <a href="https://youtu.be/k2lgbdL6_TA"><img src="assets/showcase/mac-keyboard.jpg" alt="Mac keyboard from 3D primitives" width="100%"></a>
+ <br><a href="https://youtu.be/k2lgbdL6_TA"><b>Mac Keyboard</b></a>
+ <br><sub><a href="examples/26_mac_keyboard_from_3d_primitives"><code>26_mac_keyboard_from_3d_primitives</code></a></sub>
+ </td>
+ <td width="50%" align="center">
<a href="https://youtu.be/FVXTqAozAv8"><img src="assets/showcase/framefields-launch.jpg" alt="Framefields launch film" width="100%"></a>
<br><a href="https://youtu.be/FVXTqAozAv8"><b>Framefields launch</b></a>
<br><sub><a href="examples/22_framefields_launch"><code>22_framefields_launch</code></a></sub>
</td>
- <td width="33%" align="center">
+ </tr>
+ <tr>
+ <td width="50%" align="center">
<a href="https://youtu.be/9BF1snfmg3o"><img src="assets/showcase/full-circle.jpg" alt="Full Circle film" width="100%"></a>
<br><a href="https://youtu.be/9BF1snfmg3o"><b>Full Circle</b></a>
<br><sub><a href="examples/21_full_circle"><code>21_full_circle</code></a></sub>
</td>
- <td width="33%" align="center">
+ <td width="50%" align="center">
<a href="https://youtu.be/RQ3yi_lzPqI"><img src="assets/showcase/dancer.jpg" alt="Dancer showcase film" width="100%"></a>
<br><a href="https://youtu.be/RQ3yi_lzPqI"><b>Dancer showcase</b></a>
<br><sub><a href="examples/19_framefields_film"><code>19_framefields_film</code></a></sub>
@@ -131,7 +138,7 @@ A comprehensive suite of professional image/video shader nodes in [`nodes/`](nod
### 3. Unified 3D Scene Graph, Camera & Mesh Shading
- **Calibrated camera rig** — LookAt and Turntable cameras ([`Camera3D`](packages/webgpu-renderers/src/math3d/camera3d.ts)) calibrated so `z = 0` matches 2D canvas pixel coordinates 1:1.
-- **3D layout primitives** — [`Layer3D.cube`](packages/framefields/src/shapes3d.ts), `carousel`, `prism`, `plane`, `grid` with unified depth-buffer testing.
+- **3D layout primitives** — [`Layer3D.cube`](packages/framefields/src/shapes3d.ts), `carousel`, `prism`, `plane`, `grid` with unified depth-buffer testing, plus solid smooth-shaded meshes: `roundedBox` (with `taper`, for keycaps and device bodies), `sphere` and `cylinder`.
- **Zero-dependency model parsers** — OBJ, FBX, glTF/GLB, STL, PLY, VOX, 3DS, OFF.
- **Skeletal animation & shading** — 128-bone Linear Blend Skinning, Blinn-Phong & PBR multi-light shading, PCSS/Poisson contact shadows, SSAO, and optical DoF.
- **Physical motion blur** — 180° shutter motion blur with per-vertex velocity vectors packed into `rg16float` MRT buffers.
@@ -667,6 +674,7 @@ The [`examples/`](examples) directory holds production-grade reference compositi
| [`19_framefields_film`](examples/19_framefields_film) | The 30-second master brand film — full pipeline, audio, VFX, 3D |
| [`21_full_circle`](examples/21_full_circle) | Multi-scene narrative composition |
| [`22_framefields_launch`](examples/22_framefields_launch) | Launch/product-motion composition |
+| [`26_mac_keyboard_from_3d_primitives`](examples/26_mac_keyboard_from_3d_primitives) | Mac keyboard product shot from 3D primitives — procedural keycap tapers, typing choreography, and light waves |
---
diff --git a/assets/showcase/mac-keyboard.jpg b/assets/showcase/mac-keyboard.jpg
new file mode 100644
index 00000000..f3cea1ea
Binary files /dev/null and b/assets/showcase/mac-keyboard.jpg differ
diff --git a/examples/26_mac_keyboard_from_3d_primitives/README.md b/examples/26_mac_keyboard_from_3d_primitives/README.md
new file mode 100644
index 00000000..b164480e
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/README.md
@@ -0,0 +1,55 @@
+# 26 — Mac Keyboard
+
+A 12-second product shot of a compact Mac keyboard with Touch ID, made only from 3D primitives. The
+aluminium body lands, 78 keycaps rain in from the center out, someone types `Hello, framefields.`
+with each key bottoming out and flashing its backlight in time with the line on screen, and then a
+blue-to-pink backlight wave rolls across the board while the camera rises to top-down.
+
+Nothing to download or generate: fonts come from the repo's `assets/fonts`.
+
+```bash
+pnpm render grid # output/grid.png, a 16-frame contact sheet
+pnpm render frames 116 290
+pnpm render # output/mac-keyboard.mp4
+pnpm render:src grid # same, on the engine's source (no package builds)
+```
+
+## The parts
+
+| Part | Primitive |
+|---|---|
+| Body | `Layer3D.roundedBox`: one smooth-shaded mesh, metallic silver |
+| Keycaps | `Layer3D.roundedBox` with `taper: 0.95`, so the top face is a little smaller than the base |
+| Legends | `Layer3D.text`, laid flat on each cap (`rotateX: -90`) |
+| ⌘ and ⌥ | Inter has no glyphs for these, so they are stroked `Layer.shape("path")` icons on a transparent `Layer3D.plane` |
+| Touch ID ring | `Layer3D.cylinder`, 1.2 px tall |
+| Floor | A very large, very thin `roundedBox` under a point light. `BG` matches the floor's color at the far plane, so there is no horizon line |
+
+Every key is a `preserve-3d` box holding its cap and legends, so moving the box moves all of them
+together. The cap's `tint` multiplies its color and animates as the `color` prop, which is how keys
+light up. Keys of the same size share one mesh: `Layer3D` caches geometry by its options, so all
+the letter keys use a single vertex buffer.
+
+## Files
+
+- `layout.ts`: the US layout in key units (rows, widths, legends) and `keysForChar`, which maps a
+ character to the keys it needs, with shift for capitals and symbols.
+- `keyboard.ts`: builds the keyboard from the layout. World axes: x right, y down, z away from the
+ camera. The keyboard lies in the x/z plane, so "up" is -y.
+- `timeline.ts`: the three acts and the typing schedule. Keystrokes have a fixed, human-feeling
+ rhythm: about 5.5 frames per key with deterministic jitter, a bit longer on spaces and a pause
+ after the comma.
+- `motion.ts`: each key's full animation as one `y` track and one `color` track: rain in, press for
+ every stroke that uses it, then the wave. A quick repeat (the "ll" in Hello) springs back faster
+ so the second press still reads. A modifier goes down before the key it modifies and comes up
+ after it.
+- `film.ts`: the camera (keyed `orbitAzimuth` / `orbitElevation` / `orbitRadius`), the lights, the
+ typed line and its caret, the caption, plus vignette and grain. The grain also dithers the
+ floor's light pool, which would otherwise show banding in 8-bit.
+
+## Typing in sync
+
+On a text layer, `text` reads as a fraction of the string while it is at most 1, and as a character
+count above 1. The typed line keys one count per keystroke with `"hold"` easing, so each character
+appears on the exact frame its key bottoms out. The caret's `x` uses the same keys:
+JetBrains Mono advances 0.6 em per character, so its position follows from the count.
diff --git a/examples/26_mac_keyboard_from_3d_primitives/package.json b/examples/26_mac_keyboard_from_3d_primitives/package.json
new file mode 100644
index 00000000..1d3619b0
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@framefields/example-26-mac-keyboard",
+ "version": "2.0.10",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "render": "tsx src/render.ts",
+ "render:src": "tsx --tsconfig tsconfig.dev.json --conditions=development src/render.ts",
+ "typecheck": "tsc --noEmit -p ."
+ },
+ "dependencies": {
+ "framefields": "workspace:*"
+ },
+ "devDependencies": {
+ "@framefields/tsconfig": "workspace:*",
+ "@types/node": "^24.1.0",
+ "tsx": "^4.20.3",
+ "typescript": "^5.8.3"
+ }
+}
diff --git a/examples/26_mac_keyboard_from_3d_primitives/src/film.ts b/examples/26_mac_keyboard_from_3d_primitives/src/film.ts
new file mode 100644
index 00000000..18b5e119
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/src/film.ts
@@ -0,0 +1,215 @@
+import {
+ CameraAnimation,
+ Composition,
+ FilmGrain,
+ Layer,
+ Layer3D,
+ LayerAnimation,
+ Vignette,
+} from "framefields";
+import { keyboard } from "./keyboard.js";
+import { animateKey } from "./motion.js";
+import {
+ ACCENT,
+ BG,
+ FPS,
+ H,
+ MONO,
+ MUTED,
+ registerFonts,
+ SANS,
+ TEXT,
+ W,
+} from "./theme.js";
+import {
+ ASSEMBLE,
+ DURATION,
+ LINE,
+ STROKES,
+ TITLE_AT,
+ TYPE_FROM,
+ WAVE_FROM,
+} from "./timeline.js";
+
+export { DURATION };
+
+/** The keyboard sits at the world origin of the shot: the screen's center. */
+const CX = W / 2;
+const CY = H / 2;
+
+type Key = [frame: number, value: number | string, ease?: string];
+
+/**
+ * Three moves: a low three-quarter swing in while it assembles, a slow
+ * push over the typing, then a rise to near top-down for the wave.
+ */
+function camera() {
+ return CameraAnimation.camera()
+ .keys("orbitAzimuth", [
+ [0, -42],
+ [100, -14, "power2.inOut"],
+ [WAVE_FROM - 12, 6, "sine.inOut"],
+ [WAVE_FROM + 50, 0, "power3.inOut"],
+ ])
+ .keys("orbitElevation", [
+ [0, 12],
+ [100, 30, "power2.inOut"],
+ [WAVE_FROM - 12, 38, "sine.inOut"],
+ [WAVE_FROM + 50, 68, "power3.inOut"],
+ ])
+ .keys("orbitRadius", [
+ [0, 2500],
+ [100, 1520, "power2.inOut"],
+ [WAVE_FROM - 12, 1180, "sine.inOut"],
+ [WAVE_FROM + 50, 1640, "power3.inOut"],
+ ]);
+}
+
+/** JetBrains Mono advances 0.6 em per character, so the caret can be placed by count. */
+const LINE_SIZE = 60;
+const ADVANCE = LINE_SIZE * 0.6;
+const LINE_X = CX - (LINE.length * ADVANCE) / 2;
+const LINE_Y = 118;
+
+/** The typed line: revealed one character per keystroke, frame-exact. */
+function typedLine() {
+ // `text` above 1 is a character count; 1 and below a fraction of the line.
+ const reveal: Key[] = [[0, 0]];
+ for (const s of STROKES) {
+ reveal.push([s.at, s.count === 1 ? 1 / LINE.length : s.count, "hold"]);
+ }
+ const caretX: Key[] = [[0, LINE_X]];
+ for (const s of STROKES) {
+ caretX.push([s.at, LINE_X + s.count * ADVANCE, "hold"]);
+ }
+ // Steady while typing, blinking at rest; it goes when the wave starts.
+ const blink: Key[] = [[0, 0]];
+ const typingFrom = STROKES[0]!.at;
+ const typingTo = STROKES[STROKES.length - 1]!.at;
+ for (let f = TYPE_FROM - 24; f < WAVE_FROM; f += 16) {
+ const typing = f + 16 > typingFrom && f < typingTo + 8;
+ blink.push([f, 1, "hold"], [f + 8, typing ? 1 : 0, "hold"]);
+ }
+ blink.push([WAVE_FROM, 0, "hold"]);
+ return [
+ Layer.text(LINE, {
+ id: "typed",
+ position: "absolute",
+ x: LINE_X,
+ y: LINE_Y,
+ fontFamily: MONO,
+ fontSize: LINE_SIZE,
+ fill: TEXT,
+ }).animate(LayerAnimation.create().keys("text", reveal)),
+ Layer.box({
+ id: "caret",
+ position: "absolute",
+ x: LINE_X,
+ y: LINE_Y + 4,
+ width: 5,
+ height: LINE_SIZE + 6,
+ background: ACCENT,
+ borderRadius: 2,
+ }).animate(
+ LayerAnimation.create().keys("x", caretX).keys("opacity", blink),
+ ),
+ ];
+}
+
+function caption() {
+ return Layer.text("A Mac keyboard, built from framefields 3D primitives", {
+ id: "caption",
+ position: "absolute",
+ x: 0,
+ y: H - 120,
+ width: W,
+ align: "center",
+ fontFamily: SANS,
+ fontSize: 30,
+ fill: MUTED,
+ letterSpacing: 0.5,
+ }).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [TITLE_AT, 0],
+ [TITLE_AT + 24, 1, "power2.out"],
+ ])
+ .keys("y", [
+ [TITLE_AT, H - 100],
+ [TITLE_AT + 30, H - 120, "expo.out"],
+ ]),
+ );
+}
+
+export async function buildFilm(): Promise<Composition> {
+ await registerFonts();
+ const film = new Composition({
+ width: W,
+ height: H,
+ fps: FPS,
+ durationMs: (DURATION / FPS) * 1000,
+ backgroundColor: BG,
+ });
+ film.add([
+ Layer.camera({
+ id: "cam",
+ targetX: CX,
+ targetY: CY,
+ targetZ: 0,
+ animation: camera(),
+ } as never),
+ Layer.directionalLight({
+ id: "key-light",
+ color: "#ffffff",
+ intensity: 0.7,
+ direction: [-0.35, 1, 0.45],
+ } as never),
+ // A warm-white pool overhead: it falls off across the floor like a studio spot.
+ Layer.pointLight({
+ id: "pool",
+ color: "#fff6ea",
+ intensity: 0.9,
+ x: CX,
+ y: CY - 900,
+ z: -150,
+ radius: 2600,
+ decay: 1.2,
+ }),
+ Layer.ambientLight("#ffffff", 0.22, { id: "fill" }),
+ Layer3D.roundedBox({
+ id: "floor",
+ width: 60000,
+ height: 10,
+ depth: 60000,
+ x: CX,
+ y: CY + 13,
+ z: 0,
+ color: "#17181c",
+ roughness: 0.9,
+ specularIntensity: 0.05,
+ }),
+ keyboard({
+ id: "kb",
+ x: CX,
+ y: CY,
+ z: 0,
+ animateKey,
+ body: LayerAnimation.create()
+ .keys("opacity", [
+ [ASSEMBLE.body, 0],
+ [ASSEMBLE.body + 14, 1, "power1.out"],
+ ])
+ .keys("y", [
+ [ASSEMBLE.body, 70],
+ [ASSEMBLE.body + 22, 0, "expo.out"],
+ ]),
+ }),
+ ...typedLine(),
+ caption(),
+ ]);
+ // Fine grain dithers the floor's light pool, which would band in 8 bits.
+ film.apply(new Vignette({ strength: 0.18, radius: 0.9, softness: 0.75 }));
+ film.apply(new FilmGrain({ strength: 0.03, size: 1.2, animated: true }));
+ return film;
+}
diff --git a/examples/26_mac_keyboard_from_3d_primitives/src/keyboard.ts b/examples/26_mac_keyboard_from_3d_primitives/src/keyboard.ts
new file mode 100644
index 00000000..359e8a9d
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/src/keyboard.ts
@@ -0,0 +1,235 @@
+/**
+ * The keyboard as 3D primitives: an aluminium `Layer3D.roundedBox` body,
+ * one tapered rounded box per keycap (equal sizes share one mesh), flat
+ * `Layer3D.text` legends lying on the caps, and a `Layer3D.cylinder` Touch
+ * ID ring. World axes: x right, y down, z away from the camera, so the
+ * keyboard lies in the x/z plane and "up" is -y.
+ */
+import {
+ type AnimatableNode,
+ Layer,
+ Layer3D,
+ type LayerAnimation,
+ type LayoutNode,
+} from "framefields";
+import {
+ KEYBOARD_UNITS_D,
+ KEYBOARD_UNITS_W,
+ KEYS,
+ type KeyDef,
+} from "./layout.js";
+import { ALUMINIUM, CAP, LEGEND, SANS } from "./theme.js";
+
+/** `.animate(...given(a))` animates only when there is an animation. */
+const given = (a: LayerAnimation | undefined) => (a ? [a] : []);
+
+/** One key unit in world px. */
+export const U = 78;
+/** Space between neighbouring caps. */
+const GAP = 13;
+const CAP_H = 15;
+const BODY_H = 24;
+const BODY_MARGIN = 0.32 * U;
+
+export const KEYBOARD_W = KEYBOARD_UNITS_W * U + BODY_MARGIN * 2;
+export const KEYBOARD_D = KEYBOARD_UNITS_D * U + BODY_MARGIN * 2;
+/** Height of the body's top face and of a resting cap's top face (y is down). */
+export const BODY_TOP = -BODY_H / 2;
+export const CAP_TOP = BODY_TOP - CAP_H;
+
+/** A key's center in the keyboard's own space. */
+export function keyCenter(key: KeyDef): { x: number; z: number } {
+ return {
+ x: (key.x - KEYBOARD_UNITS_W / 2) * U,
+ // Row 0 is the back row: far from the camera, so +z.
+ z: (KEYBOARD_UNITS_D / 2 - key.z) * U,
+ };
+}
+
+export interface KeyAnimations {
+ /** Moves the whole key (cap and legends): drop-in, press travel. */
+ key?: LayerAnimation;
+ /** Animates the cap alone, e.g. its `color` tint for the backlight. */
+ cap?: LayerAnimation;
+}
+
+export interface KeyboardOptions {
+ id: string;
+ x: number;
+ y: number;
+ z: number;
+ /** Per-key animation; called once for every key. */
+ animateKey?: (key: KeyDef, index: number) => KeyAnimations;
+ body?: LayerAnimation;
+}
+
+/** A legend lying flat on a cap's top face, reading toward the camera. */
+function legend(
+ id: string,
+ text: string,
+ size: number,
+ dz: number,
+): AnimatableNode<LayoutNode> {
+ return Layer3D.text({
+ id,
+ text,
+ fontFamily: SANS,
+ fontWeight: 500,
+ fontSize: size,
+ fill: LEGEND,
+ material: "unlit",
+ x: 0,
+ y: CAP_TOP - 0.6,
+ z: dz,
+ rotateX: -90,
+ twoSided: false,
+ });
+}
+
+/**
+ * Glyphs Inter lacks, drawn as stroked paths (Lucide's command and option
+ * icons, 24-unit grid scaled to `k`).
+ */
+const GLYPH_PATHS: Record<string, (k: number) => string> = {
+ "⌘": (k) =>
+ `M${15 * k} ${6 * k}v${12 * k}a${3 * k} ${3 * k} 0 1 0 ${3 * k} ${-3 * k}` +
+ `H${6 * k}a${3 * k} ${3 * k} 0 1 0 ${3 * k} ${3 * k}V${6 * k}` +
+ `a${3 * k} ${3 * k} 0 1 0 ${-3 * k} ${3 * k}h${12 * k}` +
+ `a${3 * k} ${3 * k} 0 1 0 ${-3 * k} ${-3 * k}`,
+ "⌥": (k) =>
+ `M${3 * k} ${3 * k}h${6 * k}l${6 * k} ${18 * k}h${6 * k}` +
+ `M${14 * k} ${3 * k}h${7 * k}`,
+};
+
+/** A vector glyph on a transparent card lying on the cap, like `legend`. */
+function glyphLegend(
+ id: string,
+ glyph: string,
+ size: number,
+ dz: number,
+): LayoutNode {
+ const path = GLYPH_PATHS[glyph]!;
+ return Layer3D.plane({
+ id,
+ width: size,
+ height: size,
+ background: "transparent",
+ x: 0,
+ y: CAP_TOP - 0.6,
+ z: dz,
+ rotateX: -90,
+ twoSided: false,
+ children: [
+ Layer.shape("path", {
+ id: `${id}-path`,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: size,
+ height: size,
+ d: path(size / 24),
+ fillColor: "transparent",
+ strokeColor: LEGEND,
+ strokeWidth: size / 13,
+ }),
+ ],
+ });
+}
+
+function keyNode(key: KeyDef, anims: KeyAnimations): LayoutNode {
+ const w = key.w * U - GAP;
+ const d = key.d * U - GAP;
+ const { x, z } = keyCenter(key);
+ const children: LayoutNode[] = [
+ Layer3D.roundedBox({
+ id: `key-${key.id}-cap`,
+ width: w,
+ height: CAP_H,
+ depth: d,
+ radius: 6,
+ segments: 3,
+ taper: 0.95,
+ y: BODY_TOP - CAP_H / 2,
+ color: key.touchId ? "#1b1c1f" : CAP,
+ roughness: 0.55,
+ shininess: 24,
+ specularIntensity: 0.25,
+ ...(anims.cap && { tint: "#ffffff" }),
+ }).animate(...given(anims.cap)),
+ ];
+ if (key.touchId) {
+ children.push(
+ Layer3D.cylinder({
+ id: `key-${key.id}-sensor`,
+ radius: d * 0.36,
+ height: 1.2,
+ segments: 48,
+ y: CAP_TOP - 0.6,
+ color: "#2f3136",
+ metallic: 0.8,
+ roughness: 0.25,
+ shininess: 80,
+ }),
+ );
+ }
+ const small = 0.15 * U;
+ const big = 0.25 * U;
+ if (key.sub && key.label) {
+ const size = key.small ? small : 0.19 * U;
+ children.push(
+ GLYPH_PATHS[key.sub]
+ ? glyphLegend(`key-${key.id}-sub`, key.sub, size * 0.95, d * 0.18)
+ : legend(`key-${key.id}-sub`, key.sub, size, d * 0.18),
+ legend(`key-${key.id}-label`, key.label, size, -d * 0.18),
+ );
+ } else if (key.label) {
+ children.push(
+ legend(`key-${key.id}-label`, key.label, key.small ? small : big, 0),
+ );
+ }
+ return Layer.box({
+ id: `key-${key.id}`,
+ position: "absolute",
+ x,
+ y: 0,
+ z,
+ width: w,
+ height: d,
+ is3D: true,
+ transformStyle: "preserve-3d",
+ background: "transparent",
+ children,
+ }).animate(...given(anims.key)) as unknown as LayoutNode;
+}
+
+export function keyboard(options: KeyboardOptions): AnimatableNode<LayoutNode> {
+ const body = Layer3D.roundedBox({
+ id: `${options.id}-body`,
+ width: KEYBOARD_W,
+ height: BODY_H,
+ depth: KEYBOARD_D,
+ radius: 11,
+ segments: 5,
+ color: ALUMINIUM,
+ metallic: 0.55,
+ roughness: 0.38,
+ shininess: 60,
+ specularIntensity: 0.7,
+ }).animate(...given(options.body));
+ const keys = KEYS.map((key, i) =>
+ keyNode(key, options.animateKey?.(key, i) ?? {}),
+ );
+ return Layer.box({
+ id: options.id,
+ position: "absolute",
+ x: options.x,
+ y: options.y,
+ z: options.z,
+ width: KEYBOARD_W,
+ height: KEYBOARD_D,
+ is3D: true,
+ transformStyle: "preserve-3d",
+ background: "transparent",
+ children: [body, ...keys],
+ }) as unknown as AnimatableNode<LayoutNode>;
+}
diff --git a/examples/26_mac_keyboard_from_3d_primitives/src/layout.ts b/examples/26_mac_keyboard_from_3d_primitives/src/layout.ts
new file mode 100644
index 00000000..7fd99f23
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/src/layout.ts
@@ -0,0 +1,144 @@
+/**
+ * A compact US Magic Keyboard (with Touch ID), in key units: one unit is
+ * the pitch of a letter key. Rows run from the function row (back, row 0)
+ * to the modifier row (front, row 5); every main row is 15 units wide.
+ */
+export interface KeyDef {
+ /** Stable id: also what `type()` looks keys up by. */
+ id: string;
+ /** Main legend. */
+ label: string;
+ /** Second legend above the main one (shifted symbol, modifier glyph). */
+ sub?: string;
+ /** Center, in units from the keyboard's left edge. */
+ x: number;
+ /** Center, in units from the back edge. */
+ z: number;
+ /** Width and depth in units. */
+ w: number;
+ d: number;
+ /** Small legends: words on modifiers, F-keys. */
+ small?: boolean;
+ /** The Touch ID button: a dark cap with a sensor ring. */
+ touchId?: boolean;
+}
+
+export const KEYBOARD_UNITS_W = 15;
+const FN_ROW_D = 0.6;
+export const KEYBOARD_UNITS_D = FN_ROW_D + 5;
+
+type RowItem = [id: string, label: string, w?: number, sub?: string];
+
+const ROWS: RowItem[][] = [
+ [
+ ["esc", "esc", 1.5],
+ ...Array.from(
+ { length: 12 },
+ (_, i) => [`f${i + 1}`, `F${i + 1}`, 1] as RowItem,
+ ),
+ ["touchid", "", 1.5],
+ ],
+ [
+ ["grave", "`", 1, "~"],
+ ["1", "1", 1, "!"],
+ ["2", "2", 1, "@"],
+ ["3", "3", 1, "#"],
+ ["4", "4", 1, "$"],
+ ["5", "5", 1, "%"],
+ ["6", "6", 1, "^"],
+ ["7", "7", 1, "&"],
+ ["8", "8", 1, "*"],
+ ["9", "9", 1, "("],
+ ["0", "0", 1, ")"],
+ ["minus", "-", 1, "_"],
+ ["equal", "=", 1, "+"],
+ ["delete", "delete", 2],
+ ],
+ [
+ ["tab", "tab", 1.5],
+ ..."QWERTYUIOP".split("").map((c) => [c.toLowerCase(), c] as RowItem),
+ ["lbracket", "[", 1, "{"],
+ ["rbracket", "]", 1, "}"],
+ ["backslash", "\\", 1.5, "|"],
+ ],
+ [
+ ["caps", "caps lock", 1.75],
+ ..."ASDFGHJKL".split("").map((c) => [c.toLowerCase(), c] as RowItem),
+ ["semicolon", ";", 1, ":"],
+ ["quote", "'", 1, '"'],
+ ["return", "return", 2.25],
+ ],
+ [
+ ["lshift", "shift", 2.25, "⇧"],
+ ..."ZXCVBNM".split("").map((c) => [c.toLowerCase(), c] as RowItem),
+ ["comma", ",", 1, "<"],
+ ["period", ".", 1, ">"],
+ ["slash", "/", 1, "?"],
+ ["rshift", "shift", 2.75, "⇧"],
+ ],
+ [
+ ["fn", "fn", 1],
+ ["lctrl", "control", 1, "^"],
+ ["lopt", "option", 1, "⌥"],
+ ["lcmd", "command", 1.25, "⌘"],
+ ["space", "", 5.5],
+ ["rcmd", "command", 1.25, "⌘"],
+ ["ropt", "option", 1, "⌥"],
+ // The arrow cluster is laid out by hand below.
+ ],
+];
+
+/** Labels set in the small size. */
+const SMALL =
+ /^(esc|F\d+|delete|tab|caps lock|return|shift|fn|control|option|command)$/;
+
+function buildLayout(): KeyDef[] {
+ const keys: KeyDef[] = [];
+ ROWS.forEach((row, r) => {
+ const d = r === 0 ? FN_ROW_D : 1;
+ const z = r === 0 ? FN_ROW_D / 2 : FN_ROW_D + (r - 1) + 0.5;
+ let x = 0;
+ for (const [id, label, w = 1, sub] of row) {
+ keys.push({
+ id,
+ label,
+ sub,
+ x: x + w / 2,
+ z,
+ w,
+ d,
+ small: SMALL.test(label),
+ touchId: id === "touchid",
+ });
+ x += w;
+ }
+ });
+ // Arrows: ← and → are half-height, ↑ and ↓ share one key slot.
+ const rowZ = FN_ROW_D + 4;
+ const arrows: Array<[string, string, number, number]> = [
+ ["left", "←", 12.5, rowZ + 0.75],
+ ["up", "↑", 13.5, rowZ + 0.25],
+ ["down", "↓", 13.5, rowZ + 0.75],
+ ["right", "→", 14.5, rowZ + 0.75],
+ ];
+ for (const [id, label, x, z] of arrows) {
+ keys.push({ id, label, x, z, w: 1, d: 0.5, small: true });
+ }
+ return keys;
+}
+
+export const KEYS: readonly KeyDef[] = buildLayout();
+
+/** Which keys a character needs: its own key, plus shift for capitals and symbols. */
+export function keysForChar(ch: string): string[] {
+ if (ch === " ") return ["space"];
+ if (ch === "\n") return ["return"];
+ const lower = ch.toLowerCase();
+ const letter = KEYS.find((k) => k.id === lower && /^[a-z0-9]$/.test(k.id));
+ if (letter) return ch !== lower ? ["lshift", letter.id] : [letter.id];
+ const plain = KEYS.find((k) => k.label === ch);
+ if (plain) return [plain.id];
+ const shifted = KEYS.find((k) => k.sub === ch);
+ if (shifted) return ["lshift", shifted.id];
+ throw new Error(`No key types ${JSON.stringify(ch)}`);
+}
diff --git a/examples/26_mac_keyboard_from_3d_primitives/src/motion.ts b/examples/26_mac_keyboard_from_3d_primitives/src/motion.ts
new file mode 100644
index 00000000..7416a176
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/src/motion.ts
@@ -0,0 +1,111 @@
+/**
+ * Every key's whole life as one pair of key tracks: it rains in, gets
+ * pressed whenever the typing schedule needs it, then rides the backlight
+ * wave. Tracks must run forward in time, so each key's moments are
+ * collected first and written out in order.
+ */
+import { LayerAnimation } from "framefields";
+import { type KeyAnimations, keyCenter, U } from "./keyboard.js";
+import { KEYBOARD_UNITS_W, KEYS, type KeyDef } from "./layout.js";
+import { GLOW } from "./theme.js";
+import { ASSEMBLE, STROKES, WAVE_FROM, WAVE_SPREAD } from "./timeline.js";
+
+type Key = [frame: number, value: number | string, ease?: string];
+
+/** How far a cap travels when pressed (y is down). */
+const TRAVEL = 6;
+const DROP = -340;
+const REST = "#ffffff";
+
+/** Frames a key is held down: [bottomed out, released]. */
+function pressIntervals(id: string): Array<[number, number]> {
+ const raw: Array<[number, number]> = [];
+ for (const s of STROKES) {
+ const i = s.keys.indexOf(id);
+ if (i < 0) continue;
+ // A modifier goes down first and lets go after its partner.
+ const isModifier = i < s.keys.length - 1;
+ raw.push(isModifier ? [s.at - 4, s.at + 3] : [s.at, s.at + 1]);
+ }
+ // Strokes too close to come back up in between merge into one hold.
+ const merged: Array<[number, number]> = [];
+ for (const iv of raw) {
+ const last = merged[merged.length - 1];
+ if (last && iv[0] - last[1] < 5) last[1] = Math.max(last[1], iv[1]);
+ else merged.push([...iv]);
+ }
+ return merged;
+}
+
+/** Keys in time order; where two land on one frame the later-written wins. */
+function ordered(keys: Key[]): Key[] {
+ const byFrame = new Map<number, Key>();
+ for (const k of keys) byFrame.set(k[0], k);
+ return [...byFrame.values()].sort((a, b) => a[0] - b[0]);
+}
+
+/** hsl → hex, for the wave's gradient. */
+function hsl(h: number, s: number, l: number): string {
+ const a = s * Math.min(l, 1 - l);
+ const f = (n: number) => {
+ const k = (n + h / 30) % 12;
+ const c = l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
+ return Math.round(c * 255)
+ .toString(16)
+ .padStart(2, "0");
+ };
+ return `#${f(0)}${f(8)}${f(4)}`;
+}
+
+const HALF_W = (KEYBOARD_UNITS_W / 2) * U;
+const MAX_DIST = Math.max(
+ ...KEYS.map((k) => Math.hypot(keyCenter(k).x, keyCenter(k).z)),
+);
+
+export function animateKey(key: KeyDef): KeyAnimations {
+ const { x, z } = keyCenter(key);
+ const y: Key[] = [];
+ const color: Key[] = [[0, REST]];
+
+ // Act 1: rain in, nearest the center first.
+ const d =
+ ASSEMBLE.keysFrom +
+ Math.round((Math.hypot(x, z) / MAX_DIST) * ASSEMBLE.keysSpread);
+ y.push([0, DROP], [d, DROP], [d + ASSEMBLE.land, 0, "back.out(1.5)"]);
+ const opacity: Key[] = [
+ [0, 0],
+ [d, 0],
+ [d + 5, 1, "power1.out"],
+ ];
+
+ // Act 2: presses, each with a backlight flash that fades after release.
+ // A quick repeat (the "ll" in Hello) springs back faster and flashes again.
+ const presses = pressIntervals(key.id);
+ presses.forEach(([down, up], i) => {
+ const next = presses[i + 1]?.[0] ?? Number.POSITIVE_INFINITY;
+ const back = Math.min(up + 5, next - 2);
+ const fade = Math.min(up + 14, next - 1);
+ y.push([down - 2, 0], [down, TRAVEL, "power2.in"]);
+ if (up > down) y.push([up, TRAVEL]);
+ y.push([back, 0, "power2.out"]);
+ if (i === 0) color.push([down - 1, REST]);
+ color.push([down, GLOW, "power2.out"]);
+ if (up > down) color.push([up, GLOW]);
+ color.push([fade, REST, "sine.inOut"]);
+ });
+
+ // Act 3: a crest rolls left to right; the gradient runs blue → violet → pink.
+ const u = (x + HALF_W) / (2 * HALF_W);
+ const w = WAVE_FROM + Math.round(u * WAVE_SPREAD);
+ y.push([w, 0], [w + 9, -18, "sine.out"], [w + 22, 0, "sine.inOut"]);
+ color.push(
+ [w, REST],
+ [w + 6, hsl(212 + u * 118, 0.95, 0.74), "power1.out"],
+ [w + 40, REST, "sine.inOut"],
+ );
+
+ return {
+ key: LayerAnimation.create().keys("y", ordered(y)).keys("opacity", opacity),
+ cap: LayerAnimation.create().keys("color", ordered(color)),
+ };
+}
diff --git a/examples/26_mac_keyboard_from_3d_primitives/src/render.ts b/examples/26_mac_keyboard_from_3d_primitives/src/render.ts
new file mode 100644
index 00000000..0635037f
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/src/render.ts
@@ -0,0 +1,66 @@
+/**
+ * pnpm render → output/mac-keyboard.mp4
+ * pnpm render frames 60 180 → output/frames/f0060.png …
+ * pnpm render grid → output/grid.png, a contact sheet of the whole film
+ * pnpm render preview → live player on localhost; add --open for the system browser
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { HeadlessMediaRenderer, startPreview } from "framefields";
+import { buildFilm, DURATION } from "./film.js";
+import { OUTPUT } from "./theme.js";
+
+const [mode = "video", ...args] = process.argv.slice(2);
+
+if (mode === "preview") {
+ // The page runs film.ts itself and renders with WebGPU in the browser.
+ const session = await startPreview(
+ { entry: new URL("./film.ts", import.meta.url), export: "buildFilm" },
+ { title: "Mac keyboard", open: args.includes("--open") },
+ );
+ console.log(`Preview at ${session.url}`);
+ // Serves until its tab closes, or the next `pnpm render preview` takes over.
+ await session.closed;
+ process.exit(0);
+}
+const film = await buildFilm();
+await fs.mkdir(path.join(OUTPUT, "frames"), { recursive: true });
+
+if (mode === "frames") {
+ const renderer = new HeadlessMediaRenderer();
+ for (const frame of args.map(Number)) {
+ const file = path.join(
+ OUTPUT,
+ "frames",
+ `f${String(frame).padStart(4, "0")}.png`,
+ );
+ await fs.writeFile(file, await film.renderFrame({ frame, renderer }));
+ console.log(file);
+ }
+} else if (mode === "grid") {
+ const frames = Array.from({ length: 16 }, (_, i) =>
+ Math.round((i * (DURATION - 1)) / 15),
+ );
+ const file = path.join(OUTPUT, "grid.png");
+ await fs.writeFile(
+ file,
+ await film.renderFrameGrid({
+ frames,
+ columns: 4,
+ cellWidth: 480,
+ showLabels: true,
+ }),
+ );
+ console.log(file);
+} else {
+ const started = Date.now();
+ const result = await film.renderVideo({
+ outputPath: path.join(OUTPUT, "mac-keyboard.mp4"),
+ quality: "high",
+ });
+ await result.cleanup?.().catch(() => {});
+ console.log(
+ `${result.filePath} (${((Date.now() - started) / 1000).toFixed(1)} s)`,
+ );
+}
+process.exit(0);
diff --git a/examples/26_mac_keyboard_from_3d_primitives/src/theme.ts b/examples/26_mac_keyboard_from_3d_primitives/src/theme.ts
new file mode 100644
index 00000000..ee6431fb
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/src/theme.ts
@@ -0,0 +1,39 @@
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { FontManager } from "framefields";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FONTS = path.resolve(HERE, "../../../assets/fonts");
+export const OUTPUT = path.resolve(HERE, "../output");
+
+export const W = 1920;
+export const H = 1080;
+export const FPS = 30;
+
+/** Studio: a near-black sweep, so the white caps and silver body read. It
+ * matches the floor where it meets the far plane, so there is no horizon. */
+export const BG = "#101114";
+export const TEXT = "#f3f4f6";
+export const MUTED = "#8b8f98";
+/** Backlight: what a pressed key glows, a cool Apple blue. */
+export const GLOW = "#9cc3ff";
+export const ACCENT = "#5ea0ff";
+
+/** Silver aluminium body and white caps with graphite legends. */
+export const ALUMINIUM = "#b4b8be";
+export const CAP = "#f4f4f2";
+export const LEGEND = "#2b2d31";
+
+export const SANS = "Inter";
+export const MONO = "JetBrains Mono";
+
+export async function registerFonts(): Promise<void> {
+ await FontManager.register({
+ family: SANS,
+ source: path.join(FONTS, "Inter.ttf"),
+ });
+ await FontManager.register({
+ family: MONO,
+ source: path.join(FONTS, "JetBrainsMono.ttf"),
+ });
+}
diff --git a/examples/26_mac_keyboard_from_3d_primitives/src/timeline.ts b/examples/26_mac_keyboard_from_3d_primitives/src/timeline.ts
new file mode 100644
index 00000000..0c96c4c2
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/src/timeline.ts
@@ -0,0 +1,49 @@
+import { keysForChar } from "./layout.js";
+
+/** 12 seconds at 30 fps. */
+export const DURATION = 360;
+
+/** Act 1: the body lands and the caps rain in from the center out. */
+export const ASSEMBLE = { body: 0, keysFrom: 8, keysSpread: 52, land: 16 };
+
+/** Act 2: the line that gets typed, and when typing starts. */
+export const LINE = "Hello, framefields.";
+export const TYPE_FROM = 112;
+
+/** Act 3: a backlight wave sweeps left to right, then the title. */
+export const WAVE_FROM = 262;
+export const WAVE_SPREAD = 44;
+export const TITLE_AT = 300;
+
+export interface Stroke {
+ /** Frame the key bottoms out. */
+ at: number;
+ /** Key ids pressed together: a modifier first, then the key. */
+ keys: string[];
+ /** Characters on screen once this stroke lands. */
+ count: number;
+}
+
+/** Deterministic jitter in [-1, 1], so every render types with the same rhythm. */
+function jitter(i: number): number {
+ const x = Math.sin(i * 12.9898 + 78.233) * 43758.5453;
+ return (x - Math.floor(x)) * 2 - 1;
+}
+
+/** A human rhythm: ~5.5 frames a key, slower on spaces, a breath after punctuation. */
+function schedule(): Stroke[] {
+ const strokes: Stroke[] = [];
+ let at = TYPE_FROM;
+ [...LINE].forEach((ch, i) => {
+ strokes.push({ at, keys: keysForChar(ch), count: i + 1 });
+ let gap = 5.5 + jitter(i) * 1.6;
+ if (ch === " ") gap += 2;
+ if (ch === ",") gap += 7;
+ at += Math.max(3, Math.round(gap));
+ });
+ strokes.push({ at: at + 10, keys: ["return"], count: LINE.length });
+ return strokes;
+}
+
+export const STROKES: readonly Stroke[] = schedule();
+export const TYPE_END = STROKES[STROKES.length - 1]!.at;
diff --git a/examples/26_mac_keyboard_from_3d_primitives/tsconfig.dev.json b/examples/26_mac_keyboard_from_3d_primitives/tsconfig.dev.json
new file mode 100644
index 00000000..c5e4355b
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/tsconfig.dev.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.json",
+ "include": [
+ "src/**/*",
+ "../../nodes/**/*",
+ "../../packages/**/*",
+ "../../node_modules/@framefields/**/*"
+ ]
+}
diff --git a/examples/26_mac_keyboard_from_3d_primitives/tsconfig.json b/examples/26_mac_keyboard_from_3d_primitives/tsconfig.json
new file mode 100644
index 00000000..999801f9
--- /dev/null
+++ b/examples/26_mac_keyboard_from_3d_primitives/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "@framefields/tsconfig/base.json",
+ "compilerOptions": {
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "target": "ES2022",
+ "noEmit": true
+ },
+ "include": ["src/**/*"]
+}
diff --git a/nodes/node-compositor/src/renderers/webgpu-renderer.ts b/nodes/node-compositor/src/renderers/webgpu-renderer.ts
index 74db347a..0d5087f6 100644
--- a/nodes/node-compositor/src/renderers/webgpu-renderer.ts
+++ b/nodes/node-compositor/src/renderers/webgpu-renderer.ts
@@ -28,6 +28,7 @@ import {
type ExtrudedTextGeometryOptions,
type GPUMeshBuffers,
generateExtrudedTextGeometry,
+ getPrimitiveGeometry,
jointMatrices,
type Light3DOptions,
type Mat4,
@@ -35,6 +36,7 @@ import {
type Mesh3DData,
type Model3DData,
measureMaxCaptionHeight,
+ type PrimitiveGeometryOptions,
parseColor,
poseNodes,
type RenderContextValue,
@@ -1345,6 +1347,13 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {
}
}
+ if (!modelSrc && lop.primitive3d) {
+ modelSrc = getPrimitiveGeometry(
+ lop.primitive3d as PrimitiveGeometryOptions,
+ );
+ lop.modelData = modelSrc;
+ }
+
if (!modelSrc) return;
let model: Model3DData | undefined;
@@ -2923,8 +2932,11 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {
typeof target?.text === "number"
? Math.max(0, Math.min(1, target.text))
: 1;
+ // Above 1, `text` is a count of characters (words, lines), not a fraction.
+ const countsUnits =
+ typeof target?.text === "number" && target.text > 1.0001;
- if (progress >= 1) {
+ if (progress >= 1 && !countsUnits) {
displayText = fullText;
} else if (progress <= 0) {
displayText = "";
diff --git a/packages/compositions/src/program/schema.ts b/packages/compositions/src/program/schema.ts
index ca4c6d97..01a35d11 100644
--- a/packages/compositions/src/program/schema.ts
+++ b/packages/compositions/src/program/schema.ts
@@ -1131,6 +1131,8 @@ export interface Model3DNode {
animation?: LayerAnimationSpec;
audioDeform?: MeshAudioDeformConfig;
text3dOptions?: unknown;
+ /** Layer3D primitive options (roundedBox, sphere, cylinder) the mesh is rebuilt from when modelData is lost. */
+ primitive3d?: unknown;
}
export type LayoutNode =
@@ -1422,7 +1424,11 @@ export const Model3DNodeSchema: z.ZodType<Model3DNode> = z
scaleX: z.number().default(1.0),
scaleY: z.number().default(1.0),
audioDeform: z.record(z.string(), z.unknown()).optional(),
+ /** Multiplies the model's material colors (animatable as `color`). */
+ color: ColorSchema.optional(),
+ colorTint: ColorSchema.optional(),
text3dOptions: z.unknown().optional(),
+ primitive3d: z.unknown().optional(),
})
.strict() as unknown as z.ZodType<Model3DNode>;
diff --git a/packages/framefields/src/builder-schema-conformance.test.ts b/packages/framefields/src/builder-schema-conformance.test.ts
index 6e91ecb1..18d53743 100644
--- a/packages/framefields/src/builder-schema-conformance.test.ts
+++ b/packages/framefields/src/builder-schema-conformance.test.ts
@@ -34,6 +34,17 @@ const builders = {
Layer.carousel3d({ radius: 200, items: [Layer.box(), Layer.box()] }),
plane3d: () => Layer.plane3d({ width: 100, height: 50 }),
prism3d: () => Layer.prism3d({ sides: 6, radius: 50, height: 100 }),
+ roundedBox: () =>
+ Layer3D.roundedBox({
+ width: 100,
+ height: 20,
+ depth: 60,
+ radius: 6,
+ taper: 0.9,
+ }),
+ sphere: () => Layer3D.sphere({ radius: 40, color: "#f00" }),
+ cylinder: () =>
+ Layer3D.cylinder({ radiusTop: 10, radiusBottom: 20, height: 40 }),
barChart: () =>
Layer.chart({
type: "bar",
diff --git a/packages/framefields/src/index.ts b/packages/framefields/src/index.ts
index 96bbcf9e..266ae0ee 100644
--- a/packages/framefields/src/index.ts
+++ b/packages/framefields/src/index.ts
@@ -750,12 +750,16 @@ export {
type Cube3DOptions,
type CubeFaceConfig,
type CubeFaceInput,
+ type Cylinder3DOptions,
type ExtrudedText3DOptions,
type Grid3DOptions,
Layer3D,
type Plane3DOptions,
+ type Primitive3DNodeOptions,
type Prism3DOptions,
+ type RoundedBox3DOptions,
type Shape3DContainer,
+ type Sphere3DOptions,
type Text3DOptions,
} from "./shapes3d.js";
diff --git a/packages/framefields/src/primitives-3d-render.test.ts b/packages/framefields/src/primitives-3d-render.test.ts
new file mode 100644
index 00000000..f7a9f010
--- /dev/null
+++ b/packages/framefields/src/primitives-3d-render.test.ts
@@ -0,0 +1,155 @@
+import { Canvas, loadImage } from "skia-canvas";
+import { describe, expect, it } from "vitest";
+import { Composition, Layer, Layer3D, LayerAnimation } from "./index.js";
+
+async function decode(png: Buffer) {
+ const img = await loadImage(png);
+ const canvas = new Canvas(img.width, img.height);
+ const ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0);
+ const { data } = ctx.getImageData(0, 0, img.width, img.height);
+ return {
+ at(x: number, y: number) {
+ const i = (Math.round(y) * img.width + Math.round(x)) * 4;
+ return { r: data[i]!, g: data[i + 1]!, b: data[i + 2]! };
+ },
+ data,
+ };
+}
+
+/** A camera above and in front of (400, 300, 0), looking down at ~45°. */
+function stage() {
+ const comp = new Composition({
+ width: 800,
+ height: 600,
+ fps: 30,
+ durationMs: 1000,
+ backgroundColor: "#000000",
+ });
+ comp.add([
+ Layer.camera({
+ x: 400,
+ y: 300 - 600,
+ z: -600,
+ targetX: 400,
+ targetY: 300,
+ targetZ: 0,
+ }),
+ Layer.ambientLight("#ffffff", 0.9),
+ ]);
+ return comp;
+}
+
+describe("Layer3D mesh primitives", () => {
+ it("draws a rounded box's top face from above, single-sided", async () => {
+ const comp = stage();
+ comp.add(
+ Layer3D.roundedBox({
+ id: "slab",
+ width: 300,
+ height: 40,
+ depth: 300,
+ radius: 12,
+ x: 400,
+ y: 300,
+ color: "#ff3030",
+ }),
+ );
+ const img = await decode(await comp.renderFrame({ frame: 0 }));
+ // The middle of the frame is the slab's top face, not the black background.
+ const top = img.at(400, 300);
+ expect(top.r).toBeGreaterThan(150);
+ expect(top.g).toBeLessThan(top.r / 2);
+ expect(img.at(20, 20).r).toBeLessThan(10);
+ });
+
+ it("tints by the animated `color` prop", async () => {
+ const comp = stage();
+ comp.add(
+ Layer3D.sphere({
+ id: "ball",
+ radius: 120,
+ x: 400,
+ y: 300,
+ tint: "#ffffff",
+ }).animate(
+ LayerAnimation.create().keys("color", [
+ [0, "#ffffff"],
+ [10, "#2040ff"],
+ ]),
+ ),
+ );
+ const start = (await decode(await comp.renderFrame({ frame: 0 }))).at(
+ 400,
+ 300,
+ );
+ const end = (await decode(await comp.renderFrame({ frame: 10 }))).at(
+ 400,
+ 300,
+ );
+ expect(start.r).toBeGreaterThan(180);
+ expect(end.b).toBeGreaterThan(end.r * 2);
+ });
+
+ it("rebuilds the mesh from its options when modelData is lost (a JSON spec)", async () => {
+ const comp = stage();
+ const cylinder = Layer3D.cylinder({
+ id: "can",
+ radius: 100,
+ height: 120,
+ x: 400,
+ y: 300,
+ color: "#30ff30",
+ });
+ expect(cylinder.primitive3d).toMatchObject({
+ type: "cylinder",
+ radius: 100,
+ });
+ delete cylinder.modelData;
+ comp.add(cylinder);
+ const center = (await decode(await comp.renderFrame({ frame: 0 }))).at(
+ 400,
+ 300,
+ );
+ expect(center.g).toBeGreaterThan(150);
+ expect(center.r).toBeLessThan(center.g / 2);
+ });
+});
+
+describe("text reveal by count", () => {
+ it("shows that many characters when `text` is above 1", async () => {
+ const render = async (node: ReturnType<typeof Layer.text>) => {
+ const comp = new Composition({
+ width: 400,
+ height: 120,
+ fps: 30,
+ durationMs: 1000,
+ backgroundColor: "#000000",
+ });
+ comp.add(node);
+ return decode(await comp.renderFrame({ frame: 0 }));
+ };
+ const props = {
+ id: "t",
+ position: "absolute" as const,
+ x: 10,
+ y: 10,
+ fontSize: 64,
+ fill: "#ffffff",
+ };
+ const counted = await render(
+ Layer.text("Hello", props).animate(
+ LayerAnimation.create().keys("text", [[0, 3]]),
+ ),
+ );
+ const plain = await render(Layer.text("Hel", props));
+ const full = await render(Layer.text("Hello", props));
+ const diff = (a: Uint8ClampedArray, b: Uint8ClampedArray) => {
+ let sum = 0;
+ for (let i = 0; i < a.length; i++) sum += Math.abs(a[i]! - b[i]!);
+ return sum;
+ };
+ expect(diff(counted.data, plain.data)).toBe(0);
+ expect(diff(counted.data, full.data)).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/framefields/src/shapes3d.ts b/packages/framefields/src/shapes3d.ts
index 4be081fc..6f10f33f 100644
--- a/packages/framefields/src/shapes3d.ts
+++ b/packages/framefields/src/shapes3d.ts
@@ -5,9 +5,14 @@ import type {
Model3DNode,
} from "@framefields/compositions/program";
import {
+ type CylinderGeometryOptions,
generateExtrudedTextGeometry,
+ getPrimitiveGeometry,
type Model3DData,
+ type PrimitiveGeometryOptions,
+ type RoundedBoxGeometryOptions,
SlugFontCache,
+ type SphereGeometryOptions,
} from "@framefields/webgpu-renderers";
import { autoId } from "./ids.js";
import { type AnimatableNode, Layer } from "./index.js";
@@ -216,6 +221,100 @@ export interface ExtrudedText3DOptions extends Text3DOptions {
curveTolerance?: number;
}
+/** Node props shared by the mesh primitives (roundedBox, sphere, cylinder). */
+export interface Primitive3DNodeOptions {
+ id?: string;
+ x?: number;
+ y?: number;
+ z?: number;
+ rotateX?: number;
+ rotateY?: number;
+ rotateZ?: number;
+ scale?: number;
+ scaleX?: number;
+ scaleY?: number;
+ scaleZ?: number;
+ /** Surface color baked into the mesh (default white). */
+ color?: string;
+ /**
+ * Multiplies the surface color. It is the node's `color`, so animate it
+ * with `.keys("color", …)`; the baked surface `color` stays fixed.
+ */
+ tint?: string;
+ material?: MaterialType;
+ shininess?: number;
+ roughness?: number;
+ specularIntensity?: number;
+ ambientIntensity?: number;
+ metallic?: number;
+ opacity?: number;
+ startFrame?: number;
+ durationFrames?: number;
+}
+
+export type RoundedBox3DOptions = Primitive3DNodeOptions &
+ Omit<RoundedBoxGeometryOptions, "type" | "color" | "material">;
+export type Sphere3DOptions = Primitive3DNodeOptions &
+ Omit<SphereGeometryOptions, "type" | "color" | "material">;
+export type Cylinder3DOptions = Primitive3DNodeOptions &
+ Omit<CylinderGeometryOptions, "type" | "color" | "material">;
+
+/** Mesh shading the geometry can bake in; layer materials (glass, …) apply on the node. */
+function meshShading(
+ material: MaterialType | undefined,
+): "lit" | "unlit" | "toon" | undefined {
+ return material === "lit" || material === "unlit" || material === "toon"
+ ? material
+ : undefined;
+}
+
+function primitiveNode(
+ prefix: string,
+ geometry: PrimitiveGeometryOptions,
+ o: Primitive3DNodeOptions,
+): AnimatableNode<Model3DNode> {
+ // Only defined keys, so equal shapes share one cached mesh.
+ const spec = Object.fromEntries(
+ Object.entries({
+ ...geometry,
+ color: o.color,
+ material: meshShading(o.material),
+ shininess: o.shininess,
+ roughness: o.roughness,
+ metallic: o.metallic,
+ }).filter(([, v]) => v !== undefined),
+ ) as unknown as PrimitiveGeometryOptions;
+ return Layer.model({
+ id: o.id ?? autoId(prefix),
+ modelData: getPrimitiveGeometry(spec),
+ // What the compositor rebuilds the mesh from when modelData did not
+ // survive (a spec sent as JSON).
+ primitive3d: spec,
+ is3D: true,
+ x: o.x ?? 0,
+ y: o.y ?? 0,
+ z: o.z ?? 0,
+ rotateX: o.rotateX ?? 0,
+ rotateY: o.rotateY ?? 0,
+ rotateZ: o.rotateZ ?? 0,
+ scale: o.scale ?? 1,
+ scaleX: o.scaleX ?? 1,
+ scaleY: o.scaleY ?? 1,
+ scaleZ: o.scaleZ ?? 1,
+ opacity: o.opacity ?? 1,
+ color: o.tint,
+ material: o.material,
+ shininess: o.shininess ?? 32,
+ roughness: o.roughness,
+ specularIntensity: o.specularIntensity ?? 0.5,
+ ambientIntensity: o.ambientIntensity ?? 1.0,
+ metallic: o.metallic,
+ twoSided: false,
+ startFrame: o.startFrame,
+ durationFrames: o.durationFrames,
+ });
+}
+
export type Shape3DContainer = AnimatableNode<BoxNode> & {
faces?: AnimatableNode<BoxNode>[];
items?: LayoutNode[];
@@ -746,6 +845,53 @@ export const Layer3D = {
}) as unknown as Shape3DContainer;
},
+ /**
+ * A solid box with rounded edges and corners, as one smooth-shaded mesh:
+ * cards, buttons, device bodies. `taper` below 1 narrows the top (-y)
+ * face, the shape of a keycap. Equal shapes share one GPU buffer.
+ */
+ roundedBox(options: RoundedBox3DOptions): AnimatableNode<Model3DNode> {
+ return primitiveNode(
+ "rounded-box",
+ {
+ type: "roundedBox",
+ width: options.width,
+ height: options.height,
+ depth: options.depth,
+ radius: options.radius,
+ segments: options.segments,
+ taper: options.taper,
+ },
+ options,
+ );
+ },
+
+ /** A UV sphere mesh. */
+ sphere(options: Sphere3DOptions): AnimatableNode<Model3DNode> {
+ return primitiveNode(
+ "sphere",
+ { type: "sphere", radius: options.radius, segments: options.segments },
+ options,
+ );
+ },
+
+ /** A capped cylinder, or a cone/frustum with different top and bottom radii. */
+ cylinder(options: Cylinder3DOptions): AnimatableNode<Model3DNode> {
+ return primitiveNode(
+ "cylinder",
+ {
+ type: "cylinder",
+ radius: options.radius,
+ radiusTop: options.radiusTop,
+ radiusBottom: options.radiusBottom,
+ height: options.height,
+ segments: options.segments,
+ openEnded: options.openEnded,
+ },
+ options,
+ );
+ },
+
/**
* Creates a 3D model node rendered natively with WebGPU mesh shaders.
*/
diff --git a/packages/webgpu-renderers/src/renderer3d/index.ts b/packages/webgpu-renderers/src/renderer3d/index.ts
index c7692fe0..190adcc0 100644
--- a/packages/webgpu-renderers/src/renderer3d/index.ts
+++ b/packages/webgpu-renderers/src/renderer3d/index.ts
@@ -2,6 +2,7 @@ export * from "./audio-mesh-deform-pipeline.js";
export * from "./glass-pipeline.js";
export * from "./mesh3d-pipeline.js";
export * from "./motion-blur-pipeline.js";
+export * from "./primitive-geometry.js";
export * from "./quad3d-pipeline.js";
export * from "./renderer3d.js";
export * from "./shadow-pipeline.js";
diff --git a/packages/webgpu-renderers/src/renderer3d/primitive-geometry.test.ts b/packages/webgpu-renderers/src/renderer3d/primitive-geometry.test.ts
new file mode 100644
index 00000000..e4f9cfb1
--- /dev/null
+++ b/packages/webgpu-renderers/src/renderer3d/primitive-geometry.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, it } from "vitest";
+import type { Model3DData } from "../loaders/types.js";
+import {
+ generatePrimitiveGeometry,
+ getPrimitiveGeometry,
+ type PrimitiveGeometryOptions,
+} from "./primitive-geometry.js";
+
+type V = [number, number, number];
+
+const sub = (a: V, b: V): V => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
+const cross = (a: V, b: V): V => [
+ a[1] * b[2] - a[2] * b[1],
+ a[2] * b[0] - a[0] * b[2],
+ a[0] * b[1] - a[1] * b[0],
+];
+const dot = (a: V, b: V) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+
+/**
+ * Every triangle must wind so its geometric normal points away from the
+ * solid's center (single-sided shading drops the others) and agree with
+ * its vertex normals.
+ */
+function expectOutwardSolid(model: Model3DData): void {
+ const mesh = model.meshes[0]!;
+ const p = mesh.positions;
+ const n = mesh.normals;
+ const at = (i: number): V => [p[i * 3]!, p[i * 3 + 1]!, p[i * 3 + 2]!];
+ const normalAt = (i: number): V => [n[i * 3]!, n[i * 3 + 1]!, n[i * 3 + 2]!];
+ let checked = 0;
+ for (let t = 0; t < mesh.indices.length; t += 3) {
+ const [i0, i1, i2] = [
+ mesh.indices[t]!,
+ mesh.indices[t + 1]!,
+ mesh.indices[t + 2]!,
+ ];
+ const a = at(i0);
+ const face = cross(sub(at(i1), a), sub(at(i2), a));
+ // Degenerate slivers (arc samples meeting at a pole or corner) say nothing.
+ if (Math.hypot(...face) < 1e-6) continue;
+ const centroid: V = [
+ (a[0] + at(i1)[0] + at(i2)[0]) / 3,
+ (a[1] + at(i1)[1] + at(i2)[1]) / 3,
+ (a[2] + at(i1)[2] + at(i2)[2]) / 3,
+ ];
+ expect(dot(face, centroid)).toBeGreaterThan(0);
+ expect(dot(face, normalAt(i0))).toBeGreaterThan(0);
+ checked++;
+ }
+ expect(checked).toBeGreaterThan(0);
+ for (let i = 0; i < n.length; i += 3) {
+ expect(Math.hypot(n[i]!, n[i + 1]!, n[i + 2]!)).toBeCloseTo(1, 4);
+ }
+}
+
+describe("3D primitive geometry", () => {
+ it("builds a rounded box to size, wound outward on all six faces", () => {
+ const model = generatePrimitiveGeometry({
+ type: "roundedBox",
+ width: 200,
+ height: 40,
+ depth: 120,
+ radius: 10,
+ segments: 4,
+ });
+ expect(model.bounds.size[0]).toBeCloseTo(200, 4);
+ expect(model.bounds.size[1]).toBeCloseTo(40, 4);
+ expect(model.bounds.size[2]).toBeCloseTo(120, 4);
+ expect(model.bounds.center).toEqual([0, 0, 0]);
+ expectOutwardSolid(model);
+ });
+
+ it("builds a sharp box when the radius is 0", () => {
+ const model = generatePrimitiveGeometry({
+ type: "roundedBox",
+ width: 10,
+ height: 10,
+ depth: 10,
+ });
+ // Six single-quad faces.
+ expect(model.meshes[0]!.indices.length).toBe(6 * 6);
+ expectOutwardSolid(model);
+ });
+
+ it("tapers the top (-y) face and tilts the side normals up", () => {
+ const model = generatePrimitiveGeometry({
+ type: "roundedBox",
+ width: 100,
+ height: 20,
+ depth: 100,
+ radius: 0,
+ taper: 0.8,
+ });
+ const { positions: p, normals: n } = model.meshes[0]!;
+ let topHalfWidth = 0;
+ let bottomHalfWidth = 0;
+ for (let i = 0; i < p.length; i += 3) {
+ if (p[i + 1]! < 0) topHalfWidth = Math.max(topHalfWidth, p[i]!);
+ else bottomHalfWidth = Math.max(bottomHalfWidth, p[i]!);
+ // A side vertex (|x| at its max) leans up: its normal has -y.
+ if (Math.abs(n[i]!) > 0.9) expect(n[i + 1]!).toBeLessThan(0);
+ }
+ expect(topHalfWidth).toBeCloseTo(40, 4);
+ expect(bottomHalfWidth).toBeCloseTo(50, 4);
+ expectOutwardSolid(model);
+ });
+
+ it("builds spheres and capped cylinders wound outward", () => {
+ expectOutwardSolid(
+ generatePrimitiveGeometry({ type: "sphere", radius: 50, segments: 24 }),
+ );
+ const cyl = generatePrimitiveGeometry({
+ type: "cylinder",
+ radiusTop: 20,
+ radiusBottom: 40,
+ height: 60,
+ segments: 24,
+ });
+ expect(cyl.bounds.size[1]).toBeCloseTo(60, 4);
+ expect(cyl.bounds.size[0]).toBeCloseTo(80, 4);
+ expectOutwardSolid(cyl);
+ });
+
+ it("bakes the color into the material", () => {
+ const model = generatePrimitiveGeometry({
+ type: "sphere",
+ radius: 1,
+ color: "#ff0000",
+ });
+ const material = Object.values(model.materials)[0]!;
+ expect(material.diffuseColor).toEqual([1, 0, 0, 1]);
+ });
+
+ it("hands equal shapes the same mesh, so they share one GPU buffer", () => {
+ const opts: PrimitiveGeometryOptions = {
+ type: "roundedBox",
+ width: 65,
+ height: 15,
+ depth: 65,
+ radius: 6,
+ };
+ const a = getPrimitiveGeometry(opts);
+ expect(getPrimitiveGeometry({ ...opts })).toBe(a);
+ expect(getPrimitiveGeometry({ ...opts, width: 66 })).not.toBe(a);
+ });
+});
diff --git a/packages/webgpu-renderers/src/renderer3d/primitive-geometry.ts b/packages/webgpu-renderers/src/renderer3d/primitive-geometry.ts
new file mode 100644
index 00000000..1dde6e3e
--- /dev/null
+++ b/packages/webgpu-renderers/src/renderer3d/primitive-geometry.ts
@@ -0,0 +1,368 @@
+import type { Material3D, Mesh3DData, Model3DData } from "../loaders/types.js";
+import { parseHexOrRgbColor } from "./text-extruder.js";
+
+/**
+ * Procedural solids built as real meshes (one draw call each), centered on
+ * the origin in the 3D world's convention: x right, y down, z away from a
+ * default camera. "Top" is therefore -y.
+ */
+interface PrimitiveSurface {
+ /** Diffuse color (hex or rgb()). Default white, so a node `color` tints it. */
+ color?: string;
+ material?: "lit" | "unlit" | "toon";
+ shininess?: number;
+ roughness?: number;
+ metallic?: number;
+}
+
+export interface RoundedBoxGeometryOptions extends PrimitiveSurface {
+ type: "roundedBox";
+ width: number;
+ height: number;
+ depth: number;
+ /** Corner and edge radius, clamped to half the smallest side. Default 0 (a sharp box). */
+ radius?: number;
+ /** Segments per rounded quarter (default 4). */
+ segments?: number;
+ /**
+ * Scale of the top (-y) face against the bottom along x and z: 0.9 draws
+ * a keycap-like frustum. Default 1.
+ */
+ taper?: number;
+}
+
+export interface SphereGeometryOptions extends PrimitiveSurface {
+ type: "sphere";
+ radius: number;
+ /** Segments around the equator (default 32); rings are half of it. */
+ segments?: number;
+}
+
+export interface CylinderGeometryOptions extends PrimitiveSurface {
+ type: "cylinder";
+ /** Radius of the top (-y) cap; defaults to `radius`. */
+ radiusTop?: number;
+ /** Radius of the bottom (+y) cap; defaults to `radius`. */
+ radiusBottom?: number;
+ radius?: number;
+ height: number;
+ /** Segments around (default 32). */
+ segments?: number;
+ /** Leave the caps off (a tube). */
+ openEnded?: boolean;
+}
+
+export type PrimitiveGeometryOptions =
+ | RoundedBoxGeometryOptions
+ | SphereGeometryOptions
+ | CylinderGeometryOptions;
+
+class MeshBuilder {
+ positions: number[] = [];
+ normals: number[] = [];
+ uvs: number[] = [];
+ indices: number[] = [];
+
+ vertex(p: number[], n: number[], uv: [number, number]): number {
+ this.positions.push(p[0]!, p[1]!, p[2]!);
+ this.normals.push(n[0]!, n[1]!, n[2]!);
+ this.uvs.push(uv[0], uv[1]);
+ return this.positions.length / 3 - 1;
+ }
+
+ /**
+ * Joins a (cols+1) x (rows+1) vertex grid that starts at `base` into
+ * quads. Front faces wind so that cross(row step, column step) points
+ * out; `flip` reverses that for grids laid out the other way round.
+ */
+ grid(base: number, cols: number, rows: number, flip = false): void {
+ for (let j = 0; j < rows; j++) {
+ for (let i = 0; i < cols; i++) {
+ const a = base + j * (cols + 1) + i;
+ const b = a + 1;
+ const c = a + cols + 1;
+ const d = c + 1;
+ if (flip) this.indices.push(a, b, c, b, d, c);
+ else this.indices.push(a, c, b, b, c, d);
+ }
+ }
+ }
+
+ build(name: string): Mesh3DData {
+ const count = this.positions.length / 3;
+ return {
+ id: `${name}-mesh`,
+ name,
+ positions: new Float32Array(this.positions),
+ normals: new Float32Array(this.normals),
+ uvs: new Float32Array(this.uvs),
+ indices:
+ count > 65535
+ ? new Uint32Array(this.indices)
+ : new Uint16Array(this.indices),
+ materialName: `${name}-material`,
+ };
+ }
+}
+
+function normalize(v: number[]): number[] {
+ const len = Math.hypot(v[0]!, v[1]!, v[2]!);
+ return len > 1e-12 ? [v[0]! / len, v[1]! / len, v[2]! / len] : [0, 0, 0];
+}
+
+/**
+ * 1D samples across a side of half-extent `e` whose ends round off with
+ * radius `r`: arc-spaced through each rounded zone, nothing in between, so
+ * the flat middle of a face is a single quad.
+ */
+function edgeSamples(e: number, r: number, segments: number): number[] {
+ if (r <= 0) return [-e, e];
+ const inner = e - r;
+ const out: number[] = [];
+ for (let i = 0; i <= segments; i++) {
+ out.push(-inner - r * Math.cos(((i / segments) * Math.PI) / 2));
+ }
+ for (let i = inner > 1e-9 ? 0 : 1; i <= segments; i++) {
+ out.push(inner + r * Math.sin(((i / segments) * Math.PI) / 2));
+ }
+ return out;
+}
+
+function roundedBox(o: RoundedBoxGeometryOptions, mb: MeshBuilder): void {
+ const hx = o.width / 2;
+ const hy = o.height / 2;
+ const hz = o.depth / 2;
+ const r = Math.max(0, Math.min(o.radius ?? 0, hx, hy, hz));
+ const seg = Math.max(1, Math.round(o.segments ?? 4));
+ const taper = o.taper ?? 1;
+ const ix = hx - r;
+ const iy = hy - r;
+ const iz = hz - r;
+ const sx = edgeSamples(hx, r, seg);
+ const sy = edgeSamples(hy, r, seg);
+ const sz = edgeSamples(hz, r, seg);
+
+ // Taper scales x and z linearly from 1 at the bottom (+y) to `taper` at
+ // the top (-y); normals follow through the inverse transpose of that map.
+ const slope = o.height > 0 ? (1 - taper) / o.height : 0;
+ const scaleAt = (y: number) => taper + slope * (y + hy);
+ const place = (surface: number[], faceNormal: number[]) => {
+ const inner = [
+ Math.max(-ix, Math.min(ix, surface[0]!)),
+ Math.max(-iy, Math.min(iy, surface[1]!)),
+ Math.max(-iz, Math.min(iz, surface[2]!)),
+ ];
+ let n =
+ r > 0
+ ? normalize([
+ surface[0]! - inner[0]!,
+ surface[1]! - inner[1]!,
+ surface[2]! - inner[2]!,
+ ])
+ : faceNormal;
+ if (n[0] === 0 && n[1] === 0 && n[2] === 0) n = faceNormal;
+ const p = [
+ inner[0]! + n[0]! * r,
+ inner[1]! + n[1]! * r,
+ inner[2]! + n[2]! * r,
+ ];
+ if (taper === 1) return { p, n };
+ const s = scaleAt(p[1]!);
+ return {
+ p: [p[0]! * s, p[1]!, p[2]! * s],
+ n: normalize([
+ n[0]! / s,
+ n[1]! - (p[0]! * slope * n[0]!) / s - (p[2]! * slope * n[2]!) / s,
+ n[2]! / s,
+ ]),
+ };
+ };
+
+ // Each face: a fixed axis at ±extent, and two in-plane axes with samples.
+ const faces: Array<{
+ axis: 0 | 1 | 2;
+ sign: 1 | -1;
+ u: 0 | 1 | 2;
+ v: 0 | 1 | 2;
+ }> = [
+ { axis: 2, sign: -1, u: 0, v: 1 }, // front (-z)
+ { axis: 2, sign: 1, u: 0, v: 1 }, // back (+z)
+ { axis: 0, sign: -1, u: 2, v: 1 }, // left
+ { axis: 0, sign: 1, u: 2, v: 1 }, // right
+ { axis: 1, sign: -1, u: 0, v: 2 }, // top (-y)
+ { axis: 1, sign: 1, u: 0, v: 2 }, // bottom
+ ];
+ const half = [hx, hy, hz];
+ const samples = [sx, sy, sz];
+ for (const f of faces) {
+ const us = samples[f.u]!;
+ const vs = samples[f.v]!;
+ const faceNormal = [0, 0, 0];
+ faceNormal[f.axis] = f.sign;
+ const base = mb.positions.length / 3;
+ for (let j = 0; j < vs.length; j++) {
+ for (let i = 0; i < us.length; i++) {
+ const surface = [0, 0, 0];
+ surface[f.axis] = f.sign * half[f.axis]!;
+ surface[f.u] = us[i]!;
+ surface[f.v] = vs[j]!;
+ const { p, n } = place(surface, faceNormal);
+ mb.vertex(p, n, [
+ (us[i]! / half[f.u]! + 1) / 2,
+ (vs[j]! / half[f.v]! + 1) / 2,
+ ]);
+ }
+ }
+ // cross(v axis, u axis) is +axis when (v, u) runs x→y→z→x; outward
+ // needs it along the face normal, so the other faces wind the other way.
+ const cyclic = (f.v + 1) % 3 === f.u;
+ mb.grid(base, us.length - 1, vs.length - 1, (cyclic ? 1 : -1) !== f.sign);
+ }
+}
+
+function sphere(o: SphereGeometryOptions, mb: MeshBuilder): void {
+ const seg = Math.max(3, Math.round(o.segments ?? 32));
+ const rings = Math.max(2, Math.round(seg / 2));
+ for (let j = 0; j <= rings; j++) {
+ const phi = (j / rings) * Math.PI;
+ for (let i = 0; i <= seg; i++) {
+ const theta = (i / seg) * Math.PI * 2;
+ const n = [
+ Math.sin(phi) * Math.cos(theta),
+ -Math.cos(phi),
+ Math.sin(phi) * Math.sin(theta),
+ ];
+ mb.vertex([n[0]! * o.radius, n[1]! * o.radius, n[2]! * o.radius], n, [
+ i / seg,
+ j / rings,
+ ]);
+ }
+ }
+ mb.grid(0, seg, rings);
+}
+
+function cylinder(o: CylinderGeometryOptions, mb: MeshBuilder): void {
+ const seg = Math.max(3, Math.round(o.segments ?? 32));
+ const rTop = o.radiusTop ?? o.radius ?? 50;
+ const rBottom = o.radiusBottom ?? o.radius ?? 50;
+ const hy = o.height / 2;
+ // Side normals lean by the cone's slope.
+ const lean = o.height > 0 ? (rBottom - rTop) / o.height : 0;
+ for (let j = 0; j <= 1; j++) {
+ const rr = j === 0 ? rTop : rBottom;
+ const y = j === 0 ? -hy : hy;
+ for (let i = 0; i <= seg; i++) {
+ const theta = (i / seg) * Math.PI * 2;
+ const c = Math.cos(theta);
+ const s = Math.sin(theta);
+ mb.vertex([c * rr, y, s * rr], normalize([c, -lean, s]), [i / seg, j]);
+ }
+ }
+ mb.grid(0, seg, 1);
+ if (o.openEnded) return;
+ for (const [y, rr, ny] of [
+ [-hy, rTop, -1],
+ [hy, rBottom, 1],
+ ] as const) {
+ if (rr <= 0) continue;
+ const center = mb.vertex([0, y, 0], [0, ny, 0], [0.5, 0.5]);
+ const ring = mb.positions.length / 3;
+ for (let i = 0; i <= seg; i++) {
+ const theta = (i / seg) * Math.PI * 2;
+ const c = Math.cos(theta);
+ const s = Math.sin(theta);
+ mb.vertex([c * rr, y, s * rr], [0, ny, 0], [(c + 1) / 2, (s + 1) / 2]);
+ }
+ for (let i = 0; i < seg; i++) {
+ // Wound to face -y on the top cap; the bottom cap turns over.
+ if (ny < 0) mb.indices.push(center, ring + i, ring + i + 1);
+ else mb.indices.push(center, ring + i + 1, ring + i);
+ }
+ }
+}
+
+/** Builds a procedural solid as a single-mesh Model3DData. */
+export function generatePrimitiveGeometry(
+ options: PrimitiveGeometryOptions,
+): Model3DData {
+ const mb = new MeshBuilder();
+ if (options.type === "roundedBox") roundedBox(options, mb);
+ else if (options.type === "sphere") sphere(options, mb);
+ else if (options.type === "cylinder") cylinder(options, mb);
+ else {
+ throw new Error(
+ `Unknown 3D primitive: ${(options as { type?: string }).type}`,
+ );
+ }
+
+ const name = options.type;
+ const mesh = mb.build(name);
+ const material: Material3D = {
+ name: `${name}-material`,
+ diffuseColor: parseHexOrRgbColor(options.color ?? "#ffffff"),
+ shading: options.material ?? "lit",
+ shininess: options.shininess ?? 32,
+ roughness: options.roughness,
+ metallic: options.metallic,
+ };
+
+ const min: [number, number, number] = [
+ Number.POSITIVE_INFINITY,
+ Number.POSITIVE_INFINITY,
+ Number.POSITIVE_INFINITY,
+ ];
+ const max: [number, number, number] = [
+ Number.NEGATIVE_INFINITY,
+ Number.NEGATIVE_INFINITY,
+ Number.NEGATIVE_INFINITY,
+ ];
+ const pos = mesh.positions;
+ for (let i = 0; i < pos.length; i += 3) {
+ for (let k = 0; k < 3; k++) {
+ const v = pos[i + k]!;
+ if (v < min[k]!) min[k] = v;
+ if (v > max[k]!) max[k] = v;
+ }
+ }
+ const size: [number, number, number] = [
+ max[0] - min[0],
+ max[1] - min[1],
+ max[2] - min[2],
+ ];
+ return {
+ name: `primitive-${name}`,
+ meshes: [mesh],
+ materials: { [material.name]: material },
+ animations: [],
+ bounds: {
+ min,
+ max,
+ center: [
+ (min[0] + max[0]) / 2,
+ (min[1] + max[1]) / 2,
+ (min[2] + max[2]) / 2,
+ ],
+ size,
+ boundingSphereRadius: Math.hypot(...size) / 2,
+ },
+ };
+}
+
+const primitiveCache = new Map<string, Model3DData>();
+
+/**
+ * Like generatePrimitiveGeometry, but identical options return the same
+ * Model3DData, so a hundred equal keycaps upload one vertex buffer.
+ */
+export function getPrimitiveGeometry(
+ options: PrimitiveGeometryOptions,
+): Model3DData {
+ const key = JSON.stringify(options);
+ let model = primitiveCache.get(key);
+ if (!model) {
+ model = generatePrimitiveGeometry(options);
+ if (primitiveCache.size > 512) primitiveCache.clear();
+ primitiveCache.set(key, model);
+ }
+ return model;
+}
diff --git a/plugins/framefields/skills/framefields-compose/SKILL.md b/plugins/framefields/skills/framefields-compose/SKILL.md
index bb50b02d..99cece90 100644
--- a/plugins/framefields/skills/framefields-compose/SKILL.md
+++ b/plugins/framefields/skills/framefields-compose/SKILL.md
@@ -98,6 +98,7 @@ All `Layer.*` builders return `AnimatableNode<T>` instances with chainable `.ani
| `Layer.camera(options)` | `"camera"` | 3D scene camera with FOV, lens rack focus, and orbital coordinates. |
| `Layer.light(options)` | `"light"` | 3D lighting primitive (`ambient`, `directional`, `point`, `spot`). |
| `Layer.model(options)` | `"model3d"` | 3D mesh loader (`.gltf`, `.glb`, `.obj`, `.fbx`, `.stl`, `.ply`). Supports skinning and audio deformation compute shaders. |
+| `Layer3D.roundedBox / sphere / cylinder(options)` | `"model3d"` | Procedural solid meshes, centered on `x`/`y`/`z` (y is down, so "top" is -y). `roundedBox`: `width`, `height`, `depth`, `radius`, `segments`, `taper` (top face scale, <1 for a keycap). `sphere`: `radius`. `cylinder`: `radius` or `radiusTop`/`radiusBottom`, `height`, `openEnded`. `color` is baked in; `tint` multiplies it and animates as the `color` prop. Equal shapes share one GPU buffer, so hundreds of copies are cheap. |
---
diff --git a/plugins/framefields/skills/framefields/SKILL.md b/plugins/framefields/skills/framefields/SKILL.md
index 76664c0e..4ed51691 100644
--- a/plugins/framefields/skills/framefields/SKILL.md
+++ b/plugins/framefields/skills/framefields/SKILL.md
@@ -253,7 +253,7 @@ Never go straight to a full video render. Rendering strictly requires a WebGPU-c
4. `npm run preview` when a person is watching: they play the film with sound before you export (see below).
5. `npm run render` once frames and motion look right.
-Show the user the frame PNGs or the grid before the full render. `framefields-render` covers pixel-probe tests, render QA (`renderVideo({ qa })`), and diagnosing blank frames.
+Show the user the frame PNGs or the grid before the full render. `framefields-render` covers pixel-probe tests, render QA (`renderVideo({ qa })`), and diagnosing blank frames. If you suspect an issue or defect in the engine itself, file an issue at https://github.com/gatewai-dev/framefields.
### Live preview
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 22dbcd44..ad9c1f8a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -375,6 +375,25 @@ importers:
specifier: ^5.8.3
version: 5.9.3
+ examples/26_mac_keyboard:
+ dependencies:
+ framefields:
+ specifier: workspace:*
+ version: link:../../packages/framefields
+ devDependencies:
+ '@framefields/tsconfig':
+ specifier: workspace:*
+ version: link:../../packages/tsconfig
+ '@types/node':
+ specifier: ^24.1.0
+ version: 24.10.14
+ tsx:
+ specifier: ^4.20.3
+ version: 4.21.0
+ typescript:
+ specifier: ^5.8.3
+ version: 5.9.3
+
nodes/node-apply-lut:
dependencies:
'@framefields/core':