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.

SG4a: the clipping check holds each shape's solid over its part's frames; frame purity's stills skip the checks it never reads

shinyobjectz2fd0c7f14a0c
diff --git a/apps/direction/src/pure.rs b/apps/direction/src/pure.rs
index 6edc4ea2..14d1d71a 100644
--- a/apps/direction/src/pure.rs
+++ b/apps/direction/src/pure.rs
@@ -98,7 +98,10 @@ fn stills(file: &str, args: &[String], at: &[u64], dir: &Path) -> Result<Value,
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let manifest = dir.join("stills.json");
let (flag, out) = if at.len() == 1 { ("--frame", dir.join("frame-00000.png").display().to_string()) } else { ("--at", format!("{}/", dir.display())) };
- let o = Command::new(me).arg("render").arg(file).args(kept(args)).args([flag, &list.join(","), "-o", &out, "--manifest"]).arg(&manifest).env("RAEA_RECORD", "off").env("RAEA_FRAME_PURE", "0").env("RAEA_DESPITE", "all: frame-pure's own stills").output().map_err(|e| e.to_string())?;
+ let o = Command::new(me).arg("render").arg(file).args(kept(args)).args([flag, &list.join(","), "-o", &out, "--manifest"]).arg(&manifest).env("RAEA_RECORD", "off").env("RAEA_FRAME_PURE", "0").env("RAEA_DESPITE", "all: frame-pure's own stills")
+ // nothing here reads the stills' clipping or staging, only their pictures and parts on screen: the checks cost
+ // the film's 44 stills 1.6 GB, beside the render that's still held (SG4a: its 8.6 GB peak)
+ .env("RAEA_CLIP_CHECK", "0").env("RAEA_STAGE_CHECK", "0").output().map_err(|e| e.to_string())?;
let m = std::fs::read(&manifest).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok());
m.ok_or_else(|| format!("the stills didn't render: {}", String::from_utf8_lossy(&o.stderr).lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no message")))
}
diff --git a/docs/stage-guards.feature b/docs/stage-guards.feature
index e3b4b69f..d1661828 100644
--- a/docs/stage-guards.feature
+++ b/docs/stage-guards.feature
@@ -176,6 +176,10 @@ Feature: Stage guards: a 3D render an agent can't break
| raea-io-av1 | io/av1/src/lib.rs | +4 | rav1e's packets kept in Samples |
| raea-sys-mix | systems/mix/src/offline.rs | +4 | the bounce fills each channel as the frames come, sized once from the frame count |
| raea-sys-share | systems/share/src/lib.rs | +43 | the mesh share (moved from runtime/scene3d) lets go of what no part holds |
+ | raea-sys-contact | systems/contact/src/solid.rs | +96 | Held: a shape's solid made at its part's first frame, let go after its last; occluders moved here |
+ | raea-sys-contact | systems/contact/src/lib.rs | 0 | the clipping check holds each part's solid over its frames only (Held), 3 lines shorter |
+ | raea-app-direction | apps/direction/src/pure.rs | +3 | frame purity's stills skip the clipping and staging checks it never reads |
+ | raea-runtime-export | runtime/export/src/scene.rs | +1 | a memory mark after what's on screen |
Then a 13,000-frame 3D render's memory stays within 10% of its first minute's
# Status 11-21 (branch stage-guards-8): the film (13,175 frames, 7:19) renders whole with every end check on, at
# a 9.4 to 13.6 GB peak. Before, memguard killed it past 24 GB (28 to 33 GB) after its last frame. Four causes,
@@ -219,6 +223,18 @@ Feature: Stage guards: a 3D render an agent can't break
# off), pages the allocator holds while they're partly free (Malloc Small's dirty memory 440 to 825 MB while the
# heap in use grew 150 MB: a mesh made and let go each frame for each part that changes size), the sound as it's
# bounced (0.17 GB, the film's sound itself) and each frame's manifest entry kept as JSON values (6 KB a frame).
+ # Branch stage-guards-19: the end's peak was two things, each measured on the film (resident memory every 2 s
+ # beside the memory marks). The clipping check made every part's solid before its first frame and held them all to
+ # its end: 1,323 shape expressions' solids, 2.9 GB of cells and 4 GB of footprint, against 26 MB for its 4 models'
+ # (a part whose size or words change is a new expression). A shape's solid is made at its part's first frame now,
+ # shared while parts hold it and let go after the last of them, unless an overlap of it is still to be said: the
+ # footprint after the check fell from 6.4 GB to 3.2 GB, in the same 19 s. And frame purity's 44 stills, rendered by
+ # a second raea while the first still held its memory, ran their own clipping and staging checks (1.6 GB), though
+ # purity reads only their pictures and parts on screen; they run without them now, their pictures the same. The
+ # film with every check on: 2.4 GB at frame 1,000, 3.7 GB at 13,000, a 6.0 GB peak (8.5 before), the same 439
+ # errors, 705 warns and 47 notes. mimalloc in place of the system allocator was measured and dropped: no less
+ # growth over the frames (3.74 GB at 13,000 against 3.89), and 7.8 GB kept after the end checks (2.3) for a 10.4 GB
+ # peak. Still not met: memory grows by about 45% after the first minute, for the causes left above.
Rule: The SDK stops allowing it
diff --git a/runtime/export/src/scene.rs b/runtime/export/src/scene.rs
index 0035ef90..098da177 100644
--- a/runtime/export/src/scene.rs
+++ b/runtime/export/src/scene.rs
@@ -36,6 +36,7 @@ fn checked(frames: Vec<(i64, Vec<raea_core_scene::Item>)>, page: Option<&[serde_
mark("end checks: each frame's parts made");
let (nums, all): (Vec<i64>, Vec<_>) = frames.into_iter().unzip();
*SEEN.lock().unwrap() = Some(raea_sys_stage::seen(&all, &nums, w, h));
+ mark("end checks: what's on screen");
let mut found = if std::env::var("RAEA_CLIP_CHECK").as_deref() == Ok("0") { Vec::new() } else { raea_sys_contact::told(&all, &nums, w, h, fps) };
mark("end checks: clipping");
found.extend(raea_sys_stage::told(&all, &nums, &page.map_or_else(Vec::new, |p| raea_sys_stage::pages(p, &nums, w, h)), w, h, fps));
diff --git a/systems/contact/src/lib.rs b/systems/contact/src/lib.rs
index c6de5dba..4822dc2c 100644
--- a/systems/contact/src/lib.rs
+++ b/systems/contact/src/lib.rs
@@ -264,15 +264,9 @@ fn volume(a: &Solid, wa: &Mat4, b: &Solid, wb: &Mat4) -> Option<Hit> {
pub fn check(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64) -> Vec<Value> {
// each part over the frames it's in (spans, not a slot per frame: SG4a); placed(i, k): part i's place on frame k
let parts: Vec<(String, Span)> = spans_of(all, &["mesh", "model"]);
- let solids: Vec<Option<Arc<Vec<Solid>>>> = parts.iter().map(|(_, tr)| solid_of(tr.items.iter().flatten().next()?).ok()).collect();
+ // each part's solid held over its frames only (Held, SG4a)
+ let mut held = Held::new(&parts, frames.len());
let placed = |i: usize, k: usize| parts[i].1.at(k).map_or(Mat4::IDENTITY, |it| it.world);
- // the pieces that hide others on frame k: every checked part there, see-through ones left out
- let occluders = |k: usize| -> Vec<(&Solid, Mat4)> {
- parts.iter().enumerate().filter_map(|(i, (_, tr))| Some((tr.at(k)?, solids[i].as_ref()?)))
- .filter(|(it, _)| !excused(it) || it.props.get("allowOverlap").and_then(Value::as_bool) == Some(true))
- .flat_map(|(it, ss)| ss.iter().map(move |s| (s, it.world)))
- .collect()
- };
// frame by frame: the parts' world boxes swept along x for the pairs that meet, each pair's test reused while
// neither part moves (the camera may still have)
let mut last: HashMap<(usize, usize), (Mat4, Mat4, Option<Hit>)> = HashMap::new();
@@ -281,6 +275,8 @@ pub fn check(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64) -> Vec
// overlaps no frame shows (off frame, behind something): first and last frame, and the first frame's hit
let mut hidden: HashMap<(usize, usize), (usize, usize, Hit)> = HashMap::new();
for k in 0..frames.len() {
+ held.at(&parts, k);
+ let solids = &held.solids;
let mut boxes: Vec<(usize, Vec3, Vec3)> = Vec::new();
for (i, (_, tr)) in parts.iter().enumerate() {
let (Some(it), Some(ss)) = (tr.at(k), &solids[i]) else { continue };
@@ -330,7 +326,7 @@ pub fn check(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64) -> Vec
if let Some(mut hit) = r {
let (sa, sb) = (&a[hit.pieces.0], &b[hit.pieces.1]);
let skip = 3.0 * (sa.cell * scale_of(&wa)).max(sb.cell * scale_of(&wb));
- if shows(&all[k], &std::mem::take(&mut hit.seam), occ.get_or_insert_with(|| occluders(k)), skip, w as f32, h as f32) {
+ if shows(&all[k], &std::mem::take(&mut hit.seam), occ.get_or_insert_with(|| occluders(&parts, solids, k)), skip, w as f32, h as f32) {
let runs = found.entry((i, j)).or_default();
match runs.last_mut() {
Some(run) if run.1 + 1 == k => {
@@ -346,6 +342,7 @@ pub fn check(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64) -> Vec
}
}
}
+ held.after(k, |i| found.keys().chain(hidden.keys()).any(|&(a, b)| a == i || b == i));
}
// unseen on every frame: still said, so a clip turned away from reads as hidden, not fixed (DR3, DR9's cheats)
let mut unseen: Vec<_> = hidden.into_iter().filter(|(p, _)| !found.contains_key(p)).collect();
@@ -359,7 +356,7 @@ pub fn check(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64) -> Vec
let mut out = Vec::new();
// one overlap said, over frames f0 to f1 (`seen`: its seam on screen, else said as standing in the scene unseen)
let mut say = |i: usize, j: usize, k: usize, hit: &Hit, f0: i64, f1: i64, seen: bool| {
- let (pa, pb, sa, sb) = (parts[i].1.at(k).unwrap(), parts[j].1.at(k).unwrap(), solids[i].as_ref().unwrap(), solids[j].as_ref().unwrap());
+ let (pa, pb, sa, sb) = (parts[i].1.at(k).unwrap(), parts[j].1.at(k).unwrap(), held.solids[i].as_ref().unwrap(), held.solids[j].as_ref().unwrap());
let (la, lb) = (label(pa, &sa[hit.pieces.0].name), label(pb, &sb[hit.pieces.1].name));
let (small, big) = if hit.small_first { (la, lb) } else { (lb, la) };
// out the shortest way: the smallest move along a world axis (not down) that leaves no piece in the other's
diff --git a/systems/contact/src/solid.rs b/systems/contact/src/solid.rs
index e01c9aa8..56aa2475 100644
--- a/systems/contact/src/solid.rs
+++ b/systems/contact/src/solid.rs
@@ -205,43 +205,139 @@ pub(crate) fn forget_solids() {
}
}
+/// What a part's solids are made from: its model's file, or its shape expression.
+fn key_of(it: &Item) -> String {
+ match it.kind {
+ "model" => format!("model:{}", src_path(it.props.get("src").and_then(Value::as_str).unwrap_or(""))),
+ _ => format!("mesh:{}", it.shape.as_deref().unwrap_or("")),
+ }
+}
+
/// A part's solids (one per mesh node of a model), made once per file or shape expression this process (an Err: not
/// checked, and why).
pub(crate) fn solid_of(it: &Item) -> Result<Arc<Vec<Solid>>, String> {
- let key = match it.kind {
- "model" => format!("model:{}", src_path(it.props.get("src").and_then(Value::as_str).unwrap_or(""))),
- _ => format!("mesh:{}", it.shape.as_deref().unwrap_or("")),
- };
+ let key = key_of(it);
if let Some(s) = CACHE.get_or_init(Default::default).lock().unwrap().get(&key) {
return s.clone();
}
- let made = (|| {
- let groups: Vec<(String, Vec<[Vec3; 3]>)> = if it.kind == "model" {
- let (g, moves) = gltf_tris(&key["model:".len()..])?;
- if moves {
- return Err("it animates".into());
- }
- g
- } else {
- let t = raea_core_shape::cached(it.shape.as_deref().ok_or("no shape")?)?;
- vec![(String::new(), t.positions.chunks_exact(3).map(|c| [Vec3::from(c[0]), Vec3::from(c[1]), Vec3::from(c[2])]).collect())]
- };
- // the whole model, and each mesh on its own when there are several: a statue in open pieces is only solid
- // whole, a ruin's thin column only resolved alone
- let mut solids: Vec<Solid> = Vec::new();
- if groups.len() > 1 {
- let whole: Vec<[Vec3; 3]> = groups.iter().flat_map(|(_, t)| t.iter().copied()).collect();
- solids.extend(voxelize(&whole));
- solids.extend(groups.into_iter().filter_map(|(name, t)| voxelize(&t).map(|mut s| {
- s.name = name;
- s
- })));
- } else {
- solids.extend(groups.into_iter().filter_map(|(_, t)| voxelize(&t)));
- }
- solids.retain(Solid::solid);
- if solids.is_empty() { Err("it has no volume".to_string()) } else { Ok(Arc::new(solids)) }
- })();
+ let made = make(it, &key);
CACHE.get_or_init(Default::default).lock().unwrap().insert(key, made.clone());
made
}
+
+fn make(it: &Item, key: &str) -> Result<Arc<Vec<Solid>>, String> {
+ let groups: Vec<(String, Vec<[Vec3; 3]>)> = if it.kind == "model" {
+ let (g, moves) = gltf_tris(&key["model:".len()..])?;
+ if moves {
+ return Err("it animates".into());
+ }
+ g
+ } else {
+ let t = raea_core_shape::cached(it.shape.as_deref().ok_or("no shape")?)?;
+ vec![(String::new(), t.positions.chunks_exact(3).map(|c| [Vec3::from(c[0]), Vec3::from(c[1]), Vec3::from(c[2])]).collect())]
+ };
+ // the whole model, and each mesh on its own when there are several: a statue in open pieces is only solid
+ // whole, a ruin's thin column only resolved alone
+ let mut solids: Vec<Solid> = Vec::new();
+ if groups.len() > 1 {
+ let whole: Vec<[Vec3; 3]> = groups.iter().flat_map(|(_, t)| t.iter().copied()).collect();
+ solids.extend(voxelize(&whole));
+ solids.extend(groups.into_iter().filter_map(|(name, t)| voxelize(&t).map(|mut s| {
+ s.name = name;
+ s
+ })));
+ } else {
+ solids.extend(groups.into_iter().filter_map(|(_, t)| voxelize(&t)));
+ }
+ solids.retain(Solid::solid);
+ if solids.is_empty() { Err("it has no volume".to_string()) } else { Ok(Arc::new(solids)) }
+}
+
+/// The parts' solids over a check's frames (`check`): a shape's made at its part's first frame, shared by the parts
+/// holding it, and let go after the last of them; a model's from the process's cache (its file, a few at most). A
+/// film's shapes change as its words and parts do: a 13,175-frame film's 1,323 shapes held at once were 2.9 GB of cells
+/// at its end, its render's peak (docs/stage-guards.feature SG4a).
+pub(crate) struct Held {
+ pub(crate) solids: Vec<Option<Arc<Vec<Solid>>>>,
+ /// the parts that start on each frame, and those whose last frame it is
+ starts: Vec<Vec<usize>>,
+ ends: Vec<Vec<usize>>,
+ shared: HashMap<String, Result<std::sync::Weak<Vec<Solid>>, String>>,
+}
+
+impl Held {
+ pub(crate) fn new(parts: &[(String, Span)], frames: usize) -> Held {
+ let (mut starts, mut ends) = (vec![Vec::new(); frames], vec![Vec::new(); frames]);
+ for (i, (_, s)) in parts.iter().enumerate() {
+ starts[s.first].push(i);
+ ends[s.first + s.items.len() - 1].push(i);
+ }
+ Held { solids: vec![None; parts.len()], starts, ends, shared: HashMap::new() }
+ }
+
+ /// Frame k's new parts' solids.
+ pub(crate) fn at(&mut self, parts: &[(String, Span)], k: usize) {
+ for &i in &self.starts[k] {
+ let Some(it) = parts[i].1.items.iter().flatten().next() else { continue };
+ let key = key_of(it);
+ let had = match self.shared.get(&key) {
+ Some(Ok(w)) => w.upgrade().map(Ok),
+ Some(Err(e)) => Some(Err(e.clone())),
+ None => None,
+ };
+ let s = had.unwrap_or_else(|| {
+ let s = if it.kind == "model" { solid_of(it) } else { make(it, &key) };
+ self.shared.insert(key, s.as_ref().map(Arc::downgrade).map_err(Clone::clone));
+ s
+ });
+ self.solids[i] = s.ok();
+ }
+ }
+
+ /// After frame k: the solids of the parts it was the last frame of let go, but those `keep` names (an overlap still
+ /// to be said with their pieces' names).
+ pub(crate) fn after(&mut self, k: usize, keep: impl Fn(usize) -> bool) {
+ for &i in &self.ends[k] {
+ if !keep(i) {
+ self.solids[i] = None;
+ }
+ }
+ }
+}
+
+/// The pieces that hide others on frame k: every checked part there, see-through ones left out.
+pub(crate) fn occluders<'a>(parts: &'a [(String, Span)], solids: &'a [Option<Arc<Vec<Solid>>>], k: usize) -> Vec<(&'a Solid, Mat4)> {
+ parts.iter().enumerate().filter_map(|(i, (_, tr))| Some((tr.at(k)?, solids[i].as_ref()?)))
+ .filter(|(it, _)| !excused(it) || it.props.get("allowOverlap").and_then(Value::as_bool) == Some(true))
+ .flat_map(|(it, ss)| ss.iter().map(move |s| (s, it.world)))
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn mesh(shape: &str) -> Item {
+ Item { kind: "mesh", props: Arc::new(serde_json::Map::new()), shape: Some(shape.into()), material: None, at: None, world: Mat4::IDENTITY }
+ }
+
+ #[test]
+ fn a_shape_is_held_over_its_parts_frames_only() {
+ let (a, b) = ("box(1, 1, 1)", "box(2, 1, 1)");
+ // parts: a#0 on frames 0-1, a#1 on frame 0, b#0 on frames 1-2
+ let all = vec![vec![mesh(a), mesh(a)], vec![mesh(a), mesh(b)], vec![mesh(b)]];
+ let parts = spans_of(&all, &["mesh"]);
+ let mut held = Held::new(&parts, all.len());
+ held.at(&parts, 0);
+ assert!(Arc::ptr_eq(held.solids[0].as_ref().unwrap(), held.solids[1].as_ref().unwrap()), "one shape's parts share its solid");
+ held.after(0, |_| false);
+ assert!(held.solids[0].is_some() && held.solids[1].is_none(), "a#1's last frame was 0");
+ held.at(&parts, 1);
+ held.after(1, |_| false);
+ assert!(held.solids[0].is_none() && held.solids[2].is_some());
+ assert!(held.shared["mesh:box(1, 1, 1)"].as_ref().is_ok_and(|w| w.upgrade().is_none()), "let go once no part holds it");
+ held.at(&parts, 2);
+ held.after(2, |i| i == 2);
+ assert!(held.solids[2].is_some(), "kept for an overlap still to be said");
+ }
+}