Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
R3F19: a plain three.js program drawn by raea: <Three program={fn}> runs a single-file demo's script as a function, its renderers raea's stand-ins (src/input/vanilla.ts for "three", vanilla-webgpu.ts for "three/webgpu": three re-exported, its renderer replaced by one that records a render to the screen and its animation loop into the program running it). Its setAnimationLoop and requestAnimationFrame step once a frame at i*1000/fps ms with performance.now() at that time and Math.random seeded, so a frame is the same played to or rendered alone; a frame before the last runs it again from the start, an async one (await renderer.init()) holds the frame until it's ready. The scene it last rendered is converted as <R3F>'s is; a full-screen pass to the screen (three's EffectComposer) is drawn as the scene it rendered. The stand-in renderer and the seeded random move out of session.ts (renderer.ts, seed.ts) so a composition's three needs nothing of React Three Fiber's. test/program.test.ts 7/7; test/parity programs.ts in-vanilla (native.tsx, the Chrome page) SSIM 0.9921
shinyobjectz415391a9e1d4
diff --git a/sdk/r3f/src/index.ts b/sdk/r3f/src/index.tsindex e781390a..2e17a38b 100644--- a/sdk/r3f/src/index.ts+++ b/sdk/r3f/src/index.ts@@ -1,7 +1,9 @@// raea/r3f: React Three Fiber both ways (docs/r3f.feature). <R3F> draws an R3F scene with raea (R3F as raea's input);// <Raea> draws a raea composition's 3D inside an R3F <Canvas>, and Scene3d (the three.js host) draws raea's parts for-// any three.js app (raea as R3F's input). loadShapes brings in raea's solids (minus, hull, extrude, Text3D) for both.+// any three.js app (raea as R3F's input). <Three program> draws a plain three.js program, its renderer raea's stand-in.+// loadShapes brings in raea's solids (minus, hull, extrude, Text3D) for both.export { R3F, type R3FProps } from "./input/R3F";+export { Three, type ThreeProps } from "./input/Three";export { convert, type Converted } from "./input/scene";export { Raea, type RaeaProps } from "./output/Raea";export { Scene3d, type Settings } from "./three/scene";diff --git a/sdk/r3f/src/input/Three.tsx b/sdk/r3f/src/input/Three.tsxnew file mode 100644index 00000000..1f2727b0--- /dev/null+++ b/sdk/r3f/src/input/Three.tsx@@ -0,0 +1,73 @@+// <Three program={fn}>: a plain three.js program drawn by raea (docs/r3f.feature R3F19). `fn` is a single-file demo's+// script as a function: it makes its renderer (`new THREE.WebGLRenderer({ canvas })`, three/webgpu's WebGPURenderer, or+// its own domElement appended to document.body), its scene and camera, and renders from setAnimationLoop or+// requestAnimationFrame. raea's bundler gives it a renderer that draws nothing and records what it renders+// (program.ts); each frame that scene becomes raea's parts as <R3F>'s does (scene.ts), drawn by raea's engine. Its loop+// steps 1/fps a frame from the composition's frame, never the wall clock, and a frame before the last runs the program+// again from the start, so a render equals its play. It needs three alone: no React Three Fiber.+import { useEffect, useId, useMemo } from "react";+import { AbsoluteFill, useCurrentFrame, useVideoConfig } from "raea";+import type * as THREE from "three";+import { useHold, useWake } from "./hold";+import { drawnOf, endRun, programCanvas, startRun, stepRun, type Program, type Run } from "./program";+import { convert } from "./scene";+import { standInImages } from "./texture";+import { standInPMREM } from "./pmrem";+import { elementsOf } from "../parts";++standInImages();+standInPMREM();++export interface ThreeProps {+ /** the program: given the canvas to draw on, it may return a function that undoes it (or a promise: an async program+ * is waited for, the frame held, then stepped from frame 0) */+ program: Program;+ /** a name of its own when one composition has more than one program that come and go */+ name?: string;+}++const runs = new Map<string, Run>();++function end(key: string) {+ const r = runs.get(key);+ if (!r) return;+ runs.delete(key);+ endRun(r);+}++/** a plain three.js program, drawn by raea */+export function Three({ program, name }: ThreeProps) {+ const frame = useCurrentFrame();+ const { fps, width, height } = useVideoConfig();+ useWake();+ const id = useId();+ const key = name ?? id;+ const canvas = useMemo(() => programCanvas(width, height), [width, height]);+ let run = runs.get(key);+ // another program, another canvas, or a frame before the last (a seek back): from the start+ if (run && (run.source !== String(program) || run.canvas !== canvas || (!run.waiting && frame < run.frame))) {+ end(key);+ run = undefined;+ }+ if (!run) runs.set(key, (run = startRun(key, program, canvas)));+ useHold(run.waiting);+ useEffect(() => () => end(key), [key]);+ // what it threw is the composition's: the render is refused, naming it (as <R3F>'s is, #131)+ if (run.failed) {+ const { error } = run.failed;+ end(key);+ throw error;+ }+ if (run.waiting) return null;+ try {+ stepRun(run, frame, fps);+ } catch (e) {+ end(key);+ throw e;+ }+ const d = drawnOf(run);+ if (!d) return null;+ const out = convert(d.scene as THREE.Scene, d.camera, d.gl, height, run.now / 1000, 1 / fps);+ const drawn = elementsOf(out.parts, "three.");+ return out.background ? <AbsoluteFill style={{ background: out.background }}>{drawn}</AbsoluteFill> : <>{drawn}</>;+}diff --git a/sdk/r3f/src/input/hold.tsx b/sdk/r3f/src/input/hold.tsxindex 1ef82af3..5e9ccaca 100644--- a/sdk/r3f/src/input/hold.tsx+++ b/sdk/r3f/src/input/hold.tsx@@ -11,17 +11,33 @@ interface Hold {const HOLD = ((globalThis as { __raeaHold?: Hold }).__raeaHold ??= { n: 0, wake: new Set() });+/** a hold opened on raea's frame, and its release (once: the last one wakes the frame) */+function open(): () => void {+ HOLD.n++;+ let done = false;+ return () => {+ if (done) return;+ done = true;+ HOLD.n = Math.max(0, HOLD.n - 1);+ if (HOLD.n === 0) for (const w of [...HOLD.wake]) w();+ };+}+function Waiting() {- useLayoutEffect(() => {- HOLD.n++;- return () => {- HOLD.n = Math.max(0, HOLD.n - 1);- if (HOLD.n === 0) for (const w of [...HOLD.wake]) w();- };- }, []);+ useLayoutEffect(() => open(), []);return null;}+/** raea's frame held until `p` settles (no promise, no hold), then woken: an async three.js program (<Three>) */+export function useHold(p: Promise<unknown> | undefined) {+ useLayoutEffect(() => {+ if (!p) return;+ const release = open();+ void p.then(release, release);+ return release;+ }, [p]);+}+/** `children` under a Suspense that holds raea's frame while any of it suspends */export function Held({ children }: { children?: ReactNode }) {return <Suspense fallback={<Waiting />}>{children}</Suspense>;diff --git a/sdk/r3f/src/input/program.ts b/sdk/r3f/src/input/program.tsnew file mode 100644index 00000000..ff6965be--- /dev/null+++ b/sdk/r3f/src/input/program.ts@@ -0,0 +1,242 @@+// A plain three.js program drawn by raea (docs/r3f.feature R3F19): the function a single-file demo's script is, run by+// <Three program={fn}> (Three.tsx) with three's renderers swapped by raea's bundler for stand-ins (the composition's own+// `import "three"` and `"three/webgpu"` are vanilla.ts and vanilla-webgpu.ts, three with its renderer replaced): they+// draw nothing and record what they're asked to render. Each frame the scene last rendered to the screen is drawn by+// raea's engine as <R3F>'s is (scene.ts). The program's animation loop (setAnimationLoop, requestAnimationFrame) runs+// once a frame at that frame's time, i * 1000 / fps ms, with performance.now() reading the same time and Math.random+// seeded, so frame f is the same played to or rendered alone (raea's first rule); going backwards runs the program+// again from the start.+import * as THREE from "three";+import { standInRenderer, warnOnce } from "./renderer";+import { nextRandom, seedOf } from "./seed";++type Rec = Record<string | symbol, any>;+type Loop = (time: number) => void;++/** a plain three.js page's script as a function, given the canvas to draw on (or it makes its own) */+export type Program = (canvas: HTMLCanvasElement) => unknown;++/** what a renderer was asked to render: the scene, its camera, and the renderer (its tone mapping, its shadows) */+export interface Drawn {+ scene: THREE.Object3D;+ camera: THREE.Camera;+ gl: THREE.WebGLRenderer;+}++export interface Run {+ /** the program's text: a program written inline is the same one each render */+ source: string;+ /** the last frame stepped (-1: none yet) */+ frame: number;+ /** its Math.random's state */+ rand: number;+ /** the time the step being run reads, ms */+ now: number;+ /** its renderers' animation loops */+ loops: Map<object, Loop>;+ /** the frame callbacks it asked for, run at the next step */+ rafs: Map<number, FrameRequestCallback>;+ raf: number;+ /** the last render to the screen, and the last render of a Scene (into anything) */+ drawn: Drawn | null;+ scene: Drawn | null;+ canvas: HTMLCanvasElement;+ /** what the program returned to undo itself, run when it ends */+ stop?: () => void;+ /** an async program's promise, until it settles; then it steps from frame 0 */+ waiting?: Promise<unknown>;+ failed?: { error: unknown };+ /** how many times its globals are in place (a step, the program running, an async program's first moments) */+ depth: number;+}++// ---- the globals a program reads, its own while it runs ----++const live: Run[] = [];+let saved: { raf: unknown; caf: unknown; random: () => number; now: unknown; own: boolean } | null = null;+const top = () => live[live.length - 1];++function enter(run: Run) {+ if (run.depth++ > 0) return;+ live.push(run);+ if (live.length > 1) return;+ const g = globalThis as Rec;+ const perf = g.performance as Rec | undefined;+ saved = { raf: g.requestAnimationFrame, caf: g.cancelAnimationFrame, random: Math.random, now: perf?.now, own: !!perf && Object.prototype.hasOwnProperty.call(perf, "now") };+ g.requestAnimationFrame = (cb: FrameRequestCallback) => {+ const r = top();+ r.rafs.set(++r.raf, cb);+ return r.raf;+ };+ g.cancelAnimationFrame = (id: number) => void top()?.rafs.delete(id);+ Math.random = () => nextRandom(top());+ try {+ if (perf) Object.defineProperty(perf, "now", { value: () => top().now, configurable: true, writable: true });+ } catch {+ // a performance whose now can't be replaced: three's Clock reads the wall clock+ }+}++function leave(run: Run) {+ if (run.depth === 0 || --run.depth > 0) return;+ live.splice(live.indexOf(run), 1);+ if (live.length || !saved) return;+ const g = globalThis as Rec;+ const perf = g.performance as Rec | undefined;+ g.requestAnimationFrame = saved.raf;+ g.cancelAnimationFrame = saved.caf;+ Math.random = saved.random;+ try {+ if (perf && saved.own) perf.now = saved.now;+ else if (perf) delete perf.now;+ } catch {+ // as entered+ }+ saved = null;+}++function within<T>(run: Run, fn: () => T): T {+ enter(run);+ try {+ return fn();+ } finally {+ leave(run);+ }+}++// ---- the stand-ins ----++/** What a program draws on: a raea element where the composition has a DOM, so `document.body.appendChild+ * (renderer.domElement)` takes it (createElement("canvas") is a 2D OffscreenCanvas here, which isn't a node), with+ * what three and its controls ask of a canvas; a plain stand-in where there's no DOM. */+export function programCanvas(width: number, height: number): HTMLCanvasElement {+ const noop = () => {};+ const doc = (globalThis as Rec).document as Rec | undefined;+ let el: Rec | undefined;+ try {+ el = doc?.createElement?.("div");+ } catch {+ el = undefined;+ }+ el ??= { style: {} };+ const asks: Rec = {+ width, height, addEventListener: noop, removeEventListener: noop, dispatchEvent: () => true, setPointerCapture: noop, releasePointerCapture: noop,+ hasPointerCapture: () => false, focus: noop, getContext: () => null, getRootNode: () => doc ?? el, ownerDocument: doc ?? null,+ getBoundingClientRect: () => ({ left: 0, top: 0, width, height, x: 0, y: 0, right: width, bottom: height }),+ };+ for (const [k, v] of Object.entries(asks)) {+ if (k in el) continue;+ try {+ Object.defineProperty(el, k, { value: v, writable: true, configurable: true });+ } catch {+ // a sealed element: what it has+ }+ }+ return el as unknown as HTMLCanvasElement;+}++/** The renderer a program's `new THREE.WebGLRenderer()` (or WebGPURenderer) makes: R3F's stand-in (session.ts: what's+ * set on it is read back, a render into a target is done where raea can), which records a render to the screen and+ * its animation loop into the program running it. */+export function standIn(params: { canvas?: unknown } | undefined, webgpu: boolean): THREE.WebGLRenderer {+ const run = live.length ? top() : null;+ const kind = webgpu ? "WebGPURenderer" : "WebGLRenderer";+ if (!run) warnOnce(`new ${kind}()`, "outside <Three program>: raea draws a plain three.js program from inside <Three program={fn}>, its script a function it can run from the start; this one draws nothing");+ const base = standInRenderer() as unknown as Rec;+ let self: Rec = {};+ const render = (scene: THREE.Object3D, camera: THREE.Camera) => {+ if (!run || !scene || !camera) return;+ const d = { scene, camera, gl: self as unknown as THREE.WebGLRenderer };+ if ((scene as Rec).isScene) run.scene = d;+ if (base.getRenderTarget()) return base.render(scene, camera);+ run.drawn = d;+ };+ const own: Rec = {+ domElement: params?.canvas ?? run?.canvas ?? programCanvas(300, 150),+ render,+ setAnimationLoop: (cb: Loop | null) => void (run && (cb ? run.loops.set(self, cb) : run.loops.delete(self))),+ dispose: () => void run?.loops.delete(self),+ };+ // three/webgpu's: ready at once (`await renderer.init()`), its async calls the sync ones+ if (webgpu) Object.assign(own, { isWebGPURenderer: true, init: async () => self, hasInitialized: () => true, renderAsync: async (s: THREE.Object3D, c: THREE.Camera) => render(s, c), hasFeature: () => false, hasFeatureAsync: async () => false });+ self = new Proxy(own, {+ get: (t, k) => (k in t ? t[k] : base[k]),+ set: (t, k, v) => {+ if (k in t) t[k] = v;+ else base[k] = v;+ return true;+ },+ has: (t, k) => k in t || k in base,+ });+ return self as unknown as THREE.WebGLRenderer;+}++// ---- a run ----++/** `program` run for the <Three> keyed `key`, on `canvas`: what it made recorded, no frame stepped yet */+export function startRun(key: string, program: Program, canvas: HTMLCanvasElement): Run {+ const run: Run = { source: String(program), frame: -1, rand: seedOf(key), now: 0, loops: new Map(), rafs: new Map(), raf: 0, drawn: null, scene: null, canvas, depth: 0 };+ enter(run);+ let out: unknown;+ try {+ out = program(canvas);+ } catch (e) {+ leave(run);+ throw e;+ }+ if (typeof out === "function") run.stop = out as () => void;+ if (!out || typeof (out as Promise<unknown>).then !== "function") {+ leave(run);+ return run;+ }+ // an async program (`await renderer.init()`, then its scene): its globals stay its own until it settles or the+ // moment ends, whichever is first (what it does after a real load reads the page's), and it steps once settled+ const end = () => leave(run);+ setTimeout(end, 0);+ run.waiting = (out as Promise<unknown>)+ .then(+ (r) => void (typeof r === "function" && (run.stop = r as () => void)),+ (error) => void (run.failed = { error }),+ )+ .finally(() => {+ end();+ run.waiting = undefined;+ run.frame = -1;+ });+ return run;+}++/** `run` stepped to frame `frame` (fps a second): each step runs its animation loops and the frame callbacks it asked+ * for, at that step's time */+export function stepRun(run: Run, frame: number, fps: number) {+ for (let i = run.frame + 1; i <= frame; i++) {+ run.now = (i * 1000) / (fps > 0 ? fps : 30);+ within(run, () => {+ const due = [...run.rafs.values()];+ run.rafs.clear();+ for (const cb of [...run.loops.values()]) cb(run.now);+ for (const cb of due) cb(run.now);+ });+ run.frame = i;+ }+}++/** `run` ended: what it returned to undo itself run, its loops dropped */+export function endRun(run: Run) {+ const stop = run.stop;+ run.stop = undefined;+ run.loops.clear();+ run.rafs.clear();+ if (stop) within(run, stop);+}++/** what `run` shows: its last render to the screen. A full-screen pass there (three's EffectComposer, a+ * FullScreenQuad: a mesh rendered alone) is drawn as the scene it rendered last, without the pass */+export function drawnOf(run: Run): Drawn | null {+ const d = run.drawn;+ if (d && !(d.scene as Rec).isScene && run.scene) {+ warnOnce("a full-screen pass", "renders to the screen (three's EffectComposer, a FullScreenQuad): raea draws the scene it rendered last, without the pass");+ return run.scene;+ }+ return d ?? run.scene;+}diff --git a/sdk/r3f/src/input/renderer.ts b/sdk/r3f/src/input/renderer.tsnew file mode 100644index 00000000..c3ea35a1--- /dev/null+++ b/sdk/r3f/src/input/renderer.ts@@ -0,0 +1,74 @@+// The renderer React Three Fiber configures and a plain three.js program makes (session.ts, program.ts), which never+// draws: raea does. What's set on it (shadows, tone mapping, clear colour) is read back as the scene is converted.+// Its own module, so a composition's `import "three"` (vanilla.ts) needs nothing of React Three Fiber's.+import * as THREE from "three";+import { renderInto } from "./targets";++const warned = new Set<string>();+export function warnOnce(k: string, why: string) {+ if (warned.has(k)) return;+ warned.add(k);+ console.warn(`raea/r3f: ${k} ${why}`);+}++/** the renderer R3F configures and never draws with: what it sets on it (shadows, tone mapping) is read back */+export function standInRenderer(): THREE.WebGLRenderer {+ const noop = () => {};+ const size = { width: 1, height: 1 };+ // a WebGL context that answers what a composer asks as it is made (@react-three/postprocessing, three's own), and+ // takes every other call as it renders (its depth blit: bindFramebuffer, blitFramebuffer) doing nothing, its+ // constants (READ_FRAMEBUFFER, DEPTH_BUFFER_BIT) 0: raea draws the effect (post.ts)+ const gl = {+ getContextAttributes: () => ({ alpha: true, depth: true, stencil: false, antialias: false, premultipliedAlpha: true }),+ getExtension: () => null, getParameter: () => 0, getSupportedExtensions: () => [], isContextLost: () => false,+ } as Record<string | symbol, unknown>;+ const context = new Proxy(gl, { get: (t, k) => (k in t ? t[k] : typeof k !== "string" || k === "then" ? undefined : /^[A-Z0-9_]+$/.test(k) ? 0 : /^[a-z]/.test(k) ? noop : undefined) });+ // a pass an app draws into a render target itself (drei's <ContactShadows>) is done on the CPU (targets.ts)+ let target: THREE.RenderTarget | null = null;+ const clear: [number, number, number, number] = [0, 0, 0, 0];+ // WebGLRenderer's GL state, which a pass an app draws itself sets as it goes (drei's <MeshReflectorMaterial>:+ // state.buffers.depth.setMask): every call does nothing, every flag reads as off (docs/r3f.feature R3F16)+ const inert = (): unknown => new Proxy(noop, { get: (_, k) => (k === "then" || typeof k !== "string" ? undefined : inert()), apply: () => undefined });+ const state = { buffers: { color: inert(), depth: inert(), stencil: inert() }, enable: noop, disable: noop, reset: noop, bindTexture: noop, unbindTexture: noop, activeTexture: noop, setBlending: noop, setFlipSided: noop, setCullFace: noop, viewport: noop, scissor: noop, setScissorTest: noop, useProgram: () => false, bindFramebuffer: () => false, drawBuffers: noop, setPolygonOffset: noop, setLineWidth: noop, setMaterial: noop };+ // what an app dispatched with gl.compute this frame (TSL's compute nodes), in order: raea runs them as <Compute>s+ // once they can be (R3F22); until then each is named once and the scene drawn without it+ const dispatched: unknown[] = [];+ const compute = (node: unknown) => {+ dispatched.push(node);+ if (dispatched.length > 4096) dispatched.splice(0, dispatched.length - 4096);+ warnOnce("gl.compute", "dispatches a compute raea doesn't run yet: the scene is drawn without what it computes");+ };+ const own = {+ compute,+ computeAsync: async (node: unknown) => compute(node),+ __raea: { computes: dispatched },+ // three's WebGL clip space (a CubeCamera asks, drei's <Environment> with children): raea draws in Bevy's anyway+ coordinateSystem: THREE.WebGLCoordinateSystem,+ state,+ extensions: { has: () => false, get: () => null, init: noop },+ render: (scene: THREE.Object3D, camera: THREE.Camera) => {+ if (target) renderInto(target, scene, camera, clear);+ },+ setRenderTarget: (t: THREE.RenderTarget | null) => void (target = t),+ getRenderTarget: () => target,+ setClearColor: (c: THREE.ColorRepresentation, a?: number) => {+ const col = new THREE.Color(c);+ clear[0] = col.r, clear[1] = col.g, clear[2] = col.b;+ if (a !== undefined) clear[3] = a;+ },+ setClearAlpha: (a: number) => void (clear[3] = a),+ getClearAlpha: () => clear[3], setSize: (w: number, h: number) => void Object.assign(size, { width: w, height: h }), setPixelRatio: noop, getPixelRatio: () => 1,+ getSize: (v: THREE.Vector2) => v.set(size.width, size.height), getDrawingBufferSize: (v: THREE.Vector2) => v.set(size.width, size.height),+ getContext: () => context, getClearColor: (c: THREE.Color) => c.setRGB(clear[0], clear[1], clear[2]),+ dispose: noop, compile: noop, autoClear: true, autoClearColor: true, autoClearDepth: true, autoClearStencil: true,+ domElement: { style: {}, addEventListener: noop, removeEventListener: noop },+ xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },+ shadowMap: { enabled: false, type: THREE.PCFShadowMap },+ outputColorSpace: THREE.SRGBColorSpace, toneMapping: THREE.NoToneMapping, toneMappingExposure: 1,+ capabilities: { isWebGL2: true, maxTextureSize: 16384, maxSamples: 4, logarithmicDepthBuffer: false }, info: { autoReset: true, reset: noop, render: { calls: 0, triangles: 0, points: 0, lines: 0, frame: 0 }, memory: { geometries: 0, textures: 0 }, programs: [] }, properties: { get: () => ({}) },+ } as Record<string | symbol, unknown>;+ // any other of WebGLRenderer's methods (setRenderTarget, clear, readRenderTargetPixels ...) does nothing: raea draws+ // (verbs only: a catch-all would answer `then`, and the renderer would read as a promise)+ const verb = /^(set|get|clear|read|copy|init|reset|render|dispose|compile|update|bind)[A-Z]?/;+ return new Proxy(own, { get: (t, k) => (k in t ? t[k] : typeof k === "string" && verb.test(k) ? noop : undefined) }) as unknown as THREE.WebGLRenderer;+}diff --git a/sdk/r3f/src/input/seed.ts b/sdk/r3f/src/input/seed.tsnew file mode 100644index 00000000..f3246a9b--- /dev/null+++ b/sdk/r3f/src/input/seed.ts@@ -0,0 +1,11 @@+// Math.random as a seeded generator of its own: a scene started again draws the same numbers (session.ts, program.ts).++/** the next of `s`'s random numbers (mulberry32), its state kept in s.rand */+export function nextRandom(s: { rand: number }): number {+ let t = (s.rand = (s.rand + 0x6d2b79f5) | 0);+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+}++export const seedOf = (key: string) => [...key].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 16777619), 2166136261) | 0;diff --git a/sdk/r3f/src/input/session.ts b/sdk/r3f/src/input/session.tsindex 5ef42652..047c955c 100644--- a/sdk/r3f/src/input/session.ts+++ b/sdk/r3f/src/input/session.ts@@ -6,78 +6,12 @@import * as THREE from "three";import { advance, createRoot, extend, flushSync, type ReconcilerRoot, type RenderProps, type RootState } from "@react-three/fiber";import { Component, createElement, type ReactNode } from "react";-import { renderInto } from "./targets";+import { standInRenderer } from "./renderer";+import { nextRandom, seedOf } from "./seed";-extend(THREE as unknown as Parameters<typeof extend>[0]);--const warned = new Set<string>();-function warnOnce(k: string, why: string) {- if (warned.has(k)) return;- warned.add(k);- console.warn(`raea/r3f: ${k} ${why}`);-}+export { standInRenderer, warnOnce } from "./renderer";-/** the renderer R3F configures and never draws with: what it sets on it (shadows, tone mapping) is read back */-export function standInRenderer(): THREE.WebGLRenderer {- const noop = () => {};- const size = { width: 1, height: 1 };- // a WebGL context that answers what a composer asks as it is made (@react-three/postprocessing, three's own), and- // takes every other call as it renders (its depth blit: bindFramebuffer, blitFramebuffer) doing nothing, its- // constants (READ_FRAMEBUFFER, DEPTH_BUFFER_BIT) 0: raea draws the effect (post.ts)- const gl = {- getContextAttributes: () => ({ alpha: true, depth: true, stencil: false, antialias: false, premultipliedAlpha: true }),- getExtension: () => null, getParameter: () => 0, getSupportedExtensions: () => [], isContextLost: () => false,- } as Record<string | symbol, unknown>;- const context = new Proxy(gl, { get: (t, k) => (k in t ? t[k] : typeof k !== "string" || k === "then" ? undefined : /^[A-Z0-9_]+$/.test(k) ? 0 : /^[a-z]/.test(k) ? noop : undefined) });- // a pass an app draws into a render target itself (drei's <ContactShadows>) is done on the CPU (targets.ts)- let target: THREE.RenderTarget | null = null;- const clear: [number, number, number, number] = [0, 0, 0, 0];- // WebGLRenderer's GL state, which a pass an app draws itself sets as it goes (drei's <MeshReflectorMaterial>:- // state.buffers.depth.setMask): every call does nothing, every flag reads as off (docs/r3f.feature R3F16)- const inert = (): unknown => new Proxy(noop, { get: (_, k) => (k === "then" || typeof k !== "string" ? undefined : inert()), apply: () => undefined });- const state = { buffers: { color: inert(), depth: inert(), stencil: inert() }, enable: noop, disable: noop, reset: noop, bindTexture: noop, unbindTexture: noop, activeTexture: noop, setBlending: noop, setFlipSided: noop, setCullFace: noop, viewport: noop, scissor: noop, setScissorTest: noop, useProgram: () => false, bindFramebuffer: () => false, drawBuffers: noop, setPolygonOffset: noop, setLineWidth: noop, setMaterial: noop };- // what an app dispatched with gl.compute this frame (TSL's compute nodes), in order: raea runs them as <Compute>s- // once they can be (R3F22); until then each is named once and the scene drawn without it- const dispatched: unknown[] = [];- const compute = (node: unknown) => {- dispatched.push(node);- if (dispatched.length > 4096) dispatched.splice(0, dispatched.length - 4096);- warnOnce("gl.compute", "dispatches a compute raea doesn't run yet: the scene is drawn without what it computes");- };- const own = {- compute,- computeAsync: async (node: unknown) => compute(node),- __raea: { computes: dispatched },- // three's WebGL clip space (a CubeCamera asks, drei's <Environment> with children): raea draws in Bevy's anyway- coordinateSystem: THREE.WebGLCoordinateSystem,- state,- extensions: { has: () => false, get: () => null, init: noop },- render: (scene: THREE.Object3D, camera: THREE.Camera) => {- if (target) renderInto(target, scene, camera, clear);- },- setRenderTarget: (t: THREE.RenderTarget | null) => void (target = t),- getRenderTarget: () => target,- setClearColor: (c: THREE.ColorRepresentation, a?: number) => {- const col = new THREE.Color(c);- clear[0] = col.r, clear[1] = col.g, clear[2] = col.b;- if (a !== undefined) clear[3] = a;- },- setClearAlpha: (a: number) => void (clear[3] = a),- getClearAlpha: () => clear[3], setSize: (w: number, h: number) => void Object.assign(size, { width: w, height: h }), setPixelRatio: noop, getPixelRatio: () => 1,- getSize: (v: THREE.Vector2) => v.set(size.width, size.height), getDrawingBufferSize: (v: THREE.Vector2) => v.set(size.width, size.height),- getContext: () => context, getClearColor: (c: THREE.Color) => c.setRGB(clear[0], clear[1], clear[2]),- dispose: noop, compile: noop, autoClear: true, autoClearColor: true, autoClearDepth: true, autoClearStencil: true,- domElement: { style: {}, addEventListener: noop, removeEventListener: noop },- xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },- shadowMap: { enabled: false, type: THREE.PCFShadowMap },- outputColorSpace: THREE.SRGBColorSpace, toneMapping: THREE.NoToneMapping, toneMappingExposure: 1,- capabilities: { isWebGL2: true, maxTextureSize: 16384, maxSamples: 4, logarithmicDepthBuffer: false }, info: { autoReset: true, reset: noop, render: { calls: 0, triangles: 0, points: 0, lines: 0, frame: 0 }, memory: { geometries: 0, textures: 0 }, programs: [] }, properties: { get: () => ({}) },- } as Record<string | symbol, unknown>;- // any other of WebGLRenderer's methods (setRenderTarget, clear, readRenderTargetPixels ...) does nothing: raea draws- // (verbs only: a catch-all would answer `then`, and the renderer would read as a promise)- const verb = /^(set|get|clear|read|copy|init|reset|render|dispose|compile|update|bind)[A-Z]?/;- return new Proxy(own, { get: (t, k) => (k in t ? t[k] : typeof k === "string" && verb.test(k) ? noop : undefined) }) as unknown as THREE.WebGLRenderer;-}+extend(THREE as unknown as Parameters<typeof extend>[0]);function standInCanvas(width: number, height: number): HTMLCanvasElement {const noop = () => {};@@ -101,12 +35,7 @@ export interface Session {* come out the same each time the root is stepped from frame 0, so a render after a seek equals its play */function seeded<T>(s: Session, fn: () => T): T {const was = Math.random;- Math.random = () => {- let t = (s.rand = (s.rand + 0x6d2b79f5) | 0);- t = Math.imul(t ^ (t >>> 15), t | 1);- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;- };+ Math.random = () => nextRandom(s);try {return fn();} finally {@@ -114,8 +43,6 @@ function seeded<T>(s: Session, fn: () => T): T {}}-const seedOf = (key: string) => [...key].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 16777619), 2166136261) | 0;-const sessions = new Map<string, Session>();/** The scene under an error boundary of raea's: what it throws (rendering, in an effect, in a ref) is handed to `on`,diff --git a/sdk/r3f/src/input/vanilla-webgpu.ts b/sdk/r3f/src/input/vanilla-webgpu.tsnew file mode 100644index 00000000..1ee0cfd3--- /dev/null+++ b/sdk/r3f/src/input/vanilla-webgpu.ts@@ -0,0 +1,16 @@+// "three/webgpu" as a composition's own code imports it in raea (docs/r3f.feature R3F19): three's WebGPU build, its+// WebGPURenderer a stand-in that draws nothing and records what it's asked to render into the <Three program> running+// it (program.ts). Its node materials are compiled by tsl.ts against three's own renderer, which the SDK imports as it is.+import type * as WEBGPU from "three/webgpu";+import { standIn } from "./program";++export * from "three/webgpu";++class StandIn {+ constructor(params?: { canvas?: unknown }) {+ return standIn(params, true) as unknown as StandIn;+ }+}++export const WebGPURenderer = StandIn as unknown as typeof WEBGPU.WebGPURenderer;+export type WebGPURenderer = WEBGPU.WebGPURenderer;diff --git a/sdk/r3f/src/input/vanilla.ts b/sdk/r3f/src/input/vanilla.tsnew file mode 100644index 00000000..d75c21cb--- /dev/null+++ b/sdk/r3f/src/input/vanilla.ts@@ -0,0 +1,18 @@+// "three" as a composition's own code imports it in raea (docs/r3f.feature R3F19): three itself, its WebGLRenderer a+// stand-in that draws nothing and records what it's asked to render into the <Three program> running it (program.ts).+// raea's bundler resolves the composition's `import "three"` here (engine/bundle edit.rs); three's own modules, its+// addons and the SDK's import three as it is.+import type * as THREE from "three";+import { standIn } from "./program";++export * from "three";++class StandIn {+ constructor(params?: { canvas?: unknown }) {+ // the stand-in in its place: `new WebGLRenderer()` is what the constructor returns+ return standIn(params, false) as unknown as StandIn;+ }+}++export const WebGLRenderer = StandIn as unknown as typeof THREE.WebGLRenderer;+export type WebGLRenderer = THREE.WebGLRenderer;diff --git a/sdk/r3f/test/parity/native.tsx b/sdk/r3f/test/parity/native.tsxindex b9765001..c9b57859 100644--- a/sdk/r3f/test/parity/native.tsx+++ b/sdk/r3f/test/parity/native.tsx@@ -1,14 +1,18 @@// The parity cases as raea compositions, for `raea render native.tsx --composition in-basic --frame 24`: an R3F scene-// through <R3F>, a raea scene as it is.+// through <R3F>, a plain three.js program through <Three>, a raea scene as it is.import { Composition, registerRoot } from "raea";-import { R3F } from "raea/r3f";+import { R3F, Three } from "raea/r3f";import { INPUTS, OUTPUTS, SIZE } from "./fixtures";+import { PROGRAMS } from "./programs";registerRoot(() => (<>{Object.entries(INPUTS).map(([k, c]) => (<Composition key={`in-${k}`} id={`in-${k}`} component={() => <R3F {...c.canvas}>{c.scene()}</R3F>} width={SIZE.width} height={SIZE.height} fps={SIZE.fps} durationInFrames={c.frame + 1} />))}+ {Object.entries(PROGRAMS).map(([k, c]) => (+ <Composition key={`in-${k}`} id={`in-${k}`} component={() => <Three program={c.program} />} width={SIZE.width} height={SIZE.height} fps={SIZE.fps} durationInFrames={c.frame + 1} />+ ))}{Object.entries(OUTPUTS).map(([k, c]) => (<Composition key={`out-${k}`} id={`out-${k}`} component={c.component} width={SIZE.width} height={SIZE.height} fps={SIZE.fps} durationInFrames={c.frame + 1} />))}diff --git a/sdk/r3f/test/parity/page.tsx b/sdk/r3f/test/parity/page.tsxindex 3594c82f..e3a4294f 100644--- a/sdk/r3f/test/parity/page.tsx+++ b/sdk/r3f/test/parity/page.tsx@@ -3,9 +3,10 @@// composition from the R3F source the source export wrote for it. Each steps its clock to// the case's frame (1/fps a step, as raea's <R3F> does), waits for what it loads, draws once and says "drawn".import { Canvas, advance } from "@react-three/fiber"-import { useEffect, useState } from "react"+import { useEffect, useRef, useState } from "react"import * as THREE from "three"import { INPUTS, OUTPUTS, SIZE } from "./fixtures"+import { PROGRAMS } from "./programs"import type { ComponentType } from "react"import { Raea } from "@raea/r3f/output/Raea"import { loadShapes } from "@raea/r3f/three/geometry"@@ -35,6 +36,32 @@ function Stepper({ frame, onDone }: { frame: number; onDone: () => void }) {return null}+/** a plain three.js program (programs.ts) on a real canvas: requestAnimationFrame is the page's own queue while it runs,+ * stepped at i * 1000 / fps for i up to the case's frame, as raea's <Three> steps it */+function ProgramCase({ name, onDone }: { name: string; onDone: () => void }) {+ const ref = useRef<HTMLCanvasElement>(null)+ useEffect(() => {+ const c = PROGRAMS[name]+ const queue = new Map<number, FrameRequestCallback>()+ let id = 0+ const was = [window.requestAnimationFrame, window.cancelAnimationFrame] as const+ window.requestAnimationFrame = (cb) => (queue.set(++id, cb), id)+ window.cancelAnimationFrame = (i) => void queue.delete(i)+ try {+ c.program(ref.current!)+ for (let i = 0; i <= c.frame; i++) {+ const due = [...queue.values()]+ queue.clear()+ for (const cb of due) cb((i * 1000) / SIZE.fps)+ }+ } finally {+ ;[window.requestAnimationFrame, window.cancelAnimationFrame] = was+ }+ onDone()+ }, [])+ return <canvas ref={ref} width={SIZE.width} height={SIZE.height} style={{ width: SIZE.width, height: SIZE.height, display: "block" }} />+}+/** `sources`: the output cases as R3F source, each its module's <Scene> (the source export's, which tools/serve.ts writes* into test/parity/gen and hands to the page) */export default function R3FParityPage({ sources = {} }: { sources?: Record<string, ComponentType<{ frame?: number }>> }) {@@ -47,6 +74,14 @@ export default function R3FParityPage({ sources = {} }: { sources?: Record<strin}, [])const done = () => setNote("drawn")const style = { width: SIZE.width, height: SIZE.height }+ if (dir === "in" && PROGRAMS[name]) {+ return (+ <div style={{ background: "#000", ...style }}>+ <ProgramCase name={name} onDone={done} />+ <div className="font-mono" style={{ position: "fixed", left: 0, top: SIZE.height + 4, color: "#fff" }}>{note}</div>+ </div>+ )+ }if (dir === "in") {const c = INPUTS[name]return (diff --git a/sdk/r3f/test/parity/programs.ts b/sdk/r3f/test/parity/programs.tsnew file mode 100644index 00000000..9fdd0f27--- /dev/null+++ b/sdk/r3f/test/parity/programs.ts@@ -0,0 +1,63 @@+// Plain three.js programs (docs/r3f.feature R3F19): a single-file demo's script as a function, its renderer its own.+// In raea, <Three program> runs it with raea's stand-in renderer (the bundler resolves this file's "three" to+// src/input/vanilla.ts); in Chrome, the harness page runs it on a real canvas with three's WebGLRenderer, its+// requestAnimationFrame stepped 1/fps a frame. Both draw frame `frame`, compared by SSIM (tools/parity.sh).+import * as THREE from "three";++export interface ProgramCase {+ program: (canvas: HTMLCanvasElement) => void;+ frame: number;+}++/** three's "getting started" grown a little: a lit, shadowed knot turning on a floor, a ring of boxes around it */+function vanilla(canvas: HTMLCanvasElement) {+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: true });+ renderer.setPixelRatio(1);+ renderer.setSize(640, 360, false);+ renderer.shadowMap.enabled = true;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;++ const scene = new THREE.Scene();+ scene.background = new THREE.Color("#20242e");+ const camera = new THREE.PerspectiveCamera(45, 640 / 360, 0.1, 100);+ camera.position.set(0, 2.4, 6.5);+ camera.lookAt(0, 0.8, 0);++ scene.add(new THREE.HemisphereLight("#cfe0ff", "#2a2420", 0.8));+ const sun = new THREE.DirectionalLight("#ffffff", 2.4);+ sun.position.set(3, 6, 2);+ sun.castShadow = true;+ scene.add(sun);++ const floor = new THREE.Mesh(new THREE.PlaneGeometry(14, 14), new THREE.MeshStandardMaterial({ color: "#cfd6e0", roughness: 0.9 }));+ floor.rotation.x = -Math.PI / 2;+ floor.receiveShadow = true;+ scene.add(floor);++ const knot = new THREE.Mesh(new THREE.TorusKnotGeometry(0.6, 0.22, 160, 24), new THREE.MeshStandardMaterial({ color: "#e05a2b", roughness: 0.35, metalness: 0.1 }));+ knot.position.y = 1.1;+ knot.castShadow = true;+ scene.add(knot);++ const ring = new THREE.Group();+ for (let i = 0; i < 10; i++) {+ const a = (i / 10) * Math.PI * 2;+ const box = new THREE.Mesh(new THREE.BoxGeometry(0.35, 0.35, 0.35), new THREE.MeshStandardMaterial({ color: new THREE.Color().setHSL(i / 10, 0.6, 0.55) }));+ box.position.set(Math.cos(a) * 2.2, 0.18, Math.sin(a) * 2.2);+ box.castShadow = true;+ ring.add(box);+ }+ scene.add(ring);++ renderer.setAnimationLoop((time) => {+ // by the loop's time, and by a step a call: both come out the same when each frame is one call+ knot.rotation.y = time / 1000;+ knot.rotation.x += 0.03;+ ring.rotation.y = -time / 2000;+ renderer.render(scene, camera);+ });+}++export const PROGRAMS: Record<string, ProgramCase> = {+ vanilla: { program: vanilla, frame: 24 },+};diff --git a/sdk/r3f/test/program.test.ts b/sdk/r3f/test/program.test.tsnew file mode 100644index 00000000..a812d29a--- /dev/null+++ b/sdk/r3f/test/program.test.ts@@ -0,0 +1,140 @@+// A plain three.js program run as <Three program> runs it (docs/r3f.feature R3F19, src/input/program.ts): its renderer+// raea's stand-in (vanilla.ts, as raea's bundler resolves a composition's "three"), its loop stepped 1/fps a frame.+import { expect, test } from "bun:test";+import * as THREE from "three";+import { WebGLRenderer } from "../src/input/vanilla";+import { WebGPURenderer } from "../src/input/vanilla-webgpu";+import { drawnOf, endRun, programCanvas, startRun, stepRun } from "../src/input/program";++const FPS = 24;+const canvas = () => programCanvas(640, 360);++test("setAnimationLoop steps once a frame at that frame's time, and the scene it renders is drawn", () => {+ const seen: { scene?: THREE.Scene; cube?: THREE.Mesh; ticks: number; now: number[] } = { ticks: 0, now: [] };+ const run = startRun("loop", (c) => {+ const renderer = new WebGLRenderer({ canvas: c });+ renderer.shadowMap.enabled = true;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ const scene = (seen.scene = new THREE.Scene());+ const camera = new THREE.PerspectiveCamera(50, 16 / 9, 0.1, 100);+ const cube = (seen.cube = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshStandardMaterial()));+ scene.add(cube);+ renderer.setAnimationLoop((t) => {+ seen.ticks++;+ seen.now.push(performance.now());+ cube.rotation.y = t / 1000;+ cube.rotation.x += 0.1;+ renderer.render(scene, camera);+ });+ }, canvas());+ stepRun(run, 24, FPS);+ expect(seen.ticks).toBe(25);+ expect(seen.cube!.rotation.y).toBeCloseTo(1);+ expect(seen.cube!.rotation.x).toBeCloseTo(2.5);+ // performance.now() reads the step's time, three's Clock with it+ expect(seen.now[12]).toBeCloseTo(500);+ const d = drawnOf(run)!;+ expect(d.scene).toBe(seen.scene!);+ expect(d.gl.shadowMap.enabled).toBe(true);+ expect(d.gl.toneMapping).toBe(THREE.ACESFilmicToneMapping);+ // drawn again at the same frame: no step+ stepRun(run, 24, FPS);+ expect(seen.ticks).toBe(25);+ endRun(run);+});++test("a requestAnimationFrame loop steps as the page's would, and the page's own comes back after", () => {+ const was = globalThis.requestAnimationFrame;+ const times: number[] = [];+ const run = startRun("raf", () => {+ const renderer = new WebGLRenderer();+ const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera();+ const animate = (t: number) => {+ requestAnimationFrame(animate);+ times.push(t);+ renderer.render(scene, camera);+ };+ requestAnimationFrame(animate);+ }, canvas());+ expect(globalThis.requestAnimationFrame).toBe(was);+ stepRun(run, 10, FPS);+ expect(times.length).toBe(11);+ expect(times[10]).toBeCloseTo((10 * 1000) / FPS);+ expect(drawnOf(run)).not.toBeNull();+});++test("Math.random is the run's own: a program started again draws the same numbers", () => {+ const draw = () => {+ const xs: number[] = [];+ const run = startRun("random", () => {+ const renderer = new WebGLRenderer();+ xs.push(Math.random());+ renderer.setAnimationLoop(() => void xs.push(Math.random()));+ }, canvas());+ stepRun(run, 3, FPS);+ endRun(run);+ return xs;+ };+ const a = draw();+ expect(draw()).toEqual(a);+ expect(new Set(a).size).toBe(a.length);+});++test("ending a run undoes it with what the program returned, and drops its loop", () => {+ let undone = 0, ticks = 0;+ const run = startRun("stop", () => {+ new WebGLRenderer().setAnimationLoop(() => void ticks++);+ return () => void undone++;+ }, canvas());+ stepRun(run, 2, FPS);+ endRun(run);+ expect(undone).toBe(1);+ stepRun(run, 5, FPS);+ expect(ticks).toBe(3);+});++test("a full-screen pass to the screen (three's EffectComposer) is drawn as the scene it rendered", () => {+ const scene = new THREE.Scene();+ const run = startRun("composer", () => {+ const renderer = new WebGLRenderer();+ const target = new THREE.WebGLRenderTarget(64, 64);+ const camera = new THREE.PerspectiveCamera();+ const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.MeshBasicMaterial({ map: target.texture }));+ const ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);+ renderer.setAnimationLoop(() => {+ renderer.setRenderTarget(target);+ renderer.render(scene, camera);+ renderer.setRenderTarget(null);+ renderer.render(quad, ortho);+ });+ }, canvas());+ stepRun(run, 0, FPS);+ expect(drawnOf(run)!.scene).toBe(scene);+});++test("three/webgpu's renderer: `await renderer.init()`, then its loop, stepped from frame 0 once it's ready", async () => {+ let ticks = 0;+ const run = startRun("webgpu", async (c) => {+ const renderer = new WebGPURenderer({ canvas: c });+ await renderer.init();+ const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera();+ renderer.setAnimationLoop(() => {+ ticks++;+ void renderer.renderAsync(scene, camera);+ });+ }, canvas());+ expect(run.waiting).toBeDefined();+ await run.waiting;+ expect(run.waiting).toBeUndefined();+ stepRun(run, 4, FPS);+ expect(ticks).toBe(5);+ expect(drawnOf(run)).not.toBeNull();+});++test("a renderer made outside <Three program> draws nothing and throws nothing", () => {+ const r = new WebGLRenderer();+ r.setAnimationLoop(() => {});+ r.render(new THREE.Scene(), new THREE.PerspectiveCamera());+ r.setSize(100, 100);+ expect(r.domElement).toBeDefined();+});