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
Every shader constant in the inventory is set from TypeScript: arrays and vectors too, toon and lens embedded, Solari's inline numbers named
shinyobjectz177f74e376ed
diff --git a/docs/manual/reference/sdk/light.md b/docs/manual/reference/sdk/light.mdindex 002ef4ff..fa94692a 100644--- a/docs/manual/reference/sdk/light.md+++ b/docs/manual/reference/sdk/light.md@@ -216,6 +216,7 @@ raster-lit: Bevy 0.20's Solari can't trace it.| `aa` | `boolean` | jitter a full-size view too, so the denoiser anti-aliases its edges as it gathers frames. Default true; RAEA_SOLARI_AA=0 overrides it || `jitter` | `"denoiser" \| "scaler" \| "both" \| "flip" \| "none"` | which of MetalFX's passes is told the camera's jitter: "denoiser", "scaler", "both", "flip" (the denoiser, negated), "none" (and the view isn't jittered). For A/Bs of RT9; default "denoiser"; RAEA_SOLARI_JITTER ("" the denoiser, "0" none) overrides it || `emissiveSharpness` | `number` | how fast a sample's weight falls with its distance from a pixel's centre in the emission's history, exp(-k d²) in output pixels: lower is softer. Default 6; RAEA_EMIT_TAA_SHARP overrides it |+| `jitterFrames` | `number` | the jitter's cycle at the full size, in frames: a view drawn at s of its size a side cycles through jitterFrames / s² offsets, and an emissive twig glimpsed through it may stay away that long. Default 8 (DLSS's) || `constants` | `{ /** how far ReSTIR looks for a neighbour's light samples, pixels (30): smaller keeps …` | constants in Solari's and the denoiser's shaders, compiled in when the scene loads (a value changed later in the composition isn't drawn); each left out keeps the shader's own, given in brackets. <ShaderConstants> reaches the rest |### `SpotLight`diff --git a/docs/manual/reference/sdk/pbr.md b/docs/manual/reference/sdk/pbr.mdindex 21bfbd27..edf0e72a 100644--- a/docs/manual/reference/sdk/pbr.md+++ b/docs/manual/reference/sdk/pbr.md@@ -190,7 +190,7 @@ typed props (<SolariLighting constants>); this reaches the rest.| Prop | Type | What it does || --- | --- | --- || `shader` (required) | `string` | the shader as the engine embeds it, `<crate>/<path under its src>`: "bevy_solari/realtime/restir.wesl", "raea_render_raytrace/emit_taa.wgsl". To read its constants, put an empty file of that name in the project's engine-shaders/ folder and render once: raea fills it with the shader |-| `values` (required) | `Record<string, ShaderConstantValue>` | each `const NAME` to set, and its value; the const keeps its type |+| `values` (required) | `Record<string, ShaderConstantValue>` | each `const NAME` to set, and its value; the const keeps its type (an array's or a vector's values as a list) |### `ShaderExtension`@@ -461,10 +461,11 @@ The props of [`ShaderConstants`](#shaderconstants), tabled there.### `ShaderConstantValue`-A shader constant's value: a number (a float or a whole number, as the const is) or a boolean+A shader constant's value: a number (a float or a whole number, as the const is), a boolean, or for an array or a+vector its values in order (as many as it holds)```ts-type ShaderConstantValue = number | boolean+type ShaderConstantValue = number | boolean | readonly number[]```### `ShaderExtensionProps`diff --git a/engine/render/raytrace/src/emit_taa.wgsl b/engine/render/raytrace/src/emit_taa.wgslindex fa132dd3..5a5156d9 100644--- a/engine/render/raytrace/src/emit_taa.wgsl+++ b/engine/render/raytrace/src/emit_taa.wgsl@@ -15,6 +15,12 @@@group(0) @binding(15) var hist_depth_out: texture_storage_2d<rgba32float, write>;// the most frames' weight the history holds: past it, it fades as 1 / HISTORY_CAP a frameconst HISTORY_CAP: f32 = 16.0;+// a still pixel's history held within what's about it now, its darkest and brightest times these+const STILL_LOW: f32 = 0.95;+const STILL_HIGH: f32 = 1.05;+// a moving pixel's history held under this many times the brightest about it, plus this+const MOVING_GAIN: f32 = 4.0;+const MOVING_FLOOR: f32 = 0.02;// the history at `uv` through a Catmull-Rom filter in five bilinear taps (Jimenez's), so a moving view isn't blurred a// little more each frame as a bilinear read would; never below zero (its lobes ring on a hard edge)fn history_at(uv: vec2<f32>, size: vec2<f32>) -> vec4<f32> {@@ -152,7 +158,7 @@ fn restore_taa(@builtin(global_invocation_id) id: vec3<u32>) {// held to the samples about it: where the view is still, within them; where it moves, only a light that isn't// there any more (four times the brightest about it): an edge's history under a drifting view isn't spanned by// one frame's samples, and holding it to them flickered photo 2's window edges 80 levels from frame to frame- let clamped = select(min(hrgb, mhi * 4.0 + 0.02), clamp(hrgb, elo * 0.95, ehi * 1.05), still);+ let clamped = select(min(hrgb, mhi * MOVING_GAIN + MOVING_FLOOR), clamp(hrgb, elo * STILL_LOW, ehi * STILL_HIGH), still);if (!kept && !still && params[0].w != 3.0) {// a history that failed its test at a moving pixel is kept as one frame's (below), held to what's about it// now: a moving silhouette's mix of its two sides is, and a light taken while the camera moves is gone atdiff --git a/engine/render/raytrace/src/lib.rs b/engine/render/raytrace/src/lib.rsindex 808bf618..b2ae2446 100644--- a/engine/render/raytrace/src/lib.rs+++ b/engine/render/raytrace/src/lib.rs@@ -68,6 +68,9 @@ pub struct SolariSettings {/// tracer's as seen (tone mapped), its sky through the twigs spread wider than a pixel, and a screen's detail 0.38/// of the tracer'spub emissive_sharpness: f32,+ /// the jitter's cycle at the full size, in frames: a view drawn at s of its size a side cycles through+ /// `jitter_frames / s²` offsets (DLSS's 8), and emit_taa lets a twig glimpsed through it stay away that long+ pub jitter_frames: f32,}impl Default for SolariSettings {@@ -82,6 +85,7 @@ impl Default for SolariSettings {aa: true,jitter: String::new(),emissive_sharpness: 6.0,+ jitter_frames: 8.0,}}}diff --git a/engine/render/raytrace/src/metalfx.rs b/engine/render/raytrace/src/metalfx.rsindex 8405a930..401ae811 100644--- a/engine/render/raytrace/src/metalfx.rs+++ b/engine/render/raytrace/src/metalfx.rs@@ -320,7 +320,7 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDelet back = ext.world_from_view.back();let reset = solari.reset || kit.views.get(&entity).is_none_or(|v| v.fresh);// the jitter's cycle at this render scale, how long a twig glimpsed through it can stay away (emit_taa.wgsl)- let cycle = super::upscale::cycle(size.x as f32 / full.x as f32) as f32;+ let cycle = super::upscale::cycle(size.x as f32 / full.x as f32, st.jitter_frames) as f32;let words: [f32; 16] = [cam.exposure, if st.split() { 1.0 } else { 0.0 }, if reset { 1.0 } else { 0.0 }, super::emit_taa::debug(), out_size.x as f32, out_size.y as f32, size.x as f32, size.y as f32, back.x, back.y, back.z, st.emissive_sharpness, jitter.x, jitter.y, cycle, 0.0];let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_ne_bytes()).collect();let params = wgpu::util::DeviceExt::create_buffer_init(&dev, &wgpu::util::BufferInitDescriptor { label: Some("metalfx params"), contents: &bytes, usage: wgpu::BufferUsages::UNIFORM });diff --git a/engine/render/raytrace/src/settings.rs b/engine/render/raytrace/src/settings.rsindex fdb30edc..d94f8809 100644--- a/engine/render/raytrace/src/settings.rs+++ b/engine/render/raytrace/src/settings.rs@@ -97,7 +97,7 @@ pub(crate) fn record(view: Entity, s: &SolariSettings, scale: f32, seen: &mut Ha"view": view.to_bits(),"denoise": s.denoise, "guides": s.guides, "reflection_depth": s.reflection_depth, "emissive": s.emissive,"upscale": s.upscale, "preexposure": s.preexposure, "aa": s.aa, "jitter": s.jitter,- "emissive_sharpness": s.emissive_sharpness, "scale": (f64::from(scale) * 1000.0).round() / 1000.0,+ "emissive_sharpness": s.emissive_sharpness, "jitter_frames": s.jitter_frames, "scale": (f64::from(scale) * 1000.0).round() / 1000.0,"env": env.iter().map(|(n, v, _)| format!("{n}={v}")).collect::<Vec<_>>(),}),);diff --git a/engine/render/raytrace/src/upscale.rs b/engine/render/raytrace/src/upscale.rsindex 5434edfb..c6a590c8 100644--- a/engine/render/raytrace/src/upscale.rs+++ b/engine/render/raytrace/src/upscale.rs@@ -93,12 +93,12 @@ fn halton(mut i: u32, base: u32) -> f32 {struct Jittered;/// How many frames the jitter takes to come round at render scale `s`: 8 / s², as DLSS asks.-pub(crate) fn cycle(s: f32) -> u32 {- (8.0 / (s * s)).ceil() as u32+pub(crate) fn cycle(s: f32, frames: f32) -> u32 {+ (frames / (s * s)).ceil().max(1.0) as u32}/// Each drawn-small camera's sub-pixel offset this frame (a Halton (2, 3) cycle, longer the smaller it draws, as-/// DLSS asks: 8 / s² frames), its mip bias, and the prepasses the scaler reads (depth, motion). A Solari camera at its+/// DLSS asks: 8 / s² frames, its settings' `jitter_frames`), its mip bias, and the prepasses the scaler reads (depth, motion). A Solari camera at its/// full size is jittered too unless its settings' `aa` is off, so MetalFX's denoiser anti-aliases its edges as it/// gathers frames: photo 2's frame 95 had stepped edges held still, and jittered it came 15.9 -> 15.6 off the path/// tracer.@@ -108,7 +108,7 @@ fn jitter(mut cmd: Commands, frame: Res<FrameCount>, mut cams: Query<(Entity, Oplet s = scale(rs, solari);let st = super::settings::of(st);if s < 1.0 || (solari && st.aa && st.denoise && DENOISING.load(Ordering::Relaxed)) {- let n = cycle(s);+ let n = cycle(s, st.jitter_frames);let i = frame.0 % n + 1;let offset = if st.jitter == "0" { Vec2::ZERO } else { Vec2::new(halton(i, 2), halton(i, 3)) - 0.5 };match j {diff --git a/sdk/guides/craft/bevy/solari.md b/sdk/guides/craft/bevy/solari.mdindex ec348190..0be038f9 100644--- a/sdk/guides/craft/bevy/solari.md+++ b/sdk/guides/craft/bevy/solari.md@@ -21,14 +21,14 @@the denoiser, 4 and 2 look the same in most rooms and save time.- Every other choice the engine makes for the traced light is a prop too, so an A/B is two compositions, never abuild: `denoise`, `guides`, `reflectionDepth`, `emissive` ("taa", "split", "mask"), `upscale` ("one", "two"),- `preexposure`, `aa`, `jitter`, `emissiveSharpness`, `firstBounce`, `confidenceCap` and `cache` (the world cache's+ `preexposure`, `aa`, `jitter`, `jitterFrames`, `emissiveSharpness`, `firstBounce`, `confidenceCap` and `cache` (the world cache's`frames`, `lightSamples`, `reach`, `updates`, `cellSize`, `lodScale`). Each prop's TSDoc says what it changes. Thedefaults are the measured best, so leave them unless a test scene shows otherwise. A developer's environmentvariable of the same setting (`RAEA_SOLARI_DENOISE=0`, `RAEA_METALFX_PREEXPOSURE=4`) overrides the prop on everycamera, for an A/B across many scenes at once.- The numbers inside Solari's and the denoiser's shaders are props too: `constants` (`spatialReuse`,- `mirrorRoughness`, `cacheEnd`, `cacheLifetime`, `cacheSearch`, the `reconnect...` three, `mirror`'s four rules,- `emissiveHistory`). They're compiled into the shaders when the scene loads, so set them from the first frame; a value+ `mirrorRoughness`, `cacheEnd`, `cacheLifetime`, `cacheSearch`, the `reconnect...` three, `glossyLightFloor`,+ `mirror`'s six rules, `emissiveHistory`, `emissiveClamp`). They're compiled into the shaders when the scene loads, so set them from the first frame; a valuethat changes later isn't drawn. `<ShaderConstants>` sets a constant in any other engine shader (`bevy/limits`).- Keep a look's settings as a TypeScript object and spread it: `const LIVE = { primarySamples: 4, scale: 0.67 }`,then `<SolariLighting {...LIVE} />` or `<SolariLighting {...LIVE} preexposure={32} />`.diff --git a/sdk/render/src/bevy3d/raytracing.tsx b/sdk/render/src/bevy3d/raytracing.tsxindex b3a6d219..9ab8a2ca 100644--- a/sdk/render/src/bevy3d/raytracing.tsx+++ b/sdk/render/src/bevy3d/raytracing.tsx@@ -69,6 +69,9 @@ export interface SolariLightingProps {/** how fast a sample's weight falls with its distance from a pixel's centre in the emission's history, exp(-k d²) in* output pixels: lower is softer. Default 6; RAEA_EMIT_TAA_SHARP overrides it */emissiveSharpness?: number;+ /** the jitter's cycle at the full size, in frames: a view drawn at s of its size a side cycles through+ * jitterFrames / s² offsets, and an emissive twig glimpsed through it may stay away that long. Default 8 (DLSS's) */+ jitterFrames?: number;/** constants in Solari's and the denoiser's shaders, compiled in when the scene loads (a value changed later in the* composition isn't drawn); each left out keeps the shader's own, given in brackets. <ShaderConstants> reaches the* rest */@@ -91,8 +94,14 @@ export interface SolariLightingProps {reconnectRelax?: number;/** only when the bounce's footprint is at least this percent of the pixel's (0.02) */reconnectFootprint?: number;+ /** the least chance a glossy surface's path samples a light directly, so a small bright light shows in it (0.25) */+ glossyLightFloor?: number;/** the mirror guides' rules (RT17): when a surface is drawn as what it reflects */mirror?: {+ /** under this roughness a reflection's own motion is traced, so the denoiser follows what it reflects (0.0625) */+ motionRoughness?: number;+ /** the specular share over which such a pixel takes its reflection's depth (RT34, 0.5) */+ depthShare?: number;/** the share of its reflectance that must leave through the mirror lobe (0.9) */replaceFraction?: number;/** how far its reflection's depth may shift between neighbouring pixels, as a share of that depth, before it@@ -106,6 +115,10 @@ export interface SolariLightingProps {/** the most frames an emissive surface's own light is gathered over (emissive "taa", 16): higher is smoother and* slower to follow a change */emissiveHistory?: number;+ /** how an emissive surface's history is held to the light about it now: a still pixel within the darkest times+ * stillLow (0.95) and the brightest times stillHigh (1.05); a moving one under the brightest times movingGain (4)+ * plus movingFloor (0.02) */+ emissiveClamp?: { stillLow?: number; stillHigh?: number; movingGain?: number; movingFloor?: number };};}@@ -121,6 +134,8 @@ export function solariConstants(c: SolariLightingProps["constants"]) {const cache = "bevy_solari/realtime/world_cache_query.wesl";const mirror = "bevy_solari/realtime/resolve_dlss_rr_textures.wesl";const m = c.mirror ?? {};+ const e = c.emissiveClamp ?? {};+ const taa = "raea_render_raytrace/emit_taa.wgsl";return shaderConstants([[restir, "SPATIAL_REUSE_RADIUS_PIXELS", at(c.spatialReuse, "spatialReuse")],["bevy_solari/scene/bindings.wesl", "MIRROR_ROUGHNESS_THRESHOLD", at(c.mirrorRoughness, "mirrorRoughness")],@@ -130,11 +145,18 @@ export function solariConstants(c: SolariLightingProps["constants"]) {[path, "RECONNECTION_ROUGHNESS_MIN", at(c.reconnectRoughness, "reconnectRoughness")],[path, "RECONNECTION_RELAX_DISTANCE", at(c.reconnectRelax, "reconnectRelax")],[path, "RECONNECTION_FOOTPRINT_KAPPA", at(c.reconnectFootprint, "reconnectFootprint")],+ [path, "GLOSSY_NEE_FLOOR", at(c.glossyLightFloor, "glossyLightFloor")],+ [mirror, "SPECULAR_MOTION_ROUGHNESS", at(m.motionRoughness, "mirror.motionRoughness")],+ [mirror, "REFLECTION_DEPTH_SHARE", at(m.depthShare, "mirror.depthShare")],[mirror, "FULL_REPLACEMENT_FRACTION", at(m.replaceFraction, "mirror.replaceFraction")],[mirror, "MAX_VIRTUAL_DEPTH_JITTER", at(m.depthJitter, "mirror.depthJitter")],[mirror, "NORMAL_QUANTIZATION_FLOOR", at(m.normalFloor, "mirror.normalFloor")],[mirror, "ENVIRONMENT_VIRTUAL_DISTANCE", at(m.skyDistance, "mirror.skyDistance")],- ["raea_render_raytrace/emit_taa.wgsl", "HISTORY_CAP", at(c.emissiveHistory, "emissiveHistory")],+ [taa, "HISTORY_CAP", at(c.emissiveHistory, "emissiveHistory")],+ [taa, "STILL_LOW", at(e.stillLow, "emissiveClamp.stillLow")],+ [taa, "STILL_HIGH", at(e.stillHigh, "emissiveClamp.stillHigh")],+ [taa, "MOVING_GAIN", at(e.movingGain, "emissiveClamp.movingGain")],+ [taa, "MOVING_FLOOR", at(e.movingFloor, "emissiveClamp.movingFloor")],]);}@@ -147,6 +169,7 @@ export function solariSettings(p: SolariLightingProps): Record<string, unknown>};pos("preexposure", p.preexposure);pos("emissiveSharpness", p.emissiveSharpness);+ pos("jitterFrames", p.jitterFrames);const one = <T extends string>(n: string, v: T | undefined, of: readonly T[]) => {if (v !== undefined && !of.includes(v)) throw new RangeError(`SolariLighting: ${n} is one of ${of.join(", ")}, got ${v}`);};@@ -164,6 +187,7 @@ export function solariSettings(p: SolariLightingProps): Record<string, unknown>// the engine's names for the passes (upscale.rs jitter_gain): "" the denoiser, "0" noneif (p.jitter !== undefined) v.jitter = p.jitter === "denoiser" ? "" : p.jitter === "none" ? "0" : p.jitter;if (p.emissiveSharpness !== undefined) v.emissive_sharpness = p.emissiveSharpness;+ if (p.jitterFrames !== undefined) v.jitter_frames = p.jitterFrames;return Object.keys(v).length ? v : undefined;}diff --git a/sdk/render/src/bevy3d/shaders.tsx b/sdk/render/src/bevy3d/shaders.tsxindex 1d16d99a..f8f78aa7 100644--- a/sdk/render/src/bevy3d/shaders.tsx+++ b/sdk/render/src/bevy3d/shaders.tsx@@ -1,15 +1,16 @@// Constants in the engine's own shaders, set from TypeScript when the scene loads (docs/nobuild.feature NB1a).import { BevyComponent, Entity } from "../3d";-/** A shader constant's value: a number (a float or a whole number, as the const is) or a boolean */-export type ShaderConstantValue = number | boolean;+/** A shader constant's value: a number (a float or a whole number, as the const is), a boolean, or for an array or a+ * vector its values in order (as many as it holds) */+export type ShaderConstantValue = number | boolean | readonly number[];export interface ShaderConstantsProps {/** the shader as the engine embeds it, `<crate>/<path under its src>`: "bevy_solari/realtime/restir.wesl",* "raea_render_raytrace/emit_taa.wgsl". To read its constants, put an empty file of that name in the project's* engine-shaders/ folder and render once: raea fills it with the shader */shader: string;- /** each `const NAME` to set, and its value; the const keeps its type */+ /** each `const NAME` to set, and its value; the const keeps its type (an array's or a vector's values as a list) */values: Record<string, ShaderConstantValue>;}@@ -19,9 +20,13 @@ export function shaderConstants(list: ReadonlyArray<readonly [string, string, Shconst values = list.filter(([, , v]) => v !== undefined).map(([shader, name, v]) => {+ if (Array.isArray(v)) {+ if (!v.length || !v.every(Number.isFinite)) throw new RangeError(`ShaderConstants: ${name} in ${shader} is a list of numbers, got ${v}`);+ return { shader, name, value: 0, list: [...v] };+ }const value = typeof v === "boolean" ? (v ? 1 : 0) : (v as number);if (!Number.isFinite(value)) throw new RangeError(`ShaderConstants: ${name} in ${shader} is a number or a boolean, got ${v}`);- return { shader, name, value };+ return { shader, name, value, list: [] };});return values.length ? <BevyComponent type="raea_sys_frame::engine_shaders::consts::ShaderConstants" value={{ values }} /> : undefined;}diff --git a/systems/frame/src/engine_shaders.rs b/systems/frame/src/engine_shaders.rsindex 55db642c..4133a2a3 100644--- a/systems/frame/src/engine_shaders.rs+++ b/systems/frame/src/engine_shaders.rs@@ -140,9 +140,10 @@ fn with_constants(app: &mut App, set: &[consts::ShaderConstant], swaps: &mut Vec};let before = s.clone();for c in set.iter().filter(|c| c.shader == shader) {- match consts::rewrite(&s, &c.name, c.value) {+ match consts::rewrite(&s, &c.name, c.value, &c.list) {Ok((t, old)) => {- said.push(format!("{shader} {} {old} -> {}", c.name, c.value));+ let v = if c.list.is_empty() { c.value.to_string() } else { format!("{:?}", c.list) };+ said.push(format!("{shader} {} {old} -> {v}", c.name));s = t;}Err(e) => eprintln!("raea: <ShaderConstants> {shader}: {e}; left as the shader has it"),@@ -194,7 +195,7 @@ fn original(app: &App, rel: &str) -> Option<Vec<u8>> {pub fn text(rel: &str, builtin: &'static str) -> std::borrow::Cow<'static, str> {let mut s = source(rel, builtin);for c in CONSTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().filter(|c| c.shader == rel) {- if let Ok((t, _)) = consts::rewrite(&s, &c.name, c.value) {+ if let Ok((t, _)) = consts::rewrite(&s, &c.name, c.value, &c.list) {s = t.into();}}diff --git a/systems/frame/src/engine_shaders/consts.rs b/systems/frame/src/engine_shaders/consts.rsindex 91e26914..8d1eaad5 100644--- a/systems/frame/src/engine_shaders/consts.rs+++ b/systems/frame/src/engine_shaders/consts.rs@@ -8,13 +8,14 @@ use raea_core_program::ir::{Program, V};use serde_json::Value;/// One constant: its shader as Bevy embeds it (`<crate>/<path under its src>`), the const's name, its value (a bool as-/// 1 or 0).+/// 1 or 0), or for an array or a vector its values in order (`list`, `value` then unused).#[derive(Reflect, Clone, Debug, Default, PartialEq)]#[reflect(Default)]pub struct ShaderConstant {pub shader: String,pub name: String,pub value: f64,+ pub list: Vec<f64>,}/// The constants a part sets in the engine's shaders, read from the first frame's rows when the Engine opens.@@ -69,13 +70,15 @@ fn take(value: &Value, out: &mut Vec<ShaderConstant>) {for c in value.get("values").and_then(Value::as_array).into_iter().flatten() {let (Some(shader), Some(name)) = (c.get("shader").and_then(Value::as_str), c.get("name").and_then(Value::as_str)) else { continue };let value = c.get("value").and_then(|v| v.as_f64().or_else(|| v.as_bool().map(f64::from))).unwrap_or(f64::NAN);+ let list = c.get("list").and_then(Value::as_array).map(|a| a.iter().map(|v| v.as_f64().unwrap_or(f64::NAN)).collect()).unwrap_or_default();out.retain(|k| !(k.shader == shader && k.name == name));- out.push(ShaderConstant { shader: shader.into(), name: name.into(), value });+ out.push(ShaderConstant { shader: shader.into(), name: name.into(), value, list });}}-/// `text` with `const NAME ... = EXPR;` given `value` in the const's type: the new text and the expression it had.-pub(super) fn rewrite(text: &str, name: &str, value: f64) -> Result<(String, String), String> {+/// `text` with `const NAME ... = EXPR;` given `value` in the const's type, or `list` for an array or a vector (as many+/// values as it holds, each in its element type): the new text and the expression it had.+pub(super) fn rewrite(text: &str, name: &str, value: f64, list: &[f64]) -> Result<(String, String), String> {let mut found = None;let mut at = 0;for line in text.split_inclusive('\n') {@@ -95,6 +98,11 @@ pub(super) fn rewrite(text: &str, name: &str, value: f64) -> Result<(String, Strlet end = rest.find(';').filter(|e| *e > eq).ok_or_else(|| format!("{name}'s value doesn't end on its line"))?;let ty = rest[..eq].trim().trim_start_matches(':').trim();let old = rest[eq + 1..end].trim();+ let e0 = start + eq + 1;+ let put = |new: String| (format!("{} {new}{}", &text[..e0], &text[start + end..]), old.to_string());+ if !list.is_empty() {+ return several(name, old, list).map(put);+ }if !value.is_finite() {return Err(format!("{name} needs a number or a boolean"));}@@ -116,11 +124,53 @@ pub(super) fn rewrite(text: &str, name: &str, value: f64) -> Result<(String, Str"" if old.parse::<i64>().is_ok() => int("", f64::MIN)?,// a float literal, or an expression of floats (PI, 1.0 / 16.0); not an array, a vector or a matrix"" if !old.contains('<') && !["array", "vec", "mat"].iter().any(|t| old.starts_with(t)) => float(value),- _ => return Err(format!("{name} is {}, not a number", if ty.is_empty() { old } else { ty })),+ _ => return Err(format!("{name} is {}, not a number{}", if ty.is_empty() { old } else { ty }, if old.contains('(') { " (give its values as a list)" } else { "" })),};- let e0 = start + eq + 1;- let s = format!("{} {new}{}", &text[..e0], &text[start + end..]);- Ok((s, old.to_string()))+ Ok(put(new))+}++/// An array's or a vector's new expression, its constructor as the shader writes it (`array<f32, 6>(...)`,+/// `vec3<f32>(...)`, `vec3(...)`), each value in its element type.+fn several(name: &str, old: &str, list: &[f64]) -> Result<String, String> {+ let (Some(open), true) = (old.find('('), old.ends_with(')')) else { return Err(format!("{name} is {old}, one number (not a list)")) };+ let ctor = old[..open].trim();+ if !(ctor.starts_with("array") || ctor.starts_with("vec")) {+ return Err(format!("{name} is {old}, not an array or a vector"));+ }+ // its values: the commas at the top level inside the constructor's brackets+ let args = &old[open + 1..old.len() - 1];+ let (mut depth, mut n, mut floats) = (0, 1, args.contains('.'));+ for ch in args.chars() {+ match ch {+ '(' => depth += 1,+ ')' => depth -= 1,+ ',' if depth == 0 => n += 1,+ _ => {}+ }+ }+ // array<T, N> or vecN<T>: T+ let elem = ctor.split_once('<').map_or("", |(_, g)| {+ let inner = g.strip_suffix('>').unwrap_or(g);+ inner.rsplit_once(',').map_or(inner, |(e, _)| e).trim()+ });+ if ["vec", "array", "mat"].iter().any(|t| elem.starts_with(t)) {+ return Err(format!("{name} is an array of {elem}, not of numbers"));+ }+ if args.trim().is_empty() || n != list.len() {+ return Err(format!("{name} holds {n} values, not {}", list.len()));+ }+ floats |= matches!(elem, "f32" | "f16");+ let each = |v: f64| -> Result<String, String> {+ let whole = |suffix: &str, min: f64| if v.fract() != 0.0 || v < min || !v.is_finite() { Err(format!("{name}'s values are whole numbers{}, not {v}", if min >= 0.0 { " from 0" } else { "" })) } else { Ok(format!("{v:.0}{suffix}")) };+ match elem {+ "u32" => whole("u", 0.0),+ "i32" => whole("i", f64::MIN),+ "bool" => Ok((if v != 0.0 { "true" } else { "false" }).into()),+ _ if floats => if v.is_finite() { Ok(float(v)) } else { Err(format!("{name}'s values are numbers")) },+ _ => whole("", f64::MIN),+ }+ };+ Ok(format!("{ctor}({})", list.iter().map(|v| each(*v)).collect::<Result<Vec<_>, _>>()?.join(", ")))}/// A float literal WGSL reads as one: 24 as 24.0.@@ -138,6 +188,7 @@ pub(super) fn changed_later(q: Query<&ShaderConstants, Changed<ShaderConstants>>}if let Some(c) = q.iter().flat_map(|c| &c.values).find(|c| !loaded.0.contains(c)) {*said = true;- eprintln!("raea: the engine's shader constants are compiled in when the scene loads; {} {} = {} came later and isn't drawn (set it from the first frame)", c.shader, c.name, c.value);+ let v = if c.list.is_empty() { c.value.to_string() } else { format!("{:?}", c.list) };+ eprintln!("raea: the engine's shader constants are compiled in when the scene loads; {} {} = {v} came later and isn't drawn (set it from the first frame)", c.shader, c.name);}}diff --git a/systems/material/src/toon.rs b/systems/material/src/toon.rsindex 2890314a..c7da1d07 100644--- a/systems/material/src/toon.rs+++ b/systems/material/src/toon.rs@@ -12,15 +12,15 @@//! sh_r sh_g sh_b (an animated shadow colour), rim_k, spec_k, outline_wuse super::*;-use bevy::asset::{load_internal_asset, uuid_handle};use bevy::light::{NotShadowCaster, NotShadowReceiver};use bevy::mesh::{MeshVertexBufferLayoutRef, VertexAttributeValues};use bevy::pbr::{ExtendedMaterial, MaterialExtension, MaterialPipeline, MaterialPipelineKey, MaterialPlugin};use bevy::render::render_resource::{AsBindGroup, Face, RenderPipelineDescriptor, ShaderType, SpecializedMeshPipelineError};-use bevy::shader::{Shader, ShaderRef};+use bevy::shader::ShaderRef;-const TOON_SHADER: Handle<Shader> = uuid_handle!("6a0b6c1e-3f0e-4b8e-9d4f-5c2f1a7e0b31");-const OUTLINE_SHADER: Handle<Shader> = uuid_handle!("9c3d2e7a-81b4-4f6a-a0c5-2d9e6b4f7a12");+// embedded, so a project's engine-shaders/ and <ShaderConstants> reach them (docs/nobuild.feature NB5b)+const TOON_SHADER: &str = "embedded://raea_sys_material/toon.wesl";+const OUTLINE_SHADER: &str = "embedded://raea_sys_material/toon_outline.wesl";/// The toon surface: the standard material's inputs (base colour, its texture, emissive, opacity, fog) lit in bands.pub type ToonMaterial = ExtendedMaterial<StandardMaterial, ToonExt>;@@ -44,7 +44,7 @@ pub struct ToonExt {impl MaterialExtension for ToonExt {fn fragment_shader() -> ShaderRef {- ShaderRef::Handle(TOON_SHADER)+ TOON_SHADER.into()}}@@ -64,10 +64,10 @@ pub struct OutlineMaterial {impl Material for OutlineMaterial {fn vertex_shader() -> ShaderRef {- ShaderRef::Handle(OUTLINE_SHADER)+ OUTLINE_SHADER.into()}fn fragment_shader() -> ShaderRef {- ShaderRef::Handle(OUTLINE_SHADER)+ OUTLINE_SHADER.into()}fn alpha_mode(&self) -> AlphaMode {if self.blend { AlphaMode::Blend } else { AlphaMode::Opaque }@@ -87,8 +87,8 @@ impl Material for OutlineMaterial {/// The shaders and the two materials, on every engine (nothing is compiled until a toon part draws).pub fn install(app: &mut App) {- load_internal_asset!(app, TOON_SHADER, "toon.wesl", Shader::from_wesl);- load_internal_asset!(app, OUTLINE_SHADER, "toon_outline.wesl", Shader::from_wesl);+ bevy::asset::embedded_asset!(app, "toon.wesl");+ bevy::asset::embedded_asset!(app, "toon_outline.wesl");app.add_plugins((MaterialPlugin::<ToonMaterial>::default(), MaterialPlugin::<OutlineMaterial>::default()));}diff --git a/systems/post/src/lens.rs b/systems/post/src/lens.rsindex e4d7046a..7c555fcb 100644--- a/systems/post/src/lens.rs+++ b/systems/post/src/lens.rs@@ -12,7 +12,6 @@//! all.use super::*;-use bevy::asset::{load_internal_asset, uuid_handle};use bevy::core_pipeline::{schedule::Core3d, tonemapping::tonemapping, Core3dSystems, FullscreenShader};use bevy::render::{extract_component::{ComponentUniforms, DynamicUniformIndex, ExtractComponent, ExtractComponentPlugin, UniformComponentPlugin},@@ -24,9 +23,7 @@ use bevy::render::{view::ViewTarget,RenderApp, RenderStartup,};-use bevy::shader::Shader;-const LENS_SHADER: Handle<Shader> = uuid_handle!("2f8b1c4d-6e3a-4d7b-9a51-0c4e7f2b8d63");/// The lens on the camera, as the shader reads it (lens.wesl's `Lens`).#[derive(Component, Clone, Copy, Debug, Default, PartialEq, ExtractComponent, ShaderType)]@@ -87,7 +84,8 @@ pub fn render_fov(vals: &BTreeMap<String, V>, cam_fov: f32) -> f32 {/// The pass, on every engine (a camera without a Lens never runs it).pub fn install(app: &mut App) {- load_internal_asset!(app, LENS_SHADER, "lens.wesl", Shader::from_wesl);+ // embedded, so a project's engine-shaders/ and <ShaderConstants> reach it (docs/nobuild.feature NB5b)+ bevy::asset::embedded_asset!(app, "lens.wesl");app.add_plugins((ExtractComponentPlugin::<Lens>::default(), UniformComponentPlugin::<Lens>::default()));let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return };render_app.add_systems(RenderStartup, init_pipeline);@@ -102,7 +100,8 @@ struct LensPipeline {ids: Vec<(TextureFormat, CachedRenderPipelineId)>,}-fn init_pipeline(mut commands: Commands, device: Res<RenderDevice>, fullscreen: Res<FullscreenShader>, cache: Res<PipelineCache>) {+fn init_pipeline(mut commands: Commands, device: Res<RenderDevice>, fullscreen: Res<FullscreenShader>, cache: Res<PipelineCache>, assets: Res<AssetServer>) {+ let shader = bevy::asset::load_embedded_asset!(assets.as_ref(), "lens.wesl");let layout = BindGroupLayoutDescriptor::new("raea_lens",&BindGroupLayoutEntries::sequential(@@ -125,7 +124,7 @@ fn init_pipeline(mut commands: Commands, device: Res<RenderDevice>, fullscreen:layout: vec![layout.clone()],vertex: fullscreen.to_vertex_state(),fragment: Some(FragmentState {- shader: LENS_SHADER,+ shader: shader.clone(),targets: vec![Some(ColorTargetState { format, blend: None, write_mask: ColorWrites::ALL })],..default()}),diff --git a/tools/nobuild.sh b/tools/nobuild.shindex d58858cb..76c10f25 100755--- a/tools/nobuild.sh+++ b/tools/nobuild.sh@@ -8,6 +8,10 @@# of the binaries tools build, declared Bevy plugins), each joined with its decision# in docs/nobuild/decisions.tsv, written to docs/nobuild/inventory.tsv; prints what# has no decision yet and the counts by kind and status+# tools/nobuild.sh consts each shader constant in the inventory set through <ShaderConstants> in one scene that+# RAEA_BIN (target/release/raea) renders with every pass on: settable (raea set it), refused+# (an array, a vector, not found) or absent (that Engine doesn't load the shader);+# written to docs/nobuild/consts.tsv, NB1a's check for each row## A decision row (tab-separated): kind:name, then its class, the TypeScript form it becomes, its check, its status# (open, doing, done, stays). Classes: frame (changes what a frame shows or costs: a prop), view (a debug view: NB2),@@ -85,8 +89,61 @@ scan() {[ "$undecided" = 0 ] || echo "nobuild: $undecided causes have no decision (class ?) in docs/nobuild/decisions.tsv"}+# a shader file's path as Bevy embeds it: its crate's name (dashes as underscores), then its path under src+embedded() {+ local f=$1 d n+ d=$(dirname "$f")+ while [ "$d" != . ] && [ ! -f "$d/Cargo.toml" ]; do d=$(dirname "$d"); done+ n=$(awk '/^\[package\]/{p=1; next} /^\[/{p=0} p && /^name *=/{gsub(/[" ]/, "", $0); sub(/^name=/, ""); print; exit}' "$d/Cargo.toml" 2>/dev/null)+ [ -n "$n" ] && [ "${f#"$d"/src/}" != "$f" ] && printf '%s/%s\n' "${n//-/_}" "${f#"$d"/src/}"+}++consts() {+ local bin=${RAEA_BIN:-$RAEA/target/release/raea} inv=$DOCS/inventory.tsv out=$DOCS/consts.tsv+ [ -x "$bin" ] || { echo "nobuild: no raea at $bin (RAEA_BIN)" >&2; exit 1; }+ [ -f "$inv" ] || scan > /dev/null+ local dir; dir=$(mktemp -d "${TMPDIR:-/tmp}/nobuild-consts.XXXXXX") || exit 1+ cd "$RAEA" || exit 1+ # each constant: its shader as embedded, its name, and its own value where it's a literal (else 1: only its type is+ # checked, and the scene draws nothing that reads it)+ awk -F'\t' 'NR > 1 && $1 == "shader" { print $2 "\t" $3 }' "$inv" | while IFS=$'\t' read -r name where; do+ local file=${where%:*} line=${where##*:} rel expr v+ rel=$(embedded "$file") || { printf '%s\t%s\t-\tnot under a crate src\n' "$name" "$file"; continue; }+ expr=$(sed -n "${line}p" "$file" | sed -E 's/^[^=]*=[[:space:]]*//; s/;.*$//')+ if [[ $expr =~ ^-?[0-9]+(\.[0-9]*)?(e-?[0-9]+)?[uifh]?$ ]]; then v=${expr%[uifh]}+ elif [ "$expr" = true ] || [ "$expr" = false ]; then v=$expr+ # an array or a vector: its own values, or as many 1s when they aren't plain numbers+ elif [[ $expr =~ ^(array|vec)[^\(]*\((.*)\)$ ]]; then+ v=$(printf '%s' "${BASH_REMATCH[2]}" | awk -F, '{ s = ""; for (i = 1; i <= NF; i++) { x = $i; gsub(/[[:space:]uifh]/, "", x); if (x !~ /^-?[0-9.]+(e-?[0-9]+)?$/) x = 1; s = s (i > 1 ? ", " : "") x } print "[" s "]" }')+ else v=1; fi+ printf '%s\t%s\t%s\n' "$name" "$rel" "$v"+ done > "$dir/rows.tsv"+ { printf 'import { Composition, registerRoot } from "raea";\nimport { Camera3d } from "raea/camera";\nimport { ShaderConstants } from "raea/pbr";\n'+ printf 'function Scene() {\n return (\n <>\n <Camera3d />\n'+ awk -F'\t' '$3 != "-" { v[$2] = v[$2] (v[$2] ? ", " : "") $1 ": " $3 } END { for (s in v) printf " <ShaderConstants shader=\"%s\" values={{ %s }} />\n", s, v[s] }' "$dir/rows.tsv" | sort+ printf ' </>\n );\n}\nregisterRoot(() => <Composition id="consts" component={Scene} width={64} height={64} fps={30} durationInFrames={1} />);\n'+ } > "$dir/scene.tsx"+ # every pass that embeds shaders switched on: Solari, raea's traced passes (AO, GI's probes, the far sun) and the sun pass+ (cd "$dir" && RAEA_LIGHT=solari RAEA_TRACED_AO=1 RAEA_GI=1 RAEA_SUN_FAR=1 RAEA_PASS=sun "$bin" render scene.tsx --frame 0 -o "$dir/f.png" > /dev/null 2> "$dir/err.log")+ local set; set=$(grep -h "compiled in at load:" "$dir/err.log")+ while IFS=$'\t' read -r name rel v; do+ local got+ if [ "$v" = - ]; then got=$rel; rel=-+ elif grep -qF "no engine shader at $rel " "$dir/err.log"; then got="absent: this Engine doesn't load it"+ elif grep -qF "$rel: no \`const $name\`" "$dir/err.log"; then got="refused: not found"+ elif grep -qF "$rel: $name " "$dir/err.log"; then got="refused: $(grep -F "$rel: $name " "$dir/err.log" | head -1 | sed -E "s|.*$rel: ||; s/; left as.*//" | cut -c1-60)"+ elif printf '%s' "$set" | grep -qF "$rel $name "; then got=settable+ else got="unknown (see $dir/err.log)"; fi+ printf '%s\t%s\t%s\n' "$name" "$rel" "$got"+ done < "$dir/rows.tsv" | sort -u > "$out"+ echo "nobuild: $(wc -l < "$out" | tr -d ' ') shader constants in ${out#"$RAEA"/}, set through <ShaderConstants> by $bin"+ cut -f3 "$out" | sed 's/:.*//' | sort | uniq -c+ grep -q "unknown" "$out" || rm -rf -- "${dir:?}"+}+case ${1:-} inbuilds) shift; builds "$@" ;;scan) scan ;;- *) sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;+ consts) consts ;;+ *) sed -n '2,24p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;esacdiff --git a/vendor/bevy_solari/src/realtime/initial_path.wesl b/vendor/bevy_solari/src/realtime/initial_path.weslindex 4448976c..babba612 100644--- a/vendor/bevy_solari/src/realtime/initial_path.wesl+++ b/vendor/bevy_solari/src/realtime/initial_path.wesl@@ -19,6 +19,8 @@ const RECONNECTION_ROUGHNESS_MIN = 0.6;const RECONNECTION_RELAX_DISTANCE = 1.0;const CACHE_TERMINATION_MIN_SOLID_ANGLE = PI;+// raea: the least chance a glossy surface's path samples a light directly (NEE), so a small bright light shows in it+const GLOSSY_NEE_FLOOR = 0.25;/// What tracing one path produced.///@@ -99,7 +101,7 @@ fn generate_initial_path(world_position: vec3<f32>, world_normal: vec3<f32>, mat// panorama's sun, EnvironmentSun) is sampled often enough to show; NEE's weights divide by p_nee, so this stays// unbiased. A perfect mirror still never samples lights and sees the sun in the environment map.let p_nee_upstream = mix(1.0, path.material.perceptual_roughness, path.material.metallic);- let p_nee = select(max(p_nee_upstream, 0.25), p_nee_upstream, path.material.roughness <= MIRROR_ROUGHNESS_THRESHOLD);+ let p_nee = select(max(p_nee_upstream, GLOSSY_NEE_FLOOR), p_nee_upstream, path.material.roughness <= MIRROR_ROUGHNESS_THRESHOLD);let di_samples = select(constants.secondary_di_samples, constants.primary_di_samples, bounce == 0u);generate_nee_candidate(&path, F_ab, p_nee, di_samples, workgroup_id, bounce, rng);diff --git a/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.wesl b/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.weslindex 79947db2..aee72c8b 100644--- a/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.wesl+++ b/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.wesl@@ -24,6 +24,12 @@ const NORMAL_QUANTIZATION_FLOOR = 0.002;/// Distance, in meters, standing in for "infinitely far" when a mirror ray finds nothing.const ENVIRONMENT_VIRTUAL_DISTANCE = 10000.0;+/// raea: under this roughness a reflection's own motion is traced, so the denoiser follows what it reflects (RT17).+const SPECULAR_MOTION_ROUGHNESS = 0.0625;++/// raea: the specular share over which such a pixel takes its reflection's depth (RT34).+const REFLECTION_DEPTH_SHARE = 0.5;+@compute @workgroup_size(8, 8, 1)fn resolve_dlss_rr_textures(@builtin(global_invocation_id) global_id: vec3<u32>) {let pixel_id = global_id.xy;@@ -69,14 +75,14 @@ fn resolve_dlss_rr_textures(@builtin(global_invocation_id) global_id: vec3<u32>)}fn needs_specular_motion_vector(roughness: f32) -> bool {- return roughness <= 0.0625;+ return roughness <= SPECULAR_MOTION_ROUGHNESS;}// raea: a pixel whose depth is its reflection's under PSR_DEPTH_FOLLOWS_MOTION: one whose motion is (a near-mirror) and// that mostly reflects (a dark monitor's glass, 0.88 of its light specular): when what it reflects moves off (an orb), the// denoiser sees the wall behind as a disocclusion and drops the orb's history, where at the glass's depth it smeared itfn depth_follows_reflection(material: ResolvedMaterial, NdotV: f32) -> bool {- return needs_specular_motion_vector(material.roughness) && specular_fraction(material, F_AB(material.perceptual_roughness, NdotV)) >= 0.5;+ return needs_specular_motion_vector(material.roughness) && specular_fraction(material, F_AB(material.perceptual_roughness, NdotV)) >= REFLECTION_DEPTH_SHARE;}/// Carried across every bounce of the path walk, so anything derivable from a value the walk already