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
Stills late in a long 3D composition no longer cost memory and time with the frame index (closes #77). A still at --at F stepped React only near F, but held every frame before it as copies; each changing column was keyed on every one of those frames, and the timeline evaluated and kept every frame (a film's --at 2448: 234 s and 7.1 GB, against 9 s and 3.1 GB at --at 30). The timeline (core/program) now evaluates only the frames where some key's value can change from the frame before, and a frame no key changes shares the frame before's columns. A column keyed one value a frame keeps only the keys where its value differs from a neighbour's (raea_runtime_look::linear_keys, also used by the scene's per-frame colours), which is exact under linear interpolation. 200 turning cubes at --at 2448: peak 829 MB -> 504 MB (1.32x the --at 30 peak, was 2.14x), engine open 700 ms -> 280 ms, and the frame is pixel-exact. bench/at-cost checks the ratio and the pixels.
shinyobjectzd4a00c60445e
diff --git a/bench/at-cost/check.sh b/bench/at-cost/check.shnew file mode 100755index 00000000..504acd8d--- /dev/null+++ b/bench/at-cost/check.sh@@ -0,0 +1,56 @@+#!/bin/bash+# A still late in a long 3D composition costs about what one early in it does (#77). A still at --at F stepped React+# only near F, but held every frame before it as copies, keyed each changing column on all of them and evaluated and+# kept every one in the timeline: a film's --at 2448 took 234 s and 7.1 GB against 9 s and 3.1 GB at --at 30.+# 200 turning cubes over 3618 frames are drawn at --at 30 and --at 2448. The peak memory at 2448 must stay under 1.6x+# the one at 30 (the #60 build: 2.3x), and the 2448 still must match the same scene drawn at frame 30 with its clock+# moved on 2418 frames (within 1 level, as frames are pure), so the shortcut changes no pixel. Exits 1 on a failure.+# bench/at-cost/check.sh (RAEA_BIN: the raea to run, default target/release/raea)+cd "$(dirname "$0")/../.." || exit 2+BIN=${RAEA_BIN:-$PWD/target/release/raea}+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0+OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-at-cost.XXXXXX")+trap 'rm -rf "$OUT"' EXIT+scene() { # FILE OFFSET+ cat > "$1" <<TSX+import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";+import { StandardMaterial } from "raea/pbr";+import { Cuboid, Mesh3d } from "raea/mesh";+import { DirectionalLight } from "raea/light";+import { Transform, Quat } from "raea/transform";+import { Camera3d } from "raea/camera";+function Shot() {+ const f = useCurrentFrame() + $2;+ const parts = Array.from({ length: 200 }, (_, i) => (+ <Mesh3d key={i} transform={Transform.fromXyz((i % 20) - 10, Math.floor(i / 20) - 5, -8).withRotation(Quat.fromEuler("XYZ", 0, f * 0.01 + i, 0))}>+ <Cuboid half_size={[0.3, 0.3, 0.3]} />+ <StandardMaterial base_color="#ff7a1a" />+ </Mesh3d>+ ));+ return (+ <AbsoluteFill style={{ backgroundColor: "#1b2230" }}>+ <Camera3d transform={Transform.fromXyz(0, 0, 8).lookingAt([0, 0, 0])} />+ <DirectionalLight illuminance={8000} transform={Transform.fromXyz(3, 5, 4).lookingAt([0, 0, 0])} />+ {parts}+ </AbsoluteFill>+ );+}+registerRoot(() => <Composition id="c" component={Shot} width={640} height={360} fps={30} durationInFrames={3618} />);+TSX+}+scene "$OUT/late.tsx" 0+scene "$OUT/moved.tsx" 2418+status=0+peak() { # NAME TSX AT: the render's peak resident bytes on stdout+ /usr/bin/time -l "$BIN" render "$2" --at "$3" -o "$OUT/$1" > "$OUT/$1.log" 2>&1 && [ -f "$OUT/$1/frame-00000.png" ] || { echo "FAIL $1: the render failed" >&2; tail -4 "$OUT/$1.log" | sed 's/^/ /' >&2; return 1; }+ awk '/maximum resident set size/ { print $1 }' "$OUT/$1.log"+}+early=$(peak early "$OUT/late.tsx" 30) && late=$(peak late "$OUT/late.tsx" 2448) && moved=$(peak moved "$OUT/moved.tsx" 30) || exit 1+ratio=$(echo "scale=2; $late / $early" | bc)+if (( late * 10 < early * 16 )); then echo "ok --at 2448 peaks at ${ratio}x --at 30 ($((late >> 20)) MB, $((early >> 20)) MB)"+else echo "FAIL --at 2448 peaks at ${ratio}x --at 30 ($((late >> 20)) MB against $((early >> 20)) MB), wanted under 1.6x"; status=1; fi+max=$(magick "$OUT/late/frame-00000.png" "$OUT/moved/frame-00000.png" -compose difference -composite -format "%[fx:int(maxima*255+0.5)]" info:)+if (( max <= 1 )); then echo "ok frame 2448 matches the scene moved on to it at frame 30 (largest difference $max)"+else echo "FAIL frame 2448 differs from the scene moved on to it at frame 30 by up to $max levels"; status=1; fi+[ $status = 0 ] && echo "PASS a late still costs about what an early one does, and draws the same frame"+exit $statusdiff --git a/core/program/src/timeline.rs b/core/program/src/timeline.rsindex 074deac9..ab1eeabd 100644--- a/core/program/src/timeline.rs+++ b/core/program/src/timeline.rs@@ -10,8 +10,9 @@ use crate::ir::{Program, V};pub struct Timeline {pub frames: i64,pub base: Cols,- /// per frame: the columns whose values differ from the base (whole columns)- written: Vec<HashMap<String, std::sync::Arc<Col>>>,+ /// per frame: the columns whose values differ from the base (whole columns); a frame no key changes from the one+ /// before shares that frame's (#77)+ written: Vec<std::sync::Arc<HashMap<String, std::sync::Arc<Col>>>>,/// per row: true when no frame changes any of its values from the base, so a system that applies a row's values/// to the World each frame can apply a still row's oncestill: Vec<bool>,@@ -27,8 +28,11 @@ impl Timeline {pub fn from_cols(prog: &Program, base: Cols) -> Result<Timeline, String> {let frames = prog.frames.max(0);- let per: Vec<(HashMap<String, std::sync::Arc<Col>>, Vec<(usize, String)>)> = parallel(frames as usize, |f| {- let raw = eval::frame_cols(prog, &base, f as i64);+ // only the frames some key changes from the frame before are evaluated: a still at frame 2448 of a scene keyed+ // on every frame held its frames before as copies of one, and evaluated and kept all 2449 (#77: 234 s, 7.1 GB)+ let fresh: Vec<i64> = changes(prog, frames).into_iter().enumerate().filter(|(_, c)| *c).map(|(f, _)| f as i64).collect();+ let per: Vec<(HashMap<String, std::sync::Arc<Col>>, Vec<(usize, String)>)> = parallel(fresh.len(), |i| {+ let raw = eval::frame_cols(prog, &base, fresh[i]);let w: HashMap<String, std::sync::Arc<Col>> = raw.cols.into_iter().filter(|(c, v)| base.cols.get(c) != Some(v)).collect();// the rows this frame moves and by which columns: a written column's value differing from the base's therelet moved = w.iter().flat_map(|(c, col)| (0..base.len()).filter(|r| !col.same_at(base.cols.get(c).map(|b| &**b), *r)).map(move |r| (r, c.clone()))).collect();@@ -36,15 +40,16 @@ impl Timeline {})?;let mut still = vec![true; base.len()];let mut moving: Vec<Vec<String>> = vec![Vec::new(); base.len()];- let written = per.into_iter().map(|(w, moved)| {+ let evaluated: Vec<std::sync::Arc<HashMap<String, std::sync::Arc<Col>>>> = per.into_iter().map(|(w, moved)| {for (r, c) in moved {still[r] = false;if !moving[r].contains(&c) {moving[r].push(c);}}- w+ std::sync::Arc::new(w)}).collect();+ let written = (0..frames).map(|f| evaluated[fresh.partition_point(|&e| e <= f) - 1].clone()).collect();Ok(Timeline { frames, base, written, still, moving })}@@ -67,7 +72,7 @@ impl Timeline {pub fn cols(&self, f: i64) -> Cols {let mut c = self.base.clone();if let Some(w) = self.written.get(f as usize) {- for (k, v) in w {+ for (k, v) in w.iter() {c.cols.insert(k.clone(), v.clone());}}@@ -88,6 +93,26 @@ impl Timeline {}}+/// Per frame: whether some key's value there may differ from the frame before's (frame 0: always). Between two of a+/// key's points with one value nothing moves, whatever the ease; before its first point and after its last it holds.+fn changes(prog: &Program, frames: i64) -> Vec<bool> {+ let mut c = vec![false; frames as usize];+ if let Some(first) = c.first_mut() {+ *first = true;+ }+ for pts in prog.keys.values() {+ for w in pts.windows(2) {+ let ((f0, v0, _), (f1, v1, _)) = (&w[0], &w[1]);+ if v0 != v1 || v0.is_nan() {+ for f in (f0 + 1).max(0)..=(*f1).min(frames - 1) {+ c[f as usize] = true;+ }+ }+ }+ }+ c+}+/// f(0..n) on every core, in order. A browser build (wasm32) has one thread and can't spawn more: in turn there.fn parallel<T: Send>(n: usize, f: impl Fn(usize) -> Result<T, String> + Sync) -> Result<Vec<T>, String> {#[cfg(target_arch = "wasm32")]@@ -151,4 +176,19 @@ mod tests {assert_eq!(t.cols(1).get(0, "x"), Some(V::N(1.0)), "a value set on a frame's columns changed the timeline");assert_eq!(t.cols(1).get(1, "x"), Some(V::N(1.0)));}++ #[test]+ fn frames_no_key_changes_read_as_the_frame_before_and_every_frame_matches_its_own_evaluation() {+ // held at 5 to frame 6, up to 9 by frame 8, held after; a step key, and a key starting before frame 0+ let mut prog = Program { frames: 12, ..Default::default() };+ prog.keys.insert(("a".into(), "x".into()), vec![(0, 5.0, "linear".into()), (6, 5.0, "linear".into()), (8, 9.0, "inout".into())]);+ prog.keys.insert(("b".into(), "x".into()), vec![(-3, 0.0, "linear".into()), (2, 4.0, "step".into())]);+ let base = Cols::from_tups(&[row("a", 0.0), row("b", 0.0)]);+ assert_eq!(changes(&prog, 12), [true, true, true, false, false, false, false, true, true, false, false, false]);+ let t = Timeline::from_cols(&prog, base.clone()).unwrap();+ for f in 0..12 {+ assert_eq!(t.cols(f), eval::frame_cols(&prog, &base, f), "frame {f}");+ }+ assert!(std::sync::Arc::ptr_eq(&t.written[3], &t.written[6]) && std::sync::Arc::ptr_eq(&t.written[9], &t.written[11]));+ }}diff --git a/runtime/look/src/lib.rs b/runtime/look/src/lib.rsindex 11e0f879..6c3442f9 100644--- a/runtime/look/src/lib.rs+++ b/runtime/look/src/lib.rs@@ -146,10 +146,18 @@ pub fn column(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, name: &spub fn exact(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, name: &str, vals: &[f64]) {row.insert(name.into(), V::N(vals[0]));if !vals.iter().all(|v| (*v - vals[0]).abs() < 1e-9) {- p.keys.insert((id.to_string(), name.to_string()), vals.iter().enumerate().map(|(f, v)| (f as i64, *v, "linear".to_string())).collect());+ p.keys.insert((id.to_string(), name.to_string()), linear_keys(vals));}}+/// One value a frame as linear keys: a key only where the value differs from a neighbour's, as linear between the rest+/// gives the same value on every frame; a still late in a long scene (its frames before held as copies of one) keyed+/// thousands of frames per column (#77).+pub fn linear_keys(vals: &[f64]) -> Vec<(i64, f64, String)> {+ let keep = |f: usize| f == 0 || f + 1 == vals.len() || vals[f] != vals[f - 1] || vals[f] != vals[f + 1];+ vals.iter().enumerate().filter(|(f, _)| keep(*f)).map(|(f, v)| (f as i64, *v, "linear".to_string())).collect()+}+/// A model's look as raea-render's look column has it: 0 solid, 1 pixel, 2 site.pub fn look_of(props: &Map<String, Value>) -> f64 {match props.get("look").and_then(Value::as_str) {diff --git a/runtime/scene/src/models.rs b/runtime/scene/src/models.rsindex 084686e0..38924824 100644--- a/runtime/scene/src/models.rs+++ b/runtime/scene/src/models.rs@@ -234,7 +234,7 @@ pub(crate) fn fogs_rows(tr: &Tracks, p: &mut Program) {if colors.iter().any(|c| *c != colors[0]) {let c: Vec<[f64; 3]> = colors.iter().map(|c| rgb(c)).collect();for (k, name) in ["col_r", "col_g", "col_b"].iter().enumerate() {- p.keys.insert((id.clone(), name.to_string()), c.iter().enumerate().map(|(f, v)| (f as i64, v[k], "linear".to_string())).collect());+ p.keys.insert((id.clone(), name.to_string()), raea_runtime_look::linear_keys(&c.iter().map(|v| v[k]).collect::<Vec<_>>()));row.insert(name.to_string(), V::N(c[0][k]));}}diff --git a/runtime/scene/src/parts.rs b/runtime/scene/src/parts.rsindex 1e44b0c7..16829b57 100644--- a/runtime/scene/src/parts.rs+++ b/runtime/scene/src/parts.rs@@ -154,7 +154,7 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {for (k, name) in ["col_r", "col_g", "col_b"].iter().enumerate() {let vals: Vec<f64> = c.iter().map(|v| v[k]).collect();// exact, as the hex's byte over 255 (the engine reads either into the same f32: #26)- p.keys.insert((id.clone(), name.to_string()), vals.iter().enumerate().map(|(f, v)| (f as i64, *v, "linear".to_string())).collect());+ p.keys.insert((id.clone(), name.to_string()), raea_runtime_look::linear_keys(&vals));row.insert(name.to_string(), V::N(vals[0]));}}