Skip to content

Write HTML. Render video. Built for agents.

feat(runtime): data-vfx-chain — a seek-deterministic per-pixel effect element (#4306)

Vance Ingallsb32b9a7dabf7
diff --git a/docs/docs.json b/docs/docs.json
index 00cd346181..9129fd2a1e 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -887,6 +887,7 @@
"concepts/frame-adapters",
"concepts/determinism",
"guides/html-in-canvas",
+ "guides/vfx-chain",
"guides/figma"
]
},
diff --git a/docs/guides/vfx-chain.mdx b/docs/guides/vfx-chain.mdx
new file mode 100644
index 0000000000..5a6ca5fcd5
--- /dev/null
+++ b/docs/guides/vfx-chain.mdx
@@ -0,0 +1,129 @@
+---
+title: "Per-pixel effects with data-vfx-chain"
+sidebarTitle: "VFX chain"
+description: "The data-vfx-chain attribute: a WebGL2 kernel chain for warps, displacement, and generated noise that repaints deterministically on every seek."
+---
+
+`data-vfx-chain` gives an element a chain of per-pixel WebGL2 kernels — warps,
+displacement maps, generated noise — that the runtime repaints from `(t, params)`
+every time the composition seeks. It mirrors the shipped audio effects rack
+(`data-fx-chain`): a versioned JSON chain attribute, static params in JSON,
+animated params as CSS custom properties GSAP tweens like any other exporter
+variable.
+
+Use it for a per-pixel treatment a CSS filter or SVG `<filter>` cannot express —
+a wave warp, a self-referential displacement map, or a generated fractal-noise
+texture — where you need the same frame twice at the same `t` to produce
+byte-identical pixels.
+
+## Element
+
+```html
+<div id="rw-main-text" class="clip" data-start="0" data-duration="8.8"
+ data-vfx-chain='{"version":1,"nodes":[{"type":"displacement-map","id":"n1","params":{"useH":1,"useV":2,"edge":0,"expand":true}},{"type":"wave-warp","id":"n2","params":{"waveType":1,"direction":0,"speed":1,"pinning":1,"phase":0}}]}'
+ style="--vfx-n1-maxH:150;--vfx-n1-maxV:150;--vfx-n2-height:21;--vfx-n2-width:93.4">
+ <canvas layoutsubtree class="hf-vfx-src"><div class="hf-vfx-in">…layer content, with any PRECEDING CSS/SVG effects already applied on this wrapper…</div></canvas>
+ <canvas class="hf-vfx-out"></canvas>
+</div>
+```
+
+- `data-vfx-chain` is JSON with the same field names as `data-fx-chain`:
+ `version`, `nodes[]`, and each node's `type` / `id` / `enabled` / `params`.
+- **Static params** live in `params`. **Animated params** live in CSS custom
+ properties named `--vfx-<nodeId>-<key>` on the host element, tweened by GSAP
+ like every other exporter variable. The runtime reads the CSS var first on
+ every paint and falls back to `params` when it doesn't resolve.
+- `.hf-vfx-src` (a `<canvas layoutsubtree>`) is present **only** when some
+ node's def needs to read pixels besides `(x, y, t, params)` — see
+ [Capture](#capture) below. Its one child, `.hf-vfx-in`, is the texture
+ source. Give `.hf-vfx-in` an **explicit pixel box** (`width`/`height`, the
+ layer's own size) — `position:absolute; inset:0` has no containing block to
+ resolve against inside a `layoutsubtree` canvas and collapses to 0×0, which
+ makes the capture succeed and draw nothing, silently.
+- Effects that run **before** the chain in After Effects order belong on
+ `.hf-vfx-in` (inside the capture); effects that run **after** belong on the
+ host (outside, applied to `.hf-vfx-out` by the ordinary page compositor).
+ Chain order is nesting order.
+- `.hf-vfx-out` is created by the runtime if you don't provide it. It is
+ `position:absolute; inset:0`, sized to the host's own (untransformed) layout
+ box — `offsetWidth`/`offsetHeight` — times devicePixelRatio, not the host's
+ transformed bounding box. A GSAP scale or rotation on the host does not
+ inflate or stretch the capture.
+
+## Capture
+
+Every kernel declares a `capture` requirement on its **def**, not the element:
+
+| capture | reads | render capture path | ships in this plan |
+| --- | --- | --- | --- |
+| `none` | `(x, y, t, params)` only | screenshot capture, workers unpinned | `fractal-noise` |
+| `self` | its own layer's pixels, via `drawElementImage` | screenshot capture, **pinned to 1 worker** | `wave-warp`, `displacement-map` |
+| `backdrop` | every layer below it | screenshot capture, pinned to 1 worker | not yet — later phase |
+
+A `self` or `backdrop` node puts the whole composition on screenshot capture
+pinned to one worker (the `htmlInCanvas` render-mode hint exists because a
+paint-cache race across parallel browser instances is a measured failure, not
+a theoretical one). A `none` node still forces screenshot capture — WebGL
+content is not something the fast `drawElementImage` path can read back
+faithfully — but leaves worker count auto-resolved.
+
+Neither is a regression against the alternative of baking the effect in After
+Effects and shipping video instead of a live chain: a bake costs a full AE
+render up front and produces a filmstrip nothing can retime. But compared to a
+`drawElement` render of the same composition **without** the node, both `self`
+and `none` capture are slower. Budget for it, and don't add a chain to a layer
+that doesn't need per-pixel treatment.
+
+## Determinism
+
+Same backend, same `(u_t, params)` → byte-identical `.hf-vfx-out` pixels. A
+kernel may read only `(u_size, u_t, u_fps, params, u_src)` — no `Math.random`,
+no clock, no state carried between paints. That's what makes `data-vfx-chain`
+safe to seek anywhere in a render, including backwards, and still get the same
+frame you'd get scrubbing forward to it in Studio.
+
+## Studio and browser support
+
+`self` and `backdrop` capture depend on `drawElementImage`, the same
+experimental Chromium API [HTML in Canvas](/guides/html-in-canvas) uses. In a
+normal browser preview, enable `chrome://flags/#canvas-draw-element` in a
+compatible Chrome or Brave build and restart it before opening a composition
+that uses a capturing chain. Without it — or on a browser build with no
+WebGL2 — a chain fails loudly (a `[HyperFrames] composition script error:`
+console line naming the flag) rather than silently rendering the wrong thing.
+`none`-capture chains (like `fractal-noise`) need only WebGL2, not the flag.
+
+## Known constraints
+
+A few things the runtime implementation found worth knowing before you author
+a chain by hand:
+
+- **`.hf-vfx-in` needs an explicit pixel box.** See [Element](#element) above —
+ this is the one that costs a silent, empty capture if you skip it.
+- **Only immediate children of the `layoutsubtree` canvas can be captured.**
+ `drawElementImage` throws on a grandchild. `.hf-vfx-in` must be the canvas's
+ only child.
+- **Output size follows the host's layout box, not its transformed bounding
+ box.** A GSAP `transform: scale()` or rotation on the host does not affect
+ `.hf-vfx-out`'s resolution.
+- **A chain repaints on seek, not on every animation-frame tick.** Every render
+ path seeks per frame, so this only matters for Studio scrubbing-free
+ playback, where a chain does not repaint between seeks.
+- **Known conflict with page-side shader transitions.** A composition running
+ both `@hyperframes/shader-transitions`' page-side compositing and a
+ capturing `data-vfx-chain` node can have the chain painted from a stale
+ texture outside a transition's own active window. If your composition uses
+ both features together and a chain looks wrong outside a transition, this is
+ why.
+
+## Related topics
+
+<CardGroup cols={2}>
+ <Card title="HTML in Canvas" icon="cube" href="/guides/html-in-canvas">
+ The same `drawElementImage` capture, for compositing DOM into a 3D scene
+ instead of a per-pixel kernel.
+ </Card>
+ <Card title="Audio effects implementation" icon="waveform-lines" href="/reference/audio-effects">
+ The `data-fx-chain` shape `data-vfx-chain` mirrors, for the audio rack.
+ </Card>
+</CardGroup>
diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts
index c632cc9fbb..71499db68d 100644
--- a/packages/cli/src/commands/render.ts
+++ b/packages/cli/src/commands/render.ts
@@ -1796,6 +1796,9 @@ function trackRenderMetrics(
beginFrameNoDamageFrames: perf?.beginFrameReuse?.noDamageFrames,
beginFrameHasDamageFrames: perf?.beginFrameReuse?.hasDamageFrames,
deCaptureMode: perf?.drawElement?.mode,
+ vfxHostCount: perf?.drawElement?.vfxHostCount,
+ vfxCapture: perf?.drawElement?.vfxCapture,
+ vfxTypes: perf?.drawElement?.vfxTypes,
deCompileGate: perf?.drawElement?.compileGate,
deClampReason: perf?.drawElement?.clampReason,
deWorkerInversion: perf?.drawElement?.workerInversion,
diff --git a/packages/cli/src/telemetry/events.test.ts b/packages/cli/src/telemetry/events.test.ts
index 0bf560dae2..37ff307162 100644
--- a/packages/cli/src/telemetry/events.test.ts
+++ b/packages/cli/src/telemetry/events.test.ts
@@ -588,6 +588,48 @@ describe("render telemetry events", () => {
expect(props.has_lut).toBe(false);
});
+ it("carries the vfx chain scan's node count, capture class, and def types", () => {
+ trackRenderComplete({
+ durationMs: 1000,
+ fps: 30,
+ quality: "high",
+ docker: false,
+ gpu: false,
+ vfxHostCount: 2,
+ vfxCapture: "self",
+ vfxTypes: "displacement-map,wave-warp",
+ });
+ const props = trackEvent.mock.calls[0]?.[1] as Record<string, unknown>;
+ expect(props.vfx_host_count).toBe(2);
+ expect(props.vfx_capture).toBe("self");
+ expect(props.vfx_types).toBe("displacement-map,wave-warp");
+ });
+
+ it("reports a zero node count and empty types rather than dropping the properties", () => {
+ trackRenderComplete({
+ durationMs: 1000,
+ fps: 30,
+ quality: "high",
+ docker: false,
+ gpu: false,
+ vfxHostCount: 0,
+ vfxTypes: "",
+ });
+ const props = trackEvent.mock.calls[0]?.[1] as Record<string, unknown>;
+ expect(props.vfx_host_count).toBe(0);
+ expect(props.vfx_types).toBe("");
+ // No vfx-chain host means chainCapture never ran — undefined, not "none".
+ expect(props.vfx_capture).toBeUndefined();
+ });
+
+ it("omits the vfx fields entirely when the caller never resolved them", () => {
+ trackRenderComplete({ durationMs: 1000, fps: 30, quality: "high", docker: false, gpu: false });
+ const props = trackEvent.mock.calls[0]?.[1] as Record<string, unknown>;
+ expect(props.vfx_host_count).toBeUndefined();
+ expect(props.vfx_capture).toBeUndefined();
+ expect(props.vfx_types).toBeUndefined();
+ });
+
// emitStudioRenderComplete never resolves perfSummary.drawElement, only the
// observability capture fields (captureAudioCount/captureRootBodyMismatch/etc),
// so these must fall back to the capture value or a studio render reports none
diff --git a/packages/cli/src/telemetry/events.ts b/packages/cli/src/telemetry/events.ts
index 2a73edddbd..b4e019dda9 100644
--- a/packages/cli/src/telemetry/events.ts
+++ b/packages/cli/src/telemetry/events.ts
@@ -384,6 +384,15 @@ export function trackRenderComplete(
hasLut?: boolean;
rootBodyMismatch?: boolean;
rootBodyDeltaPxBucket?: string;
+ // `data-vfx-chain` facts from the same static scan (Task 1.5's kernel-cost
+ // measurement's producer-side counterpart). Undefined on render paths
+ // with no capture session, same as the composition-element fields above.
+ /** Host count — one per `data-vfx-chain` attribute occurrence, regardless of its chain's node count. */
+ vfxHostCount?: number;
+ /** Strongest enabled node's capture across every host ("none" | "self" | "backdrop", max). */
+ vfxCapture?: string;
+ /** Sorted unique def ids across every enabled node in every chain, comma-joined. */
+ vfxTypes?: string;
deShortBand?: string;
deParallelRouter?: string;
dePreRouterWorkers?: number;
@@ -503,6 +512,9 @@ export function trackRenderComplete(
begin_frame_no_damage_frames: props.beginFrameNoDamageFrames,
begin_frame_has_damage_frames: props.beginFrameHasDamageFrames,
de_capture_mode: props.deCaptureMode,
+ vfx_host_count: props.vfxHostCount,
+ vfx_capture: props.vfxCapture,
+ vfx_types: props.vfxTypes,
de_compile_gate: props.deCompileGate,
de_clamp_reason: props.deClampReason,
de_worker_inversion: directOrCapture(props.deWorkerInversion, props.captureDeWorkerInversion),
diff --git a/packages/core/src/generated/position-edits-render-inline.ts b/packages/core/src/generated/position-edits-render-inline.ts
index f570886ad5..c5a2e45243 100644
--- a/packages/core/src/generated/position-edits-render-inline.ts
+++ b/packages/core/src/generated/position-edits-render-inline.ts
@@ -1,6 +1,6 @@
// AUTO-GENERATED by scripts/build-position-edits-render.ts - do not edit
const POSITION_EDITS_RENDER_IIFE: string =
- '"use strict";(()=>{function T(){return globalThis}function P(e,t){if(typeof window>"u")return;let o=T(),r=o.__hf?.onSwallowed;if(r)try{r({label:e,error:t})}catch(s){}(o.__hfDebug||o.__HYPERFRAMES_DEBUG)&&console.debug(`[hyperframes] ${e} swallowed:`,t)}var x=null;function R(e,t){if(x)try{x({source:"hf-preview",type:"analytics",event:e,properties:t??{}})}catch(o){P("runtime.analytics.site1",o)}}var W="http://www.w3.org/1999/xhtml";function N(e){return e!=null&&e.nodeType===1}function _(e){return N(e)&&(e.namespaceURI===W||e.namespaceURI==="http://www.w3.org/2000/svg")}var w="data-hf-edit-base-x",y="data-hf-edit-base-y",m="data-hf-edit-original-translate",k=e=>{let t=parseFloat(e??"");return Number.isFinite(t)?t:0},O=e=>{let t=[],o=0,r="";for(let s of e.trim())s==="("&&(o+=1),s===")"&&(o=Math.max(0,o-1)),/\\s/.test(s)&&o===0?(r&&t.push(r),r=""):r+=s;return r&&t.push(r),t},L=/^-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)px$/,b=(e,t)=>L.test(e)&&L.test(t)?`${parseFloat(e)+parseFloat(t)}px`:`calc(${e} + ${t})`,V=(e,t,o)=>{if(!e||e==="none")return`${t} ${o}`;let[r,s,a]=O(e);if(r===void 0)return`${t} ${o}`;if(s===void 0)return`${b(r,t)} ${o}`;let i=a===void 0?"":` ${a}`;return`${b(r,t)} ${b(s,o)}${i}`},j=e=>{try{e.ownerDocument.defaultView?.gsap?.getProperty?.(e,"x")}catch{}},G=e=>{let t=e.style.getPropertyValue("translate").trim();if(t)return t==="none"?"":t;try{let o=e.ownerDocument.defaultView,r=o?o.getComputedStyle(e).getPropertyValue("translate").trim():"";return r==="none"?"":r}catch{return""}},E=new WeakMap;function B(e,t){let o=E.get(e);if(!t?.force&&o!==void 0&&e.style.getPropertyValue("translate")!==o){R("position_edit_fold_skipped",{hfId:e.getAttribute("data-hf-id")});return}let r=k(e.getAttribute("data-x"))-k(e.getAttribute(w)),s=k(e.getAttribute("data-y"))-k(e.getAttribute(y));e.hasAttribute(m)||e.setAttribute(m,G(e)),o===void 0&&j(e);let a=e.getAttribute(m)??"",i=V(a,`${r}px`,`${s}px`);e.style.setProperty("translate",i),E.set(e,e.style.getPropertyValue("translate"))}function S(e,t){let o=e.querySelectorAll(`[${m}]:not([${w}]):not([${y}])`);for(let a=0;a<o.length;a++){let i=o[a];if(i===void 0||!_(i))continue;let g=i.getAttribute(m)??"";g===""?i.style.removeProperty("translate"):i.style.setProperty("translate",g),i.removeAttribute(m),E.delete(i)}let r=e.querySelectorAll(`[${w}], [${y}]`),s=0;for(let a=0;a<r.length;a++){let i=r[a];i===void 0||!_(i)||(B(i,t),s+=1)}return s}var $="__hfPositionEditsSeekReapplyWrapped",D=new WeakSet,M=new WeakMap,F=new WeakMap;function H(e){let t=e,o=()=>{try{S(t.document)}catch{}},r=n=>typeof n=="function"&&(D.has(n)||!!n[$]),s=n=>{D.add(n);try{Object.defineProperty(n,$,{value:!0})}catch{}},a=n=>{if(typeof n!="function"||r(n))return n;let l=function(...u){let d=n.apply(this,u);return o(),d};return s(l),l},i=(n,l)=>{let u=M.get(n);if(u?.has(l))return!0;let d=Object.getOwnPropertyDescriptor(n,l);if(d?.configurable===!1){let c=n[l];return typeof c=="function"&&(n[l]=a(c),o()),!1}let p=n[l],f=d?.set;return Object.defineProperty(n,l,{configurable:!0,enumerable:d?.enumerable??!0,get:()=>p,set:c=>{p=a(c),f?.call(n,c)}}),p=a(p),u??(u=new Set),u.add(l),M.set(n,u),o(),!0},g=(n,l)=>{let u=F.get(t),d=Object.getOwnPropertyDescriptor(t,n);if(!u?.has(n)){if(d?.configurable===!1){let c=t[n];return c?i(c,l):!1}let f=t[n];Object.defineProperty(t,n,{configurable:!0,enumerable:d?.enumerable??!0,get:()=>f,set:c=>{f=c,f&&i(f,l)}}),u??(u=new Set),u.add(n),F.set(t,u)}let p=t[n];return p?i(p,l):!1},h=()=>{let n=g("__hf","seek"),l=g("__player","renderSeek");return n&&l};if(h())return;let v=120,A=t.setInterval(()=>{if(h()){t.clearInterval(A);return}v-=1,v<=0&&t.clearInterval(A)},50)}function I(){document.querySelector(`[${w}], [${y}]`)&&(S(document),H(window))}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",I,{once:!0}):I();})();\n';
+ '"use strict";(()=>{function T(){return globalThis}function P(e,t){if(typeof window>"u")return;let o=T(),r=o.__hf?.onSwallowed;if(r)try{r({label:e,error:t})}catch(s){}(o.__hfDebug||o.__HYPERFRAMES_DEBUG)&&console.debug(`[hyperframes] ${e} swallowed:`,t)}var x=null;function R(e,t){if(x)try{x({source:"hf-preview",type:"analytics",event:e,properties:t??{}})}catch(o){P("runtime.analytics.site1",o)}}var W="http://www.w3.org/1999/xhtml";function N(e){return e!=null&&e.nodeType===1}function _(e){return N(e)&&(e.namespaceURI===W||e.namespaceURI==="http://www.w3.org/2000/svg")}var w="data-hf-edit-base-x",y="data-hf-edit-base-y",m="data-hf-edit-original-translate",k=e=>{let t=parseFloat(e??"");return Number.isFinite(t)?t:0},O=e=>{let t=[],o=0,r="";for(let s of e.trim())s==="("&&(o+=1),s===")"&&(o=Math.max(0,o-1)),/\\s/.test(s)&&o===0?(r&&t.push(r),r=""):r+=s;return r&&t.push(r),t},L=/^-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)px$/,b=(e,t)=>L.test(e)&&L.test(t)?`${parseFloat(e)+parseFloat(t)}px`:`calc(${e} + ${t})`,V=(e,t,o)=>{if(!e||e==="none")return`${t} ${o}`;let[r,s,a]=O(e);if(r===void 0)return`${t} ${o}`;if(s===void 0)return`${b(r,t)} ${o}`;let i=a===void 0?"":` ${a}`;return`${b(r,t)} ${b(s,o)}${i}`},j=e=>{try{e.ownerDocument.defaultView?.gsap?.getProperty?.(e,"x")}catch{}},G=e=>{let t=e.style.getPropertyValue("translate").trim();if(t)return t==="none"?"":t;try{let o=e.ownerDocument.defaultView,r=o?o.getComputedStyle(e).getPropertyValue("translate").trim():"";return r==="none"?"":r}catch{return""}},E=new WeakMap;function B(e,t){let o=E.get(e);if(!t?.force&&o!==void 0&&e.style.getPropertyValue("translate")!==o){R("position_edit_fold_skipped",{hfId:e.getAttribute("data-hf-id")});return}let r=k(e.getAttribute("data-x"))-k(e.getAttribute(w)),s=k(e.getAttribute("data-y"))-k(e.getAttribute(y));e.hasAttribute(m)||e.setAttribute(m,G(e)),o===void 0&&j(e);let a=e.getAttribute(m)??"",i=V(a,`${r}px`,`${s}px`);e.style.setProperty("translate",i),E.set(e,e.style.getPropertyValue("translate"))}function S(e,t){let o=e.querySelectorAll(`[${m}]:not([${w}]):not([${y}])`);for(let a=0;a<o.length;a++){let i=o[a];if(i===void 0||!_(i))continue;let g=i.getAttribute(m)??"";g===""?i.style.removeProperty("translate"):i.style.setProperty("translate",g),i.removeAttribute(m),E.delete(i)}let r=e.querySelectorAll(`[${w}], [${y}]`),s=0;for(let a=0;a<r.length;a++){let i=r[a];i===void 0||!_(i)||(B(i,t),s+=1)}return s}var $="__hfPositionEditsSeekReapplyWrapped",D=new WeakSet,M=new WeakMap,H=new WeakMap;function F(e){let t=e,o=()=>{try{S(t.document)}catch{}},r=n=>typeof n=="function"&&(D.has(n)||!!n[$]),s=n=>{D.add(n);try{Object.defineProperty(n,$,{value:!0})}catch{}},a=n=>{if(typeof n!="function"||r(n))return n;let l=function(...u){let d=n.apply(this,u);return o(),d};return s(l),l},i=(n,l)=>{let u=M.get(n);if(u?.has(l))return!0;let d=Object.getOwnPropertyDescriptor(n,l);if(d?.configurable===!1){let c=n[l];return typeof c=="function"&&(n[l]=a(c),o()),!1}let p=n[l],f=d?.set;return Object.defineProperty(n,l,{configurable:!0,enumerable:d?.enumerable??!0,get:()=>p,set:c=>{p=a(c),f?.call(n,c)}}),p=a(p),u??(u=new Set),u.add(l),M.set(n,u),o(),!0},g=(n,l)=>{let u=H.get(t),d=Object.getOwnPropertyDescriptor(t,n);if(!u?.has(n)){if(d?.configurable===!1){let c=t[n];return c?i(c,l):!1}let f=t[n];Object.defineProperty(t,n,{configurable:!0,enumerable:d?.enumerable??!0,get:()=>f,set:c=>{f=c,f&&i(f,l)}}),u??(u=new Set),u.add(n),H.set(t,u)}let p=t[n];return p?i(p,l):!1},v=()=>{let n=g("__hf","seek"),l=g("__player","renderSeek");return n&&l};if(v())return;let h=120,A=t.setInterval(()=>{if(v()){t.clearInterval(A);return}h-=1,h<=0&&t.clearInterval(A)},50)}function I(){document.querySelector(`[${w}], [${y}]`)&&(S(document),F(window))}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",I,{once:!0}):I();})();\n';
/** Returns the pre-built position-edits render IIFE as a string constant. */
export function getPositionEditsRenderScript(): string {
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 99a4ae8775..f1ecf7ed10 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -379,3 +379,21 @@ export {
overdueCanaries,
type CanaryDefinition,
} from "./canaryRegistry.js";
+
+// VFX chain (data-vfx-chain) — defs, chain parse/serialize/normalize
+export {
+ HF_VFX_ATTR,
+ HF_VFX_CHAIN_VERSION,
+ HF_VFX,
+ chainCapture,
+ getVfxDef,
+ parseVfxChain,
+ serializeVfxChain,
+ normalizeVfxParams,
+ type HfVfxCapture,
+ type HfVfxChain,
+ type HfVfxDef,
+ type HfVfxNode,
+ type HfVfxParam,
+ type HfVfxParamValues,
+} from "./vfx.js";
diff --git a/packages/core/src/runtime/adapters/seek-dispatch.ts b/packages/core/src/runtime/adapters/seek-dispatch.ts
index 391e99f8d9..011e7cdfc9 100644
--- a/packages/core/src/runtime/adapters/seek-dispatch.ts
+++ b/packages/core/src/runtime/adapters/seek-dispatch.ts
@@ -49,7 +49,21 @@ function dispatch(time: number): void {
accepting = false;
}
if (pending.length === 0) return;
- const completion = Promise.all(pending)
+ registerSeekCompletion(Promise.all(pending));
+}
+
+/**
+ * Join `promise` to the seek-completion barrier: `waitForSeekCompletion` will
+ * not resolve until it settles, and its rejection (the first one) becomes the
+ * barrier's.
+ *
+ * Exported because the `"hf-seek"` event's synchronous `waitUntil()` is not
+ * the only asynchronous seek work a frame can owe. `runtime/vfx.ts` registers
+ * its preview-side capture here, so the CLI seek paths that already await this
+ * barrier wait for a `self` chain's paint instead of racing it.
+ */
+export function registerSeekCompletion(promise: Promise<unknown>): void {
+ const completion = promise
.then<SeekCompletionResult>(() => ({ status: "fulfilled" }))
.catch<SeekCompletionResult>((reason: unknown) => ({ status: "rejected", reason }));
_pendingCompletions.add(completion);
diff --git a/packages/core/src/runtime/domRealm.ts b/packages/core/src/runtime/domRealm.ts
index 5caea70e4d..f43c3d0d7e 100644
--- a/packages/core/src/runtime/domRealm.ts
+++ b/packages/core/src/runtime/domRealm.ts
@@ -86,6 +86,11 @@ export function isImageElement(value: unknown): value is HTMLImageElement {
return isHtmlTag(value, "img");
}
+/** `<canvas>`, from any realm. Mirrors `instanceof HTMLCanvasElement`. */
+export function isCanvasElement(value: unknown): value is HTMLCanvasElement {
+ return isHtmlTag(value, "canvas");
+}
+
/** `<style>`, from any realm. Mirrors `instanceof HTMLStyleElement`. */
export function isStyleElement(value: unknown): value is HTMLStyleElement {
return isHtmlTag(value, "style");
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index 20b548214e..ffb6ba685c 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -45,6 +45,7 @@ import { applyCaptionOverrides } from "./captionOverrides";
import { applyPositionEdits, installPositionEditsSeekReapply } from "./positionEdits";
import { applyVariableBindings } from "./applyVariableBindings";
import { createColorGradingRuntime, type RuntimeColorGradingApi } from "./colorGrading";
+import { initVfx, paintVfx } from "./vfx";
import { TransportClock } from "./clock";
import { WebAudioTransport } from "./webAudioTransport";
import {
@@ -3032,6 +3033,10 @@ export function initSandboxRuntimeModular(): void {
// values) don't exist at the init-time binding pass — re-apply so
// data-var-* / --{id} bindings inside them resolve. Idempotent.
applyVariableBindings(document);
+ // A vfx host inside a sub-composition enters the DOM only now, so the
+ // init-time pass below never saw it. Re-scan before readiness is
+ // published: an unregistered chain paints nothing and logs nothing.
+ initVfx(document.body, state.canonicalFps);
maybePublishRenderReady();
});
} else {
@@ -3057,6 +3062,8 @@ export function initSandboxRuntimeModular(): void {
colorGrading.destroy();
colorGradingRuntime = null;
});
+ // Per-pixel effect chains: compile once here, repaint on every seek below.
+ initVfx(document.body, state.canonicalFps);
const applyPlaybackRate = (nextRate: number) => {
const parsed = Number(nextRate);
@@ -3153,6 +3160,7 @@ export function initSandboxRuntimeModular(): void {
}
syncMediaForCurrentState();
colorGrading.redraw();
+ paintVfx(state.currentTime);
postState(true);
},
renderSeek: (timeSeconds, options) => {
@@ -3176,6 +3184,7 @@ export function initSandboxRuntimeModular(): void {
runAdapters("pause");
syncMediaForCurrentState();
colorGrading.redraw();
+ paintVfx(state.currentTime, { engineMode: true });
postState(true);
},
getTime: () => clock.now(),
diff --git a/packages/core/src/runtime/vfx.test.ts b/packages/core/src/runtime/vfx.test.ts
new file mode 100644
index 0000000000..c989b18db8
--- /dev/null
+++ b/packages/core/src/runtime/vfx.test.ts
@@ -0,0 +1,682 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { HfVfxCapture } from "../vfx";
+import { resetSeekDispatchState, waitForSeekCompletion } from "./adapters/seek-dispatch";
+import { initVfx, paintVfx } from "./vfx";
+
+/**
+ * No def has `capture !== "none"` until Task 2.2 registers `wave-warp`, so the
+ * capture tests below lift a real `fractal-noise` chain into `self` through the
+ * two functions the runtime asks. `null` leaves the real answers alone, so the
+ * Task 1.2 cases in this file are untouched.
+ */
+const override = vi.hoisted(() => ({ capture: null as HfVfxCapture | null }));
+
+vi.mock("../vfx", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../vfx")>();
+ return {
+ ...actual,
+ chainCapture: (chain: import("../vfx").HfVfxChain) =>
+ override.capture ?? actual.chainCapture(chain),
+ getVfxDef: (id: string) => {
+ const def = actual.getVfxDef(id);
+ return def && override.capture ? { ...def, capture: override.capture } : def;
+ },
+ };
+});
+
+const LABEL = "[HyperFrames] composition script error:";
+
+interface MockGl {
+ calls: string[];
+ uniforms: Record<string, unknown>;
+ programCount: number;
+ usedPrograms: unknown[];
+ shaderSources: string[];
+ viewports: number[][];
+}
+
+/**
+ * The slice of WebGL2 the vfx runtime touches. jsdom has no GL at all, so the
+ * unit tests stand a recorder in front of it and assert on the call order and
+ * the uniform values rather than on pixels — pixels are the browser test's job.
+ */
+function createMockGl(): WebGL2RenderingContext & MockGl {
+ const state: MockGl = {
+ calls: [],
+ uniforms: {},
+ programCount: 0,
+ usedPrograms: [],
+ shaderSources: [],
+ viewports: [],
+ };
+ let currentProgram: unknown = null;
+ const gl = {
+ ...state,
+ VERTEX_SHADER: 0x8b31,
+ FRAGMENT_SHADER: 0x8b30,
+ COMPILE_STATUS: 0x8b81,
+ LINK_STATUS: 0x8b82,
+ TRIANGLES: 0x0004,
+ TEXTURE_2D: 0x0de1,
+ TEXTURE0: 0x84c0,
+ RGBA: 0x1908,
+ UNSIGNED_BYTE: 0x1401,
+ CLAMP_TO_EDGE: 0x812f,
+ LINEAR: 0x2601,
+ TEXTURE_WRAP_S: 0x2802,
+ TEXTURE_WRAP_T: 0x2803,
+ TEXTURE_MIN_FILTER: 0x2801,
+ TEXTURE_MAG_FILTER: 0x2800,
+ FRAMEBUFFER: 0x8d40,
+ COLOR_ATTACHMENT0: 0x8ce0,
+ UNPACK_FLIP_Y_WEBGL: 0x9240,
+ UNPACK_PREMULTIPLY_ALPHA_WEBGL: 0x9241,
+ createShader: () => ({}),
+ shaderSource: (_s: unknown, src: string) => state.shaderSources.push(src),
+ compileShader: () => {},
+ getShaderParameter: () => true,
+ getShaderInfoLog: () => "",
+ deleteShader: () => {},
+ createProgram: () => ({ id: ++state.programCount }),
+ attachShader: () => {},
+ linkProgram: () => {},
+ getProgramParameter: () => true,
+ getProgramInfoLog: () => "",
+ deleteProgram: () => {},
+ getUniformLocation: (_p: unknown, name: string) => name,
+ useProgram: (p: unknown) => {
+ currentProgram = p;
+ state.usedPrograms.push(p);
+ state.calls.push("useProgram");
+ },
+ uniform1f: (name: string, v: number) => {
+ state.uniforms[name] = v;
+ },
+ uniform1i: (name: string, v: number) => {
+ state.uniforms[name] = v;
+ },
+ uniform2f: (name: string, a: number, b: number) => {
+ state.uniforms[name] = [a, b];
+ },
+ viewport: (_x: number, _y: number, w: number, h: number) => state.viewports.push([w, h]),
+ drawArrays: () => state.calls.push(`draw:${(currentProgram as { id: number }).id}`),
+ createTexture: () => ({}),
+ bindTexture: () => {},
+ texParameteri: () => {},
+ texImage2D: () => {},
+ activeTexture: () => {},
+ pixelStorei: () => {},
+ createFramebuffer: () => ({}),
+ bindFramebuffer: (_t: unknown, fb: unknown) => state.calls.push(fb ? "fbo" : "screen"),
+ framebufferTexture2D: () => {},
+ deleteFramebuffer: () => {},
+ deleteTexture: () => {},
+ } as unknown as WebGL2RenderingContext & MockGl;
+ return gl;
+}
+
+let gl: (WebGL2RenderingContext & MockGl) | null = null;
+let errors: unknown[][] = [];
+
+function installCanvasMock(webgl2: () => unknown): void {
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(function (
+ this: HTMLCanvasElement,
+ kind: string,
+ ) {
+ return kind === "webgl2" ? (webgl2() as never) : null;
+ } as never);
+}
+
+/**
+ * Hosts are 0×0 in jsdom; the runtime refuses to paint a zero-area box. Sets
+ * both the layout box (`offsetWidth`/`offsetHeight`, what `deviceSize` reads)
+ * and the client rect (what a GSAP transform would inflate) to the same
+ * values by default — a test that wants to simulate a transformed host
+ * overrides `getBoundingClientRect` afterwards.
+ */
+function sizeHost(host: HTMLElement, width = 320, height = 180): void {
+ host.getBoundingClientRect = () =>
+ ({ width, height, left: 0, top: 0, right: width, bottom: height, x: 0, y: 0 }) as DOMRect;
+ Object.defineProperty(host, "offsetWidth", { value: width, configurable: true });
+ Object.defineProperty(host, "offsetHeight", { value: height, configurable: true });
+}
+
+function makeHost(chain: string, id = "h1"): HTMLElement {
+ const host = document.createElement("div");
+ host.id = id;
+ host.setAttribute("data-vfx-chain", chain);
+ sizeHost(host);
+ document.body.appendChild(host);
+ return host;
+}
+
+const ONE_NODE =
+ '{"version":1,"nodes":[{"type":"fractal-noise","id":"n1","params":{"contrast":562}}]}';
+const TWO_NODES =
+ '{"version":1,"nodes":[{"type":"fractal-noise","id":"n1","params":{}},' +
+ '{"type":"fractal-noise","id":"n2","params":{}}]}';
+
+describe("vfx runtime", () => {
+ beforeEach(() => {
+ document.body.innerHTML = "";
+ gl = createMockGl();
+ installCanvasMock(() => gl);
+ errors = [];
+ override.capture = null;
+ delete compositeWindow().__hf_page_composite_pending;
+ delete compositeWindow().__hf_page_composite_resolve;
+ vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => {
+ errors.push(args);
+ });
+ });
+
+ afterEach(() => {
+ // Empty the registry BEFORE the canvas mock comes off, or jsdom's real
+ // (unimplemented) getContext runs and floods the console.
+ document.body.innerHTML = "";
+ initVfx(document.body, 30);
+ vi.restoreAllMocks();
+ });
+
+ it("registers every [data-vfx-chain] host and creates a missing .hf-vfx-out", () => {
+ const a = makeHost(ONE_NODE, "a");
+ const b = makeHost(ONE_NODE, "b");
+ const preset = document.createElement("canvas");
+ preset.className = "hf-vfx-out";
+ b.appendChild(preset);
+
+ const registry = initVfx(document.body, 30);
+
+ expect(registry).toHaveLength(2);
+ expect(a.querySelectorAll("canvas.hf-vfx-out")).toHaveLength(1);
+ expect(b.querySelectorAll("canvas.hf-vfx-out")).toHaveLength(1);
+ expect(registry[1]!.out).toBe(preset);
+ expect(errors).toEqual([]);
+ });
+
+ it("gives an exporter-emitted .hf-vfx-out the same box as one it creates", () => {
+ const a = makeHost(ONE_NODE, "a");
+ const b = makeHost(ONE_NODE, "b");
+ const preset = document.createElement("canvas");
+ preset.className = "hf-vfx-out";
+ b.appendChild(preset);
+
+ initVfx(document.body, 30);
+
+ const created = a.querySelector("canvas.hf-vfx-out") as HTMLCanvasElement;
+ // The exporter emits the canvas bare (`<canvas class="hf-vfx-out"></canvas>`).
+ // Adopted untouched it stays `position:static; display:inline`, wraps to the
+ // line after the `.hf-vfx-src` canvas and paints one layer height below the
+ // host — measured on retro-wave `#main-l6-text` (findings Task 3.5b).
+ expect(preset.style.position).toBe("absolute");
+ expect(preset.style.cssText).toBe(created.style.cssText);
+ expect(errors).toEqual([]);
+ });
+
+ it("reports an unsupported chain version loudly and registers nothing", () => {
+ makeHost('{"version":2,"nodes":[]}');
+
+ const registry = initVfx(document.body, 30);
+
+ expect(registry).toHaveLength(0);
+ expect(errors).toHaveLength(1);
+ expect(errors[0]![0]).toBe(LABEL);
+ expect(String(errors[0]![1])).toMatch(/vfx/);
+ expect(String(errors[0]![1])).toMatch(/version/);
+ });
+
+ it("reports an unknown effect type loudly", () => {
+ makeHost('{"version":1,"nodes":[{"type":"nope","id":"n1","params":{}}]}');
+
+ expect(initVfx(document.body, 30)).toHaveLength(0);
+ expect(String(errors[0]![1])).toMatch(/unknown effect type/);
+ });
+
+ it("reports an unavailable WebGL2 context loudly and registers nothing", () => {
+ makeHost(ONE_NODE);
+ installCanvasMock(() => null);
+
+ expect(initVfx(document.body, 30)).toHaveLength(0);
+ expect(errors).toHaveLength(1);
+ expect(String(errors[0]![1])).toMatch(/WebGL2/);
+ });
+
+ it("draws one full-screen triangle per enabled node, last pass to the canvas", () => {
+ makeHost(TWO_NODES);
+ initVfx(document.body, 30);
+
+ // Second paint: the ping-pong targets already exist, so the call list is
+ // exactly the draw sequence — which also pins that they are reused.
+ paintVfx(1.25);
+ gl!.calls.length = 0;
+ paintVfx(1.25);
+
+ expect(gl!.calls).toEqual(["useProgram", "fbo", "draw:1", "useProgram", "screen", "draw:2"]);
+ });
+
+ it("passes the seek time, the composition fps and the device-pixel size as uniforms", () => {
+ makeHost(ONE_NODE);
+ initVfx(document.body, 24);
+
+ paintVfx(1.5);
+
+ expect(gl!.uniforms["u_t"]).toBe(1.5);
+ expect(gl!.uniforms["u_fps"]).toBe(24);
+ expect(gl!.uniforms["u_size"]).toEqual([320, 180]);
+ expect(gl!.viewports.at(-1)).toEqual([320, 180]);
+ });
+
+ it("takes a static param from the chain and an animated one from its CSS var", () => {
+ const host = makeHost(ONE_NODE);
+ host.style.setProperty("--vfx-n1-opacity", "42");
+ initVfx(document.body, 30);
+
+ paintVfx(0);
+
+ expect(gl!.uniforms["u_contrast"]).toBe(562);
+ expect(gl!.uniforms["u_opacity"]).toBe(42);
+ });
+
+ it("clamps a param that the chain put outside the def's range", () => {
+ makeHost(
+ '{"version":1,"nodes":[{"type":"fractal-noise","id":"n1","params":{"contrast":99999}}]}',
+ );
+ initVfx(document.body, 30);
+
+ paintVfx(0);
+
+ expect(gl!.uniforms["u_contrast"]).toBe(1000);
+ });
+
+ it("sizes the output canvas from the host's layout box, not its transformed AABB", () => {
+ // A GSAP `transform: scale(2)` inflates getBoundingClientRect but leaves
+ // offsetWidth/offsetHeight alone — the runtime must use the latter, or a
+ // scaled or rotated host gets an inflated canvas and a stretched capture.
+ const host = makeHost(ONE_NODE);
+ sizeHost(host, 200, 100);
+ host.getBoundingClientRect = () =>
+ ({
+ width: 400,
+ height: 200,
+ left: 0,
+ top: 0,
+ right: 400,
+ bottom: 200,
+ x: 0,
+ y: 0,
+ }) as DOMRect;
+ initVfx(document.body, 30);
+
+ paintVfx(0);
+
+ expect(gl!.uniforms["u_size"]).toEqual([200, 100]);
+ expect(gl!.viewports.at(-1)).toEqual([200, 100]);
+ });
+
+ it("does not paint a host whose box has no area", () => {
+ const host = makeHost(ONE_NODE);
+ sizeHost(host, 0, 0);
+ initVfx(document.body, 30);
+
+ paintVfx(0);
+
+ expect(gl!.calls).toEqual([]);
+ });
+
+ it("reports a lost WebGL context once and then paints that host no more", () => {
+ const host = makeHost(ONE_NODE);
+ const entries = initVfx(document.body, 30);
+ const out = host.querySelector("canvas.hf-vfx-out") as HTMLCanvasElement;
+ const lose = (): void => {
+ out.dispatchEvent(new Event("webglcontextlost", { cancelable: true }));
+ };
+
+ lose();
+ paintVfx(0);
+ // A second loss event, and a second paint, must stay quiet: the report is
+ // the moment of loss, not every frame after it.
+ lose();
+ paintVfx(1);
+
+ expect({
+ contextLost: entries[0]!.contextLost,
+ reports: errors.length,
+ message: String(errors[0]?.[1] ?? ""),
+ calls: gl!.calls,
+ }).toEqual({
+ contextLost: true,
+ reports: 1,
+ message: expect.stringMatching(/context lost/i) as unknown as string,
+ calls: [],
+ });
+ });
+
+ it("forgets the previous composition's hosts when re-initialised", () => {
+ makeHost(ONE_NODE);
+ initVfx(document.body, 30);
+ document.body.innerHTML = "";
+
+ expect(initVfx(document.body, 30)).toHaveLength(0);
+ paintVfx(0);
+ expect(gl!.calls).toEqual([]);
+ });
+});
+
+interface CompositeWindow extends Window {
+ __hf_page_composite_pending?: boolean;
+ __hf_page_composite_resolve?: () => boolean;
+}
+
+function compositeWindow(): CompositeWindow {
+ return window as CompositeWindow;
+}
+
+interface MockCtx2d {
+ cleared: number[][];
+ drawn: { el: Element; w: number; h: number }[];
+}
+
+/** The 2-D slice a capture host uses, with `drawElementImage` present. */
+function createMockCtx2d(onDraw?: () => void): MockCtx2d {
+ const state: MockCtx2d = { cleared: [], drawn: [] };
+ return Object.assign(state, {
+ clearRect: (_x: number, _y: number, w: number, h: number) => state.cleared.push([w, h]),
+ drawElementImage: (el: Element, _x: number, _y: number, w: number, h: number) => {
+ onDraw?.();
+ state.drawn.push({ el, w, h });
+ },
+ }) as MockCtx2d;
+}
+
+/** A `self` host as the exporter emits it: src canvas wrapping `.hf-vfx-in`. */
+function makeCaptureHost(ctx: unknown, id = "cap"): HTMLElement {
+ const host = makeHost(ONE_NODE, id);
+ const src = document.createElement("canvas");
+ src.className = "hf-vfx-src";
+ src.setAttribute("layoutsubtree", "");
+ if (ctx !== undefined) {
+ src.getContext = ((kind: string) => (kind === "2d" ? ctx : null)) as never;
+ }
+ const inner = document.createElement("div");
+ inner.className = "hf-vfx-in";
+ src.appendChild(inner);
+ host.insertBefore(src, host.firstChild);
+ return host;
+}
+
+describe("vfx runtime — self capture", () => {
+ beforeEach(() => {
+ document.body.innerHTML = "";
+ gl = createMockGl();
+ installCanvasMock(() => gl);
+ errors = [];
+ override.capture = "self";
+ // `paintVfx` now registers its preview capture into the module-level
+ // seek-completion set; a leftover entry would stall the next test's barrier.
+ resetSeekDispatchState();
+ delete compositeWindow().__hf_page_composite_pending;
+ delete compositeWindow().__hf_page_composite_resolve;
+ vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => {
+ errors.push(args);
+ });
+ });
+
+ afterEach(() => {
+ document.body.innerHTML = "";
+ override.capture = null;
+ initVfx(document.body, 30);
+ delete compositeWindow().__hf_page_composite_pending;
+ delete compositeWindow().__hf_page_composite_resolve;
+ resetSeekDispatchState();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it("refuses a capture host that has no .hf-vfx-src canvas", () => {
+ makeHost(ONE_NODE);
+
+ expect(initVfx(document.body, 30)).toHaveLength(0);
+ expect(String(errors[0]![1])).toMatch(/hf-vfx-src/);
+ });
+
+ it("names the Chrome flag when drawElementImage is missing", () => {
+ makeCaptureHost({ clearRect: () => {} });
+
+ expect(initVfx(document.body, 30)).toHaveLength(0);
+ expect(String(errors[0]![1])).toMatch(/chrome:\/\/flags\/#canvas-draw-element/);
+ });
+
+ it("arms the page-composite protocol instead of painting inline in engine mode", () => {
+ makeCaptureHost(createMockCtx2d());
+ initVfx(document.body, 30);
+
+ paintVfx(1.25, { engineMode: true });
+
+ expect(compositeWindow().__hf_page_composite_pending).toBe(true);
+ expect(typeof compositeWindow().__hf_page_composite_resolve).toBe("function");
+ expect(gl!.calls).toEqual([]);
+ });
+
+ it("captures, uploads and paints when the engine resolves, then clears the flag", () => {
+ const ctx = createMockCtx2d();
+ const host = makeCaptureHost(ctx);
+ initVfx(document.body, 30);
+ paintVfx(1.25, { engineMode: true });
+
+ expect(compositeWindow().__hf_page_composite_resolve!()).toBe(true);
+
+ expect(ctx.drawn).toHaveLength(1);
+ expect(ctx.drawn[0]!.el).toBe(host.querySelector(".hf-vfx-in"));
+ // Cleared before the draw AND after the upload: the src canvas bitmap does
+ // paint on screen even though its layoutsubtree children do not.
+ expect(ctx.cleared).toEqual([
+ [320, 180],
+ [320, 180],
+ ]);
+ expect(gl!.calls).toEqual(["useProgram", "screen", "draw:1"]);
+ expect(compositeWindow().__hf_page_composite_pending).toBe(false);
+ });
+
+ it("composes with a resolver that was already installed, running it first", () => {
+ const order: string[] = [];
+ compositeWindow().__hf_page_composite_resolve = () => {
+ order.push("prior");
+ return true;
+ };
+ const ctx = createMockCtx2d(() => order.push("vfx"));
+ makeCaptureHost(ctx);
+ initVfx(document.body, 30);
+
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ expect(order).toEqual(["prior", "vfx"]);
+ });
+
+ it("re-wraps a resolver that was installed after ours", () => {
+ const order: string[] = [];
+ const ctx = createMockCtx2d(() => order.push("vfx"));
+ makeCaptureHost(ctx);
+ initVfx(document.body, 30);
+ paintVfx(0, { engineMode: true });
+
+ // shader-transitions' 50 ms poll lands after us and assigns over the slot.
+ compositeWindow().__hf_page_composite_resolve = () => {
+ order.push("late");
+ return true;
+ };
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ expect(order).toEqual(["late", "vfx"]);
+ });
+
+ it("reports a throwing drawElementImage loudly and paints nothing", () => {
+ const ctx = createMockCtx2d(() => {
+ throw new Error(
+ "Failed to execute 'drawElementImage' on 'CanvasRenderingContext2D': " +
+ "No cached paint record for element.",
+ );
+ });
+ makeCaptureHost(ctx);
+ initVfx(document.body, 30);
+ paintVfx(0, { engineMode: true });
+
+ expect(compositeWindow().__hf_page_composite_resolve!()).toBe(false);
+ expect(String(errors[0]![1])).toMatch(/No cached paint record for element/);
+ expect(gl!.calls).toEqual([]);
+ });
+
+ it("skips a host the clip runtime has hidden at this time", () => {
+ const ctx = createMockCtx2d();
+ const host = makeCaptureHost(ctx);
+ initVfx(document.body, 30);
+ host.style.visibility = "hidden";
+
+ paintVfx(0, { engineMode: true });
+
+ expect(compositeWindow().__hf_page_composite_pending).toBeUndefined();
+ expect(ctx.drawn).toHaveLength(0);
+ });
+
+ it("asks the canvas to paint before capturing on the preview path", async () => {
+ const ctx = createMockCtx2d();
+ const host = makeCaptureHost(ctx);
+ const src = host.querySelector("canvas.hf-vfx-src") as HTMLCanvasElement & {
+ requestPaint?: () => void;
+ };
+ let requested = 0;
+ src.requestPaint = () => {
+ requested += 1;
+ };
+ initVfx(document.body, 30);
+
+ paintVfx(0.5);
+ expect(requested).toBe(1);
+ expect(ctx.drawn).toHaveLength(0);
+
+ src.dispatchEvent(new Event("paint"));
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(ctx.drawn).toHaveLength(1);
+ expect(compositeWindow().__hf_page_composite_pending).toBeUndefined();
+ });
+
+ /**
+ * `seekCompositionTimeline` — the seek every `snapshot`/`check`/`compare`/
+ * `validate`/`layout` run goes through — awaits
+ * `window.__hfWaitForSeekCompletion` (this function) and then screenshots.
+ * If the preview capture is not in that set, the screenshot is a race the
+ * host count decides.
+ *
+ * rAF is stubbed to never call back so the ONLY thing that can finish
+ * `awaitCanvasPaint` is a `paint` event; with the real one the barrier would
+ * resolve on a timer and the case would prove nothing.
+ */
+ it("holds the seek-completion barrier until every capture host has painted", async () => {
+ vi.stubGlobal("requestAnimationFrame", () => 1);
+ const ctxA = createMockCtx2d();
+ const ctxB = createMockCtx2d();
+ const srcOf = (host: HTMLElement): HTMLCanvasElement =>
+ host.querySelector("canvas.hf-vfx-src") as HTMLCanvasElement;
+ const a = makeCaptureHost(ctxA, "cap-a");
+ const b = makeCaptureHost(ctxB, "cap-b");
+ initVfx(document.body, 30);
+ const flush = (): Promise<void> => new Promise<void>((r) => setTimeout(r, 0));
+
+ paintVfx(0.5);
+ let resolved = false;
+ const barrier = waitForSeekCompletion().then(() => {
+ resolved = true;
+ });
+ await flush();
+ const beforeAnyPaint = resolved;
+
+ srcOf(a).dispatchEvent(new Event("paint"));
+ await flush();
+ // Still held: one host of two is not a finished frame.
+ const afterFirstPaint = resolved;
+
+ srcOf(b).dispatchEvent(new Event("paint"));
+ await flush();
+ await barrier;
+
+ expect({
+ beforeAnyPaint,
+ afterFirstPaint,
+ resolved,
+ drawn: [ctxA.drawn.length, ctxB.drawn.length],
+ }).toEqual({
+ beforeAnyPaint: false,
+ afterFirstPaint: false,
+ resolved: true,
+ drawn: [1, 1],
+ });
+ expect(errors).toEqual([]);
+ });
+
+ /**
+ * The worst case the ceiling exists for: a host whose canvas never fires
+ * `paint` AND whose rAF never calls back — what a BeginFrame-controlled
+ * compositor (Linux headless-shell, `drawelement` capture) looks like when
+ * `frameCapture.ts` drains this barrier before issuing the frame's
+ * `HeadlessExperimental.beginFrame`. Unbounded, that host holds the barrier
+ * every `__hfWaitForSeekCompletion` caller awaits forever.
+ *
+ * Fake timers so the 2 s ceiling costs no wall clock. The second host proves
+ * the bound is per host: it paints promptly and is captured then, not after
+ * the stalled host's ceiling.
+ */
+ it("bounds a never-painting host's wait, reports it loudly, and leaves its peers alone", async () => {
+ vi.useFakeTimers();
+ try {
+ vi.stubGlobal("requestAnimationFrame", () => 1);
+ const ctxStalled = createMockCtx2d();
+ const ctxPainting = createMockCtx2d();
+ const srcOf = (host: HTMLElement): HTMLCanvasElement =>
+ host.querySelector("canvas.hf-vfx-src") as HTMLCanvasElement;
+ makeCaptureHost(ctxStalled, "cap-stalled");
+ const painting = makeCaptureHost(ctxPainting, "cap-painting");
+ initVfx(document.body, 30);
+
+ paintVfx(0.5);
+ let resolved = false;
+ const barrier = waitForSeekCompletion().then(() => {
+ resolved = true;
+ });
+
+ // The healthy host paints immediately and is captured on its own
+ // schedule — before the stalled host's ceiling, not after it.
+ srcOf(painting).dispatchEvent(new Event("paint"));
+ await vi.advanceTimersByTimeAsync(0);
+ const paintingDrawnEarly = ctxPainting.drawn.length;
+ const heldBeforeCeiling = resolved;
+
+ await vi.advanceTimersByTimeAsync(2000);
+ await barrier;
+
+ expect({
+ paintingDrawnEarly,
+ heldBeforeCeiling,
+ resolved,
+ stalledDrawn: ctxStalled.drawn.length,
+ paintingDrawn: ctxPainting.drawn.length,
+ }).toEqual({
+ paintingDrawnEarly: 1,
+ heldBeforeCeiling: false,
+ resolved: true,
+ // The stalled host is skipped, not guessed at.
+ stalledDrawn: 0,
+ paintingDrawn: 1,
+ });
+ expect(errors).toHaveLength(1);
+ expect(errors[0]![0]).toBe(LABEL);
+ expect(String(errors[0]![1])).toMatch(/#cap-stalled/);
+ expect(String(errors[0]![1])).toMatch(/no paint arrived within 2000ms/);
+ expect(String(errors[0]![1])).toMatch(/BeginFrame/);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/core/src/runtime/vfx.ts b/packages/core/src/runtime/vfx.ts
new file mode 100644
index 0000000000..3f32fc7051
--- /dev/null
+++ b/packages/core/src/runtime/vfx.ts
@@ -0,0 +1,806 @@
+/**
+ * VFX chain runtime — paints every `data-vfx-chain` host's WebGL2 canvas from
+ * `(t, params)` after each seek.
+ *
+ * One registry entry per host element. Shaders are compiled once at init; a
+ * paint binds uniforms and draws one full-screen triangle per enabled node,
+ * ping-ponging through two framebuffers when a chain has more than one node so
+ * the last pass always lands on the visible `.hf-vfx-out` canvas.
+ *
+ * A paint may read only `(u_size, u_t, u_fps, params, u_src)` — no clock, no
+ * randomness, no state carried between paints. That is the determinism
+ * contract the exporter's gate depends on.
+ *
+ * Every failure is loud: the `[HyperFrames] composition script error:` prefix
+ * is what the engine turns into `runtime-error:<compId>` and fails fast on, so
+ * a broken chain stops a render instead of silently rendering the wrong frame.
+ */
+
+import {
+ HF_VFX_ATTR,
+ VfxChainError,
+ chainCapture,
+ enabledVfxNodes,
+ getVfxDef,
+ normalizeVfxParams,
+ parseVfxChain,
+ type HfVfxCapture,
+ type HfVfxChain,
+ type HfVfxDef,
+ type HfVfxNode,
+ type HfVfxParam,
+ type HfVfxParamValues,
+} from "../vfx";
+import { registerSeekCompletion } from "./adapters/seek-dispatch";
+import { isCanvasElement, isHtmlElement } from "./domRealm";
+
+/** The prefix `frameCapture.ts` matches to fail a render fast. */
+const VFX_ERROR_LABEL = "[HyperFrames] composition script error:";
+
+/**
+ * `preserveDrawingBuffer` is what the engine's accelerated-canvas composite
+ * needs to `drawImage` this canvas later (Phase 5); it costs nothing now.
+ */
+const GL_ATTRS: WebGLContextAttributes = {
+ preserveDrawingBuffer: true,
+ antialias: false,
+ premultipliedAlpha: true,
+ alpha: true,
+};
+
+/**
+ * A full-screen triangle from `gl_VertexID` alone — no buffers, no attributes,
+ * so nothing about the geometry can differ between backends. `v_uv` is 0..1
+ * across the viewport with y UP, matching texture space rather than canvas
+ * space.
+ */
+const VERTEX_SHADER = `#version 300 es
+out vec2 v_uv;
+void main() {
+ vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
+ v_uv = p;
+ gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
+}
+`;
+
+/** The html-in-canvas 2-D context, behind the Chrome flag. */
+interface DrawElementCtx extends CanvasRenderingContext2D {
+ drawElementImage: (el: Element, x: number, y: number, w: number, h: number) => void;
+}
+
+/** Chrome's paint-record invalidation hook on a `layoutsubtree` canvas. */
+interface RequestPaintCanvas extends HTMLCanvasElement {
+ requestPaint?: () => void;
+}
+
+interface CompositeWindow extends Window {
+ __hf_page_composite_pending?: boolean;
+ __hf_page_composite_resolve?: () => boolean;
+}
+
+/** Everything a `self` host needs to read its own pixels back. */
+interface VfxCaptureSource {
+ canvas: HTMLCanvasElement;
+ inner: HTMLElement;
+ ctx: DrawElementCtx;
+ texture: WebGLTexture;
+}
+
+/**
+ * Every uniform location one pass can bind, resolved once. `getUniformLocation`
+ * is a synchronous driver query, and the paint loop used to make one per
+ * uniform per param per pass per frame; the program is linked once at init, so
+ * the answers never change.
+ *
+ * `null` is the correct cached value for a uniform the linker optimised out —
+ * `gl.uniform*(null, …)` is a defined no-op, which is what the old per-frame
+ * query did with it too.
+ */
+interface PassLocations {
+ size: WebGLUniformLocation | null;
+ t: WebGLUniformLocation | null;
+ fps: WebGLUniformLocation | null;
+ src: WebGLUniformLocation | null;
+ /** Keyed by the def's param key, without the `u_` prefix. */
+ params: Record<string, WebGLUniformLocation | null>;
+}
+
+interface VfxPass {
+ node: HfVfxNode;
+ def: HfVfxDef;
+ program: WebGLProgram;
+ /** Chain params after clamp/defaults; CSS vars override per paint. */
+ params: HfVfxParamValues;
+ locations: PassLocations;
+}
+
+/** Two colour targets a multi-node chain alternates between. */
+interface PingPong {
+ textures: [WebGLTexture, WebGLTexture];
+ framebuffers: [WebGLFramebuffer, WebGLFramebuffer];
+ width: number;
+ height: number;
+}
+
+export interface VfxEntry {
+ host: HTMLElement;
+ chain: HfVfxChain;
+ capture: HfVfxCapture;
+ out: HTMLCanvasElement;
+ gl: WebGL2RenderingContext;
+ passes: VfxPass[];
+ /** Present exactly when `capture !== "none"`. */
+ src?: VfxCaptureSource;
+ ping?: PingPong;
+ /** Set once `out` fires `webglcontextlost`; the entry never paints again. */
+ contextLost: boolean;
+}
+
+export type VfxRegistry = VfxEntry[];
+
+let registry: VfxRegistry = [];
+let registryFps = 30;
+/** The time the last `paintVfx` was given; a capturing chain paints later. */
+let lastPaintTime = 0;
+/**
+ * Monotonic seek token. Every `paintVfx` claims one; an async capture that
+ * comes back to find a newer token has been superseded and must not repaint.
+ */
+let paintSeq = 0;
+/** The token the page-composite resolver last completed, so a race can yield. */
+let resolvedSeq = -1;
+/** The resolver we installed, and whoever owned the slot when we wrapped it. */
+let vfxResolver: (() => boolean) | null = null;
+let priorResolver: (() => boolean) | null = null;
+
+function reportVfxError(message: string): void {
+ // eslint-disable-next-line no-console
+ console.error(VFX_ERROR_LABEL, `vfx: ${message}`);
+}
+
+function compileShader(
+ gl: WebGL2RenderingContext,
+ type: number,
+ source: string,
+): WebGLShader | null {
+ const shader = gl.createShader(type);
+ if (!shader) return null;
+ gl.shaderSource(shader, source);
+ gl.compileShader(shader);
+ if (gl.getShaderParameter(shader, gl.COMPILE_STATUS)) return shader;
+ reportVfxError(`shader failed to compile: ${gl.getShaderInfoLog(shader) ?? "(no log)"}`);
+ gl.deleteShader(shader);
+ return null;
+}
+
+// The attach/link/delete sequence is the same six WebGL calls colorGrading.ts
+// makes; the two differ in their failure reporting (loud here, `swallow` there)
+// and in who owns the vertex shader, so sharing one helper would couple the
+// vfx runtime's error contract to the colour pipeline's.
+// fallow-ignore-next-line code-duplication
+function linkVfxProgram(gl: WebGL2RenderingContext, frag: string): WebGLProgram | null {
+ const vertex = compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER);
+ const fragment = vertex ? compileShader(gl, gl.FRAGMENT_SHADER, frag) : null;
+ if (!vertex || !fragment) return null;
+ // fallow-ignore-next-line code-duplication
+ const program = gl.createProgram();
+ if (!program) return null;
+ gl.attachShader(program, vertex);
+ gl.attachShader(program, fragment);
+ gl.linkProgram(program);
+ gl.deleteShader(vertex);
+ gl.deleteShader(fragment);
+ if (gl.getProgramParameter(program, gl.LINK_STATUS)) return program;
+ reportVfxError(`program failed to link: ${gl.getProgramInfoLog(program) ?? "(no log)"}`);
+ gl.deleteProgram(program);
+ return null;
+}
+
+/**
+ * The box the interface spec fixes for `.hf-vfx-out` ("it is `position:absolute;
+ * inset:0` and sized to the host's box"). It belongs to the ELEMENT, not to
+ * whoever created it, so an exporter-emitted canvas gets it too.
+ */
+const OUT_BOX = "position:absolute;inset:0;width:100%;height:100%;pointer-events:none;";
+
+/** The output canvas the exporter may already have emitted, else a new one. */
+function findOrCreateOut(host: HTMLElement): HTMLCanvasElement {
+ const existing = host.querySelector("canvas.hf-vfx-out");
+ if (isCanvasElement(existing)) {
+ // The exporter emits the canvas bare — `<canvas class="hf-vfx-out"></canvas>`
+ // — "for layout stability". Adopted untouched it keeps the default
+ // `position:static; display:inline`, so it is an inline box that wraps to
+ // the line AFTER the (layer-wide) `.hf-vfx-src` canvas and paints one full
+ // layer height below the host. Measured on retro-wave `#main-l6-text`:
+ // `.hf-vfx-src` rect top 315.1 h 93.0, `.hf-vfx-out` rect top 409.2 — a
+ // clean, unwarped second copy of the layer below where it belongs, with no
+ // error anywhere (ae-mcp findings §Task 3.5b). Prepending rather than
+ // assigning leaves any style the exporter DID write in the winning position.
+ existing.style.cssText = OUT_BOX + existing.style.cssText;
+ return existing;
+ }
+ const out = document.createElement("canvas");
+ out.className = "hf-vfx-out";
+ out.style.cssText = OUT_BOX;
+ host.appendChild(out);
+ return out;
+}
+
+function resolveUniformLocations(
+ gl: WebGL2RenderingContext,
+ program: WebGLProgram,
+ def: HfVfxDef,
+): PassLocations {
+ const params: Record<string, WebGLUniformLocation | null> = {};
+ for (const param of def.params) {
+ // `ref` params carry element ids, not numbers, and have no uniform.
+ if (param.kind === "ref") continue;
+ params[param.key] = gl.getUniformLocation(program, `u_${param.key}`);
+ }
+ return {
+ size: gl.getUniformLocation(program, "u_size"),
+ t: gl.getUniformLocation(program, "u_t"),
+ fps: gl.getUniformLocation(program, "u_fps"),
+ src: gl.getUniformLocation(program, "u_src"),
+ params,
+ };
+}
+
+function buildPasses(gl: WebGL2RenderingContext, chain: HfVfxChain): VfxPass[] | null {
+ const passes: VfxPass[] = [];
+ for (const node of enabledVfxNodes(chain)) {
+ const def = getVfxDef(node.type);
+ if (!def) {
+ reportVfxError(`node "${node.id}" has unknown effect type "${node.type}"`);
+ return null;
+ }
+ const program = linkVfxProgram(gl, def.frag);
+ if (!program) {
+ reportVfxError(`node "${node.id}" (${def.id}) has no usable program`);
+ return null;
+ }
+ passes.push({
+ node,
+ def,
+ program,
+ params: normalizeVfxParams(def.id, node.params),
+ locations: resolveUniformLocations(gl, program, def),
+ });
+ }
+ return passes;
+}
+
+function createCaptureTexture(gl: WebGL2RenderingContext): WebGLTexture {
+ const texture = gl.createTexture()!;
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ return texture;
+}
+
+/**
+ * The `<canvas layoutsubtree class="hf-vfx-src">` the exporter emits for a
+ * `self` chain, plus its 2-D context. Never injected at runtime: the compiler
+ * derives the `htmlInCanvas` render-mode hint from this canvas being in the
+ * source, and that pin exists for a measured reason.
+ */
+function resolveCaptureSource(
+ host: HTMLElement,
+ gl: WebGL2RenderingContext,
+): VfxCaptureSource | undefined {
+ const canvas = host.querySelector("canvas.hf-vfx-src");
+ const inner = canvas?.querySelector(".hf-vfx-in");
+ if (!isCanvasElement(canvas) || !isHtmlElement(inner)) {
+ reportVfxError(
+ `${describeHost(host)}: a capturing chain needs ` +
+ `<canvas layoutsubtree class="hf-vfx-src"><div class="hf-vfx-in">…</div></canvas> in source.`,
+ );
+ return undefined;
+ }
+ const ctx = canvas.getContext("2d") as DrawElementCtx | null;
+ if (!ctx || typeof ctx.drawElementImage !== "function") {
+ reportVfxError(
+ `${describeHost(host)}: drawElementImage is unavailable, so the layer cannot be ` +
+ `captured. In Studio, enable chrome://flags/#canvas-draw-element.`,
+ );
+ return undefined;
+ }
+ return { canvas, inner, ctx, texture: createCaptureTexture(gl) };
+}
+
+/**
+ * Chrome caps live WebGL contexts (commonly 16, and `colorGrading.ts` holds
+ * one per graded element too), and a driver reset can take one at any moment.
+ * Calls on a lost context are spec'd to do nothing, so without this the chain
+ * would go on "painting" an empty canvas in silence — the one thing this
+ * module promises not to do.
+ *
+ * Only the OUTPUT canvas is watched: `.hf-vfx-src` is a 2-D context and is
+ * unaffected by GL context loss.
+ *
+ * Restore is deliberately unhandled — the entry stays lost for as long as this
+ * registry does. `initVfx` already re-scans and re-registers every host when
+ * the composition mounts and again when a sub-composition arrives, rebuilding
+ * every program, texture and framebuffer from scratch; a second, narrower
+ * rebuild path for `webglcontextrestored` alone would duplicate that one and
+ * be free to drift from it. `preventDefault()` still runs, so the context is
+ * restorable if a follow-up wants to take it.
+ */
+function watchContextLoss(entry: VfxEntry): void {
+ entry.out.addEventListener("webglcontextlost", (event) => {
+ event.preventDefault();
+ // A later `initVfx` may have replaced the registry, and `findOrCreateOut`
+ // hands the same canvas to the new entry — a released entry's loss is
+ // nobody's frame, and reporting it would be a phantom error.
+ if (!registry.includes(entry) || entry.contextLost) return;
+ entry.contextLost = true;
+ reportVfxError(`${describeHost(entry.host)}: WebGL context lost.`);
+ });
+}
+
+function registerVfxHost(host: HTMLElement): VfxEntry | null {
+ let chain: HfVfxChain;
+ try {
+ chain = parseVfxChain(host.getAttribute(HF_VFX_ATTR) ?? "");
+ } catch (err) {
+ const detail = err instanceof VfxChainError ? err.message : String(err);
+ reportVfxError(`${describeHost(host)}: ${detail}`);
+ return null;
+ }
+ const out = findOrCreateOut(host);
+ const gl = out.getContext("webgl2", GL_ATTRS);
+ if (!gl) {
+ reportVfxError(`${describeHost(host)}: WebGL2 is unavailable, so the chain cannot paint.`);
+ out.remove();
+ return null;
+ }
+ const passes = buildPasses(gl, chain);
+ if (!passes) {
+ out.remove();
+ return null;
+ }
+ const capture = chainCapture(chain);
+ const src = capture === "none" ? undefined : resolveCaptureSource(host, gl);
+ if (capture !== "none" && !src) {
+ out.remove();
+ return null;
+ }
+ const entry: VfxEntry = { host, chain, capture, out, gl, passes, src, contextLost: false };
+ watchContextLoss(entry);
+ return entry;
+}
+
+/**
+ * A hidden host has no paint record, so `drawElementImage` would throw on it —
+ * and the clip runtime hides every host outside its `data-start`/`data-duration`
+ * window, which would otherwise fail the render on each of those frames.
+ */
+function isPaintableHost(host: HTMLElement): boolean {
+ const style = getComputedStyle(host);
+ return style.display !== "none" && style.visibility !== "hidden";
+}
+
+function describeHost(host: HTMLElement): string {
+ return host.id ? `#${host.id}` : `<${host.tagName.toLowerCase()}>`;
+}
+
+/** Drop the GL objects the outgoing registry owns before replacing it. */
+function releaseRegistry(): void {
+ for (const entry of registry) {
+ const { gl } = entry;
+ for (const pass of entry.passes) gl.deleteProgram(pass.program);
+ if (entry.src) gl.deleteTexture(entry.src.texture);
+ if (!entry.ping) continue;
+ for (const texture of entry.ping.textures) gl.deleteTexture(texture);
+ for (const framebuffer of entry.ping.framebuffers) gl.deleteFramebuffer(framebuffer);
+ }
+}
+
+/**
+ * Discover every chain host under `root`, compile its programs, and replace
+ * the module registry. Called where the runtime finishes mounting the
+ * composition and AGAIN once sub-compositions have loaded — a host inside a
+ * `data-composition-src` mount is not in the DOM for the first pass, and an
+ * unregistered host paints nothing and reports nothing. Re-initialising
+ * forgets (and releases) the previous pass's hosts.
+ */
+export function initVfx(root: HTMLElement, fps: number): VfxRegistry {
+ releaseRegistry();
+ registry = [];
+ registryFps = Number.isFinite(fps) && fps > 0 ? fps : 30;
+ const hosts = root.querySelectorAll(`[${HF_VFX_ATTR}]`);
+ for (const host of hosts) {
+ if (!isHtmlElement(host)) continue;
+ const entry = registerVfxHost(host);
+ if (entry) registry.push(entry);
+ }
+ return registry;
+}
+
+/**
+ * Device-pixel size of the host's box; `null` when it has no area to paint.
+ *
+ * `offsetWidth`/`offsetHeight`, not `getBoundingClientRect()`: the latter is
+ * the element's transformed axis-aligned bounding box, so a host carrying a
+ * GSAP scale or rotation would get an inflated output canvas and a stretched
+ * capture. An After Effects effect operates on the layer's own untransformed
+ * box, which is what the layout size gives.
+ */
+function deviceSize(host: HTMLElement): { width: number; height: number } | null {
+ const dpr = typeof window === "undefined" ? 1 : window.devicePixelRatio || 1;
+ const width = Math.round(host.offsetWidth * dpr);
+ const height = Math.round(host.offsetHeight * dpr);
+ return width > 0 && height > 0 ? { width, height } : null;
+}
+
+function makePingTarget(
+ gl: WebGL2RenderingContext,
+ width: number,
+ height: number,
+): [WebGLTexture, WebGLFramebuffer] {
+ const texture = gl.createTexture()!;
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ const framebuffer = gl.createFramebuffer()!;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
+ return [texture, framebuffer];
+}
+
+function ensurePingPong(entry: VfxEntry, width: number, height: number): PingPong {
+ const existing = entry.ping;
+ if (existing && existing.width === width && existing.height === height) return existing;
+ const { gl } = entry;
+ if (existing) {
+ for (const t of existing.textures) gl.deleteTexture(t);
+ for (const f of existing.framebuffers) gl.deleteFramebuffer(f);
+ }
+ const a = makePingTarget(gl, width, height);
+ const b = makePingTarget(gl, width, height);
+ const ping: PingPong = {
+ textures: [a[0], b[0]],
+ framebuffers: [a[1], b[1]],
+ width,
+ height,
+ };
+ entry.ping = ping;
+ return ping;
+}
+
+/**
+ * A number for `u_<key>`: the `--vfx-<nodeId>-<key>` CSS var when the def says
+ * the param is animatable and the var resolves, else the chain's clamped value.
+ * Booleans become 0/1; `ref` params carry element ids and have no uniform.
+ */
+function paramUniformValue(
+ param: HfVfxParam,
+ pass: VfxPass,
+ style: CSSStyleDeclaration,
+): number | null {
+ if (param.kind === "ref") return null;
+ if (param.kind === "number" && param.animatable) {
+ const raw = style.getPropertyValue(`--vfx-${pass.node.id}-${param.key}`).trim();
+ const n = raw === "" ? Number.NaN : Number.parseFloat(raw);
+ if (Number.isFinite(n)) return Math.min(param.max, Math.max(param.min, n));
+ }
+ const value = pass.params[param.key];
+ if (typeof value === "boolean") return value ? 1 : 0;
+ return typeof value === "number" ? value : 0;
+}
+
+function setPassUniforms(
+ entry: VfxEntry,
+ pass: VfxPass,
+ style: CSSStyleDeclaration,
+ t: number,
+ width: number,
+ height: number,
+): void {
+ const { gl } = entry;
+ const { locations } = pass;
+ gl.uniform2f(locations.size, width, height);
+ gl.uniform1f(locations.t, t);
+ gl.uniform1f(locations.fps, registryFps);
+ for (const param of pass.def.params) {
+ const value = paramUniformValue(param, pass, style);
+ if (value === null) continue;
+ gl.uniform1f(locations.params[param.key] ?? null, value);
+ }
+}
+
+/** Bind this pass's render target and its input texture. */
+function bindPass(entry: VfxEntry, index: number, last: number, ping: PingPong | null): void {
+ const { gl } = entry;
+ gl.bindFramebuffer(
+ gl.FRAMEBUFFER,
+ index === last || !ping ? null : (ping.framebuffers[index % 2] ?? null),
+ );
+ const source =
+ index === 0 ? (entry.src?.texture ?? null) : ping && ping.textures[(index - 1) % 2];
+ if (!source) return;
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, source);
+ gl.uniform1i(entry.passes[index]!.locations.src, 0);
+}
+
+function paintEntry(entry: VfxEntry, t: number): void {
+ const size = deviceSize(entry.host);
+ if (!size) return;
+ const { gl, out, passes } = entry;
+ if (out.width !== size.width) out.width = size.width;
+ if (out.height !== size.height) out.height = size.height;
+ const ping = passes.length > 1 ? ensurePingPong(entry, size.width, size.height) : null;
+ const style = getComputedStyle(entry.host);
+ const last = passes.length - 1;
+ for (let i = 0; i <= last; i++) {
+ const pass = passes[i]!;
+ // useProgram FIRST: bindPass sets the `u_src` sampler, and uniforms land on
+ // whichever program is current at the time of the call.
+ gl.useProgram(pass.program);
+ bindPass(entry, i, last, ping);
+ gl.viewport(0, 0, size.width, size.height);
+ setPassUniforms(entry, pass, style, t, size.width, size.height);
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
+ }
+}
+
+function uploadCaptureTexture(gl: WebGL2RenderingContext, src: VfxCaptureSource): void {
+ gl.bindTexture(gl.TEXTURE_2D, src.texture);
+ // The full-screen triangle's `v_uv` is y-up and a canvas is y-down; the
+ // kernels write premultiplied colour, so the source must arrive that way too.
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, src.canvas);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
+}
+
+/**
+ * Read the host's own pixels into `u_src`. Both `clearRect`s matter: the first
+ * because `drawElementImage` composites onto whatever is there, the second
+ * because a `layoutsubtree` canvas's BITMAP is painted by the page compositor
+ * even though its children are not — leaving the captured frame in it would
+ * show the unprocessed layer through every transparent pixel of `.hf-vfx-out`.
+ */
+function captureEntry(entry: VfxEntry, quiet = false): boolean {
+ const src = entry.src;
+ const size = deviceSize(entry.host);
+ if (!src || !size) return false;
+ if (src.canvas.width !== size.width) src.canvas.width = size.width;
+ if (src.canvas.height !== size.height) src.canvas.height = size.height;
+ src.ctx.clearRect(0, 0, size.width, size.height);
+ try {
+ src.ctx.drawElementImage(src.inner, 0, 0, size.width, size.height);
+ } catch (err) {
+ // A speculative capture is quiet on purpose: it is the engine path's SECOND
+ // attempt at the same frame, racing the host's own `resolve`, and "no cached
+ // paint record yet" there is expected, recoverable, and must not fail a
+ // render. The authoritative attempt (preview paint, or `resolveVfxCapture`)
+ // still owns the loud error contract.
+ if (!quiet) {
+ reportVfxError(
+ `${describeHost(entry.host)}: drawElementImage failed: ${(err as Error).message} ` +
+ `In Studio, enable chrome://flags/#canvas-draw-element.`,
+ );
+ }
+ return false;
+ }
+ uploadCaptureTexture(entry.gl, src);
+ src.ctx.clearRect(0, 0, size.width, size.height);
+ return true;
+}
+
+/** Phase 2 of the page-composite protocol: the paint records are valid now. */
+function resolveVfxCapture(): boolean {
+ let painted = false;
+ for (const entry of registry) {
+ if (entry.contextLost) continue;
+ if (!entry.src || !isPaintableHost(entry.host)) continue;
+ if (!captureEntry(entry)) continue;
+ paintEntry(entry, lastPaintTime);
+ painted = true;
+ }
+ // Deliberately NOT idempotent: the engine resolves only after its own
+ // before-capture hooks have mutated the DOM (video frames injected as <img>,
+ // scenes cloned), so its capture is the authoritative one even when a
+ // fallback already painted this frame from the pre-hook DOM. Recording the
+ // token is what lets that earlier fallback stand down, not the reverse.
+ resolvedSeq = paintSeq;
+ (window as CompositeWindow).__hf_page_composite_pending = false;
+ return painted;
+}
+
+/**
+ * Claim the engine's two-phase readiness protocol, COMPOSING with whoever else
+ * owns it rather than replacing them: shader-transitions runs first (its
+ * composite is whole-scene, ours is per-layer). Re-checked on every paint
+ * because `installPageSideCompositor` polls for `__hf.seek` on a 50 ms interval
+ * and plainly assigns the slot, so an install after ours would replace us.
+ */
+function armPageComposite(): void {
+ const w = window as CompositeWindow;
+ const current = w.__hf_page_composite_resolve;
+ if (current !== vfxResolver) {
+ priorResolver = typeof current === "function" ? current : null;
+ vfxResolver = () => {
+ const prior = priorResolver ? priorResolver() : false;
+ return resolveVfxCapture() || prior;
+ };
+ w.__hf_page_composite_resolve = vfxResolver;
+ }
+ w.__hf_page_composite_pending = true;
+}
+
+/**
+ * Ceiling on ONE host's `paint` wait before its capture is abandoned.
+ *
+ * A real paint is two animation frames — under 100 ms at any plausible frame
+ * rate — so 2 s is roughly a 20x margin, and it is short next to what a hung
+ * barrier would otherwise burn (Puppeteer's ~180 s CDP `protocolTimeout`). It
+ * is also the deadline this repo already uses for a BeginFrame-shaped wait
+ * (`BEGINFRAME_PROBE_TIMEOUT_MS`, `engine/src/services/browserManager.ts`).
+ *
+ * Deliberately longer than the comparable 250 ms `paint`-event fallback in
+ * `engine/src/services/drawElementService.ts`: that one falls back to DRAWING a
+ * frame-stale snapshot, so a false positive costs a frame of staleness, while
+ * this one skips the host's capture and reports loudly — so its false positives
+ * are expensive and it gets the wider margin.
+ */
+const CAPTURE_PAINT_TIMEOUT_MS = 2000;
+
+/**
+ * Preview/Studio readiness: `drawElementImage` throws "No cached paint record
+ * for element" unless the subtree has been painted since it last changed, and
+ * a synchronous `requestPaint()` does not create one within the same task.
+ *
+ * BOUNDED, because this wait is part of the shared seek-completion barrier
+ * (see `paintVfx`) and neither thing that settles it is guaranteed to happen.
+ * Under BeginFrame control (Linux headless-shell, `drawelement` capture) the
+ * compositor advances only on an explicit `HeadlessExperimental.beginFrame`,
+ * and `frameCapture.ts` issues that inside its per-frame capture stage — AFTER
+ * `prepareFrameForCapture` has already drained this barrier. With no tick yet
+ * for the frame, no `paint` event fires, and the rAF fallback does not fire
+ * either: the engine's own notes say rAF is gated the same way
+ * (`frameCapture.ts` ~line 2445, "waitForFunction uses rAF polling internally,
+ * which won't fire in beginFrame mode"; ~line 4755, "headless only fires rAF
+ * when a frame is produced, and nothing produces one until a screenshot
+ * asks"). `setTimeout` is the one clock that is NOT compositor-gated there —
+ * `drawElementService.ts` (~line 341) describes its 250 ms paint-wait fallback
+ * as burning "on every frame" under BeginFrame control, which can only happen
+ * if the timer fires — so this ceiling is what keeps the barrier live.
+ */
+function awaitCanvasPaint(canvas: HTMLCanvasElement): Promise<"painted" | "timeout"> {
+ return new Promise<"painted" | "timeout">((resolve) => {
+ let settled = false;
+ const finish = (outcome: "painted" | "timeout"): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ canvas.removeEventListener("paint", onPaint);
+ resolve(outcome);
+ };
+ const onPaint = (): void => finish("painted");
+ // Cleared by `finish`, so the common case adds no latency and leaves no
+ // timer behind; on a canvas that never paints it is the only way out.
+ const timer = setTimeout(() => finish("timeout"), CAPTURE_PAINT_TIMEOUT_MS);
+ canvas.addEventListener("paint", onPaint, { once: true });
+ try {
+ (canvas as RequestPaintCanvas).requestPaint?.();
+ } catch {
+ // Feature drift on this build — the rAF fallback below still fires.
+ }
+ if (typeof requestAnimationFrame !== "function") {
+ finish("painted");
+ return;
+ }
+ requestAnimationFrame(() => requestAnimationFrame(() => finish("painted")));
+ });
+}
+
+/**
+ * Wait for one host's canvas to paint, then capture and paint that host.
+ *
+ * Per host, not per batch: a host whose compositor genuinely cannot paint this
+ * frame must not make every other host on the page wait out the ceiling too.
+ * A host that times out is skipped for this paint — no capture, no guess at
+ * pixels — and says so loudly. The report is NOT suppressed in engine mode
+ * even though a capture failure there is quiet (`speculative`): that quiet is
+ * for the engine's second attempt at the same frame, and in `drawelement` /
+ * `beginframe` capture mode there is no second attempt — `frameCapture.ts`
+ * (~line 2708) skips `__hf_page_composite_resolve` in exactly those modes, so
+ * this wait is the only capture path the frame has.
+ */
+async function capturePaintedHost(
+ entry: VfxEntry,
+ t: number,
+ seq: number,
+ speculative: boolean,
+): Promise<void> {
+ if ((await awaitCanvasPaint(entry.src!.canvas)) === "timeout") {
+ reportVfxError(
+ `${describeHost(entry.host)}: no paint arrived within ${CAPTURE_PAINT_TIMEOUT_MS}ms, so ` +
+ `this frame's capture was skipped (a BeginFrame-controlled compositor without a tick ` +
+ `for this frame is a known cause).`,
+ );
+ return;
+ }
+ // A newer seek, or the engine's own resolve, owns these pixels now.
+ if (seq !== paintSeq || resolvedSeq === seq) return;
+ // `initVfx` re-scans when a sub-composition mounts and releases the
+ // outgoing registry's programs and textures; painting a released entry is
+ // a silent GL error, not a frame.
+ if (!registry.includes(entry) || entry.contextLost) return;
+ if (captureEntry(entry, speculative)) paintEntry(entry, t);
+}
+
+async function capturePreviewThenPaint(
+ entries: VfxEntry[],
+ t: number,
+ seq: number,
+ speculative: boolean,
+): Promise<void> {
+ // In parallel, not in sequence: each wait costs up to two animation frames,
+ // so N hosts awaited one after another cost 2N — more slack than the CLI's
+ // post-barrier settle leaves, and the cost grows with the composition.
+ await Promise.all(entries.map((entry) => capturePaintedHost(entry, t, seq, speculative)));
+}
+
+/**
+ * Repaint every registered chain for composition-local time `t`. Called from
+ * the runtime transport's `seek` (preview) and `renderSeek` (engine) — the two
+ * places a frame's DOM state is finished changing.
+ *
+ * A chain with no capture paints inline. A capturing chain cannot: its texture
+ * comes from `drawElementImage`, which needs a paint record that does not exist
+ * yet at this point in the task.
+ *
+ * That deferred capture is REGISTERED INTO THE SHARED SEEK-COMPLETION BARRIER
+ * (`adapters/seek-dispatch.ts`) rather than left fire-and-forget, so the paths
+ * that already drain the barrier wait for it instead of racing it:
+ * `seekCompositionTimeline` awaits `window.__hfWaitForSeekCompletion` before
+ * its settle race and screenshot, which covers `snapshot`, `check`, `compare`,
+ * `validate` and `layout`. Racing it is the silent-blank-under-snapshot defect
+ * this module has already shipped once (dcfbda9fd) — there the capture never
+ * ran at all, here it ran too late, and both read as an unpainted layer.
+ *
+ * Joining that barrier makes this module's wait able to STALL every caller of
+ * `__hfWaitForSeekCompletion`, the engine's render path included:
+ * `frameCapture.ts` drains the barrier inside `prepareFrameForCapture` (~line
+ * 2692), which on a BeginFrame-controlled host (Linux headless-shell,
+ * `drawelement` capture) runs BEFORE the per-frame
+ * `HeadlessExperimental.beginFrame` that the compositor needs to paint at all
+ * (~line 3797). Fire-and-forget, that could not hurt anyone; registered, it
+ * can. `awaitCanvasPaint` is therefore bounded at
+ * `CAPTURE_PAINT_TIMEOUT_MS`, which converts an indefinite hang into a loud,
+ * bounded, per-host failure — the other hosts on the page still paint on their
+ * own schedule, and the barrier always resolves.
+ */
+export function paintVfx(t: number, options?: { engineMode?: boolean }): void {
+ lastPaintTime = t;
+ const seq = ++paintSeq;
+ const capturing: VfxEntry[] = [];
+ for (const entry of registry) {
+ // Reported once, at the moment of loss; repeating it per frame is spam.
+ if (entry.contextLost) continue;
+ if (!isPaintableHost(entry.host)) continue;
+ if (entry.src) capturing.push(entry);
+ else paintEntry(entry, t);
+ }
+ if (capturing.length === 0) return;
+ // Engine mode arms the page-composite protocol AND the preview-side capture,
+ // then paints on whichever completes first. Arming alone was a bet that every
+ // capture host runs under `frameCapture.ts`, and it does not: `hyperframes
+ // snapshot` (and `check`/`compare`/`validate`/`layout`, and Studio's
+ // thumbnail capture) seek through the same `seekCompositionTimeline` →
+ // `renderSeek`, never read `__hf_page_composite_pending`, and never call
+ // `__hf_page_composite_resolve` — so a `self` chain painted nothing there, in
+ // silence. The runtime has to be able to finish its own frame.
+ if (options?.engineMode) armPageComposite();
+ registerSeekCompletion(capturePreviewThenPaint(capturing, t, seq, options?.engineMode === true));
+}
diff --git a/packages/core/src/vfx.test.ts b/packages/core/src/vfx.test.ts
new file mode 100644
index 0000000000..6c470baa51
--- /dev/null
+++ b/packages/core/src/vfx.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+import {
+ HF_VFX_ATTR,
+ chainCapture,
+ getVfxDef,
+ normalizeVfxParams,
+ parseVfxChain,
+ serializeVfxChain,
+} from "./vfx";
+
+describe("vfx chain", () => {
+ it("round-trips a one-node chain with the audio-chain field names", () => {
+ const json =
+ '{"version":1,"nodes":[{"type":"fractal-noise","id":"n1","params":{"contrast":562}}]}';
+ const chain = parseVfxChain(json);
+ expect(chain.nodes[0].type).toBe("fractal-noise");
+ expect(JSON.parse(serializeVfxChain(chain))).toEqual(JSON.parse(json));
+ });
+ it("rejects an unknown type and a wrong version loudly", () => {
+ expect(() =>
+ parseVfxChain('{"version":1,"nodes":[{"type":"nope","id":"n1","params":{}}]}'),
+ ).toThrow(/unknown effect type/);
+ expect(() => parseVfxChain('{"version":2,"nodes":[]}')).toThrow(/version/);
+ });
+ it("normalizes params to the def's range and defaults", () => {
+ const p = normalizeVfxParams("fractal-noise", { contrast: 99999 });
+ expect(p.contrast).toBe(1000); // clamped to the def's max
+ expect(p.complexity).toBe(6); // default filled in
+ expect(getVfxDef("fractal-noise")!.capture).toBe("none");
+ });
+ it("a chain's capture is the strongest enabled node's", () => {
+ expect(
+ chainCapture(
+ parseVfxChain('{"version":1,"nodes":[{"type":"fractal-noise","id":"n1","params":{}}]}'),
+ ),
+ ).toBe("none");
+ });
+ it("attribute name is data-vfx-chain", () => expect(HF_VFX_ATTR).toBe("data-vfx-chain"));
+});
diff --git a/packages/core/src/vfx.ts b/packages/core/src/vfx.ts
new file mode 100644
index 0000000000..6728d76ff8
--- /dev/null
+++ b/packages/core/src/vfx.ts
@@ -0,0 +1,596 @@
+/**
+ * VFX chain: the one description of every per-pixel effect that can be
+ * applied to a layer's own pixels through the WebGL2 runtime.
+ *
+ * Mirrors `audioFx.ts` (`data-fx-chain`) in shape: a versioned JSON chain
+ * attribute, a def registry with typed params, and parse/serialize/normalize
+ * helpers so the exporter and the runtime agree on one description of each
+ * effect.
+ */
+
+import { FRACTAL_NOISE_FRAG } from "./vfx/fractalNoise.frag";
+import { DISPLACEMENT_MAP_FRAG } from "./vfx/displacementMap.frag";
+import { WAVE_WARP_FRAG } from "./vfx/waveWarp.frag";
+
+export const HF_VFX_ATTR = "data-vfx-chain";
+
+/**
+ * Chain files are versioned; a reader must refuse a version it doesn't know.
+ * Exported for the exporter (hyperframes-ae-mcp), which stamps the version it
+ * emits; inside this repo only parse/serialize below read it.
+ */
+// fallow-ignore-next-line unused-export
+export const HF_VFX_CHAIN_VERSION = 1;
+
+/**
+ * What a def's kernel must read besides `(x, y, t, params)`:
+ * - `none` — the kernel is a generator/replacement; no captured texture.
+ * - `self` — the kernel reads the host's own pixels through a `layoutsubtree`
+ * capture canvas.
+ * - `backdrop` — the kernel reads everything below the host (adjustment-layer
+ * style effects).
+ */
+export type HfVfxCapture = "none" | "self" | "backdrop";
+
+export interface HfVfxNumberParam {
+ kind: "number";
+ key: string;
+ label: string;
+ unit: string;
+ min: number;
+ max: number;
+ step: number;
+ default: number;
+ /** May be driven by a `--vfx-<nodeId>-<key>` CSS var instead of `params`. */
+ animatable?: boolean;
+ hint?: string;
+}
+
+export interface HfVfxEnumParam {
+ kind: "enum";
+ key: string;
+ label: string;
+ options: readonly { value: number; label: string }[];
+ default: number;
+ hint?: string;
+}
+
+export interface HfVfxBoolParam {
+ kind: "bool";
+ key: string;
+ label: string;
+ default: boolean;
+}
+
+/** A second-source param (v1.1): its value is the id of another element. */
+export interface HfVfxRefParam {
+ kind: "ref";
+ key: string;
+ label: string;
+}
+
+export type HfVfxParam = HfVfxNumberParam | HfVfxEnumParam | HfVfxBoolParam | HfVfxRefParam;
+
+/** `string` values only occur for `ref` params (element ids). */
+export type HfVfxParamValues = Record<string, number | boolean | string>;
+
+export interface HfVfxDef {
+ id: string;
+ label: string;
+ /** What the kernel must read besides (x, y, t, params). */
+ capture: HfVfxCapture;
+ params: readonly HfVfxParam[];
+ /** GLSL ES 3.00 fragment source; uniforms are u_size/u_t/u_fps/u_src(2)/u_<key>. */
+ frag: string;
+ /** AE match name this def ports, for docs — e.g. "ADBE Fractal Noise". */
+ ae?: string;
+}
+
+/**
+ * After Effects' channel selector, shared by both Displacement Map axes.
+ * Hue (6), Lightness (7) and Saturation (8) stay selectable and are read as
+ * Luminance by the kernel — folding them back to the param's default would
+ * mean Red on the horizontal axis, a much larger error.
+ */
+const DISPLACEMENT_CHANNELS = [
+ { value: 1, label: "Red" },
+ { value: 2, label: "Green" },
+ { value: 3, label: "Blue" },
+ { value: 4, label: "Alpha" },
+ { value: 5, label: "Luminance" },
+ { value: 6, label: "Hue" },
+ { value: 7, label: "Lightness" },
+ { value: 8, label: "Saturation" },
+ { value: 9, label: "Full" },
+ { value: 10, label: "Half" },
+ { value: 11, label: "Off" },
+] as const;
+
+/**
+ * The def registry. Params come from the AE deep dives and retro-wave's
+ * observed values; each kernel's own `frag` module states the v1 scope
+ * decision — which of the effect's modes it actually implements and why.
+ *
+ * Exported as the whole registry for the exporter and Studio's effect picker;
+ * inside the runtime, defs are reached through `getVfxDef`.
+ */
+// fallow-ignore-next-line unused-export
+export const HF_VFX: readonly HfVfxDef[] = [
+ {
+ id: "fractal-noise",
+ label: "Fractal Noise",
+ ae: "ADBE Fractal Noise",
+ capture: "none",
+ frag: FRACTAL_NOISE_FRAG,
+ params: [
+ {
+ kind: "enum",
+ key: "fractalType",
+ label: "Fractal Type",
+ options: [{ value: 1, label: "Basic" }],
+ default: 1,
+ hint: "Only Basic is implemented in v1.",
+ },
+ {
+ kind: "enum",
+ key: "noiseType",
+ label: "Noise Type",
+ options: [
+ { value: 1, label: "Block" },
+ { value: 2, label: "Linear" },
+ { value: 3, label: "Soft Linear" },
+ { value: 4, label: "Spline" },
+ ],
+ default: 3,
+ },
+ { kind: "bool", key: "invert", label: "Invert", default: false },
+ {
+ kind: "number",
+ key: "contrast",
+ label: "Contrast",
+ unit: "%",
+ min: 0,
+ max: 1000,
+ step: 1,
+ default: 100,
+ },
+ {
+ kind: "number",
+ key: "brightness",
+ label: "Brightness",
+ unit: "",
+ min: -1000,
+ max: 1000,
+ step: 1,
+ default: 0,
+ },
+ {
+ kind: "number",
+ key: "scale",
+ label: "Scale",
+ unit: "%",
+ min: 6,
+ max: 10000,
+ step: 1,
+ default: 100,
+ },
+ {
+ kind: "number",
+ key: "complexity",
+ label: "Complexity",
+ unit: "",
+ min: 1,
+ max: 20,
+ step: 1,
+ default: 6,
+ },
+ {
+ kind: "number",
+ key: "subInfluence",
+ label: "Sub Influence",
+ unit: "%",
+ min: 0,
+ max: 100,
+ step: 1,
+ default: 70,
+ },
+ {
+ kind: "number",
+ key: "subScaling",
+ label: "Sub Scaling",
+ unit: "%",
+ min: 0,
+ max: 100,
+ step: 1,
+ default: 56,
+ },
+ {
+ kind: "number",
+ key: "evolution",
+ label: "Evolution",
+ unit: "revolutions",
+ min: -10000,
+ max: 10000,
+ step: 0.01,
+ default: 0,
+ animatable: true,
+ },
+ {
+ kind: "number",
+ key: "randomSeed",
+ label: "Random Seed",
+ unit: "",
+ min: 0,
+ max: 99999,
+ step: 1,
+ default: 0,
+ },
+ {
+ kind: "number",
+ key: "opacity",
+ label: "Opacity",
+ unit: "%",
+ min: 0,
+ max: 100,
+ step: 1,
+ default: 100,
+ animatable: true,
+ },
+ ],
+ },
+ {
+ id: "wave-warp",
+ label: "Wave Warp",
+ ae: "ADBE Wave Warp",
+ capture: "self",
+ frag: WAVE_WARP_FRAG,
+ params: [
+ {
+ kind: "enum",
+ key: "waveType",
+ label: "Wave Type",
+ options: [{ value: 1, label: "Sine" }],
+ default: 1,
+ hint: "Only Sine is implemented in v1; the exporter marks the others cosmetic.",
+ },
+ {
+ kind: "number",
+ key: "height",
+ label: "Wave Height",
+ unit: "px",
+ min: -1000,
+ max: 1000,
+ step: 1,
+ default: 10,
+ animatable: true,
+ },
+ {
+ kind: "number",
+ key: "width",
+ label: "Wave Width",
+ unit: "px",
+ min: 1,
+ max: 10000,
+ step: 1,
+ default: 40,
+ animatable: true,
+ },
+ {
+ kind: "number",
+ key: "direction",
+ label: "Direction",
+ unit: "deg",
+ min: -360,
+ max: 360,
+ step: 1,
+ default: 90,
+ },
+ {
+ kind: "number",
+ key: "speed",
+ label: "Wave Speed",
+ unit: "waves/s",
+ min: -100,
+ max: 100,
+ step: 0.1,
+ default: 1,
+ },
+ {
+ kind: "enum",
+ key: "pinning",
+ label: "Pinning",
+ options: [{ value: 1, label: "None" }],
+ default: 1,
+ hint: "Only None is implemented in v1; the exporter marks the others cosmetic.",
+ },
+ {
+ kind: "number",
+ key: "phase",
+ label: "Phase",
+ unit: "deg",
+ min: -360,
+ max: 360,
+ step: 1,
+ default: 0,
+ animatable: true,
+ },
+ ],
+ },
+ {
+ id: "displacement-map",
+ label: "Displacement Map",
+ ae: "ADBE Displacement Map",
+ capture: "self",
+ frag: DISPLACEMENT_MAP_FRAG,
+ params: [
+ {
+ kind: "enum",
+ key: "useH",
+ label: "Use For Horizontal Displacement",
+ options: DISPLACEMENT_CHANNELS,
+ default: 1,
+ hint: "Hue, Lightness and Saturation are read as Luminance in v1.",
+ },
+ {
+ kind: "number",
+ key: "maxH",
+ label: "Max Horizontal Displacement",
+ unit: "px",
+ min: -32000,
+ max: 32000,
+ step: 1,
+ default: 5,
+ animatable: true,
+ },
+ {
+ kind: "enum",
+ key: "useV",
+ label: "Use For Vertical Displacement",
+ options: DISPLACEMENT_CHANNELS,
+ default: 2,
+ hint: "Hue, Lightness and Saturation are read as Luminance in v1.",
+ },
+ {
+ kind: "number",
+ key: "maxV",
+ label: "Max Vertical Displacement",
+ unit: "px",
+ min: -32000,
+ max: 32000,
+ step: 1,
+ default: 5,
+ animatable: true,
+ },
+ {
+ kind: "enum",
+ key: "behavior",
+ label: "Displacement Map Behavior",
+ options: [{ value: 1, label: "Center Map" }],
+ default: 1,
+ hint: "Only Center Map is implemented in v1.",
+ },
+ {
+ kind: "enum",
+ key: "edge",
+ label: "Edge Behavior",
+ options: [{ value: 0, label: "Off" }],
+ default: 0,
+ hint: "Only Off (transparent outside the layer) is implemented in v1.",
+ },
+ {
+ kind: "bool",
+ key: "expand",
+ label: "Expand Output",
+ default: true,
+ },
+ ],
+ },
+] as const;
+
+const BY_ID = new Map(HF_VFX.map((d) => [d.id, d]));
+
+export function getVfxDef(id: string): HfVfxDef | undefined {
+ return BY_ID.get(id);
+}
+
+/**
+ * Clamp and fill a parameter set so it is always renderable: unknown keys are
+ * dropped, missing keys take their default, numbers are clamped into their
+ * declared range, an unrecognised enum value falls back to its default, and a
+ * non-boolean bool value falls back to its default. Mirrors
+ * `normalizeAudioFxParams`.
+ */
+export function normalizeVfxParams(
+ id: string,
+ values: Readonly<HfVfxParamValues> | undefined,
+): HfVfxParamValues {
+ const def = BY_ID.get(id);
+ if (!def) return {};
+ const out: HfVfxParamValues = {};
+ for (const p of def.params) {
+ const raw = values?.[p.key];
+ out[p.key] =
+ p.kind === "enum"
+ ? normalizeEnumParam(p, raw)
+ : p.kind === "bool"
+ ? normalizeBoolParam(p, raw)
+ : p.kind === "ref"
+ ? normalizeRefParam(raw)
+ : normalizeNumberParam(p, raw);
+ }
+ return out;
+}
+
+/** A number, or a string that actually spells one; `undefined` otherwise.
+ * `Number(null)`, `Number("")`, `Number(false)` and `Number([])` are all 0
+ * and all pass `Number.isFinite`, so a raw value of that shape must be
+ * treated as missing rather than coerced to 0 — 0 is a legal value for most
+ * of these knobs, so nothing downstream could otherwise tell. */
+function coerceFiniteNumber(raw: unknown): number | undefined {
+ const n =
+ typeof raw === "number"
+ ? raw
+ : typeof raw === "string" && raw.trim() !== ""
+ ? Number(raw)
+ : Number.NaN;
+ return Number.isFinite(n) ? n : undefined;
+}
+
+function normalizeEnumParam(p: HfVfxEnumParam, raw: unknown): number {
+ const n = coerceFiniteNumber(raw);
+ return n !== undefined && p.options.some((o) => o.value === n) ? n : p.default;
+}
+
+function normalizeBoolParam(p: HfVfxBoolParam, raw: unknown): boolean {
+ return typeof raw === "boolean" ? raw : p.default;
+}
+
+function normalizeRefParam(raw: unknown): string {
+ return typeof raw === "string" ? raw : "";
+}
+
+function normalizeNumberParam(p: HfVfxNumberParam, raw: unknown): number {
+ const n = coerceFiniteNumber(raw);
+ return n !== undefined ? Math.min(p.max, Math.max(p.min, n)) : p.default;
+}
+
+export interface HfVfxNode {
+ type: string;
+ id: string;
+ enabled?: boolean;
+ params: HfVfxParamValues;
+}
+
+export interface HfVfxChain {
+ version: 1;
+ nodes: HfVfxNode[];
+}
+
+export class VfxChainError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "VfxChainError";
+ }
+}
+
+/** The nodes that should paint, in order. */
+export function enabledVfxNodes(chain: HfVfxChain): HfVfxNode[] {
+ return chain.nodes.filter((n) => n.enabled !== false);
+}
+
+const CAPTURE_RANK: Record<HfVfxCapture, number> = { none: 0, self: 1, backdrop: 2 };
+
+/** A chain's capture requirement is the strongest of its enabled nodes'. */
+export function chainCapture(chain: HfVfxChain): HfVfxCapture {
+ let best: HfVfxCapture = "none";
+ for (const node of enabledVfxNodes(chain)) {
+ const def = BY_ID.get(node.type);
+ if (def && CAPTURE_RANK[def.capture] > CAPTURE_RANK[best]) best = def.capture;
+ }
+ return best;
+}
+
+/**
+ * Parse a chain file. Unknown effect ids are rejected rather than skipped: a
+ * chain that silently loses a node would render differently from the
+ * composition the author saved, which is worse than refusing to render at
+ * all. Params are kept as given (not normalized) so a chain round-trips
+ * exactly; call `normalizeVfxParams` at paint time.
+ */
+export function parseVfxChain(json: string): HfVfxChain {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(json);
+ } catch (err) {
+ throw new VfxChainError(`Chain file is not valid JSON: ${(err as Error).message}`);
+ }
+ if (typeof raw !== "object" || raw === null) {
+ throw new VfxChainError("Chain file must be a JSON object.");
+ }
+ const obj = raw as { version?: unknown; nodes?: unknown };
+ if (obj.version !== HF_VFX_CHAIN_VERSION) {
+ throw new VfxChainError(`Unsupported chain version: ${String(obj.version)}`);
+ }
+ if (!Array.isArray(obj.nodes)) {
+ throw new VfxChainError("Chain file is missing a `nodes` array.");
+ }
+ const nodes = obj.nodes.map(parseVfxNode);
+ return { version: HF_VFX_CHAIN_VERSION, nodes };
+}
+
+/** Serialise a chain for the `data-vfx-chain` attribute. */
+export function serializeVfxChain(chain: HfVfxChain): string {
+ return JSON.stringify({
+ version: HF_VFX_CHAIN_VERSION,
+ nodes: chain.nodes.map(serializeVfxNode),
+ });
+}
+
+/** The shape a node is READ as: everything unknown until checked. */
+interface RawVfxNode {
+ type?: unknown;
+ id?: unknown;
+ enabled?: unknown;
+ params?: unknown;
+}
+
+function isPlainObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null;
+}
+
+function requireVfxNodeType(node: RawVfxNode, i: number): string {
+ if (typeof node.type !== "string" || !BY_ID.has(node.type)) {
+ throw new VfxChainError(`Node ${i} has unknown effect type: ${String(node.type)}`);
+ }
+ return node.type;
+}
+
+function requireVfxNodeId(node: RawVfxNode, i: number): string {
+ if (typeof node.id !== "string" || node.id === "") {
+ throw new VfxChainError(`Node ${i} is missing an id.`);
+ }
+ return node.id;
+}
+
+/**
+ * One node out of a chain file, validated. Throws rather than dropping: a
+ * chain that silently loses a node would render differently from the
+ * composition the author saved.
+ */
+function parseVfxNode(n: unknown, i: number): HfVfxNode {
+ if (!isPlainObject(n)) {
+ throw new VfxChainError(`Node ${i} is not an object.`);
+ }
+ const node = n as RawVfxNode;
+ const type = requireVfxNodeType(node, i);
+ const id = requireVfxNodeId(node, i);
+ const params = isPlainObject(node.params) ? (node.params as HfVfxParamValues) : {};
+ return withoutUndefined({
+ type,
+ id,
+ enabled: node.enabled === false ? false : undefined,
+ params,
+ });
+}
+
+/** One node as the `data-vfx-chain` attribute carries it. `enabled` is
+ * omitted when it holds its default, so a plain chain stays plain. */
+function serializeVfxNode(node: HfVfxNode) {
+ return withoutUndefined({
+ type: node.type,
+ id: node.id,
+ enabled: node.enabled === false ? false : undefined,
+ params: node.params,
+ });
+}
+
+// Mirrors audioFx.ts's identical helper (Task 1.1: copy the shape of the
+// audio chain, not its code — the two chain files stay independently
+// readable rather than sharing a module neither owns).
+// fallow-ignore-next-line code-duplication
+function withoutUndefined<T extends object>(obj: T): T {
+ for (const key of Object.keys(obj) as Array<keyof T>) {
+ if (obj[key] === undefined) delete obj[key];
+ }
+ return obj;
+}
diff --git a/packages/core/src/vfx/displacementMap.frag.ts b/packages/core/src/vfx/displacementMap.frag.ts
new file mode 100644
index 0000000000..818fd2a433
--- /dev/null
+++ b/packages/core/src/vfx/displacementMap.frag.ts
@@ -0,0 +1,87 @@
+/**
+ * `displacement-map` kernel — GLSL ES 3.00, capture `self`.
+ *
+ * **Scope (v1, recorded rather than implied):** every corpus instance points
+ * its Displacement Map Layer at **the layer itself** (retro-wave `Main/Text`
+ * → idx 5 = Text; `Logo Anim/Text Site` and `Logo Anim/Logo` likewise), so
+ * `u_src` is both the source and the map and no second capture is needed. A
+ * map that is a *different* layer is out of v1 — it needs a second source,
+ * which is Phase 2b's `ref`-param shape; the exporter emits a structural
+ * capability for it instead.
+ *
+ * Per axis: `d = (channel(map) − 0.5) · 2 · max`, then sample `u_src` at
+ * `uv + d/u_size` with **clamp-to-transparent** edges (Edge = Off, the only
+ * mode v1 implements). Behavior is Center Map only. `expand` is carried for
+ * the exporter but is a no-op: the host's box is the output.
+ *
+ * **Channel selector.** 1 Red, 2 Green, 3 Blue, 4 Alpha, 5 Luminance,
+ * 9 Full, 10 Half, 11 Off are implemented as themselves. 6 Hue, 7 Lightness
+ * and 8 Saturation are **read as Luminance** rather than being dropped back to
+ * the param's default — for Use For Horizontal that default is Red, which
+ * would be a much larger error than luminance. The exporter still marks them
+ * for verification.
+ *
+ * The capture texture is premultiplied, so a colour channel is unpremultiplied
+ * before it is read; alpha is read straight.
+ *
+ * **Open question for the corpus gate, same family as `wave-warp`'s
+ * `direction`:** the vertical displacement is applied in the shader's y-up
+ * pixel space, so a Green above 0.5 moves the sample *up* the frame. After
+ * Effects works in y-down. Corpus retro-wave animates both maxima from 0, so
+ * the sign shows up as a mirrored wobble rather than a missing one; if the gate
+ * disagrees, negating `d.y` here (and in the reference) is the whole fix.
+ */
+
+/** Rec.601 luma — what After Effects calls Luminance in these selectors. */
+export const DISPLACEMENT_MAP_CONSTANTS = {
+ lumaR: 0.299,
+ lumaG: 0.587,
+ lumaB: 0.114,
+} as const;
+
+const { lumaR, lumaG, lumaB } = DISPLACEMENT_MAP_CONSTANTS;
+
+export const DISPLACEMENT_MAP_FRAG = `#version 300 es
+precision highp float;
+
+in vec2 v_uv;
+out vec4 fragColor;
+
+uniform vec2 u_size;
+uniform float u_t;
+uniform float u_fps;
+uniform sampler2D u_src;
+uniform float u_useH;
+uniform float u_maxH;
+uniform float u_useV;
+uniform float u_maxV;
+uniform float u_behavior;
+uniform float u_edge;
+uniform float u_expand;
+
+vec4 hfSampleSrc(vec2 uv) {
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return vec4(0.0);
+ return texture(u_src, uv);
+}
+
+// The selector's value, in [0, 1]. Half and Off both land on 0.5, which is the
+// "no displacement" midpoint the caller subtracts.
+float hfMapChannel(vec4 premultiplied, float selector) {
+ vec3 rgb = premultiplied.a > 0.0 ? premultiplied.rgb / premultiplied.a : vec3(0.0);
+ if (selector < 1.5) return rgb.r;
+ if (selector < 2.5) return rgb.g;
+ if (selector < 3.5) return rgb.b;
+ if (selector < 4.5) return premultiplied.a;
+ if (selector < 8.5) return dot(rgb, vec3(${lumaR}, ${lumaG}, ${lumaB}));
+ if (selector < 9.5) return 1.0;
+ return 0.5;
+}
+
+void main() {
+ vec4 mapTexel = texture(u_src, v_uv);
+ float h = hfMapChannel(mapTexel, u_useH);
+ float v = hfMapChannel(mapTexel, u_useV);
+ vec2 d = vec2((h - 0.5) * 2.0 * u_maxH, (v - 0.5) * 2.0 * u_maxV);
+ fragColor = hfSampleSrc(v_uv + d / u_size);
+}
+`;
diff --git a/packages/core/src/vfx/displacementMap.test.ts b/packages/core/src/vfx/displacementMap.test.ts
new file mode 100644
index 0000000000..b30b3a6be4
--- /dev/null
+++ b/packages/core/src/vfx/displacementMap.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from "vitest";
+import { DISPLACEMENT_MAP_FRAG } from "./displacementMap.frag";
+import { displacementMapSampleRef, type MapSampler } from "./refs/displacementMap";
+import { getVfxDef, normalizeVfxParams } from "../vfx";
+
+const P = { x: 137, y: 61 };
+/** retro-wave: Use For Horizontal = Red, Use For Vertical = Green. */
+const RETRO = { useH: 1, useV: 2, behavior: 1, edge: 0, expand: true };
+
+const uniform =
+ (r: number, g: number, b: number, a = 1): MapSampler =>
+ () => ({ r, g, b, a });
+
+const MID_GREY = uniform(0.5, 0.5, 0.5);
+const PURE_RED = uniform(1, 0, 0);
+
+describe("displacement-map def", () => {
+ it("is registered as a self-capture kernel with the real fragment source", () => {
+ const def = getVfxDef("displacement-map")!;
+ expect(def.capture).toBe("self");
+ expect(def.ae).toBe("ADBE Displacement Map");
+ expect(def.frag).toBe(DISPLACEMENT_MAP_FRAG);
+ expect(DISPLACEMENT_MAP_FRAG.startsWith("#version 300 es")).toBe(true);
+ });
+
+ it("normalizes the unimplemented behaviour and edge modes back to the v1 pair", () => {
+ const p = normalizeVfxParams("displacement-map", { behavior: 3, edge: 1 });
+ expect(p["behavior"]).toBe(1);
+ expect(p["edge"]).toBe(0);
+ });
+
+ it("keeps Hue, Lightness and Saturation as selectable channels", () => {
+ // The kernel reads them as Luminance rather than dropping them back to the
+ // param's default, which for Use For Horizontal would be Red.
+ for (const value of [6, 7, 8]) {
+ expect(normalizeVfxParams("displacement-map", { useH: value })["useH"]).toBe(value);
+ }
+ });
+});
+
+describe("displacementMapSampleRef", () => {
+ it("is the identity when both maxima are zero, whatever the map says", () => {
+ expect(displacementMapSampleRef(P, 0, { ...RETRO, maxH: 0, maxV: 0 }, PURE_RED)).toEqual(P);
+ });
+
+ it("is the identity for a mid-grey map at any maximum", () => {
+ expect(displacementMapSampleRef(P, 0, { ...RETRO, maxH: 150, maxV: 309 }, MID_GREY)).toEqual(P);
+ });
+
+ it("shifts by +maxH for a pure-red map on the red channel", () => {
+ const s = displacementMapSampleRef(P, 0, { ...RETRO, maxH: 150, maxV: 0 }, PURE_RED);
+ expect(s.x).toBeCloseTo(P.x + 150, 10);
+ expect(s.y).toBe(P.y);
+ });
+
+ it("shifts by −maxV when the vertical channel reads zero", () => {
+ const s = displacementMapSampleRef(P, 0, { ...RETRO, maxH: 0, maxV: 309 }, PURE_RED);
+ expect(s.y).toBeCloseTo(P.y - 309, 10);
+ });
+
+ it("reads Full as +max, Half and Off as no displacement", () => {
+ const at = (useH: number): number =>
+ displacementMapSampleRef(P, 0, { ...RETRO, useH, maxH: 100, maxV: 0 }, uniform(0, 0, 0)).x;
+ expect(at(9)).toBeCloseTo(P.x + 100, 10);
+ expect(at(10)).toBe(P.x);
+ expect(at(11)).toBe(P.x);
+ });
+
+ it("reads Hue, Lightness and Saturation as Luminance", () => {
+ const at = (useH: number): number =>
+ displacementMapSampleRef(P, 0, { ...RETRO, useH, maxH: 100, maxV: 0 }, uniform(1, 0.5, 0.2))
+ .x;
+ for (const value of [6, 7, 8]) expect(at(value)).toBeCloseTo(at(5), 10);
+ });
+
+ it("unpremultiplies the map before reading a colour channel", () => {
+ // The capture texture is premultiplied, so a half-transparent pure red
+ // arrives as (0.5, 0, 0, 0.5) and must still read as red = 1.
+ const premultipliedRed = uniform(0.5, 0, 0, 0.5);
+ expect(
+ displacementMapSampleRef(P, 0, { ...RETRO, maxH: 100, maxV: 0 }, premultipliedRed).x,
+ ).toBeCloseTo(P.x + 100, 10);
+ });
+
+ it("reads alpha straight, without unpremultiplying it", () => {
+ const s = displacementMapSampleRef(
+ P,
+ 0,
+ { ...RETRO, useH: 4, maxH: 100, maxV: 0 },
+ uniform(0, 0, 0, 1),
+ );
+ expect(s.x).toBeCloseTo(P.x + 100, 10);
+ });
+
+ it("is a pure function of its inputs", () => {
+ const at = () =>
+ displacementMapSampleRef(P, 0.37, { ...RETRO, maxH: 150, maxV: 309 }, PURE_RED);
+ expect(at()).toEqual(at());
+ });
+});
diff --git a/packages/core/src/vfx/fractalNoise.frag.ts b/packages/core/src/vfx/fractalNoise.frag.ts
new file mode 100644
index 0000000000..65986c14eb
--- /dev/null
+++ b/packages/core/src/vfx/fractalNoise.frag.ts
@@ -0,0 +1,129 @@
+/**
+ * `fractal-noise` kernel — GLSL ES 3.00, capture `none`.
+ *
+ * **Scope (v1, recorded rather than implied):** After Effects' Fractal Noise
+ * builds a 64×64 CPU lattice per Random Seed / Evolution and runs one of 17
+ * fractal-type kernels over it. The corpus needs exactly one point of that
+ * space (Basic, Noise Type 3, Complexity 6, Sub Influence 70 %, Sub Scaling
+ * 56 %, Contrast 562, Scale 411, Evolution 0, Seed 0, **Opacity 5 %**), and at
+ * 5 % opacity an approximate fBm is very likely to pass the gate. So this is
+ * the classic textbook construction — value noise on an integer lattice, a
+ * fixed 32-bit hash, `complexity` octaves with lacunarity `100/subScaling` and
+ * gain `subInfluence/100`, then AE's linear contrast/brightness remap.
+ * **Exactness against AE is not claimed in v1**; a Tier-1 decode of
+ * `FracBASICKernel` plus the lattice is the upgrade path.
+ *
+ * Two v1 approximations worth naming:
+ * - **Evolution** translates the noise field rather than rotating it. AE
+ * evolves through a third axis; 2-D value noise has none, and the corpus
+ * point is Evolution 0.
+ * - **Noise Type** selects the interpolation curve (Block / Linear / Soft
+ * Linear / Spline) rather than a different lattice.
+ *
+ * The kernel is time-invariant: animation reaches it through `evolution`, not
+ * through `u_t`. `u_t`/`u_fps`/`u_fractalType` are declared for the uniform
+ * contract and go unread, which is why a GL driver may optimise them away.
+ */
+
+/**
+ * The single source of truth for the hash. Both this GLSL string and the CPU
+ * reference (`refs/fractalNoise.ts`) are built from these numbers, so a change
+ * to the picture cannot land in one without the other.
+ */
+export const HASH_CONSTANTS = {
+ /** Odd 32-bit multipliers, one per lattice axis plus one for the seed. */
+ mulX: 374761393,
+ mulY: 668265263,
+ mulMix: 1274126177,
+ /** 2^32/φ — breaks the all-zero fixed point at lattice corner (0, 0). */
+ offset: 2654435769,
+ shift1: 13,
+ shift2: 16,
+ /** 2^32: maps the mixed 32-bit word into [0, 1). */
+ divisor: 4294967296,
+} as const;
+
+const { mulX, mulY, mulMix, offset, shift1, shift2, divisor } = HASH_CONSTANTS;
+
+/** The most octaves any chain can ask for — the def clamps `complexity` to 20. */
+const MAX_OCTAVES = 20;
+
+export const FRACTAL_NOISE_FRAG = `#version 300 es
+precision highp float;
+precision highp int;
+
+in vec2 v_uv;
+out vec4 fragColor;
+
+uniform vec2 u_size;
+uniform float u_t;
+uniform float u_fps;
+uniform float u_fractalType;
+uniform float u_noiseType;
+uniform float u_invert;
+uniform float u_contrast;
+uniform float u_brightness;
+uniform float u_scale;
+uniform float u_complexity;
+uniform float u_subInfluence;
+uniform float u_subScaling;
+uniform float u_evolution;
+uniform float u_randomSeed;
+uniform float u_opacity;
+
+float hfHashUnit(int ix, int iy, int seed) {
+ uint h = ((uint(ix) * ${mulX}u) ^ (uint(iy) * ${mulY}u) ^ (uint(seed) * ${mulMix}u)) + ${offset}u;
+ h = h ^ (h >> ${shift1}u);
+ h = h * ${mulMix}u;
+ h = h ^ (h >> ${shift2}u);
+ return float(h) / ${divisor}.0;
+}
+
+float hfFade(float f, float noiseType) {
+ if (noiseType < 1.5) return 0.0;
+ if (noiseType < 2.5) return f;
+ if (noiseType < 3.5) return f * f * (3.0 - 2.0 * f);
+ return f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
+}
+
+float hfValueNoise(vec2 p, int seed) {
+ vec2 cell = floor(p);
+ vec2 f = p - cell;
+ int ix = int(cell.x);
+ int iy = int(cell.y);
+ float sx = hfFade(f.x, u_noiseType);
+ float sy = hfFade(f.y, u_noiseType);
+ float bottom = mix(hfHashUnit(ix, iy, seed), hfHashUnit(ix + 1, iy, seed), sx);
+ float top = mix(hfHashUnit(ix, iy + 1, seed), hfHashUnit(ix + 1, iy + 1, seed), sx);
+ return mix(bottom, top, sy);
+}
+
+float hfFbm(vec2 p) {
+ float lacunarity = 100.0 / max(u_subScaling, 1.0);
+ float gain = u_subInfluence / 100.0;
+ int seed = int(u_randomSeed);
+ float amp = 1.0;
+ float freq = 1.0;
+ float sum = 0.0;
+ float norm = 0.0;
+ for (int i = 0; i < ${MAX_OCTAVES}; i++) {
+ if (float(i) >= u_complexity) break;
+ sum += amp * hfValueNoise(p * freq, seed + i);
+ norm += amp;
+ amp *= gain;
+ freq *= lacunarity;
+ }
+ return norm > 0.0 ? sum / norm : 0.0;
+}
+
+void main() {
+ vec2 px = v_uv * u_size;
+ vec2 p = px / max(u_scale, 1.0) + vec2(u_evolution, u_evolution * 0.5);
+ float v = hfFbm(p);
+ v = (v - 0.5) * (u_contrast / 100.0) + 0.5 + u_brightness / 100.0;
+ if (u_invert > 0.5) v = 1.0 - v;
+ v = clamp(v, 0.0, 1.0);
+ float a = clamp(u_opacity / 100.0, 0.0, 1.0);
+ fragColor = vec4(v * a, v * a, v * a, a);
+}
+`;
diff --git a/packages/core/src/vfx/fractalNoise.test.ts b/packages/core/src/vfx/fractalNoise.test.ts
new file mode 100644
index 0000000000..219a766f36
--- /dev/null
+++ b/packages/core/src/vfx/fractalNoise.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from "vitest";
+import { FRACTAL_NOISE_FRAG, HASH_CONSTANTS } from "./fractalNoise.frag";
+import { fractalNoiseHashUnit, fractalNoiseRef } from "./refs/fractalNoise";
+import { getVfxDef } from "../vfx";
+
+/** Complexity 1, contrast 100, brightness 0: the kernel is one raw octave. */
+const FLAT = { complexity: 1, contrast: 100, brightness: 0, scale: 100, subScaling: 56 };
+
+describe("fractal-noise hash", () => {
+ /**
+ * Four values computed from the chosen mixer BEFORE it was written into
+ * either the GLSL or the CPU reference. They pin the hash: a later refactor
+ * that changes the picture cannot pass this test quietly.
+ */
+ it.each([
+ [0, 0, 0, 0.5737507424782962],
+ [1, 0, 0, 0.48128097131848335],
+ [0, 1, 0, 0.76671754848212],
+ [-3, 7, 42, 0.4487817834597081],
+ ])("hashes lattice corner (%i, %i) seed %i", (ix, iy, seed, expected) => {
+ expect(fractalNoiseHashUnit(ix, iy, seed)).toBeCloseTo(expected, 15);
+ });
+
+ it("builds the GLSL from the same constants the CPU reference uses", () => {
+ for (const value of Object.values(HASH_CONSTANTS)) {
+ expect(FRACTAL_NOISE_FRAG).toContain(String(value));
+ }
+ });
+
+ it("is the def's fragment source, not the registry placeholder", () => {
+ expect(getVfxDef("fractal-noise")!.frag).toBe(FRACTAL_NOISE_FRAG);
+ expect(FRACTAL_NOISE_FRAG.startsWith("#version 300 es")).toBe(true);
+ });
+});
+
+describe("fractalNoiseRef", () => {
+ it("returns the same value for the same inputs twice", () => {
+ const at = () => fractalNoiseRef({ x: 137, y: 61 }, 1.25, { scale: 411, contrast: 562 });
+ expect(at()).toBe(at());
+ });
+
+ it("differs between random seeds", () => {
+ const p = { x: 137, y: 61 };
+ const a = fractalNoiseRef(p, 0, { ...FLAT, randomSeed: 0 });
+ const b = fractalNoiseRef(p, 0, { ...FLAT, randomSeed: 1 });
+ expect(a).not.toBe(b);
+ });
+
+ it("stays inside [0, 1] at contrast 100 across the frame", () => {
+ for (let y = 0; y < 180; y += 17) {
+ for (let x = 0; x < 320; x += 23) {
+ const v = fractalNoiseRef({ x, y }, 0, { contrast: 100, scale: 411 });
+ expect(v).toBeGreaterThanOrEqual(0);
+ expect(v).toBeLessThanOrEqual(1);
+ }
+ }
+ });
+
+ it("is the bare lattice value at a lattice corner with one octave", () => {
+ // scale 100 ⇒ one lattice cell per 100 device pixels, so (200, 300) is the
+ // integer corner (2, 3) and no interpolation happens.
+ expect(fractalNoiseRef({ x: 200, y: 300 }, 0, FLAT)).toBeCloseTo(
+ fractalNoiseHashUnit(2, 3, 0),
+ 12,
+ );
+ });
+
+ it("inverts about 1 when `invert` is set", () => {
+ const p = { x: 137, y: 61 };
+ const plain = fractalNoiseRef(p, 0, { ...FLAT, scale: 411 });
+ const inverted = fractalNoiseRef(p, 0, { ...FLAT, scale: 411, invert: true });
+ expect(plain + inverted).toBeCloseTo(1, 12);
+ });
+
+ it("raises contrast around the 0.5 midpoint and clamps at the ends", () => {
+ const p = { x: 137, y: 61 };
+ const plain = fractalNoiseRef(p, 0, { ...FLAT, scale: 411 });
+ const punchy = fractalNoiseRef(p, 0, { ...FLAT, scale: 411, contrast: 200 });
+ expect(punchy).toBeCloseTo(Math.min(1, Math.max(0, (plain - 0.5) * 2 + 0.5)), 12);
+ expect(fractalNoiseRef(p, 0, { ...FLAT, scale: 411, contrast: 1000 })).toBeLessThanOrEqual(1);
+ });
+
+ it("moves the field when evolution advances", () => {
+ const p = { x: 137, y: 61 };
+ expect(fractalNoiseRef(p, 0, { ...FLAT, scale: 411, evolution: 0 })).not.toBe(
+ fractalNoiseRef(p, 0, { ...FLAT, scale: 411, evolution: 0.25 }),
+ );
+ });
+
+ it("clamps a param the caller put outside the def's range", () => {
+ const p = { x: 137, y: 61 };
+ expect(fractalNoiseRef(p, 0, { ...FLAT, scale: 411, contrast: 99999 })).toBe(
+ fractalNoiseRef(p, 0, { ...FLAT, scale: 411, contrast: 1000 }),
+ );
+ });
+});
diff --git a/packages/core/src/vfx/refs/displacementMap.ts b/packages/core/src/vfx/refs/displacementMap.ts
new file mode 100644
index 0000000000..b268a3e839
--- /dev/null
+++ b/packages/core/src/vfx/refs/displacementMap.ts
@@ -0,0 +1,64 @@
+/**
+ * CPU reference for the `displacement-map` kernel. Like `wave-warp`'s it
+ * returns the *source coordinate* the kernel samples rather than a colour.
+ *
+ * Coordinates are device pixels with y measured from the bottom — the shader's
+ * `v_uv * u_size`, and the order `gl.readPixels` returns rows in.
+ *
+ * The kernel is a two-input operation even in v1, where both inputs happen to
+ * be the same texture, so the map arrives as a sampler the caller supplies
+ * rather than being implied. Its values are **premultiplied**, matching the
+ * capture texture the runtime uploads.
+ */
+
+import { normalizeVfxParams, type HfVfxParamValues } from "../../vfx";
+import { DISPLACEMENT_MAP_CONSTANTS } from "../displacementMap.frag";
+
+const { lumaR, lumaG, lumaB } = DISPLACEMENT_MAP_CONSTANTS;
+
+export interface MapTexel {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+}
+
+export type MapSampler = (x: number, y: number) => MapTexel;
+
+/** The shader's `hfMapChannel`. */
+function mapChannel(texel: MapTexel, selector: number): number {
+ const scale = texel.a > 0 ? 1 / texel.a : 0;
+ const r = texel.r * scale;
+ const g = texel.g * scale;
+ const b = texel.b * scale;
+ if (selector < 1.5) return r;
+ if (selector < 2.5) return g;
+ if (selector < 3.5) return b;
+ if (selector < 4.5) return texel.a;
+ if (selector < 8.5) return r * lumaR + g * lumaG + b * lumaB;
+ if (selector < 9.5) return 1;
+ return 0.5;
+}
+
+/**
+ * Where the kernel reads from to paint `(x, y)`, in the same pixel space.
+ *
+ * `t` is part of the call shape every kernel reference shares; Displacement Map
+ * is time-invariant — its animation arrives as tweened `maxH`/`maxV`.
+ */
+export function displacementMapSampleRef(
+ p: { x: number; y: number },
+ t: number,
+ params: HfVfxParamValues,
+ map: MapSampler,
+): { x: number; y: number } {
+ void t;
+ const n = normalizeVfxParams("displacement-map", params) as Record<string, number>;
+ const texel = map(p.x, p.y);
+ const h = mapChannel(texel, n["useH"]!);
+ const v = mapChannel(texel, n["useV"]!);
+ return {
+ x: p.x + (h - 0.5) * 2 * n["maxH"]!,
+ y: p.y + (v - 0.5) * 2 * n["maxV"]!,
+ };
+}
diff --git a/packages/core/src/vfx/refs/fractalNoise.ts b/packages/core/src/vfx/refs/fractalNoise.ts
new file mode 100644
index 0000000000..0b13299145
--- /dev/null
+++ b/packages/core/src/vfx/refs/fractalNoise.ts
@@ -0,0 +1,117 @@
+/**
+ * CPU reference for the `fractal-noise` kernel — a pure function of the same
+ * inputs the GLSL gets, built from the same `HASH_CONSTANTS`. The determinism
+ * contract's cross-backend bar (PSNR ≥ 32 dB, K = 4 sample frames) is measured
+ * against this, so it must stay a line-for-line mirror of the shader rather
+ * than an independent idea of what the effect should look like.
+ *
+ * Coordinates are **device pixels with y measured from the bottom** — the
+ * shader's `v_uv * u_size`, and the order `gl.readPixels` returns rows in. The
+ * shader samples fragment centres, so a caller comparing against pixel
+ * `(i, j)` should pass `(i + 0.5, j + 0.5)`.
+ */
+
+import { normalizeVfxParams, type HfVfxParamValues } from "../../vfx";
+import { HASH_CONSTANTS } from "../fractalNoise.frag";
+
+const { mulX, mulY, mulMix, offset, shift1, shift2, divisor } = HASH_CONSTANTS;
+
+/**
+ * The shader's `hfHashUnit`. `Math.imul` + `>>> 0` reproduce GLSL's 32-bit
+ * `uint` wrap-around exactly; without them JS would carry the products into
+ * doubles and drift from the GPU immediately.
+ */
+export function fractalNoiseHashUnit(ix: number, iy: number, seed: number): number {
+ let h = ((Math.imul(ix, mulX) ^ Math.imul(iy, mulY) ^ Math.imul(seed, mulMix)) >>> 0) + offset;
+ h = h >>> 0;
+ h = (h ^ (h >>> shift1)) >>> 0;
+ h = Math.imul(h, mulMix) >>> 0;
+ h = (h ^ (h >>> shift2)) >>> 0;
+ return h / divisor;
+}
+
+/** Noise Type picks the interpolation curve: Block, Linear, Soft Linear, Spline. */
+function fade(f: number, noiseType: number): number {
+ if (noiseType < 1.5) return 0;
+ if (noiseType < 2.5) return f;
+ if (noiseType < 3.5) return f * f * (3 - 2 * f);
+ return f * f * f * (f * (f * 6 - 15) + 10);
+}
+
+function mix(a: number, b: number, w: number): number {
+ return a + (b - a) * w;
+}
+
+function valueNoise(px: number, py: number, seed: number, noiseType: number): number {
+ const cx = Math.floor(px);
+ const cy = Math.floor(py);
+ const sx = fade(px - cx, noiseType);
+ const sy = fade(py - cy, noiseType);
+ const bottom = mix(
+ fractalNoiseHashUnit(cx, cy, seed),
+ fractalNoiseHashUnit(cx + 1, cy, seed),
+ sx,
+ );
+ const top = mix(
+ fractalNoiseHashUnit(cx, cy + 1, seed),
+ fractalNoiseHashUnit(cx + 1, cy + 1, seed),
+ sx,
+ );
+ return mix(bottom, top, sy);
+}
+
+interface FbmSettings {
+ complexity: number;
+ subInfluence: number;
+ subScaling: number;
+ randomSeed: number;
+ noiseType: number;
+}
+
+function fbm(px: number, py: number, s: FbmSettings): number {
+ const lacunarity = 100 / Math.max(s.subScaling, 1);
+ const gain = s.subInfluence / 100;
+ let amp = 1;
+ let freq = 1;
+ let sum = 0;
+ let norm = 0;
+ for (let i = 0; i < s.complexity; i++) {
+ sum += amp * valueNoise(px * freq, py * freq, s.randomSeed + i, s.noiseType);
+ norm += amp;
+ amp *= gain;
+ freq *= lacunarity;
+ }
+ return norm > 0 ? sum / norm : 0;
+}
+
+/**
+ * The grey level the kernel writes at `(x, y)`, in [0, 1]. The shader then
+ * premultiplies it by `opacity/100` and writes that as alpha; this returns the
+ * unpremultiplied value so a caller can check either.
+ *
+ * `t` is part of the call shape every kernel reference shares. Fractal Noise
+ * is time-invariant — its animation arrives as a tweened `evolution` — so it
+ * is deliberately unread here.
+ */
+export function fractalNoiseRef(
+ p: { x: number; y: number },
+ t: number,
+ params: HfVfxParamValues,
+): number {
+ void t;
+ const n = normalizeVfxParams("fractal-noise", params) as Record<string, number | boolean>;
+ const scale = Math.max(n["scale"] as number, 1);
+ const evolution = n["evolution"] as number;
+ const px = p.x / scale + evolution;
+ const py = p.y / scale + evolution * 0.5;
+ let v = fbm(px, py, {
+ complexity: n["complexity"] as number,
+ subInfluence: n["subInfluence"] as number,
+ subScaling: n["subScaling"] as number,
+ randomSeed: Math.trunc(n["randomSeed"] as number),
+ noiseType: n["noiseType"] as number,
+ });
+ v = (v - 0.5) * ((n["contrast"] as number) / 100) + 0.5 + (n["brightness"] as number) / 100;
+ if (n["invert"] === true) v = 1 - v;
+ return Math.min(1, Math.max(0, v));
+}
diff --git a/packages/core/src/vfx/refs/waveWarp.ts b/packages/core/src/vfx/refs/waveWarp.ts
new file mode 100644
index 0000000000..d30dc263d0
--- /dev/null
+++ b/packages/core/src/vfx/refs/waveWarp.ts
@@ -0,0 +1,31 @@
+/**
+ * CPU reference for the `wave-warp` kernel. It returns the *source coordinate*
+ * the kernel samples rather than a colour: the displacement is the whole of
+ * what the kernel decides, and a caller with the source image can look the
+ * colour up itself.
+ *
+ * Coordinates are device pixels with y measured from the bottom — the shader's
+ * `v_uv * u_size`, and the order `gl.readPixels` returns rows in.
+ */
+
+import { normalizeVfxParams, type HfVfxParamValues } from "../../vfx";
+import { WAVE_WARP_CONSTANTS } from "../waveWarp.frag";
+
+const { tau, degreesPerTurn } = WAVE_WARP_CONSTANTS;
+
+/** Where the kernel reads from to paint `(x, y)`, in the same pixel space. */
+export function waveWarpSampleRef(
+ p: { x: number; y: number },
+ t: number,
+ params: HfVfxParamValues,
+): { x: number; y: number } {
+ const n = normalizeVfxParams("wave-warp", params) as Record<string, number>;
+ const dir = (n["direction"]! * Math.PI) / 180;
+ const travelX = Math.sin(dir);
+ const travelY = -Math.cos(dir);
+ const proj = (p.x + 1) * travelX + p.y * travelY;
+ const turns = proj / Math.max(n["width"]!, 1) + n["phase"]! / degreesPerTurn + n["speed"]! * t;
+ const disp = n["height"]! * Math.sin(tau * turns);
+ // The displacement swings perpendicular to the direction of travel.
+ return { x: p.x - travelY * disp, y: p.y + travelX * disp };
+}
diff --git a/packages/core/src/vfx/waveWarp.frag.ts b/packages/core/src/vfx/waveWarp.frag.ts
new file mode 100644
index 0000000000..6634b9e3ea
--- /dev/null
+++ b/packages/core/src/vfx/waveWarp.frag.ts
@@ -0,0 +1,76 @@
+/**
+ * `wave-warp` kernel — GLSL ES 3.00, capture `self`.
+ *
+ * **Scope (v1, recorded rather than implied):** After Effects builds a
+ * 2048-entry displacement table per Wave Type on the CPU and reads it as
+ * `disp = table[round(proj/65536 + phase) & 2047]`, where
+ * `proj = (x + 1)·dirX + y·dirY`. The corpus needs **Wave Type 1 (Sine)** only
+ * (Direction 0, Speed 1, Pinning 1, Phase 0, Height/Width animated), and Sine
+ * ports analytically:
+ *
+ * disp = height · sin(2π · (proj/width + phase/360 + speed·t))
+ *
+ * applied perpendicular to the direction of travel, sampling `u_src` at the
+ * displaced coordinate with **clamp-to-transparent** edges. The other wave
+ * types are not defs in v1 — the exporter marks them cosmetic — and a
+ * 2048-wide strip probe is the upgrade path if the gate fails on Sine.
+ *
+ * **Pinning is not implemented (v1 = 1, "none").** The def's `pinning` option
+ * list carries only that value, so `normalizeVfxParams` folds anything else
+ * back to it, matching how `fractal-noise` handles Fractal Type.
+ *
+ * **Open question for the corpus gate:** `direction` is treated here as the
+ * direction of *travel*, with the displacement perpendicular to it — the
+ * reading the deep dive's `proj` formula supports. If After Effects' UI angle
+ * instead names the *displacement* axis, every direction is 90° out and the
+ * exporter's handler gains that offset. Corpus retro-wave uses Direction 0, so
+ * the two readings differ only by which axis moves.
+ */
+
+/**
+ * Angles arrive in degrees (AE's unit) and `phase` is degrees of one wave;
+ * both meet `2π` here, so the constant is shared rather than spelled twice.
+ */
+export const WAVE_WARP_CONSTANTS = {
+ tau: 6.283185307179586,
+ degreesPerTurn: 360,
+} as const;
+
+const { tau, degreesPerTurn } = WAVE_WARP_CONSTANTS;
+
+export const WAVE_WARP_FRAG = `#version 300 es
+precision highp float;
+
+in vec2 v_uv;
+out vec4 fragColor;
+
+uniform vec2 u_size;
+uniform float u_t;
+uniform float u_fps;
+uniform sampler2D u_src;
+uniform float u_waveType;
+uniform float u_height;
+uniform float u_width;
+uniform float u_direction;
+uniform float u_speed;
+uniform float u_pinning;
+uniform float u_phase;
+
+// Outside the layer's own box there is nothing to warp in from, so the wave
+// carries transparency rather than a smeared edge pixel.
+vec4 hfSampleSrc(vec2 uv) {
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return vec4(0.0);
+ return texture(u_src, uv);
+}
+
+void main() {
+ vec2 px = v_uv * u_size;
+ float dir = radians(u_direction);
+ vec2 travel = vec2(sin(dir), -cos(dir));
+ vec2 swing = vec2(-travel.y, travel.x);
+ float proj = (px.x + 1.0) * travel.x + px.y * travel.y;
+ float turns = proj / max(u_width, 1.0) + u_phase / ${degreesPerTurn}.0 + u_speed * u_t;
+ float disp = u_height * sin(${tau} * turns);
+ fragColor = hfSampleSrc((px + swing * disp) / u_size);
+}
+`;
diff --git a/packages/core/src/vfx/waveWarp.test.ts b/packages/core/src/vfx/waveWarp.test.ts
new file mode 100644
index 0000000000..589cb41fa8
--- /dev/null
+++ b/packages/core/src/vfx/waveWarp.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+import { WAVE_WARP_FRAG } from "./waveWarp.frag";
+import { waveWarpSampleRef } from "./refs/waveWarp";
+import { getVfxDef, normalizeVfxParams } from "../vfx";
+
+/** Corpus point: Sine, Direction 0, Speed 1, Pinning 1, Phase 0. */
+const SINE = { waveType: 1, direction: 0, speed: 1, pinning: 1, phase: 0 };
+const P = { x: 137, y: 61 };
+
+describe("wave-warp def", () => {
+ it("is registered as a self-capture kernel with the real fragment source", () => {
+ const def = getVfxDef("wave-warp")!;
+ expect(def.capture).toBe("self");
+ expect(def.ae).toBe("ADBE Wave Warp");
+ expect(def.frag).toBe(WAVE_WARP_FRAG);
+ expect(WAVE_WARP_FRAG.startsWith("#version 300 es")).toBe(true);
+ });
+
+ it("normalizes an unimplemented wave type and pinning back to the v1 pair", () => {
+ const p = normalizeVfxParams("wave-warp", { waveType: 3, pinning: 5 });
+ expect(p["waveType"]).toBe(1);
+ expect(p["pinning"]).toBe(1);
+ });
+});
+
+describe("waveWarpSampleRef", () => {
+ it("is the identity sample at height 0", () => {
+ expect(waveWarpSampleRef(P, 1.25, { ...SINE, height: 0, width: 93.4 })).toEqual(P);
+ });
+
+ it("displaces perpendicular to the direction of travel", () => {
+ // Direction 0 travels along −y, so the displacement is purely horizontal.
+ const s = waveWarpSampleRef(P, 0, { ...SINE, height: 20, width: 93.4 });
+ expect(s.y).toBe(P.y);
+ expect(s.x).not.toBe(P.x);
+ });
+
+ it("is periodic in `width` along the direction of travel", () => {
+ const opts = { ...SINE, height: 20, width: 80 };
+ const a = waveWarpSampleRef(P, 0, opts);
+ const b = waveWarpSampleRef({ x: P.x, y: P.y - 80 }, 0, opts);
+ expect(b.x - P.x).toBeCloseTo(a.x - P.x, 10);
+ });
+
+ it("flips sign with a negative height", () => {
+ const up = waveWarpSampleRef(P, 0, { ...SINE, height: 20, width: 93.4 });
+ const down = waveWarpSampleRef(P, 0, { ...SINE, height: -20, width: 93.4 });
+ expect(up.x - P.x).toBeCloseTo(-(down.x - P.x), 12);
+ });
+
+ it("scales the displacement linearly with height", () => {
+ const one = waveWarpSampleRef(P, 0, { ...SINE, height: 10, width: 93.4 });
+ const two = waveWarpSampleRef(P, 0, { ...SINE, height: 20, width: 93.4 });
+ expect(two.x - P.x).toBeCloseTo(2 * (one.x - P.x), 10);
+ });
+
+ it("advances one whole wave per second at speed 1", () => {
+ const opts = { ...SINE, height: 20, width: 93.4, speed: 1 };
+ expect(waveWarpSampleRef(P, 1, opts).x).toBeCloseTo(waveWarpSampleRef(P, 0, opts).x, 10);
+ expect(waveWarpSampleRef(P, 0.5, opts).x).not.toBeCloseTo(waveWarpSampleRef(P, 0, opts).x, 6);
+ });
+
+ it("treats phase as degrees of the same wave", () => {
+ const opts = { ...SINE, height: 20, width: 93.4, speed: 0 };
+ expect(waveWarpSampleRef(P, 0, { ...opts, phase: 360 }).x).toBeCloseTo(
+ waveWarpSampleRef(P, 0, opts).x,
+ 10,
+ );
+ });
+
+ it("is a pure function of its inputs", () => {
+ const at = () => waveWarpSampleRef(P, 0.37, { ...SINE, height: 21, width: 93.4 });
+ expect(at()).toEqual(at());
+ });
+});
diff --git a/packages/producer/scripts/test-classification.mjs b/packages/producer/scripts/test-classification.mjs
index 4457fb0fb5..8508c2e399 100644
--- a/packages/producer/scripts/test-classification.mjs
+++ b/packages/producer/scripts/test-classification.mjs
@@ -14,6 +14,7 @@ const INTEGRATION_TEST_FILES = new Set([
"src/regression-harness-psnr.test.ts",
"src/services/coreRuntimeBrowser.test.ts",
"src/services/deterministicFonts-systemCapture.test.ts",
+ "src/services/vfxDeterminism.test.ts",
"src/services/distributed/assemble.test.ts",
"src/services/distributed/chunkBoundary.test.ts",
"src/services/distributed/crossWorkerIdempotency.test.ts",
diff --git a/packages/producer/src/services/render/perfSummary.ts b/packages/producer/src/services/render/perfSummary.ts
index b77327005b..02a100ea45 100644
--- a/packages/producer/src/services/render/perfSummary.ts
+++ b/packages/producer/src/services/render/perfSummary.ts
@@ -4,7 +4,7 @@
*/
import { arch, cpus, platform, totalmem } from "node:os";
-import { fpsToNumber } from "@hyperframes/core";
+import { fpsToNumber, type HfVfxCapture } from "@hyperframes/core";
import type {
CapturePerfSummary,
StaticVerificationOutcome,
@@ -108,6 +108,12 @@ export interface DrawElementPerfInput {
/** Authored root data-width/height vs. the scaffold's html/body CSS size; absent when either is undetectable. */
rootBodyMismatch?: boolean;
rootBodyDeltaPxBucket?: "0" | "1-10" | "11-50" | "51+";
+ /** `data-vfx-chain` host count from the same static scan. Only set when the source above is "static". */
+ vfxHostCount?: number;
+ /** Strongest enabled node's capture across every host (`chainCapture`, max: backdrop > self > none). Undefined when vfxHostCount is 0. */
+ vfxCapture?: HfVfxCapture;
+ /** Sorted unique def ids across every enabled node in every chain, comma-joined ("" when vfxHostCount is 0). */
+ vfxTypes?: string;
/** Short-comp band decision when the band was DECISIVE: "applied" (inverts once HF_DE_SHORT_BAND_ROUTE is on; counterfactual in the baseline release) | "skipped_elements" (element ceiling was the only blocker); unset when the band could not have affected this render. */
shortBand?: "applied" | "skipped_elements" | "unmeasured";
parallelRouter?: "routed" | "reverted";
@@ -165,6 +171,9 @@ function aggregateDrawElement(
hasLut: de.hasLut,
rootBodyMismatch: de.rootBodyMismatch,
rootBodyDeltaPxBucket: de.rootBodyDeltaPxBucket,
+ vfxHostCount: de.vfxHostCount,
+ vfxCapture: de.vfxCapture,
+ vfxTypes: de.vfxTypes,
shortBand: de.shortBand,
parallelRouter: de.parallelRouter ?? "none",
preRouterWorkers: de.preRouterWorkers,
diff --git a/packages/producer/src/services/renderOrchestrator.test.ts b/packages/producer/src/services/renderOrchestrator.test.ts
index 221f47b808..0a042cf06f 100644
--- a/packages/producer/src/services/renderOrchestrator.test.ts
+++ b/packages/producer/src/services/renderOrchestrator.test.ts
@@ -2432,6 +2432,54 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {
// default) when there's no root tag at all to compare against.
expect(scan.rootBodyMismatch).toBeUndefined();
expect(scan.rootBodyDeltaPxBucket).toBeUndefined();
+ // data-vfx-chain: no hosts, so vfxCapture never ran ("undefined", not
+ // "none" — there is nothing to have a capture requirement).
+ expect(scan.vfxHostCount).toBe(0);
+ expect(scan.vfxTypes).toBe("");
+ expect(scan.vfxCapture).toBeUndefined();
+ });
+
+ it("counts data-vfx-chain hosts, unions sorted def ids across every chain, and takes the strongest capture", () => {
+ const html =
+ '<div data-vfx-chain=\'{"version":1,"nodes":[{"type":"fractal-noise","id":"n1","params":{}}]}\'></div>' +
+ '<div data-vfx-chain=\'{"version":1,"nodes":[{"type":"wave-warp","id":"n1","params":{}},' +
+ '{"type":"displacement-map","id":"n2","params":{}}]}\'></div>';
+ const scan = scanElementTags(html);
+ expect(scan.vfxHostCount).toBe(2);
+ // fractal-noise is capture "none"; wave-warp/displacement-map are "self"
+ // — the strongest of the two hosts wins.
+ expect(scan.vfxCapture).toBe("self");
+ expect(scan.vfxTypes).toBe("displacement-map,fractal-noise,wave-warp");
+ });
+
+ it("excludes a disabled node's type from vfxTypes but still counts its host", () => {
+ const html =
+ '<div data-vfx-chain=\'{"version":1,"nodes":[' +
+ '{"type":"wave-warp","id":"n1","enabled":false,"params":{}},' +
+ '{"type":"fractal-noise","id":"n2","params":{}}]}\'></div>';
+ const scan = scanElementTags(html);
+ expect(scan.vfxHostCount).toBe(1);
+ expect(scan.vfxTypes).toBe("fractal-noise");
+ // The only enabled node is fractal-noise (capture "none") — the
+ // disabled self-capture node must not inflate the chain's capture.
+ expect(scan.vfxCapture).toBe("none");
+ });
+
+ it("decodes the &quot;-escaped data-vfx-chain form the compile pipeline emits", () => {
+ const html =
+ '<div data-vfx-chain="{&quot;version&quot;:1,&quot;nodes&quot;:[{&quot;type&quot;:' +
+ '&quot;fractal-noise&quot;,&quot;id&quot;:&quot;n1&quot;,&quot;params&quot;:{}}]}"></div>';
+ const scan = scanElementTags(html);
+ expect(scan.vfxHostCount).toBe(1);
+ expect(scan.vfxTypes).toBe("fractal-noise");
+ });
+
+ it("does not crash on a malformed data-vfx-chain attribute; still counts the host, no type or capture signal from it", () => {
+ const html = "<div data-vfx-chain='{not json'></div>";
+ const scan = scanElementTags(html);
+ expect(scan.vfxHostCount).toBe(1);
+ expect(scan.vfxTypes).toBe("");
+ expect(scan.vfxCapture).toBeUndefined();
});
describe("rootBodyMismatch / rootBodyDeltaPxBucket", () => {
@@ -2532,6 +2580,8 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {
audioGroupCount: 0,
colorGradingCount: 0,
hasLut: false,
+ vfxHostCount: 0,
+ vfxTypes: "",
});
});
@@ -2549,6 +2599,8 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {
audioGroupCount: 0,
colorGradingCount: 0,
hasLut: false,
+ vfxHostCount: 0,
+ vfxTypes: "",
});
});
@@ -2573,6 +2625,8 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {
audioGroupCount: 0,
colorGradingCount: 0,
hasLut: false,
+ vfxHostCount: 0,
+ vfxTypes: "",
});
});
@@ -2590,6 +2644,8 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {
audioGroupCount: 0,
colorGradingCount: 0,
hasLut: false,
+ vfxHostCount: 0,
+ vfxTypes: "",
});
});
diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts
index 388192d6ac..0295bf2a1c 100644
--- a/packages/producer/src/services/renderOrchestrator.ts
+++ b/packages/producer/src/services/renderOrchestrator.ts
@@ -49,8 +49,12 @@ import {
type CanvasResolution,
type Fps,
type FpsInput,
+ type HfVfxCapture,
+ chainCapture,
fpsToNumber,
HF_COLOR_GRADING_ATTR,
+ HF_VFX_ATTR,
+ parseVfxChain,
redactTelemetryString,
toFps,
} from "@hyperframes/core";
@@ -601,6 +605,12 @@ export interface RenderPerfSummary {
/** Authored root data-width/height vs. the scaffold's html/body CSS size; absent when either is undetectable. */
rootBodyMismatch?: boolean;
rootBodyDeltaPxBucket?: "0" | "1-10" | "11-50" | "51+";
+ /** `data-vfx-chain` host count from the same static scan. Only set when the source above is "static". */
+ vfxHostCount?: number;
+ /** Strongest enabled node's capture across every `data-vfx-chain` host (`chainCapture`, max: backdrop > self > none). Undefined when vfxHostCount is 0. */
+ vfxCapture?: HfVfxCapture;
+ /** Sorted unique def ids across every enabled node in every chain, comma-joined ("" when vfxHostCount is 0). */
+ vfxTypes?: string;
/** Short-comp band attribution: "applied" | "skipped_elements" | "unmeasured"; unset when the frame count made the band irrelevant. */
shortBand?: "applied" | "skipped_elements" | "unmeasured";
/** DE parallel-router outcome: "routed" (fired, held), "reverted" (fired, self-verify retry rolled back), "none". Mutually exclusive with workerInversion. */
@@ -1584,9 +1594,17 @@ export interface ElementTagScan {
/** Authored root data-width/height vs. the scaffold's html/body CSS size; absent when either is undetectable. */
rootBodyMismatch?: boolean;
rootBodyDeltaPxBucket?: "0" | "1-10" | "11-50" | "51+";
+ /** `data-vfx-chain` host count — each occurrence of the attribute is one host, regardless of how many nodes its chain has. */
+ vfxHostCount: number;
+ /** Strongest enabled node's capture across every host (`chainCapture`, max: backdrop > self > none). Undefined when vfxHostCount is 0. */
+ vfxCapture?: HfVfxCapture;
+ /** Sorted unique def ids across every enabled node in every chain, comma-joined ("" when vfxHostCount is 0). */
+ vfxTypes: string;
}
const MAX_REPORTED_ELEMENT_TAGS = 50;
+/** none < self < backdrop — mirrors @hyperframes/core vfx.ts's internal CAPTURE_RANK, duplicated here (not exported) to combine per-host captures across an entire composition's static scan. */
+const VFX_CAPTURE_RANK: Record<HfVfxCapture, number> = { none: 0, self: 1, backdrop: 2 };
/** First element carrying data-composition-id, the same root marker other `[data-composition-id]` queries here use. */
const ROOT_COMPOSITION_TAG_RE =
@@ -1743,6 +1761,31 @@ export function scanElementTags(html: string): ElementTagScan {
// JSON parse stops running for every element after the first hit.
if (!hasLut) hasLut = colorGradingValueHasLut(m[1] ?? m[2] ?? "");
}
+ let vfxHostCount = 0;
+ let vfxCapture: HfVfxCapture | undefined;
+ const vfxTypeSet = new Set<string>();
+ for (const m of markup.matchAll(new RegExp(`\\b${HF_VFX_ATTR}=(?:"([^"]*)"|'([^']*)')`, "gi"))) {
+ vfxHostCount++;
+ // A chain the runtime would refuse (bad JSON, unknown type, wrong
+ // version) is skipped rather than thrown here: this scan is
+ // observational telemetry, and the runtime already reports the bad
+ // chain loudly at paint time (interface spec's failure modes).
+ try {
+ const chain = parseVfxChain(decodeHtmlAttrJson(m[1] ?? m[2] ?? ""));
+ for (const node of chain.nodes) {
+ if (node.enabled === false) continue;
+ vfxTypeSet.add(node.type);
+ }
+ const capture = chainCapture(chain);
+ if (vfxCapture === undefined || VFX_CAPTURE_RANK[capture] > VFX_CAPTURE_RANK[vfxCapture]) {
+ vfxCapture = capture;
+ }
+ } catch {
+ // Unparsable — not counted toward vfxCapture/vfxTypes, but the host
+ // itself still counts toward vfxHostCount (it IS a data-vfx-chain host).
+ }
+ }
+ const vfxTypes = [...vfxTypeSet].sort().join(",");
return {
total,
byTag,
@@ -1754,17 +1797,25 @@ export function scanElementTags(html: string): ElementTagScan {
audioGroupCount,
colorGradingCount,
hasLut,
+ vfxHostCount,
+ vfxCapture,
+ vfxTypes,
...detectRootBodySizeMismatch(html),
};
}
/** `data-color-grading`'s JSON `lut` field means "has a LUT" (see `HF_COLOR_GRADING_ATTR`).
* Decode is load-bearing: linkedom re-serializes this `&quot;`-escaped, or `JSON.parse` throws. */
-function colorGradingValueHasLut(rawAttributeValue: string): boolean {
- const decoded = rawAttributeValue
+/** Undoes the HTML-entity escaping compiled markup applies to an attribute value with embedded quotes, so it can be `JSON.parse`d. Shared by every attribute-value-is-JSON static scan in this file. */
+function decodeHtmlAttrJson(rawAttributeValue: string): string {
+ return rawAttributeValue
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&amp;/g, "&");
+}
+
+function colorGradingValueHasLut(rawAttributeValue: string): boolean {
+ const decoded = decodeHtmlAttrJson(rawAttributeValue);
try {
const parsed: unknown = JSON.parse(decoded);
if (typeof parsed !== "object" || parsed === null || !("lut" in parsed)) return false;
@@ -1820,6 +1871,9 @@ export async function resolveCompositionElementCount(
hasLut?: boolean;
rootBodyMismatch?: boolean;
rootBodyDeltaPxBucket?: ElementTagScan["rootBodyDeltaPxBucket"];
+ vfxHostCount?: number;
+ vfxCapture?: HfVfxCapture;
+ vfxTypes?: string;
}> {
if (probeSession?.isInitialized) {
try {
@@ -1855,6 +1909,9 @@ export async function resolveCompositionElementCount(
hasLut: scan.hasLut,
rootBodyMismatch: scan.rootBodyMismatch,
rootBodyDeltaPxBucket: scan.rootBodyDeltaPxBucket,
+ vfxHostCount: scan.vfxHostCount,
+ vfxCapture: scan.vfxCapture,
+ vfxTypes: scan.vfxTypes,
};
}
@@ -3621,6 +3678,9 @@ async function executeRenderPipeline(input: {
hasLut,
rootBodyMismatch,
rootBodyDeltaPxBucket,
+ vfxHostCount,
+ vfxCapture,
+ vfxTypes,
} = await resolveCompositionElementCount(probeSession, compiled.html);
const adaptersUsed = await resolveAdaptersUsed(probeSession, compiled.html);
// HF_DE_SHORT_MAX_ELEMENTS=0 is the documented kill switch (symmetric
@@ -5119,6 +5179,9 @@ async function executeRenderPipeline(input: {
hasLut,
rootBodyMismatch,
rootBodyDeltaPxBucket,
+ vfxHostCount,
+ vfxCapture,
+ vfxTypes,
shortBand: deShortBand,
parallelRouter: deParallelRouter,
preRouterWorkers: deParallelRouter ? preRoutingWorkerCount : undefined,
diff --git a/packages/producer/src/services/vfxDeterminism.test.ts b/packages/producer/src/services/vfxDeterminism.test.ts
new file mode 100644
index 0000000000..4cfd7cd3e2
--- /dev/null
+++ b/packages/producer/src/services/vfxDeterminism.test.ts
@@ -0,0 +1,861 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import puppeteer, { type Browser, type Page } from "puppeteer";
+import { displacementMapSampleRef } from "../../../core/src/vfx/refs/displacementMap";
+import { fractalNoiseRef } from "../../../core/src/vfx/refs/fractalNoise";
+import { waveWarpSampleRef } from "../../../core/src/vfx/refs/waveWarp";
+
+/**
+ * Browser-side contract for `data-vfx-chain`, on the real runtime bundle.
+ *
+ * Rebuild the bundle before running this file, or it tests a stale runtime:
+ *
+ * cd packages/core && bun run build:hyperframes-runtime
+ *
+ * `drawElementImage` lives behind `--enable-features=CanvasDrawElement`, which
+ * the engine's own browser launcher already passes
+ * (`packages/engine/src/services/browserManager.ts`,
+ * `CANVAS_DRAW_ELEMENT_FEATURE_FLAG`).
+ */
+const RUNTIME_PATH = resolve(import.meta.dirname, "../../../core/dist/hyperframe.runtime.iife.js");
+
+const HOST_W = 160;
+const HOST_H = 120;
+/** The red block fills the left half of `.hf-vfx-in`. */
+const SQUARE_W = 80;
+/** Clearance between the two hosts of `twoHostFixture`. */
+const GAP = 20;
+/** Opaque red — what a correctly painted identity chain puts at the probe point. */
+const red = [255, 0, 0, 255];
+
+interface CompositeWindow extends Window {
+ __hf_page_composite_pending?: boolean;
+ __hf_page_composite_resolve?: () => boolean;
+ __player?: { renderSeek: (t: number) => void };
+ __playerReady?: boolean;
+ __renderReady?: boolean;
+}
+
+function chainOf(type: string, params: Record<string, number | boolean>): string {
+ return JSON.stringify({ version: 1, nodes: [{ type, id: "n1", params }] });
+}
+
+function waveWarpChain(params: Record<string, number>): string {
+ return chainOf("wave-warp", {
+ waveType: 1,
+ direction: 0,
+ speed: 0,
+ pinning: 1,
+ phase: 0,
+ ...params,
+ });
+}
+
+/**
+ * A `self` host exactly as the exporter emits it: the layer content lives in a
+ * `<canvas layoutsubtree>`, the kernel's output in a sibling canvas. The page
+ * is blue so a transparent output pixel is distinguishable from a black one.
+ *
+ * `.hf-vfx-in` carries an explicit pixel box. Inside a `layoutsubtree` canvas
+ * there is no containing block to resolve `inset: 0` against, so the wrapper
+ * collapses to 0×0 and `drawElementImage` silently draws nothing — the same
+ * collapse `engineModePageComposite.clonePinStyleFor` exists to undo.
+ */
+function fixture(chain: string, innerStyle = "", hostStyle = ""): string {
+ return `<!doctype html>
+<style>
+ html, body { margin: 0; background: #0000ff; }
+ #host { position: absolute; left: 0; top: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ #host > canvas { position: absolute; inset: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ /* An explicit box, not inset:0 — see the fixture note below. */
+ .hf-vfx-in { position: absolute; left: 0; top: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ #square {
+ position: absolute; left: 0; top: 0;
+ width: ${SQUARE_W}px; height: ${HOST_H}px; background: #ff0000;
+ }
+</style>
+<div data-composition-id="root" data-start="0" data-duration="4"
+ data-width="${HOST_W}" data-height="${HOST_H}">
+ <div id="host" class="clip" data-start="0" data-duration="4"
+ data-vfx-chain='${chain}' style="${hostStyle}">
+ <canvas layoutsubtree class="hf-vfx-src"><div class="hf-vfx-in" style="${innerStyle}"><div id="square"></div></div></canvas>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>
+</div>`;
+}
+
+/**
+ * The same `self` host, except `.hf-vfx-in` is a SUB-COMPOSITION MOUNT: it
+ * carries `data-composition-src`, so the runtime empties it and mounts
+ * `inner.html` into it after init. The real exporter emits exactly this shape
+ * for any AE layer that is a pre-comp — the mount attributes live on
+ * `.hf-vfx-in` rather than the host so `resetCompositionHost` cannot take the
+ * `.hf-vfx-src`/`.hf-vfx-out` canvases with it.
+ */
+function mountFixture(chain: string): string {
+ return `<!doctype html>
+<style>
+ html, body { margin: 0; background: #0000ff; }
+ #host { position: absolute; left: 0; top: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ #host > canvas { position: absolute; inset: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+</style>
+<div data-composition-id="root" data-start="0" data-duration="4"
+ data-width="${HOST_W}" data-height="${HOST_H}">
+ <div id="host" class="clip" data-start="0" data-duration="4" data-vfx-chain='${chain}'>
+ <canvas layoutsubtree class="hf-vfx-src" width="${HOST_W}" height="${HOST_H}"><div class="hf-vfx-in" data-composition-id="inner" data-composition-src="inner.html" data-width="${HOST_W}" data-height="${HOST_H}" style="position:absolute;left:0;top:0;width:${HOST_W}px;height:${HOST_H}px;"><div id="pre-mount" style="position:absolute;left:0;top:0;width:${HOST_W}px;height:${HOST_H}px;background:rgb(0,255,0)"></div></div></canvas>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>
+</div>`;
+}
+
+/** The mounted sub-composition, in the exporter's `<template>` document shape. */
+const MOUNT_INNER = `<!doctype html>
+<html lang="en">
+<head><meta charset="utf-8"><title>Inner</title></head>
+<body>
+<template>
+<style>html,body{margin:0;padding:0;background:transparent}#root *{box-sizing:border-box}</style>
+<div id="root" data-composition-id="inner" data-width="${HOST_W}" data-height="${HOST_H}" data-duration="4" data-fps="30" style="position:relative;overflow:hidden;width:${HOST_W}px;height:${HOST_H}px;background:transparent">
+<div id="inner-square" class="clip" data-start="0" data-duration="4" style="position:absolute;left:0;top:0;width:${SQUARE_W}px;height:${HOST_H}px;background:rgb(255,0,0)"></div>
+</div>
+<script>
+(function () {
+ var tl = window.gsap ? gsap.timeline({ paused: true }) : { seek: function () {} };
+ window.__timelines["inner"] = tl;
+})();
+</script>
+</template>
+</body>
+</html>`;
+
+/** A page whose only content is a sub-composition mount. */
+const NESTED_HOST_MAIN = `<!doctype html>
+<style>html, body { margin: 0; background: #0000ff; }</style>
+<div data-composition-id="root" data-start="0" data-duration="4"
+ data-width="${HOST_W}" data-height="${HOST_H}">
+ <div id="outer" class="clip" data-start="0" data-duration="4" data-composition-id="inner"
+ data-composition-src="inner.html" data-width="${HOST_W}" data-height="${HOST_H}"
+ style="position:absolute;left:0;top:0;width:${HOST_W}px;height:${HOST_H}px"></div>
+</div>`;
+
+/** The whole vfx host lives in the sub-composition, so it enters the DOM on mount. */
+const NESTED_HOST_INNER = (chain: string): string => `<!doctype html>
+<html lang="en"><head><meta charset="utf-8"></head><body>
+<template>
+<style>
+ #host { position: absolute; left: 0; top: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ #host > canvas { position: absolute; inset: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+</style>
+<div id="root" data-composition-id="inner" data-width="${HOST_W}" data-height="${HOST_H}" data-duration="4" data-fps="30" style="position:relative;overflow:hidden;width:${HOST_W}px;height:${HOST_H}px">
+ <div id="host" class="clip" data-start="0" data-duration="4" data-vfx-chain='${chain}'>
+ <canvas layoutsubtree class="hf-vfx-src" width="${HOST_W}" height="${HOST_H}"><div class="hf-vfx-in" style="position:absolute;left:0;top:0;width:${HOST_W}px;height:${HOST_H}px"><div style="position:absolute;left:0;top:0;width:${SQUARE_W}px;height:${HOST_H}px;background:rgb(255,0,0)"></div></div></canvas>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>
+</div>
+</template>
+</body></html>`;
+
+/** Where the two side-by-side panels sit in the chain-order fixture. */
+const PANEL = { ax: 20, bx: 220, y: 30, w: HOST_W, h: HOST_H };
+
+/** Retro-wave's Fractal Noise parameter point, opacity raised to 100 so the readback isn't flattened by alpha. */
+const NOISE_PARAMS = {
+ fractalType: 1,
+ noiseType: 3,
+ invert: false,
+ contrast: 562,
+ brightness: 0,
+ scale: 411,
+ complexity: 6,
+ subInfluence: 70,
+ subScaling: 56,
+ evolution: 0,
+ randomSeed: 0,
+ opacity: 100,
+};
+
+/**
+ * `fractal-noise` has `capture: "none"` — no `.hf-vfx-src`/`.hf-vfx-in`
+ * wrapper, so the host is plain content with just the output canvas the
+ * runtime paints into inline on `renderSeek` (no page-composite round trip).
+ */
+function noiseFixture(chain: string): string {
+ return `<!doctype html>
+<style>
+ html, body { margin: 0; background: #000; }
+ #host { position: absolute; left: 0; top: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ #host > canvas { position: absolute; inset: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+</style>
+<div data-composition-id="root" data-start="0" data-duration="4"
+ data-width="${HOST_W}" data-height="${HOST_H}">
+ <div id="host" class="clip" data-start="0" data-duration="4" data-vfx-chain='${chain}'>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>
+</div>`;
+}
+
+async function readNoiseBuffer(
+ page: Page,
+): Promise<{ width: number; height: number; data: number[] }> {
+ return page.evaluate(() => {
+ const out = document.querySelector("canvas.hf-vfx-out") as HTMLCanvasElement;
+ const gl = out.getContext("webgl2")!;
+ const buf = new Uint8Array(out.width * out.height * 4);
+ gl.readPixels(0, 0, out.width, out.height, gl.RGBA, gl.UNSIGNED_BYTE, buf);
+ return { width: out.width, height: out.height, data: Array.from(buf) };
+ });
+}
+
+async function renderSeekOnly(page: Page, t: number): Promise<void> {
+ await page.evaluate((time: number) => {
+ (window as CompositeWindow).__player!.renderSeek(time);
+ }, t);
+}
+
+/**
+ * TWO `self` hosts, so a per-host sequential wait costs twice as many frames
+ * as a single-host one. One host can be painted by luck; two cannot.
+ */
+function twoHostFixture(chain: string): string {
+ const host = (side: string): string => `
+ <div id="host-${side}" class="vfx-host clip" data-start="0" data-duration="4"
+ data-vfx-chain='${chain}'>
+ <canvas layoutsubtree class="hf-vfx-src"><div class="hf-vfx-in"><div class="square"></div></div></canvas>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>`;
+ return `<!doctype html>
+<style>
+ html, body { margin: 0; background: #0000ff; }
+ .vfx-host { position: absolute; top: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ #host-a { left: 0; }
+ #host-b { left: ${HOST_W + GAP}px; }
+ .vfx-host > canvas { position: absolute; inset: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ .hf-vfx-in { position: absolute; left: 0; top: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ .square {
+ position: absolute; left: 0; top: 0;
+ width: ${SQUARE_W}px; height: ${HOST_H}px; background: #ff0000;
+ }
+</style>
+<div data-composition-id="root" data-start="0" data-duration="4"
+ data-width="${HOST_W * 2 + GAP}" data-height="${HOST_H}">${host("a")}${host("b")}
+</div>`;
+}
+
+/**
+ * What `seekCompositionTimeline` does, by hand: dispatch the seek, drain the
+ * seek-completion barrier, then ONE settle race — `setTimeout(100)` against a
+ * double rAF, copied from the CLI's default `animationFrameSettle: "race"`
+ * (`packages/cli/src/capture/captureCompositionFrame.ts`). Whatever has not
+ * painted by the time this returns is what `hyperframes snapshot` screenshots
+ * as blank.
+ */
+async function seekAndDrainBarrier(page: Page, t: number): Promise<void> {
+ await page.evaluate((time: number) => {
+ (window as CompositeWindow).__player!.renderSeek(time);
+ }, t);
+ // Asserted, not optional-chained: a bundle that never exposed the barrier
+ // would make the whole case a no-op that passes.
+ const drained = await page.evaluate(async () => {
+ const wait = Reflect.get(window, "__hfWaitForSeekCompletion");
+ if (typeof wait !== "function") return false;
+ await Reflect.apply(wait, window, []);
+ return true;
+ });
+ expect(drained).toBe(true);
+}
+
+/**
+ * The CLI's default `animationFrameSettle: "race"`, copied verbatim from
+ * `packages/cli/src/capture/captureCompositionFrame.ts`: a 100 ms timeout
+ * against a double rAF, whichever lands first. This is all the slack a real
+ * snapshot leaves between the barrier and the screenshot.
+ */
+async function settleRace(page: Page): Promise<void> {
+ await page.evaluate(`new Promise(function(r) {
+ var settled = false;
+ function finish() { if (settled) return; settled = true; r(); }
+ window.setTimeout(finish, 100);
+ requestAnimationFrame(function() { requestAnimationFrame(finish); });
+ })`);
+}
+
+/** RGBA at one interior point of every `.hf-vfx-out` on the page. */
+async function sampleEveryOut(page: Page): Promise<number[][]> {
+ return page.evaluate(() =>
+ [...document.querySelectorAll("canvas.hf-vfx-out")].map((node) => {
+ const gl = (node as HTMLCanvasElement).getContext("webgl2");
+ if (!gl) return [];
+ const px = new Uint8Array(4);
+ gl.readPixels(40, 60, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
+ return [...px];
+ }),
+ );
+}
+
+/**
+ * Chain order is nesting order. The exporter puts effects that run BEFORE the
+ * chain node on `.hf-vfx-in` (inside the capture) and effects that run AFTER it
+ * on the host (outside, applied by the page compositor to `.hf-vfx-out`).
+ *
+ * Panel A is that arrangement with an identity kernel between the two filters;
+ * panel B is the same nesting as plain DOM. If the runtime honours the order,
+ * the two panels are the same picture. Both sit on the same blue field with the
+ * same clearance, so their filters spill into identical neighbourhoods.
+ */
+function chainOrderFixture(chain: string): string {
+ return `<!doctype html>
+<style>
+ html, body { margin: 0; background: #0000ff; }
+ .panel { position: absolute; top: ${PANEL.y}px; width: ${HOST_W}px; height: ${HOST_H}px; }
+ #host { left: ${PANEL.ax}px; }
+ #control { left: ${PANEL.bx}px; }
+ #host > canvas { position: absolute; inset: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ .inner { position: absolute; left: 0; top: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ .square {
+ position: absolute; left: 0; top: 0;
+ width: ${SQUARE_W}px; height: ${HOST_H}px; background: #ff0000;
+ }
+</style>
+<svg width="0" height="0" style="position:absolute">
+ <filter id="tint" color-interpolation-filters="sRGB">
+ <feColorMatrix type="matrix" values="0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0"/>
+ </filter>
+</svg>
+<div data-composition-id="root" data-start="0" data-duration="4"
+ data-width="400" data-height="180">
+ <div id="host" class="panel clip" data-start="0" data-duration="4"
+ data-vfx-chain='${chain}' style="filter: blur(2px)">
+ <canvas layoutsubtree class="hf-vfx-src"><div class="hf-vfx-in inner" style="filter: url(#tint)"><div class="square"></div></div></canvas>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>
+ <div id="control" class="panel" style="filter: blur(2px)">
+ <div class="inner" style="filter: url(#tint)"><div class="square"></div></div>
+ </div>
+</div>`;
+}
+
+interface OutSample {
+ width: number;
+ height: number;
+ /** RGBA at a few probe points. */
+ left: number[];
+ right: number[];
+ /** Every `[start, end)` run of red pixels in each requested row. */
+ rows: [number, number][][];
+ /** Alpha left behind in the capture canvas after the upload. */
+ srcAlpha: number[];
+}
+
+describe("data-vfx-chain in the browser", () => {
+ let browser: Browser;
+ let runtime: string;
+
+ beforeAll(async () => {
+ runtime = readFileSync(RUNTIME_PATH, "utf8");
+ browser = await puppeteer.launch({
+ headless: true,
+ args: ["--no-sandbox", "--disable-setuid-sandbox", "--enable-features=CanvasDrawElement"],
+ });
+ const probe = await browser.newPage();
+ const caps = await probe.evaluate(() => ({
+ drawElementImage: typeof (
+ document.createElement("canvas").getContext("2d") as CanvasRenderingContext2D & {
+ drawElementImage?: unknown;
+ }
+ )?.drawElementImage,
+ webgl2: !!document.createElement("canvas").getContext("webgl2"),
+ }));
+ await probe.close();
+ // A missing capability makes every assertion below meaningless, so fail
+ // here — naming the build that was actually launched — rather than on a
+ // pixel compare thirty lines down.
+ expect({ ...caps, version: await browser.version() }).toMatchObject({
+ drawElementImage: "function",
+ webgl2: true,
+ });
+ }, 60_000);
+
+ afterAll(async () => {
+ await browser?.close();
+ });
+
+ /**
+ * Loud-error collector per page. A chain the runtime refused — the shape a
+ * stale `dist/hyperframe.runtime.iife.js` takes, since a kernel it has never
+ * heard of is an unknown effect type — otherwise surfaces as an unreadable
+ * `expected false to be true` two helpers away.
+ */
+ const pageErrors = new Map<Page, string[]>();
+
+ function watchPage(page: Page): string[] {
+ const errors: string[] = [];
+ pageErrors.set(page, errors);
+ page.on("console", (message) => {
+ const text = message.text();
+ if (text.includes("[HyperFrames] composition script error:")) errors.push(text);
+ });
+ page.on("pageerror", (error) => errors.push(error.message));
+ return errors;
+ }
+
+ async function bootRuntime(page: Page, errors: string[]): Promise<void> {
+ await page.addScriptTag({ content: runtime });
+ await page.waitForFunction(
+ () =>
+ (window as CompositeWindow).__playerReady === true &&
+ (window as CompositeWindow).__renderReady === true,
+ );
+ expect(errors).toEqual([]);
+ }
+
+ async function open(html: string, viewport = { width: 320, height: 240 }): Promise<Page> {
+ const page = await browser.newPage();
+ const errors = watchPage(page);
+ await page.setViewport({ ...viewport, deviceScaleFactor: 1 });
+ await page.setContent(html);
+ await bootRuntime(page, errors);
+ return page;
+ }
+
+ /**
+ * `setContent` leaves the document on `about:blank`, where the loader's
+ * `fetch("<data-composition-src>")` cannot resolve — a mounted fixture needs
+ * a real origin, so both files are served from the interceptor.
+ */
+ async function openMounted(files: Record<string, string>): Promise<Page> {
+ const page = await browser.newPage();
+ const errors = watchPage(page);
+ await page.setRequestInterception(true);
+ page.on("request", (request) => {
+ const name = new URL(request.url()).pathname.slice(1);
+ const body = files[name];
+ if (body === undefined) {
+ void request.continue();
+ return;
+ }
+ void request.respond({ status: 200, contentType: "text/html", body });
+ });
+ await page.setViewport({ width: 320, height: 240, deviceScaleFactor: 1 });
+ await page.goto("http://vfx.test/main.html", { waitUntil: "domcontentloaded" });
+ await bootRuntime(page, errors);
+ return page;
+ }
+
+ /**
+ * The engine's three-phase protocol, by hand: seek (which arms the pending
+ * flag), force a compositor paint with a 1×1 screenshot, then resolve.
+ */
+ async function seekAndResolve(page: Page, t: number): Promise<boolean> {
+ const armed = await page.evaluate((time: number) => {
+ (window as CompositeWindow).__player!.renderSeek(time);
+ return (window as CompositeWindow).__hf_page_composite_pending === true;
+ }, t);
+ expect({ armed, errors: pageErrors.get(page) }).toEqual({ armed: true, errors: [] });
+ await page.screenshot({ clip: { x: 0, y: 0, width: 1, height: 1 } });
+ return page.evaluate(() => (window as CompositeWindow).__hf_page_composite_resolve!());
+ }
+
+ async function sample(page: Page, rows: number[]): Promise<OutSample> {
+ return page.evaluate((rowList: number[]) => {
+ const out = document.querySelector("canvas.hf-vfx-out") as HTMLCanvasElement;
+ const gl = out.getContext("webgl2")!;
+ const buf = new Uint8Array(out.width * out.height * 4);
+ gl.readPixels(0, 0, out.width, out.height, gl.RGBA, gl.UNSIGNED_BYTE, buf);
+ const at = (x: number, y: number): number[] => {
+ const i = (y * out.width + x) * 4;
+ return [buf[i]!, buf[i + 1]!, buf[i + 2]!, buf[i + 3]!];
+ };
+ // Runs, not a width: a displacement can split the block in two, and a
+ // shift that runs one edge off the frame leaves the width unchanged.
+ const redRuns = (y: number): [number, number][] => {
+ const runs: [number, number][] = [];
+ let start = -1;
+ for (let x = 0; x <= out.width; x++) {
+ const red = x < out.width && buf[(y * out.width + x) * 4]! > 127;
+ if (red && start < 0) start = x;
+ if (!red && start >= 0) {
+ runs.push([start, x]);
+ start = -1;
+ }
+ }
+ return runs;
+ };
+ const src = document.querySelector("canvas.hf-vfx-src") as HTMLCanvasElement;
+ const sctx = src.getContext("2d")!;
+ return {
+ width: out.width,
+ height: out.height,
+ left: at(40, 60),
+ right: at(120, 60),
+ rows: rowList.map(redRuns),
+ srcAlpha: [
+ sctx.getImageData(40, 60, 1, 1).data[3]!,
+ sctx.getImageData(120, 60, 1, 1).data[3]!,
+ ],
+ };
+ }, rows);
+ }
+
+ it("reproduces the captured layer exactly when the kernel is an identity", async () => {
+ const page = await open(fixture(waveWarpChain({ height: 0, width: 93.4 })));
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const s = await sample(page, [10, 60, 90]);
+
+ expect([s.width, s.height]).toEqual([HOST_W, HOST_H]);
+ expect(s.left).toEqual([255, 0, 0, 255]);
+ expect(s.right).toEqual([0, 0, 0, 0]);
+ expect(s.rows).toEqual([[[0, SQUARE_W]], [[0, SQUARE_W]], [[0, SQUARE_W]]]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ /**
+ * `hyperframes snapshot` (and `check`/`compare`/`validate`/`layout`, and
+ * Studio's thumbnail capture) seek through the same `renderSeek` the engine
+ * does, but never read
+ * `__hf_page_composite_pending` and never call `__hf_page_composite_resolve`
+ * — so arming the protocol alone left every `self` chain unpainted and
+ * silent there. No `page.screenshot` in this case ON PURPOSE: a screenshot
+ * is the engine's phase-2 paint force, and taking one would test the engine
+ * protocol again by the back door instead of the runtime's own fallback.
+ */
+ it("paints a self-capture host when nobody ever resolves the composite", async () => {
+ const page = await open(fixture(waveWarpChain({ height: 0, width: 93.4 })));
+ try {
+ const armed = await page.evaluate(() => {
+ (window as CompositeWindow).__player!.renderSeek(0);
+ return (window as CompositeWindow).__hf_page_composite_pending === true;
+ });
+ expect({ armed, errors: pageErrors.get(page) }).toEqual({ armed: true, errors: [] });
+
+ await page.waitForFunction(
+ () => {
+ const out = document.querySelector("canvas.hf-vfx-out") as HTMLCanvasElement;
+ const gl = out.getContext("webgl2");
+ if (!gl) return false;
+ const px = new Uint8Array(4);
+ gl.readPixels(40, 60, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
+ return px[3] === 255;
+ },
+ { timeout: 5_000 },
+ );
+
+ const s = await sample(page, [10, 60, 90]);
+ expect([s.width, s.height]).toEqual([HOST_W, HOST_H]);
+ expect(s.left).toEqual([255, 0, 0, 255]);
+ expect(s.right).toEqual([0, 0, 0, 0]);
+ expect(s.rows).toEqual([[[0, SQUARE_W]], [[0, SQUARE_W]], [[0, SQUARE_W]]]);
+ // The engine contract is untouched: the flag stays armed, so a host that
+ // DOES run the three-phase protocol still gets its authoritative capture.
+ expect(
+ await page.evaluate(() => (window as CompositeWindow).__hf_page_composite_pending),
+ ).toBe(true);
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ /**
+ * The same snapshot-family path, but joined rather than raced. Every
+ * `hyperframes` seek caller (`snapshot`/`check`/`compare`/`validate`/
+ * `layout`) drains `__hfWaitForSeekCompletion` and then allows exactly one
+ * settle race before screenshotting. The preview-side capture used to be
+ * fire-and-forget AND sequential per host, so N hosts cost up to 2N frames
+ * while the settle bought about two — the screenshot landed on hosts that
+ * had not painted yet, and which ones varied run to run.
+ *
+ * Two hosts, so one host finishing in time cannot hide the defect. No
+ * `page.screenshot` before the read: that is the engine's phase-2 paint
+ * force, and taking one would test the engine protocol by the back door.
+ */
+ it("has every self-capture host painted the moment the CLI's seek barrier returns", async () => {
+ const page = await open(twoHostFixture(waveWarpChain({ height: 0, width: 93.4 })), {
+ width: HOST_W * 2 + GAP,
+ height: HOST_H + GAP,
+ });
+ try {
+ expect(await page.evaluate(() => document.querySelectorAll("[data-vfx-chain]").length)).toBe(
+ 2,
+ );
+
+ await seekAndDrainBarrier(page, 0);
+
+ // Read immediately — no waitForFunction, no extra rAF. Measured on the
+ // pre-fix bundle this is `[[0,0,0,0],[0,0,0,0]]`: the barrier returned
+ // with neither host painted, and only the settle race that follows
+ // happened to cover them. That slack is not a guarantee — it is two
+ // frames against a cost that grows with host count — so the contract is
+ // pinned here, where the barrier's promise is the only thing holding.
+ const atBarrier = await sampleEveryOut(page);
+ await settleRace(page);
+ const atScreenshot = await sampleEveryOut(page);
+
+ expect({ atBarrier, atScreenshot, errors: pageErrors.get(page) }).toEqual({
+ atBarrier: [red, red],
+ atScreenshot: [red, red],
+ errors: [],
+ });
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("captures a .hf-vfx-in that is a sub-composition mount", async () => {
+ const page = await openMounted({
+ "main.html": mountFixture(waveWarpChain({ height: 0, width: 93.4 })),
+ "inner.html": MOUNT_INNER,
+ });
+ try {
+ // The mount replaces .hf-vfx-in's children, so the exporter's
+ // preceding-effect content goes with them — and a silent 404 would leave
+ // the wrapper empty, which looks exactly like the defect under test.
+ expect(
+ await page.evaluate(() => {
+ const inner = document.querySelector(".hf-vfx-in")!;
+ return {
+ mounted: inner.querySelectorAll("#inner-square").length,
+ preMountContentKept: !!document.getElementById("pre-mount"),
+ };
+ }),
+ ).toEqual({ mounted: 1, preMountContentKept: false });
+
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const s = await sample(page, [10, 60, 90]);
+
+ expect([s.width, s.height]).toEqual([HOST_W, HOST_H]);
+ expect(s.left).toEqual([255, 0, 0, 255]);
+ expect(s.rows).toEqual([[[0, SQUARE_W]], [[0, SQUARE_W]], [[0, SQUARE_W]]]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("registers a vfx host that arrives inside a mounted sub-composition", async () => {
+ const page = await openMounted({
+ "main.html": NESTED_HOST_MAIN,
+ "inner.html": NESTED_HOST_INNER(waveWarpChain({ height: 0, width: 93.4 })),
+ });
+ try {
+ expect(await page.evaluate(() => document.querySelectorAll("[data-vfx-chain]").length)).toBe(
+ 1,
+ );
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const s = await sample(page, [10, 60, 90]);
+ expect([s.width, s.height]).toEqual([HOST_W, HOST_H]);
+ expect(s.left).toEqual([255, 0, 0, 255]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("clears the capture canvas so the unprocessed layer cannot show through", async () => {
+ const page = await open(fixture(waveWarpChain({ height: 0, width: 93.4 })));
+ try {
+ await seekAndResolve(page, 0);
+ const s = await sample(page, []);
+
+ // The layoutsubtree canvas's CHILDREN are not painted by the page
+ // compositor, but its bitmap is — and that bitmap is where the capture
+ // landed. Every transparent pixel of .hf-vfx-out would otherwise reveal
+ // the unwarped original underneath it.
+ expect(s.srcAlpha).toEqual([0, 0]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("shifts each row by the analytic wave displacement", async () => {
+ const params = {
+ waveType: 1,
+ direction: 0,
+ speed: 0,
+ pinning: 1,
+ phase: 0,
+ height: 20,
+ width: 93.4,
+ };
+ const page = await open(fixture(waveWarpChain(params)));
+ try {
+ await seekAndResolve(page, 0);
+ const rows = [30, 90];
+ const s = await sample(page, rows);
+
+ for (const [i, y] of rows.entries()) {
+ // out(x, y) samples the source at x + disp, so the block's edges move
+ // by −disp, and anything displaced off the source is transparent.
+ const disp = waveWarpSampleRef({ x: 0, y }, 0, params).x;
+ expect(Math.abs(disp)).toBeGreaterThan(1);
+ expect(s.rows[i]).toHaveLength(1);
+ const [first, end] = s.rows[i]![0]!;
+ expect(first).toBeCloseTo(Math.max(0, -disp), -0.5);
+ expect(end).toBeCloseTo(Math.min(HOST_W, SQUARE_W - disp), -0.5);
+ }
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("displaces by its own pixels when the map layer is the layer itself", async () => {
+ // Use For Horizontal = Red, maxH = 20, maxV = 0. The block is opaque red
+ // (red = 1 ⇒ +20 px) and everything right of it is transparent
+ // (red = 0 ⇒ −20 px), so the output reads the source from two different
+ // directions and the block comes back split:
+ // x < 80 reads x + 20 ⇒ red while x < 60
+ // x ≥ 80 reads x − 20 ⇒ red while x < 100
+ const params = { useH: 1, useV: 2, maxH: 20, maxV: 0, behavior: 1, edge: 0, expand: true };
+ const page = await open(fixture(chainOf("displacement-map", params)));
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const s = await sample(page, [30, 90]);
+
+ const opaqueRed = { r: 1, g: 0, b: 0, a: 1 };
+ const transparent = { r: 0, g: 0, b: 0, a: 0 };
+ const shiftInside = displacementMapSampleRef({ x: 0, y: 0 }, 0, params, () => opaqueRed).x;
+ const shiftOutside = displacementMapSampleRef({ x: 0, y: 0 }, 0, params, () => transparent).x;
+ expect([shiftInside, shiftOutside]).toEqual([20, -20]);
+
+ for (const runs of s.rows) {
+ expect(runs).toEqual([
+ [0, SQUARE_W - shiftInside],
+ [SQUARE_W, SQUARE_W - shiftOutside],
+ ]);
+ }
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ /**
+ * Decode the page's own screenshot back inside the page and compare the two
+ * panels. Keeping the compare in the browser avoids a PNG decoder in Node
+ * and guarantees both panels went through one compositor pass.
+ */
+ async function panelPsnr(page: Page): Promise<{ mse: number; psnr: number; aCentre: number[] }> {
+ const shot = await page.screenshot({ encoding: "base64" });
+ const raw = await page.evaluate(
+ async (base64: string, panel: typeof PANEL) => {
+ const img = new Image();
+ img.src = `data:image/png;base64,${base64}`;
+ await img.decode();
+ const scratch = document.createElement("canvas");
+ scratch.width = img.width;
+ scratch.height = img.height;
+ const ctx = scratch.getContext("2d")!;
+ ctx.drawImage(img, 0, 0);
+ const a = ctx.getImageData(panel.ax, panel.y, panel.w, panel.h).data;
+ const b = ctx.getImageData(panel.bx, panel.y, panel.w, panel.h).data;
+ let se = 0;
+ let n = 0;
+ for (let i = 0; i < a.length; i += 4) {
+ for (let c = 0; c < 3; c++) {
+ const d = a[i + c]! - b[i + c]!;
+ se += d * d;
+ n += 1;
+ }
+ }
+ const centre = ((panel.h >> 1) * panel.w + 20) * 4;
+ // `Infinity` does not survive the CDP round trip, so the MSE crosses
+ // and the decibels are computed on this side.
+ return { mse: se / n, aCentre: [a[centre]!, a[centre + 1]!, a[centre + 2]!] };
+ },
+ shot,
+ PANEL,
+ );
+ return {
+ ...raw,
+ psnr: raw.mse === 0 ? Number.POSITIVE_INFINITY : 10 * Math.log10((255 * 255) / raw.mse),
+ };
+ }
+
+ it("captures the filters that precede the node and leaves the ones that follow outside", async () => {
+ const page = await open(chainOrderFixture(waveWarpChain({ height: 0, width: 93.4 })), {
+ width: PANEL.bx + PANEL.w + PANEL.ax,
+ height: PANEL.y + PANEL.h + PANEL.y,
+ });
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const { psnr, aCentre } = await panelPsnr(page);
+
+ // The tint runs INSIDE the capture, so the block reaches the kernel green
+ // rather than red — proof that drawElementImage paints the subtree's own
+ // filter rather than its unfiltered source.
+ expect(aCentre[0]).toBeLessThan(64);
+ expect(aCentre[1]).toBeGreaterThan(160);
+ // ...and the host's blur runs OUTSIDE, on the canvas the kernel wrote.
+ expect(psnr).toBeGreaterThanOrEqual(40);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("paints byte-identical fractal-noise output for the same seek time (determinism)", async () => {
+ const page = await open(noiseFixture(chainOf("fractal-noise", NOISE_PARAMS)));
+ try {
+ await renderSeekOnly(page, 1.25);
+ const first = await page.evaluate(() =>
+ (document.querySelector("canvas.hf-vfx-out") as HTMLCanvasElement).toDataURL(),
+ );
+
+ // Seek away, then back to the same time — the paint must not carry any
+ // state between calls (the determinism contract's "no state carried
+ // between paints" clause).
+ await renderSeekOnly(page, 0.5);
+ await renderSeekOnly(page, 1.25);
+ const second = await page.evaluate(() =>
+ (document.querySelector("canvas.hf-vfx-out") as HTMLCanvasElement).toDataURL(),
+ );
+
+ expect(second).toBe(first);
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("matches the CPU reference within the cross-backend PSNR bar for fractal-noise", async () => {
+ const page = await open(noiseFixture(chainOf("fractal-noise", NOISE_PARAMS)));
+ try {
+ const frames = [0, 0.5, 1.25, 2.0];
+ // 8 points spread across the 160x120 canvas.
+ const samplePoints: [number, number][] = [
+ [10, 10],
+ [40, 30],
+ [80, 60],
+ [120, 90],
+ [20, 100],
+ [150, 5],
+ [60, 60],
+ [100, 20],
+ ];
+ let se = 0;
+ let n = 0;
+ for (const t of frames) {
+ await renderSeekOnly(page, t);
+ const buf = await readNoiseBuffer(page);
+ for (const [x, y] of samplePoints) {
+ // Device pixels, y measured from the bottom — readPixels' row order
+ // and the shader's v_uv y-up agree, and refs/fractalNoise.ts is
+ // documented against exactly that convention.
+ const i = (y * buf.width + x) * 4;
+ const measured = buf.data[i]!;
+ const expected = Math.round(
+ fractalNoiseRef({ x: x + 0.5, y: y + 0.5 }, t, NOISE_PARAMS) * 255,
+ );
+ const d = measured - expected;
+ se += d * d;
+ n += 1;
+ }
+ }
+ const mse = se / n;
+ const psnr = mse === 0 ? Number.POSITIVE_INFINITY : 10 * Math.log10((255 * 255) / mse);
+ expect(psnr).toBeGreaterThanOrEqual(32);
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+});
diff --git a/scripts/test-reachability.json b/scripts/test-reachability.json
index 6b47471318..ea3eed5eab 100644
--- a/scripts/test-reachability.json
+++ b/scripts/test-reachability.json
@@ -45,7 +45,7 @@
],
"sources": {
"packages/producer/scripts/run-test-lane.mjs": "bff02680f19eebcce0df72cdeedbbc05edfdcede3f3f60658fc0cb18ed8c59f6",
- "packages/producer/scripts/test-classification.mjs": "f7a1129f49d86fe4a1429dc8b9b75168b25540e1c63242fc79376ae02cf5d0de",
+ "packages/producer/scripts/test-classification.mjs": "040fd35bae0ec736c61b78c74c6836ee0f49d4ff3860a95dc75fa52f1c939822",
".github/workflows/ci.yml#job#producer-source-tests": "3709c6ac6c9f5c7c66f57fc6c1c106aec4ffe906f919eb7cdf2a6ce1d4e0974c",
"packages/producer/package.json#script#test:unit": "ae6beda8319d166774be958ea5593cd27dbf7f6c9bce1d787a3fe28dfc3477b1",
"packages/producer/package.json#script#test:integration": "008589f37d026877595a13501cbb66abd5cbe50e21fdcac6904f45466c3f475d",