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.

R3F25 (part): three/webgpu's PostProcessing as raea's effects, an additive Bloom, a FramePass's frame() clamped to its Viewport

shinyobjectz80d07fda076c
diff --git a/docs/manual/reference/sdk/3d.md b/docs/manual/reference/sdk/3d.md
index 143105ff..1124751f 100644
--- a/docs/manual/reference/sdk/3d.md
+++ b/docs/manual/reference/sdk/3d.md
@@ -1355,6 +1355,7 @@ as bevy_light's ShadowFilteringMethod or bevy_pbr's ScreenSpaceReflections), app
| `threshold` | `number` | only what's brighter than this glows (0 = everything a little; 1 = only emissive parts and highlights) |
| `skip` | `string[]` | composition passes (a part's `pass`) left out of it: they neither glow nor take the glow |
| `passes` | `Record<string, number>` | each named pass's share of it, 0 (as skip) to 1 (all of it, as "scene" has) |
+| `additive` | `boolean` | the glow added on top of the frame, brightening it, as three.js's and postprocessing's bloom do; by default it takes its light from around the bright parts (Bevy's energy-conserving bloom) |
### `BodyProps`
diff --git a/docs/manual/reference/sdk/post_process.md b/docs/manual/reference/sdk/post_process.md
index 925c217f..1405e1be 100644
--- a/docs/manual/reference/sdk/post_process.md
+++ b/docs/manual/reference/sdk/post_process.md
@@ -150,6 +150,7 @@ Takes [`ToneMappingProps`](3d.md#tonemappingprops)'s props.
| `threshold` | `number` | only what's brighter than this glows (0 = everything a little; 1 = only emissive parts and highlights) |
| `skip` | `string[]` | composition passes (a part's `pass`) left out of it: they neither glow nor take the glow |
| `passes` | `Record<string, number>` | each named pass's share of it, 0 (as skip) to 1 (all of it, as "scene" has) |
+| `additive` | `boolean` | the glow added on top of the frame, brightening it, as three.js's and postprocessing's bloom do; by default it takes its light from around the bright parts (Bevy's energy-conserving bloom) |
### `ComputeProps`
diff --git a/docs/r3f.feature b/docs/r3f.feature
index a92e370b..6c792a14 100644
--- a/docs/r3f.feature
+++ b/docs/r3f.feature
@@ -554,9 +554,18 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
frame's foot). three's tone exposure (toneMappingExposure, ACES's 1/0.6) is a Grade `exposure`, Bevy's colour
grading on every pixel before the curve (new: grade_exposure), not the camera's, which skipped unlit colours (0.74
stops dark under ACES) and made effects before a composer's ToneMapping read lit and unlit pixels in two scales.
- in-post2 0.9879, in-post3 0.9767; the full parity list unchanged. Left: Outline (selected meshes in a composition
- pass, once scene.ts is free), Texture, Depth, LUT1D, three/webgpu's PostProcessing (in-tslpost), and the
- background under a composer's ToneMapping (three maps it, raea shows it as given)
+ in-post2 0.9879, in-post3 0.9767; the full parity list unchanged. three/webgpu's PostProcessing (RenderPipeline):
+ its render() hands the stand-in renderer a QuadMesh whose fragmentNode is the chain, read for its pass(scene,
+ camera), which raea draws as the frame, and its nodes in the order the frame goes through them
+ (src/input/tsl-post.ts): bloom as a Bloom added on top (new: Bloom `additive`, bloom_additive, Bevy's additive
+ composite; three's UnrealBloom brightens where Bevy's natural bloom trades light), GTAO, DOF, FXAA, SMAA (TRAA as
+ SMAA), SSAA and pixelation passes as raea's, film, dotScreen, rgbShift, chromaticAberration, lut3D, sepia and
+ bleach as FramePasses doing what their setup() builds (effects-tsl.ts), the output's tone mapping and exposure as
+ raea's; the other display nodes and an Fn of the app's own are named once (kinds.ts TSL_POST covers every node
+ three ships). A FramePass's frame() read past the edge now takes the edge pixel, not the tag row under the
+ Viewport. in-tslpost 0.9737 (bloom), in-tslpost2 0.9233 (sepia, chromatic aberration). Left: Outline (selected
+ meshes in a composition pass, once scene.ts is free), Texture, Depth, LUT1D, and the background under a
+ composer's or a PostProcessing's tone mapping (three maps it, raea shows it as given)
Scenario: R3F26. <R3F> in a box smaller than the page (#130)
Given an <R3F> in a box of its own inside a larger page
diff --git a/runtime/look/src/post.rs b/runtime/look/src/post.rs
index 60276acd..419f3a11 100644
--- a/runtime/look/src/post.rs
+++ b/runtime/look/src/post.rs
@@ -128,6 +128,10 @@ pub fn frame_post(its: &[Item]) -> BTreeMap<String, V> {
if let Some(s) = shares(b) {
row.insert("bloom_passes".into(), V::S(s));
}
+ // three.js's and postprocessing's bloom: the glow added on top, not traded for the light around it
+ if b.get("additive") == Some(&Value::Bool(true)) {
+ row.insert("bloom_additive".into(), V::N(1.0));
+ }
}
if let Some(f) = first("fog") {
row.insert("fog_color".into(), V::S(hex(f.get("color")).unwrap_or("#808080".into())));
@@ -348,6 +352,13 @@ mod tests {
assert!(row.contains_key("bloom") && row.get("tonemap") == Some(&V::S("agx".into())));
assert!(!row.contains_key("frame_sets") && p.keys.is_empty());
}
+
+ #[test]
+ fn an_additive_bloom_says_so_and_a_natural_one_doesnt() {
+ let row = frame_post(&[item("bloom", serde_json::json!({"intensity": 2.0, "additive": true}))]);
+ assert_eq!(row.get("bloom_additive"), Some(&V::N(1.0)));
+ assert!(!frame_post(&[item("bloom", serde_json::json!({"intensity": 2.0}))]).contains_key("bloom_additive"));
+ }
}
/// What a live frame's light sets (as_table) are made from: each light's colour, shadows, shafts and own biases, and the
diff --git a/runtime/scene3d/src/lib.rs b/runtime/scene3d/src/lib.rs
index 7a4ddc59..1da32ac1 100644
--- a/runtime/scene3d/src/lib.rs
+++ b/runtime/scene3d/src/lib.rs
@@ -5,7 +5,7 @@
//!
//! Columns (all optional; the defaults are what the engine drew before these existed):
//! camera: x y z look_x look_y look_z fov near far, ambient ambient_color, bloom (intensity, 0 = none)
-//! bloom_threshold, fog_color fog_start fog_end | fog_density, tonemap ('aces' 'agx' 'tony' 'reinhard'
+//! bloom_threshold bloom_additive, fog_color fog_start fog_end | fog_density, tonemap ('aces' 'agx' 'tony' 'reinhard'
//! 'none'), exposure (EV100), grade_temperature grade_tint grade_saturation, grade_{s,m,h}_{saturation,
//! contrast,gamma,gain,lift} (shadows, midtones, highlights), vignette vignette_radius vignette_smooth
//! vignette_color, aberration, vfog (1: volumetric fog) vfog_steps vfog_dither vfog_resolution vfog_ambient vfog_ambient_color, ssao
diff --git a/sdk/guides/craft/bevy/r3f.md b/sdk/guides/craft/bevy/r3f.md
index 57eb3639..fea93122 100644
--- a/sdk/guides/craft/bevy/r3f.md
+++ b/sdk/guides/craft/bevy/r3f.md
@@ -90,8 +90,11 @@ by raea); TSL node materials, unlit and lit (0.1.5); textures, environment maps,
that raea has (bloom, vignette, depth of field and bokeh, chromatic aberration, lens distortion, SSAO,
anti-aliasing, pixelation, tone mapping, brightness, contrast, hue and saturation), and, as raea frame passes running
the effect's own shader (0.1.5), noise, scanlines, sepia, dot screen, colour average and depth, grid, glitch, shock
-wave, LUT, ASCII and `<TiltShift2>`. Close, not exact: hemisphere lights, light probes, Phong and toon materials,
-`<TiltShift>` and `<GodRays>`.
+wave, LUT, ASCII and `<TiltShift2>`; three/webgpu's `PostProcessing` (`RenderPipeline`, 0.1.5): its
+`pass(scene, camera)` is the frame, its bloom, GTAO, depth of field, FXAA, SMAA and pixelation nodes are raea's, and
+its film, dot screen, RGB shift, chromatic aberration, LUT, sepia and bleach nodes are frame passes; an `Fn` of the
+chain's own isn't run. Close, not exact: hemisphere lights, light probes, Phong and toon materials, `<TiltShift>` and
+`<GodRays>`, and bloom (raea's, added on top as three's is).
What raea can't draw is named once in the render's output (`raea/r3f: ...`), and the frame draws without it:
diff --git a/sdk/r3f/src/input/effects-tsl.ts b/sdk/r3f/src/input/effects-tsl.ts
new file mode 100644
index 00000000..fbf9a693
--- /dev/null
+++ b/sdk/r3f/src/input/effects-tsl.ts
@@ -0,0 +1,72 @@
+// three/webgpu's post nodes (three/addons/tsl/display) that read only the frame, as raea FramePasses doing what each
+// node's setup() builds (docs/r3f.feature R3F25). tsl-post.ts finds them in a PostProcessing's graph and hands them to
+// post.ts as effects named by the node, their values as uniforms. A node's uv is WebGPU's, y down as raea's frame()
+// reads it: `t` below. Each replaces the frame (NORMAL at full opacity), as the node's output does.
+import type { Spec } from "./effects";
+import { SAMPLED } from "./effects-sampled";
+
+const T = "let t = vec2<f32>(p.x, 1.0 - p.y);";
+
+export const TSL: Record<string, Spec> = {
+ // film(): the colour plus itself times clamp(rand(fract(uv + time)) + 0.1), mixed in by its intensity (-1: none given)
+ FilmNode: {
+ uniforms: ["intensity"],
+ body: `${T}
+ let n = clamp(pp_rand(fract(t + u_time())) + 0.1, 0.0, 1.0);
+ let film = c.rgb + c.rgb * n;
+ o = vec4<f32>(select(mix(c.rgb, film, u_intensity()), film, u_intensity() < 0.0), c.a);`,
+ },
+ // dotScreen(): the grey's contrast raised against a pattern of dots turned by angle, in pixels times scale
+ DotScreenNode: {
+ uniforms: ["angle", "scale"],
+ body: `${T}
+ let q = t * u_resolution();
+ let sc = vec2<f32>(sin(u_angle()), cos(u_angle()));
+ let pt = vec2<f32>(sc.y * q.x - sc.x * q.y, sc.x * q.x + sc.y * q.y) * u_scale();
+ o = vec4<f32>(vec3<f32>((c.r + c.g + c.b) / 3.0 * 10.0 - 5.0 + sin(pt.x) * sin(pt.y) * 4.0), c.a);`,
+ },
+ // rgbShift(): red read amount along angle, blue as far the other way
+ RGBShiftNode: {
+ uv: true,
+ uniforms: ["amount", "angle"],
+ body: `${T}
+ let d = vec2<f32>(cos(u_angle()), sin(u_angle())) * u_amount();
+ let ga = frame(t);
+ o = vec4<f32>(frame(t + d).r, ga.g, frame(t - d).b, ga.a);`,
+ },
+ // chromaticAberration(): red scaled out from the centre and blue in, each further the farther from it
+ ChromaticAberrationNode: {
+ uv: true,
+ uniforms: ["strength", "center", "scale"],
+ body: `${T}
+ let off = t - u_center();
+ let k = u_scale() * 0.02 * u_strength();
+ let ab = u_strength() * length(off) * 0.01;
+ let rr = frame(u_center() + off * (1.0 + k) + off * ab).r;
+ let bb = frame(u_center() + off * (1.0 - k) - off * ab).b;
+ o = vec4<f32>(rr, frame(t).g, bb, frame(t).a);`,
+ },
+ // sepia() (Sepia.js): glfx's sepia weights
+ sepia: {
+ uniforms: [],
+ body: "o = vec4<f32>(dot(c.rgb, vec3<f32>(0.393, 0.769, 0.189)), dot(c.rgb, vec3<f32>(0.349, 0.686, 0.168)), dot(c.rgb, vec3<f32>(0.272, 0.534, 0.131)), c.a);",
+ },
+ // bleach() (BleachBypass.js): a multiply below mid-grey and a screen above it, by the luminance, mixed by its amount
+ bleach: {
+ uniforms: ["amount"],
+ body: `let lum = dot(c.rgb, vec3<f32>(0.2126, 0.7152, 0.0722));
+ let l = clamp(10.0 * (lum - 0.45), 0.0, 1.0);
+ let nc = mix(2.0 * lum * c.rgb, 1.0 - 2.0 * (1.0 - lum) * (1.0 - c.rgb), l);
+ let a2 = c.a * u_amount();
+ o = vec4<f32>(a2 * nc + c.rgb * (1.0 - a2), c.a);`,
+ },
+ // lut3D(): the colour looked up in its 3D table (as postprocessing's LUT3DEffect, without its sRGB round trip: the
+ // node reads the colour as the graph has it), mixed in by its intensity
+ Lut3DNode: {
+ ...SAMPLED.LUT3DEffect,
+ srgb: false,
+ uniforms: ["intensity"],
+ body: `${SAMPLED.LUT3DEffect.body}
+ o = mix(c, o, u_intensity());`,
+ },
+};
diff --git a/sdk/r3f/src/input/effects.ts b/sdk/r3f/src/input/effects.ts
index b833940d..7574aafa 100644
--- a/sdk/r3f/src/input/effects.ts
+++ b/sdk/r3f/src/input/effects.ts
@@ -6,14 +6,9 @@
// it when it comes after a <ToneMapping>. The effects that read the frame elsewhere, a texture or the depth are in
// effects-sampled.ts.
import type * as THREE from "three";
-import { FramePass } from "raea/3d";
-import { COMPONENTS } from "../parts";
import type { Part } from "./material";
import { SAMPLED } from "./effects-sampled";
-
-// raea's <FramePass> among the components a part may name (here until parts.tsx's table takes it: lane r3f-tsl has
-// that table open for R3F22's <Compute>)
-COMPONENTS.FramePass ??= FramePass;
+import { TSL } from "./effects-tsl";
/** an effect of pmndrs' postprocessing, as post.ts reads it */
export interface PPEffect {
@@ -141,7 +136,7 @@ const BODIES: Record<string, Spec> = {
},
};
-const SPECS: Record<string, Spec> = { ...BODIES, ...SAMPLED };
+const SPECS: Record<string, Spec> = { ...BODIES, ...SAMPLED, ...TSL };
/** the effects this module draws */
export const FRAME_EFFECTS = new Set(Object.keys(SPECS));
diff --git a/sdk/r3f/src/input/kinds.ts b/sdk/r3f/src/input/kinds.ts
index 0a239192..6d85fc59 100644
--- a/sdk/r3f/src/input/kinds.ts
+++ b/sdk/r3f/src/input/kinds.ts
@@ -96,3 +96,20 @@ export const EFFECTS: Record<string, { status: InputStatus; raea: string; note?:
GodRaysEffect: { status: "near", raea: "FramePass: rays streaked from the sun's disc on screen, where the depth prepass has nothing nearer", note: "its light source's own mask and the rays' blur aren't drawn" },
...Object.fromEntries(["LUT1DEffect", "TextureEffect", "DepthEffect", "OutlineEffect"].map((k) => [k, { status: "none" as const, raea: "left out, named once", note: "write it as a raea <FramePass> (WESL) outside <R3F>" }])),
};
+
+/** three/webgpu's post nodes (three/addons/tsl/display) in a PostProcessing (RenderPipeline), and the raea effect each
+ * becomes (tsl-post.ts). The chain starts from its scene pass, which raea draws; its output's tone mapping is raea's.
+ * The arithmetic joining nodes is taken as the raea effect's own blend; an Fn of the app's own isn't run. */
+export const TSL_POST: Record<string, { status: InputStatus; raea: string; note?: string }> = {
+ PassNode: { status: "drawn", raea: "the frame: its scene seen by its camera" },
+ BloomNode: { status: "near", raea: "Bloom, added on top (additive: strength x 4 as its intensity, its threshold)", note: "Bevy's bloom, not three's mip blur: a glow of its own size" },
+ GTAONode: { status: "near", raea: "AmbientOcclusion (Bevy's SSAO)" },
+ DepthOfFieldNode: { status: "near", raea: "DepthOfField bokeh (focusDistance as focus, bokehScale as its blur)" },
+ FXAANode: { status: "drawn", raea: "AntiAliasing fxaa" },
+ SMAANode: { status: "drawn", raea: "AntiAliasing smaa" },
+ ...Object.fromEntries(["TRAANode", "TAAUNode"].map((k) => [k, { status: "near" as const, raea: "AntiAliasing smaa", note: "temporal anti-aliasing needs the frames before: raea draws a frame from that frame alone" }])),
+ SSAAPassNode: { status: "near", raea: "its scene pass, AntiAliasing msaa" },
+ PixelationPassNode: { status: "near", raea: "its scene pass, Look pixel (pixelSize as the cell)", note: "its normal and depth edges aren't drawn" },
+ ...Object.fromEntries(["FilmNode", "DotScreenNode", "RGBShiftNode", "ChromaticAberrationNode", "Lut3DNode", "sepia", "bleach"].map((k) => [k, { status: "drawn" as const, raea: "FramePass: what its setup() builds, in WGSL (effects-tsl.ts)" }])),
+ ...Object.fromEntries(["AfterImageNode", "AnaglyphPassNode", "BilateralBlurNode", "DenoiseNode", "FSR1Node", "GaussianBlurNode", "GodraysNode", "LensflareNode", "OutlineNode", "ParallaxBarrierPassNode", "RecurrentDenoiseNode", "RetroPassNode", "SharpenNode", "SobelOperatorNode", "SSGINode", "SSRNode", "SSSNode", "StereoCompositePassNode", "StereoPassNode", "TemporalReprojectNode", "TransitionNode"].map((k) => [k, { status: "none" as const, raea: "left out, named once", note: "write it as a raea <FramePass> (WESL) outside <R3F>" }])),
+};
diff --git a/sdk/r3f/src/input/lights.ts b/sdk/r3f/src/input/lights.ts
index 5bfafb6a..cf39b981 100644
--- a/sdk/r3f/src/input/lights.ts
+++ b/sdk/r3f/src/input/lights.ts
@@ -1,9 +1,7 @@
// three.js's lights, cameras, fog and environment as raea's parts, in world space (raea places a light and the camera
// by position and target, not inside a group). Intensities go through units.ts: a three light and the raea light it
// becomes put the same light on screen.
-import { Fragment } from "react";
import * as THREE from "three";
-import { COMPONENTS } from "../parts";
import { toRaea, stopsOf } from "../units";
import type { Part, Props } from "./material";
import { srcOf } from "./texture";
@@ -190,7 +188,6 @@ export function skyOf(scene: THREE.Scene, gl?: THREE.WebGLRenderer, webgpu = fal
export function toneParts(mode: string, stops: number): Part {
const tone: Part = { type: "ToneMapping", props: { mode } };
if (stops === 0) return tone;
- COMPONENTS.Fragment ??= Fragment as unknown as (typeof COMPONENTS)[string];
return { type: "Fragment", props: {}, children: [tone, { type: "Grade", props: { exposure: stops } }] };
}
diff --git a/sdk/r3f/src/input/post.ts b/sdk/r3f/src/input/post.ts
index 6abc6dd8..e636463b 100644
--- a/sdk/r3f/src/input/post.ts
+++ b/sdk/r3f/src/input/post.ts
@@ -12,6 +12,7 @@
import type * as THREE from "three";
import type { Part, Props } from "./material";
import { framePass, type PPEffect } from "./effects";
+import { pipelineOf } from "./tsl-post";
const warned = new Set<string>();
function warnOnce(k: string, why: string) {
@@ -58,6 +59,12 @@ export function composerEffects(scene: THREE.Scene): { found: boolean; effects:
}
}
});
+ // three/webgpu's PostProcessing drawn from this scene's pass: its chain (tsl-post.ts), at its own clock in a program
+ const tsl = pipelineOf(scene);
+ if (tsl) {
+ root = { time: tsl.time ?? root.time, size: tsl.time === undefined ? root.size : tsl.size, camera: tsl.camera };
+ return { found: true, effects: tsl.effects };
+ }
return { found, effects };
}
@@ -77,6 +84,11 @@ export function postParts(effects: unknown[]): { parts: Part[]; tone?: Part } {
continue;
}
const e = raw as Effect;
+ // one of raea's own effects, as a PostProcessing's node gives it (tsl-post.ts)
+ if (e.name === "RaeaPart") {
+ parts.push(e.part as Part);
+ continue;
+ }
// a blend of SKIP (BlendFunction 9, DST) draws nothing; an effect's opacity scales it
if (e.blendMode?.blendFunction === 9) continue;
const share = num(e.blendMode?.opacity?.value, 1);
@@ -114,7 +126,9 @@ export function postParts(effects: unknown[]): { parts: Part[]; tone?: Part } {
// three's ACES scales its input by 1/0.6 where Bevy's doesn't: as the Grade's exposure, on every pixel just before
// the curve (lights.ts's toneParts), so the effects before it see three's values
tone = { type: "ToneMapping", props: { mode } };
- if (mode === "aces") grade.exposure = Math.log2(1 / 0.6);
+ // and three's own exposure, from a PostProcessing's output (tsl-post.ts)
+ const k = num(e.exposure, 1) / (mode === "aces" ? 0.6 : 1);
+ if (k !== 1) grade.exposure = Math.log2(k);
mapped = true;
break;
}
diff --git a/sdk/r3f/src/input/program.ts b/sdk/r3f/src/input/program.ts
index 206008e9..313c69fd 100644
--- a/sdk/r3f/src/input/program.ts
+++ b/sdk/r3f/src/input/program.ts
@@ -9,6 +9,7 @@
import * as THREE from "three";
import { standInRenderer, warnOnce } from "./renderer";
import { nextRandom, seedOf } from "./seed";
+import { recordPipeline } from "./tsl-post";
type Rec = Record<string | symbol, any>;
type Loop = (time: number) => void;
@@ -151,7 +152,9 @@ export function standIn(params: { canvas?: unknown } | undefined, webgpu: boolea
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;
+ // three/webgpu's PostProcessing: the scene its chain starts from, the chain recorded at the run's clock (tsl-post.ts)
+ const p = recordPipeline(scene, self as unknown as THREE.WebGLRenderer, run.now / 1000);
+ run.drawn = p ? { ...p, gl: d.gl } : d;
};
const own: Rec = {
domElement: params?.canvas ?? run?.canvas ?? programCanvas(300, 150),
diff --git a/sdk/r3f/src/input/renderer.ts b/sdk/r3f/src/input/renderer.ts
index 884c6b73..8b56148b 100644
--- a/sdk/r3f/src/input/renderer.ts
+++ b/sdk/r3f/src/input/renderer.ts
@@ -4,6 +4,7 @@
import * as THREE from "three";
import { renderInto } from "./targets";
import { Dispatches } from "./tsl-compute";
+import { recordPipeline } from "./tsl-post";
const warned = new Set<string>();
export function warnOnce(k: string, why: string) {
@@ -66,6 +67,10 @@ export function standInRenderer(): THREE.WebGLRenderer {
// 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));
+ // three/webgpu's PostProcessing draws its quad to the screen: its chain is recorded for the scene it starts from,
+ // which R3F's frame is (tsl-post.ts, docs/r3f.feature R3F25)
+ const into = own.render as (scene: THREE.Object3D, camera: THREE.Camera) => void;
+ own.render = (scene: THREE.Object3D, camera: THREE.Camera) => (target ? into(scene, camera) : void recordPipeline(scene, 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/tsl-post.ts b/sdk/r3f/src/input/tsl-post.ts
new file mode 100644
index 00000000..42abf797
--- /dev/null
+++ b/sdk/r3f/src/input/tsl-post.ts
@@ -0,0 +1,157 @@
+// three/webgpu's PostProcessing (its RenderPipeline) as raea's frame effects (docs/r3f.feature R3F25). Its render()
+// draws one full-screen quad (a QuadMesh) whose material's fragmentNode is the whole chain; the stand-in renderer hands
+// that quad here. Its graph is read for the scene pass it starts from (a `pass(scene, camera)`), which raea draws as
+// the frame, and for the nodes the frame goes through, in order, each becoming the raea effect that does the same,
+// as a composer's effects do (post.ts): bloom, ambient occlusion, depth of field, anti-aliasing and pixelation as
+// raea's own, the nodes reading only the frame as FramePasses (effects-tsl.ts), the output's tone mapping as raea's.
+// The arithmetic joining them (`scenePassColor.add(bloomPass)`) is taken as the raea effect's own blend; a node raea
+// has nothing for is named once and left out.
+import * as THREE from "three";
+import { TSL_POST } from "./kinds";
+
+interface N {
+ isNode?: boolean;
+ value?: unknown;
+ getChildren?: () => Iterable<N>;
+ [k: string]: unknown;
+}
+
+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}`);
+}
+
+/** what a pipeline was last seen running a scene through: post.ts's effects, and the clock and size they're drawn at
+ * (a plain program's; R3F's own are read from its scene) */
+export interface Pipeline {
+ effects: unknown[];
+ time?: number;
+ size: [number, number];
+ camera: THREE.Camera;
+}
+
+const pipelines = new WeakMap<object, Pipeline>();
+
+/** the pipeline last drawn from `scene`'s pass, if one was */
+export function pipelineOf(scene: object): Pipeline | undefined {
+ return pipelines.get(scene);
+}
+
+// an Fn's call is a plain Node by its static type: its class's name
+const typeOf = (n: N) => (n.isShaderCallNodeInternal === true ? "ShaderCallNodeInternal" : ((n.constructor as { type?: string }).type ?? n.constructor.name));
+/** a uniform's or a constant's number (or a plain number) */
+const num = (n: unknown, d: number) => {
+ const v = (n as N | null)?.isNode ? (n as N).value : n;
+ return typeof v === "number" && Number.isFinite(v) ? v : d;
+};
+const vec2 = (n: unknown, d: [number, number]): [number, number] => {
+ const v = ((n as N | null)?.isNode ? (n as N).value : n) as { x?: number; y?: number } | null;
+ return typeof v?.x === "number" && typeof v.y === "number" ? [v.x, v.y] : d;
+};
+/** an effect post.ts draws as a FramePass (effects-tsl.ts's spec by `name`), replacing the frame */
+const effect = (name: string, uniforms: Record<string, unknown>) => ({ name, blendMode: { blendFunction: 23, opacity: { value: 1 } }, uniforms: new Map(Object.entries(uniforms).map(([k, value]) => [k, { value }])) });
+/** one of raea's own effects, as it is */
+const part = (type: string, props: Record<string, unknown>) => ({ name: "RaeaPart", part: { type, props } });
+
+/** three's tone mappings as postprocessing's ToneMappingMode (post.ts's TONE): Linear and Custom draw untonemapped */
+const MODES: Record<number, number> = { [THREE.ReinhardToneMapping]: 1, [THREE.CineonToneMapping]: 5, [THREE.ACESFilmicToneMapping]: 6, [THREE.AgXToneMapping]: 7, [THREE.NeutralToneMapping]: 8 };
+
+/** the display nodes raea has nothing for yet (kinds.ts TSL_POST) */
+const NONE = new Set(Object.entries(TSL_POST).filter(([, k]) => k.status === "none").map(([n]) => n));
+
+/** What a QuadMesh drawn to the screen shows when it is a PostProcessing's: the scene and camera of the pass it starts
+ * from, its chain recorded for that scene (null for any other quad). `gl` is the renderer it's drawn with, `time` a
+ * plain program's clock in seconds (TSL's `time`). */
+export function recordPipeline(quad: unknown, gl: THREE.WebGLRenderer, time?: number): { scene: THREE.Object3D; camera: THREE.Camera } | null {
+ const out = (quad as { isQuadMesh?: boolean; material?: { fragmentNode?: N } }).material?.fragmentNode;
+ if (!(quad as { isQuadMesh?: boolean }).isQuadMesh || !out?.isNode) return null;
+ const effects: unknown[] = [];
+ const seen = new Set<N>();
+ let pass: { scene: THREE.Object3D; camera: THREE.Camera } | null = null;
+ let pipeline: { _toneMapping?: number } | null = null;
+ const read = (n: N) => {
+ const type = typeOf(n);
+ if (n.isPassNode === true) {
+ const p = { scene: n.scene as THREE.Object3D, camera: n.camera as THREE.Camera };
+ if (!pass) pass = p;
+ else if (p.scene !== pass.scene) warnOnce("a second pass(scene, camera)", "in one PostProcessing: raea draws the first one's scene, and the others' aren't drawn");
+ if (type === "PixelationPassNode") {
+ effects.push(part("Look", { mode: "pixel", pixelSize: Math.max(1, Math.round(num(n.pixelSize, 6))) }));
+ warnOnce("pixelationPass()'s edges", "aren't drawn: its cells are");
+ } else if (type === "SSAAPassNode") effects.push(part("AntiAliasing", { mode: "msaa" }));
+ return;
+ }
+ switch (type) {
+ case "BloomNode":
+ // three's UnrealBloom adds strength times its blurred mips (their radius-weighted factors sum to about 3): raea's
+ // Bloom, added on top too, at 4 times it (in-tslpost, SSIM 0.97)
+ effects.push(part("Bloom", { intensity: num(n.strength, 1) * 4, threshold: num(n.threshold, 0), additive: true }));
+ return;
+ case "GTAONode":
+ effects.push(part("AmbientOcclusion", { quality: "medium" }));
+ return;
+ case "DepthOfFieldNode":
+ effects.push(part("DepthOfField", { mode: "bokeh", focus: num(n.focusDistanceNode, 1), maxBlur: Math.max(1, Math.round(num(n.bokehScaleNode, 1) * 16)) }));
+ return;
+ case "FXAANode":
+ effects.push(part("AntiAliasing", { mode: "fxaa" }));
+ return;
+ case "SMAANode":
+ case "TRAANode":
+ case "TAAUNode":
+ // temporal ones too: raea draws a frame from that frame alone, so a render equals its play
+ effects.push(part("AntiAliasing", { mode: "smaa" }));
+ return;
+ case "FilmNode":
+ effects.push(effect(type, { intensity: n.intensityNode ? num(n.intensityNode, 1) : -1 }));
+ return;
+ case "DotScreenNode":
+ effects.push(effect(type, { angle: num(n.angle, 1.57), scale: num(n.scale, 1) }));
+ return;
+ case "RGBShiftNode":
+ effects.push(effect(type, { amount: num(n.amount, 0.005), angle: num(n.angle, 0) }));
+ return;
+ case "ChromaticAberrationNode":
+ effects.push(effect(type, { strength: num(n.strengthNode, 1), center: vec2(n.centerNode, [0.5, 0.5]), scale: num(n.scaleNode, 1.1) }));
+ return;
+ case "Lut3DNode":
+ effects.push(effect(type, { lut: (n.lutNode as N | undefined)?.value ?? null, intensity: num(n.intensityNode, 1) }));
+ return;
+ case "RenderOutputNode": {
+ // the output transform: the pipeline's tone mapping (the renderer's), with three's exposure
+ const tm = (n._toneMapping as number | null) ?? pipeline?._toneMapping ?? gl.toneMapping;
+ const mode = MODES[tm];
+ if (mode !== undefined) effects.push({ name: "ToneMappingEffect", blendMode: { blendFunction: 23 }, mode, exposure: gl.toneMappingExposure ?? 1 });
+ return;
+ }
+ case "ShaderCallNodeInternal": {
+ // an Fn's call: sepia() and bleach() are known by what their source holds
+ const src = String((n.shaderNode as { jsFunc?: unknown } | undefined)?.jsFunc ?? "");
+ const args = (n.rawInputs as unknown[] | undefined) ?? [];
+ if (/\.393\b/.test(src) && /\.769\b/.test(src)) effects.push(effect("sepia", {}));
+ else if (/\.45\b/.test(src) && /luminance/.test(src)) effects.push(effect("bleach", { amount: num(args[1], 1) }));
+ else warnOnce("an Fn of the app's own", "in a PostProcessing isn't run: raea draws the chain's known nodes and the frame without it");
+ return;
+ }
+ default:
+ if (NONE.has(type)) warnOnce(`three's ${type.replace(/Node$/, "")} node`, "in a PostProcessing has no raea counterpart yet: left out");
+ }
+ };
+ const visit = (n: N) => {
+ if (!n?.isNode || seen.has(n)) return;
+ seen.add(n);
+ const ctx = n.isContextNode === true ? (n.value as { renderPipeline?: { _toneMapping?: number } } | undefined) : undefined;
+ if (ctx?.renderPipeline) pipeline = ctx.renderPipeline;
+ for (const c of n.getChildren?.() ?? []) visit(c);
+ // after what it reads: the order the frame goes through them
+ read(n);
+ };
+ visit(out);
+ if (!pass) return null;
+ const { scene, camera } = pass as { scene: THREE.Object3D; camera: THREE.Camera };
+ const size = gl.getSize?.(new THREE.Vector2()) ?? new THREE.Vector2(1, 1);
+ pipelines.set(scene, { effects, time, size: [size.x, size.y], camera });
+ return { scene, camera };
+}
diff --git a/sdk/r3f/src/parts.tsx b/sdk/r3f/src/parts.tsx
index f73dd776..acb1251d 100644
--- a/sdk/r3f/src/parts.tsx
+++ b/sdk/r3f/src/parts.tsx
@@ -1,9 +1,9 @@
// raea's parts as React elements: each Part (a raea/3d component's name and its props, what the R3F input makes and
// the source export writes) drawn by that component. One table, so the input, the export and the tests name the same
// components.
-import type { ReactNode } from "react";
+import { Fragment, type ReactNode } from "react";
import {
- AmbientOcclusion, AntiAliasing, Bloom, BufferMesh, Compute, DepthOfField, Environment, Fog, Gizmo, Grade, Instances, LensDistortion, Look, RichText, ToneMapping,
+ AmbientOcclusion, AntiAliasing, Bloom, BufferMesh, Compute, DepthOfField, Environment, Fog, FramePass, Gizmo, Grade, Instances, LensDistortion, Look, RichText, ToneMapping,
} from "raea/3d";
import {
AmbientLight, DirectionalLight, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial,
@@ -16,10 +16,12 @@ export type { Part, Props } from "./input/material";
/** every component a Part may name */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const COMPONENTS: Record<string, (p: any) => ReactNode> = {
- AmbientLight, AmbientOcclusion, AntiAliasing, Bloom, BufferMesh, Compute, DepthOfField, DirectionalLight, Environment, Fog, Gizmo, Grade, Group, Instances,
+ AmbientLight, AmbientOcclusion, AntiAliasing, Bloom, BufferMesh, Compute, DepthOfField, DirectionalLight, Environment, Fog, FramePass, Gizmo, Grade, Group, Instances,
LensDistortion, Look, Mesh, MeshBasicMaterial,
MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, OrthographicCamera, PerspectiveCamera, PointLight,
RectAreaLight, RichText, SpotLight, ThreeShaderMaterial, ToneMapping,
+ // a tone mapping and the Grade carrying three's exposure (lights.ts toneParts)
+ Fragment: Fragment as unknown as (p: any) => ReactNode,
};
/** parts as elements, keyed by their place */
diff --git a/sdk/r3f/test/parity/fixtures.tsx b/sdk/r3f/test/parity/fixtures.tsx
index 99005b2c..0b2d615c 100644
--- a/sdk/r3f/test/parity/fixtures.tsx
+++ b/sdk/r3f/test/parity/fixtures.tsx
@@ -15,6 +15,7 @@ import inter from "./fonts/Inter-400.json";
export { OUTPUTS } from "./outputs";
import { TSL_INPUTS } from "./tsl";
import { POST2_INPUTS } from "./post2";
+import { TSLPOST_INPUTS } from "./tslpost";
export const SIZE = { width: 640, height: 360, fps: 24 };
@@ -381,6 +382,8 @@ export const INPUTS: Record<string, InputCase> = {
...TSL_INPUTS,
// postprocessing's effects raea draws as frame passes (R3F25): test/parity/post2.tsx
...POST2_INPUTS,
+ // three/webgpu's PostProcessing, its TSL chain as raea's effects (R3F25): test/parity/tslpost.tsx
+ ...TSLPOST_INPUTS,
};
const WAVE_VERTEX = /* glsl */ `
diff --git a/sdk/r3f/test/parity/tslpost.tsx b/sdk/r3f/test/parity/tslpost.tsx
new file mode 100644
index 00000000..ea073ca4
--- /dev/null
+++ b/sdk/r3f/test/parity/tslpost.tsx
@@ -0,0 +1,85 @@
+// The parity cases for three/webgpu's PostProcessing (docs/r3f.feature R3F25, src/input/tsl-post.ts): a lit scene
+// drawn through a TSL chain, by three/webgpu in Chrome (its WebGL 2 backend) and by raea, which draws the chain's scene
+// pass and maps its nodes to raea's effects. No node reads TSL's `time` (Chrome's would differ).
+import { useFrame, useThree } from "@react-three/fiber";
+import { useMemo } from "react";
+import * as THREE from "three";
+import { RenderPipeline } from "three/webgpu";
+import * as TSLTyped from "three/tsl";
+import * as BloomM from "three/examples/jsm/tsl/display/BloomNode.js";
+import * as AberrationM from "three/examples/jsm/tsl/display/ChromaticAberrationNode.js";
+import * as SepiaM from "three/examples/jsm/tsl/display/Sepia.js";
+import type { InputCase } from "./fixtures";
+
+// untyped: @types/three's chained TSL types make tsc take minutes and gigabytes
+type Fn = (...a: unknown[]) => any;
+const { pass } = TSLTyped as unknown as Record<string, Fn>;
+const [{ bloom }, { chromaticAberration }, { sepia }] = [BloomM, AberrationM, SepiaM] as unknown as Record<string, Fn>[];
+
+/** three's WebGPURenderer: its WebGL 2 backend (headless Chrome may have no WebGPU) */
+async function nodeRenderer(props: object) {
+ const { WebGPURenderer } = await import("three/webgpu");
+ const r = new WebGPURenderer({ ...props, forceWebGL: true, antialias: true });
+ await r.init();
+ return r;
+}
+
+/** the scene drawn through the chain `make` builds on its pass, in place of R3F's own render (useFrame's priority 1) */
+function Piped({ make }: { make: (color: any) => unknown }) {
+ const { gl, scene, camera } = useThree();
+ const pp = useMemo(() => {
+ const p = new RenderPipeline(gl as never);
+ p.outputNode = make(pass(scene, camera).getTextureNode("output")) as never;
+ return p;
+ }, [gl, scene, camera, make]);
+ useFrame(() => pp.render(), 1);
+ return null;
+}
+
+const scene = (
+ <>
+ <color attach="background" args={["#10131a"]} />
+ <ambientLight intensity={0.4} />
+ <directionalLight position={[2, 5, 1]} intensity={2.5} />
+ <mesh position={[-0.9, 0.6, 0]}>
+ <sphereGeometry args={[0.6, 32, 16]} />
+ <meshStandardMaterial color="#e05a2b" roughness={0.4} />
+ </mesh>
+ <mesh position={[0.9, 0.6, -0.4]}>
+ <torusKnotGeometry args={[0.4, 0.14, 128, 16]} />
+ <meshStandardMaterial color="#202a3a" emissive="#58c8ff" emissiveIntensity={4} />
+ </mesh>
+ <mesh rotation={[-Math.PI / 2, 0, 0]}>
+ <planeGeometry args={[8, 8]} />
+ <meshStandardMaterial color="#9aa3b0" roughness={0.9} />
+ </mesh>
+ </>
+);
+
+const bloomed = (color: any) => color.add(bloom(color, 0.8, 0.3, 0.9));
+const aged = (color: any) => chromaticAberration(sepia(color), 2, new THREE.Vector2(0.5, 0.5), 1.2);
+
+export const TSLPOST_INPUTS: Record<string, InputCase> = {
+ // three's own bloom on what's brighter than 0.9 (the glowing knot), added to the scene, then ACES (R3F's)
+ tslpost: {
+ canvas: { camera: { position: [0, 2, 4.5], fov: 45 }, gl: nodeRenderer },
+ frame: 6,
+ scene: () => (
+ <>
+ {scene}
+ <Piped make={bloomed} />
+ </>
+ ),
+ },
+ // sepia, then its colours split away from the centre, before the tone mapping
+ tslpost2: {
+ canvas: { camera: { position: [0, 2, 4.5], fov: 45 }, gl: nodeRenderer },
+ frame: 6,
+ scene: () => (
+ <>
+ {scene}
+ <Piped make={aged} />
+ </>
+ ),
+ },
+};
diff --git a/sdk/r3f/test/tsl-post.test.ts b/sdk/r3f/test/tsl-post.test.ts
new file mode 100644
index 00000000..039b48f6
--- /dev/null
+++ b/sdk/r3f/test/tsl-post.test.ts
@@ -0,0 +1,104 @@
+// three/webgpu's PostProcessing as raea's frame effects (src/input/tsl-post.ts, docs/r3f.feature R3F25): a plain
+// program's pipeline drawn by the stand-in renderer, its graph read for the scene pass and the nodes after it.
+import { expect, test } from "bun:test";
+import * as THREE from "three";
+import * as TSLTyped from "three/tsl";
+import * as BloomM from "three/examples/jsm/tsl/display/BloomNode.js";
+import * as FilmM from "three/examples/jsm/tsl/display/FilmNode.js";
+import * as FXAAM from "three/examples/jsm/tsl/display/FXAANode.js";
+import * as SepiaM from "three/examples/jsm/tsl/display/Sepia.js";
+import * as OutlineM from "three/examples/jsm/tsl/display/OutlineNode.js";
+import { composerEffects, postParts } from "../src/input/post";
+import { drawnOf, programCanvas, startRun, stepRun } from "../src/input/program";
+import { PostProcessing, WebGPURenderer } from "../src/input/vanilla-webgpu";
+import type { Part } from "../src/parts";
+
+const FPS = 24;
+// untyped: @types/three's chained TSL types make tsc take minutes and gigabytes
+type Fn = (...a: unknown[]) => any;
+const { pass, uniform, renderOutput } = TSLTyped as unknown as Record<string, Fn>;
+const [{ bloom }, { film }, { fxaa }, { sepia }, { outline }] = [BloomM, FilmM, FXAAM, SepiaM, OutlineM] as unknown as Record<string, Fn>[];
+
+/** a program drawing `scene` through the PostProcessing `chain` makes, stepped to frame 2 */
+async function piped(chain: (scenePass: any, pp: PostProcessing) => void, tone: THREE.ToneMapping = THREE.ACESFilmicToneMapping) {
+ const scene = new THREE.Scene();
+ scene.add(new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshBasicMaterial()));
+ const camera = new THREE.PerspectiveCamera(45, 16 / 9, 0.1, 100);
+ const run = startRun(`pp-${Math.random()}`, async (c) => {
+ const renderer = new WebGPURenderer({ canvas: c });
+ await renderer.init();
+ renderer.setSize(640, 360);
+ renderer.toneMapping = tone;
+ renderer.toneMappingExposure = 1.5;
+ const pp = new PostProcessing(renderer);
+ chain(pass(scene, camera), pp);
+ renderer.setAnimationLoop(() => pp.render());
+ }, programCanvas(640, 360));
+ await run.waiting;
+ stepRun(run, 2, FPS);
+ return { run, scene, camera };
+}
+
+const of = (parts: Part[], type: string) => parts.filter((p) => p.type === type);
+
+test("the scene its pass draws is the frame, and bloom, film and the output's tone are raea's", async () => {
+ const strength = uniform(0.8);
+ const { run, scene, camera } = await piped((sp, pp) => {
+ const color = sp.getTextureNode("output");
+ pp.outputNode = film(color.add(bloom(color, strength, 0.2, 0.6)), uniform(0.4));
+ });
+ const d = drawnOf(run)!;
+ expect(d.scene).toBe(scene);
+ expect(d.camera).toBe(camera);
+ const found = composerEffects(scene);
+ expect(found.found).toBe(true);
+ const { parts, tone } = postParts(found.effects);
+ expect(of(parts, "Bloom")[0].props).toEqual({ intensity: 3.2, threshold: 0.6, additive: true });
+ const fp = of(parts, "FramePass");
+ expect(fp.length).toBe(1);
+ expect((fp[0].props as { uniforms: Record<string, number> }).uniforms.intensity).toBeCloseTo(0.4);
+ // effects before the output's tone mapping run on the linear frame
+ expect((fp[0].props as { at: string }).at).toBe("before-tonemap");
+ expect(tone!.props).toEqual({ mode: "aces" });
+ // three's exposure and its ACES's 1/0.6, every pixel before the curve
+ expect(of(parts, "Grade")[0].props.exposure as number).toBeCloseTo(Math.log2(1.5 / 0.6));
+});
+
+test("an effect after renderOutput() runs on the tone-mapped frame; sepia() is known by its weights", async () => {
+ const { scene } = await piped((sp, pp) => {
+ pp.outputColorTransform = false;
+ pp.outputNode = fxaa(sepia(renderOutput(sp)));
+ }, THREE.AgXToneMapping);
+ const { parts, tone } = postParts(composerEffects(scene).effects);
+ expect(tone!.props).toEqual({ mode: "agx" });
+ expect(of(parts, "AntiAliasing")[0].props).toEqual({ mode: "fxaa" });
+ const fp = of(parts, "FramePass");
+ expect(fp.length).toBe(1);
+ expect((fp[0].props as { at: string; wgsl: string }).at).toBe("after-tonemap");
+ expect((fp[0].props as { wgsl: string }).wgsl).toContain("0.393");
+});
+
+test("a node raea has nothing for is named once and left out, and the frame still draws", async () => {
+ const warn = console.warn;
+ const said: string[] = [];
+ console.warn = (s: string) => said.push(s);
+ try {
+ const { run, scene } = await piped((sp, pp) => {
+ const o = outline(sp.scene as THREE.Scene, sp.camera as THREE.Camera, { selectedObjects: [] });
+ pp.outputNode = sp.add(o);
+ });
+ expect(drawnOf(run)!.scene).toBe(scene);
+ postParts(composerEffects(scene).effects);
+ } finally {
+ console.warn = warn;
+ }
+ expect(said.some((s) => /Outline node/.test(s))).toBe(true);
+});
+
+test("every post node three ships is named, with what raea draws for it", async () => {
+ const { TSL_POST } = await import("../src/input/kinds");
+ const dir = new URL("../node_modules/three/examples/jsm/tsl/display/", import.meta.url).pathname;
+ const nodes = [...new Bun.Glob("*Node.js").scanSync(dir)].map((f) => f.replace(/\.js$/, ""));
+ expect(nodes.length).toBeGreaterThan(20);
+ expect(nodes.filter((k) => !TSL_POST[k])).toEqual([]);
+});
diff --git a/sdk/r3f/tools/parity.sh b/sdk/r3f/tools/parity.sh
index 38de51b0..a6b165ce 100755
--- a/sdk/r3f/tools/parity.sh
+++ b/sdk/r3f/tools/parity.sh
@@ -19,6 +19,8 @@ CASES+=(in-tsl-particles:12)
CASES+=(in-vanilla:24)
# postprocessing's effects as raea <FramePass>es (test/parity/post2.tsx), before and after an ACES tone mapping (R3F25)
CASES+=(in-post2:6 in-post3:6)
+# three/webgpu's PostProcessing: its scene pass and TSL nodes as raea's effects (test/parity/tslpost.tsx, R3F25)
+CASES+=(in-tslpost:6 in-tslpost2:6)
[ -z "${R3F_CASES:-}" ] || read -ra CASES <<<"$R3F_CASES"
mkdir -p "$OUT"
for c in "${CASES[@]}"; do
diff --git a/sdk/render/src/3d/effects.tsx b/sdk/render/src/3d/effects.tsx
index 941e9ae3..4f35558d 100644
--- a/sdk/render/src/3d/effects.tsx
+++ b/sdk/render/src/3d/effects.tsx
@@ -127,6 +127,9 @@ export interface BloomProps {
skip?: string[];
/** each named pass's share of it, 0 (as skip) to 1 (all of it, as "scene" has) */
passes?: Record<string, number>;
+ /** the glow added on top of the frame, brightening it, as three.js's and postprocessing's bloom do; by default it
+ * takes its light from around the bright parts (Bevy's energy-conserving bloom) */
+ additive?: boolean;
}
/** Glow around bright parts (emissive materials, strong highlights). Put it inside the Canvas3D.
diff --git a/systems/framepass/src/lib.rs b/systems/framepass/src/lib.rs
index 3b463bb0..061de04a 100644
--- a/systems/framepass/src/lib.rs
+++ b/systems/framepass/src/lib.rs
@@ -117,7 +117,11 @@ pub fn module(source: &str, uniforms: &[(String, &'static str)], textures: &[Str
@group(0) @binding(2) var<uniform> raea_pass: RaeaPass;\n\
// a uv over the camera's Viewport as one over the frame's texture (view: its size, then its corner, over the texture's)\n\
fn raea_view_uv(uv: vec2<f32>) -> vec2<f32> { return raea_pass.view.zw + uv * raea_pass.view.xy; }\n\
- fn frame(uv: vec2<f32>) -> vec4<f32> { return textureSampleLevel(raea_frame, raea_frame_sampler, raea_view_uv(uv), 0.0); }\n",
+ // read past its edge, the frame's edge pixel (as a clamped texture is), never the row under the Viewport\n\
+ fn frame(uv: vec2<f32>) -> vec4<f32> {\n\
+ \x20 let h = 0.5 / (vec2<f32>(textureDimensions(raea_frame)) * raea_pass.view.xy);\n\
+ \x20 return textureSampleLevel(raea_frame, raea_frame_sampler, raea_view_uv(clamp(uv, h, 1.0 - h)), 0.0);\n\
+ }\n",
);
for (i, t) in textures.iter().enumerate() {
m += &format!("@group(0) @binding({}) var tex_{t}: texture_2d<f32>;\n@group(0) @binding({}) var samp_{t}: sampler;\n", 3 + i * 2, 4 + i * 2);
@@ -128,7 +132,7 @@ pub fn module(source: &str, uniforms: &[(String, &'static str)], textures: &[Str
if prepass {
m += "@group(0) @binding(13) var raea_depth: texture_depth_2d;\n\
@group(0) @binding(14) var raea_normal: texture_2d<f32>;\n\
- fn raea_texel(uv: vec2<f32>, size: vec2<u32>) -> vec2<i32> { return clamp(vec2<i32>(raea_view_uv(uv) * vec2<f32>(size)), vec2<i32>(0), vec2<i32>(size) - vec2<i32>(1)); }\n\
+ fn raea_texel(uv: vec2<f32>, size: vec2<u32>) -> vec2<i32> { return clamp(vec2<i32>(raea_view_uv(clamp(uv, vec2<f32>(0.0), vec2<f32>(0.99999))) * vec2<f32>(size)), vec2<i32>(0), vec2<i32>(size) - vec2<i32>(1)); }\n\
// reverse-Z: the depth is near / distance, 0 where nothing was drawn\n\
fn depth(uv: vec2<f32>) -> f32 {\n\
\x20 let d = textureLoad(raea_depth, raea_texel(uv, textureDimensions(raea_depth)), 0);\n\
@@ -441,8 +445,8 @@ mod tests {
let d = module("@fragment fn f(in: FullscreenVertexOutput) -> @location(0) vec4<f32> { return vec4(depth(in.uv)); }", &[], &[], None, true);
assert!(d.contains("fn depth(") && d.contains("fn normal(") && !d.contains("raea_frame_pass("));
// the frame, the depth and the normals are read at the Viewport's uv mapped onto their textures
- assert!(m.contains("textureSampleLevel(raea_frame, raea_frame_sampler, raea_view_uv(uv), 0.0)"));
- assert!(d.contains("vec2<i32>(raea_view_uv(uv) * vec2<f32>(size))"));
+ assert!(m.contains("textureSampleLevel(raea_frame, raea_frame_sampler, raea_view_uv(clamp(uv, h, 1.0 - h)), 0.0)"));
+ assert!(d.contains("vec2<i32>(raea_view_uv(clamp(uv, vec2<f32>(0.0), vec2<f32>(0.99999))) * vec2<f32>(size))"));
}
#[test]
diff --git a/systems/post/src/camera/on.rs b/systems/post/src/camera/on.rs
index c58ca650..fac75766 100644
--- a/systems/post/src/camera/on.rs
+++ b/systems/post/src/camera/on.rs
@@ -55,6 +55,11 @@ pub fn bloom(world: &mut World, e: Entity, vals: &Vals) {
if bloom > 0.0 {
let mut b = bevy::post_process::bloom::Bloom::NATURAL;
b.intensity = bloom;
+ // a glow added on top of the frame (three.js's UnrealBloom, postprocessing's), where Bevy's natural bloom takes
+ // its light from around it
+ if vals.get("bloom_additive").is_some_and(V::truthy) {
+ b.composite_mode = bevy::post_process::bloom::BloomCompositeMode::Additive;
+ }
if let Some(th) = vals.get("bloom_threshold").map(V::num) {
b.prefilter.threshold = th as f32;
b.prefilter.threshold_softness = 0.2;