Skip to content

Write HTML. Render video. Built for agents.

feat(runtime): data-vfx-chain backdrop capture and two-source kernels (luma-matte, noise) (#4330)

Vance Ingalls84e36fc16afc
diff --git a/packages/core/src/runtime/vfx.test.ts b/packages/core/src/runtime/vfx.test.ts
index c989b18db8..0d550aa8f8 100644
--- a/packages/core/src/runtime/vfx.test.ts
+++ b/packages/core/src/runtime/vfx.test.ts
@@ -9,7 +9,11 @@ import { initVfx, paintVfx } from "./vfx";
* 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 }));
+const override = vi.hoisted(() => ({
+ capture: null as HfVfxCapture | null,
+ /** Appends a `ref` param with this key to every def, as `luma-matte` has. */
+ refKey: null as string | null,
+}));
vi.mock("../vfx", async (importOriginal) => {
const actual = await importOriginal<typeof import("../vfx")>();
@@ -19,7 +23,22 @@ vi.mock("../vfx", async (importOriginal) => {
override.capture ?? actual.chainCapture(chain),
getVfxDef: (id: string) => {
const def = actual.getVfxDef(id);
- return def && override.capture ? { ...def, capture: override.capture } : def;
+ if (!def) return def;
+ if (!override.capture && !override.refKey) return def;
+ return {
+ ...def,
+ capture: override.capture ?? def.capture,
+ params: override.refKey
+ ? [...def.params, { kind: "ref", key: override.refKey, label: "Second source" }]
+ : def.params,
+ };
+ },
+ normalizeVfxParams: (id: string, values: import("../vfx").HfVfxParamValues | undefined) => {
+ const normalized = actual.normalizeVfxParams(id, values);
+ // The real `normalizeVfxParams` reads the real def, which has no ref
+ // param, so the injected one would be dropped before the runtime saw it.
+ if (override.refKey) normalized[override.refKey] = String(values?.[override.refKey] ?? "");
+ return normalized;
},
};
});
@@ -59,6 +78,7 @@ function createMockGl(): WebGL2RenderingContext & MockGl {
TRIANGLES: 0x0004,
TEXTURE_2D: 0x0de1,
TEXTURE0: 0x84c0,
+ TEXTURE1: 0x84c1,
RGBA: 0x1908,
UNSIGNED_BYTE: 0x1401,
CLAMP_TO_EDGE: 0x812f,
@@ -156,27 +176,58 @@ 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);
- });
+/**
+ * One fixture for every describe in this file: a clean body, a recording mock
+ * GL behind `getContext`, a console spy, a page-composite slot nobody else
+ * owns, and the def overrides this test lifts its chains through.
+ */
+function installVfxHarness(capture: HfVfxCapture | null, refKey: string | null = null): void {
+ document.body.innerHTML = "";
+ gl = createMockGl();
+ installCanvasMock(() => gl);
+ errors = [];
+ override.capture = capture;
+ override.refKey = refKey;
+ // `paintVfx` registers its preview capture into the module-level
+ // seek-completion set; a leftover entry would stall the next test's barrier.
+ resetSeekDispatchState();
+ clearCompositeSlot();
+ 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();
- });
+function releaseVfxHarness(): void {
+ // Empty the registry BEFORE the canvas mock comes off, or jsdom's real
+ // (unimplemented) getContext runs and floods the console.
+ document.body.innerHTML = "";
+ override.capture = null;
+ override.refKey = null;
+ initVfx(document.body, 30);
+ clearCompositeSlot();
+ resetSeekDispatchState();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+}
+
+/**
+ * One macrotask. The preview capture path awaits a `paint` event, a
+ * `Promise.all` over every source, and then the capture itself, so counting
+ * microtask ticks by hand is a test that breaks when a hop is added; a timer
+ * tick settles all of them.
+ */
+function flushTasks(): Promise<void> {
+ return new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
+function clearCompositeSlot(): void {
+ delete compositeWindow().__hf_page_composite_pending;
+ delete compositeWindow().__hf_page_composite_resolve;
+}
+
+describe("vfx runtime", () => {
+ beforeEach(() => installVfxHarness(null));
+ afterEach(releaseVfxHarness);
it("registers every [data-vfx-chain] host and creates a missing .hf-vfx-out", () => {
const a = makeHost(ONE_NODE, "a");
@@ -388,49 +439,48 @@ function createMockCtx2d(onDraw?: () => void): MockCtx2d {
}) 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);
+/**
+ * A capture wrapper as the exporter emits it. `.hf-vfx-in` is given a real
+ * layout box because inside a `layoutsubtree` canvas an unsized wrapper
+ * measures 0×0 and captures nothing in silence — the runtime refuses it, so a
+ * fixture without a box would be testing that refusal and nothing else.
+ */
+function makeCaptureWrapper(ctx: unknown, forId?: string): HTMLCanvasElement {
const src = document.createElement("canvas");
src.className = "hf-vfx-src";
src.setAttribute("layoutsubtree", "");
+ if (forId !== undefined) src.setAttribute("data-vfx-for", forId);
if (ctx !== undefined) {
src.getContext = ((kind: string) => (kind === "2d" ? ctx : null)) as never;
}
const inner = document.createElement("div");
inner.className = "hf-vfx-in";
+ sizeHost(inner, 320, 180);
src.appendChild(inner);
- host.insertBefore(src, host.firstChild);
+ return src;
+}
+
+/** A `self` host as the exporter emits it: src canvas wrapping `.hf-vfx-in`. */
+function makeCaptureHost(ctx: unknown, id = "cap", chain = ONE_NODE): HTMLElement {
+ const host = makeHost(chain, id);
+ host.insertBefore(makeCaptureWrapper(ctx), 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);
- });
- });
+/**
+ * A `backdrop` host as interface v1.1 shapes it: the wrapper holding every
+ * layer below the host is the host's PRECEDING SIBLING, named by
+ * `data-vfx-for`, not a child of the host.
+ */
+function makeBackdropHost(ctx: unknown, id = "adj", chain = ONE_NODE): HTMLElement {
+ const host = makeHost(chain, id);
+ host.parentElement!.insertBefore(makeCaptureWrapper(ctx, id), host);
+ return host;
+}
- 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();
- });
+describe("vfx runtime — self capture", () => {
+ beforeEach(() => installVfxHarness("self"));
+ afterEach(releaseVfxHarness);
it("refuses a capture host that has no .hf-vfx-src canvas", () => {
makeHost(ONE_NODE);
@@ -556,8 +606,7 @@ describe("vfx runtime — self capture", () => {
expect(ctx.drawn).toHaveLength(0);
src.dispatchEvent(new Event("paint"));
- await Promise.resolve();
- await Promise.resolve();
+ await flushTasks();
expect(ctx.drawn).toHaveLength(1);
expect(compositeWindow().__hf_page_composite_pending).toBeUndefined();
@@ -583,23 +632,22 @@ describe("vfx runtime — self capture", () => {
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();
+ await flushTasks();
const beforeAnyPaint = resolved;
srcOf(a).dispatchEvent(new Event("paint"));
- await flush();
+ await flushTasks();
// Still held: one host of two is not a finished frame.
const afterFirstPaint = resolved;
srcOf(b).dispatchEvent(new Event("paint"));
- await flush();
+ await flushTasks();
await barrier;
expect({
@@ -680,3 +728,536 @@ describe("vfx runtime — self capture", () => {
}
});
});
+
+/**
+ * Interface v1.1's `backdrop` shape. The def side is unchanged — a kernel that
+ * reads `u_src` cannot tell whose pixels those are — so these cases are about
+ * the DOM: where the wrapper is, and what happens to the layers inside it when
+ * the host itself is not painting.
+ */
+describe("vfx runtime — backdrop capture", () => {
+ beforeEach(() => installVfxHarness("self"));
+ afterEach(releaseVfxHarness);
+
+ it("reads its source from the data-vfx-for sibling and records it as a backdrop", () => {
+ const ctx = createMockCtx2d();
+ const host = makeBackdropHost(ctx, "adj-1");
+
+ const registry = initVfx(document.body, 30);
+ paintVfx(1.25, { engineMode: true });
+
+ expect(compositeWindow().__hf_page_composite_resolve!()).toBe(true);
+ expect(registry).toHaveLength(1);
+ // Resolved, not declared: the chain's defs say `self`, the DOM says the
+ // pixels come from the wrapper beside the host.
+ expect(registry[0]!.capture).toBe("backdrop");
+ expect(host.querySelector(".hf-vfx-in")).toBeNull();
+ expect(ctx.drawn.map((d) => d.el)).toEqual([
+ document.querySelector('canvas[data-vfx-for="adj-1"] > .hf-vfx-in'),
+ ]);
+ expect(gl!.calls).toEqual(["useProgram", "screen", "draw:1"]);
+ expect(errors).toEqual([]);
+ });
+
+ it("prefers the data-vfx-for sibling over a wrapper inside the host", () => {
+ const below = createMockCtx2d();
+ const own = createMockCtx2d();
+ const host = makeBackdropHost(below, "adj-1");
+ host.appendChild(makeCaptureWrapper(own));
+
+ initVfx(document.body, 30);
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ expect({ below: below.drawn.length, own: own.drawn.length }).toEqual({ below: 1, own: 0 });
+ });
+
+ it("keeps drawing the layers below while the backdrop host is hidden", () => {
+ const ctx = createMockCtx2d();
+ const host = makeBackdropHost(ctx, "adj-1");
+ initVfx(document.body, 30);
+ host.style.visibility = "hidden";
+
+ paintVfx(0, { engineMode: true });
+
+ expect(compositeWindow().__hf_page_composite_pending).toBe(true);
+ expect(compositeWindow().__hf_page_composite_resolve!()).toBe(true);
+ expect({
+ // Captured: the wrapper's children are invisible to the page compositor,
+ // so an undrawn bitmap would delete every layer below the adjustment.
+ drawn: ctx.drawn.length,
+ // Cleared ONCE — before the draw. The second clear is what a painting
+ // frame does to stop the raw capture showing through `.hf-vfx-out`;
+ // here the bitmap IS the frame and must stay.
+ cleared: ctx.cleared,
+ // The kernel does not run: the adjustment layer is off.
+ calls: gl!.calls,
+ }).toEqual({ drawn: 1, cleared: [[320, 180]], calls: [] });
+ expect(errors).toEqual([]);
+ });
+
+ it("passes the layers below through on the preview path too", async () => {
+ const ctx = createMockCtx2d();
+ const host = makeBackdropHost(ctx, "adj-1");
+ const src = document.querySelector('canvas[data-vfx-for="adj-1"]')!;
+ initVfx(document.body, 30);
+ host.style.visibility = "hidden";
+
+ paintVfx(0.5);
+ src.dispatchEvent(new Event("paint"));
+ await flushTasks();
+
+ expect(ctx.drawn).toHaveLength(1);
+ expect(gl!.calls).toEqual([]);
+ });
+
+ it("still skips a hidden self host, whose source is inside it", () => {
+ const ctx = createMockCtx2d();
+ const host = makeCaptureHost(ctx, "cap");
+ 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("reports a .hf-vfx-in that measures 0×0 once, not once per frame", () => {
+ const ctx = createMockCtx2d();
+ const host = makeCaptureHost(ctx, "cap");
+ const inner = host.querySelector(".hf-vfx-in") as HTMLElement;
+ sizeHost(inner, 0, 0);
+ initVfx(document.body, 30);
+
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+ paintVfx(1, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ expect(ctx.drawn).toHaveLength(0);
+ expect(errors).toHaveLength(1);
+ expect(String(errors[0]![1])).toMatch(/measures 0×0/);
+ expect(String(errors[0]![1])).toMatch(/explicit width and height in px/);
+ });
+
+ it("refuses a .hf-vfx-in that is not the capture canvas's immediate child", () => {
+ const ctx = createMockCtx2d();
+ const host = makeCaptureHost(ctx, "cap");
+ const inner = host.querySelector(".hf-vfx-in")!;
+ const between = document.createElement("div");
+ inner.parentElement!.appendChild(between);
+ between.appendChild(inner);
+
+ // Chrome: "Only immediate children of the <canvas> element can be passed
+ // to DrawElementImage" — a registration error, not a per-frame throw.
+ expect(initVfx(document.body, 30)).toHaveLength(0);
+ expect(String(errors[0]![1])).toMatch(/hf-vfx-in/);
+ });
+});
+
+/**
+ * Interface v1.1's second source: a `ref` param carrying the id of another
+ * element, captured into `u_src2`. `luma-matte` is the first def to use one.
+ */
+describe("vfx runtime — ref (second source) params", () => {
+ const REF_NODE =
+ '{"version":1,"nodes":[{"type":"fractal-noise","id":"n1","params":{"matte":"matte-1"}}]}';
+
+ /** The element a `ref` names, wrapped by the exporter like any other source. */
+ function makeRefTarget(ctx: unknown, id = "matte-1", wrapped = true): HTMLElement {
+ const el = document.createElement("div");
+ el.id = id;
+ sizeHost(el);
+ if (wrapped) el.appendChild(makeCaptureWrapper(ctx));
+ document.body.appendChild(el);
+ return el;
+ }
+
+ beforeEach(() => installVfxHarness("self", "matte"));
+ afterEach(releaseVfxHarness);
+
+ it("captures the ref's element into u_src2 alongside the host's own u_src", () => {
+ const ctx = createMockCtx2d();
+ const matteCtx = createMockCtx2d();
+ makeRefTarget(matteCtx);
+ makeCaptureHost(ctx, "cap", REF_NODE);
+
+ expect(initVfx(document.body, 30)).toHaveLength(1);
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ expect({ src: ctx.drawn.length, matte: matteCtx.drawn.length }).toEqual({ src: 1, matte: 1 });
+ // Unit 0 is the chain's own texture, unit 1 the second source.
+ expect(gl!.uniforms["u_src"]).toBe(0);
+ expect(gl!.uniforms["u_src2"]).toBe(1);
+ expect(errors).toEqual([]);
+ });
+
+ it("captures one texture for two nodes that name the same element", () => {
+ const ctx = createMockCtx2d();
+ const matteCtx = createMockCtx2d();
+ makeRefTarget(matteCtx);
+ makeCaptureHost(
+ ctx,
+ "cap",
+ '{"version":1,"nodes":[{"type":"fractal-noise","id":"n1","params":{"matte":"matte-1"}},' +
+ '{"type":"fractal-noise","id":"n2","params":{"matte":"matte-1"}}]}',
+ );
+
+ initVfx(document.body, 30);
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ expect(matteCtx.drawn).toHaveLength(1);
+ });
+
+ it("binds u_src2 explicitly when a MANDATORY ref names its own host", () => {
+ // Unlike displacement-map's optional `map` (self-reference there is
+ // treated exactly like "empty"), a mandatory ref like luma-matte's
+ // `matte` has no shader-side branch to fall back on — the shader always
+ // samples `u_src2`, so a self-reference needs u_src2 pointed at u_src's
+ // own texture unit rather than left to an unbound sampler's default.
+ const ctx = createMockCtx2d();
+ makeCaptureHost(
+ ctx,
+ "cap",
+ '{"version":1,"nodes":[{"type":"fractal-noise","id":"n1","params":{"matte":"cap"}}]}',
+ );
+
+ expect(initVfx(document.body, 30)).toHaveLength(1);
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ // One capture only — no second `drawElementImage` for the same image.
+ expect(ctx.drawn).toHaveLength(1);
+ expect(gl!.uniforms["u_src2"]).toBe(0);
+ expect(gl!.uniforms["u_hasSrc2"]).toBe(1);
+ expect(errors).toEqual([]);
+ });
+
+ it("refuses a ref whose element carries no capture wrapper", () => {
+ makeRefTarget(undefined, "matte-1", false);
+ makeCaptureHost(createMockCtx2d(), "cap", REF_NODE);
+
+ expect(initVfx(document.body, 30)).toHaveLength(0);
+ expect(String(errors[0]![1])).toMatch(/"matte" source/);
+ expect(String(errors[0]![1])).toMatch(/hf-vfx-src/);
+ });
+
+ it("refuses a ref naming an element that is not in the composition", () => {
+ makeCaptureHost(createMockCtx2d(), "cap", REF_NODE);
+
+ expect(initVfx(document.body, 30)).toHaveLength(0);
+ expect(String(errors[0]![1])).toMatch(/#matte-1/);
+ expect(String(errors[0]![1])).toMatch(/not in the composition/);
+ });
+
+ it("refuses a node that names no ref element at all", () => {
+ makeCaptureHost(createMockCtx2d(), "cap", ONE_NODE);
+
+ expect(initVfx(document.body, 30)).toHaveLength(0);
+ expect(String(errors[0]![1])).toMatch(/needs a "matte" param/);
+ });
+
+ it("captures a hidden matte as empty instead of failing the frame", async () => {
+ // The exporter wraps a matte layer's own element, and the clip runtime
+ // hides that element outside its window — so `.hf-vfx-in` is hidden too.
+ // Waiting for a paint that cannot come would burn the 2 s ceiling on every
+ // frame of a matte's out point, and drawing it would throw. Only the matte
+ // ELEMENT is hidden here: the wrapper inside it inherits it, which is the
+ // shape the exporter and the clip runtime actually produce.
+ vi.stubGlobal("requestAnimationFrame", () => 1);
+ const ctx = createMockCtx2d();
+ const matteCtx = createMockCtx2d();
+ const matte = makeRefTarget(matteCtx);
+ const host = makeCaptureHost(ctx, "cap", REF_NODE);
+ initVfx(document.body, 30);
+ matte.style.visibility = "hidden";
+
+ paintVfx(0.5);
+ host.querySelector("canvas.hf-vfx-src")!.dispatchEvent(new Event("paint"));
+ await flushTasks();
+
+ expect({ src: ctx.drawn.length, matte: matteCtx.drawn.length }).toEqual({ src: 1, matte: 0 });
+ // An empty u_src2, not a skipped frame: the host still paints, and the
+ // kernel reads a matte that covers nothing.
+ expect(gl!.calls).toEqual(["useProgram", "screen", "draw:1"]);
+ expect(errors).toEqual([]);
+ });
+
+ it("treats a matte whose OWNING element is display:none as hidden too", async () => {
+ // `display` does not inherit: `.hf-vfx-in` inside a `display:none` matte
+ // still computes `display:block`, so a check at `inner` alone calls it
+ // paintable, waits out the 2 s ceiling, then fails as a misleading 0×0.
+ // The clip runtime uses `display:none` for `data-hidden` and for in-flow
+ // timed leaves, so the ancestor walk has to find it.
+ vi.stubGlobal("requestAnimationFrame", () => 1);
+ const ctx = createMockCtx2d();
+ const matteCtx = createMockCtx2d();
+ const matte = makeRefTarget(matteCtx);
+ const host = makeCaptureHost(ctx, "cap", REF_NODE);
+ initVfx(document.body, 30);
+ matte.style.display = "none";
+
+ paintVfx(0.5);
+ // Only the host's canvas paints — the matte's never will, and the frame
+ // must not wait on it.
+ host.querySelector("canvas.hf-vfx-src")!.dispatchEvent(new Event("paint"));
+ await flushTasks();
+
+ expect({ src: ctx.drawn.length, matte: matteCtx.drawn.length }).toEqual({ src: 1, matte: 0 });
+ expect(gl!.calls).toEqual(["useProgram", "screen", "draw:1"]);
+ expect(errors).toEqual([]);
+ });
+
+ it("keeps a visible ref's bitmap and draws it at the ref's own box", async () => {
+ // retro-wave `Logo Anim` layer 5 is layer 4's displacement map AND a layer
+ // that paints: clearing its bitmap after the upload would delete it from
+ // the frame, and drawing it at the host's box would resample it.
+ const ctx = createMockCtx2d();
+ const matteCtx = createMockCtx2d();
+ const matte = makeRefTarget(matteCtx);
+ matte.querySelector("canvas.hf-vfx-src")!.setAttribute("data-vfx-ref-visible", "");
+ sizeHost(matte.querySelector(".hf-vfx-in") as HTMLElement, 640, 360);
+ makeCaptureHost(ctx, "cap", REF_NODE);
+
+ initVfx(document.body, 30);
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ expect(matteCtx.drawn).toEqual([{ el: matte.querySelector(".hf-vfx-in"), w: 640, h: 360 }]);
+ // Cleared once, before the draw: the bitmap that is left is the layer.
+ expect(matteCtx.cleared).toEqual([[640, 360]]);
+ // The host's own capture is unchanged — host box, cleared after upload.
+ expect(ctx.drawn.map((d) => [d.w, d.h])).toEqual([[320, 180]]);
+ expect(ctx.cleared).toEqual([
+ [320, 180],
+ [320, 180],
+ ]);
+ expect(errors).toEqual([]);
+ });
+
+ it("clears an ordinary ref's bitmap and draws it at the host's box", () => {
+ const matteCtx = createMockCtx2d();
+ const matte = makeRefTarget(matteCtx);
+ sizeHost(matte.querySelector(".hf-vfx-in") as HTMLElement, 640, 360);
+ makeCaptureHost(createMockCtx2d(), "cap", REF_NODE);
+
+ initVfx(document.body, 30);
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ // Host box, so `u_src`, `u_src2` and `.hf-vfx-out` share a pixel grid.
+ expect(matteCtx.drawn.map((d) => [d.w, d.h])).toEqual([[320, 180]]);
+ expect(matteCtx.cleared).toEqual([
+ [320, 180],
+ [320, 180],
+ ]);
+ });
+
+ it("holds the preview barrier until the ref's canvas has painted too", async () => {
+ vi.stubGlobal("requestAnimationFrame", () => 1);
+ const ctx = createMockCtx2d();
+ const matteCtx = createMockCtx2d();
+ const matte = makeRefTarget(matteCtx);
+ const host = makeCaptureHost(ctx, "cap", REF_NODE);
+ initVfx(document.body, 30);
+
+ paintVfx(0.5);
+ let resolved = false;
+ const barrier = waitForSeekCompletion().then(() => {
+ resolved = true;
+ });
+ host.querySelector("canvas.hf-vfx-src")!.dispatchEvent(new Event("paint"));
+ await flushTasks();
+ const afterHostPaint = resolved;
+
+ matte.querySelector("canvas.hf-vfx-src")!.dispatchEvent(new Event("paint"));
+ await flushTasks();
+ await barrier;
+
+ expect({ afterHostPaint, resolved, matte: matteCtx.drawn.length }).toEqual({
+ afterHostPaint: false,
+ resolved: true,
+ matte: 1,
+ });
+ });
+
+ it("still captures a visible ref while its own host is hidden", () => {
+ // retro-wave `Logo Anim` layer 5's own AE layer can outlive layer 4's (the
+ // kernel host's) data-start/data-duration window. Before the fix, a
+ // hidden non-backdrop host was dropped entirely, so this ref went missing
+ // before its host's window and stale (last captured frame) after it.
+ const ctx = createMockCtx2d();
+ const matteCtx = createMockCtx2d();
+ const matte = makeRefTarget(matteCtx);
+ matte.querySelector("canvas.hf-vfx-src")!.setAttribute("data-vfx-ref-visible", "");
+ sizeHost(matte.querySelector(".hf-vfx-in") as HTMLElement, 640, 360);
+ const host = makeCaptureHost(ctx, "cap", REF_NODE);
+ initVfx(document.body, 30);
+ host.style.visibility = "hidden";
+
+ paintVfx(0, { engineMode: true });
+
+ expect(compositeWindow().__hf_page_composite_pending).toBe(true);
+ expect(compositeWindow().__hf_page_composite_resolve!()).toBe(true);
+ expect(matteCtx.drawn).toEqual([{ el: matte.querySelector(".hf-vfx-in"), w: 640, h: 360 }]);
+ // Cleared once, before the draw — kept, not re-cleared after: the bitmap
+ // that is left is the ref's own on-page layer.
+ expect(matteCtx.cleared).toEqual([[640, 360]]);
+ // Never uploaded: no kernel runs for a hidden host, so nothing binds it.
+ // The hidden host's own (non-ref) capture never runs either.
+ expect({ ctx: ctx.drawn.length, calls: gl!.calls }).toEqual({ ctx: 0, calls: [] });
+ expect(errors).toEqual([]);
+ });
+
+ it("captures a visible ref through the preview path even while its host is hidden", async () => {
+ const ctx = createMockCtx2d();
+ const matteCtx = createMockCtx2d();
+ const matte = makeRefTarget(matteCtx);
+ matte.querySelector("canvas.hf-vfx-src")!.setAttribute("data-vfx-ref-visible", "");
+ sizeHost(matte.querySelector(".hf-vfx-in") as HTMLElement, 640, 360);
+ const host = makeCaptureHost(ctx, "cap", REF_NODE);
+ initVfx(document.body, 30);
+ host.style.visibility = "hidden";
+
+ paintVfx(0.5);
+ // A ref-only frame waits on the REF's own canvas, never the hidden host's
+ // — the host's canvas fires no "paint" at all while it stays hidden.
+ matte.querySelector("canvas.hf-vfx-src")!.dispatchEvent(new Event("paint"));
+ await flushTasks();
+
+ expect({ matte: matteCtx.drawn.length, ctx: ctx.drawn.length, calls: gl!.calls }).toEqual({
+ matte: 1,
+ ctx: 0,
+ calls: [],
+ });
+ });
+
+ it("still captures a visible ref while its BACKDROP host is hidden", () => {
+ // The prior fix only covered a non-backdrop hidden host: captureHiddenEntry
+ // returned capturePassThrough(entry) for a backdrop and never reached
+ // captureVisibleRefsOnly, so an adjustment layer whose displacement map is
+ // itself a visible layer lost that layer outside the adjustment's window.
+ const belowCtx = createMockCtx2d();
+ const matteCtx = createMockCtx2d();
+ const matte = makeRefTarget(matteCtx);
+ matte.querySelector("canvas.hf-vfx-src")!.setAttribute("data-vfx-ref-visible", "");
+ sizeHost(matte.querySelector(".hf-vfx-in") as HTMLElement, 640, 360);
+ const host = makeBackdropHost(belowCtx, "adj-1", REF_NODE);
+ initVfx(document.body, 30);
+ host.style.visibility = "hidden";
+
+ paintVfx(0, { engineMode: true });
+
+ expect(compositeWindow().__hf_page_composite_resolve!()).toBe(true);
+ // The pass-through still runs (the adjustment layer's own layers below).
+ expect(belowCtx.drawn).toHaveLength(1);
+ // ...and the visible ref, on a DIFFERENT element, still draws too.
+ expect(matteCtx.drawn).toEqual([{ el: matte.querySelector(".hf-vfx-in"), w: 640, h: 360 }]);
+ expect(errors).toEqual([]);
+ });
+
+ it("still captures a visible ref through the preview path while its BACKDROP host is hidden", async () => {
+ const belowCtx = createMockCtx2d();
+ const matteCtx = createMockCtx2d();
+ const matte = makeRefTarget(matteCtx);
+ matte.querySelector("canvas.hf-vfx-src")!.setAttribute("data-vfx-ref-visible", "");
+ sizeHost(matte.querySelector(".hf-vfx-in") as HTMLElement, 640, 360);
+ const host = makeBackdropHost(belowCtx, "adj-1", REF_NODE);
+ const below = document.querySelector('canvas[data-vfx-for="adj-1"]')!;
+ initVfx(document.body, 30);
+ host.style.visibility = "hidden";
+
+ paintVfx(0.5);
+ // A pass-through frame now waits on the backdrop wrapper AND the visible
+ // ref's own canvas, so both must paint before the barrier releases.
+ below.dispatchEvent(new Event("paint"));
+ matte.querySelector("canvas.hf-vfx-src")!.dispatchEvent(new Event("paint"));
+ await flushTasks();
+
+ expect({ below: belowCtx.drawn.length, matte: matteCtx.drawn.length }).toEqual({
+ below: 1,
+ matte: 1,
+ });
+ });
+});
+
+/**
+ * `displacement-map`'s `map` ref (plan Backlog, "one-line def change after
+ * Task 2.6"). Optional, so the self-referential form every corpus instance
+ * uses keeps working untouched.
+ */
+describe("vfx runtime — an optional ref (displacement-map's map)", () => {
+ const mapChain = (params: Record<string, unknown>): string =>
+ JSON.stringify({
+ version: 1,
+ nodes: [{ type: "displacement-map", id: "n1", params }],
+ });
+
+ function makeMapTarget(ctx: unknown, id = "map-1"): HTMLElement {
+ const el = document.createElement("div");
+ el.id = id;
+ sizeHost(el);
+ el.appendChild(makeCaptureWrapper(ctx));
+ document.body.appendChild(el);
+ return el;
+ }
+
+ beforeEach(() => installVfxHarness(null));
+ afterEach(releaseVfxHarness);
+
+ it("binds a named map element as u_src2 and tells the kernel it is there", () => {
+ const ctx = createMockCtx2d();
+ const mapCtx = createMockCtx2d();
+ const map = makeMapTarget(mapCtx);
+ makeCaptureHost(ctx, "cap", mapChain({ useH: 1, maxH: 20, map: "map-1" }));
+
+ expect(initVfx(document.body, 30)).toHaveLength(1);
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ expect(mapCtx.drawn[0]!.el).toBe(map.querySelector(".hf-vfx-in"));
+ expect(gl!.uniforms["u_src2"]).toBe(1);
+ expect(gl!.uniforms["u_hasSrc2"]).toBe(1);
+ expect(errors).toEqual([]);
+ });
+
+ it("falls back to the layer's own pixels when the map is empty", () => {
+ const ctx = createMockCtx2d();
+ makeCaptureHost(ctx, "cap", mapChain({ useH: 1, maxH: 20 }));
+
+ expect(initVfx(document.body, 30)).toHaveLength(1);
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ // One capture, not two, and the kernel is told to read `u_src` as its map.
+ expect(ctx.drawn).toHaveLength(1);
+ expect(gl!.uniforms["u_hasSrc2"]).toBe(0);
+ expect(errors).toEqual([]);
+ });
+
+ it("treats a map naming the host itself as the self-referential form", () => {
+ const ctx = createMockCtx2d();
+ makeCaptureHost(ctx, "cap", mapChain({ useH: 1, maxH: 20, map: "cap" }));
+
+ expect(initVfx(document.body, 30)).toHaveLength(1);
+ paintVfx(0, { engineMode: true });
+ compositeWindow().__hf_page_composite_resolve!();
+
+ expect(ctx.drawn).toHaveLength(1);
+ expect(gl!.uniforms["u_hasSrc2"]).toBe(0);
+ expect(errors).toEqual([]);
+ });
+
+ it("still refuses a map that names an element with no capture wrapper", () => {
+ const orphan = document.createElement("div");
+ orphan.id = "map-1";
+ document.body.appendChild(orphan);
+ makeCaptureHost(createMockCtx2d(), "cap", mapChain({ map: "map-1" }));
+
+ expect(initVfx(document.body, 30)).toHaveLength(0);
+ expect(String(errors[0]![1])).toMatch(/"map" source/);
+ });
+});
diff --git a/packages/core/src/runtime/vfx.ts b/packages/core/src/runtime/vfx.ts
index 3f32fc7051..4cf1cafed3 100644
--- a/packages/core/src/runtime/vfx.ts
+++ b/packages/core/src/runtime/vfx.ts
@@ -30,10 +30,20 @@ import {
type HfVfxNode,
type HfVfxParam,
type HfVfxParamValues,
+ type HfVfxRefParam,
} from "../vfx";
import { registerSeekCompletion } from "./adapters/seek-dispatch";
import { isCanvasElement, isHtmlElement } from "./domRealm";
+/**
+ * Marks a `ref` wrapper whose element ALSO paints on its own — v1.1 assumed a
+ * matte source is invisible in After Effects and that is not always true
+ * (retro-wave `Logo Anim` layer 5 is layer 4's displacement map AND an enabled,
+ * fully opaque layer). Without it the runtime would clear the wrapper's bitmap
+ * after reading it and the layer would vanish from the page.
+ */
+const VFX_REF_VISIBLE_ATTR = "data-vfx-ref-visible";
+
/** The prefix `frameCapture.ts` matches to fail a render fast. */
const VFX_ERROR_LABEL = "[HyperFrames] composition script error:";
@@ -78,12 +88,36 @@ interface CompositeWindow extends Window {
__hf_page_composite_resolve?: () => boolean;
}
-/** Everything a `self` host needs to read its own pixels back. */
+/**
+ * One captured texture: the `<canvas layoutsubtree class="hf-vfx-src">` wrapper
+ * the exporter emitted, its single `.hf-vfx-in` child, and the GL texture the
+ * capture is uploaded into.
+ *
+ * The same shape serves all three sources a chain can read — the host's own
+ * pixels (`self`), everything below the host (`backdrop`), and a second element
+ * named by a `ref` param (`u_src2`) — because at capture time they differ only
+ * in WHICH element supplies the pixels.
+ */
interface VfxCaptureSource {
canvas: HTMLCanvasElement;
inner: HTMLElement;
ctx: DrawElementCtx;
texture: WebGLTexture;
+ /**
+ * The wrapper was found through `data-vfx-for`, i.e. it wraps the layers
+ * BELOW the host rather than the host's own content. Such a wrapper lives
+ * outside the host, which is what makes a hidden host a pass-through rather
+ * than a hole (see `capturePassThrough`).
+ */
+ backdrop: boolean;
+ /**
+ * The wrapper carries `data-vfx-ref-visible`: its bitmap is a layer the page
+ * shows, not only a texture, so the capture keeps it and draws it at the
+ * REF's own box rather than the host's.
+ */
+ visible: boolean;
+ /** `.hf-vfx-in` measured 0×0 and that has already been reported once. */
+ emptyBoxReported: boolean;
}
/**
@@ -101,6 +135,10 @@ interface PassLocations {
t: WebGLUniformLocation | null;
fps: WebGLUniformLocation | null;
src: WebGLUniformLocation | null;
+ /** Bound only for a def with a `ref` param (v1.1's second source). */
+ src2: WebGLUniformLocation | null;
+ /** 1 when this pass's optional ref actually resolved, 0 when it did not. */
+ hasSrc2: WebGLUniformLocation | null;
/** Keyed by the def's param key, without the `u_` prefix. */
params: Record<string, WebGLUniformLocation | null>;
}
@@ -112,6 +150,16 @@ interface VfxPass {
/** Chain params after clamp/defaults; CSS vars override per paint. */
params: HfVfxParamValues;
locations: PassLocations;
+ /** `u_src2`: the element this node's `ref` param named. Per NODE, not per
+ * entry — two nodes in one chain may matte against different elements. */
+ ref?: VfxCaptureSource;
+ /**
+ * The `ref` param names this pass's OWN host — the self-referential stencil
+ * shape (`target === host` in `resolveRefSource`). There is no second
+ * texture to capture, so `bindPass` points `u_src2` at unit 0 explicitly
+ * instead of leaving it unbound.
+ */
+ selfRef?: boolean;
}
/** Two colour targets a multi-node chain alternates between. */
@@ -125,6 +173,13 @@ interface PingPong {
export interface VfxEntry {
host: HTMLElement;
chain: HfVfxChain;
+ /**
+ * What this host RESOLVED to, not what its defs declare: `backdrop` when the
+ * wrapper was found through `data-vfx-for`, else the chain's own requirement.
+ * The two are the same kernel reading the same `u_src` — `self` and
+ * `backdrop` differ only in which element the exporter put inside the
+ * wrapper — so the DOM is the only place the distinction exists.
+ */
capture: HfVfxCapture;
out: HTMLCanvasElement;
gl: WebGL2RenderingContext;
@@ -242,12 +297,107 @@ function resolveUniformLocations(
t: gl.getUniformLocation(program, "u_t"),
fps: gl.getUniformLocation(program, "u_fps"),
src: gl.getUniformLocation(program, "u_src"),
+ src2: gl.getUniformLocation(program, "u_src2"),
+ hasSrc2: gl.getUniformLocation(program, "u_hasSrc2"),
params,
};
}
-function buildPasses(gl: WebGL2RenderingContext, chain: HfVfxChain): VfxPass[] | null {
+/**
+ * What a pass's `ref` param resolved to. A plain union return (rather than
+ * overloading `undefined`/`null`) is what lets `buildPasses` tell "no ref
+ * param on this def" apart from "ref param present, but self-referential" —
+ * `VfxPass.selfRef` needs that distinction to bind `u_src2` explicitly instead
+ * of relying on an unbound sampler's implicit unit-0 default.
+ */
+type RefResolution =
+ | { kind: "none" }
+ | { kind: "self" }
+ | { kind: "error" }
+ | { kind: "source"; source: VfxCaptureSource };
+
+/**
+ * The element a `ref` param names, wrapped in its own capture canvas.
+ *
+ * The exporter wraps a matte/map source the same way it wraps a `self` layer
+ * (the interface spec's v1.1: "the exporter wraps the referenced element in its
+ * own `.hf-vfx-src` canvas") — which is also why nothing is injected here. A
+ * runtime-created `<canvas layoutsubtree>` would be invisible to
+ * `detectRenderModeHints`, and the `htmlInCanvas` single-worker pin it derives
+ * from the SOURCE markup is what keeps concurrent `drawElementImage` off.
+ */
+/**
+ * A `ref` param with no id supplied. An optional ref left empty is the def's
+ * own fallback (displacement-map reads `u_src` as its map), not a broken
+ * chain; a mandatory one with nothing named is an authoring error.
+ */
+function resolveEmptyRefParam(
+ host: HTMLElement,
+ node: HfVfxNode,
+ def: HfVfxDef,
+ param: HfVfxRefParam,
+): RefResolution {
+ if (param.optional) return { kind: "none" };
+ reportVfxError(
+ `${describeHost(host)}: node "${node.id}" (${def.id}) needs a "${param.key}" ` +
+ `param naming the id of the element to read as its second source.`,
+ );
+ return { kind: "error" };
+}
+
+function resolveRefSource(
+ host: HTMLElement,
+ node: HfVfxNode,
+ def: HfVfxDef,
+ params: HfVfxParamValues,
+ gl: WebGL2RenderingContext,
+ cache: Map<HTMLElement, VfxCaptureSource>,
+): RefResolution {
+ const param = def.params.find((p): p is HfVfxRefParam => p.kind === "ref");
+ if (!param) return { kind: "none" };
+ const id = params[param.key];
+ if (typeof id !== "string" || id === "") return resolveEmptyRefParam(host, node, def, param);
+ const target = host.ownerDocument.getElementById(id);
+ if (!isHtmlElement(target)) {
+ reportVfxError(
+ `${describeHost(host)}: node "${node.id}" (${def.id}) names "${param.key}" element ` +
+ `#${id}, which is not in the composition.`,
+ );
+ return { kind: "error" };
+ }
+ // A ref naming its own host is the self-referential form — `u_src` already
+ // holds those pixels. Capturing it again would cost a second
+ // `drawElementImage` per frame for the same image, and on a `backdrop` host
+ // it would resolve the `data-vfx-for` sibling and read the layers BELOW as
+ // the map.
+ //
+ // An OPTIONAL ref (displacement-map's `map`) already has a shader-side
+ // branch keyed off `u_hasSrc2` for "nothing named" — self-reference means
+ // exactly the same thing to it as leaving the param empty, so it is folded
+ // into `"none"` rather than given its own kind: `u_hasSrc2` stays 0 and the
+ // shader's own fallback reads `u_src`, unchanged from before this type.
+ // A MANDATORY ref (luma-matte's `matte`) has no such branch — its shader
+ // always samples `u_src2` — so a real `"self"` kind is the only way `u_src2`
+ // gets bound at all; `bindPass` points it at `u_src`'s own texture unit.
+ if (target === host) return param.optional ? { kind: "none" } : { kind: "self" };
+ const cached = cache.get(target);
+ if (cached) return { kind: "source", source: cached };
+ const source = resolveCaptureSource(target, gl, `${describeHost(host)}: "${param.key}" source`);
+ if (!source) return { kind: "error" };
+ source.visible = source.canvas.hasAttribute(VFX_REF_VISIBLE_ATTR);
+ cache.set(target, source);
+ return { kind: "source", source };
+}
+
+function buildPasses(
+ gl: WebGL2RenderingContext,
+ chain: HfVfxChain,
+ host: HTMLElement,
+): VfxPass[] | null {
const passes: VfxPass[] = [];
+ // One source per referenced ELEMENT: two nodes matting against the same
+ // matte capture it once and share the texture.
+ const refs = new Map<HTMLElement, VfxCaptureSource>();
for (const node of enabledVfxNodes(chain)) {
const def = getVfxDef(node.type);
if (!def) {
@@ -259,12 +409,17 @@ function buildPasses(gl: WebGL2RenderingContext, chain: HfVfxChain): VfxPass[] |
reportVfxError(`node "${node.id}" (${def.id}) has no usable program`);
return null;
}
+ const params = normalizeVfxParams(def.id, node.params);
+ const resolved = resolveRefSource(host, node, def, params, gl, refs);
+ if (resolved.kind === "error") return null;
passes.push({
node,
def,
program,
- params: normalizeVfxParams(def.id, node.params),
+ params,
locations: resolveUniformLocations(gl, program, def),
+ ...(resolved.kind === "source" ? { ref: resolved.source } : {}),
+ selfRef: resolved.kind === "self",
});
}
return passes;
@@ -281,33 +436,82 @@ function createCaptureTexture(gl: WebGL2RenderingContext): WebGLTexture {
}
/**
- * 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.
+ * The `backdrop` wrapper for `owner`: a `<canvas layoutsubtree class="hf-vfx-src"
+ * data-vfx-for="<owner id>">` among the owner's SIBLINGS, holding every layer
+ * below it (interface v1.1).
+ *
+ * Scoped to the parent rather than the document because that is where the
+ * exporter puts it — z-order is DOM order, so the wrapper is the host's own
+ * preceding sibling at whatever depth the host sits, stacked adjustment layers
+ * included. Read attribute-by-attribute instead of through a selector: an id
+ * goes into this comparison unescaped, and a `querySelector` built by
+ * concatenation would throw on an id a selector cannot spell.
+ */
+function findBackdropWrapper(owner: HTMLElement): HTMLCanvasElement | null {
+ const parent = owner.parentElement;
+ if (!parent || owner.id === "") return null;
+ const siblings = parent.children;
+ for (let i = 0; i < siblings.length; i++) {
+ const sibling = siblings.item(i);
+ if (!isCanvasElement(sibling)) continue;
+ if (!sibling.classList.contains("hf-vfx-src")) continue;
+ if (sibling.getAttribute("data-vfx-for") === owner.id) return sibling;
+ }
+ return null;
+}
+
+/**
+ * The `<canvas layoutsubtree class="hf-vfx-src">` that supplies `owner`'s
+ * pixels, 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.
+ *
+ * Resolution order, per plan Task 2.6: a `data-vfx-for` sibling (the
+ * `backdrop` shape — the layers below) before the owner's own child (the
+ * `self` shape — its own content). A def's `capture` says only THAT the kernel
+ * needs a texture; which element fills it is the exporter's placement, and this
+ * is where the runtime reads that placement off the DOM.
+ *
+ * `.hf-vfx-in` must be the canvas's IMMEDIATE child: Chrome refuses anything
+ * else with "Only immediate children of the <canvas> element can be passed to
+ * DrawElementImage", so a deeper wrapper is a registration-time error here
+ * rather than a throw on every frame.
*/
function resolveCaptureSource(
- host: HTMLElement,
+ owner: HTMLElement,
gl: WebGL2RenderingContext,
+ label: string,
): VfxCaptureSource | undefined {
- const canvas = host.querySelector("canvas.hf-vfx-src");
- const inner = canvas?.querySelector(".hf-vfx-in");
+ const backdrop = findBackdropWrapper(owner);
+ const canvas = backdrop ?? owner.querySelector("canvas.hf-vfx-src");
+ const inner = isCanvasElement(canvas) ? canvas.querySelector(":scope > .hf-vfx-in") : null;
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.`,
+ `${label}: a capturing chain needs ` +
+ `<canvas layoutsubtree class="hf-vfx-src"><div class="hf-vfx-in">…</div></canvas> in ` +
+ `source — inside the element for its own pixels, or beside it with ` +
+ `data-vfx-for="${owner.id}" for the layers below it.`,
);
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 ` +
+ `${label}: 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) };
+ return {
+ canvas,
+ inner,
+ ctx,
+ texture: createCaptureTexture(gl),
+ backdrop: backdrop !== null,
+ // Only a `ref` source may be visible; `resolveRefSource` sets it.
+ visible: false,
+ emptyBoxReported: false,
+ };
}
/**
@@ -340,15 +544,20 @@ function watchContextLoss(entry: VfxEntry): void {
});
}
-function registerVfxHost(host: HTMLElement): VfxEntry | null {
- let chain: HfVfxChain;
+/** The host's chain, or `null` once the reason it is unusable has been said. */
+function readVfxChain(host: HTMLElement): HfVfxChain | null {
try {
- chain = parseVfxChain(host.getAttribute(HF_VFX_ATTR) ?? "");
+ return parseVfxChain(host.getAttribute(HF_VFX_ATTR) ?? "");
} catch (err) {
const detail = err instanceof VfxChainError ? err.message : String(err);
reportVfxError(`${describeHost(host)}: ${detail}`);
return null;
}
+}
+
+function registerVfxHost(host: HTMLElement): VfxEntry | null {
+ const chain = readVfxChain(host);
+ if (!chain) return null;
const out = findOrCreateOut(host);
const gl = out.getContext("webgl2", GL_ATTRS);
if (!gl) {
@@ -356,42 +565,102 @@ function registerVfxHost(host: HTMLElement): VfxEntry | null {
out.remove();
return null;
}
- const passes = buildPasses(gl, chain);
+ const passes = buildPasses(gl, chain, host);
if (!passes) {
out.remove();
return null;
}
- const capture = chainCapture(chain);
- const src = capture === "none" ? undefined : resolveCaptureSource(host, gl);
- if (capture !== "none" && !src) {
+ const declared = chainCapture(chain);
+ const src = declared === "none" ? undefined : resolveCaptureSource(host, gl, describeHost(host));
+ if (declared !== "none" && !src) {
out.remove();
return null;
}
+ const capture = src?.backdrop ? "backdrop" : declared;
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.
+ * Whether an element is on screen, and so whether it has a paint record at
+ * all: `drawElementImage` throws on a hidden subtree, and the clip runtime
+ * hides everything outside its `data-start`/`data-duration` window, which
+ * would otherwise fail the render on each of those frames.
+ *
+ * Asked of hosts (does this chain paint?) and of capture sources (is there
+ * anything to read?) alike.
*/
function isPaintableHost(host: HTMLElement): boolean {
const style = getComputedStyle(host);
return style.display !== "none" && style.visibility !== "hidden";
}
+/**
+ * Whether a source's `.hf-vfx-in` has a paint record to capture. `visibility`
+ * inherits, so one read at `inner` covers a matte hidden that way; `display`
+ * does NOT, so a ref whose OWNING element is `display:none` (the clip
+ * runtime's `data-hidden` and in-flow timed-leaf paths) still computes
+ * `display:block` at `inner` — and would wait out the paint ceiling, then fail
+ * as a misleading 0×0. Hence the ancestor walk. `checkVisibility()` and
+ * `offsetParent` would say the same in Chrome but are absent or always-null
+ * in the unit harness's DOM.
+ */
+function isPaintableSource(src: VfxCaptureSource): boolean {
+ if (getComputedStyle(src.inner).visibility === "hidden") return false;
+ for (let el: HTMLElement | null = src.inner; el; el = el.parentElement) {
+ if (getComputedStyle(el).display === "none") return false;
+ }
+ return true;
+}
+
function describeHost(host: HTMLElement): string {
return host.id ? `#${host.id}` : `<${host.tagName.toLowerCase()}>`;
}
+/**
+ * Every texture this entry captures per frame, in binding order: `u_src`
+ * first, then each node's `u_src2`. A ref shared by two nodes appears once —
+ * `buildPasses` hands both passes the same source object.
+ */
+function entrySources(entry: VfxEntry): VfxCaptureSource[] {
+ const sources: VfxCaptureSource[] = entry.src ? [entry.src] : [];
+ for (const pass of entry.passes) {
+ if (pass.ref && !sources.includes(pass.ref)) sources.push(pass.ref);
+ }
+ return sources;
+}
+
+/**
+ * A chain whose source is the layers BELOW the host. Its wrapper is outside the
+ * host, so the host's own visibility does not decide whether those layers are
+ * on screen — `capturePassThrough` does.
+ */
+function isBackdropEntry(entry: VfxEntry): boolean {
+ return entry.src?.backdrop === true;
+}
+
+/**
+ * Every distinct VISIBLE ref this entry's passes read — element(s) that paint
+ * on the page independently of whether this entry's own kernel currently
+ * runs, exactly like `entrySources` but restricted to the sources whose
+ * bitmap is itself the frame (`VFX_REF_VISIBLE_ATTR`). A ref shared by two
+ * passes appears once, same rule as `entrySources`.
+ */
+function visibleRefSources(entry: VfxEntry): VfxCaptureSource[] {
+ const sources: VfxCaptureSource[] = [];
+ for (const pass of entry.passes) {
+ if (pass.ref?.visible && !sources.includes(pass.ref)) sources.push(pass.ref);
+ }
+ return sources;
+}
+
/** 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);
+ for (const source of entrySources(entry)) gl.deleteTexture(source.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);
@@ -507,6 +776,11 @@ function setPassUniforms(
gl.uniform2f(locations.size, width, height);
gl.uniform1f(locations.t, t);
gl.uniform1f(locations.fps, registryFps);
+ // A def whose ref is optional needs to know which sampler holds its second
+ // input; on a shader without the uniform the location is null and this is a
+ // defined no-op. A self-referential ref counts as resolved too — `u_src2`
+ // reads real data, just from unit 0 rather than a second capture.
+ gl.uniform1f(locations.hasSrc2, pass.ref || pass.selfRef ? 1 : 0);
for (const param of pass.def.params) {
const value = paramUniformValue(param, pass, style);
if (value === null) continue;
@@ -514,19 +788,51 @@ function setPassUniforms(
}
}
-/** Bind this pass's render target and its input texture. */
+/** Where this pass draws: the visible canvas for the last one, else the
+ * ping-pong target the next pass will read. */
+function passTarget(index: number, last: number, ping: PingPong | null): WebGLFramebuffer | null {
+ if (index === last || !ping) return null;
+ return ping.framebuffers[index % 2] ?? null;
+}
+
+/** What this pass reads as `u_src`: the capture for the first pass, the
+ * previous pass's target after that. */
+function passInput(entry: VfxEntry, index: number, ping: PingPong | null): WebGLTexture | null {
+ if (index === 0) return entry.src?.texture ?? null;
+ return ping?.textures[(index - 1) % 2] ?? null;
+}
+
+/** Bind this pass's render target and its input textures. */
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);
+ const pass = entry.passes[index]!;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, passTarget(index, last, ping));
+ const source = passInput(entry, index, ping);
+ if (source) bindSampler(gl, pass.locations.src, source, 0);
+ // Unit 1 for `u_src2`, then back to unit 0 so every other bind in this
+ // module — the next pass's, and `uploadCaptureTexture`'s — starts from the
+ // same active unit no matter which passes carry a ref.
+ if (pass.ref) {
+ bindSampler(gl, pass.locations.src2, pass.ref.texture, 1);
+ gl.activeTexture(gl.TEXTURE0);
+ } else if (pass.selfRef && source) {
+ // A `ref` param naming its own host: `u_src2` reads exactly what `u_src`
+ // just bound. Previously left unbound, which happened to read unit 0 by
+ // GLSL's default sampler binding — correct today, but implicit rather than
+ // stated.
+ gl.uniform1i(pass.locations.src2, 0);
+ }
+}
+
+function bindSampler(
+ gl: WebGL2RenderingContext,
+ location: WebGLUniformLocation | null,
+ texture: WebGLTexture,
+ unit: 0 | 1,
+): void {
+ gl.activeTexture(unit === 0 ? gl.TEXTURE0 : gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.uniform1i(location, unit);
}
function paintEntry(entry: VfxEntry, t: number): void {
@@ -551,6 +857,7 @@ function paintEntry(entry: VfxEntry, t: number): void {
}
function uploadCaptureTexture(gl: WebGL2RenderingContext, src: VfxCaptureSource): void {
+ gl.activeTexture(gl.TEXTURE0);
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.
@@ -562,18 +869,106 @@ function uploadCaptureTexture(gl: WebGL2RenderingContext, src: VfxCaptureSource)
}
/**
- * 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`.
+ * What a capture does with what it drew. Three combinations exist, and each
+ * one is a different kind of source:
+ *
+ * - texture only — an invisible source read as `u_src`/`u_src2`. The bitmap is
+ * cleared after the upload because a `layoutsubtree` canvas's BITMAP is
+ * painted by the page compositor even though its children are not, and
+ * leaving the raw capture there would show through `.hf-vfx-out`.
+ * - bitmap only — a `backdrop` wrapper whose host is not painting this frame
+ * (the bitmap IS the frame: it carries the layers below an adjustment layer
+ * that is currently off), or a VISIBLE ref whose owning host is not
+ * painting (the ref's own layer still has to show; no kernel will read the
+ * texture this frame, so there is nothing to upload).
+ * - both — a `ref` source the exporter marked visible, captured while its
+ * owning host IS painting. Its layer paints on its own AND feeds a kernel,
+ * so the capture is uploaded and left on screen.
*/
-function captureEntry(entry: VfxEntry, quiet = false): boolean {
- const src = entry.src;
- const size = deviceSize(entry.host);
- if (!src || !size) return false;
+interface CaptureMode {
+ upload: boolean;
+ keepBitmap: boolean;
+}
+
+const CAPTURE_TO_TEXTURE: CaptureMode = { upload: true, keepBitmap: false };
+const CAPTURE_PASS_THROUGH: CaptureMode = { upload: false, keepBitmap: true };
+const CAPTURE_VISIBLE_SOURCE: CaptureMode = { upload: true, keepBitmap: true };
+/**
+ * A visible ref captured while its owning entry's host is NOT painting: the
+ * ref's own layer still has to stay current on screen, but no kernel will run
+ * to read the texture this frame (`paintEntry` never fires), so the upload is
+ * skipped.
+ */
+const CAPTURE_VISIBLE_ONLY: CaptureMode = { upload: false, keepBitmap: true };
+
+/** Assigning `width`/`height` clears the bitmap, so only a real change does. */
+function resizeCaptureCanvas(src: VfxCaptureSource, size: { width: number; height: number }): void {
if (src.canvas.width !== size.width) src.canvas.width = size.width;
if (src.canvas.height !== size.height) src.canvas.height = size.height;
+}
+
+/**
+ * Read one source's pixels into its texture. 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`.
+ *
+ * `keepBitmap` inverts exactly that second clear: for a `backdrop` wrapper
+ * whose host is not painting this frame, where the bitmap IS the frame (see
+ * `capturePassThrough`), and for a VISIBLE ref whose owning host is not
+ * painting (see `captureVisibleRefsOnly`) — the ref's layer is on screen
+ * either way.
+ *
+ * Every source is drawn at the HOST's device size (`captureBox`'s default),
+ * so `u_src` and `u_src2` share one coordinate space with `.hf-vfx-out` and a
+ * kernel can read both at the same `v_uv`. A matte whose own box differs from
+ * the host's is therefore scaled into the host's box rather than placed in
+ * composition space — v1's semantic, recorded because After Effects places it
+ * in comp space. A VISIBLE ref is the one exception: `captureBox` draws it at
+ * its OWN box, since it is a layer on the page and must paint at its own
+ * size, not the host's.
+ */
+function captureSource(
+ entry: VfxEntry,
+ src: VfxCaptureSource,
+ size: { width: number; height: number },
+ quiet: boolean,
+ mode: CaptureMode,
+): boolean {
+ // A hidden source is an EMPTY capture, not a failure. The clip runtime hides
+ // a matte layer outside its own window (`visibility: hidden`, inherited by
+ // the `.hf-vfx-in` inside it), and a hidden subtree has no paint record:
+ // `drawElementImage` would throw "No cached paint record" on every one of
+ // those frames, and the `paint` wait before it would burn its whole ceiling
+ // first. An empty `u_src2` is also the right answer — under Alpha the layer
+ // it mattes disappears, under Alpha Inverted it passes, which is what After
+ // Effects does with a matte that is not there yet.
+ if (!isPaintableSource(src)) {
+ resizeCaptureCanvas(src, size);
+ src.ctx.clearRect(0, 0, size.width, size.height);
+ if (mode.upload) uploadCaptureTexture(entry.gl, src);
+ return true;
+ }
+ // The one capture failure Chrome does NOT report: inside a `layoutsubtree`
+ // canvas a child sized by `inset`/percentages measures 0×0, and
+ // `drawElementImage` then succeeds and draws nothing at all — no throw, no
+ // warning, a blank layer. Measured (vault `layoutsubtree-capture-rules`),
+ // so it is checked here and said out loud, once per source rather than once
+ // per frame.
+ if (deviceSize(src.inner) === null) {
+ if (!src.emptyBoxReported) {
+ src.emptyBoxReported = true;
+ reportVfxError(
+ `${describeHost(entry.host)}: the .hf-vfx-in wrapper measures 0×0, so its capture ` +
+ `would be empty. Inside a layoutsubtree canvas an inset or percentage box has no ` +
+ `size — the wrapper must state an explicit width and height in px.`,
+ );
+ }
+ return false;
+ }
+ resizeCaptureCanvas(src, size);
src.ctx.clearRect(0, 0, size.width, size.height);
try {
src.ctx.drawElementImage(src.inner, 0, 0, size.width, size.height);
@@ -591,17 +986,115 @@ function captureEntry(entry: VfxEntry, quiet = false): boolean {
}
return false;
}
- uploadCaptureTexture(entry.gl, src);
- src.ctx.clearRect(0, 0, size.width, size.height);
+ if (mode.upload) uploadCaptureTexture(entry.gl, src);
+ if (!mode.keepBitmap) src.ctx.clearRect(0, 0, size.width, size.height);
return true;
}
+/**
+ * The box one source is drawn at. The host's, so `u_src`, `u_src2` and
+ * `.hf-vfx-out` share a pixel grid — except for a VISIBLE ref, which is a
+ * layer on the page and must paint at its own size and resolution. Sampling is
+ * unaffected either way: `drawElementImage(el, 0, 0, w, h)` scales the element
+ * into the whole canvas, so normalized `v_uv` addresses the same point in the
+ * element's box whatever the bitmap's pixel size — which is the v1 rule, a
+ * ref scaled into the host's box rather than placed in composition space.
+ */
+function captureBox(
+ src: VfxCaptureSource,
+ hostSize: { width: number; height: number },
+): { width: number; height: number } {
+ if (!src.visible) return hostSize;
+ return deviceSize(src.inner) ?? hostSize;
+}
+
+/**
+ * Capture everything this entry's kernels read for one frame: `u_src`, then
+ * each node's `u_src2`. A source that fails does not stop the others — the
+ * failure is reported where it happened — but the frame is only "captured"
+ * when all of them are, so a half-captured paint never counts as authoritative.
+ */
+function captureEntry(entry: VfxEntry, quiet = false): boolean {
+ const size = deviceSize(entry.host);
+ const sources = entrySources(entry);
+ if (!size || sources.length === 0) return false;
+ let captured = true;
+ for (const source of sources) {
+ const mode = source.visible ? CAPTURE_VISIBLE_SOURCE : CAPTURE_TO_TEXTURE;
+ if (!captureSource(entry, source, captureBox(source, size), quiet, mode)) {
+ captured = false;
+ }
+ }
+ return captured;
+}
+
+/**
+ * A `backdrop` host that is not painting this frame — the clip runtime hides
+ * every host outside its `data-start`/`data-duration` window — still has to
+ * draw its source, because that source is every layer BELOW it and those
+ * layers are children of a `layoutsubtree` canvas: the page compositor paints
+ * the canvas bitmap and nothing else. Skipping the capture the way a `self`
+ * host is skipped would delete them from the frame instead of passing them
+ * through unprocessed.
+ *
+ * So: capture, keep the bitmap, paint no kernel. The adjustment layer is off,
+ * its input is on. Sized from the wrapper's own box when the host has none, so
+ * a host hidden with `display:none` (the timed-clip leaf path) still passes its
+ * layers through.
+ */
+function capturePassThrough(entry: VfxEntry, quiet = false): boolean {
+ const src = entry.src;
+ if (!src) return false;
+ const size = deviceSize(entry.host) ?? deviceSize(src.inner);
+ if (!size) return false;
+ return captureSource(entry, src, size, quiet, CAPTURE_PASS_THROUGH);
+}
+
+/**
+ * A host that is not painting this frame but owns a VISIBLE ref: that ref's
+ * AE layer can outlive the kernel host's own `data-start`/`data-duration`
+ * window (retro-wave `Logo Anim` layer 5 again — it is layer 4's displacement
+ * map AND a layer with its own, different, on-screen span), so its bitmap has
+ * to stay current even though no kernel reads it this frame. Capture only,
+ * never upload: nothing will bind the texture, since `paintEntry` does not
+ * run for a host that is not painting.
+ *
+ * A `hostSize` fallback of `{0, 0}` is safe here: `captureBox` only falls back
+ * to it when a VISIBLE source's own box (`deviceSize(src.inner)`) is null, and
+ * that is already reported by `captureSource`'s own 0×0 check.
+ */
+function captureVisibleRefsOnly(entry: VfxEntry, quiet = false): boolean {
+ let ok = true;
+ for (const ref of visibleRefSources(entry)) {
+ const size = captureBox(ref, { width: 0, height: 0 });
+ if (!captureSource(entry, ref, size, quiet, CAPTURE_VISIBLE_ONLY)) ok = false;
+ }
+ return ok;
+}
+
+/**
+ * A hidden host still needs capturing when it's a backdrop's layers-below
+ * source, or when one of its passes' ref sources paints visibly elsewhere —
+ * and a host can be BOTH (a backdrop whose displacement map is itself a
+ * visible layer), so this always runs whichever apply, not one or the other.
+ */
+function captureHiddenEntry(entry: VfxEntry): boolean {
+ let ok = false;
+ if (isBackdropEntry(entry) && capturePassThrough(entry)) ok = true;
+ if (visibleRefSources(entry).length > 0 && captureVisibleRefsOnly(entry)) ok = true;
+ return ok;
+}
+
/** 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 (entrySources(entry).length === 0) continue;
+ if (!isPaintableHost(entry.host)) {
+ if (captureHiddenEntry(entry)) painted = true;
+ continue;
+ }
if (!captureEntry(entry)) continue;
paintEntry(entry, lastPaintTime);
painted = true;
@@ -703,6 +1196,64 @@ function awaitCanvasPaint(canvas: HTMLCanvasElement): Promise<"painted" | "timeo
});
}
+/** Every source's canvas, awaited together; `false` once a timeout has been
+ * reported. In parallel because one canvas's wait does not inform another's. */
+async function awaitSourcePaints(entry: VfxEntry, sources: VfxCaptureSource[]): Promise<boolean> {
+ const outcomes = await Promise.all(sources.map((source) => awaitCanvasPaint(source.canvas)));
+ if (!outcomes.includes("timeout")) return true;
+ 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 false;
+}
+
+/**
+ * Which of an entry's three capture shapes this frame needs, decided once so
+ * every step of `capturePaintedHost` reads the same answer: the host's own
+ * kernel paint, the backdrop pass-through (which ALSO captures any visible
+ * ref the host owns — a backdrop's displacement map can itself be a layer
+ * with its own on-screen span), or — a host that is hidden and NOT a
+ * backdrop, but owns a visible ref whose own layer must keep showing — a
+ * ref-only capture that skips the kernel entirely.
+ */
+type FrameCaptureMode = "paint" | "passThrough" | "refOnly";
+
+function frameCaptureMode(entry: VfxEntry): FrameCaptureMode {
+ if (isPaintableHost(entry.host)) return "paint";
+ return isBackdropEntry(entry) ? "passThrough" : "refOnly";
+}
+
+/** The sources this frame needs: all of them to paint; the backdrop wrapper
+ * plus any visible ref(s) to pass through (a backdrop host can itself own a
+ * visible ref — its displacement map may be a layer with its own on-screen
+ * span); or just the visible ref(s) alone to keep them current. */
+function sourcesForFrame(entry: VfxEntry, mode: FrameCaptureMode): VfxCaptureSource[] {
+ const sources =
+ mode === "passThrough"
+ ? [...(entry.src ? [entry.src] : []), ...visibleRefSources(entry)]
+ : mode === "refOnly"
+ ? visibleRefSources(entry)
+ : entrySources(entry);
+ // A hidden source never fires `paint`, and under a BeginFrame-controlled
+ // compositor the rAF fallback does not either — waiting on one would spend
+ // the whole ceiling, every frame, to arrive at the empty capture
+ // `captureSource` gives it for free.
+ return sources.filter(isPaintableSource);
+}
+
+/**
+ * Nothing has taken this frame over during the paint wait: no newer seek, no
+ * engine resolve that already owns the pixels, and no `initVfx` re-scan — that
+ * releases the outgoing registry's programs and textures, and painting a
+ * released entry is a silent GL error rather than a frame.
+ */
+function stillOwnsFrame(entry: VfxEntry, seq: number): boolean {
+ if (seq !== paintSeq || resolvedSeq === seq) return false;
+ return registry.includes(entry) && !entry.contextLost;
+}
+
/**
* Wait for one host's canvas to paint, then capture and paint that host.
*
@@ -722,20 +1273,22 @@ async function capturePaintedHost(
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).`,
- );
+ // A pass-through frame needs the backdrop wrapper's paint record plus any
+ // visible ref's; a ref-only frame needs only the visible ref's; a painting
+ // frame needs one per source the kernels read. Records are per canvas, so
+ // the waits are too.
+ const mode = frameCaptureMode(entry);
+ if (!(await awaitSourcePaints(entry, sourcesForFrame(entry, mode)))) return;
+ if (!stillOwnsFrame(entry, seq)) return;
+ if (mode === "passThrough") {
+ capturePassThrough(entry, speculative);
+ captureVisibleRefsOnly(entry, speculative);
+ return;
+ }
+ if (mode === "refOnly") {
+ captureVisibleRefsOnly(entry, speculative);
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);
}
@@ -788,8 +1341,20 @@ export function paintVfx(t: number, options?: { engineMode?: boolean }): void {
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);
+ if (!isPaintableHost(entry.host)) {
+ // A hidden `backdrop` host is an adjustment layer that is off, not a
+ // reason to drop the layers below it — those live in the wrapper
+ // OUTSIDE the host and are invisible until something draws them. A
+ // hidden non-backdrop host with a VISIBLE ref is the same shape one
+ // level removed: the ref's own AE layer can outlive this host's
+ // data-start/data-duration window, and skipping the whole entry would
+ // leave that layer missing (before its host's window) or stale (after
+ // it, since `CAPTURE_VISIBLE_SOURCE`/`CAPTURE_VISIBLE_ONLY` both keep
+ // the bitmap).
+ if (isBackdropEntry(entry) || visibleRefSources(entry).length > 0) capturing.push(entry);
+ continue;
+ }
+ if (entrySources(entry).length > 0) capturing.push(entry);
else paintEntry(entry, t);
}
if (capturing.length === 0) return;
diff --git a/packages/core/src/vfx.ts b/packages/core/src/vfx.ts
index 6728d76ff8..b48966bdf8 100644
--- a/packages/core/src/vfx.ts
+++ b/packages/core/src/vfx.ts
@@ -10,6 +10,8 @@
import { FRACTAL_NOISE_FRAG } from "./vfx/fractalNoise.frag";
import { DISPLACEMENT_MAP_FRAG } from "./vfx/displacementMap.frag";
+import { LUMA_MATTE_FRAG } from "./vfx/lumaMatte.frag";
+import { NOISE_FRAG } from "./vfx/noise.frag";
import { WAVE_WARP_FRAG } from "./vfx/waveWarp.frag";
export const HF_VFX_ATTR = "data-vfx-chain";
@@ -67,6 +69,14 @@ export interface HfVfxRefParam {
kind: "ref";
key: string;
label: string;
+ /**
+ * The kernel works without it. `displacement-map` reads its own pixels as
+ * the map when `map` is empty (every corpus instance is self-referential),
+ * while `luma-matte` without a matte has nothing to do, so a missing id
+ * there is a loud failure. Spec amendment to v1.1, which had no optional
+ * refs because its only ref was required.
+ */
+ optional?: boolean;
}
export type HfVfxParam = HfVfxNumberParam | HfVfxEnumParam | HfVfxBoolParam | HfVfxRefParam;
@@ -323,6 +333,14 @@ export const HF_VFX: readonly HfVfxDef[] = [
capture: "self",
frag: DISPLACEMENT_MAP_FRAG,
params: [
+ {
+ kind: "ref",
+ key: "map",
+ label: "Displacement Map Layer",
+ // Optional: empty means the AE default the corpus uses, a map layer
+ // pointing at the layer itself, which `u_src` already holds.
+ optional: true,
+ },
{
kind: "enum",
key: "useH",
@@ -385,6 +403,67 @@ export const HF_VFX: readonly HfVfxDef[] = [
},
],
},
+ {
+ id: "luma-matte",
+ label: "Matte",
+ // Not one AE effect: the runtime form of every matte the exporter cannot
+ // express as CSS — unsupported track-matte sources, stencils and
+ // silhouettes, Set Matte. Which element is the source and which the matte
+ // is the exporter's choice of what to wrap and what to name in `matte`.
+ capture: "self",
+ frag: LUMA_MATTE_FRAG,
+ params: [
+ { kind: "ref", key: "matte", label: "Matte Layer" },
+ {
+ kind: "enum",
+ key: "mode",
+ label: "Matte Mode",
+ options: [
+ { value: 1, label: "Alpha" },
+ { value: 2, label: "Alpha Inverted" },
+ { value: 3, label: "Luma" },
+ { value: 4, label: "Luma Inverted" },
+ ],
+ default: 1,
+ },
+ ],
+ },
+ {
+ id: "noise",
+ label: "Noise",
+ ae: "ADBE Noise",
+ // `self` on a content layer and `backdrop` on an adjustment layer are the
+ // same kernel reading the same `u_src`; the runtime resolves which from
+ // the DOM (a `data-vfx-for` wrapper), so the def declares only that a
+ // texture is needed.
+ capture: "self",
+ frag: NOISE_FRAG,
+ params: [
+ {
+ kind: "number",
+ key: "amount",
+ label: "Amount of Noise",
+ unit: "%",
+ min: 0,
+ max: 400,
+ step: 0.1,
+ default: 0,
+ animatable: true,
+ },
+ {
+ kind: "bool",
+ key: "useColorNoise",
+ label: "Use Color Noise",
+ default: false,
+ },
+ {
+ kind: "bool",
+ key: "clipping",
+ label: "Clip Result Values",
+ default: true,
+ },
+ ],
+ },
] as const;
const BY_ID = new Map(HF_VFX.map((d) => [d.id, d]));
diff --git a/packages/core/src/vfx/displacementMap.frag.ts b/packages/core/src/vfx/displacementMap.frag.ts
index 818fd2a433..60443fd0da 100644
--- a/packages/core/src/vfx/displacementMap.frag.ts
+++ b/packages/core/src/vfx/displacementMap.frag.ts
@@ -1,13 +1,16 @@
/**
* `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.
+ * **The map layer.** 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 — that is what the `map` ref param
+ * being EMPTY means, and it stays the default. An external map layer is the
+ * same kernel reading `u_src2`: the exporter names that element in `map` and
+ * wraps it in its own `.hf-vfx-src` capture, and `u_hasSrc2` switches the
+ * sampler. The two inputs are read at the same `v_uv`, so an external map is
+ * scaled into the host's box (see `captureSource`), not placed in composition
+ * space.
*
* 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
@@ -51,6 +54,10 @@ uniform vec2 u_size;
uniform float u_t;
uniform float u_fps;
uniform sampler2D u_src;
+uniform sampler2D u_src2;
+// 1 when the map ref named another element, 0 when the map is the layer
+// itself. Set by the runtime for every pass, from whether a ref resolved.
+uniform float u_hasSrc2;
uniform float u_useH;
uniform float u_maxH;
uniform float u_useV;
@@ -78,7 +85,7 @@ float hfMapChannel(vec4 premultiplied, float selector) {
}
void main() {
- vec4 mapTexel = texture(u_src, v_uv);
+ vec4 mapTexel = u_hasSrc2 > 0.5 ? texture(u_src2, v_uv) : 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);
diff --git a/packages/core/src/vfx/lumaMatte.frag.ts b/packages/core/src/vfx/lumaMatte.frag.ts
new file mode 100644
index 0000000000..e4405ab1ed
--- /dev/null
+++ b/packages/core/src/vfx/lumaMatte.frag.ts
@@ -0,0 +1,76 @@
+/**
+ * `luma-matte` kernel — GLSL ES 3.00, capture `self` plus a `ref` second
+ * source.
+ *
+ * **What it ports.** Not a single After Effects effect: this is the runtime
+ * form of every matte the exporter cannot express as CSS — a track matte whose
+ * source layer is unsupported (`matte-source-unsupported:*`), a stencil or
+ * silhouette (`stencil-*`), and Set Matte. All of them are the same
+ * per-pixel operation, `out = src · coverage(matte)`, differing only in which
+ * element is the source and which is the matte. The exporter decides that by
+ * choosing which element the host wraps and which the `matte` ref names; a
+ * stencil is this kernel with the host's own content as the matte.
+ *
+ * **Coverage.** `src` arrives premultiplied, so scaling all four channels by a
+ * single coverage value is the whole operation — no unpremultiply/repremultiply
+ * round trip, and a coverage of 0 yields a genuinely empty pixel rather than a
+ * black one.
+ *
+ * - Alpha (1) / Alpha Inverted (2): the matte's alpha.
+ * - Luma (3) / Luma Inverted (4): the matte's luminance **composited over
+ * black**, which is what the premultiplied texel already holds — a matte that
+ * is 50 % grey at 50 % opacity reads as 0.25, matching After Effects, where a
+ * luma matte's transparent regions are black rather than ignored.
+ *
+ * Rec.601 weights, shared with `displacement-map`'s Luminance channel selector
+ * so the two agree on what "luminance" means.
+ *
+ * **Out of scope in v1, recorded rather than implied:** the matte is sampled at
+ * the host's own `v_uv`, so the runtime captures it into the host's box (see
+ * `captureSource`). After Effects places a matte layer in composition space
+ * with its own transform; a matte whose box differs from the layer's is
+ * therefore stretched here, not positioned. Every corpus matte is a
+ * full-frame sibling of its layer, where the two agree.
+ */
+
+import { DISPLACEMENT_MAP_CONSTANTS } from "./displacementMap.frag";
+
+const { lumaR, lumaG, lumaB } = DISPLACEMENT_MAP_CONSTANTS;
+
+/** The `mode` enum, named once so the def, the shader and the reference agree. */
+export const LUMA_MATTE_MODES = {
+ alpha: 1,
+ alphaInverted: 2,
+ luma: 3,
+ lumaInverted: 4,
+} as const;
+
+export const LUMA_MATTE_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 sampler2D u_src2;
+uniform float u_mode;
+
+// The matte texel is premultiplied, so its rgb is already "over black" — the
+// composite After Effects reads a luma matte through.
+float hfCoverage(vec4 matte, float mode) {
+ if (mode < 1.5) return matte.a;
+ if (mode < 2.5) return 1.0 - matte.a;
+ float luma = dot(matte.rgb, vec3(${lumaR}, ${lumaG}, ${lumaB}));
+ if (mode < 3.5) return luma;
+ return 1.0 - luma;
+}
+
+void main() {
+ vec4 src = texture(u_src, v_uv);
+ vec4 matte = texture(u_src2, v_uv);
+ fragColor = src * clamp(hfCoverage(matte, u_mode), 0.0, 1.0);
+}
+`;
diff --git a/packages/core/src/vfx/lumaMatte.test.ts b/packages/core/src/vfx/lumaMatte.test.ts
new file mode 100644
index 0000000000..f60b9f14b4
--- /dev/null
+++ b/packages/core/src/vfx/lumaMatte.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from "vitest";
+import { LUMA_MATTE_FRAG, LUMA_MATTE_MODES } from "./lumaMatte.frag";
+import { lumaMatteCoverageRef, lumaMatteSampleRef, type Rgba } from "./refs/lumaMatte";
+import { getVfxDef, normalizeVfxParams } from "../vfx";
+
+/** An opaque mid-grey source, premultiplied like the capture texture. */
+const SRC: Rgba = { r: 0.4, g: 0.6, b: 0.8, a: 1 };
+const OPAQUE_WHITE: Rgba = { r: 1, g: 1, b: 1, a: 1 };
+const CLEAR: Rgba = { r: 0, g: 0, b: 0, a: 0 };
+
+describe("luma-matte def", () => {
+ it("is registered as a capturing kernel with a ref param and the real fragment source", () => {
+ const def = getVfxDef("luma-matte")!;
+ const ref = def.params.find((p) => p.kind === "ref");
+ expect(def.capture).toBe("self");
+ expect(ref?.key).toBe("matte");
+ expect(def.frag).toBe(LUMA_MATTE_FRAG);
+ expect(LUMA_MATTE_FRAG.startsWith("#version 300 es")).toBe(true);
+ // The second source is what makes this kernel possible at all.
+ expect(LUMA_MATTE_FRAG).toContain("uniform sampler2D u_src2;");
+ });
+
+ it("keeps a ref param's element id and falls back to empty for a non-string", () => {
+ expect(normalizeVfxParams("luma-matte", { matte: "rw-matte-1" })["matte"]).toBe("rw-matte-1");
+ expect(normalizeVfxParams("luma-matte", { matte: 7 })["matte"]).toBe("");
+ expect(normalizeVfxParams("luma-matte", {})["matte"]).toBe("");
+ });
+
+ it("normalizes an unknown mode back to Alpha", () => {
+ expect(normalizeVfxParams("luma-matte", { mode: 9 })["mode"]).toBe(LUMA_MATTE_MODES.alpha);
+ });
+});
+
+describe("lumaMatteCoverageRef", () => {
+ it("reads the matte's alpha, and its complement when inverted", () => {
+ const matte: Rgba = { r: 0, g: 0, b: 0, a: 0.25 };
+ expect(lumaMatteCoverageRef(matte, LUMA_MATTE_MODES.alpha)).toBe(0.25);
+ expect(lumaMatteCoverageRef(matte, LUMA_MATTE_MODES.alphaInverted)).toBe(0.75);
+ });
+
+ it("reads luma as the matte composited over black", () => {
+ // Premultiplied: a 50 % grey at 50 % opacity carries rgb 0.25, and After
+ // Effects' luma matte sees exactly that — transparent is black, not absent.
+ const half: Rgba = { r: 0.25, g: 0.25, b: 0.25, a: 0.5 };
+ expect(lumaMatteCoverageRef(half, LUMA_MATTE_MODES.luma)).toBeCloseTo(0.25, 12);
+ expect(lumaMatteCoverageRef(half, LUMA_MATTE_MODES.lumaInverted)).toBeCloseTo(0.75, 12);
+ });
+
+ it("weights the channels the way the Luminance channel selector does", () => {
+ const red: Rgba = { r: 1, g: 0, b: 0, a: 1 };
+ const green: Rgba = { r: 0, g: 1, b: 0, a: 1 };
+ const blue: Rgba = { r: 0, g: 0, b: 1, a: 1 };
+ const luma = (m: Rgba): number => lumaMatteCoverageRef(m, LUMA_MATTE_MODES.luma);
+ expect(luma(green)).toBeGreaterThan(luma(red));
+ expect(luma(red)).toBeGreaterThan(luma(blue));
+ expect(luma(red) + luma(green) + luma(blue)).toBeCloseTo(1, 12);
+ });
+});
+
+describe("lumaMatteSampleRef", () => {
+ it("is the identity under a fully opaque alpha matte", () => {
+ expect(lumaMatteSampleRef(SRC, OPAQUE_WHITE, 0, { mode: LUMA_MATTE_MODES.alpha })).toEqual(SRC);
+ });
+
+ it("empties the pixel — alpha included — where the matte does not cover", () => {
+ expect(lumaMatteSampleRef(SRC, CLEAR, 0, { mode: LUMA_MATTE_MODES.alpha })).toEqual({
+ r: 0,
+ g: 0,
+ b: 0,
+ a: 0,
+ });
+ });
+
+ it("scales every channel by one coverage, keeping the pixel premultiplied", () => {
+ const out = lumaMatteSampleRef(
+ { r: 0.5, g: 0.5, b: 0.5, a: 0.5 },
+ { r: 0, g: 0, b: 0, a: 0.5 },
+ 0,
+ { mode: LUMA_MATTE_MODES.alpha },
+ );
+ // rgb <= a before, so rgb <= a after: a scalar multiply cannot break it.
+ expect(out).toEqual({ r: 0.25, g: 0.25, b: 0.25, a: 0.25 });
+ });
+
+ it("inverts, so an opaque matte hides the layer under Alpha Inverted", () => {
+ const out = lumaMatteSampleRef(SRC, OPAQUE_WHITE, 0, {
+ mode: LUMA_MATTE_MODES.alphaInverted,
+ });
+ expect(out).toEqual({ r: 0, g: 0, b: 0, a: 0 });
+ });
+
+ it("is a pure function of its inputs", () => {
+ const at = (): Rgba => lumaMatteSampleRef(SRC, OPAQUE_WHITE, 0.37, { mode: 3 });
+ expect(at()).toEqual(at());
+ });
+});
diff --git a/packages/core/src/vfx/noise.frag.ts b/packages/core/src/vfx/noise.frag.ts
new file mode 100644
index 0000000000..b8a7981e9d
--- /dev/null
+++ b/packages/core/src/vfx/noise.frag.ts
@@ -0,0 +1,171 @@
+/**
+ * `noise` kernel — GLSL ES 3.00, capture `self`.
+ *
+ * A port of After Effects' `ADBE Noise`, decoded from `AEFX_Noise.metallib`
+ * (`docs/superpowers/specs/ae-metal-ir/AEFX_Noise.metallib.ll` in the exporter
+ * repo, helper `_Z5Noise8PixelRGBiifiiff`). The kernel is a pure integer hash of
+ * `(x, y, seed)` — no lookup table, no state between frames — so it ports
+ * exactly and stays seek-safe by construction.
+ *
+ * **What the IR says, read from the struct metadata rather than from prose.**
+ * `NoiseKernelValues` is `{ inDeviceFormat, inNoiseAmount, inUseColorNoise,
+ * inClipNoiseOutput, inRandomSeed_High, inRandomSeed_Low, inNoiseOffsetX,
+ * inNoiseOffsetY, … }`. So `ADBE Noise-0002` is **Use Color Noise**, a
+ * checkbox — not the "Noise Type (Uniform / Gaussian)" popup the deep dive
+ * guessed — and the two mystery seed floats are the halves of one 32-bit
+ * random seed. Both params are named here the way the metadata names them.
+ *
+ * Per channel:
+ *
+ * seed32 = (uint(seedHigh) << 16) | (uint(seedLow) & 0xFFFF)
+ * h = jenkinsMix(a, y, seed32) // Bob Jenkins' 1997 mix, verbatim
+ * t2 = h * 1103515245 + 12345
+ * t4 = t2 * 12996205 + 12345
+ * byte = ((t4 >> 16) & 0xFF) ^ ((t2 >> 9) & 0x7F80)
+ * noise = amount · (byte / 32704 − 0.5)
+ *
+ * with `a = x` for monochrome noise and `a = 3x + channel` (R, G, B) for colour
+ * noise — four separate hash blocks in the IR, three of them consecutive in
+ * `3x`. `32704` is the reciprocal constant `0x3F00002000000000` spelled as a
+ * fraction. The noise is ADDED to the buffer's colour and, when Clip Result
+ * Values is on, all four channels are clamped to [0, 1] — alpha is clamped but
+ * never noised.
+ *
+ * **Interim seed (plan Task 2.7, pending the Task 4.3 probe).** What the CPU
+ * puts in `inRandomSeed_High`/`inRandomSeed_Low` per frame is still unknown —
+ * it is the effect's Random Seed combined with something frame-derived, which
+ * is why the noise animates with no keyframed property. Until the probe pins
+ * it, this kernel seeds the low half with the frame index and leaves the high
+ * half at zero, so the pattern is deterministic per frame and different between
+ * frames. Switching to the decoded packing is a change to two lines here and
+ * two in the reference; nothing else depends on it, and the tests assert the
+ * byte distribution and determinism rather than After Effects parity.
+ *
+ * **Pixel space.** `x` and `y` are integer pixel coordinates with y measured
+ * from the TOP, which is how After Effects indexes the buffer — the shader's
+ * `v_uv` is y-up, so the row is flipped back here. `inNoiseOffsetX/Y` (the
+ * layer's origin inside the source buffer) are not modelled: a HyperFrames host
+ * always captures its own box, so its origin is (0, 0).
+ *
+ * **Premultiplication.** The noise is added to the captured texel as it is,
+ * which is premultiplied — the literal port, and After Effects' own buffers are
+ * premultiplied too. The consequence is worth stating: on a layer with
+ * transparency the noise lands in the transparent region as well, exactly as
+ * the effect does in After Effects.
+ *
+ * **`rgb ≤ a` is enforced regardless of `Clip Result Values`, and that is a
+ * deliberate DEPARTURE from AE, not a port of it.** A valid premultiplied
+ * colour always has `rgb ≤ a` component-wise (it is `straightRgb · a`); adding
+ * noise to `src.rgb` can push it above `src.a` on a near-transparent texel,
+ * and `clamp(out4, 0, 1)` alone does not fix that — it clamps each channel to
+ * [0, 1] independently, never rgb to a. After Effects can carry that
+ * transient state through its float pipeline because everything downstream of
+ * it is float too; every render target this runtime writes is 8-bit RGBA
+ * (`GL_ATTRS`, `makePingTarget`), and an invalid premultiplied texel read back
+ * later (e.g. straight-alpha `rgb / a` for display) reads as a blown-out
+ * bright fringe rather than the visible defect After Effects itself never
+ * produces. So the clamp to `a` runs unconditionally, on both the `Clip
+ * Result Values` on and off paths.
+ *
+ * **`Clip Result Values` off is otherwise inert here, and that is a real,
+ * currently permanent limitation, not a bug to fix in this file.** Every
+ * render target in this runtime — the visible `.hf-vfx-out` canvas AND the
+ * ping-pong intermediates a multi-node chain reads between passes — is 8-bit
+ * `UNSIGNED_BYTE` RGBA, and the GL spec clamps a float fragment output to
+ * [0, 1] on conversion to a normalized integer target regardless of what the
+ * shader computes. `u_clipping = 0` therefore cannot produce an unclamped
+ * value anywhere in this pipeline today; it would take a floating-point
+ * render target (a real infrastructure change, not a one-line fix) to give it
+ * one. Recorded rather than silently accepted: a reviewer who mutates this
+ * shader and finds `u_clipping` untestable is finding a known limitation, not
+ * a fresh bug.
+ */
+
+/**
+ * The constants the reference has to agree with, named once. `byteScale` is
+ * `0x3F00002000000000` from the IR — (1 + 2⁻⁹) · 2⁻¹⁵, i.e. 1/32704.
+ */
+export const NOISE_CONSTANTS = {
+ lcgMulA: 1103515245,
+ lcgMulB: 12996205,
+ lcgAdd: 12345,
+ highMask: 0x7f80,
+ lowMask: 0xff,
+ byteScale: 32704,
+} as const;
+
+const { lcgMulA, lcgMulB, lcgAdd, highMask, lowMask, byteScale } = NOISE_CONSTANTS;
+
+export const NOISE_FRAG = `#version 300 es
+precision highp float;
+// NOT decoration: a fragment shader's default integer precision is mediump,
+// and a mediump uint is only guaranteed 16 bits (ESSL 3.00 §4.5.2). Every step
+// below — the Jenkins mix, both LCG rounds — is defined by 32-bit wraparound,
+// so without this the hash is a different function on any implementation that
+// honours the minimum. ANGLE and SwiftShader both use 32-bit ints, which is
+// exactly why no test on this machine would catch it.
+precision highp int;
+
+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_amount;
+uniform float u_useColorNoise;
+uniform float u_clipping;
+
+// Bob Jenkins' 1997 integer mix, the six-round shift/xor/subtract sequence the
+// metallib runs verbatim. uint arithmetic wraps in GLSL ES 3.00, which is what
+// makes this bit-identical to the C original.
+uint hfJenkinsMix(uint a, uint b, uint c) {
+ a -= b; a -= c; a ^= (c >> 13u);
+ b -= c; b -= a; b ^= (a << 8u);
+ c -= a; c -= b; c ^= (b >> 13u);
+ a -= b; a -= c; a ^= (c >> 12u);
+ b -= c; b -= a; b ^= (a << 16u);
+ c -= a; c -= b; c ^= (b >> 5u);
+ a -= b; a -= c; a ^= (c >> 3u);
+ b -= c; b -= a; b ^= (a << 10u);
+ c -= a; c -= b; c ^= (b >> 15u);
+ return c;
+}
+
+// The hash's 15-bit output byte for one channel.
+float hfNoiseByte(uint a, uint y, uint seed) {
+ uint h = hfJenkinsMix(a, y, seed);
+ uint t2 = h * ${lcgMulA}u + ${lcgAdd}u;
+ uint t4 = t2 * ${lcgMulB}u + ${lcgAdd}u;
+ return float(((t4 >> 16u) & ${lowMask}u) ^ ((t2 >> 9u) & ${highMask}u));
+}
+
+void main() {
+ vec4 src = texture(u_src, v_uv);
+ vec2 px = floor(v_uv * u_size);
+ uint x = uint(max(px.x, 0.0));
+ // After Effects indexes rows from the top; v_uv is y-up.
+ uint y = uint(max(u_size.y - 1.0 - px.y, 0.0));
+ float frame = floor(u_t * u_fps + 0.5);
+ uint seed = uint(max(frame, 0.0)) & 0xFFFFu;
+
+ float amount = u_amount * 0.01;
+ vec3 nz;
+ if (u_useColorNoise > 0.5) {
+ uint a = x * 3u;
+ nz = vec3(hfNoiseByte(a, y, seed), hfNoiseByte(a + 1u, y, seed), hfNoiseByte(a + 2u, y, seed));
+ } else {
+ nz = vec3(hfNoiseByte(x, y, seed));
+ }
+ nz = amount * (nz / ${byteScale}.0 - 0.5);
+
+ vec4 out4 = vec4(src.rgb + nz, src.a);
+ // A valid premultiplied colour needs rgb <= a component-wise; noise on a
+ // near-transparent texel can push rgb above it, which our fixed 8-bit RGBA
+ // storage cannot carry safely the way AE's float pipeline can (see the doc
+ // comment above). This runs before, and independently of, u_clipping.
+ out4.rgb = min(out4.rgb, out4.a);
+ fragColor = u_clipping > 0.5 ? clamp(out4, 0.0, 1.0) : out4;
+}
+`;
diff --git a/packages/core/src/vfx/noise.test.ts b/packages/core/src/vfx/noise.test.ts
new file mode 100644
index 0000000000..b7ea26d2fd
--- /dev/null
+++ b/packages/core/src/vfx/noise.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it } from "vitest";
+import { NOISE_CONSTANTS, NOISE_FRAG } from "./noise.frag";
+import { noiseByteRef, noiseOffsetRef, noiseSeedRef } from "./refs/noise";
+import { getVfxDef, normalizeVfxParams } from "../vfx";
+
+const FPS = 30;
+const P = { x: 137, y: 61 };
+
+describe("noise def", () => {
+ it("is registered as a capturing kernel with the real fragment source", () => {
+ const def = getVfxDef("noise")!;
+ expect(def.capture).toBe("self");
+ expect(def.ae).toBe("ADBE Noise");
+ expect(def.frag).toBe(NOISE_FRAG);
+ expect(NOISE_FRAG.startsWith("#version 300 es")).toBe(true);
+ });
+
+ it("names the three params the metallib's struct names", () => {
+ // `ADBE Noise-0002` is Use Color Noise — `inUseColorNoise` in
+ // `NoiseKernelValues` — not the Uniform/Gaussian popup the deep dive
+ // guessed from the parameter list alone.
+ expect(getVfxDef("noise")!.params.map((p) => p.key)).toEqual([
+ "amount",
+ "useColorNoise",
+ "clipping",
+ ]);
+ });
+
+ it("defaults to clipped monochrome noise at zero amount", () => {
+ expect(normalizeVfxParams("noise", {})).toEqual({
+ amount: 0,
+ useColorNoise: false,
+ clipping: true,
+ });
+ });
+});
+
+describe("noiseByteRef", () => {
+ it("stays inside the 15 bits the two masks can produce", () => {
+ const max = NOISE_CONSTANTS.highMask | NOISE_CONSTANTS.lowMask;
+ for (let x = 0; x < 64; x++) {
+ const byte = noiseByteRef(x, 3, 0);
+ expect(byte).toBeGreaterThanOrEqual(0);
+ expect(byte).toBeLessThanOrEqual(max);
+ }
+ });
+
+ it("spreads roughly uniformly over its range", () => {
+ // The distribution, not After Effects parity: until the Task 4.3 seed
+ // probe lands, parity is unmeasurable, but a hash that clumps would be
+ // wrong under any seed.
+ const buckets = new Array<number>(8).fill(0);
+ let sum = 0;
+ for (let y = 0; y < 64; y++) {
+ for (let x = 0; x < 64; x++) {
+ const byte = noiseByteRef(x, y, 0);
+ sum += byte;
+ buckets[Math.min(7, Math.floor(byte / 4096))]! += 1;
+ }
+ }
+ expect(sum / 4096).toBeGreaterThan(14884);
+ expect(sum / 4096).toBeLessThan(17884);
+ for (const count of buckets) {
+ expect(count).toBeGreaterThan(392);
+ expect(count).toBeLessThan(632);
+ }
+ });
+
+ it("decorrelates neighbouring pixels and neighbouring seeds", () => {
+ expect(noiseByteRef(0, 0, 0)).not.toBe(noiseByteRef(1, 0, 0));
+ expect(noiseByteRef(0, 0, 0)).not.toBe(noiseByteRef(0, 1, 0));
+ expect(noiseByteRef(5, 7, 0)).not.toBe(noiseByteRef(5, 7, 1));
+ });
+
+ it("is a pure function of (a, y, seed)", () => {
+ expect(noiseByteRef(21, 9, 4)).toBe(noiseByteRef(21, 9, 4));
+ });
+});
+
+describe("noiseSeedRef", () => {
+ it("packs the frame index into the low half, as the interim seed", () => {
+ expect(noiseSeedRef(0, FPS)).toBe(0);
+ expect(noiseSeedRef(1, FPS)).toBe(30);
+ // Rounds to the nearest frame, the same rule `u_fps` documents.
+ expect(noiseSeedRef(1 / FPS - 0.001, FPS)).toBe(1);
+ });
+});
+
+describe("noiseOffsetRef", () => {
+ it("adds nothing at zero amount", () => {
+ expect(noiseOffsetRef(P, 0.5, FPS, { amount: 0 })).toEqual({ r: 0, g: 0, b: 0 });
+ });
+
+ it("centres the offset on zero and bounds it by half the amount", () => {
+ const amount = 100;
+ let min = Infinity;
+ let max = -Infinity;
+ for (let x = 0; x < 256; x++) {
+ const { r } = noiseOffsetRef({ x, y: 4 }, 0, FPS, { amount });
+ min = Math.min(min, r);
+ max = Math.max(max, r);
+ }
+ expect(min).toBeLessThan(-0.4);
+ expect(max).toBeGreaterThan(0.4);
+ expect(min).toBeGreaterThanOrEqual(-0.5);
+ // The byte's top value overshoots 1.0 slightly — 32767/32704 — which is
+ // After Effects' own asymmetry, not a rounding slip here.
+ expect(max).toBeLessThan(0.51);
+ });
+
+ it("scales linearly with amount", () => {
+ const one = noiseOffsetRef(P, 0, FPS, { amount: 50 }).r;
+ const two = noiseOffsetRef(P, 0, FPS, { amount: 100 }).r;
+ expect(two).toBeCloseTo(2 * one, 12);
+ });
+
+ it("is monochrome by default and per-channel with Use Color Noise", () => {
+ const mono = noiseOffsetRef(P, 0, FPS, { amount: 100 });
+ const colour = noiseOffsetRef(P, 0, FPS, { amount: 100, useColorNoise: true });
+ expect(mono.r).toBe(mono.g);
+ expect(mono.g).toBe(mono.b);
+ expect(colour.r).not.toBe(colour.g);
+ expect(colour.g).not.toBe(colour.b);
+ });
+
+ it("repeats exactly at one time and changes at the next frame", () => {
+ const at = (t: number): number => noiseOffsetRef(P, t, FPS, { amount: 100 }).r;
+ // Seek determinism: the same t is byte-identical, twice.
+ expect(at(1.25)).toBe(at(1.25));
+ // Two times inside one frame are one pattern; the next frame is another.
+ expect(at(1 / FPS)).toBe(at(1 / FPS + 0.01));
+ expect(at(1 / FPS)).not.toBe(at(2 / FPS));
+ });
+});
diff --git a/packages/core/src/vfx/refs/lumaMatte.ts b/packages/core/src/vfx/refs/lumaMatte.ts
new file mode 100644
index 0000000000..6354cb345e
--- /dev/null
+++ b/packages/core/src/vfx/refs/lumaMatte.ts
@@ -0,0 +1,46 @@
+/**
+ * CPU reference for the `luma-matte` kernel. Unlike `wave-warp`'s and
+ * `displacement-map`'s, which return the coordinate they sample, this one
+ * returns the colour: the kernel's whole decision is a per-pixel scale, and a
+ * caller with both texels can check it exactly.
+ *
+ * Both texels are **premultiplied**, matching the textures the runtime uploads.
+ */
+
+import { normalizeVfxParams, type HfVfxParamValues } from "../../vfx";
+import { DISPLACEMENT_MAP_CONSTANTS } from "../displacementMap.frag";
+import { LUMA_MATTE_MODES } from "../lumaMatte.frag";
+
+const { lumaR, lumaG, lumaB } = DISPLACEMENT_MAP_CONSTANTS;
+
+export interface Rgba {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+}
+
+/** The shader's `hfCoverage`. */
+export function lumaMatteCoverageRef(matte: Rgba, mode: number): number {
+ if (mode < LUMA_MATTE_MODES.alphaInverted) return matte.a;
+ if (mode < LUMA_MATTE_MODES.luma) return 1 - matte.a;
+ const luma = matte.r * lumaR + matte.g * lumaG + matte.b * lumaB;
+ return mode < LUMA_MATTE_MODES.lumaInverted ? luma : 1 - luma;
+}
+
+/**
+ * The colour the kernel paints. `t` is part of the call shape every kernel
+ * reference shares; a matte is time-invariant — its animation arrives as
+ * movement in the matte element itself.
+ */
+export function lumaMatteSampleRef(
+ src: Rgba,
+ matte: Rgba,
+ t: number,
+ params: HfVfxParamValues,
+): Rgba {
+ void t;
+ const n = normalizeVfxParams("luma-matte", params);
+ const coverage = Math.min(1, Math.max(0, lumaMatteCoverageRef(matte, Number(n["mode"]))));
+ return { r: src.r * coverage, g: src.g * coverage, b: src.b * coverage, a: src.a * coverage };
+}
diff --git a/packages/core/src/vfx/refs/noise.ts b/packages/core/src/vfx/refs/noise.ts
new file mode 100644
index 0000000000..05305f6a2a
--- /dev/null
+++ b/packages/core/src/vfx/refs/noise.ts
@@ -0,0 +1,77 @@
+/**
+ * CPU reference for the `noise` kernel — the same integer hash the shader
+ * runs, in 32-bit wrapping arithmetic. JavaScript's `>>> 0` and `Math.imul`
+ * reproduce C's `unsigned int` overflow exactly, which is the property the
+ * whole port rests on.
+ *
+ * Returns the noise OFFSET applied to a pixel, not the colour: the offset is
+ * the entirety of what the kernel computes, and the add-and-clip around it is
+ * two lines a caller can apply itself.
+ */
+
+import { normalizeVfxParams, type HfVfxParamValues } from "../../vfx";
+import { NOISE_CONSTANTS } from "../noise.frag";
+
+const { lcgMulA, lcgMulB, lcgAdd, highMask, lowMask, byteScale } = NOISE_CONSTANTS;
+
+/** Bob Jenkins' 1997 integer mix, the metallib's sequence verbatim. */
+function jenkinsMix(a0: number, b0: number, c0: number): number {
+ let a = a0 >>> 0;
+ let b = b0 >>> 0;
+ let c = c0 >>> 0;
+ a = (a - b - c) ^ (c >>> 13);
+ b = (b - c - a) ^ (a << 8);
+ c = (c - a - b) ^ (b >>> 13);
+ a = (a - b - c) ^ (c >>> 12);
+ b = (b - c - a) ^ (a << 16);
+ c = (c - a - b) ^ (b >>> 5);
+ a = (a - b - c) ^ (c >>> 3);
+ b = (b - c - a) ^ (a << 10);
+ c = (c - a - b) ^ (b >>> 15);
+ return c >>> 0;
+}
+
+/** The hash's 15-bit output byte for one channel index `a`. */
+export function noiseByteRef(a: number, y: number, seed: number): number {
+ const h = jenkinsMix(a, y, seed);
+ const t2 = (Math.imul(h, lcgMulA) + lcgAdd) >>> 0;
+ const t4 = (Math.imul(t2, lcgMulB) + lcgAdd) >>> 0;
+ return (((t4 >>> 16) & lowMask) ^ ((t2 >>> 9) & highMask)) >>> 0;
+}
+
+/**
+ * The 32-bit seed the kernel hashes with. Interim, pending the Task 4.3 probe:
+ * the frame index goes in the low half and the high half is zero. The packing
+ * itself is the metallib's (`inRandomSeed_High` << 16 | `inRandomSeed_Low`), so
+ * the probe's answer replaces the arguments, not the shape.
+ */
+export function noiseSeedRef(t: number, fps: number): number {
+ const frame = Math.floor(t * fps + 0.5);
+ return Math.max(frame, 0) & 0xffff;
+}
+
+/**
+ * The per-channel noise offset the kernel adds at pixel `(x, y)` — `y` counted
+ * from the TOP of the layer, as After Effects indexes its buffer.
+ */
+export function noiseOffsetRef(
+ p: { x: number; y: number },
+ t: number,
+ fps: number,
+ params: HfVfxParamValues,
+): { r: number; g: number; b: number } {
+ const n = normalizeVfxParams("noise", params);
+ const amount = Number(n["amount"]) * 0.01;
+ const seed = noiseSeedRef(t, fps);
+ const x = Math.max(Math.floor(p.x), 0);
+ const y = Math.max(Math.floor(p.y), 0);
+ const bytes = n["useColorNoise"]
+ ? [
+ noiseByteRef(x * 3, y, seed),
+ noiseByteRef(x * 3 + 1, y, seed),
+ noiseByteRef(x * 3 + 2, y, seed),
+ ]
+ : Array<number>(3).fill(noiseByteRef(x, y, seed));
+ const [r, g, b] = bytes.map((byte) => amount * (byte / byteScale - 0.5));
+ return { r: r!, g: g!, b: b! };
+}
diff --git a/packages/producer/src/services/vfxDeterminism.test.ts b/packages/producer/src/services/vfxDeterminism.test.ts
index 4cfd7cd3e2..eaa3318fec 100644
--- a/packages/producer/src/services/vfxDeterminism.test.ts
+++ b/packages/producer/src/services/vfxDeterminism.test.ts
@@ -335,6 +335,180 @@ function chainOrderFixture(chain: string): string {
</div>`;
}
+/**
+ * `backdrop` capture: two stacked (not side-by-side) colored blocks live in a
+ * `<canvas layoutsubtree class="hf-vfx-src" data-vfx-for="host">` SIBLING of
+ * the host, per interface v1.1 and `resolveCaptureSource`/`findBackdropWrapper`
+ * in `packages/core/src/runtime/vfx.ts`. `#control` renders the same two
+ * blocks as plain DOM at `PANEL.bx` so `panelPsnr` can compare the two.
+ */
+function backdropStackedFixture(chain: string): string {
+ const blocks = `
+ <div style="position:absolute;left:0;top:0;width:${PANEL.w}px;height:${PANEL.h / 2}px;background:#ff0000"></div>
+ <div style="position:absolute;left:0;top:${PANEL.h / 2}px;width:${PANEL.w}px;height:${PANEL.h / 2}px;background:#00ff00"></div>`;
+ return `<!doctype html>
+<style>
+ html, body { margin: 0; background: #0000ff; }
+ .panel { position: absolute; top: ${PANEL.y}px; width: ${PANEL.w}px; height: ${PANEL.h}px; }
+ #host { left: ${PANEL.ax}px; }
+ #host > canvas { position: absolute; inset: 0; width: ${PANEL.w}px; height: ${PANEL.h}px; }
+ #wrap { position: absolute; left: ${PANEL.ax}px; top: ${PANEL.y}px; width: ${PANEL.w}px; height: ${PANEL.h}px; }
+ .hf-vfx-in { position: absolute; left: 0; top: 0; width: ${PANEL.w}px; height: ${PANEL.h}px; }
+ #control { left: ${PANEL.bx}px; }
+</style>
+<div data-composition-id="root" data-start="0" data-duration="4"
+ data-width="${PANEL.bx + PANEL.w + PANEL.ax}" data-height="${PANEL.y + PANEL.h + PANEL.y}">
+ <canvas id="wrap" layoutsubtree class="hf-vfx-src" data-vfx-for="host"><div class="hf-vfx-in">${blocks}</div></canvas>
+ <div id="host" class="panel clip" data-start="0" data-duration="4" data-vfx-chain='${chain}'>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>
+ <div id="control" class="panel">${blocks}</div>
+</div>`;
+}
+
+/**
+ * The same two stacked blocks, but the host reading them through `backdrop`
+ * is OUTSIDE its own `data-start`/`data-duration` window at the seek time
+ * under test — the real way a host goes invisible (the clip runtime owns
+ * `visibility` for `.clip` elements and forces it back to `visible` inside
+ * the window, which is what made a plain CSS `visibility:hidden` override on
+ * an in-window host a no-op when this fixture was first written).
+ * `capturePassThrough` keeps the captured bitmap ON the wrapper canvas itself
+ * rather than clearing it, because the wrapper's children never paint on
+ * their own — it is the only thing left that can still show the layers below
+ * a switched-off adjustment layer.
+ */
+function hiddenBackdropFixture(chain: string): string {
+ return `<!doctype html>
+<style>
+ html, body { margin: 0; background: #0000ff; }
+ #wrap { position: absolute; left: 20px; top: 30px; 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; }
+ #host { position: absolute; left: 20px; top: 30px; 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="20" data-width="240" data-height="180">
+ <canvas id="wrap" layoutsubtree class="hf-vfx-src" data-vfx-for="host">
+ <div class="hf-vfx-in">
+ <div style="position:absolute;left:0;top:0;width:${HOST_W}px;height:${HOST_H / 2}px;background:#ff0000"></div>
+ <div style="position:absolute;left:0;top:${HOST_H / 2}px;width:${HOST_W}px;height:${HOST_H / 2}px;background:#00ff00"></div>
+ </div>
+ </canvas>
+ <div id="host" class="clip" data-start="10" data-duration="4" data-vfx-chain='${chain}'>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>
+</div>`;
+}
+
+/**
+ * `luma-matte`: the host's own content is an opaque white square (so the
+ * kernel's output is coverage alone), and a `matte` `ref` param names a
+ * second element — `#matte` — wrapped in its own `.hf-vfx-src` capture, per
+ * `resolveRefSource`. Four vertical strips give four coverage samples.
+ */
+function lumaMatteFixture(chain: string, matteStrips: 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; }
+ #matte { position: absolute; left: 0; top: 200px; 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; }
+</style>
+<div data-composition-id="root" data-start="0" data-duration="4" data-width="${HOST_W}" data-height="320">
+ <div id="host" class="clip" data-start="0" data-duration="4" data-vfx-chain='${chain}'>
+ <canvas layoutsubtree class="hf-vfx-src"><div class="hf-vfx-in"><div style="position:absolute;left:0;top:0;width:${HOST_W}px;height:${HOST_H}px;background:#ffffff"></div></div></canvas>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>
+ <div id="matte">
+ <canvas layoutsubtree class="hf-vfx-src"><div class="hf-vfx-in">${matteStrips}</div></canvas>
+ </div>
+</div>`;
+}
+
+/**
+ * `displacement-map` with an EXTERNAL map: the host holds the same red block
+ * as `fixture`, and `#map` — a second element with its own `.hf-vfx-src`
+ * capture — supplies `u_src2`. The map is a solid opaque BLACK panel, not a
+ * gradient: a CSS gradient's interpolation is implementation-defined, while a
+ * flat panel gives an exact texel and therefore an exact displacement.
+ */
+function displacementRefFixture(chain: string, mapVisible = false, mapW = HOST_W): string {
+ const visible = mapVisible ? " data-vfx-ref-visible" : "";
+ 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; }
+ #host .hf-vfx-in { position: absolute; left: 0; top: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ #map { position: absolute; left: 0; top: 200px; width: ${mapW}px; height: ${HOST_H}px; }
+ #map > canvas { width: ${mapW}px; height: ${HOST_H}px; }
+ #map .hf-vfx-in { position: absolute; left: 0; top: 0; width: ${mapW}px; height: ${HOST_H}px; }
+</style>
+<div data-composition-id="root" data-start="0" data-duration="4" data-width="${HOST_W}" data-height="320">
+ <div id="host" class="clip" data-start="0" data-duration="4" data-vfx-chain='${chain}'>
+ <canvas layoutsubtree class="hf-vfx-src"><div class="hf-vfx-in"><div style="position:absolute;left:0;top:0;width:${SQUARE_W}px;height:${HOST_H}px;background:#ff0000"></div></div></canvas>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>
+ <div id="map">
+ <canvas layoutsubtree class="hf-vfx-src"${visible}><div class="hf-vfx-in"><div style="position:absolute;left:0;top:0;width:${mapW}px;height:${HOST_H}px;background:#000000"></div></div></canvas>
+ </div>
+</div>`;
+}
+
+/**
+ * `luma-matte` with a VISIBLE matte whose box is twice the host's. Two claims
+ * at once: the wrapper's bitmap survives the capture (the layer still paints),
+ * and the kernel still reads it scaled into the host's box.
+ */
+function visibleMatteFixture(chain: string, matteW: number): string {
+ const strips = [0, 85 / 255, 170 / 255, 1]
+ .map(
+ (a, i) =>
+ `<div style="position:absolute;left:${(i * matteW) / 4}px;top:0;width:${matteW / 4}px;height:${HOST_H}px;background:rgba(0,0,0,${a})"></div>`,
+ )
+ .join("");
+ 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; }
+ #host .hf-vfx-in { position: absolute; left: 0; top: 0; width: ${HOST_W}px; height: ${HOST_H}px; }
+ #matte { position: absolute; left: 0; top: 200px; width: ${matteW}px; height: ${HOST_H}px; }
+ #matte > canvas { width: ${matteW}px; height: ${HOST_H}px; }
+ #matte .hf-vfx-in { position: absolute; left: 0; top: 0; width: ${matteW}px; height: ${HOST_H}px; }
+</style>
+<div data-composition-id="root" data-start="0" data-duration="4" data-width="${matteW}" data-height="320">
+ <div id="host" class="clip" data-start="0" data-duration="4" data-vfx-chain='${chain}'>
+ <canvas layoutsubtree class="hf-vfx-src"><div class="hf-vfx-in"><div style="position:absolute;left:0;top:0;width:${HOST_W}px;height:${HOST_H}px;background:#ffffff"></div></div></canvas>
+ <canvas class="hf-vfx-out"></canvas>
+ </div>
+ <div id="matte">
+ <canvas layoutsubtree class="hf-vfx-src" data-vfx-ref-visible><div class="hf-vfx-in">${strips}</div></canvas>
+ </div>
+</div>`;
+}
+
+/** Four strips of constant luma (black) with alpha 0, 1/3, 2/3, 1 — isolates the Alpha/Alpha Inverted modes from Luma. */
+function alphaMatteStrips(): string {
+ return [0, 85 / 255, 170 / 255, 1]
+ .map(
+ (a, i) =>
+ `<div style="position:absolute;left:${i * 40}px;top:0;width:40px;height:${HOST_H}px;background:rgba(0,0,0,${a})"></div>`,
+ )
+ .join("");
+}
+
+/** Four strips of constant alpha (opaque) with luma 0, 1/3, 2/3, 1 — isolates the Luma/Luma Inverted modes from Alpha. */
+function lumaMatteStrips(): string {
+ return [0, 85, 170, 255]
+ .map(
+ (g, i) =>
+ `<div style="position:absolute;left:${i * 40}px;top:0;width:40px;height:${HOST_H}px;background:rgb(${g},${g},${g})"></div>`,
+ )
+ .join("");
+}
+
interface OutSample {
width: number;
height: number;
@@ -858,4 +1032,393 @@ describe("data-vfx-chain in the browser", () => {
await page.close();
}
}, 60_000);
+
+ /**
+ * RGBA at arbitrary points of `canvas.hf-vfx-out`, via `readPixels`. Safe
+ * for content that varies only along x (a vertical readback flip cannot
+ * change what column a pixel is in) — `screenshotPixels` below is used
+ * instead wherever a fixture varies along y.
+ */
+ async function sampleOutPoints(page: Page, points: [number, number][]): Promise<number[][]> {
+ return page.evaluate((pts: [number, 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);
+ return pts.map(([x, y]) => {
+ const i = (y * out.width + x) * 4;
+ return [buf[i]!, buf[i + 1]!, buf[i + 2]!, buf[i + 3]!];
+ });
+ }, points);
+ }
+
+ /**
+ * RGBA at arbitrary points of the page's own screenshot, decoded back
+ * inside the page (same technique as `panelPsnr`). Used wherever a fixture
+ * varies along y, so the WebGL readback's vertical flip cannot bite —
+ * the browser's own compositor produced this pixel, top-down, the way the
+ * page actually looks.
+ */
+ async function screenshotPixels(page: Page, points: [number, number][]): Promise<number[][]> {
+ const shot = await page.screenshot({ encoding: "base64" });
+ return page.evaluate(
+ async (base64: string, pts: [number, number][]) => {
+ 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);
+ return pts.map(([x, y]) => Array.from(ctx.getImageData(x, y, 1, 1).data));
+ },
+ shot,
+ points,
+ );
+ }
+
+ describe("backdrop capture (Task 2.6)", () => {
+ it("composites an identity backdrop kernel back over the two stacked blocks below it", async () => {
+ const chain = chainOf("noise", { amount: 0 });
+ const page = await open(backdropStackedFixture(chain), {
+ width: PANEL.bx + PANEL.w + PANEL.ax,
+ height: PANEL.y + PANEL.h + PANEL.y,
+ });
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const [top, bottom] = await screenshotPixels(page, [
+ [PANEL.ax + 80, PANEL.y + 30],
+ [PANEL.ax + 80, PANEL.y + 90],
+ ]);
+ expect(top!.slice(0, 3)).toEqual([255, 0, 0]);
+ expect(bottom!.slice(0, 3)).toEqual([0, 255, 0]);
+
+ const { psnr } = await panelPsnr(page);
+ expect(psnr).toBeGreaterThanOrEqual(40);
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("keeps a hidden backdrop host's captured layers on the wrapper canvas's own bitmap", async () => {
+ const page = await open(hiddenBackdropFixture(chainOf("noise", { amount: 0 })), {
+ width: 240,
+ height: 180,
+ });
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const pixels = await page.evaluate(() => {
+ const wrap = document.querySelector("canvas.hf-vfx-src") as HTMLCanvasElement;
+ const ctx = wrap.getContext("2d")!;
+ return {
+ top: Array.from(ctx.getImageData(40, 10, 1, 1).data),
+ bottom: Array.from(ctx.getImageData(40, 90, 1, 1).data),
+ };
+ });
+ expect(pixels.top).toEqual([255, 0, 0, 255]);
+ expect(pixels.bottom).toEqual([0, 255, 0, 255]);
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+ });
+
+ describe("luma-matte (Task 2.7)", () => {
+ const points: [number, number][] = [
+ [20, 60],
+ [60, 60],
+ [100, 60],
+ [140, 60],
+ ];
+ const ALPHA_TOLERANCE = 4;
+
+ it.each([
+ [1, [0, 85, 170, 255]],
+ [2, [255, 170, 85, 0]],
+ ] as const)(
+ "mode %i (Alpha/Alpha Inverted) follows the matte's alpha",
+ async (mode, expected) => {
+ const chain = chainOf("luma-matte", { matte: "matte", mode });
+ const page = await open(lumaMatteFixture(chain, alphaMatteStrips()), {
+ width: HOST_W,
+ height: 320,
+ });
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const samples = await sampleOutPoints(page, points);
+ samples.forEach((px, i) => {
+ expect(Math.abs(px[3]! - expected[i]!)).toBeLessThanOrEqual(ALPHA_TOLERANCE);
+ });
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ },
+ 60_000,
+ );
+
+ it.each([
+ [3, [0, 85, 170, 255]],
+ [4, [255, 170, 85, 0]],
+ ] as const)(
+ "mode %i (Luma/Luma Inverted) follows the matte's luma",
+ async (mode, expected) => {
+ const chain = chainOf("luma-matte", { matte: "matte", mode });
+ const page = await open(lumaMatteFixture(chain, lumaMatteStrips()), {
+ width: HOST_W,
+ height: 320,
+ });
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const samples = await sampleOutPoints(page, points);
+ samples.forEach((px, i) => {
+ expect(Math.abs(px[3]! - expected[i]!)).toBeLessThanOrEqual(ALPHA_TOLERANCE);
+ });
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ },
+ 60_000,
+ );
+ });
+
+ describe("noise (Task 2.7)", () => {
+ it("leaves the source untouched when amount is 0", async () => {
+ const page = await open(fixture(chainOf("noise", { amount: 0 })));
+ 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(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("paints byte-identical output for the same seek time (determinism)", async () => {
+ const page = await open(fixture(chainOf("noise", { amount: 50 })));
+ try {
+ expect(await seekAndResolve(page, 1.25)).toBe(true);
+ const first = await page.evaluate(() =>
+ (document.querySelector("canvas.hf-vfx-out") as HTMLCanvasElement).toDataURL(),
+ );
+
+ // Seek away, then back to the same time — no state may carry between paints.
+ expect(await seekAndResolve(page, 0.5)).toBe(true);
+ expect(await seekAndResolve(page, 1.25)).toBe(true);
+ 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("changes the pattern when the seek time — its only seed — changes", async () => {
+ const page = await open(fixture(chainOf("noise", { amount: 50 })));
+ try {
+ expect(await seekAndResolve(page, 1.25)).toBe(true);
+ const a = await page.evaluate(() =>
+ (document.querySelector("canvas.hf-vfx-out") as HTMLCanvasElement).toDataURL(),
+ );
+ expect(await seekAndResolve(page, 2.0)).toBe(true);
+ const b = await page.evaluate(() =>
+ (document.querySelector("canvas.hf-vfx-out") as HTMLCanvasElement).toDataURL(),
+ );
+ expect(b).not.toBe(a);
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("matches refs/noise.ts's hash byte-for-byte at several pixels", async () => {
+ // The three checks above (identity at amount 0, same-time determinism,
+ // different-time difference) hold for almost any hash function — none
+ // of them can tell a correct Jenkins-mix port from a subtly wrong one
+ // (see PR #4330's review). This pins actual measured bytes against
+ // refs/noise.ts, the same CPU reference fractal-noise's pixel test
+ // above compares against.
+ //
+ // Known, checked limitation: the seed is `floor(t * fps + 0.5)`, and
+ // this fixture's reachable t is bounded by data-duration="4" at this
+ // composition's ~30 fps, so the seed here is 0 — small enough that a
+ // mutation to `hfJenkinsMix`'s FIRST line (`a ^= (c >> 13u)`, which
+ // touches only the raw incoming seed, before anything has mixed it into
+ // a wrapped, effectively-random register) would not move any pixel
+ // this test reads: `seed >> 13` and `seed >> 14` are both 0 for any
+ // seed under 2^13, which every reachable (x, y, seed) in this fixture
+ // is. Confirmed by brute force over the full reachable input space
+ // (x<80, y<120, seed<=120): the review's own 13->14 mutation changes
+ // ZERO of the 1,161,600 possible outputs there. Every OTHER line of the
+ // mix — all 8 of them — differs on the very first input tried under
+ // the same one-bit-shift mutation, so this test is a real hash-pinning
+ // guard for 8 of the mix's 9 steps, not a restatement of the three
+ // invariant checks above.
+ const AMOUNT = 100;
+ const page = await open(fixture(chainOf("noise", { amount: AMOUNT })));
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const buf = await readNoiseBuffer(page);
+ // [x, readback row (bottom-origin, as gl.readPixels indexes), R byte].
+ // Computed offline from noiseOffsetRef with the SAME flip the shader
+ // applies (its own y is top-origin, After Effects' convention; a
+ // readback row is bottom-origin/y-up, so topY = HOST_H - 1 - row) —
+ // see the flip line in noise.frag.ts and the doc comment on
+ // refs/noise.ts's noiseOffsetRef. Verified against a live measurement
+ // (not just derived): swapping the flip direction reproduces a
+ // DIFFERENT, also-internally-consistent set of values, so getting it
+ // backwards silently passes against the wrong ground truth — this
+ // set was checked against the actual runtime output, not only
+ // against its own formula. All points sit inside the opaque red
+ // square (x < 80) and well clear of the 0/255 clip bounds, so 8-bit
+ // rounding cannot mask a wrong hash.
+ const points: [x: number, row: number, expectedR: number][] = [
+ [4, 10, 160],
+ [5, 10, 192],
+ [6, 10, 135],
+ [0, 60, 162],
+ [2, 60, 145],
+ [4, 60, 200],
+ [0, 90, 142],
+ [1, 90, 201],
+ [3, 90, 182],
+ ];
+ for (const [x, row, expectedR] of points) {
+ const i = (row * buf.width + x) * 4;
+ // ±1 for GPU-vs-JS float rounding at the 8-bit conversion, not for
+ // hash tolerance: a mutated shift on any of the 8 reachable steps
+ // moves these by tens of levels, verified by brute force above.
+ expect(Math.abs(buf.data[i]! - expectedR)).toBeLessThanOrEqual(1);
+ }
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+ });
+
+ /**
+ * The `map` ref (plan Backlog, "one-line def change after Task 2.6"). The
+ * discriminator is that a SELF map gives a visibly different picture: a
+ * black external map displaces every pixel by the same −maxH, translating
+ * the block right as one run, while the layer's own pixels displace the red
+ * half one way and the transparent half the other, splitting it in two.
+ */
+ describe("displacement-map with an external map (Task 2.6 backlog)", () => {
+ const MAX_H = 20;
+ const mapParams = { useH: 1, maxH: MAX_H, useV: 11, maxV: 0, behavior: 1, edge: 0 };
+ const BLACK = { r: 0, g: 0, b: 0, a: 1 };
+
+ it("reads a named map element as u_src2", async () => {
+ const chain = chainOf("displacement-map", { ...mapParams, map: "map" });
+ const page = await open(displacementRefFixture(chain), { width: HOST_W, height: 320 });
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ // Through the CPU reference, with the constant sampler the fixture
+ // paints: an opaque black map reads 0 on Red, so d = (0 − 0.5)·2·maxH.
+ const probe = { x: 40, y: 60 };
+ const shift = probe.x - displacementMapSampleRef(probe, 0, mapParams, () => BLACK).x;
+ expect(shift).toBe(MAX_H);
+
+ const s = await sample(page, [60]);
+ expect(s.rows).toEqual([[[shift, SQUARE_W + shift]]]);
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("displaces by the layer's own pixels when no map is named", async () => {
+ const chain = chainOf("displacement-map", mapParams);
+ const page = await open(displacementRefFixture(chain), { width: HOST_W, height: 320 });
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const s = await sample(page, [60]);
+ // Two runs, not one: the self-referential form is a different picture,
+ // which is what makes the case above a real check of the binding.
+ expect(s.rows[0]!.length).toBe(2);
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+ });
+
+ /**
+ * A ref source that also paints (retro-wave `Logo Anim` layer 5 is layer 4's
+ * displacement map AND an enabled, opaque layer). Both halves of the rule in
+ * one page: the wrapper keeps its bitmap, and the kernel still reads it
+ * scaled into the host's box even though the two boxes differ.
+ */
+ describe("a visible ref source (data-vfx-ref-visible)", () => {
+ const MATTE_W = HOST_W * 2;
+
+ it("keeps the matte on screen and still mattes the host with it", async () => {
+ const chain = chainOf("luma-matte", { matte: "matte", mode: 1 });
+ const page = await open(visibleMatteFixture(chain, MATTE_W), {
+ width: MATTE_W,
+ height: 320,
+ });
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+
+ // 1. The wrapper's own bitmap still holds the strips — an invisible
+ // ref would have been cleared to nothing after its upload.
+ const bitmap = await page.evaluate((w: number) => {
+ const canvas = document.querySelector("#matte canvas.hf-vfx-src") as HTMLCanvasElement;
+ const ctx = canvas.getContext("2d")!;
+ const at = (x: number): number => ctx.getImageData(x, 60, 1, 1).data[3]!;
+ return { width: canvas.width, alphas: [at(w / 8), at((w * 7) / 8)] };
+ }, MATTE_W);
+ expect(bitmap.width).toBe(MATTE_W);
+ expect(bitmap.alphas[0]).toBe(0);
+ expect(bitmap.alphas[1]).toBe(255);
+
+ // 2. And the kernel read it across the host's box, not 1:1 — the four
+ // strips of a 320px matte land as four 40px bands in a 160px host.
+ const samples = await sampleOutPoints(page, [
+ [20, 60],
+ [60, 60],
+ [100, 60],
+ [140, 60],
+ ]);
+ [0, 85, 170, 255].forEach((expected, i) => {
+ expect(Math.abs(samples[i]![3]! - expected)).toBeLessThanOrEqual(4);
+ });
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+
+ it("clears an ordinary ref's bitmap, so an invisible matte stays invisible", async () => {
+ const chain = chainOf("luma-matte", { matte: "matte", mode: 1 });
+ const page = await open(lumaMatteFixture(chain, alphaMatteStrips()), {
+ width: HOST_W,
+ height: 320,
+ });
+ try {
+ expect(await seekAndResolve(page, 0)).toBe(true);
+ const alphas = await page.evaluate(() => {
+ const canvas = document.querySelector("#matte canvas.hf-vfx-src") as HTMLCanvasElement;
+ const ctx = canvas.getContext("2d")!;
+ return [40, 140].map((x) => ctx.getImageData(x, 60, 1, 1).data[3]!);
+ });
+ expect(alphas).toEqual([0, 0]);
+ expect(pageErrors.get(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+ });
});