Skip to content

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

fix(3d): gradient backgrounds draw behind 3D scenes; remove specs

okanasl29a49cbccbb9
diff --git a/.changeset/scene-gradient-background.md b/.changeset/scene-gradient-background.md
new file mode 100644
index 00000000..18d3642d
--- /dev/null
+++ b/.changeset/scene-gradient-background.md
@@ -0,0 +1,5 @@
+---
+"framefields": patch
+---
+
+A 3D scene box's gradient or image `background` draws behind its scene. The scene's own composition took the background string as its clear color, and a gradient is not a color, so the scene cleared to black.
diff --git a/.gitignore b/.gitignore
index 7ff4e1bf..3eb66bdb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -101,3 +101,6 @@ packages/framefields/README.md
# Local examples, not tracked
examples/34_spatial_styling/
examples/35_robot_uprising/
+
+# Local showcase film (not committed)
+examples/37_lumen/
diff --git a/packages/compositions/src/program/sequence.ts b/packages/compositions/src/program/sequence.ts
index 8cb21fa7..9483d4d9 100644
--- a/packages/compositions/src/program/sequence.ts
+++ b/packages/compositions/src/program/sequence.ts
@@ -3,7 +3,6 @@
* @module @framefields/compositions/program/sequence
*
* Multi-Scene Timeline Orchestration, Camera Choreography & Carrier Match Cuts.
- * Complies with specs/cinematic-sequencing.ts.
*/
import { assertFps } from "@framefields/core";
diff --git a/packages/compositions/src/program/to-virtual-media.ts b/packages/compositions/src/program/to-virtual-media.ts
index f381f4d3..366c3dcb 100644
--- a/packages/compositions/src/program/to-virtual-media.ts
+++ b/packages/compositions/src/program/to-virtual-media.ts
@@ -19,6 +19,7 @@ import {
getActiveMediaMetadata,
MediaTimeRemapInputSchema,
type MediaTimeSignalRemap,
+ parseCssColor,
type ResolvedMediaTimeRemap,
type VirtualMediaData,
validateMediaTimeRemap,
@@ -271,6 +272,34 @@ function nodeToVirtualMedia(
const frames =
nodeDuration ?? Math.round(((compDurationMs ?? 10000) / 1000) * fps);
const durationMs = (frames / fps) * 1000;
+ // A plain color clears the scene; any other background (a gradient,
+ // an image) is the scene's first layer, so its 3D passes see it.
+ const background =
+ typeof node.background === "string" ? node.background : undefined;
+ const clear =
+ background && parseCssColor(background) ? background : undefined;
+ if (background && !clear) {
+ children.unshift(
+ nodeToVirtualMedia(
+ {
+ kind: "box",
+ id: `${node.id ?? "scene"}-background`,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: node.width as number,
+ height: node.height as number,
+ background,
+ } as LayoutNode,
+ resolveMedia,
+ fps,
+ 0,
+ compDurationMs,
+ frames,
+ resolveSignal,
+ ),
+ );
+ }
media = {
metadata: {
width: node.width as number,
@@ -286,9 +315,7 @@ function nodeToVirtualMedia(
mode: "Video",
dataType: "Video",
volume: 1,
- ...(typeof node.background === "string" && {
- backgroundColor: node.background,
- }),
+ ...(clear && { backgroundColor: clear }),
},
children,
} as unknown as VirtualMediaData;
diff --git a/packages/framefields/src/scene-isolation-render.test.ts b/packages/framefields/src/scene-isolation-render.test.ts
index 935c4a15..184a4d64 100644
--- a/packages/framefields/src/scene-isolation-render.test.ts
+++ b/packages/framefields/src/scene-isolation-render.test.ts
@@ -87,4 +87,49 @@ describe("3D scenes in a sequence", () => {
expect(both.r).toBeGreaterThan(50);
expect(both.b).toBeGreaterThan(50);
});
+
+ it("paints a gradient background behind its 3D scene", async () => {
+ // The scene's own composition used to take the gradient string as its
+ // clear color, which is not a color, and cleared to black.
+ const comp = new Composition({
+ width: 200,
+ height: 200,
+ fps: 30,
+ durationFrames: 1,
+ backgroundColor: "#000000",
+ });
+ comp.add(
+ Layer.box({
+ width: 200,
+ height: 200,
+ background: "linear-gradient(180deg, #ff0000 0%, #ff0000 100%)",
+ children: [
+ Layer.camera({
+ x: 100,
+ y: 100,
+ z: -400,
+ targetX: 100,
+ targetY: 100,
+ targetZ: 0,
+ }),
+ Layer3D.sphere({
+ x: 100,
+ y: 100,
+ z: 0,
+ radius: 20,
+ color: "#ffffff",
+ }),
+ ],
+ }),
+ );
+ const png = await comp.renderFrame({ frame: 0 });
+ const img = await loadImage(png);
+ const canvas = new Canvas(img.width, img.height);
+ const ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0);
+ const [r, g, b] = ctx.getImageData(10, 10, 1, 1).data;
+ expect(r).toBeGreaterThan(240);
+ expect(g).toBeLessThan(15);
+ expect(b).toBeLessThan(15);
+ });
});
diff --git a/plugins/framefields/skills/framefields-compose/SKILL.md b/plugins/framefields/skills/framefields-compose/SKILL.md
index 39f397cb..8216efdd 100644
--- a/plugins/framefields/skills/framefields-compose/SKILL.md
+++ b/plugins/framefields/skills/framefields-compose/SKILL.md
@@ -622,7 +622,7 @@ stage.animate(LayerAnimation.create().signal("y", world.impact, { multiplier: 14
- **Keyframes instead of signals:** `world.bakeKeyframes({ tolerance: 0.25 })` in place of `simulate()` writes plain, simplified linear keyframes (editable, plain JSON).
- **3D:** `Physics.world3d` takes `Layer3D` solids (`roundedBox`, `sphere`, `cylinder`, `capsule`, `torus`, `ring`, `prism`, `pyramid`, `polyhedron`, `icosahedron`, `icosphere`, `shard`) and models (convex hull of the mesh); same options with 3-vectors, `world.hinge(a, b, at, axis)`, `world.walls({ width, height, depth })`. Use `Layer3D.instances({ count: bodies.length, mesh: Layer3D.shard({ radius: 24 }), bodies, emissiveBySpeed: { speedThreshold: 200, maxSpeed: 1200, color: "#ff5511", intensity: 4 } })` to render hundreds of physics bodies in a single GPU draw call.
- **Destruction:** `const broken = world.fracture(statue, { cells: 48, impactPoint: [x, y, z], fractureFrame: "onImpact" | frame, explosionSpeed: 300, interiorColor: "#e9dcc0" })` cuts a `Layer3D` solid, extruded text or model (with `modelData`) into Voronoi pieces. It looks whole (a fixed collider of its own shape) until the frame or the first body that hits it, which carries on through, then the pieces fall as rigid bodies (`broken.pieces`, `broken.frame` after simulating). The node changes in place: add it as usual. One draw call per material; pieces crowd around `impactPoint`. An animated layer (position, rotation) collides along its path while whole and breaks where it is, its pieces carrying its motion; inside a 3D group the pieces fly in the group's space, like other bodies. Its scale must not animate (rigid pieces). Needs `simulate()` (not `live()`).
-- **Timing:** signals are on the composition clock. In a scene that starts at frame `S`, pass `startFrame: S` to the world. Before it and after `frames` the signals hold their first/last value. Add every body, joint and force before `simulate()` (or before reading any signal): the world then locks.
+- **Timing:** signals are on the clock of the composition that reads them. In a flat scene that starts at frame `S`, pass `startFrame: S` to the world. A 3D scene box (a box holding its own `Layer.camera`) renders on its own clock, so a world for its bodies starts at the scene's frame 0 (no `startFrame`). Before it and after `frames` the signals hold their first/last value. Add every body, joint and force before `simulate()` (or before reading any signal): the world then locks.
- **Feel:** gravity 2400 px/s² reads snappy on a 1080p canvas; `pixelsPerMeter` (100) scales how heavy things feel. Raise `substeps` (4) for tall stacks or thin, fast bodies.
- Install note: physics uses the optional dependency `@dimforge/rapier2d-deterministic-compat` / `rapier3d-deterministic-compat` (installed by default with framefields).
diff --git a/specs/3d-shards.md b/specs/3d-shards.md
deleted file mode 100644
index 358dec95..00000000
--- a/specs/3d-shards.md
+++ /dev/null
@@ -1,443 +0,0 @@
-# Spec: 3D Shards, Instanced 3D Mesh Swarm & Floor Reflections
-
-## Goal
-
-Extend Framefields' 3D engine with general-purpose primitives and GPU pipelines forfaceted polyhedral geometry (`Layer3D.shard`), high-count 3D mesh/particle simulations (`Layer3D.swarm`), instanced 3D rigid-body rendering (`Layer3D.instances`), and glossy ground reflections (`floor` on `Layer.environment`).
-
-All additions are first-class, reusable engine primitives that compose with existing `Camera3D`, `Light3D`, `Layer.environment` (GGX PBR + IBL + HDR bloom + fog + shadows), `Physics.world3d` (Rapier), `Signal`, `comp.vision`, and `CompositorProgramSchema`.
-
----
-
-## Architectural Pillars
-
-1. **`Layer3D.shard(options)`** — Procedural flat-faceted convex polyhedron primitive in `primitive-geometry.ts` and `Layer3D`.
-2. **`Layer3D.instances(options)`** — Single-draw-call hardware-instanced 3D mesh batch node (`Model3DNode` / `Renderer3D`) for rendering hundreds or thousands of 3D meshes driven by `Physics.world3d` or procedural callbacks without layout-tree overhead.
-3. **`Layer3D.swarm(options)`** — GPU compute-simulated 3D particle & mesh-shard system rendered natively inside `Renderer3D` (participating in 3D camera projection, depth buffer, GGX PBR lighting, shadow receiving, and HDR bloom) with 3D forces (curl noise, attractors, vortex/swirl, floor friction, and `comp.vision` silhouette push) and dynamic kinetic shading (`emissiveBySpeed`, `emissiveByContact`, secondary spark emission).
-4. **`Environment.floor` (Planar Glossy Floor Reflection)** — Scene-wide ground plane reflection in `Renderer3D` / `Layer.environment` with anisotropic roughness blur and Fresnel falloff.
-
----
-
-## 1. Procedural Faceted Polyhedron Primitive: `Layer3D.shard`
-
-### Motivation
-`primitive-geometry.ts` currently provides smooth primitives (`roundedBox`, `sphere`, `cylinder`). Authors need a general-purpose faceted geometric primitive for crystals, low-poly debris, fractured glass, asteroids, Voronoi-like shards, and abstract faceted motion graphics.
-
-### Geometry Algorithm (`packages/webgpu-renderers/src/renderer3d/primitive-geometry.ts`)
-Add `ShardGeometryOptions` (`type: "shard"`) to `PrimitiveGeometryOptions`:
-
-```ts
-export interface ShardGeometryOptions extends PrimitiveSurface {
- type: "shard";
- /** Approximate bounding radius (or half-extents when aspect/scale is used). Default 50. */
- radius?: number;
- /** Optional non-uniform half-extents [hx, hy, hz]; overrides `radius` per axis. */
- size?: [number, number, number];
- /** Number of clipping half-space planes that carve the convex polyhedron (6..48). Default 14. */
- facets?: number;
- /** Deterministic PRNG seed for plane normals and depths. Default 1. */
- seed?: number;
- /** How unevenly planes cut toward the center, 0..0.85 (0 = regular polyhedron, 0.5 = jagged shard). Default 0.35. */
- irregularity?: number;
- /** Bevel / chamfer fraction along edges, 0..0.3 (0 = razor-sharp flat facets). Default 0. */
- bevel?: number;
-}
-```
-
-#### Construction (Deterministic Convex Half-Space Clipping)
-1. Start from a bounding cube of half-extents `[hx, hy, hz]` (derived from `size ? [size[0]/2, size[1]/2, size[2]/2] : [radius, radius, radius]`).
-2. Generate `facets` quasi-uniformly distributed unit normals $\hat{n}_k$ on the sphere using a seeded Fibonacci lattice perturbed by PCG hash jitter (`seed`, `irregularity`).
-3. For each plane $k$, choose signed distance $d_k = r_k \cdot (1 - \text{irregularity} \cdot \text{rnd}(k, \text{seed}))$ where $r_k$ is the support radius along $\hat{n}_k$.
-4. Iteratively clip the convex polygon soup against each half-space $\hat{n}_k \cdot \mathbf{x} \le d_k$ (Sutherland–Hodgman 3D convex polyhedron clipping):
- - Clip each existing polygon face against the plane.
- - Collect the intersection loop vertices on the clipping plane, sort them counter-clockwise around $\hat{n}_k$, and add the new cap polygon face.
-5. **Recenter & Normalize**:
- - Compute the centroid of the resulting polyhedron and shift all vertices so the mesh origin is `[0, 0, 0]`. Rescale so the bounding box matches the requested `radius` / `size`.
-6. **Flat-Faceted Normal & UV Generation**:
- - Emit separate vertices per face (no normal averaging across sharp edges) so every facet has a crisp, flat geometric normal $\hat{n}_{\text{face}}$ that catches specular and environment highlights cleanly.
- - Compute planar tangent-space UVs `[u, v]` per face in `[0, 1]`.
-7. **Caching & Rapier Integration**:
- - Cached via `getPrimitiveGeometry(options)` by JSON key (identical `(radius, facets, seed, irregularity)` share one `GPUMeshBuffers` allocation).
- - In `Physics.world3d` (`packages/framefields/src/physics/world3d.ts`), `colliderShape3D` automatically falls through to `hull()` (`meshPoints(t.modelData)`), giving every `Layer3D.shard` an exact Rapier 3D `convexHull` collider out of the box.
-
-### Public SDK (`packages/framefields/src/shapes3d.ts`)
-```ts
-export type Shard3DOptions = Primitive3DNodeOptions &
- Omit<ShardGeometryOptions, "type" | "color" | "material">;
-
-Layer3D.shard(options: Shard3DOptions): AnimatableNode<Model3DNode>
-```
-Supports all `Primitive3DNodeOptions` (`material: "lit" | "unlit" | "toon" | "glass" | "acrylic" | "frosted" | "metallic"`, `roughness`, `metallic`, `emissive`, `emissiveIntensity`, `castShadow`, `wireframe`, `tint`).
-
----
-
-## 2. Hardware-Instanced 3D Meshes: `Layer3D.instances`
-
-### Motivation
-Currently, rendering $N$ 3D meshes requires $N$ `Model3DNode` items in `layout`, $N$ model matrices computed on the CPU and uploaded to $N$ uniform buffers from `BufferPool`, and $N$ separate `pass.drawIndexed` calls. For $N \ge 200$ (e.g., a `Physics.world3d` simulation of 500 shards or an architectural grid of 1,000 elements), layout/schema/draw-call overhead dominates.
-
-### Renderer3D Instancing (`packages/webgpu-renderers/src/renderer3d/mesh3d-pipeline.ts`)
-Extend `Mesh3DPipeline` with an instanced draw path:
-
-#### Instance Storage Buffer Layout (`64 bytes` = `4 × vec4<f32>` per instance)
-```wgsl
-struct InstanceData {
- posScale : vec4<f32>, // xyz = world position, w = uniform scale (or pack non-uniform scale)
- quat : vec4<f32>, // xyzw = unit rotation quaternion
- color : vec4<f32>, // rgba = per-instance linear/sRGB color multiplier
- emissive : vec4<f32>, // rgb = per-instance emissive color, w = emissiveIntensity + variant bits
-};
-```
-- Bound as `@group(1) @binding(4) var<storage, read> instances : array<InstanceData>;` (with a 1-element dummy buffer bound when `useInstancing == 0`, honoring the WGSL rule that every declared binding is statically used in `vs_main`).
-- In `vs_main`: when `model.params.w > 0.5` (instanced mode), transform `localPos` and `localNorm` by `instances[instanceIndex].quat` and `instances[instanceIndex].posScale` before applying `model.modelMatrix`, and pass `instances[instanceIndex].color` and `instances[instanceIndex].emissive` to the fragment shader via `VertexOutput`.
-- Works seamlessly with:
- - Shadow map pass (`pipelineShadow` also reads `instances[instanceIndex]` so all instances cast shadows in a single instanced draw call).
- - MSAA, Depth of Field (`linearDepth` MRT), and HDR Bloom (`hdr` MRT).
- - Multi-variant meshes: if `variants: Model3DData[]` (e.g. 8 seeded `Layer3D.shard` meshes) are supplied, instances are bucketed by `variantIndex = i % variants.length`, issuing at most `variants.length` instanced draw calls (`drawIndexed(indexCount, instanceCount)`).
-
-### Public SDK (`Layer3D.instances`)
-```ts
-export interface InstanceTransform3D {
- x: number;
- y: number;
- z: number;
- /** Euler degrees [rx, ry, rz] or unit quaternion [qx, qy, qz, qw]. */
- rotation?: [number, number, number] | [number, number, number, number];
- scale?: number | [number, number, number];
- color?: string | [number, number, number, number];
- emissive?: string | [number, number, number];
- emissiveIntensity?: number;
-}
-
-export interface Instances3DOptions extends Surface3DOptions {
- id?: string;
- /** One mesh node/primitive, or an array of mesh variants distributed across instances. */
- mesh: AnimatableNode<Model3DNode> | Array<AnimatableNode<Model3DNode>>;
- /** Count of instances when driven by `instanceAt` or `bodies`. */
- count?: number;
- /** Bind directly to Physics.world3d rigid bodies. */
- bodies?: readonly PhysicsBody3D[];
- /** Per-frame callback `(index, frame, fps) => InstanceTransform3D` (or Float32Array batch). */
- instanceAt?: (index: number, frame: number, fps: number) => InstanceTransform3D;
- /** Optional speed/impact-to-emissive mapping when bound to `bodies`. */
- emissiveBySpeed?: { color: string | string[]; maxSpeed: number; intensity?: number };
- emissiveByImpact?: { color: string; intensity?: number };
- material?: MaterialType;
- roughness?: number;
- metallic?: number;
- specularIntensity?: number;
- startFrame?: number;
- durationFrames?: number;
-}
-```
-
----
-
-## 3. GPU 3D Swarm & Shard Simulation: `Layer3D.swarm`
-
-### Motivation
-`Layer.particles` (`nodes/node-particles`) is a 2D screen-space particle system (`pos: vec2<f32>`). It does not know about `Camera3D`, 3D depth occlusion, 3D lighting, or 3D mesh orientations.
-To simulate thousands of 3D shards and secondary sparks with real-time 3D forces, floor friction, angular tumbling, and velocity/contact-driven HDR emission inside the 3D scene pass, we introduce `Layer3D.swarm` (backed by `Swarm3DPipeline` in `packages/webgpu-renderers/src/renderer3d/swarm3d-pipeline.ts`).
-
-### GPU State & Compute Simulation (`Swarm3DPipeline`)
-
-#### Particle State Struct (`64 bytes` per 3D particle in `GPUBuffer`)
-```wgsl
-struct SwarmParticle3D {
- pos : vec3<f32>, // world-space position (px, y down)
- age : f32, // seconds alive
- vel : vec3<f32>, // world-space velocity (px/s)
- life : f32, // total lifetime (seconds; <= 0 means dead)
- quat : vec4<f32>, // unit orientation quaternion
- angVel : vec3<f32>, // angular velocity (rad/s)
- heat : f32, // smoothed kinetic/friction heat [0..1+]
- scale : f32, // size multiplier (with jitter)
- variant : u32, // mesh variant index (0..N-1) or spark flag (0xFFFFFFFFu)
- seed : u32, // per-particle deterministic random id
- contact : f32, // floor/surface contact factor [0..1] this step
-};
-```
-
-#### Deterministic Stepping & Scrubbing Snapshots
-Follows the proven architecture of `nodes/node-particles`:
-- Steps forward on the GPU with `substeps` per frame (default `2`) and optional `prewarm` seconds before `startFrame`.
-- Saves GPU buffer snapshots every `24` frames (`SNAPSHOT_EVERY = 24`, up to `64` snapshots) so scrubbing backward in preview or non-sequential frame rendering restores the nearest snapshot and replays at most 23 frames.
-
-#### 3D Forces & Collision Solver in `SIM_3D_WGSL`
-1. **Emitters (`emitter`)**:
- - Shapes in 3D: `"point"`, `"box"`, `"sphere"`, `"shell"`, `"ring"`, `"disc"`, `"cone"`.
- - Position `[x, y, z]` and `rate` accept `PhysicsDriver` (number, `Signal`, or `(frame) => number`) for moving 3D emitters and beat bursts.
-2. **3D Curl Noise (`noise`)**:
- - True 3D divergence-free curl of a 3D FBM vector potential $\nabla \times \mathbf{\Psi}(\mathbf{p} / \text{scale} + \mathbf{v}_{\text{time}} t)$ for organic 3D turbulence.
-3. **3D Attractors & Vortex / Swirl Fields (`attractors`, `vortex`)**:
- - Point/sphere attractors & repellers in 3D: `{ x, y, z, strength, radius }` (up to 8, drivers supported).
- - **3D Vortex / Orbit (`vortex`)**: `{ x, y, z, axis: [ax, ay, az], swirl, pull, axial, radius, falloff }`:
- - Tangential acceleration around `axis` (`swirl` px/s²), radial inward/outward pull toward the axis or center (`pull` px/s²), and axial lift (`axial` px/s²). This drives cohesive 3D cyclones, orbital streams, and sweeping swarms without hand-keyed paths.
-4. **Floor Collision, Sliding Friction & Angular Tumble (`floor`)**:
- - Plane at `y = floor.y` (or arbitrary normal `[nx, ny, nz]`).
- - When `p.pos.y + radius > floor.y`:
- - Project out of floor; reflect normal velocity with `bounce` (restitution).
- - Apply Coulomb/exponential tangential **sliding friction**: $\mathbf{v}_{\parallel} \leftarrow \mathbf{v}_{\parallel} \cdot \exp(-\mu_{\text{friction}} \cdot \Delta t)$.
- - **Friction-induced torque**: sliding along the floor induces angular velocity $\boldsymbol{\omega} \leftarrow \boldsymbol{\omega} + (\hat{n} \times \mathbf{v}_{\parallel}) / r$, making shards physically roll and tumble when scraping the ground.
- - **Friction heat accumulation**: `p.heat` increases proportionally to $|\Delta \mathbf{v}_{\text{friction}}|$ and floor contact speed, and decays exponentially over `heatDecay` seconds (`p.heat *= exp(-dt / heatDecay)`).
-5. **Performer 3D Silhouette Push (`push`)**:
- - Reuses `PersonTrack.silhouetteGrid(frame)` from `comp.vision`, pushing 3D particles within a configurable depth slab `zRange: [zMin, zMax]` away from the performer's 2D silhouette gradient and imparting `heat` on impact.
-6. **Quaternion Integration**:
- - Updates `p.quat = normalize(p.quat + 0.5 * dt * quatMul(vec4(p.angVel, 0.0), p.quat))` with `angularDrag`.
-
-#### Dual-Mode Rendering in `Renderer3D` (Shards + Secondary Sparks)
-A `Layer3D.swarm` can render:
-1. **3D Mesh Shards**: Instanced draw of `mesh` variants (default: 8 seeded `Layer3D.shard` geometries) using `Mesh3DPipeline`'s instanced path.
- - Base material uses scene lighting & `Layer.environment` PBR (`color`, `roughness`, `metallic`).
- - **Dynamic Emissive Modulation**: Each shard's emissive radiance is computed in the shader from:
- - `emissiveBySpeed`: ramps emissive color & HDR intensity by `length(p.vel) / maxSpeed`.
- - `emissiveByHeat`: ramps emissive color & HDR intensity by `p.heat` (floor friction + high-acceleration turns + vision push).
- - Color ramp supports multi-stop gradients (e.g. `["#1a161b", "#a8006b", "#ff1aff", "#ffffff"]` with `emissiveIntensity: 6`), feeding directly into `Renderer3D`'s HDR bloom attachment (`hdrTexture`).
-2. **Secondary Friction / Trail Sparks (`sparks`)**:
- - Optional companion buffer (or partitioned tail of the particle buffer) spawned where parent shards have high `heat` or `contact > 0` (or high speed).
- - Rendered in the same 3D pass as camera-facing 3D capsules/streaks stretched along `cam.viewProjMatrix * vel`, depth-tested against the shards and writing into both display color and HDR bloom.
-
-### Public SDK (`packages/framefields/src/swarm3d.ts`)
-```ts
-export interface Swarm3DOptions extends Surface3DOptions {
- id?: string;
- startFrame?: number;
- durationFrames?: number;
- /** Maximum 3D mesh particles alive at once (default 2000, up to 100000). */
- max?: number;
- seed?: number;
- /**
- * Geometry drawn per particle:
- * - `"shard"` (default: 8 procedural shard variants)
- * - `{ type: "shard", variants?: number, facets?: number, irregularity?: number }`
- * - `"sphere" | "roundedBox" | "cylinder"`
- * - `AnimatableNode<Model3DNode> | Array<AnimatableNode<Model3DNode>>`
- */
- mesh?:
- | "shard"
- | "sphere"
- | "roundedBox"
- | "cylinder"
- | { type: "shard"; variants?: number; facets?: number; irregularity?: number; bevel?: number }
- | AnimatableNode<Model3DNode>
- | Array<AnimatableNode<Model3DNode>>;
- /** Particle radius/scale in px at birth -> death (default [18, 12]). */
- size?: number | [number, number];
- sizeJitter?: number;
- fade?: [number, number];
- emitter?: {
- shape?: "point" | "box" | "sphere" | "shell" | "ring" | "disc";
- x?: PhysicsDriver;
- y?: PhysicsDriver;
- z?: PhysicsDriver;
- width?: number;
- height?: number;
- depth?: number;
- radius?: number;
- rate?: PhysicsDriver;
- bursts?: Array<{ frame: number; count: number }>;
- };
- lifetime?: number | [number, number];
- speed?: number | [number, number];
- direction?: [number, number, number];
- spread?: number;
- angularSpeed?: number | [number, number];
- angularDrag?: PhysicsDriver;
- gravity?: PhysicsDriver | [PhysicsDriver, PhysicsDriver, PhysicsDriver];
- drag?: PhysicsDriver;
- noise?: {
- strength?: PhysicsDriver;
- scale?: number;
- speed?: number;
- };
- attractors?: Array<{
- x: PhysicsDriver;
- y: PhysicsDriver;
- z: PhysicsDriver;
- strength: PhysicsDriver;
- radius?: number;
- }>;
- vortex?: {
- x?: PhysicsDriver;
- y?: PhysicsDriver;
- z?: PhysicsDriver;
- axis?: [number, number, number];
- /** Tangential swirl acceleration (px/s²). */
- swirl?: PhysicsDriver;
- /** Radial pull toward the vortex center/axis (px/s²). */
- pull?: PhysicsDriver;
- /** Axial acceleration along `axis` (px/s²). */
- axial?: PhysicsDriver;
- radius?: number;
- };
- push?: {
- person: PersonTrack;
- strength?: PhysicsDriver;
- sweep?: PhysicsDriver;
- zRange?: [number, number];
- };
- floor?: {
- y: number;
- bounce?: number;
- /** Sliding friction damping (0 = ice, 3 = rough stone). Default 1.5. */
- friction?: PhysicsDriver;
- /** How strongly floor scraping & sharp acceleration build up `heat`. Default 1.0. */
- heatGain?: number;
- /** Seconds for friction/acceleration heat to cool down. Default 0.45. */
- heatDecay?: number;
- };
- /** Base surface color (default "#232026"). */
- color?: string | string[];
- roughness?: number;
- metallic?: number;
- /** Dynamic HDR emission driven by particle speed and/or friction heat. */
- heat?: {
- /** Source driver: `"friction"` | `"speed"` | `"both"` (default `"both"`). */
- source?: "friction" | "speed" | "both";
- /** Speed (px/s) that reaches full heat=1 when source includes speed (default 900). */
- maxSpeed?: number;
- /** Emissive color ramp from cool (0) to hot (1). */
- color: string | string[];
- /** Peak HDR emissiveIntensity at heat = 1 (feeds bloom when > 2.5). Default 5.0. */
- intensity?: PhysicsDriver;
- /** Power curve shaping the heat ramp (default 1.6). */
- curve?: number;
- };
- /** Optional secondary fine sparks spawned from hot/scraping shards in 3D. */
- sparks?: {
- max?: number;
- rate?: number;
- /** Minimum shard heat [0..1] required to shed sparks (default 0.25). */
- threshold?: number;
- size?: number | [number, number];
- lifetime?: number | [number, number];
- speed?: number | [number, number];
- stretch?: number;
- color?: string | string[];
- intensity?: number;
- };
- substeps?: number;
- prewarm?: number;
-}
-```
-
----
-
-## 4. Glossy Reflective Floor in `Renderer3D` (`Environment.floor`)
-
-### Motivation
-In 3D motion graphics and VFX shots (product stages, glowing shards on dark polished stone/acrylic, neon typography over wet ground), a glossy floor that reflects the 3D scene above it—especially bright HDR emissives—grounds the entire shot in 3D space.
-
-### Design (`packages/webgpu-renderers/src/math3d/environment3d.ts` & `Renderer3D`)
-Extend `Environment3DOptions` and `LightNode` (`lightType: "environment"`) with an optional `floor` configuration:
-
-```ts
-export interface Environment3DFloor {
- /** World Y coordinate of the floor plane (px, y down). */
- y: number;
- /** Base floor surface color (default "#08070a"). */
- color?: string;
- /** Mirror reflectivity at normal incidence / Fresnel scale, 0..1 (default 0.35). */
- reflectivity?: number;
- /** Surface roughness 0..1: controls anisotropic vertical/horizontal reflection blur (default 0.35). */
- roughness?: number;
- /** Reflection fade-out distance from the floor plane in world Y px (default 900). */
- fadeDistance?: number;
- /** Optional overall opacity of the floor plane, 0..1 (default 1; 0 draws only the additive reflection over background). */
- opacity?: number;
-}
-```
-
-### Rendering Technique (Planar Reflection + Anisotropic Roughness Blur)
-Why planar reflection instead of screen-space reflection (SSR)?
-- In `Renderer3D`, the scene geometry (`pending3DItems`: meshes, quads, slugs, and `swarm` instances) is already collected in `flush3DPass`.
-- SSR fails whenever an object near the floor occludes what is behind it or when camera pitch changes, and requires G-buffer normals.
-- **Planar Reflection Pass** in `Renderer3D`:
- 1. Construct the reflected `Camera3D` pose by mirroring `camera.eye` and `camera.target` across the horizontal plane $y = y_{\text{floor}}$ (and flipping the Y scale / winding or clipping vertices with $y > y_{\text{floor}}$ via a clip distance check in the shader).
- 2. Render the reflected 3D items at **half resolution** (`width / 2`, `height / 2`) into a pooled temporary reflection texture (`rgba16float` when bloom/HDR is active, so HDR emissive shards reflect at full HDR radiance before tone mapping).
- 3. Apply a **separable 2-pass roughness blur** (`FloorReflectionPipeline`) where vertical blur radius is stretched relative to horizontal blur ($\sigma_y \approx 3.5 \cdot \sigma_x \cdot \text{roughness}$), matching the physical elongated reflection lobes of a grazing-angle rough floor.
- 4. Composite the floor plane in the 3D pass (or immediately before bloom) with Fresnel grazing boost and vertical distance attenuation $\exp(-\Delta y / \text{fadeDistance})$, writing into both display and `hdr` targets so hot reflections also bloom naturally.
-
----
-
-## 5. Schema, Compiler & Lint Integration
-
-To satisfy `CompositorProgramSchema` (`.strict()`) and all engine invariants:
-
-1. **`packages/compositions/src/program/schema.ts`**:
- - Add `EnvironmentFloorSchema` to `LightNodeSchema` (`floor?: EnvironmentFloor`).
- - Extend `Model3DNodeSchema` with `instances3d?: unknown` and `swarm3d?: unknown` (similar to `primitive3d` and `text3dOptions`) so `comp.toSpec()` serializes and validates cleanly.
- - Add `"shard"` to `PrimitiveGeometryOptions` validation/types.
-2. **`packages/compositions/src/program/lint.ts`**:
- - Warn if `Layer3D.swarm` uses `heat.intensity > 2.5` without an active `Layer.environment({ bloom: true })` when bloom is expected, or if `floor.y` is outside the camera frustum.
-3. **`nodes/node-compositor/SKILL.md` & `plugins/framefields/skills/framefields-compose/SKILL.md`**:
- - Document `Layer3D.shard`, `Layer3D.instances`, `Layer3D.swarm`, and `Layer.environment(..., { floor })`.
- - Keep `packages/compositions/src/program/skillmd-check.test.ts` green.
-
----
-
-## 6. Implementation Plan & Phases
-
-### Phase 1: `Layer3D.shard` Procedural Geometry & Physics Collider
-- **Files**:
- - `packages/webgpu-renderers/src/renderer3d/primitive-geometry.ts`
- - `packages/framefields/src/shapes3d.ts`
- - `packages/framefields/src/physics/world3d.ts`
-- **Deliverables**:
- - Deterministic 3D half-space convex polyhedron clipper (`shard(o, mb)`).
- - Flat-faceted normals, UVs, centered bounds, and `getPrimitiveGeometry` caching.
- - `Layer3D.shard(options)` builder exported on `Layer3D`.
- - Unit & visual tests in `packages/webgpu-renderers/src/renderer3d/primitive-geometry.test.ts` verifying watertight convex geometry, outward normals, deterministic seed output, and Rapier `Physics.world3d` hull collision.
-
-### Phase 2: Hardware-Instanced 3D Meshes (`Mesh3DPipeline` + `Layer3D.instances`)
-- **Files**:
- - `packages/webgpu-renderers/src/shaders/mesh3d.ts`
- - `packages/webgpu-renderers/src/renderer3d/mesh3d-pipeline.ts`
- - `packages/webgpu-renderers/src/renderer3d/shadow-pipeline.ts`
- - `packages/webgpu-renderers/src/renderer3d/renderer3d.ts`
- - `packages/compositions/src/program/schema.ts`
- - `nodes/node-compositor/src/renderers/webgpu-renderer.ts`
- - `packages/framefields/src/shapes3d.ts`
-- **Deliverables**:
- - Storage buffer `@group(1) @binding(4)` for per-instance `(posScale, quat, color, emissive)` in `mesh3d.wgsl` and shadow depth shader.
- - `r3d.drawMesh3DInstanced(...)` supporting multi-variant mesh buckets in 1 draw call per variant.
- - `Layer3D.instances({ mesh, count, bodies, instanceAt, emissiveBySpeed })`.
- - Unit & GPU render tests verifying 1,000 instanced shards with per-instance color/emissive and shadow casting.
-
-### Phase 3: GPU 3D Swarm & Secondary Sparks (`Swarm3DPipeline` + `Layer3D.swarm`)
-- **Files**:
- - `packages/webgpu-renderers/src/renderer3d/swarm3d-pipeline.ts` (new)
- - `packages/webgpu-renderers/src/renderer3d/renderer3d.ts`
- - `packages/compositions/src/program/schema.ts`
- - `nodes/node-compositor/src/renderers/webgpu-renderer.ts`
- - `packages/framefields/src/swarm3d.ts` (new)
- - `packages/framefields/src/index.ts`
-- **Deliverables**:
- - WGSL 3D compute simulator (`SIM_3D_WGSL`): 3D emitters, 3D curl noise, 3D attractors, 3D vortex (`swirl`, `pull`, `axial`), floor plane collision with Coulomb sliding friction, friction-induced angular torque, heat accumulation/decay, and `comp.vision` silhouette push.
- - Snapshot ring (`SNAPSHOT_EVERY = 24`) for deterministic scrubbing.
- - Instanced 3D shard rendering with `heat` colour/emissive ramp into `Renderer3D`'s PBR + HDR bloom pass.
- - Secondary 3D spark emission and velocity-stretched 3D capsule rendering in the same pass.
- - Headless GPU tests verifying deterministic stepping, snapshot restore, floor friction heat buildup, and HDR bloom output.
-
-### Phase 4: Glossy Floor Reflection (`Environment.floor`)
-- **Files**:
- - `packages/webgpu-renderers/src/math3d/environment3d.ts`
- - `packages/webgpu-renderers/src/renderer3d/floor-reflection-pipeline.ts` (new)
- - `packages/webgpu-renderers/src/renderer3d/renderer3d.ts`
- - `packages/compositions/src/program/schema.ts`
- - `nodes/node-compositor/src/renderers/webgpu-renderer.ts`
-- **Deliverables**:
- - Half-res mirrored-camera planar reflection pass in `Renderer3D` (clipped above `floor.y`).
- - Anisotropic vertical/horizontal roughness blur and Fresnel-weighted floor composite writing to both display and HDR bloom buffers.
- - GPU render tests verifying reflections of emissive 3D shards and bloom integration.
-
-### Phase 5: Docs, Skills & End-to-End Verification
-- **Files**:
- - `nodes/node-compositor/SKILL.md`
- - `plugins/framefields/skills/framefields-compose/SKILL.md`
-- **Verification Ladder**:
- 1. `tsc --noEmit -p .` across all modified packages.
- 2. `CompositorProgramSchema.parse(comp.toSpec())` validation tests.
- 3. Vitest unit and headless WebGPU tests (`pnpm --filter @framefields/webgpu-renderers test`, `pnpm --filter framefields test`).
- 4. `renderFrame` & `renderFrameGrid` visual verification with pixel probes confirming shard facets, vortex motion, friction-driven HDR magenta/white emission, secondary sparks, and anisotropic floor reflections.
- 5. `pnpm exec biome check --write` and `pnpm run check:plugins`.
-
diff --git a/specs/ue58-engine-roadmap.md b/specs/ue58-engine-roadmap.md
deleted file mode 100644
index 3459dba1..00000000
--- a/specs/ue58-engine-roadmap.md
+++ /dev/null
@@ -1,419 +0,0 @@
-# Spec: Framefields Next-Gen 3D, Material, Lighting & Procedural Engine Roadmap (UE 5.8+ Parity)
-
-## Goal
-
-Bridge the visual fidelity, procedural world-building, material expressiveness, and character/crowd animation gap between **Unreal Engine 5.8+** and **Framefields**—while staying 100% true to Framefields' architecture:
-
-- **Deterministic, code-first `(composition, frame) -> pixels`** in headless Node.js on native WebGPU (Dawn).
-- **Zero editor bloat**: every capability is exposed as a declarative, type-safe TypeScript builder on `Layer`, `Layer3D`, `Lighting`, `Physics`, or `Environment3DOptions`, serializable through `CompositorProgramSchema` (`packages/compositions/src/program/schema.ts`), and linted by `comp.lint()` (`packages/compositions/src/program/lint.ts`).
-- **Composable with the existing stack**: `Camera3D`, `Light3D` (`@group(3)` storage lights + `texture_depth_2d_array` shadow maps), `Mesh3DPipeline`, `Swarm3DPipeline`, `Physics.world3d` (Rapier), `Signal`, `AudioSignal`, and `comp.vision`.
-
----
-
-## Architectural Pillars & Roadmap Overview
-
-| Phase | Pillar | UE 5.8+ Inspiration | Framefields Surface & Pipeline |
-|---|---|---|---|
-| **Phase 1** | **Volumetric Fog, Light Shafts & Area Lights** | Volumetric Fog Froxels + MegaLights Area Lights | `Layer.environment(..., { volumetricFog })` (`VolumetricFogPipeline`) + `Layer.rectLight(...)` (`lightType: "rect"` LTC shading + dual-paraboloid/omni point shadows in `@group(3)`) |
-| **Phase 2** | **Substrate-Grade Multi-Lobe PBR Materials & HDRI** | Substrate (`Clearcoat`, `Anisotropy`, `Subsurface`, `Sheen`, `Triplanar`) + HDR Skylight | Extended `SurfaceParams` (`SURFACE_PARAMS_FLOATS`), `mesh3d.wgsl` multi-lobe BRDF, `triplanar` UV-less mapping, and `.hdr` / `.exr` equirectangular IBL prefiltering (`HdrEnvironmentLoader`) |
-| **Phase 3** | **Lumen-Lite: Screen-Space GI & Reflections (SSR / SSGI)** | Lumen Lite (60fps screen-space + depth-hierarchy GI & reflections) | `SsrGiPipeline` in `packages/webgpu-renderers/src/renderer3d/` consuming `GeometryResolvePipeline` depth/normals + hierarchical Z (Hi-Z) raymarching |
-| **Phase 4** | **Mesh Terrain, SDF Booleans & PCG Surface Scatter** | UE 5.8 Mesh Terrain + PCG Framework + Procedural Vegetation | `Layer3D.terrain(...)`, `Layer3D.sdf(...)` (Dual Contouring / Marching Cubes CSG), and `Layer3D.scatter(...)` (Poisson-disk surface instancing + GPU vertex wind sway) |
-| **Phase 5** | **Character Rigging, IK, Pose Blending & VAT Crowds** | Control Rig Physics + Direct Mesh Controls + MetaHuman Crowds | Multi-clip animation blending, Two-Bone IK & spring bones in `GltfLoader`/`Renderer3D`, plus Vertex Animation Textures (VAT) in `Layer3D.instances` for 10,000+ skinned crowd agents |
-| **Phase 6** | **Voronoi Destruction & Per-Vertex Motion Blur** | Chaos Destruction + Per-Bone Velocity Motion Blur | `Physics.fracture(mesh, options)` (3D Voronoi cell shattering into `Physics.world3d` + `Layer3D.instances`) and previous-frame skinned/morphed vertex velocity in `MotionBlurPipeline` |
-
----
-
-## Phase 1: Volumetric Atmosphere, God Rays & Area Lights
-
-### 1.1 Motivation
-Currently, `Environment3DFog` (`packages/webgpu-renderers/src/math3d/environment3d.ts`) is an analytic distance fade (`mix(surfaceColor, fog.color, fogFactor)`) evaluated only on opaque/transparent surfaces. Spotlights and directional lights cannot cast volumetric shafts ("god rays") through empty air, and point/rect lights cannot cast shadows or rectangular softbox highlights on products.
-
-### 1.2 Volumetric Fog & Light Shafts (`VolumetricFogPipeline`)
-Add `volumetricFog` to `Environment3DOptions`:
-
-```ts
-export interface Environment3DVolumetricFog {
- /** Scattering albedo tint (CSS color). Default "#ffffff". */
- color?: string;
- /** Global extinction/density coefficient (0..1). Default 0.025. */
- density?: number;
- /** Henyey-Greenstein phase anisotropy (-0.9..0.9; >0 = strong forward scattering / god rays). Default 0.55. */
- anisotropy?: number;
- /** Exponential height falloff in world Y px (y down). Optional. */
- heightFalloff?: { baseY: number; falloff: number };
- /** 3D animated curl/FBM density noise for patchy theatrical smoke/clouds. */
- noise?: { scale?: number; strength?: number; speed?: number; velocity?: [number, number, number] };
- /** Raymarch steps per pixel (16..96). Default 48. */
- steps?: number;
- /** Max raymarch distance in world px. Default 6000. */
- maxDistance?: number;
-}
-```
-
-#### GPU Pipeline (`packages/webgpu-renderers/src/renderer3d/volumetric-fog-pipeline.ts`)
-- Runs after opaque 3D geometry + `GeometryResolvePipeline` (which resolves single-sample linear depth) and before `BloomPipeline` / tone mapping so hot light shafts contribute to HDR bloom.
-- **Half-resolution Temporal/Interleaved Raymarch + Bilateral Upsample**:
- 1. For each pixel, reconstruct world-space ray from camera eye to `min(sceneLinearDepth, maxDistance)`.
- 2. Jitter start offset along the ray using Interleaved Gradient Noise (IGN) seeded deterministically by `(pixelXY, frame)` to eliminate banding at 32–48 steps.
- 3. At each step $\mathbf{p}_k$, evaluate local density $\sigma_t(\mathbf{p}_k)$ (base density $\times$ height falloff $\times$ 3D simplex/FBM noise).
- 4. Loop over `@group(3) @binding(3) var<storage, read> directLights : array<DirectLight>`:
- - Evaluate light attenuation (directional, point, spot cone) and Henyey-Greenstein phase function $P(\cos\theta, g)$.
- - Sample `@group(3) @binding(1) var shadowMaps : texture_depth_2d_array` for shadow-casting lights (`shadowParams0.w > 0.5`) so occluders carve sharp volumetric shadow shafts.
- 5. Accumulate in-scattered radiance $\mathbf{L}_{\text{scatter}}$ and transmittance $T = \exp(-\int \sigma_t \, ds)$.
- 6. Depth-aware bilateral upsample onto the linear HDR scene target: $\mathbf{L}_{\text{out}} = \mathbf{L}_{\text{scene}} \cdot T + \mathbf{L}_{\text{scatter}}$.
-
-### 1.3 Rect Area Lights & Omnidirectional Point Shadows
-Extend `LightKind` in `packages/webgpu-renderers/src/math3d/light3d.ts`:
-
-```ts
-export type LightKind = "ambient" | "directional" | "point" | "spot" | "rect";
-
-export interface RectLight3DOptions extends Light3DOptions {
- lightType: "rect";
- /** Width of the rectangular emitter in world px. Default 400. */
- width?: number;
- /** Height of the rectangular emitter in world px. Default 200. */
- height?: number;
- /** Whether the rect light emits from both sides. Default false. */
- twoSided?: boolean;
-}
-```
-
-#### WGSL Shading (`mesh3d.ts` / `quad3d.ts`)
-- Pack `typeVal = 4.0` for `"rect"` lights; store `width`, `height`, and right/up tangent basis vectors in `DirectLight` (`spotParams` + unused padding floats in the 40-float `DirectLight` record).
-- Evaluate **Linearly Transformed Cosines (LTC)** (or analytic closest-point representative sphere/rectangle approximation with horizon clipping) for GGX specular + Lambertian diffuse, producing true rectangular softbox reflections on curved product surfaces.
-- **Omnidirectional Point Light Shadows**:
- - For `point` lights with `castShadow: true`, allocate 2 layers in the existing `shadowMaps : texture_depth_2d_array` using **Dual-Paraboloid Shadow Mapping** (front hemisphere $+Z$ and back hemisphere $-Z$), requiring only 2 layers per point light instead of 6 cubemap faces and fitting cleanly into the existing `texture_depth_2d_array` architecture.
-
-**Status (implemented):** `renderer3d/volumetric-fog-pipeline.ts` raymarches at half resolution with interleaved-gradient jitter seeded by pixel and frame, height falloff, FBM noise with wind, the Henyey-Greenstein phase and shadow-map visibility per light, then upsamples bilaterally on depth into the HDR scene before bloom. Rect lights are `lightType: "rect"` (`Layer.rectLight`), shaded by representative points (closest point on the rectangle for diffuse, the point along the reflection vector for specular, both with horizon handling), not LTC; the spec allowed either. Deviation: point-light shadows are six faces in the shared `texture_depth_2d_array` (a cube's layout, 1024 px), not dual-paraboloid, which avoids paraboloid warping on low-poly casters at the cost of four more layers. Lint: `volumetric_fog_without_lights`.
-
----
-
-## Phase 2: Substrate-Grade Multi-Lobe PBR Materials & Real HDRI Environments
-
-### 2.1 Motivation
-UE 5.8's Substrate material system unifies automotive clearcoat, brushed metal anisotropy, skin/wax subsurface scattering, cloth sheen, and thin-film iridescence. Meanwhile, product and studio films frequently need real `.hdr` / `.exr` studio panoramas and UV-less triplanar projection for procedural meshes (`Layer3D.shard`, `Layer3D.extrude`, `Layer3D.terrain`).
-
-### 2.2 Multi-Lobe `SurfaceParams` (`packages/webgpu-renderers/src/renderer3d/surface-params.ts`)
-Extend `SurfaceParams` and `SURFACE_PARAMS_FLOATS` (from `20` to `32` floats = `8 × vec4<f32>`):
-
-```ts
-export interface SurfaceParams {
- // Existing fields: roughness, metallic, emissive, emissiveIntensity, castShadow, toon, outline
- /** Clearcoat layer intensity 0..1 (automotive paint, lacquered plastic, wet surfaces). Default 0. */
- clearcoat?: number;
- /** Roughness of the clearcoat layer 0..1. Default 0.08. */
- clearcoatRoughness?: number;
- /** Anisotropy strength -1..1 (brushed aluminum, vinyl grooves, satin hair). Default 0. */
- anisotropy?: number;
- /** Anisotropy tangent rotation in degrees 0..360. Default 0. */
- anisotropyRotation?: number;
- /** Subsurface scattering / wrap translucency 0..1 (skin, wax, marble, leaves, gummies). Default 0. */
- subsurface?: number;
- /** Subsurface scattering bleed color (CSS color; defaults to warm shift of base color). */
- subsurfaceColor?: string | Color | [number, number, number];
- /** Cloth / velvet micro-fiber sheen intensity 0..1. Default 0. */
- sheen?: number;
- /** Sheen tint color (CSS color). Default "#ffffff". */
- sheenColor?: string | Color | [number, number, number];
- /** Thin-film soap/oil/holo iridescence strength 0..1 and film thickness in nm (200..800). */
- iridescence?: number | { intensity?: number; thickness?: number; ior?: number };
- /** World-space triplanar texture projection (eliminates UV stretching on procedural/extruded meshes). */
- triplanar?: boolean | { scale?: number; sharpness?: number };
-}
-```
-
-#### WGSL Multi-Lobe BRDF (`packages/webgpu-renderers/src/shaders/mesh3d.ts`)
-1. **Clearcoat Lobe**: Secondary isotropic GGX lobe with $F_0 = 0.04$ (IOR 1.5), roughness $\alpha_c = \text{clearcoatRoughness}^2$, attenuating the base substrate energy by $(1 - F_c \cdot \text{clearcoat})$.
-2. **Anisotropic GGX**: Stretch microfacet roughness along tangent $\mathbf{t}$ and bitangent $\mathbf{b}$ rotated by `anisotropyRotation`: $\alpha_t = \alpha (1 + \text{aniso})$, $\alpha_b = \alpha (1 - \text{aniso})$.
-3. **Subsurface Approximation**: Burley screen-free wrap diffuse + back-lit thickness transmission (sampling the light's shadow map depth thickness $d = z_{\text{surface}} - z_{\text{blocker}}$ when available, plus view-dependent back-scatter $\max(0, -\mathbf{v} \cdot (\mathbf{l} + \mathbf{n} \cdot \text{distortion}))^p \cdot \text{subsurfaceColor}$).
-4. **Charlie Sheen Lobe**: Estevez–Kulla (`Charlie`) retro-reflective grazing lobe for fabrics and velvet.
-5. **Thin-Film Iridescence**: Belcour airy-phase spectral interference shifting $F(\cos\theta)$ by optical path difference $2 n_{\text{film}} d \cos\theta_t$.
-6. **Triplanar Mapping**: When `triplanar` is active, sample albedo/normal/roughness maps along $(yz, xz, xy)$ world planes blended by $|\mathbf{n}_{\text{world}}|^{\text{sharpness}}$.
-
-**Status (implemented):** `renderer3d/surface-params.ts` packs clearcoat, anisotropy (with rotation), subsurface, sheen (with roughness), iridescence (thickness, film IOR) and triplanar (scale, sharpness) into the shared surface block, read by meshes, 3D layer planes and Slug text alike; glTF materials with the matching Khronos extensions feed the same lobes. Triplanar samples every map (base color, normal, metal-roughness, occlusion, emissive). Deviation: subsurface is an energy-conserving per-channel wrap (each channel's light reaches past the terminator by how far it scatters) plus view-dependent back-scatter; it does not read thickness from the shadow maps. Lint: `pbr_without_environment` covers `roughness`, `metallic`, `clearcoat` and `anisotropy`.
-
-### 2.3 Equirectangular `.hdr` / `.exr` IBL (`HdrEnvironmentLoader`)
-Extend `Layer.environment(presetOrPath, options)` to accept a file path (`"assets/hdri/studio_small.hdr"`):
-- Decode Radiance `.hdr` (RGBE) in pure TypeScript (`packages/webgpu-renderers/src/loaders/hdr-loader.ts`).
-- On first upload, run a one-shot WebGPU compute pass to:
- 1. Convert equirectangular `rgba16float` into a mipmapped cubemap (`256×256×6`).
- 2. Convolve GGX prefiltered specular mip chain (`mip 0..6` mapped to `roughness 0..1`).
- 3. Project diffuse irradiance into L2 Spherical Harmonics (`9 × vec4<f32>`).
-- Bound in `@group(3)` so any scene can switch between zero-asset procedural studio presets and real captured HDRIs with a single string change.
-
-**Status (implemented):** `renderer3d/hdr-environment.ts` prefilters on the GPU (Karis split-sum, filtered importance sampling, 256 samples) into an `rgba16float` cube whose face is a quarter of the panorama width (8..256) with up to 7 mips (roughness `m / (mips - 1)`). SH projection runs on the CPU from a ≤256-wide copy (`projectIrradianceSh`) and rides in `LightsUniforms.envSh`. `.exr` is decoded by `loaders/exr-loader.ts` (scanline or tiled, NONE/RLE/ZIPS/ZIP/PIZ/PXR24, HALF/FLOAT/UINT), checked against files written by the reference OpenEXR library; lossy B44/DWA/HTJ2K are rejected with a clear error.
-
----
-
-## Phase 3: Lumen-Lite — Screen-Space Reflections (SSR) & Diffuse GI (SSGI)
-
-### 3.1 Motivation
-Planar floor reflection (`FloorReflectionPipeline`) only reflects across a single flat horizontal plane `y = floor.y`. Vertical walls, curved metallic objects, wet streets, and adjacent diffuse surfaces do not reflect or bounce light from nearby geometry or emissive neon signs.
-
-### 3.2 `SsrGiPipeline` (`packages/webgpu-renderers/src/renderer3d/ssr-gi-pipeline.ts`)
-Add `gi` and `ssr` options to `Environment3DOptions`:
-
-```ts
-export interface Environment3DSsrOptions {
- /** Max reflection intensity 0..1. Default 0.85. */
- intensity?: number;
- /** Max roughness that traces screen-space rays (0..1). Default 0.6. */
- maxRoughness?: number;
- /** Surface thickness threshold in world px before a ray passes behind an occluder. Default 120. */
- thickness?: number;
- /** Hi-Z march steps (16..64). Default 32. */
- steps?: number;
-}
-
-export interface Environment3DGiOptions {
- /** Indirect diffuse bounce strength 0..4. Default 1.0. */
- intensity?: number;
- /** Screen-space gather radius in world px. Default 400. */
- radius?: number;
- /** Rays per pixel (4..16). Default 6. */
- samples?: number;
-}
-```
-
-#### GPU Architecture
-1. **Depth Mip Pyramid (Hi-Z)**:
- - After `GeometryResolvePipeline` produces single-sample `linearDepth` and `worldNormal` textures, a compute pass generates a min-depth mip chain (`Hi-Z`, 6 levels).
-2. **Hi-Z Screen-Space Reflections (SSR)**:
- - Half-res compute pass marches reflection rays $\mathbf{r} = \text{reflect}(-\mathbf{v}, \mathbf{n})$ (jittered by GGX VNDF lobe for `roughness > 0.05`) through the Hi-Z pyramid, skipping empty space in $O(\log N)$ steps and falling back smoothly to the studio/HDRI environment at screen edges.
-3. **Screen-Space Bent-Normal Diffuse GI (SSGI)**:
- - Upgrading `SsaoPipeline` (`packages/webgpu-renderers/src/renderer3d/ssao-pipeline.ts`) into a combined **GTAO + Bent-Normal + 1-Bounce Color Bleed** pass:
- - While horizon-scanning depth slices around each pixel, sample the direct-lit HDR color buffer at visible horizon hits, accumulating indirect diffuse irradiance $\mathbf{E}_{\text{indirect}}$ and bent normal $\mathbf{n}_{\text{bent}}$.
- - Edge-preserving spatial denoise (normal + depth bilateral filter) composites indirect diffuse + specular before bloom and tone mapping.
-
-**Status (implemented):** `renderer3d/ssr-gi-pipeline.ts`. Deviations from the plan above, each for determinism or correctness: (1) SSR and GI run between two forward passes (a `radiance` pass writing pre-exposure, unfogged radiance plus the nearest-sample geometry buffer, then an `apply` pass), so the traced light enters each material's own environment terms (`screenIndirectAt` in `lighting3d.ts`) before tone mapping and fog: no material G-buffer and every Substrate lobe stays correct. (2) No GGX VNDF ray jitter: glossy surfaces cone-sample a premultiplied radiance pyramid at their lobe's footprint, which is noise-free and frame-to-frame stable without TAA. (3) Both trace at full resolution. (4) The Hi-Z holds min and max depth, so rays skip cells they pass wholly in front of or wholly behind (beyond `thickness`); `steps` budgets cell advances and level changes are free. Hits are classified by the hit pixel's tangent plane (a crossing) before falling back to `thickness`, which only applies once the ray has been in front of the scene (no self-hits off convex rims). (5) The shading pass pools each pixel's 3×3 neighbors' rays on the same surface, weighted by confidence, which resolves the holes and seams single rays leave. GI is a cosine-weighted horizon scan (visible band `sin²b − sin²a` per surface) with fixed interleaved-gradient rotation and a separable depth/normal bilateral blur; `SsaoPipeline` is left unused. The `ssr`-without-environment lint is moot since both options live on the environment.
-
----
-
-## Phase 4: Procedural Terrain, SDF Booleans & PCG Surface Scatter
-
-### 4.1 Motivation
-UE 5.8's headline world-building features are **Mesh Terrain** (caves, overhangs, cliffs beyond 2.5D heightfields) and **PCG** (rule-driven surface scattering). In Framefields, bringing these to `Layer3D` turns 20 lines of TypeScript into rich landscapes, organic boolean sculptures, and populated worlds.
-
-### 4.2 `Layer3D.terrain(options)`
-Add procedural terrain generation to `packages/webgpu-renderers/src/renderer3d/primitive-geometry.ts` and `packages/framefields/src/shapes3d.ts`:
-
-```ts
-export interface Terrain3DOptions extends Primitive3DNodeOptions {
- width: number;
- depth: number;
- /** Peak-to-trough vertical relief in world px. Default 300. */
- height?: number;
- /** Grid subdivisions along X and Z (e.g. [128, 128]). Default [128, 128]. */
- segments?: [number, number];
- /** Multi-octave FBM/ridged-multifractal noise parameters. */
- noise?: {
- seed?: number;
- scale?: number;
- octaves?: number;
- persistence?: number;
- lacunarity?: number;
- /** "fbm" (rolling hills) | "ridged" (sharp mountain crests) | "terrace" (stepped plateaus). */
- ridgeMode?: "fbm" | "ridged" | "terrace";
- terraceSteps?: number;
- };
- /** Optional 3D overhang/arch warp displacement amplitude in px (UE 5.8 Mesh Terrain style). */
- overhangWarp?: number;
- /** Optional custom height function `(u: number, v: number) => number` in [0, 1]. */
- heightFn?: (u: number, v: number) => number;
- /** Automatic vertex-color biome splatting by altitude and slope. */
- colorByElevation?: {
- lowColor: string;
- midColor?: string;
- highColor: string;
- cliffColor?: string;
- /** Slope cosine below which `cliffColor` blends in (default 0.65). */
- cliffThreshold?: number;
- };
- flatShaded?: boolean;
-}
-```
-- Generates vertex colors (`COLOR_0`) from elevation and surface normal slope (`n.y`), which `Mesh3DPipeline` already multiplies with base material properties—giving multi-material snow/rock/grass/sand terrains in a single draw call with zero texture assets.
-- Integrates with `Physics.world3d` via Rapier's `trimesh` / `heightfield` collider so rigid bodies and `Layer3D.swarm` particles roll down valleys and collide with ridges.
-
-### 4.3 `Layer3D.sdf(options)` — Signed Distance Field & CSG Boolean Meshing
-Allow authoring smooth boolean CSG shapes and organic metaballs meshed via Surface Nets / Dual Contouring:
-
-```ts
-export type SdfPrimitive =
- | { op?: "union" | "subtract" | "intersect"; smoothness?: number; shape: "sphere"; center?: [number, number, number]; radius: number }
- | { op?: "union" | "subtract" | "intersect"; smoothness?: number; shape: "box"; center?: [number, number, number]; size: [number, number, number]; radius?: number }
- | { op?: "union" | "subtract" | "intersect"; smoothness?: number; shape: "cylinder" | "capsule" | "torus"; center?: [number, number, number]; radius: number; height?: number; tube?: number }
- | { op?: "union" | "subtract" | "intersect"; smoothness?: number; shape: "gyroid"; scale: number; thickness: number };
-
-export interface Sdf3DOptions extends Primitive3DNodeOptions {
- /** List of SDF primitives combined in order via smooth/hard CSG operations (`smin` / `smax`). */
- primitives: SdfPrimitive[];
- /** Bounding volume [width, height, depth] in world px. */
- bounds: [number, number, number];
- /** Voxel grid resolution (16..128). Default 64. */
- resolution?: number;
-}
-```
-- Evaluates the composite SDF on a 3D grid and extracts a smooth, watertight triangle mesh with analytic gradient normals $\nabla f(\mathbf{x}) / |\nabla f(\mathbf{x})|$, cached in `getPrimitiveGeometry`.
-
-### 4.4 `Layer3D.scatter(options)` — Declarative PCG Surface Scattering & Wind
-Build directly on `Layer3D.instances` to scatter thousands of rocks, trees, crystals, or buildings across any `Layer3D` surface or `terrain`:
-
-```ts
-export interface Scatter3DOptions extends Omit<Instances3DOptions, "count" | "instanceAt"> {
- /** Target surface mesh (`Layer3D.terrain(...)` or any `Model3DNode`) to scatter onto. */
- surface: AnimatableNode<Model3DNode>;
- /** Number of instances to place (or Poisson-disk `minDistance` in px). */
- count: number;
- minDistance?: number;
- seed?: number;
- /** Filter candidate surface triangles by slope angle (degrees, e.g. [0, 35]) and Y altitude range. */
- slopeRange?: [number, number];
- elevationRange?: [number, number];
- /** Align instance Y axis to surface normal (`1` = full normal alignment, `0` = stay vertical). Default 0.3. */
- alignToNormal?: number;
- /** Random uniform scale range `[min, max]` and random Y-axis yaw. */
- scaleRange?: [number, number];
- randomYaw?: boolean;
- /** Optional spline/circle exclusion zones where density drops to 0 (e.g. clearing a road or stage). */
- exclude?: Array<{ x: number; z: number; radius: number; falloff?: number }>;
- /** Procedural GPU/CPU wind sway applied per instance (`frequency`, `amplitudeDeg`, `waveScale`). */
- wind?: { amplitudeDeg?: number; frequency?: number; direction?: [number, number]; waveScale?: number };
-}
-```
-- Samples surface triangles weighted by area, filters by `slopeRange` / `elevationRange` / `exclude`, enforces Poisson-disk spacing via a spatial hash grid, and outputs an `Instances3DNode` rendered in 1 GPU draw call per mesh variant.
-
-**Status (implemented):** `renderer3d/terrain-geometry.ts`, `sdf-geometry.ts`, `scatter.ts` (pure, deterministic, unit-tested for watertightness and placement), `math3d/noise.ts` (seeded improved Perlin), SDK `framefields/src/procedural3d.ts`, compositor `renderers/procedural3d.ts`, schemas in `compositions/src/program/procedural-schema.ts`. Deviations and additions: (1) Terrain's valley floor sits at the node's y and the field is normalized so `height` is the exact relief; the sheet closes into a solid block (`base`), so it is watertight. `heightFn` is sampled into `heights` (the spec stays JSON); the node carries `heightAt` / `normalAt` / `elevationAt`, exact on the mesh's own triangles, for standing any other layer on the ground. (2) `overhangWarp` pushes steep faces sideways along their downhill direction by altitude-varying 3D noise (folds, not caves; caves belong to `Layer3D.sdf`). (3) SDF meshing is Surface Nets with topological (not geometric) winding; every primitive may carry `color`, blended by the smooth min/max weight, and `rotation`; the field is clipped to `bounds` so the mesh always closes. Gyroids use a conservative distance estimate. (4) Scatter runs in the compositor from the surface node's spec (so loaded model files work as surfaces), cached per scatter; `elevationRange` is normalized 0..1 over the surface's vertical extent; instances stand on their variant's base (`sink` adjusts). `.points()` exposes the placement in the SDK. (5) Wind is a `wind` option on any model node, bent in the mesh vertex shader by height above the mesh base (a traveling-wave lean plus flutter), so shadows sway too. (6) Integration with other layers: `texture` on every Layer3D mesh (and `textureLayer` on `Layer.model`) takes an image path or any layer (video, image, layout), hoisted like a matte and drawn offscreen each frame, then bound as the mesh's base-color map through its rect (`uvRect`). (7) Physics: `shape: "mesh"` (auto for fixed / kinematic terrain and SDF bodies) builds an exact Rapier trimesh. (8) Lint: `scatter_filters_reject_all` (framefields supplies the mesher through `LintOptions.scatterCoverage`, keeping the program module geometry-free) and `volumetric_fog_without_lights`. Fixed in passing: instanced meshes ignored their own material color.
-
----
-
-## Phase 5: Character Animation Blending, IK, Spring Bones & Skinned VAT Crowds
-
-### 5.1 Motivation
-In `examples/35_robot_uprising` and character-driven films, `Layer.model` currently plays a single glTF animation clip at a time, and `Layer3D.instances` only supports rigid unskinned meshes. We need multi-clip pose blending, procedural LookAt/Two-Bone IK, secondary spring physics on bones, and **instanced crowds of thousands of animated characters**.
-
-### 5.2 Multi-Clip Blending, Two-Bone IK & Spring Bones on `Layer.model`
-Extend `Model3DNode` and `GltfLoader` (`packages/webgpu-renderers/src/loaders/gltf-loader.ts`):
-
-```ts
-export interface ModelAnimationLayer {
- /** Clip name or index in the glTF asset. */
- clip: string | number;
- /** Blend weight 0..1 (number, Signal, or keyframed prop). Default 1. */
- weight?: number;
- /** Playback speed multiplier. Default 1. */
- speed?: number;
- /** Time offset in seconds. Default 0. */
- timeOffset?: number;
- /** Optional bone mask (only affect descendants of these joint names). */
- mask?: string[];
-}
-
-export interface TwoBoneIkConstraint {
- /** [rootJointName, midJointName, effectorJointName], e.g. ["UpperArm.L", "LowerArm.L", "Hand.L"]. */
- chain: [string, string, string];
- /** World or model-local target position [x, y, z] (or driver `(frame) => [x, y, z]`). */
- target: [number, number, number] | ((frame: number) => [number, number, number]);
- /** Pole vector target for knee/elbow bend direction. */
- poleTarget?: [number, number, number];
- weight?: number;
-}
-
-export interface LookAtConstraint {
- joint: string;
- target: [number, number, number] | ((frame: number) => [number, number, number]);
- weight?: number;
- maxAngleDeg?: number;
-}
-
-export interface SpringBoneChain {
- /** Root joint name(s) for secondary jiggle/follow-through (cape, tail, antenna, hair). */
- joints: string[];
- stiffness?: number;
- damping?: number;
- gravity?: [number, number, number];
-}
-```
-
-#### Deterministic Evaluation Order per Frame
-1. Sample each active `ModelAnimationLayer` TRS (translation, rotation quaternion, scale) and blend via normalized quaternion `slerp` / `nlerp` (with optional upper-body/lower-body `mask`).
-2. Solve `LookAtConstraint` (clamped swing quaternion) and analytic **Two-Bone IK** (law of cosines for knee/elbow bend angle + pole-vector twist) in joint hierarchy order.
-3. Step `SpringBoneChain` Verlet / harmonic spring state (pre-simulated deterministically across frames `[0..totalFrames]` on build, identical to `Physics.world3d`, so random-access frame rendering stays 100% deterministic).
-4. Upload final `skinningMatrices` (`16 floats × jointCount`) to `Mesh3DPipeline`.
-
-### 5.3 Skinned Crowds via Vertex Animation Textures (VAT) in `Layer3D.instances`
-To render 500–10,000 animated characters (robots, soldiers, pedestrians) in 1 GPU draw call:
-- When `Layer3D.instances({ mesh: Layer.model({ src: "robot.glb", ... }), crowd: { clips: ["walk", "idle", "run"] }, ... })` is constructed:
- 1. **Bake Joint Palette Atlas once per model**: Sample the model's skinning joint matrices across each animation clip at 30/60 Hz into a 2D `rgba32float` texture (`width = jointCount * 4`, `height = totalBakedFrames`).
- 2. Pack `(clipIndex, animPhaseOffset, animSpeed)` into the unused bits of `InstanceData.emissive.w` (or a companion per-instance `vec4<f32>`).
- 3. In `mesh3d.wgsl` (`vs_main`), when both `isInstanced` and `isSkinned` are active, each vertex fetches its 4 influencing bone matrices from the baked joint palette storage/texture buffer at the instance's `(clipIndex, frame * speed + phaseOffset)`.
-- Result: **5,000 independently walking/running skinned 3D characters with shadows, outlines, and bloom in a single draw call**.
-
-**Status (implemented):** rig evaluator `webgpu-renderers/src/loaders/rig.ts` (pure, unit-tested), crowd baking `loaders/crowd.ts`, compositor `renderers/character.ts`, schemas `compositions/src/program/character-schema.ts`. The field is `animationLayers` (`animation` already holds keyframe tracks). Deviations: (1) Layers blend in order, each overriding the pose beneath by its weight (slerp per joint) from the rest pose, so a crossfade is two layers with the top one's weight keyed; weights and targets are tracks: a constant, linear `[[frame, …]]` keys (JSON) or a function (in process). (2) Look-at runs before IK (a head turns, then limbs reach); look-at takes the joint's local `axis` (default glTF +z). IK targets and poles are scene coordinates, mapped through the inverse of the model's transform; the pole twists the solved chain about root→target. (3) Spring bones simulate in model space (follow-through from the clips, gravity mapped by the model's current orientation), replayed from frame 0 and cached per layer; stiffness is a per-second pull toward the animated pose, damping a per-second velocity loss. (4) Crowds bake a palette per mesh into a storage buffer (the mesh's skinning binding), not a texture; each clip bakes `count + 1` samples so playback interpolates to the loop point without wrapping; rigid node-attached meshes bake their node as joint 0. Each crowd instance carries a second 64-byte record (clip range, phase, playback rate) instead of packing bits into `emissive.w`. (5) Instance and scatter variants now apply their own node rotation and scale under each instance's, so a y-up glTF (`rotateX: 180`) stands upright in crowds and scatters. (6) Direct posing and retargeting (added after Phase 6): `pose` sets joints by name (local Euler degrees and offsets, additive over the clips or from rest, weighted) and `aim` points bones along scene directions; both run after clip layers and before look-at and IK. Every track (pose, aim, IK, look-at, clip weights) also takes a signal, and a point one track per axis; the readers live in `compositions/program/track-sampler.ts`, shared by the SDK and the compositor. `retargetPose(source, { rig })` / `person.retarget()` turns a vision person's COCO keypoints into aims (spine, neck, arms, legs; presets `mixamo`, `humanoid`, `rigify`), in the picture plane (one view has no depth), with confidence fading bones back to the animated pose. Joint names match without a namespace prefix and case.
-
----
-
-## Phase 6: Voronoi Mesh Fracture & Per-Vertex Velocity Motion Blur
-
-### 6.1 `Physics.fracture` — Deterministic Voronoi Shattering
-Enable objects (statues, walls, typography, product cases) to remain a single seamless mesh until a designated impact frame, then shatter into physical 3D Voronoi fragments:
-
-```ts
-export interface Fracture3DOptions {
- /** Source solid (`Layer3D.*` primitive, `Layer3D.extrudedText`, or `Layer.model`). */
- mesh: AnimatableNode<Model3DNode>;
- /** Number of Voronoi fracture cells (8..256). Default 48. */
- cells?: number;
- /** Optional world/local impact point where Voronoi seeds cluster more densely. */
- impactPoint?: [number, number, number];
- /** Deterministic seed. Default 1. */
- seed?: number;
- /** Frame at which the intact mesh swaps to dynamic Rapier rigid bodies (or `"onImpact"`). */
- fractureFrame?: number | "onImpact";
- /** Optional interior surface material/color for newly exposed fracture faces. */
- interiorColor?: string;
- interiorRoughness?: number;
- /** Outward radial impulse speed applied at `fractureFrame` (px/s). */
- explosionSpeed?: number;
-}
-```
-- Uses the convex half-space plane clipper from `Layer3D.shard` generalized to **3D Voronoi cell clipping** (clipping the source mesh against the bisector planes $\mathbf{n}_{ij} = \mathbf{p}_j - \mathbf{p}_i$ of its $K$-nearest seed neighbors).
-- Registers each cell with `Physics.world3d` (holding `type: "fixed"` until `fractureFrame`, then switching to `"dynamic"` with `explosionSpeed` impulse) and returns a single `Layer3D.instances` node that renders all cells in one draw call.
-
-### 6.2 Per-Vertex & Per-Instance Velocity Motion Blur (`MotionBlurPipeline`)
-Currently, `MotionBlurPipeline` (`packages/webgpu-renderers/src/renderer3d/motion-blur-pipeline.ts`) reconstructs pixel velocity only from the camera's previous view-projection matrix.
-- Upgrade the MRT velocity pass to accept `prevModelMatrix`, `prevSkinningMatrices`, and `prevInstanceBuffer` (`Swarm3DPipeline` / `Layer3D.instances`).
-- Fast-moving robot limbs, tumbling shards, and fractured debris get authentic directional per-object and per-bone shutter motion blur.
-
-**Status (implemented):** fracture geometry `webgpu-renderers/src/renderer3d/fracture-geometry.ts` (pure, unit-tested for closed pieces and exact volume), SDK `framefields/src/physics/fracture3d.ts` (`world.fracture(node, options)` on `PhysicsWorld3D`), compositor `renderers/fracture.ts`; velocity pass `shaders/mesh-velocity.ts` + `Mesh3DPipeline.drawVelocity` / `Renderer3D.beginVelocityPass`, reconstruction `shaders/motion-blur.ts` + `MotionBlurPipeline`, history `node-compositor/src/renderers/motion-history.ts`. Deviations: (1) Voronoi cells are exact (bisectors nearest first until none can reach the cell), not K-nearest. The surface is clipped by each cell's planes, and each cell face is the solid's whole cross-section on its bisector (loops chained by exact position through a point welder, holes nested, triangulated, collinear points restored) clipped to the cell's other planes, so pieces of a watertight source are closed (verified by origin-independent volume) and sum to its volume. (2) The fractured layer is one rigidly skinned mesh (one joint per piece, one draw per material, cut faces in their own `interiorColor` material), not `Layer3D.instances`: pieces differ in shape, and skinning gives motion blur per-piece velocity for free. The pieces' recorded poses (`fracture3d.track`, x y z + quaternion per piece per frame) are JSON; the renderer rebuilds and re-fractures the source deterministically when `modelData` is lost. While every piece is at its frame-0 pose the layer draws in the exact rest pose without its cut faces, so it is sealed (cut faces would otherwise tie the surface's depth along seams). (3) While whole, a fixed collider of the layer's own shape stands in; `fractureFrame: "onImpact"` (default) breaks it on the first dynamic contact, which keeps going (the stand-in's bounce is undone, minus `momentumTransfer`). `Physics.fracture` is `world.fracture` (it needs a world); live worlds are refused. An animated layer's stand-in is kinematic, following its x/y/z/rotation sampled with the compositor's own eases (`sampleLayerProp` in `compositions/src/program/track-sampler.ts`, shared with the compiler's draw-time tracks); at the break each piece is placed from the stand-in's pose and inherits its rigid motion (v + ω × r). The track lives in the layer's parent space, so pieces inside a 3D group fly in the group's space like any body; animated scale is refused (rigid pieces). Kinematic bodies with `follow` now start at their drivers' pose in both worlds. (4) Motion blur is `Layer.camera({ motionBlur })` (shutter angle, samples, max blur). The velocity pass is a second draw of the scene (meshes run the shared `meshDeformWgsl` for this and the previous frame's bindings, so model matrices, skinning, instances, swarms, wind and crowds all move; 3D layer planes use their model matrices), not a color-pass MRT, which keeps every color pipeline variant unchanged. Previous-frame state comes from a per-composition history (instance records copied on the GPU, two parity slots); after a seek the compositor renders the frame before first, recording only, so every frame comes out identical in any order. (5) Reconstruction is McGuire et al.'s tile max / neighbor max gather, with per-sample coverage selection (front sample whose blur reaches, or level/behind sample this pixel's blur reaches) normalized over the samples, which makes uniform motion an exact ramp of the streak length. (6) Motion below the model matrix: the motion history keeps a GPU copy of each GPU-deformed mesh's final vertices (morph targets, audio deformation), and the velocity pass deforms from that previous position, so a mesh moved by its blend shapes alone streaks. Text drawn as native Slug glyphs in 3D writes velocity per glyph (this and the previous frame's plane and per-glyph animation, from copied glyph records, written where the outline covers the pixel). The history pass of a seek records every layer in the 3D scene, including ones placed there by `z` or `is3D` alone.
-
----
-
-## Schema, Lint & Skill Synchronization Requirements
-
-Every phase must keep the engine harness self-consistent:
-1. **`packages/compositions/src/program/schema.ts`**:
- - Add Zod schemas for `volumetricFog`, `ssr`, `gi`, `rectLight`, `SurfaceParams` extensions (`clearcoat`, `anisotropy`, `subsurface`, `sheen`, `iridescence`, `triplanar`), `Layer3D.terrain`, `Layer3D.sdf`, `Layer3D.scatter`, `ModelAnimationLayer`, `ik`, `springBones`, and `Physics.fracture`.
-2. **`packages/compositions/src/program/lint.ts`**:
- - Warn if `clearcoat`, `anisotropy`, or `ssr` is used without `Layer.environment`.
- - Warn if `volumetricFog` is enabled with zero direct lights in the scene.
- - Warn if `Layer3D.scatter` filters (`slopeRange` / `elevationRange`) reject 100% of candidate surface points.
-3. **Agent Skills & Catalog**:
- - Update `nodes/node-compositor/SKILL.md` and `plugins/framefields/skills/framefields-compose/SKILL.md`.
- - Keep `packages/compositions/src/program/skillmd-check.test.ts` and `pnpm run check:plugins` passing.
-
----
-
-## Verification Ladder (Per Phase)
-
-1. **Typecheck**: `tsc --noEmit -p .` in `@framefields/core`, `@framefields/webgpu-renderers`, `@framefields/compositions`, `@framefields/node-compositor`, and `framefields`.
-2. **Schema & Lint Tests**: Unit tests in `packages/compositions` verifying `CompositorProgramSchema.parse(comp.toSpec())` and `comp.lint()` diagnostics.
-3. **Headless GPU Render Tests**: Vitest pixel-probe tests in `packages/webgpu-renderers/src/renderer3d/renderer3d.test.ts` verifying:
- - Volumetric light shafts occluded by shadow casters.
- - Clearcoat / anisotropic / subsurface / HDRI shading energy conservation.
- - Hi-Z SSR reflection of off-floor emissive objects and SSGI color bleeding.
- - Watertight `Layer3D.terrain` and `Layer3D.sdf` meshes + deterministic `Layer3D.scatter` placement.
- - Two-Bone IK target convergence and instanced VAT skinned crowd rendering in 1 draw call.
-4. **Visual Reference Film (`examples/`)**: Render frame grids (`renderFrameGrid`) to inspect visual quality before merging each phase.
-