From ee42e314694fdf8a72427d2a91dc45e2e2721749 Mon Sep 17 00:00:00 2001 From: shinyobjectz Date: Thu, 19 Nov 2026 14:47:44 -0800 Subject: [PATCH] NB2a: stat channels and pass timings chosen and read from TypeScript io/trace's stats.rs: a stat channel is a RAEA_ variable's name without RAEA_ (bake_trace, trace, bevy_passes), on when the composition chose it (native("stats.on", { channels }) at its top level), when RAEA_STATS lists it, or when its variable is set, the override. The 51 reads of 24 trace and stat variables go through raea_io_trace::stat. Each of Bevy's render passes (RenderDiagnosticsPlugin, on by bevy_passes) and PassTimer's go into the run's totals, with the counters engine/draws and engine/updates; native("stats.read", {}) returns them, and a run that chose a channel prints the table and keeps stats.json in its trace folder (docs/manual/reference/cli/traces.md). tools/nobuild.sh stats checks it: every channel decided done reads through stat(); the scene choosing bevy_passes and trace traces, reads 9 passes and 11 draws back on its last frame, prints the table and keeps stats.json; with nothing chosen nothing prints; RAEA_TRACE=1 and RAEA_STATS give the same trace lines. 12 frames take 12 updates. raea-render's lines stay as they were (NB4a's plugin choice folded to one line). native-calls.ts gains the two calls, and bevy.app.*, which raea registers now that the macOS build links the plugin catalog. --- Cargo.lock | 18 ++++ docs/manual/reference/cli/traces.md | 23 +++++ engine/page/host/Cargo.toml | 1 + engine/page/host/src/page.rs | 2 +- engine/page/stage/Cargo.toml | 1 + engine/page/stage/src/lib.rs | 2 +- engine/render/src/engine.rs | 7 +- engine/render/src/engine/open.rs | 9 +- engine/render/src/engine/output.rs | 6 +- engine/render/src/engine/target.rs | 8 +- engine/rune/bevy/Cargo.toml | 1 + engine/rune/bevy/src/input.rs | 2 +- engine/seedling/Cargo.toml | 1 + engine/seedling/src/lib.rs | 6 +- io/apple/src/decode.rs | 2 +- io/apple/src/vt.rs | 8 +- io/apple/src/vtseek.rs | 8 +- io/trace/src/lib.rs | 9 +- io/trace/src/stats.rs | 132 ++++++++++++++++++++++++++++ runtime/bake/Cargo.toml | 1 + runtime/bake/src/lib.rs | 10 +-- runtime/bundle/Cargo.toml | 1 + runtime/bundle/src/fresh.rs | 2 +- runtime/calls/Cargo.toml | 1 + runtime/calls/src/lib.rs | 6 ++ runtime/dom/Cargo.toml | 1 + runtime/dom/media/Cargo.toml | 1 + runtime/dom/media/src/lib.rs | 2 +- runtime/dom/src/host/bridge.rs | 4 +- runtime/export/Cargo.toml | 1 + runtime/export/src/fed.rs | 2 +- runtime/export/src/render.rs | 2 +- runtime/export/src/sound.rs | 2 +- runtime/gpuframe/Cargo.toml | 1 + runtime/gpuframe/src/pool.rs | 2 +- runtime/js/Cargo.toml | 1 + runtime/js/src/media_play.rs | 2 +- runtime/live/src/lib.rs | 6 +- runtime/live/src/sound.rs | 6 +- runtime/plugins/src/lib.rs | 2 +- runtime/scene3d/Cargo.toml | 1 + runtime/scene3d/src/model.rs | 2 +- runtime/segments/Cargo.toml | 1 + runtime/segments/src/encode.rs | 2 +- runtime/sound/Cargo.toml | 1 + runtime/sound/src/lib.rs | 2 +- runtime/view/Cargo.toml | 1 + runtime/view/src/gpuview/render.rs | 4 +- sdk/raea/src/native-calls.ts | 16 ++++ systems/contact/Cargo.toml | 1 + systems/contact/src/lib.rs | 2 +- systems/mix/src/live.rs | 2 +- systems/mix/src/offline.rs | 2 +- systems/page/Cargo.toml | 1 + systems/page/src/draw.rs | 2 +- systems/page/src/lib.rs | 2 +- tools/nobuild.sh | 44 +++++++++- tools/nobuild/stats/stats.tsx | 42 +++++++++ 58 files changed, 367 insertions(+), 63 deletions(-) create mode 100644 io/trace/src/stats.rs create mode 100644 tools/nobuild/stats/stats.tsx diff --git a/Cargo.lock b/Cargo.lock index 630616db..86bae347 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14824,6 +14824,7 @@ dependencies = [ "raea-io-media", "raea-io-net-calls", "raea-io-os", + "raea-io-trace", "raea-page", "raea-page-sound", "raea-page-stage", @@ -14860,6 +14861,7 @@ dependencies = [ "blitz-dom", "raea-gpu-device", "raea-io-home", + "raea-io-trace", "raea-runtime-bake", "raea-runtime-dom", "raea-runtime-js", @@ -14983,6 +14985,7 @@ name = "raea-rune-bevy" version = "0.1.0" dependencies = [ "bevy", + "raea-io-trace", "rune", "wgpu", ] @@ -15110,6 +15113,7 @@ version = "0.1.0" dependencies = [ "bevy", "raea-io-home", + "raea-io-trace", "raea-modules", "raea-runtime-bundle", "raea-runtime-react", @@ -15126,6 +15130,7 @@ dependencies = [ "raea-core-scene", "raea-io-home", "raea-io-media", + "raea-io-trace", "raea-native", "raea-runtime-bundle-lib", "raea-runtime-cssurls", @@ -15159,6 +15164,7 @@ dependencies = [ "raea-core-shape", "raea-io-media", "raea-io-net", + "raea-io-trace", "raea-native", "raea-runtime-plugins", "raea-runtime-wear", @@ -15199,6 +15205,7 @@ dependencies = [ "keyboard-types", "raea-core-wire", "raea-io-net", + "raea-io-trace", "raea-runtime-dom-media", "raea-runtime-js", "raea-runtime-twins", @@ -15216,6 +15223,7 @@ dependencies = [ "bevy", "blitz-dom", "raea-io-net", + "raea-io-trace", "raea-runtime-js", "raea-sys-image", "raea-sys-page", @@ -15273,6 +15281,7 @@ dependencies = [ "raea-io-kept", "raea-io-media", "raea-io-net", + "raea-io-trace", "raea-page", "raea-render", "raea-runtime-bake", @@ -15304,6 +15313,7 @@ dependencies = [ "raea-core-k", "raea-core-program", "raea-gpu-device", + "raea-io-trace", "raea-runtime-view", "raea-sys-frame", "raea-sys-k", @@ -15341,6 +15351,7 @@ dependencies = [ "raea-io-net", "raea-io-net-calls", "raea-io-os", + "raea-io-trace", "raea-runtime-bundle", "raea-runtime-jsengine", "serde", @@ -15519,6 +15530,7 @@ version = "0.1.0" dependencies = [ "bevy", "raea-core-program", + "raea-io-trace", "raea-runtime-plugins", "raea-sys-compute", "raea-sys-copies", @@ -15542,6 +15554,7 @@ dependencies = [ "muxide", "raea-io-codec", "raea-io-media", + "raea-io-trace", "re_mp4", ] @@ -15573,6 +15586,7 @@ version = "0.1.0" dependencies = [ "bevy", "raea-io-assets", + "raea-io-trace", "raea-runtime-calls", "raea-runtime-react", "raea-seedling", @@ -15626,6 +15640,7 @@ dependencies = [ "raea-gpu-device", "raea-io-home", "raea-io-media", + "raea-io-trace", "raea-page", "raea-sys-frame", "raea-sys-k", @@ -15680,6 +15695,7 @@ dependencies = [ "bevy_seedling", "firewheel", "raea-io-media", + "raea-io-trace", "raea-sys-mix", "raea-sys-tone", "serde_json", @@ -15798,6 +15814,7 @@ dependencies = [ "raea-core-meshcheck", "raea-core-scene", "raea-core-shape", + "raea-io-trace", "serde_json", ] @@ -16262,6 +16279,7 @@ dependencies = [ "raea-core-facts", "raea-core-wire", "raea-gpu-device", + "raea-io-trace", "raea-sys-filters", "raea-sys-fonts", "raea-sys-image", diff --git a/docs/manual/reference/cli/traces.md b/docs/manual/reference/cli/traces.md index d72d1384..667cf8ea 100644 --- a/docs/manual/reference/cli/traces.md +++ b/docs/manual/reference/cli/traces.md @@ -15,6 +15,29 @@ raea traces show # the newest raea traces show 3 # the fourth in the list ``` +## What a run measures + +A run can also time each of Bevy's render passes, count what the engine does, and turn on raea's own traces. Each +of these is a stat channel, and you choose channels from your composition, so you don't need a rebuild or a variable. +Choose them at the file's top level, so they're on before the engine opens: + +```tsx +import { native } from "@raea/app/native"; + +native("stats.on", { channels: ["bevy_passes", "trace"] }); // or ["all"] +``` + +`bevy_passes` times every render pass Bevy runs. Every other channel is one of raea's `RAEA_*_TRACE` or `*_STATS` +switches, named without `RAEA_` and in lower case: `bake_trace`, `seedling_trace`, `media_stats`. Setting the variable +itself still works and overrides the composition, and `RAEA_STATS=bevy_passes,trace` chooses channels for a run without +touching the file. + +While the run goes, `native("stats.read", {})` gives what it has measured so far: each timed pass's runs and its mean +and worst milliseconds, and the counters (`engine/draws`, `engine/updates`; two updates a draw means each frame was +drawn twice). A render works out its frames ahead of the engine, so a frame's code can read the totals from before that +frame was drawn. When a run that chose any channel ends, it prints the table and keeps it as `stats.json` in its session +folder, which is the folder `raea traces show` reads. + ## Usage diff --git a/engine/page/host/Cargo.toml b/engine/page/host/Cargo.toml index 2cada488..ff275737 100644 --- a/engine/page/host/Cargo.toml +++ b/engine/page/host/Cargo.toml @@ -21,6 +21,7 @@ portable = ["raea-runtime-js/portable"] window = ["bevy/bevy_winit", "dep:raea-runtime-plugins", "raea-page-window/window"] [dependencies] +raea-io-trace = { path = "../../../io/trace" } # the window as an image the UI camera draws, picking's pointer input, the remote protocol, and every image format the # page decodes (raea-page's IMAGE_DECODER decodes through bevy_image): the legacy app's list, which the benches ran on bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "tonemapping_luts", "ktx2", "zstd_rust", "bevy_picking", "ui_picking", "bevy_ui_widgets", "bevy_input_focus", "jpeg", "bevy_remote", "tga", "qoi", "tiff", "pnm", "ff", "dds", "exr", "hdr", "webp", "gif", "bmp", "ico"] } diff --git a/engine/page/host/src/page.rs b/engine/page/host/src/page.rs index 69a91941..8b366f19 100644 --- a/engine/page/host/src/page.rs +++ b/engine/page/host/src/page.rs @@ -134,7 +134,7 @@ pub fn input(world: &mut World, mut at: Local) { continue; } let Some(ui) = at.event(ev) else { continue }; - if std::env::var_os("RAEA_PAGE_EVENTS").is_some() { + if raea_io_trace::stat("RAEA_PAGE_EVENTS") { eprintln!("raea-page-host: frame {} {ui:?}", world.resource::().0); } if matches!(ui, blitz_traits::events::UiEvent::PointerDown(_)) { diff --git a/engine/page/stage/Cargo.toml b/engine/page/stage/Cargo.toml index 0f965d99..615ba6f9 100644 --- a/engine/page/stage/Cargo.toml +++ b/engine/page/stage/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "The live stage in a raea page: a game item's composition played live in the page's on raea-runtime-react's live engine, its frames copied on the GPU, driven by stage.* host calls" [dependencies] +raea-io-trace = { path = "../../../io/trace" } bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "tonemapping_luts", "ktx2", "zstd_rust", "bevy_picking", "ui_picking", "bevy_ui_widgets", "bevy_input_focus", "jpeg", "bevy_remote", "tga", "qoi", "tiff", "pnm", "ff", "dds", "exr", "hdr", "webp", "gif", "bmp", "ico"] } raea-io-home = { path = "../../../io/home" } raea-runtime-js = { path = "../../../runtime/js" } diff --git a/engine/page/stage/src/lib.rs b/engine/page/stage/src/lib.rs index 8f34180c..4b2155ca 100644 --- a/engine/page/stage/src/lib.rs +++ b/engine/page/stage/src/lib.rs @@ -235,7 +235,7 @@ fn run(rx: Receiver, status: Arc>, slot: Arc>) // the scene shown as wireframe (stage.wire), and a file just opened that hasn't taken it yet let (mut wire, mut rewire) = (false, false); // RAEA_STAGE_TRACE=1: each frame stepped and its keys, on stderr - let trace = std::env::var("RAEA_STAGE_TRACE").as_deref() == Ok("1"); + let trace = raea_io_trace::stat("RAEA_STAGE_TRACE"); // the stage's size, which the page's points are in let mut stage = (1u32, 1u32); // what it shows, and the input of each frame stepped since (a tweak's next version replays it) diff --git a/engine/render/src/engine.rs b/engine/render/src/engine.rs index 009e62c1..c6a50931 100644 --- a/engine/render/src/engine.rs +++ b/engine/render/src/engine.rs @@ -140,12 +140,13 @@ impl Drop for Engine { fn drop(&mut self) { self.app.get_sub_app_mut(bevy::render::RenderApp).map(|sub| sub.world_mut().try_schedule_scope(bevy::render::ExtractSchedule, |w, s| s.apply_deferred(w))); } } +#[cfg(feature = "native")] pub(crate) use raea_io_trace::stat; #[cfg(not(feature = "native"))] pub(crate) fn stat(_: &str) -> bool { false } // a stat channel (io/trace stats.rs, nobuild NB2a); the web's build has none /// RAEA_MEM_MARKS: one line on stderr per start-up phase, "mem_mark /// ", to line up with a memory timeline (the footprint is the process's, as the OS counts it). pub fn mem_mark(what: &str) { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); static T0: std::sync::OnceLock = std::sync::OnceLock::new(); - if !*ON.get_or_init(|| std::env::var_os("RAEA_MEM_MARKS").is_some()) { + if !*ON.get_or_init(|| stat("RAEA_MEM_MARKS")) { return; } let t = T0.get_or_init(bevy::platform::time::Instant::now).elapsed().as_secs_f64() * 1e3; @@ -246,7 +247,7 @@ impl Engine { // Bevy's generated environment map, took three, so RR0's sunset shot opened 2 frames dark, RR1). A plugin's // clock steps on the first and holds on the rest, as `frames` warms up a cut and a shot rendered alone its load let cut = std::mem::take(&mut self.warm_next) || self.drawn.is_some_and(|d| self.app.world().get_resource::().is_some_and(|c| c.between(d, f))); - self.drawn = Some(f); + self.drawn = Some(f); #[cfg(feature = "native")] raea_io_trace::count("engine/draws", 1); if cut { self.pipe.flush(&mut self.app); for _ in 0..8 { @@ -257,7 +258,7 @@ impl Engine { self.pre_step(); plugins::arm(self.app.world_mut()); self.pipe.flush(&mut self.app); - self.app.update(); + self.app.update(); #[cfg(feature = "native")] raea_io_trace::count("engine/updates", 1); self.capture_aov(f); raea_sys_frame::layer::record(self.app.world_mut(), f); } diff --git a/engine/render/src/engine/open.rs b/engine/render/src/engine/open.rs index f801f116..f0009ccc 100644 --- a/engine/render/src/engine/open.rs +++ b/engine/render/src/engine/open.rs @@ -61,8 +61,7 @@ impl Engine { #[cfg(not(target_arch = "wasm32"))] let group = group.disable::(); // the registered plugins' changes (of the catalog's, those the project chose: nobuild NB4a), no WinitPlugin (no event loop, #182) - let chosen = plugins::choose(prog, dir); - app.add_plugins(plugins::group_chosen(group, &chosen)).insert_resource(chosen); + { let chosen = plugins::choose(prog, dir); app.add_plugins(plugins::group_chosen(group, &chosen)).insert_resource(chosen); } #[cfg(feature = "raytracing")] if raea_render_raytrace::wanted(prog) { raea_render_raytrace::add(&mut app); @@ -117,11 +116,11 @@ impl Engine { ); } // each render pass's time (CPU side on Metal, where wgpu has no timestamps inside passes), into the run's trace - // once a second as `bevy_passes`: a slow frame shows which of Bevy's passes it was. RAEA_BEVY_PASSES=1 only: its + // once a second as `bevy_passes`: a slow frame shows which of Bevy's passes it was. The stat channel bevy_passes only: its // statistics buffer is read back every frame, and play and a render's page path read nothing back (docs/blitz- // bevy.feature B1d) #[cfg(feature = "native")] - if std::env::var("RAEA_BEVY_PASSES").as_deref() == Ok("1") { + if raea_io_trace::stat("RAEA_BEVY_PASSES") { app.add_plugins(bevy::render::diagnostic::RenderDiagnosticsPlugin).add_systems(Last, forward_render_diagnostics); } // raea's modules as Bevy plugins, in the order they were installed one by one (raea_plugins.rs), then the @@ -160,7 +159,7 @@ impl Engine { } } // RAEA_MEM_MARKS: the render world's sets, marked through the first updates (where start-up memory goes) - if std::env::var_os("RAEA_MEM_MARKS").is_some() { + if super::stat("RAEA_MEM_MARKS") { use bevy::render::{Render, RenderSystems as RS}; fn at(name: &'static str) -> impl FnMut() { let mut n = 0u32; diff --git a/engine/render/src/engine/output.rs b/engine/render/src/engine/output.rs index a7ab2cdf..2a74820a 100644 --- a/engine/render/src/engine/output.rs +++ b/engine/render/src/engine/output.rs @@ -23,7 +23,7 @@ impl Engine { self.pre_step(); let t = std::time::Instant::now(); plugins::arm(self.app.world_mut()); - self.pipe.update(&mut self.app); + self.pipe.update(&mut self.app); raea_io_trace::count("engine/updates", 1); let dt = t.elapsed().as_nanos() as u64; let mut wait = 0; if self.serial { @@ -107,7 +107,7 @@ impl Engine { let want = tag_colour(f, self.app.world().resource::().0); let mut prev: Option> = None; for i in 0..240 { - if std::env::var_os("RAEA_TRACE").is_some() { + if raea_io_trace::stat("RAEA_TRACE") { eprintln!("trace frame {f} update {i}"); } self.step(); @@ -208,7 +208,7 @@ impl Engine { raea_gpu_device::check::panic_fault(list[sent]); sent += 1; } - if std::env::var_os("RAEA_TRACE").is_some() { + if raea_io_trace::stat("RAEA_TRACE") { eprintln!("trace pipelined next {} sent {sent}", list[next]); } self.step(); diff --git a/engine/render/src/engine/target.rs b/engine/render/src/engine/target.rs index 058b17ff..f23c795d 100644 --- a/engine/render/src/engine/target.rs +++ b/engine/render/src/engine/target.rs @@ -4,11 +4,11 @@ use super::*; pub(crate) use raea_sys_viewbox::{TagRowTarget, ViewBox, tag_row_view}; -/// Bevy's render diagnostics (each pass's elapsed time, `render/...`), into the run's trace once a second. +/// Bevy's render diagnostics (each pass's elapsed time, `render/...`): each new measurement into the run's totals (stats.read, the stats table: nobuild NB2a), the smoothed ones into its trace once a second. #[cfg(feature = "native")] -pub(crate) fn forward_render_diagnostics(store: Res, mut last: Local>) { - if last.is_some_and(|t| t.elapsed().as_secs_f64() < 1.0) { return; } - *last = Some(std::time::Instant::now()); +pub(crate) fn forward_render_diagnostics(store: Res, mut last: Local>, mut seen: Local>) { + for d in store.iter().filter(|d| d.path().as_str().starts_with("render/")) { if let Some(m) = d.measurement().filter(|m| seen.insert(d.path().as_str().to_string(), m.time) != Some(m.time)) { raea_io_trace::pass_ms(&format!("bevy/{}", d.path().as_str().trim_start_matches("render/")), m.value); } } + if last.is_some_and(|t| t.elapsed().as_secs_f64() < 1.0) { return; } *last = Some(std::time::Instant::now()); let passes: serde_json::Map = store.iter().filter(|d| d.path().as_str().starts_with("render/")) .filter_map(|d| d.smoothed().map(|v| (d.path().as_str().trim_start_matches("render/").to_string(), serde_json::json!((v * 1000.0).round() / 1000.0)))).collect(); if !passes.is_empty() { raea_io_trace::event("bevy_passes", serde_json::json!({"ms": passes})); } diff --git a/engine/rune/bevy/Cargo.toml b/engine/rune/bevy/Cargo.toml index d4a8456b..602bc6ad 100644 --- a/engine/rune/bevy/Cargo.toml +++ b/engine/rune/bevy/Cargo.toml @@ -9,6 +9,7 @@ publish = false description = "A Rune tree as a Bevy layer: drawn into a Bevy Image on Bevy's device with no copy, pointer and keys forwarded to it" [dependencies] +raea-io-trace = { path = "../../../io/trace" } rune.workspace = true bevy = { version = "=0.20.0", default-features = false, features = ["std", "async_executor", "bevy_window", "bevy_asset", "bevy_image", "bevy_render", "bevy_core_pipeline"] } wgpu = "=30.0.1" diff --git a/engine/rune/bevy/src/input.rs b/engine/rune/bevy/src/input.rs index 9228dadc..d0834088 100644 --- a/engine/rune/bevy/src/input.rs +++ b/engine/rune/bevy/src/input.rs @@ -83,7 +83,7 @@ pub(crate) fn forward( ) { let primary = primary.iter().next(); let targets: Vec<(Entity, Entity)> = overlays.iter().filter_map(|(e, o)| Some((e, o.window.or(primary)?))).collect(); - let trace = std::env::var_os("RAEA_RUNE_BEVY_TRACE").is_some(); + let trace = raea_io_trace::stat("RAEA_RUNE_BEVY_TRACE"); let mut send = |window: Entity, ev: Input| { if trace { eprintln!("raea-rune-bevy: {window} {ev:?}"); diff --git a/engine/seedling/Cargo.toml b/engine/seedling/Cargo.toml index f7a4aa06..cc95bd9d 100644 --- a/engine/seedling/Cargo.toml +++ b/engine/seedling/Cargo.toml @@ -7,6 +7,7 @@ license = "MIT OR Apache-2.0" description = "bevy_seedling on raea's one mixer core: seedling's graph (sample players, pools, effects, raea's Tone effects and limiter registered as nodes) stepped a frame at a time beside the game, its sound a voice of the core, so a render and a play of a game sound the same, sample for sample (sdk/react/docs/audio-stack.md)" [dependencies] +raea-io-trace = { path = "../../io/trace" } bevy = { version = "=0.20.0", default-features = false, features = ["std", "bevy_asset"] } # Bevy's audio on Firewheel 0.12 (MIT OR Apache-2.0). Default features off: no cpal 0.18 backend (it can't link beside # the cpal 0.15 react and the legacy app use) and no symphonia (raea decodes): raea's platform runs its processor diff --git a/engine/seedling/src/lib.rs b/engine/seedling/src/lib.rs index 679d3051..2c30224b 100644 --- a/engine/seedling/src/lib.rs +++ b/engine/seedling/src/lib.rs @@ -277,7 +277,7 @@ impl Host { if h.is_none() { eprintln!("raea seedling: {} has no sound", file.display()); } - if std::env::var_os("RAEA_SEEDLING_TRACE").is_some() { + if raea_io_trace::stat("RAEA_SEEDLING_TRACE") { eprintln!("raea seedling: {} decoded in {:.1} ms", file.display(), t0.elapsed().as_secs_f64() * 1e3); } self.samples.insert(file.to_path_buf(), h.clone()); @@ -295,7 +295,7 @@ impl Host { /// seedling updated, and the frame's samples made. A frame that isn't the next starts seedling again from silence /// (a seek); the chunk is the frame's samples on the timeline. pub fn frame(&mut self, f: i64, plays: &[Play]) -> raea_io_media::Audio { - if std::env::var_os("RAEA_SEEDLING_TRACE").is_some() && f != self.next { + if raea_io_trace::stat("RAEA_SEEDLING_TRACE") && f != self.next { eprintln!("raea seedling: frame {f}, expected {}", self.next); } if f != self.next { @@ -369,7 +369,7 @@ impl Host { let t1 = std::time::Instant::now(); let n = (self.t(f + 1) - self.t(f)).max(0) as usize; let pcm = chunk(self.app.world_mut(), n); - if std::env::var_os("RAEA_SEEDLING_TRACE").is_some() && t0.elapsed().as_secs_f64() > 0.002 { + if raea_io_trace::stat("RAEA_SEEDLING_TRACE") && t0.elapsed().as_secs_f64() > 0.002 { eprintln!("raea seedling: frame {f}: update {:.1} ms, process {:.1} ms, {} players", (t1 - t0).as_secs_f64() * 1e3, t1.elapsed().as_secs_f64() * 1e3, self.players.len()); } self.next = f + 1; diff --git a/io/apple/src/decode.rs b/io/apple/src/decode.rs index 504fd786..e0451e4f 100644 --- a/io/apple/src/decode.rs +++ b/io/apple/src/decode.rs @@ -295,7 +295,7 @@ impl Decoder { return Ok(None); } let bgra = !self.nv12; - let trace = std::env::var_os("RAEA_VT_TRACE").is_some(); + let trace = raea_io_trace::stat("RAEA_VT_TRACE"); let t0 = std::time::Instant::now(); if self.seeker.as_ref().is_none_or(|s| s.1 != bgra) { let made = unsafe { diff --git a/io/apple/src/vt.rs b/io/apple/src/vt.rs index 32eca21e..b19f5e0b 100644 --- a/io/apple/src/vt.rs +++ b/io/apple/src/vt.rs @@ -216,7 +216,7 @@ impl VtEncoder { None => o.realtime, }; set(kVTCompressionPropertyKey_RealTime, CFBoolean::new(realtime))?; - if std::env::var_os("RAEA_MEM_MARKS").is_some() { + if raea_io_trace::stat("RAEA_MEM_MARKS") { eprintln!("vt_mark session realtime {realtime}"); } set(kVTCompressionPropertyKey_ProfileLevel, if hevc10 { kVTProfileLevel_HEVC_Main10_AutoLevel } else { kVTProfileLevel_H264_High_AutoLevel })?; @@ -286,7 +286,7 @@ impl VtEncoder { } st.inflight += 1; st.max_inflight = st.max_inflight.max(st.inflight); - if std::env::var_os("RAEA_MEM_MARKS").is_some() && self.n % 25 == 0 { + if raea_io_trace::stat("RAEA_MEM_MARKS") && self.n % 25 == 0 { eprintln!("vt_mark frame {} in_flight {} max_in_flight {} kept_bytes {}", self.n, st.inflight, st.max_inflight, st.kept); } } @@ -403,7 +403,7 @@ impl VideoEncoder for VtEncoder { }) } fn finish(self: Box, audio: Option<&Audio>) -> R { - if std::env::var_os("RAEA_ENC_TRACE").is_some() && self.n > 0 { + if raea_io_trace::stat("RAEA_ENC_TRACE") && self.n > 0 { let ms = |i: usize| VT_PUSH_NS[i].load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6 / self.n as f64; eprintln!("raea encode: {} frames, a frame's submit: waiting for room and a buffer {:.3} ms, the copy into it {:.3} ms, encode_frame {:.3} ms (max in flight {})", self.n, ms(0), ms(1), ms(2), self.cap); } @@ -437,7 +437,7 @@ impl VideoEncoder for VtEncoder { if frames.len() != self.n as usize { return Err(format!("VideoToolbox: {} of {} frames came out", frames.len(), self.n)); } - if std::env::var_os("RAEA_MEM_MARKS").is_some() { + if raea_io_trace::stat("RAEA_MEM_MARKS") { eprintln!("vt_mark finish frames {} max_in_flight {} kept_bytes {}", frames.len(), st.max_inflight, st.kept); } if st.discard { diff --git a/io/apple/src/vtseek.rs b/io/apple/src/vtseek.rs index 9819f636..089891f8 100644 --- a/io/apple/src/vtseek.rs +++ b/io/apple/src/vtseek.rs @@ -141,7 +141,7 @@ impl Seeker { } let session = CFRetained::from_raw(std::ptr::NonNull::new(sp).unwrap()); let file = File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; - if std::env::var_os("RAEA_VT_TRACE").is_some() { + if raea_io_trace::stat("RAEA_VT_TRACE") { eprintln!("vtseek: {} samples indexed in {t_index:.1} ms, session in {:.1} ms", samples.len(), t0.elapsed().as_secs_f64() * 1e3 - t_index); } Ok(Some(Seeker { session, fmt, file, samples, order, h264, pos: None, shared, width: dims.width as u32, height: dims.height as u32, decoded: 0 })) @@ -252,7 +252,7 @@ impl Seeker { self.file.read_exact_at(&mut buf, s.offset).map_err(|e| format!("reading a sample: {e}"))?; kinds.push(self.kind(&buf)); } - if std::env::var_os("RAEA_VT_TRACE").is_some() { + if raea_io_trace::stat("RAEA_VT_TRACE") { let k: String = kinds.iter().map(|k| match k { Kind::Disposable => 'd', Kind::RefB => 'b', Kind::Ref => 'R' }).collect(); eprintln!("vtseek: samples {start}..={target} kinds {k}"); } @@ -272,13 +272,13 @@ impl Seeker { let (td, kb) = (std::time::Instant::now(), buf.len() / 1024); self.decode(i, &buf, out)?; self.decoded += 1; - if std::env::var_os("RAEA_VT_TRACE").is_some() { + if raea_io_trace::stat("RAEA_VT_TRACE") { eprintln!("vtseek: sample {i} ({k:?}, {kb} KB) submitted in {:.1} ms", td.elapsed().as_secs_f64() * 1e3); } } let tw = std::time::Instant::now(); unsafe { self.session.wait_for_asynchronous_frames() }; - if std::env::var_os("RAEA_VT_TRACE").is_some() { + if raea_io_trace::stat("RAEA_VT_TRACE") { eprintln!("vtseek: waited {:.1} ms for the decoder", tw.elapsed().as_secs_f64() * 1e3); } if let Some(e) = self.shared.err.lock().unwrap().take() { diff --git a/io/trace/src/lib.rs b/io/trace/src/lib.rs index 1a0c46e7..c72310a8 100644 --- a/io/trace/src/lib.rs +++ b/io/trace/src/lib.rs @@ -26,9 +26,11 @@ use serde_json::{Value, json}; mod crash; mod look; +mod stats; use crash::*; pub use look::{sessions, status, summarize}; +pub use stats::{choose as choose_stats, chosen as chosen_stats, count, pass_ms, stat, stats, table as stats_table}; struct Session { dir: PathBuf, @@ -183,14 +185,18 @@ pub fn start(app: &str) -> Option { Some(dir) } -/// A clean exit: `end.json` written (a session without it ended unclean). +/// A clean exit: `end.json` written (a session without it ended unclean), and the stats the run chose (stats.rs). pub fn end() { let Ok(mut g) = SESSION.lock() else { return }; + let dir = g.as_ref().map(|s| s.dir.clone()); if let Some(s) = g.as_mut() { flush_second(s, true); let (iso, _) = utc(SystemTime::now()); let _ = std::fs::write(s.dir.join("end.json"), json!({"ended": iso, "seconds": s.t0.elapsed().as_secs_f64(), "glitches": s.glitches}).to_string()); } + // printed with the session unlocked (stderr's tee writes into it) + drop(g); + stats::finish(dir.as_deref()); } fn write_line(s: &mut Session, line: String) { @@ -298,6 +304,7 @@ pub fn gpu_passes(source: &str, passes: &[(&str, f64)], budget_ms: f64) { use std::fmt::Write as _; s.key.clear(); let _ = write!(s.key, "{source}/{name}"); + stats::pass_ms(&s.key, ms); match s.gpu_time.get_mut(s.key.as_str()) { Some(v) => v.push(ms), None => { diff --git a/io/trace/src/stats.rs b/io/trace/src/stats.rs new file mode 100644 index 00000000..b0fa6c67 --- /dev/null +++ b/io/trace/src/stats.rs @@ -0,0 +1,132 @@ +//! What a run says about itself without a build (docs/nobuild.feature NB2a): the stat channels that turn raea's traces +//! and timings on, and the run's totals (each pass's time, counters) that TypeScript reads while it runs +//! (`native("stats.read", {})`) and that the run's end prints and keeps (`stats.json` in its trace folder) when any +//! channel was chosen. +//! +//! A channel is a RAEA_ variable's name without RAEA_, in lower case: RAEA_BAKE_TRACE is `bake_trace`, RAEA_BEVY_PASSES +//! (each of Bevy's render passes timed) `bevy_passes`. It's on when the run's TypeScript chose it +//! (`native("stats.on", { channels: [...] })` at a composition's top level, which runs before the Engine opens), when +//! RAEA_STATS lists it (`RAEA_STATS=bevy_passes,bake_trace`, or `all`), or when its own variable is set (not to 0), the +//! override. + +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::path::Path; +use std::sync::{Mutex, RwLock}; + +/// the channels chosen: RAEA_STATS's, read at the first ask, and then the TypeScript's +static CHOSEN: RwLock>> = RwLock::new(None); + +/// each pass's runs, total and worst ms; each counter's total +#[derive(Default)] +struct Totals { + passes: BTreeMap, + counters: BTreeMap, +} +static TOTALS: Mutex> = Mutex::new(None); + +fn from_env() -> Vec { + std::env::var("RAEA_STATS").unwrap_or_default().split(',').map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()).collect() +} + +/// The channels this run has chosen (RAEA_STATS's and the TypeScript's), in the order they came. +pub fn chosen() -> Vec { + if let Some(c) = CHOSEN.read().ok().and_then(|c| c.clone()) { + return c; + } + let Ok(mut w) = CHOSEN.write() else { return from_env() }; + w.get_or_insert_with(from_env).clone() +} + +/// Whether the stat channel of the variable `var` (`"RAEA_BAKE_TRACE"`) is on for this run. +pub fn stat(var: &str) -> bool { + if let Some(v) = std::env::var_os(var) { + return v != "0"; + } + let name = var.trim_start_matches("RAEA_"); + let on = |c: &Vec| c.iter().any(|n| n == "all" || n.eq_ignore_ascii_case(name)); + match CHOSEN.read().ok().and_then(|c| c.as_ref().map(on)) { + Some(o) => o, + None => on(&chosen()), + } +} + +/// Channels turned on for the rest of this run (`stats.on`); a name is a RAEA_ variable's without RAEA_, or `all`. +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()) { + if !c.contains(&n) { + c.push(n); + } + } + if let Ok(mut w) = CHOSEN.write() { + *w = Some(c); + } +} + +/// A pass's time this frame (ms), by its name (`bevy/main_opaque_pass_3d/elapsed_cpu`, `quads/composite`). +pub fn pass_ms(name: &str, ms: f64) { + let Ok(mut g) = TOTALS.lock() else { return }; + let t = g.get_or_insert_with(Totals::default); + match t.passes.get_mut(name) { + Some(p) => *p = (p.0 + 1, p.1 + ms, p.2.max(ms)), + None => { + t.passes.insert(name.to_string(), (1, ms, ms)); + } + } +} + +/// `n` more of something this run counts (`engine/updates`, `engine/draws`): a counter needs no line printed for it. +pub fn count(name: &str, n: u64) { + let Ok(mut g) = TOTALS.lock() else { return }; + let t = g.get_or_insert_with(Totals::default); + match t.counters.get_mut(name) { + Some(c) => *c += n, + None => { + t.counters.insert(name.to_string(), n); + } + } +} + +/// The run so far: the channels chosen, each pass's runs and mean and worst ms, and each counter. +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 = 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 = t.into_iter().flat_map(|t| t.counters.iter()).map(|(k, n)| (k.clone(), json!(n))).collect(); + json!({"chosen": chosen(), "passes": passes, "counters": counters}) +} + +fn round(ms: f64) -> f64 { + (ms * 1000.0).round() / 1000.0 +} + +/// The stats as a table: the passes slowest first (by mean), then the counters. +pub fn table(v: &Value) -> String { + let mut out = format!("raea stats ({}):\n", v["chosen"].as_array().map(|c| c.iter().filter_map(|n| n.as_str()).collect::>().join(", ")).unwrap_or_default()); + let mut passes: Vec<(&String, &Value)> = v["passes"].as_object().into_iter().flatten().collect(); + passes.sort_by(|a, b| b.1["mean_ms"].as_f64().unwrap_or(0.0).total_cmp(&a.1["mean_ms"].as_f64().unwrap_or(0.0))); + for (k, p) in &passes { + out += &format!(" {k:<56} {:>6} runs mean {:>8.3} ms max {:>8.3} ms\n", p["n"], p["mean_ms"].as_f64().unwrap_or(0.0), p["max_ms"].as_f64().unwrap_or(0.0)); + } + for (k, n) in v["counters"].as_object().into_iter().flatten() { + out += &format!(" {k:<56} {n:>6}\n"); + } + if passes.is_empty() { + out += " no pass timed (bevy_passes times Bevy's render passes)\n"; + } + out +} + +/// At a run's end, when it chose any channel: the table on stderr and `stats.json` in its trace folder. +pub(crate) fn finish(dir: Option<&Path>) { + if chosen().is_empty() { + return; + } + let v = stats(); + eprint!("{}", table(&v)); + if let Some(d) = dir { + let _ = std::fs::write(d.join("stats.json"), format!("{v:#}")); + eprintln!(" (kept in {})", d.join("stats.json").display()); + } +} diff --git a/runtime/bake/Cargo.toml b/runtime/bake/Cargo.toml index f4b7ebee..943a0ada 100644 --- a/runtime/bake/Cargo.toml +++ b/runtime/bake/Cargo.toml @@ -12,6 +12,7 @@ description = "A timeline baked: a composition's React commits recorded frame by modules = ["dep:raea-modules"] [dependencies] +raea-io-trace = { path = "../../io/trace" } raea-io-home = { path = "../../io/home" } raea-runtime-react = { path = "../../runtime/react", default-features = false } raea-runtime-bundle = { path = "../bundle" } diff --git a/runtime/bake/src/lib.rs b/runtime/bake/src/lib.rs index 11cc7674..dd2c7620 100644 --- a/runtime/bake/src/lib.rs +++ b/runtime/bake/src/lib.rs @@ -168,7 +168,7 @@ pub fn bake(js: &Path) -> R { for t in later { add(t.join().map_err(|_| "a bake worker panicked".to_string())??); } - if std::env::var_os("RAEA_BAKE_TRACE").is_some() { + if raea_io_trace::stat("RAEA_BAKE_TRACE") { eprintln!("raea bake: settings in {t_conf:.0} ms, {frames} frames in {:.0} ms on {} runtimes, {} flush waits timed out", t0.elapsed().as_secs_f64() * 1e3 - t_conf, ranges.len(), raea_runtime_react::FLUSH_TIMEOUTS.load(std::sync::atomic::Ordering::Relaxed) - timeouts0); } @@ -230,7 +230,7 @@ pub fn step_frames_with(app: &mut App, a: i64, b: i64, answer: &mut raea_runtime }); app.world_mut().remove_resource::(); stepped?; - if std::env::var_os("RAEA_BAKE_TRACE").is_some() { + if raea_io_trace::stat("RAEA_BAKE_TRACE") { let ms = |a: &std::sync::atomic::AtomicU64, z: u64| (ld(a) - z) as f64 / 1e6; eprintln!( "raea bake: frames {a}..{b} in {:.1} ms: waited on React {:.1} ms, applying {:.1} ms, JS {:.1} ms (those three across every runtime), recording {:.1} ms", @@ -348,7 +348,7 @@ fn from_json(mut v: Value) -> R { pub fn bake_incremental(old: &Baked, js: &Path) -> R<(Baked, i64)> { let code = code_of(js)?; let full = |why: &str| -> R<(Baked, i64)> { - if std::env::var_os("RAEA_BAKE_TRACE").is_some() { + if raea_io_trace::stat("RAEA_BAKE_TRACE") { eprintln!("raea bake: every frame again ({why})"); } let b = bake(js)?; @@ -371,7 +371,7 @@ pub fn bake_incremental(old: &Baked, js: &Path) -> R<(Baked, i64)> { continue; } if !hit.contains(whole) && !old.code.funcs.get(whole).is_some_and(|c| c.iter().any(|p| hit.contains(p))) { - if std::env::var_os("RAEA_BAKE_TRACE").is_some() { + if raea_io_trace::stat("RAEA_BAKE_TRACE") { eprintln!("raea bake: function {whole:x} (inside {:x?}) changed; components changed {:x?}", old.code.funcs.get(whole), hit); } return full("a changed function isn't a component any frame rendered"); @@ -472,7 +472,7 @@ pub fn bake_incremental(old: &Baked, js: &Path) -> R<(Baked, i64)> { b.frame_ops[k as usize].push(Value::Array(key.1.clone()).to_string()); } } - if std::env::var_os("RAEA_BAKE_TRACE").is_some() { + if raea_io_trace::stat("RAEA_BAKE_TRACE") { eprintln!("raea bake: {} runs, {stepped} frames on {} runtimes", runs.len(), pieces.len()); } Ok((b, stepped)) diff --git a/runtime/bundle/Cargo.toml b/runtime/bundle/Cargo.toml index da455e60..f5827177 100644 --- a/runtime/bundle/Cargo.toml +++ b/runtime/bundle/Cargo.toml @@ -11,6 +11,7 @@ description = "A composition's TSX bundled into one script the engine runs, with modules = ["raea-native/modules"] [dependencies] +raea-io-trace = { path = "../../io/trace" } # canonical paths without Windows' verbatim prefix, for import specifiers (fresh.rs spec) dunce = "1" # raea's home (the checkout's, or an install's share/raea): the SDK packages, the bundler's library, Tailwind's package diff --git a/runtime/bundle/src/fresh.rs b/runtime/bundle/src/fresh.rs index d94b053e..7a621fba 100644 --- a/runtime/bundle/src/fresh.rs +++ b/runtime/bundle/src/fresh.rs @@ -185,7 +185,7 @@ pub fn bundle_fresh(tsx: &Path, out_js: &Path, o: &CompOpts, portable: Option<&P let (js_text, css) = inproc::bundle(&work.join("entry.tsx"), serde_json::json!({"z3": o.lite, "edit": {"dir": dir, "js": js}, "stamps": stamps()})).map_err(|e| format!("couldn't bundle {file}: {}", e.lines().filter(|l| !l.trim().is_empty()).take(6).collect::>().join(" | ")))?; // its CSS rides in the bundle's last line (bundle_css), so every copy and cache of it carries it let code = if css.is_empty() { js_text } else { format!("{js_text}\n//# raea-css={}\n", serde_json::to_string(&css).unwrap_or_default()) }; - if std::env::var_os("RAEA_BUNDLE_TRACE").is_some() { + if raea_io_trace::stat("RAEA_BUNDLE_TRACE") { eprintln!("raea bundle: {} in {:.1} ms: the work folder {:.1} ms, Rolldown {:.1} ms", tsx.display(), t0.elapsed().as_secs_f64() * 1e3, t_work.as_secs_f64() * 1e3, (t0.elapsed() - t_work).as_secs_f64() * 1e3); } std::fs::write(out_js, code).map_err(|e| format!("{}: {e}", out_js.display()))?; diff --git a/runtime/calls/Cargo.toml b/runtime/calls/Cargo.toml index 7e9b4b76..6f654e61 100644 --- a/runtime/calls/Cargo.toml +++ b/runtime/calls/Cargo.toml @@ -15,6 +15,7 @@ raea-runtime-plugins = { path = "../plugins" } # raea/wear's bake as the native call wear.bake, registered with these (docs/wear.feature WR4) raea-runtime-wear = { path = "../wear" } raea-native = { path = "../../engine/native", default-features = false } +raea-io-trace = { path = "../../io/trace" } raea-core-shape = { path = "../../core/shape" } raea-core-place = { path = "../../core/place" } raea-core-scene = { path = "../../core/scene" } diff --git a/runtime/calls/src/lib.rs b/runtime/calls/src/lib.rs index d4eb5c8e..e27ecf7d 100644 --- a/runtime/calls/src/lib.rs +++ b/runtime/calls/src/lib.rs @@ -299,6 +299,12 @@ pub fn register() { }, ); } + // the run's stat channels, and its timings and counters so far, from TypeScript (docs/nobuild.feature NB2a) + raea_native::register("stats.on", "{ channels: string[] }", "{ chosen: string[] }", "stat channels on for the rest of the run: a RAEA_ variable's name without RAEA_, in lower case (bevy_passes, bake_trace), or all; at a composition's top level, before the Engine opens (docs/nobuild.feature NB2a)", |v| { + raea_io_trace::choose_stats(&v["channels"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(str::to_string)).collect::>()); + Ok(json!({"chosen": raea_io_trace::chosen_stats()})) + }); + raea_native::register("stats.read", "{}", "{ chosen: string[]; passes: Record; counters: Record }", "the run so far: its stat channels, each timed pass's runs and mean and worst ms, each counter (docs/nobuild.feature NB2a)", |_| Ok(raea_io_trace::stats())); // an asset loaded now, before the frame that names it uses it, as the Engine loads a handle's (S2b useAsset) raea_native::register("asset.load", "{ path: string }", "{ path: string; bytes: number; width?: number; height?: number }", "an asset by its path (absolute, or from the edit's folder), loaded now: the file found and read, a picture's size; an error when it isn't there (S2b useAsset)", |v| { let p = s(v, "path")?; diff --git a/runtime/dom/Cargo.toml b/runtime/dom/Cargo.toml index 3b002c61..04114792 100644 --- a/runtime/dom/Cargo.toml +++ b/runtime/dom/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "TSX roots on a Blitz page: their scripts, ops, events, timers, iframes and host calls, getComputedStyle, and media elements" [dependencies] +raea-io-trace = { path = "../../io/trace" } # the layers under it raea-sys-page = { path = "../../systems/page" } raea-runtime-twins = { path = "../../runtime/twins" } diff --git a/runtime/dom/media/Cargo.toml b/runtime/dom/media/Cargo.toml index 3082863b..c46d4ace 100644 --- a/runtime/dom/media/Cargo.toml +++ b/runtime/dom/media/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "The page's video and audio elements: each source decoded and played on its own thread (raea-runtime-js's stream), its news as the element's media events, a video's frame as its picture" [dependencies] +raea-io-trace = { path = "../../../io/trace" } bevy = { version = "=0.20.0", default-features = false, features = ["std", "bevy_log"] } blitz-dom = { version = "=0.3.0-beta.4", default-features = false, features = ["svg", "woff", "system-fonts", "floats", "text-transform-icu", "complex-scripts"] } raea-io-net = { path = "../../../io/net" } diff --git a/runtime/dom/media/src/lib.rs b/runtime/dom/media/src/lib.rs index c26eb82c..44f11da0 100644 --- a/runtime/dom/media/src/lib.rs +++ b/runtime/dom/media/src/lib.rs @@ -89,7 +89,7 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mu Some(m) if m.src == src && m.load == load => m, _ => { let stream = (!src.is_empty()).then(|| raea_runtime_js::media_html::stream::open(&raea_sys_page::net::page_path(&src), video)).flatten(); - medias.insert(id, Media { src, load, poster: None, seek: None, stream, video, loaded: false, seeking: None, seeked: false, duration: f64::NAN, frame: None, halves: Vec::new(), halvings: 0, ahead: VecDeque::new(), synced: (None, 1.0 / 60.0), paced: (0, 0.0, 0.0, 0.0), play: None, playing: false, muted: None, volume: None, told: None, shown_gap: (None, 0.0), stats: (std::env::var("RAEA_MEDIA_STATS").as_deref() == Ok("1")).then(|| (std::time::Instant::now(), 0, 0, 0.0, 0.0)) }); + medias.insert(id, Media { src, load, poster: None, seek: None, stream, video, loaded: false, seeking: None, seeked: false, duration: f64::NAN, frame: None, halves: Vec::new(), halvings: 0, ahead: VecDeque::new(), synced: (None, 1.0 / 60.0), paced: (0, 0.0, 0.0, 0.0), play: None, playing: false, muted: None, volume: None, told: None, shown_gap: (None, 0.0), stats: (raea_io_trace::stat("RAEA_MEDIA_STATS")).then(|| (std::time::Instant::now(), 0, 0, 0.0, 0.0)) }); medias.get_mut(&id).unwrap() } }; diff --git a/runtime/dom/src/host/bridge.rs b/runtime/dom/src/host/bridge.rs index 93d50fd7..4445b3da 100644 --- a/runtime/dom/src/host/bridge.rs +++ b/runtime/dom/src/host/bridge.rs @@ -190,7 +190,7 @@ impl EventHandler for Bridge<'_> { } let hearer = path.iter().find_map(|n| self.nodes.id_of(*n).filter(|id| self.nodes.hears(*id, ev)).map(|id| (id, *n))); // RAEA_PAGE_EVENTS=1: each DOM event the bridge sees and who hears it - if std::env::var_os("RAEA_PAGE_EVENTS").is_some() { + if raea_io_trace::stat("RAEA_PAGE_EVENTS") { eprintln!("raea-page: event {ev:?} target {} hearer {:?}", event.target, hearer.map(|h| h.0)); } let msg = match (&event.data, hearer) { @@ -289,7 +289,7 @@ impl EventHandler for Bridge<'_> { prevented = true; } if prevented { - if std::env::var_os("RAEA_PAGE_EVENTS").is_some() { + if raea_io_trace::stat("RAEA_PAGE_EVENTS") { eprintln!("raea-page: event {ev:?} prevented"); } state.prevent_default(); diff --git a/runtime/export/Cargo.toml b/runtime/export/Cargo.toml index 7f081245..095b9284 100644 --- a/runtime/export/Cargo.toml +++ b/runtime/export/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "A composition rendered to frames and files: React stepped frame by frame, its pages, 3D and sound made into one raea-render program; and its commits baked by frame" [dependencies] +raea-io-trace = { path = "../../io/trace" } dunce = "1" raea-runtime-view = { path = "../view" } raea-io-assets = { path = "../../io/assets" } diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rs index 6e69cb23..d35363ab 100644 --- a/runtime/export/src/fed.rs +++ b/runtime/export/src/fed.rs @@ -318,7 +318,7 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot if let Some(p) = std::env::var_os("RAEA_AUDIO_BOUNCE") { raea_sys_mix::write_wav(&a, Path::new(&p))?; } - if std::env::var_os("RAEA_MASTER_TRACE").is_some() { + if raea_io_trace::stat("RAEA_MASTER_TRACE") { eprintln!("core bounce (streamed): {:.2} s of sound, master {master:?}; the bounce finished {bounce_ms:.0} ms after the last frame, the master took {:.0} ms", a.duration(), t_master.elapsed().as_secs_f64() * 1e3); } Ok(Some(a)) diff --git a/runtime/export/src/render.rs b/runtime/export/src/render.rs index 5fc51694..94157e9f 100644 --- a/runtime/export/src/render.rs +++ b/runtime/export/src/render.rs @@ -365,7 +365,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti let t0 = std::time::Instant::now(); // RAEA_TIMES: where a render's frames go (React's commit, the page recorded and submitted, the page before // collected and stored), totals in ms - let times = std::env::var_os("RAEA_TIMES").is_some(); + let times = raea_io_trace::stat("RAEA_TIMES"); let (mut t_react, mut t_snap, mut t_page) = (0f64, 0f64, 0f64); for &f in &wanted { let t0 = std::time::Instant::now(); diff --git a/runtime/export/src/sound.rs b/runtime/export/src/sound.rs index 069c2b7e..94e7335b 100644 --- a/runtime/export/src/sound.rs +++ b/runtime/export/src/sound.rs @@ -24,7 +24,7 @@ pub(crate) fn core_bounce(frames: &[(i64, Frame)], notes: &[raea_sys_mix::ToneCu if let Some(p) = std::env::var_os("RAEA_AUDIO_BOUNCE") { raea_sys_mix::write_wav(&a, Path::new(&p))?; } - if std::env::var_os("RAEA_MASTER_TRACE").is_some() { + if raea_io_trace::stat("RAEA_MASTER_TRACE") { eprintln!("core bounce: {:.2} s of sound in {:.0} ms, master {master:?}", a.duration(), t.elapsed().as_secs_f64() * 1e3); } Ok(Some(a)) diff --git a/runtime/gpuframe/Cargo.toml b/runtime/gpuframe/Cargo.toml index c5a66c76..05627f03 100644 --- a/runtime/gpuframe/Cargo.toml +++ b/runtime/gpuframe/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "A frame composited on the GPU: clips as NV12 planes in a pooled byte budget, the Blitz overlay over the camera's target, and the NV12 readback for the encoder" [dependencies] +raea-io-trace = { path = "../../io/trace" } raea-sys-frame = { path = "../../systems/frame", features = ["native"] } raea-runtime-view = { path = "../view" } raea-core-program = { path = "../../core/program" } diff --git a/runtime/gpuframe/src/pool.rs b/runtime/gpuframe/src/pool.rs index c5e75661..5687bb44 100644 --- a/runtime/gpuframe/src/pool.rs +++ b/runtime/gpuframe/src/pool.rs @@ -114,7 +114,7 @@ pub fn gpu_frame_pass(world: &mut World) { pool.frame = Some(storage(&device, (w * h * 4) as u64)); pool.dummy = Some(storage(&device, 24)); } - let want = std::env::var_os("RAEA_GPU_TIMES").is_some(); + let want = raea_io_trace::stat("RAEA_GPU_TIMES"); let timing = want && device.features().contains(wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS); if want && !timing && !pool.ts_unsupported_said { pool.ts_unsupported_said = true; diff --git a/runtime/js/Cargo.toml b/runtime/js/Cargo.toml index 5e98b0c7..e30c7ea7 100644 --- a/runtime/js/Cargo.toml +++ b/runtime/js/Cargo.toml @@ -17,6 +17,7 @@ portable = ["raea-runtime-jsengine/portable"] media = ["dep:raea-io-media", "dep:cpal"] [dependencies] +raea-io-trace = { path = "../../io/trace" } # images bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "bevy_render", "bevy_image"] } dunce = "1" diff --git a/runtime/js/src/media_play.rs b/runtime/js/src/media_play.rs index d0becd90..9b32ab96 100644 --- a/runtime/js/src/media_play.rs +++ b/runtime/js/src/media_play.rs @@ -92,7 +92,7 @@ impl<'a> Player<'a> { Source::Audio(a) => (a.duration(), 0.0), }; let fps = if fps.is_finite() && fps > 1.0 { fps } else { 30.0 }; - Player { path, source, duration, fps, sound: None, muted: false, volume: 1.0, clock: None, looping: false, cursor: 0, lap: 0.0, skipped: 0, told: None, halvings: 0, still: Some(0.0), stats: (std::env::var("RAEA_MEDIA_STATS").as_deref() == Ok("1")).then(Stats::new) } + Player { path, source, duration, fps, sound: None, muted: false, volume: 1.0, clock: None, looping: false, cursor: 0, lap: 0.0, skipped: 0, told: None, halvings: 0, still: Some(0.0), stats: (raea_io_trace::stat("RAEA_MEDIA_STATS")).then(Stats::new) } } /// Answers the element's asks until it's gone (its stream dropped). diff --git a/runtime/live/src/lib.rs b/runtime/live/src/lib.rs index 6d32ef7f..c2ad3d6b 100644 --- a/runtime/live/src/lib.rs +++ b/runtime/live/src/lib.rs @@ -271,7 +271,7 @@ impl Live { if let Some(ls) = self.live3d.as_mut() { let t = std::time::Instant::now(); raea_runtime_export::live_scene(self.app.world_mut(), ls, &mut self.scene, (self.w, self.h), self.fps, &self.dir)?; - if std::env::var_os("RAEA_LIVE_TRACE").is_some() && t.elapsed().as_secs_f64() > 0.002 { + if raea_io_trace::stat("RAEA_LIVE_TRACE") && t.elapsed().as_secs_f64() > 0.002 { eprintln!("raea live: frame {f}: its 3D rows {:.1} ms", t.elapsed().as_secs_f64() * 1e3); } } @@ -281,7 +281,7 @@ impl Live { if sound { self.sound(f); } - if std::env::var_os("RAEA_LIVE_TRACE").is_some() && t0.elapsed().as_secs_f64() > 0.02 { + if raea_io_trace::stat("RAEA_LIVE_TRACE") && t0.elapsed().as_secs_f64() > 0.02 { eprintln!("raea live: frame {f}: settle {:.1} ms, sound {:.1} ms", (t1 - t0).as_secs_f64() * 1e3, t1.elapsed().as_secs_f64() * 1e3); } Ok(()) @@ -370,7 +370,7 @@ fn sound_key(js: &Path, dir: &Path) -> u64 { } let bundle = twox_hash::XxHash3_64::oneshot(&h); walk(dir, &mut h, 0); - if std::env::var_os("RAEA_SOUND_TRACE").is_some() { + if raea_io_trace::stat("RAEA_SOUND_TRACE") { eprintln!("raea live: sound key: bundle {bundle:016x} ({} bytes), with the project {:016x}", std::fs::metadata(js).map(|m| m.len()).unwrap_or(0), twox_hash::XxHash3_64::oneshot(&h)); } twox_hash::XxHash3_64::oneshot(&h) diff --git a/runtime/live/src/sound.rs b/runtime/live/src/sound.rs index 714c0e7f..f27f2fdc 100644 --- a/runtime/live/src/sound.rs +++ b/runtime/live/src/sound.rs @@ -171,7 +171,7 @@ impl Live { if let Some(rx) = &self.master { match rx.try_recv() { Ok(Ok(wav)) => { - if std::env::var_os("RAEA_LIVE_TRACE").is_some() { + if raea_io_trace::stat("RAEA_LIVE_TRACE") { eprintln!("raea live: the mastered sound is in at frame {f}"); } self.master_wav = wav; @@ -207,7 +207,7 @@ impl Live { } // the edit's Tone (raea/tone) let tone = if self.baked.as_ref().is_some_and(|b| f >= b.frames) { raea_sys_mix::ToneCue::default() } else { raea_runtime_sound::tone_at(self.app.world_mut(), f, self.fps, &self.dir, raea_runtime_react::scene::media_path, false) }; - if std::env::var_os("RAEA_SOUND_TRACE").is_some() && f % 30 == 0 { + if raea_io_trace::stat("RAEA_SOUND_TRACE") && f % 30 == 0 { eprintln!("raea live: frame {f} sounds {:?}", sounds.iter().map(|s| (s.key.clone(), s.file.file_name().map(|n| n.to_string_lossy().into_owned()), (s.at * 100.0).round() / 100.0, s.volume)).collect::>()); } if sounds.is_empty() && tone.is_empty() && self.mixer.is_none() { @@ -231,7 +231,7 @@ impl Live { if let Some(rx) = &self.game_master { match rx.try_recv() { Ok(Ok(g)) => { - if std::env::var_os("RAEA_LIVE_TRACE").is_some() { + if raea_io_trace::stat("RAEA_LIVE_TRACE") { eprintln!("raea live: the game's master is in at frame {f}: {g:?}"); } self.game_gain = g; diff --git a/runtime/plugins/src/lib.rs b/runtime/plugins/src/lib.rs index f74c293a..7240bb04 100644 --- a/runtime/plugins/src/lib.rs +++ b/runtime/plugins/src/lib.rs @@ -286,7 +286,7 @@ pub fn arm(world: &mut World) { } let step = f == c.stepped + 1; c.advancing = step; - if std::env::var_os("RAEA_PLUGIN_TRACE").is_some() { + if raea_io_trace::stat("RAEA_PLUGIN_TRACE") { eprintln!("plugin clock: frame {f}, stepped {}, {}", c.stepped, if step { "step" } else { "hold" }); } let dt = if step { diff --git a/runtime/scene3d/Cargo.toml b/runtime/scene3d/Cargo.toml index f982e05f..e0220aef 100644 --- a/runtime/scene3d/Cargo.toml +++ b/runtime/scene3d/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "The 3D kinds raea's 3D SDK writes, drawn with Bevy: meshes, lights, the camera and its post-processing, fog volumes and glTF models, moved frame by frame from the rows" [dependencies] +raea-io-trace = { path = "../../io/trace" } raea-sys-frame = { path = "../../systems/frame" } raea-sys-material = { path = "../../systems/material" } raea-sys-framepass = { path = "../../systems/framepass" } diff --git a/runtime/scene3d/src/model.rs b/runtime/scene3d/src/model.rs index 9b9ad336..a863f854 100644 --- a/runtime/scene3d/src/model.rs +++ b/runtime/scene3d/src/model.rs @@ -345,7 +345,7 @@ pub fn await_models(app: &mut App) -> Result<(), String> { // the cameras off while models load, so the draws are binned once, whole (#48): raea-sys-post's views.rs let mut off: Option> = None; // RAEA_MODELS_TRACE=1: each wait that ran an update says how many and for which models (a render's frame time) - let trace = std::env::var("RAEA_MODELS_TRACE").as_deref() == Ok("1"); + let trace = raea_io_trace::stat("RAEA_MODELS_TRACE"); let mut pumped = 0usize; loop { let world = app.world_mut(); diff --git a/runtime/segments/Cargo.toml b/runtime/segments/Cargo.toml index b9af1c94..eec49c15 100644 --- a/runtime/segments/Cargo.toml +++ b/runtime/segments/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "A render's video as shot segments, each its own encode starting on a keyframe, joined into one MP4 by stream copy with the sound laid under once (docs/rerender.feature RR3)" [dependencies] +raea-io-trace = { path = "../../io/trace" } raea-io-media = { path = "../../io/media", default-features = false } raea-io-codec = { path = "../../io/codec", features = ["mux"] } muxide = "0.2" diff --git a/runtime/segments/src/encode.rs b/runtime/segments/src/encode.rs index 915d17ff..83364f49 100644 --- a/runtime/segments/src/encode.rs +++ b/runtime/segments/src/encode.rs @@ -109,7 +109,7 @@ impl VideoEncoder for Segmented { }; let t = std::time::Instant::now(); let frames = crate::join::join(&self.paths, sound.as_ref(), self.opts.fps, &self.out)?; - if std::env::var_os("RAEA_SEGMENTS_TRACE").is_some() { + if raea_io_trace::stat("RAEA_SEGMENTS_TRACE") { eprintln!("raea segments: {frames} frames in {} segments joined in {:.1} ms (cuts {:?})", self.paths.len(), t.elapsed().as_secs_f64() * 1e3, self.cuts.all()); } let audio_codec = sound.map_or(String::new(), |s| if s.aac { "aac".into() } else { "opus".into() }); diff --git a/runtime/sound/Cargo.toml b/runtime/sound/Cargo.toml index 16572678..cece15a6 100644 --- a/runtime/sound/Cargo.toml +++ b/runtime/sound/Cargo.toml @@ -14,6 +14,7 @@ seedling = ["dep:raea-seedling"] ml = ["dep:raea-runtime-calls", "raea-runtime-calls/ml"] [dependencies] +raea-io-trace = { path = "../../io/trace" } raea-io-assets = { path = "../../io/assets" } raea-runtime-react = { path = "../../runtime/react", default-features = false } raea-sys-mix = { path = "../../systems/mix" } diff --git a/runtime/sound/src/lib.rs b/runtime/sound/src/lib.rs index 34b22d84..54800578 100644 --- a/runtime/sound/src/lib.rs +++ b/runtime/sound/src/lib.rs @@ -137,7 +137,7 @@ pub fn tone_at(world: &mut bevy::prelude::World, f: i64, fps: f64, dir: &Path, m } #[cfg(not(feature = "seedling"))] let _ = (f, fps); - if std::env::var_os("RAEA_SEEDLING_TRACE").is_some() && t0.elapsed().as_secs_f64() > 0.008 { + if raea_io_trace::stat("RAEA_SEEDLING_TRACE") && t0.elapsed().as_secs_f64() > 0.008 { eprintln!("raea seedling: tone_at {f}: plays {:.1} ms, tone {:.1} ms, seedling {:.1} ms", (t1 - t0).as_secs_f64() * 1e3, (t2 - t1).as_secs_f64() * 1e3, t2.elapsed().as_secs_f64() * 1e3); } cue diff --git a/runtime/view/Cargo.toml b/runtime/view/Cargo.toml index d02d2aae..561c1d4e 100644 --- a/runtime/view/Cargo.toml +++ b/runtime/view/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "The direct render's views (GPU and CPU) without the Bevy frame loop, the 2D rows drawn by Blitz, clips' masks, and the paint device as Bevy's renderer" [dependencies] +raea-io-trace = { path = "../../io/trace" } # a local file as a page src (raea_io_home::src: a file URL on Windows) raea-io-home = { path = "../../io/home" } raea-core-program = { path = "../../core/program" } diff --git a/runtime/view/src/gpuview/render.rs b/runtime/view/src/gpuview/render.rs index cce1edd4..9dbadaff 100644 --- a/runtime/view/src/gpuview/render.rs +++ b/runtime/view/src/gpuview/render.rs @@ -46,8 +46,8 @@ impl GpuView { let mut dt = DirectTimes::default(); // RAEA_GPU_TIMES: one frame at a time, with GPU timestamps: [2,3] the composite, [4,5] nv12buf.k, [6,7] the // copy into the readback ring, [8..16] up to four uploads (each its own copy) - let timing = std::env::var_os("RAEA_GPU_TIMES").is_some() && self.gpu.device.features().contains(wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS); - if std::env::var_os("RAEA_GPU_TIMES").is_some() && !timing { + let timing = raea_io_trace::stat("RAEA_GPU_TIMES") && self.gpu.device.features().contains(wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS); + if raea_io_trace::stat("RAEA_GPU_TIMES") && !timing { eprintln!("RAEA_GPU_TIMES: this device has no timestamp queries inside encoders: GPU stage times unsupported"); } dt.gpu_timed = timing; diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.ts index f7da1154..d4646319 100644 --- a/sdk/raea/src/native-calls.ts +++ b/sdk/raea/src/native-calls.ts @@ -20,6 +20,18 @@ export interface NativeCalls { "asset.load": { args: { path: string }; answer: { path: string; bytes: number; width?: number; height?: number } }; /** a file's bytes (absolute, from the edit's folder, or an http(s) URL through raea's cache), read now, as base64 (R3F's loaders, docs/r3f.feature R3F13) */ "asset.read": { args: { path: string }; answer: { path: string; base64: string } }; + /** a method of the app's BRP table (world.query, world.trigger_event, avian3d/cast_ray, ...) run now */ + "bevy.app.call": { args: { app: number; method: string; params?: unknown }; answer: unknown }; + /** drop an app */ + "bevy.app.close": { args: { app: number }; answer: null }; + /** a headless Bevy App with the plugins named (this build's), BRP's method table, and BRP over HTTP on port `serve` when given */ + "bevy.app.open": { args: { plugins: string[]; fps?: number; serve?: number }; answer: { app: number; methods: string[] } }; + /** the app's frame run schedule by schedule up to and including `until` (a schedule of Bevy's frame: PreUpdate, Update, PostUpdate...), or to its end; starts the next frame when none is part way */ + "bevy.app.run": { args: { app: number; until?: string; fixed?: boolean }; answer: { frame: number; done: boolean; schedules: string[] } }; + /** the schedules a frame of the app runs, in order (Bevy's MainScheduleOrder) */ + "bevy.app.schedules": { args: { app: number }; answer: string[] }; + /** the apps stepped together, a frame at a time (Time one frame on in each); each one's frame after */ + "bevy.app.step": { args: { apps: number[]; frames?: number }; answer: number[] }; /** a queued call's answer once the Engine has run it (null before) */ "bevy.world.answer": { args: { ticket: number }; answer: { value?: unknown; error?: string } | null }; /** a BRP method (world.query, world.mutate_components, a plugin's method...) queued for the live Engine's next update: its ticket */ @@ -282,6 +294,10 @@ export interface NativeCalls { "speech.stats": { args: {}; answer: unknown }; /** SQL run by SQLite on a database file (or ":memory:") */ "sqlite.exec": { args: { path: string; sql: string; readonly?: boolean }; answer: { sets: { columns: string[]; rows: (number | string | null | { blob: string })[][] }[]; error: string | null; changes: number } }; + /** stat channels on for the rest of the run: a RAEA_ variable's name without RAEA_, in lower case (bevy_passes, bake_trace), or all; at a composition's top level, before the Engine opens (docs/nobuild.feature NB2a) */ + "stats.on": { args: { channels: string[] }; answer: { chosen: string[] } }; + /** the run so far: its stat channels, each timed pass's runs and mean and worst ms, each counter (docs/nobuild.feature NB2a) */ + "stats.read": { args: {}; answer: { chosen: string[]; passes: Record; counters: Record } }; /** tar on project files: create, extract (paths kept inside) or list, gzipped or not */ "tar.run": { args: { root: string; cwd: string; create?: boolean; extract?: boolean; list?: boolean; gzip?: boolean; file: string; members?: string[]; dir?: string; verbose?: boolean }; answer: { stdout: string } }; /** a URL parsed by the WHATWG rules (null when invalid) */ diff --git a/systems/contact/Cargo.toml b/systems/contact/Cargo.toml index cc47636e..3eee3608 100644 --- a/systems/contact/Cargo.toml +++ b/systems/contact/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "Where a 3D scene's parts meet, from their geometry: what each rests on, and the parts that float, sink or clip" [dependencies] +raea-io-trace = { path = "../../io/trace" } raea-core-scene = { path = "../../core/scene" } raea-core-shape = { path = "../../core/shape" } # the Blender step a model calls for (an unloadable format, triangles over budget for its distance): docs/blender.feature diff --git a/systems/contact/src/lib.rs b/systems/contact/src/lib.rs index 4822dc2c..690cb3c7 100644 --- a/systems/contact/src/lib.rs +++ b/systems/contact/src/lib.rs @@ -414,7 +414,7 @@ pub fn told(all: &[Vec], frames: &[i64], w: u32, h: u32, fps: f64) -> Vec< eprintln!("raea: {}", f.line()); } raea_core_facts::finding::said(&found); - if std::env::var_os("RAEA_TIMES").is_some() { + if raea_io_trace::stat("RAEA_TIMES") { eprintln!("raea times: the clipping check {:.0} ms", t.elapsed().as_secs_f64() * 1e3); } found diff --git a/systems/mix/src/live.rs b/systems/mix/src/live.rs index 45e43d4b..3e5f5794 100644 --- a/systems/mix/src/live.rs +++ b/systems/mix/src/live.rs @@ -255,7 +255,7 @@ impl Live { } } let origin = self.origin.unwrap(); - if std::env::var_os("RAEA_MIXER_TRACE").is_some() { + if raea_io_trace::stat("RAEA_MIXER_TRACE") { eprintln!("raea mixer: frame {f} lag {:.2} ms clock {clock} due {due} origin {origin} drift {:.3} ms", lag * 1e3, self.drift_ms.last().copied().unwrap_or(0.0)); } // the sounds by index into the kept list, not cloned (ZeroHeap) diff --git a/systems/mix/src/offline.rs b/systems/mix/src/offline.rs index 31c83140..27079a6b 100644 --- a/systems/mix/src/offline.rs +++ b/systems/mix/src/offline.rs @@ -147,7 +147,7 @@ pub fn bounce(frames: &[Cue], fps: f64, master: Option<(f64, f64)>) -> Result = out.iter().step_by(2).copied().collect(); diff --git a/systems/page/Cargo.toml b/systems/page/Cargo.toml index f6370a27..9dfbb62e 100644 --- a/systems/page/Cargo.toml +++ b/systems/page/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "HTML and CSS pages in Bevy: a Blitz document restyled, laid out and painted by Vello on Bevy's own GPU device into a Bevy Image" [dependencies] +raea-io-trace = { path = "../../io/trace" } raea-sys-fonts = { path = "../fonts" } raea-sys-image = { path = "../image" } # a 3D view's clearColor parsed as CSS parses a colour (view3d/props.rs): linebender's, as peniko and Vello take it diff --git a/systems/page/src/draw.rs b/systems/page/src/draw.rs index 6050150f..e31240e5 100644 --- a/systems/page/src/draw.rs +++ b/systems/page/src/draw.rs @@ -238,7 +238,7 @@ pub fn draw(mut scenes: ResMut, mut vello: ResMut, device: Res Option { use std::sync::atomic::Ordering::Relaxed; let n = self.frames.load(Relaxed); - (std::env::var_os("RAEA_PAGE_TIMES").is_some() && n > 0).then(|| { + (raea_io_trace::stat("RAEA_PAGE_TIMES") && n > 0).then(|| { let (r, e) = (self.resolve_us.load(Relaxed), self.encode_us.load(Relaxed)); format!("{{\"page_frames\": {n}, \"resolve_ms\": {:.3}, \"encode_ms\": {:.3}}}", r as f64 / n as f64 / 1e3, e as f64 / n as f64 / 1e3) }) diff --git a/tools/nobuild.sh b/tools/nobuild.sh index 85bd56c9..73481e10 100755 --- a/tools/nobuild.sh +++ b/tools/nobuild.sh @@ -22,6 +22,10 @@ # package.json chose both. Then each props.tsv scene that draws the same pixels twice # (raster, the path tracer) and tools/nobuild/card.tsx draw the same by it as by RAEA_BIN: # a plugin compiled in and not chosen changes nothing. Exits 1 if one fails +# tools/nobuild.sh stats NB2a's check: every stat variable decided done is read through raea_io_trace::stat; +# tools/nobuild/stats/stats.tsx chooses bevy_passes and trace from TypeScript and reads +# stats.read back; the run prints each pass and keeps stats.json; RAEA_TRACE=1 and +# RAEA_STATS give the same trace lines on the scene without stats.on. Exits 1 if one fails # # 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), @@ -249,11 +253,49 @@ catalog() { if [ "$fails" = 0 ]; then rm -rf -- "${dir:?}"; else echo "nobuild: renders and logs kept in $dir"; exit 1; fi } +stats() { + bin=${RAEA_BIN:-$RAEA/target/release/raea} + local here=$RAEA/tools/nobuild/stats dir fails=0 v raw="" n=0 + [ -x "$bin" ] || { echo "nobuild: needs raea at $bin (RAEA_BIN)" >&2; exit 1; } + dir=$(mktemp -d "${TMPDIR:-/tmp}/nobuild-stats.XXXXXX") || exit 1 + check() { if [ "$2" = pass ]; then echo " $1: pass ($3)"; else echo " $1: FAIL ($3)"; fails=$((fails + 1)); fi; } + echo "nobuild stats: tools/nobuild/stats/stats.tsx by $bin" + # each stat variable decided done is read through stat(), so TypeScript and RAEA_STATS reach it, never straight + for v in $(awk -F'\t' '$2 == "stat" && $5 == "done" && $1 ~ /^env:/ { sub(/^env:/, "", $1); print $1 }' "$RAEA/docs/nobuild/decisions.tsv"); do + n=$((n + 1)); raw+=$(cd "$RAEA" && git grep -n -E "env::var(_os)?\(\"$v\"\)" -- '*.rs' ':!vendor' ':!io/trace' | head -2) + done + check "each done stat variable read through stat()" "$([ -z "$raw" ] && echo pass)" "${raw:-$n variables}" + # chosen from TypeScript, no variable set: stats.on at the scene's top level, stats.read on its last frame + (cd "$here" && env -u RAEA_TRACE -u RAEA_BEVY_PASSES -u RAEA_STATS RAEA_TRACE_DIR="$dir/trace" "$bin" render stats.tsx -o "$dir/ts" > "$dir/ts.log" 2>&1) + local read rows kept + # the trace channel's lines (RAEA_TRACE's: which path drew the frame), one of each + traced() { grep -E '^trace ' "$1" | sort -u; } + check "stats.on turned trace on" "$([ -n "$(traced "$dir/ts.log")" ] && echo pass)" "$(traced "$dir/ts.log" | head -1)" + # the last frame's, as the engine draws it (a render evaluates the edit's frames ahead of the engine too) + read=$(grep '^stats.read:' "$dir/ts.log" | tail -1) + check "stats.read from TypeScript" "$(awk '{ for (i = 1; i < NF; i++) if ($(i + 1) == "bevy" && $i + 0 > 0) ok = 1 } END { print ok ? "pass" : "x" }' <<<"$read")" "${read:-no stats.read line}" + rows=$(grep -c '^ bevy/' "$dir/ts.log") + check "the run's end printed each pass" "$([ "$rows" -gt 0 ] && grep -q '^raea stats (bevy_passes, trace):' "$dir/ts.log" && echo pass)" "$rows of Bevy's passes" + kept=$(find "$dir/trace" -name stats.json -exec jq -r '[.passes | keys[] | select(startswith("bevy/"))] | length' {} + 2>/dev/null | head -1) + check "stats.json kept in the run's trace" "$([ "${kept:-0}" -gt 0 ] && echo pass)" "${kept:-no stats.json}: Bevy's passes" + # the overrides, on the scene without stats.on: the channel's own variable, and RAEA_STATS + sed '/^native("stats.on"/d' "$here/stats.tsx" > "$dir/plain.tsx" + (cd "$dir" && env -u RAEA_STATS RAEA_TRACE=1 "$bin" render plain.tsx -o "$dir/env" > "$dir/env.log" 2>&1) + (cd "$dir" && env -u RAEA_TRACE RAEA_STATS=trace,bevy_passes "$bin" render plain.tsx -o "$dir/list" > "$dir/list.log" 2>&1) + (cd "$dir" && env -u RAEA_TRACE -u RAEA_BEVY_PASSES -u RAEA_STATS "$bin" render plain.tsx -o "$dir/none" > "$dir/none.log" 2>&1) + check "nothing chosen: no trace lines, no table" "$([ -z "$(traced "$dir/none.log")" ] && ! grep -q '^raea stats' "$dir/none.log" && grep -q '^APPLIED' "$dir/none.log" && echo pass)" "$(traced "$dir/none.log" | wc -l | tr -d ' ') trace lines" + check "RAEA_TRACE=1 the same trace lines" "$([ "$(traced "$dir/env.log")" = "$(traced "$dir/ts.log")" ] && ! grep -q '^raea stats' "$dir/env.log" && echo pass)" "$(traced "$dir/env.log" | wc -l | tr -d ' ') lines, no table" + check "RAEA_STATS=trace,bevy_passes the same, with the table" "$([ "$(traced "$dir/list.log")" = "$(traced "$dir/ts.log")" ] && grep -q '^ bevy/' "$dir/list.log" && echo pass)" "$(traced "$dir/list.log" | wc -l | tr -d ' ') lines, $(grep -c '^ bevy/' "$dir/list.log") passes" + echo "nobuild stats: $fails failing" + if [ "$fails" = 0 ]; then rm -rf -- "${dir:?}"; else echo "nobuild: renders and logs kept in $dir"; exit 1; fi +} + case ${1:-} in builds) shift; builds "$@" ;; scan) scan ;; consts) consts ;; props) props ;; catalog) catalog ;; - *) sed -n '2,29p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;; + stats) stats ;; + *) sed -n '2,33p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;; esac diff --git a/tools/nobuild/stats/stats.tsx b/tools/nobuild/stats/stats.tsx new file mode 100644 index 00000000..ddbb0eec --- /dev/null +++ b/tools/nobuild/stats/stats.tsx @@ -0,0 +1,42 @@ +import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea"; +import { native, print } from "@raea/app/native"; +import { Camera3d } from "raea/camera"; +import { AmbientLight, DirectionalLight } from "raea/light"; +import { Cuboid, Mesh3d } from "raea/mesh"; +import { StandardMaterial } from "raea/pbr"; +import { Quat, Transform } from "raea/transform"; + +// docs/nobuild.feature NB2a: a scene that turns stat channels on from TypeScript and reads the run's numbers back, +// with no variable set and no build (tools/nobuild.sh stats). At its top level, so they're on before the Engine opens: +// bevy_passes (each of Bevy's render passes timed) and trace (a line per update of each frame, RAEA_TRACE's). On its +// last frame it prints what stats.read says so far: the passes timed, and the Engine's draws and updates. +const FRAMES = 12; +native("stats.on", { channels: ["bevy_passes", "trace"] }); + +function Box() { + const f = useCurrentFrame(); + if (f === FRAMES - 1) { + const s = native("stats.read", {}); + const passes = Object.keys(s.passes).filter((k) => k.startsWith("bevy/")); + print(`stats.read: chosen ${s.chosen.join(",")}; ${passes.length} bevy passes timed; draws ${s.counters["engine/draws"] ?? 0}; updates ${s.counters["engine/updates"] ?? 0}`); + } + return ( + + <> + + + + + + + + + + + + + + ); +} + +registerRoot(() => );