Skip to content

armgit / raea

Public Imported from GitHub
0

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.

R3F23: what an app draws into a render target itself, drawn on raea's GPU (R3F23b). A gl.render into a target that sdk/r3f doesn't do on the CPU is recorded on the renderer that drew it (targets.ts renderInto) with its scene's parts as they were then, so two passes of one quad with another uniform each keep their own. passes.ts puts each pass's parts on a render layer of its own (64 up) and adds a camera part into the target's image ("render:<texture uuid>@WxH:WxH", ":float" for a float target), ordered before the screen's in draw order, cleared to the pass scene's background or the renderer's clear colour; a bare THREE.Camera's full-screen quad is drawn by an orthographic one. A material reading the target's texture names that image, with v turned over as a flipY picture's is (texture.ts flipsY, in scene.ts and shader.ts). session.ts and program.ts empty a renderer's passes as each frame steps, so a still of frame 3 has frame 3's passes. Cube and 3D targets stay left out. Tests: test/targets.test.tsx (the fbo probe, one frame's passes, two passes of one quad), the reflector case in errors.test.tsx; the parity case test/parity/targets.tsx (in-fbo)

shinyobjectz0226bbb21b22
diff --git a/docs/r3f.feature b/docs/r3f.feature
index e68c69f8..86c67b1d 100644
--- a/docs/r3f.feature
+++ b/docs/r3f.feature
@@ -516,6 +516,18 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
# R3F23d. in-fbo (the audit's fbo probe: a torus knot drawn into a useFBO shown on a plane), in-pingpong
# (GPUComputationRenderer's wave), in-reflector (<MeshReflectorMaterial>: its mirrored camera's pass, its
# blur, and its material's projective read; the read is an onBeforeCompile patch, so it lands with R3F24).
+ # Status (11-15): R3F23a and R3F23b written, unit-tested and in the tree. The engine's camera into an image is a
+ # "rendercam" row (raea-runtime-look rendercam.rs: its image in `into`, since a live row's `target` names the row
+ # a component is on; `on` keyed by step; the ambient light on its own layers, the screen camera's likewise), spawned
+ # by raea-render's render_camera (raea-sys-frame camera.rs into_image: IntoImage, no MSAA or dither, Hdr for a
+ # float image); every "render:" source resolves through raea-sys-frame's render_image.rs. sdk/r3f: a target is
+ # named "render:<texture uuid>@WxH:WxH" (a resized target is a new image), counted as drawn on the GPU once a pass
+ # drew into it (targets.ts onGpu: three's PMREM stand-in isn't), read with v turned over as a flipY picture is
+ # (texture.ts flipsY: scene.ts, shader.ts; tsl.ts's node textures next); a pass is recorded on the renderer that
+ # drew it (targets.ts renderInto, its __raea.passes, emptied by step() as session.ts and program.ts step a frame),
+ # its parts taken when it's drawn (two passes of one quad with another uniform each keep their own), and cube or
+ # 3D targets stay left out. Next: in-fbo's SSIM on a release build (test/parity/targets.tsx; R3F_CASES="in-fbo:12"
+ # until tools/parity.sh lists it), then R3F23c.
Scenario: R3F24. onBeforeCompile patches
Given a material patched by onBeforeCompile (drei's MeshWobbleMaterial and MeshDistortMaterial, a patched
diff --git a/sdk/r3f/src/input/passes.ts b/sdk/r3f/src/input/passes.ts
new file mode 100644
index 00000000..80315570
--- /dev/null
+++ b/sdk/r3f/src/input/passes.ts
@@ -0,0 +1,60 @@
+// What an app draws into a render target itself, drawn on raea's GPU (docs/r3f.feature R3F23): a pass
+// (gl.setRenderTarget(t); gl.render(scene, camera)) that targets.ts doesn't do on the CPU becomes its scene's parts as
+// they were when it was drawn (its uniforms then, not at the end of the frame), on a render layer of its own, and a
+// camera part drawing that layer into the target's image ("render:NAME:WxH", ":float" for a float target), ordered
+// before the screen's camera in the order the app drew. A material whose texture is the target's reads that image
+// (texture.ts srcOf), with v turned over as a flipY picture's is: three's target counts rows from the bottom.
+import * as THREE from "three";
+import type { Part } from "./material";
+import { cameraOf } from "./lights";
+import { sceneParts } from "./scene";
+import { drawPassesWith, imageOf, type Pass } from "./targets";
+
+/** the first render layer a pass takes: past a frame look's cells (layers 1 to 30) and their composite (31) */
+const FIRST_LAYER = 64;
+/** the order of the first pass's camera; the screen's is 0 */
+const FIRST_ORDER = -10000;
+
+/** each pass's place by its key (the target's texture and its place among that target's passes a frame), as it was
+ * first drawn: its layer and camera order stay the same frame to frame, so its parts and camera are the same rows */
+const seen = new Map<string, number>();
+
+function placeOf(key: string): number {
+ let i = seen.get(key);
+ if (i === undefined) {
+ i = seen.size;
+ seen.set(key, i);
+ }
+ return i;
+}
+
+/** a colour as the camera's clear: sRGB hex with alpha (three's clear colour is linear, as Bevy's decoded one is) */
+function clearOf(c: THREE.Color, a: number): string {
+ return `#${c.getHexString()}${Math.round(Math.min(1, Math.max(0, a)) * 255).toString(16).padStart(2, "0")}`;
+}
+
+/** `parts` on render layer `layer`: each part but a group's (a mesh, a light, text); a mesh's own children (its
+ * geometry and surface) go with it */
+function onLayer(parts: Part[], layer: number): Part[] {
+ return parts.map((p) => (p.type === "Group" ? { ...p, children: onLayer(p.children ?? [], layer) } : { ...p, props: { ...p.props, layers: [layer] } }));
+}
+
+/** a camera for a pass three draws with a bare THREE.Camera (GPUComputationRenderer's, a full-screen quad's): its
+ * shader places the quad itself, so any camera that sees the quad at z 0 will do */
+const QUAD: Part = { type: "OrthographicCamera", props: { position: [0, 0, 1], lookAt: [0, 0, 0], up: [0, 1, 0], height: 2, near: 0.01, far: 2 } };
+
+/** a pass as parts: its scene's on its layer and its camera into the target's image */
+function passParts(p: Omit<Pass, "parts">, gl: THREE.WebGLRenderer): Part[] {
+ const key = `${p.target.texture.uuid}#${p.k}`;
+ const i = placeOf(key);
+ const layer = FIRST_LAYER + i;
+ const root = `pass/${key}`;
+ const { world, drawn } = sceneParts(p.scene as THREE.Scene, p.camera, gl, p.target.height, root);
+ const cam = cameraOf(p.camera) ?? QUAD;
+ const bg = (p.scene as THREE.Scene).background;
+ const clear = bg instanceof THREE.Color ? { bg: clearOf(bg, 1) } : p.autoClear ? { bg: clearOf(new THREE.Color(p.clear[0], p.clear[1], p.clear[2]), p.clear[3]) } : { clear: "none" };
+ const camera: Part = { type: cam.type, props: { ...cam.props, name: root, target: imageOf(p.target), layers: [layer], order: FIRST_ORDER + i, ...clear } };
+ return [camera, ...onLayer([...world, ...drawn], layer)];
+}
+
+drawPassesWith(passParts);
diff --git a/sdk/r3f/src/input/program.ts b/sdk/r3f/src/input/program.ts
index ff6965be..206008e9 100644
--- a/sdk/r3f/src/input/program.ts
+++ b/sdk/r3f/src/input/program.ts
@@ -32,6 +32,8 @@ export interface Run {
rand: number;
/** the time the step being run reads, ms */
now: number;
+ /** the renderers it made: each one's passes into targets are emptied as a frame steps (R3F23) */
+ renderers: Set<object>;
/** its renderers' animation loops */
loops: Map<object, Loop>;
/** the frame callbacks it asked for, run at the next step */
@@ -168,6 +170,7 @@ export function standIn(params: { canvas?: unknown } | undefined, webgpu: boolea
},
has: (t, k) => k in t || k in base,
});
+ run?.renderers.add(self);
return self as unknown as THREE.WebGLRenderer;
}
@@ -175,7 +178,7 @@ export function standIn(params: { canvas?: unknown } | undefined, webgpu: boolea
/** `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 };
+ const run: Run = { source: String(program), frame: -1, rand: seedOf(key), now: 0, renderers: new Set(), loops: new Map(), rafs: new Map(), raf: 0, drawn: null, scene: null, canvas, depth: 0 };
enter(run);
let out: unknown;
try {
@@ -212,6 +215,8 @@ 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, () => {
+ // what its renderers drew into targets is this step's (R3F23): the last step's passes go
+ for (const r of run.renderers) (r as { __raea?: { step?: () => void } }).__raea?.step?.();
const due = [...run.rafs.values()];
run.rafs.clear();
for (const cb of [...run.loops.values()]) cb(run.now);
diff --git a/sdk/r3f/src/input/renderer.ts b/sdk/r3f/src/input/renderer.ts
index b4f7953f..884c6b73 100644
--- a/sdk/r3f/src/input/renderer.ts
+++ b/sdk/r3f/src/input/renderer.ts
@@ -63,6 +63,9 @@ export function standInRenderer(): THREE.WebGLRenderer {
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>;
+ // a pass the CPU doesn't do is drawn by raea's engine as a camera into the target's image, its scene's parts taken as
+ // they are when it's drawn (targets.ts recordPass, passes.ts: R3F23)
+ own.render = (scene: THREE.Object3D, camera: THREE.Camera) => void (target && renderInto(target, scene, camera, clear, own as unknown as THREE.WebGLRenderer));
// 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]?/;
diff --git a/sdk/r3f/src/input/scene.ts b/sdk/r3f/src/input/scene.ts
index 8be69381..435d080e 100644
--- a/sdk/r3f/src/input/scene.ts
+++ b/sdk/r3f/src/input/scene.ts
@@ -4,6 +4,10 @@
// Lights, the camera, fog and the environment come out in world space (lights.ts). Each part is named by its place in
// the tree (and its own name), so raea matches it across frames.
import * as THREE from "three";
+// what the app draws into render targets itself, drawn on the GPU (R3F23): passes.ts makes each pass's parts as it's drawn
+import "./passes";
+import { passesOf } from "./targets";
+import { flipsY } from "./texture";
import { arraysOf, posed, posedArrays, rewound, type Arrays } from "./geometry";
import { isTroikaText, textParts } from "./text";
import { clipArrays, clipOf, type Clip } from "./clip";
@@ -61,7 +65,7 @@ function flipped(m: THREE.Material | THREE.Material[]): boolean {
// a ShaderMaterial reads its uvs as three gives them; the engine flips where it samples a flipped picture
if (one && isShader(one)) return false;
const map = ((Array.isArray(m) ? m[0] : m) as THREE.MeshBasicMaterial | undefined)?.map;
- return map ? map.flipY : true;
+ return map ? flipsY(map) : true;
}
function colouredByVertex(m: THREE.Material) {
@@ -406,15 +410,26 @@ export interface Converted {
background?: string;
}
-/** R3F's scene, camera and renderer settings as raea's parts, this frame */
-export function convert(scene: THREE.Scene, camera: THREE.Camera, gl: THREE.WebGLRenderer, height: number, time = 0, delta = 0): Converted {
+/** a scene (or one object three was asked to render alone: a full-screen quad) seen by `camera` as raea's parts, its
+ * objects' named under `root`: its lights (`world`) and what it draws. The screen's (convert) and a pass's into a
+ * render target (passes.ts) */
+export function sceneParts(scene: THREE.Object3D, camera: THREE.Camera, gl: THREE.WebGLRenderer, height: number, root = "r3f", time = 0, delta = 0): { w: Walk; world: Part[]; drawn: Part[] } {
scene.updateMatrixWorld();
camera.updateMatrixWorld();
if (camera.parent === null) camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
- const w: Walk = { camera, shadows: gl.shadowMap.enabled, world: [], height, scene, time, delta, gl, clips: [] };
- let drawn = scene.children.flatMap((c, i) => walk(c, `r3f/${i}`, w));
+ const isScene = (scene as THREE.Scene).isScene === true;
+ const w: Walk = { camera, shadows: gl.shadowMap.enabled, world: [], height, scene: scene as THREE.Scene, time, delta, gl, clips: [] };
+ let drawn = isScene ? scene.children.flatMap((c, i) => walk(c, `${root}/${i}`, w)) : walk(scene, `${root}/0`, w);
// a scene moved, turned or scaled as a whole (rare, but three allows it)
- if (!scene.matrix.equals(new THREE.Matrix4()) && drawn.length) drawn = [{ type: "Group", props: { name: "r3f", ...place(scene) }, children: drawn }];
+ if (isScene && !scene.matrix.equals(new THREE.Matrix4()) && drawn.length) drawn = [{ type: "Group", props: { name: root, ...place(scene) }, children: drawn }];
+ return { w, world: w.world, drawn };
+}
+
+/** R3F's scene, camera and renderer settings as raea's parts, this frame */
+export function convert(scene: THREE.Scene, camera: THREE.Camera, gl: THREE.WebGLRenderer, height: number, time = 0, delta = 0): Converted {
+ const { w, drawn } = sceneParts(scene, camera, gl, height, "r3f", time, delta);
+ // what the app drew into render targets itself this frame, drawn on the GPU before the screen (passes.ts, R3F23)
+ drawn.unshift(...passesOf(gl));
// a node material runs only under three's WebGPURenderer, so a scene with one is drawn by it (whatever gl stands in)
let webgpu = (gl as { isWebGPURenderer?: boolean }).isWebGPURenderer === true;
if (!webgpu) scene.traverse((o) => {
diff --git a/sdk/r3f/src/input/session.ts b/sdk/r3f/src/input/session.ts
index 047c955c..6349dc10 100644
--- a/sdk/r3f/src/input/session.ts
+++ b/sdk/r3f/src/input/session.ts
@@ -107,6 +107,8 @@ export function stepTo(key: string, frame: number, fps: number, width: number, h
}
}
for (let i = s.frame + 1; i <= frame; i++) {
+ // what it draws into targets is this step's (R3F23): the last step's passes go
+ (live.state?.gl as unknown as { __raea?: { step?: () => void } } | undefined)?.__raea?.step?.();
render(i);
seeded(live, () => advance(i / fps, true, live.state));
live.frame = i;
diff --git a/sdk/r3f/src/input/shader.ts b/sdk/r3f/src/input/shader.ts
index 24fc7629..32e994bb 100644
--- a/sdk/r3f/src/input/shader.ts
+++ b/sdk/r3f/src/input/shader.ts
@@ -8,7 +8,7 @@
// that includes <tonemapping_fragment> on a tone-mapped material goes as "linear", those includes dropped, and Bevy's
// tone mapping maps it as three's would.
import * as THREE from "three";
-import { srcOf } from "./texture";
+import { flipsY, srcOf } from "./texture";
import type { Part, Props } from "./material";
const hex = (c: THREE.Color) => "#" + c.getHexString();
@@ -182,7 +182,7 @@ export function shaderPart(m: THREE.ShaderMaterial, points = false): Part {
if (!src) warnOnce(`${m.type} texture ${name}`, "has no picture raea can load (a render target's?): drawn as white");
// three samples a picture without a colour space raw, an sRGB one decoded (as Bevy's sRGB image is)
textures[name] = src && t.colorSpace !== THREE.SRGBColorSpace ? { src, colorSpace: "linear" } : src ?? WHITE;
- if (t.flipY && src) flipY.push(name);
+ if (flipsY(t) && src) flipY.push(name);
continue;
}
if (v instanceof THREE.Color && !color && /^(u?[cC]olou?r|diffuse)$/.test(name)) color = hex(v);
diff --git a/sdk/r3f/src/input/targets.ts b/sdk/r3f/src/input/targets.ts
index e8de75f8..3cf9d8c6 100644
--- a/sdk/r3f/src/input/targets.ts
+++ b/sdk/r3f/src/input/targets.ts
@@ -8,8 +8,10 @@
// colour plain depth or drei's tint (ucolor * z * 2, alpha 1 - z, read from the material's onBeforeCompile)
// a blur pass: three's HorizontalBlurShader or VerticalBlurShader (9 taps, h or v apart in uv) over a target
//
-// Anything else drawn into a target is left out, with one warning: the target stays empty.
+// Anything else drawn into a target is drawn by raea's engine: recorded here as a pass (passes.ts makes its parts),
+// a camera into the target's image (docs/r3f.feature R3F23).
import * as THREE from "three";
+import type { Part } from "./material";
/** a target's pixels: RGBA floats, row 0 at v = 0 (as three's targets hold them) */
interface Pixels {
@@ -19,12 +21,6 @@ interface Pixels {
}
const drawn = new WeakMap<THREE.Texture, Pixels>();
-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}`);
-}
/** raea's working size for a target (the passes are in uv, so a smaller one blurs the same) */
const MAX = 256;
@@ -46,24 +42,96 @@ export function targetPixels(t: THREE.Texture): Pixels | undefined {
const BLUR = [0.051, 0.0918, 0.12245, 0.1531, 0.1633, 0.1531, 0.12245, 0.0918, 0.051];
-/** `gl.render(scene, camera)` into `rt` (the stand-in renderer's), done here when it's a pass raea knows */
-export function renderInto(rt: THREE.RenderTarget, scene: THREE.Object3D, camera: THREE.Camera, clear: [number, number, number, number]) {
- const out = pixelsFor(rt);
+/** `gl.render(scene, camera)` into `rt` (the stand-in renderer `gl`'s, renderer.ts): done here when it's a pass raea
+ * does on the CPU, otherwise drawn by raea's engine (recordPass) */
+export function renderInto(rt: THREE.RenderTarget, scene: THREE.Object3D, camera: THREE.Camera, clear: [number, number, number, number], gl?: THREE.WebGLRenderer) {
+ if (!onCpu(rt, scene, camera, clear) && gl) recordPass(rt, scene, camera, clear, gl);
+}
+
+/** `gl.render(scene, camera)` into `rt` done here, when it's a pass raea does on the CPU: whether it was */
+function onCpu(rt: THREE.RenderTarget, scene: THREE.Object3D, camera: THREE.Camera, clear: [number, number, number, number]): boolean {
const mat = (scene as THREE.Mesh).material as THREE.ShaderMaterial | undefined;
const u = mat?.uniforms;
if ((scene as THREE.Mesh).isMesh && u?.tDiffuse && ("h" in u || "v" in u)) {
const src = u.tDiffuse.value as THREE.Texture | null;
const from = src ? drawn.get(src) : undefined;
- if (from) blur(from, out, "h" in u ? Number(u.h.value) : 0, "v" in u ? Number(u.v.value) : 0);
- return;
+ // a blur of a picture drawn here is done here; one of a target raea's engine draws is drawn there too
+ if (from || !(src && onGpu(src))) {
+ if (from) blur(from, pixelsFor(rt), "h" in u ? Number(u.h.value) : 0, "v" in u ? Number(u.v.value) : 0);
+ return true;
+ }
}
const over = (scene as THREE.Scene).overrideMaterial;
if ((scene as THREE.Scene).isScene && (over as THREE.MeshDepthMaterial | null)?.isMeshDepthMaterial && (camera as THREE.OrthographicCamera).isOrthographicCamera) {
+ const out = pixelsFor(rt);
for (let i = 0; i < out.data.length; i += 4) out.data.set(clear, i);
depth(scene as THREE.Scene, camera as THREE.OrthographicCamera, over as THREE.MeshDepthMaterial, out);
- return;
+ return true;
}
- warnOnce(`a render into a target (${(scene as THREE.Mesh).type}${mat ? " with " + mat.type : ""})`, "isn't one raea draws (a depth pass or a blur): the target stays empty");
+ return false;
+}
+
+/** a render into a target raea's engine draws: what was drawn, as it was then (its parts, made by passes.ts as the
+ * render is asked for, since an app changes its uniforms between passes), into which target, the k-th into it this
+ * frame */
+export interface Pass {
+ target: THREE.RenderTarget;
+ scene: THREE.Object3D;
+ camera: THREE.Camera;
+ /** the renderer's clear colour, linear rgba, when the render was asked for */
+ clear: [number, number, number, number];
+ autoClear: boolean;
+ k: number;
+ parts: Part[];
+}
+
+/** the targets a pass was drawn into on raea's GPU (recordPass), ever, by their texture */
+const onGpuTargets = new WeakMap<THREE.Texture, THREE.RenderTarget>();
+
+let partsOf: ((p: Omit<Pass, "parts">, gl: THREE.WebGLRenderer) => Part[]) | undefined;
+
+/** how a pass becomes parts (passes.ts, set as it loads: it walks scenes as scene.ts does, which reads targets) */
+export function drawPassesWith(fn: (p: Omit<Pass, "parts">, gl: THREE.WebGLRenderer) => Part[]) {
+ partsOf = fn;
+}
+
+/** the passes the stand-in renderer `gl` drew on raea's GPU this frame, in draw order (its __raea.passes), with the
+ * step() that empties them as each frame steps (session.ts, program.ts) */
+function passesFor(gl: THREE.WebGLRenderer): Pass[] {
+ const own = gl as unknown as { __raea?: { passes?: Pass[]; step?: () => void } };
+ const raea = (own.__raea ??= {});
+ if (!raea.passes) {
+ const passes: Pass[] = [];
+ raea.passes = passes;
+ raea.step = () => void (passes.length = 0);
+ }
+ return raea.passes;
+}
+
+/** `gl.render(scene, camera)` into `rt` that raea's engine draws, added to the frame's passes with its parts as they
+ * are now */
+function recordPass(rt: THREE.RenderTarget, scene: THREE.Object3D, camera: THREE.Camera, clear: [number, number, number, number], gl: THREE.WebGLRenderer) {
+ // a cube or 3D target (a CubeCamera's, drei's <Environment> with children) isn't a 2D image a camera draws: left out
+ // as before, the scene drawn without it (lights.ts skyOf says so for an environment)
+ if ((rt as { isWebGLCubeRenderTarget?: boolean }).isWebGLCubeRenderTarget || (rt.texture as { isCubeTexture?: boolean }).isCubeTexture || rt.depth > 1) return;
+ const passes = passesFor(gl);
+ const p = { target: rt, scene, camera, clear: [...clear] as Pass["clear"], autoClear: gl.autoClear !== false, k: passes.filter((x) => x.target === rt).length };
+ onGpuTargets.set(rt.texture, rt);
+ passes.push({ ...p, parts: partsOf ? partsOf(p, gl) : [] });
+ // a renderer whose frames nobody steps (step() not called) keeps its latest passes, not every one ever drawn
+ if (passes.length > 1024) passes.splice(0, passes.length - 1024);
+}
+
+/** whether `t` is a render target's that a pass was drawn into on raea's GPU (not one drawn on the CPU here, nor a
+ * target nothing drew into: three's PMREMGenerator's stand-in, pmrem.ts): an image a camera draws into, which counts
+ * rows from the top where three's target counts them from the bottom */
+export function onGpu(t: THREE.Texture): boolean {
+ return onGpuTargets.has(t) && !drawn.has(t);
+}
+
+/** the target a pass drew `t` into on raea's GPU, if one did */
+export function gpuTargetOf(t: THREE.Texture): THREE.RenderTarget | undefined {
+ return drawn.has(t) ? undefined : onGpuTargets.get(t);
}
/** three's 9-tap blur, `h` and `v` apart in uv, sampled linearly with edges clamped */
@@ -187,3 +255,18 @@ function depth(scene: THREE.Scene, cam: THREE.OrthographicCamera, m: THREE.MeshD
}
}
}
+
+/** a render target's image as raea names it ("render:NAME:WxH", ":float" for a float target): by its texture and
+ * size, so a resized target is a new image */
+export function imageOf(rt: THREE.RenderTarget): string {
+ const w = Math.max(1, Math.round(rt.width)), h = Math.max(1, Math.round(rt.height));
+ const t = rt.texture;
+ const float = t.type === THREE.FloatType || t.type === THREE.HalfFloatType;
+ return `render:${t.uuid}@${w}x${h}:${w}x${h}${float ? ":float" : ""}`;
+}
+
+/** the parts of what the app drew into targets on raea's GPU this frame (the stand-in renderer's passes), in order */
+export function passesOf(gl: THREE.WebGLRenderer): Part[] {
+ const passes = (gl as unknown as { __raea?: { passes?: Pass[] } }).__raea?.passes;
+ return passes ? passes.flatMap((p) => p.parts) : [];
+}
diff --git a/sdk/r3f/src/input/texture.ts b/sdk/r3f/src/input/texture.ts
index afb4f591..fe1371f4 100644
--- a/sdk/r3f/src/input/texture.ts
+++ b/sdk/r3f/src/input/texture.ts
@@ -3,7 +3,7 @@
// native render, where there's no DOM to load an <img> into, three's ImageLoader is stood in for by one that hands
// back the url (with the picture's size unknown) and the engine loads that file.
import * as THREE from "three";
-import { targetPixels } from "./targets";
+import { gpuTargetOf, imageOf, onGpu, targetPixels } from "./targets";
const urls = new WeakMap<object, string>();
@@ -278,6 +278,9 @@ export function srcOf(t: THREE.Texture | null | undefined): string | undefined {
// row 0 at v = 0: a target isn't flipped in y (its uvs reach raea as three gives them), so it's the PNG's top row
return pngOf(bytes, drawn.w, drawn.h);
}
+ // a render target raea's engine draws into (passes.ts, R3F23): the image its camera draws
+ const rt = gpuTargetOf(t);
+ if (rt) return imageOf(rt);
const given = t.userData?.src;
if (typeof given === "string") return given;
const img = t.image as { src?: string; toDataURL?: () => string; data?: unknown } | undefined;
@@ -300,6 +303,13 @@ export function srcOf(t: THREE.Texture | null | undefined): string | undefined {
return undefined;
}
+/** whether `t` counts v from the bottom of its picture, as three's flipY picture does and a render target raea draws
+ * on the GPU does (Bevy's image counts rows from the top, three's target from the bottom): a mesh reading it has its v
+ * turned over (scene.ts), a shader's samples of it too (shader.ts, tsl.ts) */
+export function flipsY(t: THREE.Texture): boolean {
+ return t.flipY || onGpu(t);
+}
+
/** a texture's repeat and offset, rotation, wrap and filter as raea's material props */
export function placementOf(t: THREE.Texture): { repeat?: [number, number]; uvTransform?: { offset?: [number, number]; rotation?: number; scale?: [number, number] }; sampler?: Record<string, unknown> } {
const out: ReturnType<typeof placementOf> = {};
diff --git a/sdk/r3f/test/errors.test.tsx b/sdk/r3f/test/errors.test.tsx
index e8cb0eab..f1a00e95 100644
--- a/sdk/r3f/test/errors.test.tsx
+++ b/sdk/r3f/test/errors.test.tsx
@@ -103,7 +103,12 @@ describe("what the 11-15 audit found refused", () => {
test("drei's <MeshReflectorMaterial> (it sets gl.state.buffers.depth) draws its plane", async () => {
const { MeshReflectorMaterial } = await import("@react-three/drei");
const { out } = quiet(() => partsOf(() => (<><Box /><mesh rotation={[-Math.PI / 2, 0, 0]}><planeGeometry args={[4, 4]} /><MeshReflectorMaterial resolution={64} mirror={0.8} /></mesh></>)));
- expect(out.filter((p) => p.type === "Mesh").length).toBe(2);
+ // the box and the plane on the screen; its mirrored camera's pass draws the box (the plane hides itself) into its
+ // target on a layer of its own (R3F23)
+ expect(out.filter((p) => p.type === "Mesh" && !p.props.layers).length).toBe(2);
+ const pass = out.find((p) => typeof p.props.target === "string");
+ expect(pass?.props.target).toMatch(/^render:.+:64x64(:float)?$/);
+ expect(out.filter((p) => p.type === "Mesh" && (p.props.layers as number[] | undefined)?.[0] === (pass?.props.layers as number[])[0]).length).toBe(1);
});
test("drei's <Environment> with Lightformers (a CubeCamera reads the renderer's coordinate system) draws the scene", async () => {
diff --git a/sdk/r3f/test/parity/fixtures.tsx b/sdk/r3f/test/parity/fixtures.tsx
index c2a6f912..99005b2c 100644
--- a/sdk/r3f/test/parity/fixtures.tsx
+++ b/sdk/r3f/test/parity/fixtures.tsx
@@ -6,6 +6,7 @@ import * as PP from "@react-three/postprocessing";
import { ContactShadows, Environment, Float, Sky, Text, useGLTF } from "@react-three/drei";
import { useMemo, useRef, type ReactNode } from "react";
import * as THREE from "three";
+import { TARGET_INPUTS } from "./targets";
import { MeshBasicNodeMaterial } from "three/webgpu";
import * as TSLTyped from "three/tsl";
import { composeEffects, configureFontTexture, createText, parseFont, scramble, wipe } from "lettra/three";
@@ -116,6 +117,8 @@ const probe = (() => {
const clipPlane = new THREE.Plane(new THREE.Vector3(-0.3, -1, 0.2).normalize(), 0.95);
export const INPUTS: Record<string, InputCase> = {
+ // render targets an app draws into itself, drawn on raea's GPU (R3F23): test/parity/targets.tsx
+ ...TARGET_INPUTS,
instanced: {
canvas: { camera: { position: [0, 3.2, 4.2], fov: 45 } },
frame: 12,
diff --git a/sdk/r3f/test/parity/targets.tsx b/sdk/r3f/test/parity/targets.tsx
new file mode 100644
index 00000000..58292816
--- /dev/null
+++ b/sdk/r3f/test/parity/targets.tsx
@@ -0,0 +1,47 @@
+// The parity cases for render targets an app draws into itself, drawn on raea's GPU (docs/r3f.feature R3F23,
+// src/input/passes.ts): each drawn by raea and by three.js in Chrome.
+import { useFBO } from "@react-three/drei";
+import { useFrame } from "@react-three/fiber";
+import { useMemo } from "react";
+import * as THREE from "three";
+import type { InputCase } from "./fixtures";
+
+/** the 11-15 audit's fbo probe: a lit, turning knot drawn into a useFBO from its own scene and camera, every frame,
+ * shown on a plane in the screen's scene (0.1.4 drew the plane white: the target was never filled) */
+function FboPlane() {
+ const fbo = useFBO(256, 256);
+ const inner = useMemo(() => {
+ const s = new THREE.Scene();
+ s.background = new THREE.Color("#ff3366");
+ const knot = new THREE.Mesh(new THREE.TorusKnotGeometry(0.6, 0.2, 128, 16), new THREE.MeshStandardMaterial({ color: "#f2c14e", roughness: 0.35 }));
+ const sun = new THREE.DirectionalLight("#ffffff", 2.5);
+ sun.position.set(2, 3, 2);
+ s.add(knot, sun, new THREE.AmbientLight("#ffffff", 0.4));
+ const cam = new THREE.PerspectiveCamera(50, 1, 0.1, 10);
+ cam.position.z = 3;
+ return { s, knot, cam };
+ }, []);
+ useFrame(({ gl, clock }) => {
+ inner.knot.rotation.set(0.4, clock.elapsedTime * 1.5, 0);
+ gl.setRenderTarget(fbo);
+ gl.render(inner.s, inner.cam);
+ gl.setRenderTarget(null);
+ });
+ return (
+ <>
+ <color attach="background" args={["#222222"]} />
+ <mesh rotation={[0, -0.3, 0]}>
+ <planeGeometry args={[3, 3]} />
+ <meshBasicMaterial map={fbo.texture} />
+ </mesh>
+ </>
+ );
+}
+
+export const TARGET_INPUTS: Record<string, InputCase> = {
+ fbo: {
+ canvas: { camera: { position: [0, 0, 4], fov: 45 } },
+ frame: 12,
+ scene: () => <FboPlane />,
+ },
+};
diff --git a/sdk/r3f/test/targets.test.tsx b/sdk/r3f/test/targets.test.tsx
new file mode 100644
index 00000000..8a0e403a
--- /dev/null
+++ b/sdk/r3f/test/targets.test.tsx
@@ -0,0 +1,106 @@
+// Render targets drawn on raea's GPU (docs/r3f.feature R3F23): a pass an app draws itself (gl.setRenderTarget(t);
+// gl.render(scene, camera)) is its scene's parts, as they were when it was drawn, on a render layer of its own, and a
+// camera part drawing that layer into the target's image; a material reading the target's texture names that image.
+import { describe, expect, test } from "bun:test";
+import { createPortal, useFrame } from "@react-three/fiber";
+import { useMemo, type ReactNode } from "react";
+import * as THREE from "three";
+import { convert } from "../src/input/scene";
+import { end, stepTo } from "../src/input/session";
+import type { Part } from "../src/parts";
+
+const flat = (parts: Part[]): Part[] => parts.flatMap((p) => [p, ...flat(p.children ?? [])]);
+let n = 0;
+function partsOf(scene: () => ReactNode, frame = 0): Part[] {
+ const key = `targets${n++}`;
+ const s = stepTo(key, frame, 30, 400, 400, {}, scene);
+ const st = s.state as unknown as { scene: THREE.Scene; camera: THREE.Camera; gl: THREE.WebGLRenderer };
+ const out = flat(convert(st.scene, st.camera, st.gl, 400).parts);
+ end(key);
+ return out;
+}
+
+/** the audit's fbo probe: a knot drawn into a target (its own scene, through a portal) shown on a plane */
+function Fbo() {
+ const target = useMemo(() => new THREE.WebGLRenderTarget(128, 64), []);
+ const scene = useMemo(() => Object.assign(new THREE.Scene(), { background: new THREE.Color("#ff8800") }), []);
+ const cam = useMemo(() => {
+ const c = new THREE.PerspectiveCamera(50, 2, 0.1, 100);
+ c.position.set(0, 0, 4);
+ return c;
+ }, []);
+ useFrame(({ gl }) => {
+ gl.setRenderTarget(target);
+ gl.render(scene, cam);
+ gl.setRenderTarget(null);
+ });
+ return (
+ <>
+ {createPortal(<mesh name="knot"><torusKnotGeometry args={[0.6, 0.2, 32, 8]} /><meshBasicMaterial color="#2266ff" /></mesh>, scene)}
+ <mesh name="screen"><planeGeometry args={[2, 1]} /><meshBasicMaterial map={target.texture} /></mesh>
+ </>
+ );
+}
+
+describe("a render into a target, drawn by raea's engine", () => {
+ test("is a camera into the target's image, before the screen's, drawing its scene's parts on its own layer", () => {
+ const out = partsOf(() => <Fbo />);
+ const cam = out.find((p) => typeof p.props.target === "string")!;
+ expect(cam.type).toBe("PerspectiveCamera");
+ expect(cam.props.target).toMatch(/^render:[^:]+:128x64$/);
+ expect(cam.props.order as number).toBeLessThan(0);
+ // cleared to the pass scene's background, opaque
+ expect(cam.props.bg).toBe("#ff8800ff");
+ const layer = (cam.props.layers as number[])[0];
+ expect(layer).toBeGreaterThan(31);
+ const knot = out.find((p) => p.type === "Mesh" && String(p.props.name).includes("knot"))!;
+ expect(knot.props.layers).toEqual([layer]);
+ expect(String(knot.props.name).startsWith("pass/")).toBe(true);
+ // the screen's plane is on no pass layer and reads the image the camera draws, by the same name
+ const screen = out.find((p) => p.type === "Mesh" && String(p.props.name).includes("screen"))!;
+ expect(screen.props.layers).toBeUndefined();
+ const map = flat(screen.children ?? []).map((c) => c.props.map).find((m) => typeof m === "string");
+ expect(map).toBe(cam.props.target as string);
+ });
+
+ test("is the frame's own: a render of frame 3 has the one pass frame 3 drew, not one for each frame stepped", () => {
+ const out = partsOf(() => <Fbo />, 3);
+ expect(out.filter((p) => typeof p.props.target === "string").length).toBe(1);
+ expect(out.filter((p) => p.type === "Mesh" && String(p.props.name).includes("knot")).length).toBe(1);
+ });
+
+ test("takes its scene as it was when drawn: a quad drawn twice with another uniform is two passes, each its own", () => {
+ function Twice() {
+ const a = useMemo(() => new THREE.WebGLRenderTarget(32, 32, { type: THREE.HalfFloatType }), []);
+ const b = useMemo(() => new THREE.WebGLRenderTarget(32, 32, { type: THREE.HalfFloatType }), []);
+ const mat = useMemo(() => new THREE.ShaderMaterial({ uniforms: { k: { value: 0 } }, vertexShader: "void main() { gl_Position = vec4(position, 1.0); }", fragmentShader: "uniform float k; void main() { gl_FragColor = vec4(k); }" }), []);
+ const quad = useMemo(() => new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat), [mat]);
+ const cam = useMemo(() => new THREE.Camera(), []);
+ useFrame(({ gl }) => {
+ mat.uniforms.k.value = 0.25;
+ gl.setRenderTarget(a);
+ gl.render(quad, cam);
+ mat.uniforms.k.value = 0.75;
+ gl.setRenderTarget(b);
+ gl.render(quad, cam);
+ gl.setRenderTarget(null);
+ });
+ return null;
+ }
+ const out = partsOf(() => <Twice />);
+ const cams = out.filter((p) => typeof p.props.target === "string");
+ expect(cams.length).toBe(2);
+ // a float target's image is a float one, and a bare THREE.Camera's pass is drawn by an orthographic one over the quad
+ for (const c of cams) {
+ expect(c.props.target).toMatch(/:32x32:float$/);
+ expect(c.type).toBe("OrthographicCamera");
+ }
+ expect(cams[0].props.order as number).toBeLessThan(cams[1].props.order as number);
+ const k = (layer: number) => {
+ const quad = out.find((p) => p.type === "Mesh" && (p.props.layers as number[] | undefined)?.[0] === layer)!;
+ return flat(quad.children ?? []).map((c) => (c.props.uniforms as { k?: number } | undefined)?.k).find((v) => v !== undefined);
+ };
+ expect(k((cams[0].props.layers as number[])[0])).toBe(0.25);
+ expect(k((cams[1].props.layers as number[])[0])).toBe(0.75);
+ });
+});