Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
LT21: detail costs the live scene no more than JS levels. A part's detail is a component row, and the live diff's fast path refused any scene holding rows of another kind, so every frame of a scene with a detail took the full diff: on 1917 Berlin's 1440p walk, step 29.7 ms against 10.6 ms with the levels picked in JS. Now the fast path keeps component rows as last sent and goes the full way only on a frame where any part's components change (scene_sig: light_sig plus each part's components), and a component row whose part has gone counts its missing frames and is forgotten as the full path forgets it. RAEA_LIVE3D_CHECK agrees over 3,413 frames of a moving scene where a part with a detail goes and comes back and another's detail changes. raea-sys-lod's apply keeps each part's meshes, bounds and last eye, walks its meshes again only when a mesh is added or its Detail changes, moves edge ranges by whole metres and rewrites a part only once the eye has moved a third of its way to the nearest fading band, since Bevy rebuilds its whole range table on any changed VisibilityRange. RAEA_LOD_DEBUG=time prints apply's time a frame. Walk at 1440p, JS levels then detail: step 10.6 / 11.8 ms, work p50 48.2 / 50.0, p99 100.5 / 87.1; fly: step 4.9 / 6.2, work p50 44.6 / 42.2, p99 139.7 / 125.0.
shinyobjectza3fec64205ea
diff --git a/runtime/look/src/post.rs b/runtime/look/src/post.rsindex 419f3a11..28334762 100644--- a/runtime/look/src/post.rs+++ b/runtime/look/src/post.rs@@ -379,3 +379,14 @@ pub fn light_sig(its: &[Item]) -> String {}s}++/// light_sig, and each part's Bevy components (its <BevyComponent>s, a Detail, its layer key): what a live frame's fast+/// path (raea-runtime-scene fast.rs) doesn't diff, so the frame where either changes goes the full way, and a frame+/// where neither did leaves the component rows as they were sent+pub fn scene_sig(its: &[Item]) -> String {+ let mut s = light_sig(its);+ for c in its.iter().filter_map(|i| i.props.get("components")) {+ s.push_str(&c.to_string());+ }+ s+}diff --git a/runtime/scene/src/fast.rs b/runtime/scene/src/fast.rsindex 01e8f7e1..ec3ae6f0 100644--- a/runtime/scene/src/fast.rs+++ b/runtime/scene/src/fast.rs@@ -16,8 +16,8 @@ impl LiveScene {if self.rows.is_empty() {return None;}- // rows of other kinds (components, entities, fires...): the full path, which diffs them (G15)- if self.rows.values().any(|r| !LIVE_GROUPS.contains(&r.kind.as_str())) {+ // rows of other kinds (entities, fires...): the full path, which diffs them (G15); components stay as sent (scene_sig)+ if self.rows.values().any(|r| !LIVE_GROUPS.contains(&r.kind.as_str()) && r.kind != "component") {return None;}// a lens, motion blur or a toon surface's keyed values: the full path, which keys them (camera_of, rows_into_of)@@ -25,8 +25,8 @@ impl LiveScene {return None;}let its = items_of(f.scene);- // a light's colour, shadows or shafts changed (its set, as_table): the full path, which makes them- if light_sig(&its) != self.light_sig {+ // a light's colour, shadows or shafts (its set, as_table) or a part's components changed: the full path, which makes them+ if scene_sig(&its) != self.light_sig {return None;}// pass 1: every part's id (as tracks_of names it on one frame), or None before anything changes@@ -285,12 +285,12 @@ impl LiveScene {// missing this frame: hidden (a light dark); dropped once it's been gone long enoughlet mut gone = Vec::new();for (id, r) in self.rows.iter_mut() {- if r.seen {+ if r.seen || (r.kind == "component" && r.missing == 0) {continue;}r.missing += 1;- if r.missing > LIVE_FORGET {- gone.push((r.kind.clone(), id.clone()));+ if r.missing > LIVE_FORGET || r.kind == "component" {+ gone.extend((r.missing > LIVE_FORGET).then(|| (r.kind.clone(), id.clone())));continue;}let (k, v) = match r.kind.as_str() {diff --git a/runtime/scene/src/live.rs b/runtime/scene/src/live.rsindex b919411f..94dfe5c3 100644--- a/runtime/scene/src/live.rs+++ b/runtime/scene/src/live.rs@@ -28,8 +28,8 @@ pub struct LiveScene {/// identity -> a panel's `src`, or an <Instances>' placements (its shared data-at), as the full path last made its row/// (the fast path leaves it a new one)pub(crate) panel_srcs: std::collections::HashMap<String, std::sync::Arc<str>>,- /// what the lights' sets were made from when the full path last made them (light_sig): the fast path, which- /// doesn't make them, goes the full way when it differs+ /// what the lights' sets and the parts' components were made from when the full path last made them (scene_sig):+ /// the fast path, which doesn't make them, goes the full way when it differspub(crate) light_sig: String,}@@ -142,7 +142,7 @@ impl LiveScene {/// by identity, with the row ids this scene keeps.pub(crate) fn current(&mut self, f: Shot) -> (BTreeMap<String, V>, Vec<(String, String, BTreeMap<String, V>)>) {let all = vec![items_of(f.scene)];- self.light_sig = light_sig(&all[0]);+ self.light_sig = scene_sig(&all[0]);// the camera's own spawns (its fog, sky...) in the frame's program with the restlet mut p = Program::default();let cam = self.camera_row(&all, f.clear, &mut p);diff --git a/systems/lod/src/lib.rs b/systems/lod/src/lib.rsindex b246ddba..d68f4df5 100644--- a/systems/lod/src/lib.rs+++ b/systems/lod/src/lib.rs@@ -49,8 +49,34 @@ struct ShadowLeft;pub fn install(app: &mut App) {app.register_type::<Detail>().add_systems(PostUpdate, apply.after(VisibilitySystems::CalculateBounds).after(bevy::transform::TransformSystems::Propagate).before(VisibilitySystems::CheckVisibility));- if std::env::var_os("RAEA_LOD_DEBUG").is_some() {- app.add_systems(PostUpdate, report.after(VisibilitySystems::CheckVisibility));+ match std::env::var("RAEA_LOD_DEBUG").as_deref() {+ Ok("time") => {+ app.init_resource::<LodTime>();+ app.add_systems(PostUpdate, (stamp.before(apply), timed.after(apply)));+ }+ Ok(_) => {+ app.add_systems(PostUpdate, report.after(VisibilitySystems::CheckVisibility));+ }+ Err(_) => {}+ }+}++/// RAEA_LOD_DEBUG=time: apply's own time and the Details changed this frame, averaged every 100 frames, on stderr+fn stamp(mut t: ResMut<LodTime>) {+ t.0 = Some(std::time::Instant::now());+}++#[derive(Resource, Default)]+struct LodTime(Option<std::time::Instant>, f64, u32, u32);++fn timed(mut t: ResMut<LodTime>, changed: Query<(), Changed<Detail>>, parts: Query<(), With<Detail>>) {+ let Some(at) = t.0 else { return };+ t.1 += at.elapsed().as_secs_f64() * 1000.0;+ t.2 += 1;+ t.3 += changed.iter().count() as u32;+ if t.2 == 100 {+ eprintln!("raea lod time: apply {:.2} ms a frame, {:.0} of {} Details changed a frame", t.1 / 100.0, t.3 as f64 / 100.0, parts.iter().count());+ *t = LodTime::default();}}@@ -102,9 +128,34 @@ pub fn edge_gap(eye: Vec3, point: Vec3, lo: Vec3, hi: Vec3) -> f32 {(eye.distance(point) - eye.distance(eye.clamp(lo, hi))).max(0.0)}+/// how far a part's nearest edge (`d`) is from the bands its range fades over (0 inside one): the eye can move a third+/// of this before a range written for it could draw the part differently (the edge and each mesh's gap move at most+/// as far as the eye)+pub fn slack(d: f32, start: f32, end: f32, fade: f32) -> f32 {+ let h = fade.clamp(0.0, 1.0) * 0.5;+ [start, end].into_iter().filter(|b| *b > 0.0 && b.is_finite()).fold(f32::INFINITY, |s, b| {+ let (lo, hi) = (b * (1.0 - h), b * (1.0 + h));+ s.min(if d < lo { lo - d } else if d > hi { d - hi } else { 0.0 })+ })+}+type MeshRow<'a> = (&'a GlobalTransform, Option<&'a Aabb>, Option<&'a VisibilityRange>, Has<NotShadowCaster>, Has<ShadowLeft>);-fn apply(cams: Query<(&Camera, &Projection, &GlobalTransform, Has<bevy::camera::ShadowLodOrigin>), With<Camera3d>>, parts: Query<(Entity, &Detail)>, children: Query<&Children>, meshes: Query<MeshRow, With<Mesh3d>>, mut commands: Commands) {+/// What `apply` last did for a part: its meshes and their bounds, and the Detail, lens and eye it wrote their ranges for.+/// Bevy rebuilds its whole table of ranges whenever one changes and never reuses a range's slot (65,535 in all), so a+/// range is written only when it can draw differently, and an edge's gap is whole metres.+#[derive(Default)]+struct Held {+ meshes: Vec<Entity>,+ bounds: Option<(Vec3, Vec3)>,+ detail: Option<Detail>,+ focal: Option<f32>,+ eye: Vec3,+ slack: f32,+}++#[allow(clippy::too_many_arguments)]+fn apply(cams: Query<(&Camera, &Projection, &GlobalTransform, Has<bevy::camera::ShadowLodOrigin>), With<Camera3d>>, parts: Query<(Entity, &Detail, Ref<GlobalTransform>)>, added: Query<(), Added<Mesh3d>>, children: Query<&Children>, meshes: Query<MeshRow, With<Mesh3d>>, mut held: Local<std::collections::HashMap<Entity, Held>>, mut commands: Commands) {// the shot's camera (raea gives it the shadow LOD origin), else the first active 3D one: a range is one per mesh,// so sizes on screen and nearest edges are measured for one cameralet shot = cams.iter().filter(|(c, ..)| c.is_active).max_by_key(|(.., origin)| *origin);@@ -113,15 +164,39 @@ fn apply(cams: Query<(&Camera, &Projection, &GlobalTransform, Has<bevy::camera::_ => None,});let eye = shot.map(|(_, _, at, _)| at.translation());- for (part, d) in &parts {- let found: Vec<Entity> = std::iter::once(part).chain(children.iter_descendants(part)).filter(|e| meshes.contains(*e)).collect();- if found.is_empty() {+ // a part's meshes are walked again only when meshes arrived (a glTF loading its children) or its Detail changed+ let loaded = !added.is_empty();+ held.retain(|e, _| parts.contains(*e));+ for (part, d, at) in &parts {+ let h = held.entry(part).or_default();+ let new = h.detail.as_ref() != Some(d);+ let walk = loaded || new || h.meshes.is_empty();+ if walk {+ h.meshes = std::iter::once(part).chain(children.iter_descendants(part)).filter(|e| meshes.contains(*e)).collect();+ }+ if h.meshes.is_empty() {continue;}- let bounds = bounds(&found, &meshes);- let size = if d.size > 0.0 { d.size } else { bounds.map_or(0.0, |(lo, hi)| (hi - lo).length()) };+ if walk || at.is_changed() {+ h.bounds = bounds(&h.meshes, &meshes);+ }+ let size = if d.size > 0.0 { d.size } else { h.bounds.map_or(0.0, |(lo, hi)| (hi - lo).length()) };let (start, end) = span(d, size, focal);- for e in found {+ let edge = match (d.edge, eye, h.bounds) {+ (true, Some(eye), Some((lo, hi))) => Some((eye, lo, hi)),+ _ => None,+ };+ let moved = edge.is_some_and(|(eye, ..)| eye.distance(h.eye) >= (h.slack / 3.0).max(0.5));+ if !(walk || at.is_changed() || h.focal != focal || moved) {+ continue;+ }+ h.detail = Some(d.clone());+ h.focal = focal;+ if let Some((eye, lo, hi)) = edge {+ h.eye = eye;+ h.slack = slack(eye.distance(eye.clamp(lo, hi)), start, end, d.fade);+ }+ for &e in &h.meshes {let Ok((gt, aabb, now, no_shadow, ours)) = meshes.get(e) else { continue };// measured from the mesh's origin, unless that lies outside its own bounds (a mesh baked in world// coordinates, as the city's tiles are): then from its bounds' centre@@ -130,10 +205,7 @@ fn apply(cams: Query<(&Camera, &Projection, &GlobalTransform, Has<bevy::camera::Some(a) => gt.affine().transform_point3(Vec3::from(a.center)),None => gt.translation(),};- let gap = match (d.edge, eye, bounds) {- (true, Some(eye), Some((lo, hi))) => edge_gap(eye, point, lo, hi),- _ => 0.0,- };+ let gap = edge.map_or(0.0, |(eye, lo, hi)| edge_gap(eye, point, lo, hi).round());let want = shifted(range(start, end, d.fade, use_aabb), gap);if now != Some(&want) {commands.entity(e).insert(want);@@ -213,4 +285,14 @@ mod tests {assert_eq!(edge_gap(Vec3::new(12.0, 0.0, 0.0), Vec3::new(15.0, 0.0, 0.0), Vec3::new(10.0, -1.0, -1.0), Vec3::new(20.0, 1.0, 1.0)), 3.0);assert_eq!(shifted(range(30.0, f32::INFINITY, 0.0, true), 5.0).end_margin, f32::MAX..f32::MAX);}++ #[test]+ fn slack_is_the_way_to_the_nearest_fading_band() {+ // drawn 120 m to 700 m, fading 10%: bands 114-126 m and 665-735 m+ assert!((slack(300.0, 120.0, 700.0, 0.1) - 174.0).abs() < 1e-3);+ assert_eq!(slack(120.0, 120.0, 700.0, 0.1), 0.0);+ // a start at 0 and an endless end have no band+ assert!((slack(50.0, 0.0, f32::INFINITY, 0.1)).is_infinite());+ assert!((slack(50.0, 0.0, 120.0, 0.1) - 64.0).abs() < 1e-3);+ }}