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.

A solid's mesh is kept on disk between runs. An expression's mesh is the same every time a build makes it, and the boolean cuts of a furnished set were a quarter of the seconds its scene took to open, on every open. raea-core-shape's cached() now reads the mesh it made before from raea's caches folder (shapes/, named by the expression and by the running build, written beside and moved into place) and makes it only when it isn't there; RAEA_SHAPE_CACHE=0 turns that off and =DIR moves it. A launch-film set played offscreen at frame 0: 12.2 s with it off, 4.6 s kept, the frame the same bytes. 1 test (a kept mesh reads back bit for bit; one cut short isn't read).

shinyobjectzee62b1325377
diff --git a/core/shape/src/kept.rs b/core/shape/src/kept.rs
new file mode 100644
index 00000000..e3952429
--- /dev/null
+++ b/core/shape/src/kept.rs
@@ -0,0 +1,81 @@
+//! Solids kept on disk between runs. An expression's mesh is the same every time this build makes it, and making it
+//! is the cost: the boolean cuts of a furnished set were a quarter of the seconds its scene took to open, every time
+//! it opened (a launch-film set, 11-10). A kept mesh is named by the expression and by this build (the running
+//! program's size and time: another build may cut differently), and read back as the bytes that were written, so
+//! what is drawn from it is what would have been made. RAEA_SHAPE_CACHE=0 turns it off, =DIR moves it from raea's
+//! caches folder (shapes/ in it).
+
+use crate::Tris;
+use std::path::PathBuf;
+
+/// raea's caches folder, as raea-io-home names it (this crate is below it): ~/Library/Caches/raea on macOS,
+/// %LOCALAPPDATA%\raea\cache on Windows, $XDG_CACHE_HOME/raea or ~/.cache/raea elsewhere.
+fn caches() -> Option<PathBuf> {
+ let var = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
+ if cfg!(windows) {
+ return var("LOCALAPPDATA").map(|d| d.join("raea").join("cache"));
+ }
+ if cfg!(target_os = "macos") {
+ return var("HOME").map(|h| h.join("Library/Caches/raea"));
+ }
+ var("XDG_CACHE_HOME").filter(|p| p.is_absolute()).or_else(|| var("HOME").map(|h| h.join(".cache"))).map(|d| d.join("raea"))
+}
+
+fn this_build() -> (u64, u128) {
+ static BUILD: std::sync::OnceLock<(u64, u128)> = std::sync::OnceLock::new();
+ *BUILD.get_or_init(|| {
+ let m = std::env::current_exe().ok().and_then(|p| std::fs::metadata(p).ok());
+ let t = m.as_ref().and_then(|m| m.modified().ok()).and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos()).unwrap_or(0);
+ (m.map(|m| m.len()).unwrap_or(0), t)
+ })
+}
+
+/// Where the mesh for `expr` is kept, or None when nothing is (off, or no caches folder here).
+pub fn place(expr: &str) -> Option<PathBuf> {
+ let root = match std::env::var("RAEA_SHAPE_CACHE") {
+ Ok(v) if v == "0" => return None,
+ Ok(v) if !v.is_empty() => PathBuf::from(v),
+ _ => caches()?.join("shapes"),
+ };
+ let (len, time) = this_build();
+ let mut key: u64 = 0xcbf2_9ce4_8422_2325;
+ for b in expr.as_bytes().iter().chain(&len.to_le_bytes()).chain(&time.to_le_bytes()) {
+ key = (key ^ *b as u64).wrapping_mul(0x100_0000_01b3);
+ }
+ Some(root.join(format!("{key:016x}-{:x}.tris", expr.len())))
+}
+
+const MAGIC: &[u8; 8] = b"raeatri1";
+
+/// The mesh kept at `p`: None when there is none or it isn't whole (a write that was cut short).
+pub fn read(p: &std::path::Path) -> Option<Tris> {
+ let b = std::fs::read(p).ok()?;
+ let n = u64::from_le_bytes(b.get(8..16)?.try_into().ok()?) as usize;
+ if &b[..8] != MAGIC || b.len() != 16 + n * 24 {
+ return None;
+ }
+ let f = |at: usize| f32::from_le_bytes(b[at..at + 4].try_into().unwrap());
+ let run = |from: usize| (0..n).map(|i| [f(from + i * 12), f(from + i * 12 + 4), f(from + i * 12 + 8)]).collect::<Vec<_>>();
+ Some(Tris { positions: run(16), normals: run(16 + n * 12) })
+}
+
+/// `t` kept at `p`, written beside it and moved into place so a reader never sees half of it. Failing is fine: the
+/// mesh is made again next time.
+pub fn write(p: &std::path::Path, t: &Tris) {
+ if t.positions.len() != t.normals.len() {
+ return;
+ }
+ let mut b = Vec::with_capacity(16 + t.positions.len() * 24);
+ b.extend_from_slice(MAGIC);
+ b.extend_from_slice(&(t.positions.len() as u64).to_le_bytes());
+ for v in t.positions.iter().chain(&t.normals) {
+ for x in v {
+ b.extend_from_slice(&x.to_le_bytes());
+ }
+ }
+ let Some(dir) = p.parent() else { return };
+ let part = dir.join(format!(".{}.{}.part", p.file_name().unwrap_or_default().to_string_lossy(), std::process::id()));
+ if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&part, b).is_ok() && std::fs::rename(&part, p).is_err() {
+ let _ = std::fs::remove_file(&part);
+ }
+}
diff --git a/core/shape/src/lib.rs b/core/shape/src/lib.rs
index 5b6c8689..4595209f 100644
--- a/core/shape/src/lib.rs
+++ b/core/shape/src/lib.rs
@@ -29,6 +29,7 @@
mod build;
mod glyphs;
mod grown;
+mod kept;
mod mesh;
mod parse;
mod sphere;
@@ -196,7 +197,18 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
if let Some(t) = cache.lock().unwrap().get(expr) {
return Ok(t.clone());
}
- let t = std::sync::Arc::new(tris(&solid(expr)?));
+ // made by this build before, on disk (kept.rs): read back as it was written
+ let kept = kept::place(expr);
+ let t = match kept.as_deref().and_then(kept::read) {
+ Some(t) => std::sync::Arc::new(t),
+ None => {
+ let t = std::sync::Arc::new(tris(&solid(expr)?));
+ if let Some(p) = &kept {
+ kept::write(p, &t);
+ }
+ t
+ }
+ };
cache.lock().unwrap().insert(expr.to_string(), t.clone());
Ok(t)
}
@@ -205,6 +217,23 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
mod tests {
use super::*;
+ #[test]
+ fn a_kept_mesh_reads_back_as_it_was_written() {
+ let dir = std::env::temp_dir().join(format!("raea-shape-kept-{}", std::process::id()));
+ let p = dir.join("a.tris");
+ let t = tris(&solid("minus(box(2, 2, 2), cylinder(0.5, 3))").unwrap());
+ assert!(kept::read(&p).is_none());
+ kept::write(&p, &t);
+ let back = kept::read(&p).unwrap();
+ assert_eq!(back.positions.iter().flatten().map(|x| x.to_bits()).collect::<Vec<_>>(), t.positions.iter().flatten().map(|x| x.to_bits()).collect::<Vec<_>>());
+ assert_eq!(back.normals.iter().flatten().map(|x| x.to_bits()).collect::<Vec<_>>(), t.normals.iter().flatten().map(|x| x.to_bits()).collect::<Vec<_>>());
+ // a file cut short isn't a mesh
+ let whole = std::fs::read(&p).unwrap();
+ std::fs::write(&p, &whole[..whole.len() - 5]).unwrap();
+ assert!(kept::read(&p).is_none());
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn csg_volumes_are_right() {
let v = |e: &str| solid(e).unwrap().volume();
diff --git a/docs/preview.feature b/docs/preview.feature
index d6465c3e..b1cbfc2c 100644
--- a/docs/preview.feature
+++ b/docs/preview.feature
@@ -119,6 +119,12 @@ Feature: Preview: anything in a project opens at once, in its space, with its pr
# started thirty still renders at once and the Mac swapped), the last moment's asks first. And a 3D part asked for
# again by id (the game inspector re-reads what is picked on every frame) answers its own box on the frame: it
# answered its holder's, so the outline a click drew was gone a frame later.
+ # 11-10, how long a heavy scene takes to open (a launch-film set, raea play offscreen at frame 0): a quarter of it
+ # was the boolean cuts of its solids, made again on every open. raea-core-shape keeps each expression's mesh on
+ # disk by expression and build (kept.rs; RAEA_SHAPE_CACHE=0 turns it off): 12.2 s with it off, 4.6 s kept, the
+ # frame the same bytes. What is left is the script's own pass (its solids are cut again there, through the
+ # /3d manifold calls: not kept yet) and the models' loading. A still for Source or a poster is drawn through
+ # raea play, one at a time at low priority, and not while a stage the person opened is still opening.
@done
Scenario: PV3b. The store is managed in one place
Then Settings lists the store by project and kind with sizes, and offers Clear and Rebuild; copies whose source