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.

nobuild: its copied code folded into what it copies (dupes: 293 exact, 57 near)

shinyobjectzcd03baf1099a
diff --git a/Cargo.lock b/Cargo.lock
index 6e033cc0..aad1f5b8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14968,6 +14968,7 @@ dependencies = [
"objc2-metal-fx",
"raea-io-trace",
"raea-sys-engine-shaders",
+ "raea-sys-post",
"raea-sys-rt",
"serde_json",
"wgpu",
diff --git a/engine/bevy-plugins/src/lib.rs b/engine/bevy-plugins/src/lib.rs
index ae0f59ac..560705c8 100644
--- a/engine/bevy-plugins/src/lib.rs
+++ b/engine/bevy-plugins/src/lib.rs
@@ -96,7 +96,7 @@ pub struct Declared {
pub fn install_all() {
install();
// the catalog: an Engine adds those its project chooses (raea_runtime_plugins::choose, docs/nobuild.feature NB4a)
- raea_runtime_plugins::catalog(declared().iter().filter(|d| compiled().contains(&d.name)).map(|d| raea_runtime_plugins::Entry { name: d.name, needs: d.needs, prefixes: d.prefixes }).collect());
+ raea_runtime_plugins::catalog(built().map(|d| raea_runtime_plugins::Entry { name: d.name, needs: d.needs, prefixes: d.prefixes }).collect());
bridge::register_natives();
}
@@ -105,7 +105,13 @@ pub fn compiled() -> Vec<&'static str> {
declared().iter().filter(|d| raea_runtime_plugins::names().iter().any(|n| n == &d.name || n.starts_with(&format!("{}_", d.name)))).map(|d| d.name).collect()
}
+/// The declared plugins this build compiled in.
+fn built() -> impl Iterator<Item = Declared> {
+ let compiled = compiled();
+ declared().into_iter().filter(move |d| compiled.contains(&d.name))
+}
+
/// The type-path prefixes each compiled plugin's reflected types live under (what the generator keeps).
pub fn prefixes() -> Vec<&'static str> {
- declared().iter().filter(|d| compiled().contains(&d.name)).flat_map(|d| d.prefixes.iter().copied()).collect()
+ built().flat_map(|d| d.prefixes.iter().copied()).collect()
}
diff --git a/engine/cli/src/bin/raea-bevy-sdk.rs b/engine/cli/src/bin/raea-bevy-sdk.rs
index d889f26e..77e8a83e 100644
--- a/engine/cli/src/bin/raea-bevy-sdk.rs
+++ b/engine/cli/src/bin/raea-bevy-sdk.rs
@@ -208,7 +208,7 @@ fn main() {
std::process::exit(raea_cli::cli(&args[1..]));
}
#[cfg(feature = "bevy-plugins")]
- let (compiled, default_prefixes) = { raea_runtime_plugins::choose_every(); (raea_bevy_plugins::compiled(), raea_bevy_plugins::prefixes()) }; // the generator walks every compiled plugin's types, chosen or not
+ let (compiled, default_prefixes) = { raea_runtime_plugins::choose_every(true); (raea_bevy_plugins::compiled(), raea_bevy_plugins::prefixes()) }; // the generator walks every compiled plugin's types, chosen or not
#[cfg(not(feature = "bevy-plugins"))]
let (compiled, default_prefixes): (Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new());
let mut prefixes = flag_all(&args, "--prefix");
diff --git a/engine/render/raytrace/Cargo.toml b/engine/render/raytrace/Cargo.toml
index 5284686c..47f0cc05 100644
--- a/engine/render/raytrace/Cargo.toml
+++ b/engine/render/raytrace/Cargo.toml
@@ -9,6 +9,8 @@ description = "raea-render's ray tracing: Bevy's Solari for a scene whose camera
[dependencies]
# each view's effective SolariSettings, once, into the run's trace (settings.rs)
raea-io-trace = { path = "../../../io/trace" }
+# the jitter's Halton places (a facility of raea-sys-post's steady)
+raea-sys-post = { path = "../../../systems/post" }
serde_json = "1"
# its own wgpu shaders read from a project's engine-shaders/ or the checkout (RAEA_ENGINE_SHADERS), as the embedded ones
raea-sys-engine-shaders = { path = "../../../systems/engine-shaders" }
diff --git a/engine/render/raytrace/src/metalfx.rs b/engine/render/raytrace/src/metalfx.rs
index a01169c3..7db6f848 100644
--- a/engine/render/raytrace/src/metalfx.rs
+++ b/engine/render/raytrace/src/metalfx.rs
@@ -250,7 +250,8 @@ fn denoise(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Ki
let st = super::settings::of(item.9);
let scale = item.5.map_or(1.0, |p| p.0.x as f32 / item.0.main_texture().width() as f32);
super::settings::record(entity, &st, scale, &mut seen);
- if !st.denoise || (item.7 && st.one_pass()) {
+ // a view drawn small is denoised and brought up in one pass, unless its upscale is "two"
+ if !st.denoise || (item.7 && st.upscale != "two") {
return;
}
run(entity, item, &st, &device, &mut kit, &mut ctx, false);
@@ -261,7 +262,7 @@ fn denoise_up(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local
let entity = view.entity();
let item = view.into_inner();
let st = super::settings::of(item.9);
- if !st.denoise || !item.7 || !st.one_pass() {
+ if !st.denoise || !item.7 || st.upscale == "two" {
return;
}
run(entity, item, &st, &device, &mut kit, &mut ctx, true);
@@ -291,7 +292,9 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
// with Solari's guides, the denoiser's depth is theirs: a mirror's pixel as far off as what it reflects, so when what
// it reflects moves off (an orb in a monitor's glass) the wall now there is a disocclusion and its history goes
let guide_depth = guides.is_some() && st.reflection_depth;
- let taa = st.taa();
+ // the emission taken out before the denoiser and put back after ("taa" or "split"), its history gathered over
+ // frames too ("taa", emit_taa.rs)
+ let (split, taa) = (st.emissive != "mask", st.emissive == "taa");
if kit.views.get(&entity).map(|v| (v.size, v.out_size, v.guide_depth, v.taa.is_some())) != Some((size, out_size, guide_depth, taa)) {
match View::new(&dev, size, out_size, guide_depth, taa) {
Ok(v) => {
@@ -321,7 +324,7 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
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, 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 words: [f32; 16] = [cam.exposure, if 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 });
let v = kit.views.get_mut(&entity).unwrap();
@@ -366,7 +369,7 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
};
ctx.add_command_buffer(raw.finish());
// the emissive back in, after the denoiser's command buffer (add_command_buffer flushed the encoder before it)
- if st.split() {
+ if split {
let mut entries = vec![
wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&color_view) },
wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() },
diff --git a/engine/render/raytrace/src/settings.rs b/engine/render/raytrace/src/settings.rs
index 1b53706d..71e24c54 100644
--- a/engine/render/raytrace/src/settings.rs
+++ b/engine/render/raytrace/src/settings.rs
@@ -25,7 +25,7 @@ fn overrides() -> &'static Overrides {
let var = |n: &str| std::env::var(n).ok();
// "0" turns a switch off and anything else on, as each variable did on its own
let switch = |n: &str| var(n).map(|v| v != "0");
- let num = |n: &str| var(n).and_then(|v| v.parse::<f32>().ok()).filter(|v| v.is_finite() && *v > 0.0);
+ let num = |n: &str| var(n).and_then(|v| v.parse::<f32>().ok()).filter(|v| (f32::MIN_POSITIVE..f32::INFINITY).contains(v));
Overrides {
denoise: switch("RAEA_SOLARI_DENOISE"),
guides: switch("RAEA_SOLARI_PSR"),
@@ -58,9 +58,8 @@ pub(crate) fn of(s: Option<&SolariSettings>) -> SolariSettings {
s
}
-/// The variables set, each with its value and the prop it overrides.
-fn set() -> Vec<(&'static str, String, &'static str)> {
- [
+/// The variables that override a prop, each with the prop.
+const VARS: &[(&str, &str)] = &[
("RAEA_SOLARI_DENOISE", "denoise"),
("RAEA_SOLARI_PSR", "guides"),
("RAEA_SOLARI_PSR_DEPTH", "reflectionDepth"),
@@ -72,11 +71,7 @@ fn set() -> Vec<(&'static str, String, &'static str)> {
("RAEA_SOLARI_DYNAMIC", "dynamic"),
("RAEA_EMIT_TAA_SHARP", "emissiveSharpness"),
("RAEA_SOLARI_SCALE", "scale"),
- ]
- .into_iter()
- .filter_map(|(n, prop)| std::env::var(n).ok().map(|v| (n, v, prop)))
- .collect()
-}
+];
/// A view's settings as they apply, into the run's trace (`solari_settings`: the view, each field, and the variables
/// that overrode a prop) the first frame and whenever they change, so a render says what it drew with; and once a run,
@@ -87,14 +82,7 @@ pub(crate) fn record(view: Entity, s: &SolariSettings, scale: f32, seen: &mut Ha
return;
}
seen.insert(view, s.clone());
- let env = set();
- static SAID: std::sync::Once = std::sync::Once::new();
- if !env.is_empty() {
- SAID.call_once(|| {
- let list: Vec<String> = env.iter().map(|(n, v, prop)| format!("{n}={v} over {prop}")).collect();
- eprintln!("raea: <SolariLighting> on every camera: {} (docs/nobuild.feature NB1a)", list.join(", "));
- });
- }
+ let env = raea_io_trace::overrides("SolariLighting", VARS);
raea_io_trace::event(
"solari_settings",
serde_json::json!({
@@ -106,18 +94,3 @@ pub(crate) fn record(view: Entity, s: &SolariSettings, scale: f32, seen: &mut Ha
}),
);
}
-
-impl SolariSettings {
- /// the emission is taken out before the denoiser and put back after ("taa" or "split")
- pub(crate) fn split(&self) -> bool {
- self.emissive != "mask"
- }
- /// the emission's history is gathered over frames (emit_taa.rs)
- pub(crate) fn taa(&self) -> bool {
- self.emissive == "taa"
- }
- /// a view drawn small is denoised and brought up in one pass
- pub(crate) fn one_pass(&self) -> bool {
- self.upscale != "two"
- }
-}
diff --git a/engine/render/raytrace/src/upscale.rs b/engine/render/raytrace/src/upscale.rs
index c6a590c8..559c3996 100644
--- a/engine/render/raytrace/src/upscale.rs
+++ b/engine/render/raytrace/src/upscale.rs
@@ -34,6 +34,7 @@ use objc2_metal::{MTLBlitCommandEncoder, MTLCommandBuffer, MTLCommandEncoder, MT
use objc2_metal_fx::{MTLFXTemporalScaler, MTLFXTemporalScalerBase, MTLFXTemporalScalerDescriptor};
use std::sync::atomic::{AtomicBool, Ordering};
use wgpu::hal::api::Metal;
+use raea_sys_post::steady::halton;
/// No temporal scaler on this GPU: every view draws at its full size.
static NONE: AtomicBool = AtomicBool::new(false);
@@ -78,16 +79,6 @@ pub(crate) fn jitter_gain(mode: &str, denoiser: bool, denoised: bool) -> f32 {
}
}
-fn halton(mut i: u32, base: u32) -> f32 {
- let (mut f, mut r) = (1.0, 0.0);
- while i > 0 {
- f /= base as f32;
- r += f * (i % base) as f32;
- i /= base;
- }
- r
-}
-
/// A camera this module jittered, so only its own jitter is taken off when the scale goes back to 1.
#[derive(Component)]
struct Jittered;
diff --git a/io/trace/src/lib.rs b/io/trace/src/lib.rs
index 55a1f286..3a2549f2 100644
--- a/io/trace/src/lib.rs
+++ b/io/trace/src/lib.rs
@@ -26,10 +26,12 @@ use serde_json::{Value, json};
mod crash;
mod look;
+mod props;
mod stats;
use crash::*;
pub use look::{sessions, status, summarize};
+pub use props::overrides;
pub use stats::{choose as choose_stats, chosen as chosen_stats, count, pass_ms, stat, stat_value, stats, table as stats_table};
struct Session {
diff --git a/io/trace/src/props.rs b/io/trace/src/props.rs
new file mode 100644
index 00000000..4368496d
--- /dev/null
+++ b/io/trace/src/props.rs
@@ -0,0 +1,17 @@
+//! The variables that still override a component's props (docs/nobuild.feature NB1a): what was a build or a variable
+//! is a prop now, and a variable left set wins over it, so a run says once which ones did.
+
+use std::collections::BTreeSet;
+use std::sync::Mutex;
+
+/// The variables of `table` (each a variable and the prop it overrides) that are set, with their values. The first time
+/// any is set in a run, stderr says which, over `component`'s props.
+pub fn overrides(component: &str, table: &[(&'static str, &'static str)]) -> Vec<(&'static str, String, &'static str)> {
+ static SAID: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());
+ let set: Vec<_> = table.iter().filter_map(|&(n, prop)| std::env::var(n).ok().map(|v| (n, v, prop))).collect();
+ if !set.is_empty() && SAID.lock().unwrap_or_else(|e| e.into_inner()).insert(component.to_owned()) {
+ let list: Vec<String> = set.iter().map(|(n, v, prop)| format!("{n}={v} over {prop}")).collect();
+ eprintln!("raea: <{component}> on every camera: {} (docs/nobuild.feature NB1a)", list.join(", "));
+ }
+ set
+}
diff --git a/io/trace/src/stats.rs b/io/trace/src/stats.rs
index bc5b2280..301e0a87 100644
--- a/io/trace/src/stats.rs
+++ b/io/trace/src/stats.rs
@@ -72,7 +72,11 @@ pub fn stat_value(var: &str) -> Option<String> {
/// `name=value` gives a view its value (a channel chosen again takes the later value).
pub fn choose(channels: &[String]) {
let mut c = chosen();
- for n in channels.iter().map(|n| n.trim().trim_start_matches("RAEA_").to_ascii_lowercase()).filter(|n| !n.is_empty()) {
+ for n in channels {
+ let n = n.trim().trim_start_matches("RAEA_").to_ascii_lowercase();
+ if n.is_empty() {
+ continue;
+ }
let key = n.split('=').next().unwrap_or_default().to_string();
c.retain(|o| o.split('=').next() != Some(key.as_str()));
c.push(n);
@@ -111,7 +115,7 @@ pub fn stats() -> Value {
let g = TOTALS.lock().ok();
let t = g.as_ref().and_then(|g| g.as_ref());
let passes: serde_json::Map<String, Value> = t.into_iter().flat_map(|t| t.passes.iter()).map(|(k, (n, sum, max))| (k.clone(), json!({"n": n, "mean_ms": round(sum / *n as f64), "max_ms": round(*max)}))).collect();
- let counters: serde_json::Map<String, Value> = t.into_iter().flat_map(|t| t.counters.iter()).map(|(k, n)| (k.clone(), json!(n))).collect();
+ let counters = t.map_or(json!({}), |t| json!(t.counters));
json!({"chosen": chosen(), "passes": passes, "counters": counters})
}
diff --git a/runtime/look/src/camera.rs b/runtime/look/src/camera.rs
index f00a9001..ff2b3d9c 100644
--- a/runtime/look/src/camera.rs
+++ b/runtime/look/src/camera.rs
@@ -28,8 +28,6 @@ pub fn env_shown(sent: Option<&V>, cam: &mut BTreeMap<String, V>) {
cam.insert("env_srcs".into(), V::S(serde_json::to_string(&list).unwrap_or_default()));
}
-/// An <Environment>'s source in env_srcs: its panorama's path, or for <Environment room> `room:` and its blur (three's
-/// RoomEnvironment, which raea-sys-environment's room.rs makes, #165).
/// <Environment portals>' openings, each four corners in order round it, as a corner and its two neighbours
fn portal_corners(list: &[Value]) -> Vec<[[f64; 3]; 3]> {
let point = |p: &Value| -> Option<[f64; 3]> {
@@ -37,13 +35,15 @@ fn portal_corners(list: &[Value]) -> Vec<[[f64; 3]; 3]> {
Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?])
};
list.iter()
- .filter_map(|q| {
- let c: Vec<[f64; 3]> = q.as_array()?.iter().filter_map(point).collect();
- (c.len() == 4).then(|| [c[0], c[1], c[3]])
+ .filter_map(|q| match q.as_array()?.iter().filter_map(point).collect::<Vec<_>>()[..] {
+ [a, b, _, d] => Some([a, b, d]),
+ _ => None,
})
.collect()
}
+/// An <Environment>'s source in env_srcs: its panorama's path, or for <Environment room> `room:` and its blur (three's
+/// RoomEnvironment, which raea-sys-environment's room.rs makes, #165).
pub fn env_src(e: &Item) -> Option<String> {
if e.props.get("room") == Some(&Value::Bool(true)) {
return Some(format!("room:{}", n(&e.props, "blur", 0.0)));
diff --git a/runtime/plugins/src/choose.rs b/runtime/plugins/src/choose.rs
index 480c4e7a..4a08a10e 100644
--- a/runtime/plugins/src/choose.rs
+++ b/runtime/plugins/src/choose.rs
@@ -29,10 +29,10 @@ pub fn catalog(entries: Vec<Entry>) {
*CATALOG.lock().unwrap() = entries;
}
-/// Every compiled plugin in every App from now on, chosen or not: the generator walks all of their types
-/// (raea-bevy-sdk).
-pub fn choose_every() {
- EVERY.store(true, Ordering::Relaxed);
+/// Every compiled plugin in every App from now on (`on`), chosen or not: the generator walks all of their types
+/// (raea-bevy-sdk); off again, only the chosen ones.
+pub fn choose_every(on: bool) {
+ EVERY.store(on, Ordering::Relaxed);
}
/// The catalog's plugins an Engine adds, by name.
@@ -79,7 +79,9 @@ pub fn named(dir: &Path) -> Option<(PathBuf, Vec<String>)> {
/// Whether `s` names a type under `prefix` (at the start of a path, not inside another crate's name).
fn mentions(s: &str, prefix: &str) -> bool {
- s.match_indices(prefix).any(|(i, _)| s[..i].chars().next_back().is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == ':')))
+ // what comes before a crate's name inside a longer one: a letter, a digit, `_`, or the `::` of a path above it
+ let inside = |c: char| c.is_alphanumeric() || c == '_' || c == ':';
+ s.match_indices(prefix).any(|(i, _)| !s[..i].ends_with(inside))
}
/// The plugins an Engine opened on `program` in `dir` adds. Said once on stderr when the project names one this
diff --git a/systems/compose/src/aov.rs b/systems/compose/src/aov.rs
index d9fb138f..43f8b86b 100644
--- a/systems/compose/src/aov.rs
+++ b/systems/compose/src/aov.rs
@@ -54,8 +54,8 @@ pub fn read(rw: &mut World, fw: u32, fh: u32) -> Result<Aov, String> {
let mut q = rw.query::<&ViewPrepassTextures>();
let pick = q
.iter(rw)
- .filter(|t| t.depth.is_some() && t.motion_vectors.is_some())
- .max_by_key(|t| t.size.width * t.size.height)
+ .filter(|t| matches!(t, ViewPrepassTextures { depth: Some(_), motion_vectors: Some(_), .. }))
+ .max_by_key(|t| u64::from(t.size.width) * u64::from(t.size.height))
.ok_or("no 3D camera drew a depth and motion-vector prepass")?;
// the target is a row taller than the frame (the frame tag's row, open.rs), at the frame's scale (RAEA_SS)
let (w, h) = (pick.size.width, pick.size.height.min(fh * (pick.size.width / fw.max(1)).max(1)));
diff --git a/systems/engine-shaders/src/lib.rs b/systems/engine-shaders/src/lib.rs
index db6f2dc6..dd4a6612 100644
--- a/systems/engine-shaders/src/lib.rs
+++ b/systems/engine-shaders/src/lib.rs
@@ -35,25 +35,31 @@ pub fn shadow(app: &mut App, edit_dir: &Path, prog: &Program) {
let declared = DECLARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
for (rel, file) in walk(&dir) {
if std::fs::metadata(&file).is_ok_and(|m| m.len() == 0) {
- let builtin = declared.iter().find(|(r, _)| *r == rel).map(|(_, t)| t.as_bytes().to_vec());
- match builtin.or_else(|| original(app, &rel)).map(|b| std::fs::write(&file, b)) {
- Some(Ok(())) => filled.push(rel),
- Some(Err(e)) => eprintln!("raea: {}: {e}", file.display()),
- None => stray.push(rel),
+ let builtin = declared.get(rel.as_str()).map(|t| t.as_bytes().to_vec());
+ let Some(text) = builtin.or_else(|| original(app, &rel)) else {
+ stray.push(rel);
+ continue;
+ };
+ match std::fs::write(&file, text) {
+ Ok(()) => filled.push(rel),
+ Err(e) => eprintln!("raea: {}: {e}", file.display()),
}
continue;
}
let fork = raea_sys_frame::bevy_api::swapped(&rel);
match replace(app, &rel, &file, &mut swaps) {
Some(_) => ours.push(if fork { format!("{rel} (over raea's fork of Bevy's)") } else { rel }),
- None if declared.iter().any(|(r, _)| *r == rel) => ours.push(format!("{rel} (read as its pass is made)")),
+ None if declared.contains_key(rel.as_str()) => ours.push(format!("{rel} (read as its pass is made)")),
None => stray.push(rel),
}
}
if !ours.is_empty() {
eprintln!("raea: {} of the engine's shaders from {} in place of this raea's ({}); each is tied to this raea's version of it (docs/nobuild.feature NB5b)", ours.len(), dir.display(), ours.join(", "));
}
- let ours: Vec<String> = ours.into_iter().map(|r| r.split(" (").next().unwrap_or_default().to_string()).collect();
+ // the bare paths, without what was said of each
+ for r in &mut ours {
+ r.truncate(r.find(" (").unwrap_or(r.len()));
+ }
if !stray.is_empty() {
eprintln!("raea: {} has no engine shader at {} (the path is <crate>/<path under its src>, as Bevy embeds it)", dir.display(), stray.join(", "));
}
@@ -129,7 +135,7 @@ fn with_constants(app: &mut App, set: &[consts::ShaderConstant], swaps: &mut Vec
let declared = DECLARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
let (mut said, mut changed) = (Vec::new(), Vec::new());
for shader in shaders {
- let builtin = declared.iter().find(|(r, _)| *r == shader).map(|(_, t)| *t);
+ let builtin = declared.get(shader).copied();
let base = match builtin {
Some(b) => Some(source(shader, b).into_owned()),
None => original(app, shader).and_then(|b| String::from_utf8(b).ok()),
@@ -168,16 +174,15 @@ fn with_constants(app: &mut App, set: &[consts::ShaderConstant], swaps: &mut Vec
/// The shaders crates read through `text` (`declare`), each path and its built-in text: a project's file for one isn't
/// stray, and an empty one is filled with it.
-static DECLARED: std::sync::Mutex<Vec<(&'static str, &'static str)>> = std::sync::Mutex::new(Vec::new());
+static DECLARED: std::sync::Mutex<std::collections::BTreeMap<&'static str, &'static str>> = std::sync::Mutex::new(std::collections::BTreeMap::new());
/// Names the shaders a crate reads through `text`: each as `<crate>/<path under its src>` with its built-in text. Call
/// before the Engine's plugins finish (a plugin's build).
pub fn declare(shaders: &[(&'static str, &'static str)]) {
let mut d = DECLARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
- for s in shaders {
- if !d.iter().any(|(r, _)| *r == s.0) {
- d.push(*s);
- }
+ for &(rel, text) in shaders {
+ // a shader declared twice keeps its first text
+ d.entry(rel).or_insert(text);
}
}
diff --git a/systems/fog/src/froxel/solari.rs b/systems/fog/src/froxel/solari.rs
index a43cc807..bc52f251 100644
--- a/systems/fog/src/froxel/solari.rs
+++ b/systems/fog/src/froxel/solari.rs
@@ -142,7 +142,7 @@ pub fn prepare(
mut views: Query<(Entity, &ViewGrid, &ExtractedView, &SolariLighting, Option<&mut SolariFog>, &super::FroxelFog)>,
) {
// <VolumetricFog solari>, RAEA_FOG_SOLARI_* over it (tuning.rs); a view with it off integrates as without Solari
- if !views.iter().any(|v| v.5.tune.solari.on) {
+ if views.iter().all(|v| !v.5.tune.solari.on) {
return;
}
let Some(scene) = scene else { return };
diff --git a/systems/fog/src/froxel/tuning.rs b/systems/fog/src/froxel/tuning.rs
index 5273a420..3fa3c3dc 100644
--- a/systems/fog/src/froxel/tuning.rs
+++ b/systems/fog/src/froxel/tuning.rs
@@ -76,18 +76,14 @@ fn shadow(s: &str) -> Option<ShadowRule> {
})
}
-fn var(name: &str) -> Option<String> {
- std::env::var(name).ok()
-}
-
/// a variable's whole number over 0
fn count(name: &str) -> Option<u32> {
- var(name).and_then(|v| v.parse().ok()).filter(|v: &u32| *v > 0)
+ std::env::var(name).ok()?.parse().ok().filter(|v: &u32| *v > 0)
}
/// a variable's comma-separated numbers, each over its place's prop
fn list<T: std::str::FromStr>(name: &str) -> Vec<Option<T>> {
- var(name).map(|v| v.split(',').map(|x| x.trim().parse().ok()).collect()).unwrap_or_default()
+ std::env::var(name).unwrap_or_default().split(',').map(|x| x.trim().parse().ok()).collect()
}
/// The camera row's tuning, each RAEA_FOG_* variable over its prop.
@@ -122,36 +118,41 @@ pub fn tuning(vals: &Vals) -> Tuning {
},
};
// the variables, as they read before they were props
- if let Some(r) = var("RAEA_FOG_SHADOW").as_deref().and_then(shadow) {
+ if let Some(r) = std::env::var("RAEA_FOG_SHADOW").ok().as_deref().and_then(shadow) {
t.shadow = r;
}
- if let Some(v) = var("RAEA_FOG_HERO_EXACT") {
+ if let Some(v) = std::env::var("RAEA_FOG_HERO_EXACT").ok() {
t.hero_exact = v != "0";
}
- if let Some(v) = var("RAEA_FOG_TRICUBIC_T") {
+ if let Some(v) = std::env::var("RAEA_FOG_TRICUBIC_T").ok() {
t.tricubic = v != "0";
}
- let e: Vec<Option<f32>> = list("RAEA_FOG_EPI");
- let at = |i: usize| e.get(i).copied().flatten();
- t.epi.line_gap = at(0).map_or(t.epi.line_gap, |v| v.max(0.5));
- t.epi.spacing = at(1).map_or(t.epi.spacing, |v| v.max(0.5));
- t.epi.every = at(2).map_or(t.epi.every, |v| (v as u32).max(1));
- t.epi.rel = at(3).unwrap_or(t.epi.rel);
- t.epi.abs = at(4).unwrap_or(t.epi.abs);
- t.epi.depth = at(5).unwrap_or(t.epi.depth);
- if let Some(v) = var("RAEA_FOG_SOLARI") {
+ // RAEA_FOG_EPI=line,spacing,every,rel,abs,depth: each number given over its prop
+ for (i, v) in list::<f32>("RAEA_FOG_EPI").into_iter().enumerate() {
+ let Some(v) = v else { continue };
+ match i {
+ 0 => t.epi.line_gap = v.max(0.5),
+ 1 => t.epi.spacing = v.max(0.5),
+ 2 => t.epi.every = (v as u32).max(1),
+ 3 => t.epi.rel = v,
+ 4 => t.epi.abs = v,
+ 5 => t.epi.depth = v,
+ _ => {}
+ }
+ }
+ if let Some(v) = std::env::var("RAEA_FOG_SOLARI").ok() {
t.solari.on = v != "0";
}
t.solari.candidates = count("RAEA_FOG_SOLARI_CANDIDATES").unwrap_or(t.solari.candidates);
t.solari.frames = count("RAEA_FOG_SOLARI_FRAMES").unwrap_or(t.solari.frames);
t.solari.sky_rays = count("RAEA_FOG_SOLARI_SKY").unwrap_or(t.solari.sky_rays);
- if let Some(p) = var("RAEA_FOG_SOLARI_PARTS") {
+ if let Some(p) = std::env::var("RAEA_FOG_SOLARI_PARTS").ok() {
(t.solari.lamps, t.solari.sky) = (p.contains("lamps"), p.contains("sky"));
}
- if let Some(v) = var("RAEA_FOG_SOLARI_FILTER") {
+ if let Some(v) = std::env::var("RAEA_FOG_SOLARI_FILTER").ok() {
t.solari.filter = v != "0";
}
- if let Some(g) = var("RAEA_FOG_SOLARI_GUIDE").and_then(|v| v.parse::<u32>().ok()) {
+ if let Some(g) = std::env::var("RAEA_FOG_SOLARI_GUIDE").ok().and_then(|v| v.parse::<u32>().ok()) {
t.solari.guide = g & 3;
}
t
@@ -166,12 +167,11 @@ pub fn grid(tile: u32, slices: u32, samples: u32) -> (u32, u32, u32) {
/// RAEA_FOG_HERO over the `hero` prop ("0" off, anything else on).
pub fn hero(prop: bool) -> bool {
- var("RAEA_FOG_HERO").map_or(prop, |v| v != "0")
+ std::env::var("RAEA_FOG_HERO").ok().map_or(prop, |v| v != "0")
}
-/// The RAEA_FOG_* variables set, each with the prop it overrides.
-fn env() -> Vec<(&'static str, String, &'static str)> {
- [
+/// The RAEA_FOG_* variables that override a prop, each with the prop.
+const VARS: &[(&str, &str)] = &[
("RAEA_FOG_MODE", "mode"),
("RAEA_FOG_HERO", "hero"),
("RAEA_FOG_GRID", "tile, slices, samples"),
@@ -186,23 +186,12 @@ fn env() -> Vec<(&'static str, String, &'static str)> {
("RAEA_FOG_SOLARI_PARTS", "solari.lamps and solari.sky"),
("RAEA_FOG_SOLARI_FILTER", "solari.filter"),
("RAEA_FOG_SOLARI_GUIDE", "solari.guide"),
- ]
- .into_iter()
- .filter_map(|(n, prop)| var(n).map(|v| (n, v, prop)))
- .collect()
-}
+];
/// A camera's fog as it draws, into the run's trace (`fog_settings`) each time it's put on: the mode, and for the grid
/// every setting; and once a run, on stderr, which variables override <VolumetricFog>'s props.
pub fn record(camera: Entity, mode: &str, fog: Option<&FroxelFog>) {
- let env = env();
- static SAID: std::sync::Once = std::sync::Once::new();
- if !env.is_empty() {
- SAID.call_once(|| {
- let list: Vec<String> = env.iter().map(|(n, v, prop)| format!("{n}={v} over {prop}")).collect();
- eprintln!("raea: <VolumetricFog> on every camera: {} (docs/nobuild.feature NB1a)", list.join(", "));
- });
- }
+ let env = raea_io_trace::overrides("VolumetricFog", VARS);
let mut j = serde_json::json!({ "camera": camera.to_bits(), "mode": mode, "env": env.iter().map(|(n, v, _)| format!("{n}={v}")).collect::<Vec<_>>() });
if let Some(f) = fog {
let (t, e, s) = (&f.tune, &f.tune.epi, &f.tune.solari);
diff --git a/systems/lod/src/lib.rs b/systems/lod/src/lib.rs
index b7a521e1..ac3c01e7 100644
--- a/systems/lod/src/lib.rs
+++ b/systems/lod/src/lib.rs
@@ -261,7 +261,7 @@ fn given(d: &Detail, at: &GlobalTransform) -> Option<(Vec3, Vec3)> {
let [x0, y0, z0, x1, y1, z1] = d.bounds[..] else { return None };
let m = at.affine();
let corners = (0..8).map(|i| m.transform_point3(Vec3::new([x0, x1][i & 1], [y0, y1][(i >> 1) & 1], [z0, z1][i >> 2])));
- Some(corners.fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), c| (lo.min(c), hi.max(c))))
+ Some((corners.clone().fold(Vec3::MAX, Vec3::min), corners.fold(Vec3::MIN, Vec3::max)))
}
/// the meshes' bounds together, in the world; None before any has bounds
diff --git a/systems/post/src/lens.rs b/systems/post/src/lens.rs
index 7c555fcb..0c32862f 100644
--- a/systems/post/src/lens.rs
+++ b/systems/post/src/lens.rs
@@ -87,9 +87,9 @@ pub fn install(app: &mut App) {
// 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);
- render_app.add_systems(Core3d, lens_pass.after(tonemapping).in_set(Core3dSystems::PostProcess));
+ if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
+ render_app.add_systems(RenderStartup, init_pipeline).add_systems(Core3d, lens_pass.after(tonemapping).in_set(Core3dSystems::PostProcess));
+ }
}
#[derive(Resource)]
diff --git a/systems/post/src/steady.rs b/systems/post/src/steady.rs
index 4165c5ce..26826ee3 100644
--- a/systems/post/src/steady.rs
+++ b/systems/post/src/steady.rs
@@ -76,8 +76,8 @@ pub fn install(app: &mut App) {
render_app.add_systems(Core3d, draw.in_set(Core3dSystems::EarlyPostProcess));
}
-/// the i-th of the Halton sequence in base b, in 0-1
-fn halton(mut i: u32, b: u32) -> f32 {
+/// the i-th of the Halton sequence in base b, in 0-1 (a jitter's places; raea-render-raytrace's upscale uses it too)
+pub fn halton(mut i: u32, b: u32) -> f32 {
let (mut f, mut r) = (1.0, 0.0);
while i > 0 {
f /= b as f32;
@@ -167,7 +167,7 @@ fn init_pipeline(mut commands: Commands, device: Res<RenderDevice>, assets: Res<
);
let shader = assets.load("embedded://raea_sys_post/steady.wesl");
let pipeline = |format: TextureFormat| {
- let target = |format| Some(ColorTargetState { format, blend: None, write_mask: ColorWrites::ALL });
+ let target = |format: TextureFormat| Some(ColorTargetState::from(format));
cache.queue_render_pipeline(RenderPipelineDescriptor {
label: Some("steady".into()),
layout: vec![layout.clone()],
diff --git a/systems/rt/src/cache.rs b/systems/rt/src/cache.rs
index 397d6ce4..3b16c48b 100644
--- a/systems/rt/src/cache.rs
+++ b/systems/rt/src/cache.rs
@@ -78,9 +78,12 @@ pub(crate) struct Passes(pub [CachedComputePipelineId; 6]);
/// cache's group 1
pub(crate) fn queue(cache: &PipelineCache, assets: &AssetServer, layouts: &[BindGroupLayoutDescriptor]) -> Passes {
let (compact, gi) = (assets.load("embedded://raea_sys_rt/compact.wesl"), assets.load("embedded://raea_sys_rt/gi.wesl"));
- Passes([(&compact, "decay"), (&compact, "scan_cells"), (&compact, "scan_blocks"), (&compact, "list"), (&gi, "learn"), (&gi, "blend")].map(|(shader, entry)| {
- cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some(format!("raea_gi_cache_{entry}").into()), layout: layouts.to_vec(), shader: shader.clone(), entry_point: Some(entry.into()), ..default() })
- }))
+ Passes([(&compact, "decay"), (&compact, "scan_cells"), (&compact, "scan_blocks"), (&compact, "list"), (&gi, "learn"), (&gi, "blend")].map(|(shader, entry)| pipeline(cache, "raea_gi_cache", layouts, shader, entry)))
+}
+
+/// One of raea GI's compute passes: `entry` of `shader` over `layouts`, labelled `{label}_{entry}`.
+pub(crate) fn pipeline(cache: &PipelineCache, label: &str, layouts: &[BindGroupLayoutDescriptor], shader: &Handle<Shader>, entry: &str) -> CachedComputePipelineId {
+ cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some(format!("{label}_{entry}").into()), layout: layouts.to_vec(), shader: shader.clone(), entry_point: Some(entry.to_owned().into()), ..default() })
}
/// The cache's buffers (zeroed: every cell empty) and the update's arguments, copied from the list's.
@@ -96,8 +99,9 @@ pub(crate) fn buffers(device: &RenderDevice) -> Buffers {
}
pub(crate) fn bind(device: &RenderDevice, layout: &BindGroupLayout, b: &Buffers, upkeep: BindingResource) -> BindGroup {
- let mut entries: Vec<BindGroupEntry> = b.all.iter().enumerate().map(|(i, buffer)| BindGroupEntry { binding: i as u32, resource: buffer.as_entire_binding() }).collect();
- entries.push(BindGroupEntry { binding: BUFFERS.len() as u32, resource: upkeep });
+ // the buffers in order, then the upkeep uniform
+ let resources = b.all.iter().map(|b| b.as_entire_binding()).chain([upkeep]);
+ let entries: Vec<BindGroupEntry> = resources.enumerate().map(|(i, resource)| BindGroupEntry { binding: i as u32, resource }).collect();
device.create_bind_group("raea_gi_cache", layout, &entries)
}
diff --git a/systems/rt/src/far.rs b/systems/rt/src/far.rs
index 90d6dccd..59ffccb9 100644
--- a/systems/rt/src/far.rs
+++ b/systems/rt/src/far.rs
@@ -10,10 +10,7 @@
//! again RAEA_SUN_FAR_ROWS rows a frame (256), in turn. RAEA_SUN_FAR_STATS: a file the traces' GPU milliseconds are
//! written to, once a second.
-use std::sync::{
- atomic::{AtomicBool, Ordering},
- Arc,
-};
+use std::sync::atomic::Ordering;
use bevy::{
core_pipeline::schedule::Core3d,
@@ -32,15 +29,12 @@ use bevy::{
},
};
-/// The far map's reach from the eye each way, in metres, if RAEA_SUN_FAR asks for one (1, or anything not a number
-/// over 1: 1024).
-pub fn wanted() -> Option<f32> {
- let v = std::env::var("RAEA_SUN_FAR").ok()?;
- Some(v.parse::<f32>().ok().filter(|r| *r > 1.0).unwrap_or(1024.0))
-}
+use crate::timer::Timer;
pub fn install(app: &mut App) {
- let Some(radius) = wanted() else { return };
+ // the far map's reach from the eye each way, in metres, if RAEA_SUN_FAR asks for one (1, or anything not a number
+ // over 1: 1024)
+ let Some(radius) = crate::reach("RAEA_SUN_FAR", 1.0, 1024.0) else { return };
bevy::asset::embedded_asset!(app, "far.wesl");
crate::install(app);
let env = |k: &str, or: u32| std::env::var(k).ok().and_then(|v| v.parse().ok()).unwrap_or(or);
@@ -108,21 +102,13 @@ struct Held {
/// the next row to trace again, and the TLAS (its build count) the pass under way catches up with
row: i32,
since: u64,
- timer: Option<Timer>,
+ /// a trace's timestamps, with what it was and its rays while they're on their way back
+ timer: Option<Timer<(Kind, u32)>>,
/// each timed trace: what it was, its rays, GPU milliseconds
seen: Vec<(Kind, u32, f64)>,
written: Option<std::time::Instant>,
}
-struct Timer {
- set: wgpu::QuerySet,
- resolve: wgpu::Buffer,
- read: wgpu::Buffer,
- period: f64,
- /// a trace's timestamps on their way back, what it was and its rays
- pending: Option<(Arc<AtomicBool>, Kind, u32)>,
-}
-
#[allow(clippy::too_many_arguments)]
fn trace(
far: Res<Far>,
@@ -222,7 +208,7 @@ fn trace(
held.params = Params { dir: dir.extend(texel), u: u.extend(0.15), v: v.extend(0.0), ray: Vec4::new(start, 2.5 * far.radius + 150.0 / dir.y + 200.0, 0.0, 0.0), map: IVec4::new(size, c.x, c.y, 0), region: IVec4::ZERO };
let group = device.create_bind_group("raea_far_sun", &cache.get_bind_group_layout(&p.layout), &BindGroupEntries::sequential((buffer.as_entire_binding(), scene.0.as_binding(), &view)));
if std::env::var_os("RAEA_SUN_FAR_STATS").is_some() && held.timer.is_none() && device.features().contains(WgpuFeatures::TIMESTAMP_QUERY) {
- held.timer = Some(timer(&device, &queue));
+ held.timer = Some(Timer::new(&device, &queue, "raea far sun timer", 2, 16));
}
// a submit each, as each has its own region in the one uniform (a write lands before the submit after it)
for (kind, region) in traces {
@@ -233,50 +219,29 @@ fn trace(
let timed = held.timer.as_ref().is_some_and(|t| t.pending.is_none());
let mut enc = device.create_command_encoder(&CommandEncoderDescriptor { label: Some("raea far sun") });
{
- let writes = held.timer.as_ref().filter(|_| timed).map(|t| wgpu::ComputePassTimestampWrites { query_set: &t.set, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) });
+ let writes = held.timer.as_ref().filter(|_| timed).map(|t| t.writes(0));
let mut pass = enc.begin_compute_pass(&ComputePassDescriptor { label: Some("raea_far_sun"), timestamp_writes: writes });
pass.set_pipeline(pipeline);
pass.set_bind_group(0, &group, &[]);
pass.dispatch_workgroups((region.z as u32).div_ceil(8), (region.w as u32).div_ceil(8), 1);
}
if let Some(t) = held.timer.as_ref().filter(|_| timed) {
- enc.resolve_query_set(&t.set, 0..2, &t.resolve, 0);
- enc.copy_buffer_to_buffer(&t.resolve, 0, &t.read, 0, 16);
+ t.resolve_into(&mut enc);
}
queue.submit([enc.finish()]);
if let Some(t) = held.timer.as_mut().filter(|_| timed) {
- let done = Arc::new(AtomicBool::new(false));
- let d = done.clone();
- t.read.slice(..).map_async(wgpu::MapMode::Read, move |r| d.store(r.is_ok(), Ordering::Release));
- t.pending = Some((done, kind, rays));
+ t.send((kind, rays));
}
}
report(&mut held, &far);
}
-fn timer(device: &RenderDevice, queue: &RenderQueue) -> Timer {
- let d = device.wgpu_device();
- let set = d.create_query_set(&wgpu::QuerySetDescriptor { label: Some("raea far sun timer"), ty: wgpu::QueryType::Timestamp, count: 2 });
- let resolve = d.create_buffer(&wgpu::BufferDescriptor { label: Some("raea far sun timer resolve"), size: 16, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
- let read = d.create_buffer(&wgpu::BufferDescriptor { label: Some("raea far sun timer read"), size: 16, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
- Timer { set, resolve, read, period: queue.get_timestamp_period() as f64, pending: None }
-}
-
/// the last timed trace's GPU milliseconds, once its readback is done
fn collect(held: &mut Held) {
let Some(t) = held.timer.as_mut() else { return };
- let Some((done, kind, rays)) = t.pending.as_ref().map(|(d, k, r)| (d.load(Ordering::Acquire), *k, *r)) else { return };
- if !done {
- return;
+ if let Some((ms, (kind, rays))) = t.take(|ms, _| ms(0, 1)) {
+ held.seen.push((kind, rays, ms));
}
- let ms = {
- let Ok(view) = t.read.slice(..).get_mapped_range() else { return };
- let ts = |i: usize| u64::from_le_bytes(view[8 * i..8 * i + 8].try_into().unwrap());
- ts(1).saturating_sub(ts(0)) as f64 * t.period / 1e6
- };
- t.read.unmap();
- t.pending = None;
- held.seen.push((kind, rays, ms));
}
/// once a second, to RAEA_SUN_FAR_STATS's file: each timed trace of a kind, its count, rays a trace and GPU
diff --git a/systems/rt/src/gi.rs b/systems/rt/src/gi.rs
index 8b41ba2e..fd0ea483 100644
--- a/systems/rt/src/gi.rs
+++ b/systems/rt/src/gi.rs
@@ -12,10 +12,7 @@
//! RAEA_GI_SHOW=volume: the probes light the scene through Bevy's irradiance volume (see `install`). Unset, nothing
//! changes.
-use std::sync::{
- atomic::{AtomicBool, Ordering},
- Arc,
-};
+use std::sync::atomic::Ordering;
use bevy::{
asset::RenderAssetUsages,
@@ -36,6 +33,8 @@ use bevy::{
},
};
+use crate::timer::Timer;
+
/// rays a probe each round (gi.wesl's RAYS: a workgroup a probe, a ray a thread)
const RAYS: u32 = 64;
@@ -199,9 +198,7 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCac
let shader = assets.load("embedded://raea_sys_rt/gi.wesl");
let cache_layout = crate::cache::layout();
let layouts = vec![layout.clone(), cache_layout.clone()];
- let [id, resolve] = ["main", "resolve"].map(|entry| {
- cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some(format!("raea_gi_{entry}").into()), layout: layouts.clone(), shader: shader.clone(), entry_point: Some(entry.into()), ..default() })
- });
+ let [id, resolve] = ["main", "resolve"].map(|entry| crate::cache::pipeline(&cache, "raea_gi", &layouts, &shader, entry));
let passes = crate::cache::queue(&cache, &assets, &layouts);
let sampler = device.create_sampler(&SamplerDescriptor { label: Some("raea gi sky"), mag_filter: FilterMode::Linear, min_filter: FilterMode::Linear, ..default() });
let shown = std::env::var("RAEA_GI_SHOW").as_deref() == Ok("volume");
@@ -216,21 +213,13 @@ struct State {
cache: Option<crate::cache::Buffers>,
frame: u32,
key: Option<[u32; 9]>,
- timer: Option<Timer>,
+ /// the cache's start and end, the probes' start and end; the read-back also takes the cache's live cells
+ timer: Option<Timer<()>>,
/// each timed frame's GPU milliseconds, the cache's and the probes', and the cache's live cells
seen: Vec<(f64, f64, u32)>,
written: Option<std::time::Instant>,
}
-struct Timer {
- set: wgpu::QuerySet,
- resolve: wgpu::Buffer,
- read: wgpu::Buffer,
- period: f64,
- /// a frame's timestamps on their way back
- pending: Option<Arc<AtomicBool>>,
-}
-
/// what the grid is lit from: the sun and the sky (and its size); any change starts every mean again. Not its place:
/// a probe is kept by where it is in the world, so the grid moving starts only the probes new to it (gi.wesl `tags`).
fn key(g: &Grid) -> [u32; 9] {
@@ -307,7 +296,7 @@ fn update(
let cells = state.cache.get_or_insert_with(|| crate::cache::buffers(&device));
let cache_group = crate::cache::bind(&device, &cache.get_bind_group_layout(&p.cache_layout), cells, upkeep.binding().unwrap());
if state.timer.is_none() && device.features().contains(WgpuFeatures::TIMESTAMP_QUERY) {
- state.timer = Some(timer(&device, &queue));
+ state.timer = Some(Timer::new(&device, &queue, "raea gi timer", 4, 48));
}
let (cubes, tags, _) = state.cubes.as_ref().unwrap();
let group = device.create_bind_group(
@@ -328,7 +317,7 @@ fn update(
// The probes, only where they light something. Unshown, their pass keeps one workgroup of `resolve`: on the Mac the
// cache's last pass writes its end time only when a timed pass follows it (11-18: without one it read 0).
{
- let writes = state.timer.as_ref().filter(|_| timed).map(|t| wgpu::ComputePassTimestampWrites { query_set: &t.set, beginning_of_pass_write_index: Some(2), end_of_pass_write_index: Some(3) });
+ let writes = state.timer.as_ref().filter(|_| timed).map(|t| t.writes(2));
let mut pass = enc.begin_compute_pass(&ComputePassDescriptor { label: Some("raea_gi"), timestamp_writes: writes });
pass.set_bind_group(0, &group, &[]);
pass.set_bind_group(1, &cache_group, &[]);
@@ -341,45 +330,25 @@ fn update(
pass.dispatch_workgroups(if p.shown { total.div_ceil(64) } else { 1 }, 1, 1);
}
if let Some(t) = state.timer.as_ref().filter(|_| timed) {
- enc.resolve_query_set(&t.set, 0..4, &t.resolve, 0);
- enc.copy_buffer_to_buffer(&t.resolve, 0, &t.read, 0, 32);
+ t.resolve_into(&mut enc);
enc.copy_buffer_to_buffer(&cells.all[crate::cache::COUNT], 0, &t.read, 32, 4);
}
queue.submit([enc.finish()]);
if let Some(t) = state.timer.as_mut().filter(|_| timed) {
- let done = Arc::new(AtomicBool::new(false));
- let d = done.clone();
- t.read.slice(..).map_async(wgpu::MapMode::Read, move |r| d.store(r.is_ok(), Ordering::Release));
- t.pending = Some(done);
+ t.send(());
}
report(&mut state, budget, total);
}
-fn timer(device: &RenderDevice, queue: &RenderQueue) -> Timer {
- let d = device.wgpu_device();
- // the cache's start and end, the probes' start and end; the read-back also takes the cache's live cells
- let set = d.create_query_set(&wgpu::QuerySetDescriptor { label: Some("raea gi timer"), ty: wgpu::QueryType::Timestamp, count: 4 });
- let resolve = d.create_buffer(&wgpu::BufferDescriptor { label: Some("raea gi timer resolve"), size: 32, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
- let read = d.create_buffer(&wgpu::BufferDescriptor { label: Some("raea gi timer read"), size: 48, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
- Timer { set, resolve, read, period: queue.get_timestamp_period() as f64, pending: None }
-}
-
/// the last timed frame's GPU milliseconds, once its readback is done
fn collect(state: &mut State, shown: bool) {
let Some(t) = state.timer.as_mut() else { return };
- let Some(done) = t.pending.as_ref() else { return };
- if !done.load(Ordering::Acquire) {
- return;
- }
- let (cache_ms, probes_ms, cells) = {
- let Ok(view) = t.read.slice(..).get_mapped_range() else { return };
- let ts = |i: usize| u64::from_le_bytes(view[8 * i..8 * i + 8].try_into().unwrap());
- let ms = |a: usize, b: usize| ts(b).saturating_sub(ts(a)) as f64 * t.period / 1e6;
- // unshown, the cache runs to the end of the marker pass after it (its own end time reads 0 there)
+ // unshown, the cache runs to the end of the marker pass after it (its own end time reads 0 there)
+ let Some(((cache_ms, probes_ms, cells), ())) = t.take(|ms, view| {
(if shown { ms(0, 1) } else { ms(0, 3) }, if shown { ms(2, 3) } else { 0.0 }, u32::from_le_bytes(view[32..36].try_into().unwrap()))
+ }) else {
+ return;
};
- t.read.unmap();
- t.pending = None;
// a frame whose times came back (the probes' pass may be empty: not shown)
if cache_ms > 0.0 {
state.seen.push((cache_ms, probes_ms, cells));
diff --git a/systems/rt/src/lib.rs b/systems/rt/src/lib.rs
index 33f35676..c9df1f57 100644
--- a/systems/rt/src/lib.rs
+++ b/systems/rt/src/lib.rs
@@ -16,6 +16,8 @@ pub mod far;
// what a hit sees: each instance's averaged albedo and emission (LT4's first tier)
pub mod records;
pub mod traced_ao;
+// a traced pass's GPU time, read back a frame later (raea GI's and the far sun's stats)
+mod timer;
/// Every traced pass asked for: traced AO (RAEA_TRACED_AO), raea GI's probes (RAEA_GI), the sun's far shadow map
/// (RAEA_SUN_FAR). Nothing when none is.
@@ -95,6 +97,12 @@ struct Held {
record_buf: Option<Buffer>,
}
+/// A traced pass's reach from its variable, in metres, if the variable is set: its number when over `least`, else `or`.
+pub(crate) fn reach(var: &str, least: f32, or: f32) -> Option<f32> {
+ let v = std::env::var(var).ok()?;
+ Some(v.parse::<f32>().ok().filter(|r| *r > least).unwrap_or(or))
+}
+
pub fn install(app: &mut App) {
// (once, whether a traced pass or traced AO asked first)
if app.world().contains_resource::<Instances>() {
@@ -253,11 +261,15 @@ fn build_tlas(mut commands: Commands, instances: Option<Res<Instances>>, blases:
return;
}
let t0 = std::time::Instant::now();
- let with: Vec<_> = instances.0.iter().filter(|(id, ..)| blases.0.contains_key(id)).collect();
+ // the instances whose mesh has its BLAS built, and those still waiting for one
+ let (mut with, mut without) = (Vec::new(), Vec::new());
+ for i in &instances.0 {
+ if blases.0.contains_key(&i.0) { with.push(i) } else { without.push(i) }
+ }
let now: Vec<(AssetId<Mesh>, [f32; 12], u8)> = with.iter().map(|(id, m, mask, _)| (*id, m.transpose().to_cols_array()[..12].try_into().unwrap(), *mask)).collect();
let recs: Vec<records::Record> = with.iter().map(|(.., r)| *r).collect();
if std::env::var_os("RAEA_RT_DEBUG").is_some() {
- for (id, ..) in instances.0.iter().filter(|(id, ..)| !blases.0.contains_key(id)) {
+ for (id, ..) in without {
eprintln!("raea rt: no BLAS for {id:?}");
}
}
diff --git a/systems/rt/src/timer.rs b/systems/rt/src/timer.rs
new file mode 100644
index 00000000..303564e1
--- /dev/null
+++ b/systems/rt/src/timer.rs
@@ -0,0 +1,69 @@
+//! A traced pass's GPU time, read back without waiting on the GPU: its timestamps resolved into a buffer that's mapped
+//! once the frame's work is done, and read on a later frame. raea GI's probes and the far sun's traces use it.
+
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+};
+
+use bevy::render::renderer::{RenderDevice, RenderQueue};
+
+/// A pass's timestamps and what rides along with them (`P`: what was timed) while they're on their way back.
+pub(crate) struct Timer<P> {
+ pub(crate) set: wgpu::QuerySet,
+ resolve: wgpu::Buffer,
+ pub(crate) read: wgpu::Buffer,
+ stamps: u32,
+ period: f64,
+ pub(crate) pending: Option<(Arc<AtomicBool>, P)>,
+}
+
+impl<P> Timer<P> {
+ /// `stamps` timestamps (two a pass), read back into `read` bytes: the stamps first, then anything the caller copies
+ /// after them.
+ pub(crate) fn new(device: &RenderDevice, queue: &RenderQueue, label: &str, stamps: u32, read: u64) -> Self {
+ let d = device.wgpu_device();
+ let set = d.create_query_set(&wgpu::QuerySetDescriptor { label: Some(label), ty: wgpu::QueryType::Timestamp, count: stamps });
+ let buffer = |what: &str, size: u64, usage: wgpu::BufferUsages| {
+ d.create_buffer(&wgpu::BufferDescriptor { label: Some(&format!("{label} {what}")), size, usage, mapped_at_creation: false })
+ };
+ let resolve = buffer("resolve", 8 * stamps as u64, wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC);
+ let read = buffer("read", read, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ);
+ Timer { set, resolve, read, stamps, period: queue.get_timestamp_period() as f64, pending: None }
+ }
+
+ /// A pass's start and end, into stamps `first` and `first + 1`.
+ pub(crate) fn writes(&self, first: u32) -> wgpu::ComputePassTimestampWrites<'_> {
+ wgpu::ComputePassTimestampWrites { query_set: &self.set, beginning_of_pass_write_index: Some(first), end_of_pass_write_index: Some(first + 1) }
+ }
+
+ /// Every stamp into the read-back, after the timed passes.
+ pub(crate) fn resolve_into(&self, enc: &mut wgpu::CommandEncoder) {
+ enc.resolve_query_set(&self.set, 0..self.stamps, &self.resolve, 0);
+ enc.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, 8 * self.stamps as u64);
+ }
+
+ /// After the submit: the read-back mapped when the GPU is done with it, `what` kept beside it.
+ pub(crate) fn send(&mut self, what: P) {
+ let done = Arc::new(AtomicBool::new(false));
+ let d = done.clone();
+ self.read.slice(..).map_async(wgpu::MapMode::Read, move |r| d.store(r.is_ok(), Ordering::Release));
+ self.pending = Some((done, what));
+ }
+
+ /// The read-back once it's mapped: `read` gets the milliseconds between two stamps and the bytes, then the buffer is
+ /// let go for the next timed frame. None while it's still on its way.
+ pub(crate) fn take<R>(&mut self, read: impl FnOnce(&dyn Fn(usize, usize) -> f64, &[u8]) -> R) -> Option<(R, P)> {
+ if !self.pending.as_ref()?.0.load(Ordering::Acquire) {
+ return None;
+ }
+ let r = {
+ let view = self.read.slice(..).get_mapped_range().ok()?;
+ let ts = |i: usize| u64::from_le_bytes(view[8 * i..8 * i + 8].try_into().unwrap());
+ let ms = |a: usize, b: usize| ts(b).saturating_sub(ts(a)) as f64 * self.period / 1e6;
+ read(&ms, &view)
+ };
+ self.read.unmap();
+ self.pending.take().map(|(_, what)| (r, what))
+ }
+}
diff --git a/systems/rt/src/traced_ao.rs b/systems/rt/src/traced_ao.rs
index c784575e..09124dd1 100644
--- a/systems/rt/src/traced_ao.rs
+++ b/systems/rt/src/traced_ao.rs
@@ -22,14 +22,9 @@ use bevy::{
},
};
-/// The reach RAEA_TRACED_AO asks for, in metres, if any.
-pub fn wanted() -> Option<f32> {
- let v = std::env::var("RAEA_TRACED_AO").ok()?;
- Some(v.parse::<f32>().ok().filter(|r| *r > 0.0).unwrap_or(0.5))
-}
-
pub fn install(app: &mut App) {
- let Some(reach) = wanted() else { return };
+ // the reach RAEA_TRACED_AO asks for, in metres, if any
+ let Some(reach) = crate::reach("RAEA_TRACED_AO", 0.0, 0.5) else { return };
bevy::asset::embedded_asset!(app, "traced_ao.wesl");
crate::install(app);
let Some(render) = app.get_sub_app_mut(RenderApp) else { return };
diff --git a/tools/dupes.max b/tools/dupes.max
index 54dcb9cc..2dbb0123 100644
--- a/tools/dupes.max
+++ b/tools/dupes.max
@@ -29,5 +29,5 @@
# tone) and Rng::range (core/grow mesh.rs Rng::range in f64; foliage's stream is its own, so moving it to
# core/grow's would change every tree)
# near: runtime/live props.rs Live::controls/held (accessors); io/av1 and io/soft Backend::sound (one-line forwards)
-exact=294
-near=58
+exact=293
+near=57