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.

An <Instances> keeps one copy of its placements across a render's frames, not one a frame (#84). The SDK sent them inside data-props, so a set whose other props changed each frame (a spin) was parsed whole into each frame's props and every frame's scene was kept (the fed render's frames, the clipping check): 20,000 spheres turning cost 2.1 GB at 120 frames and the issue's 60,000 at 4K 7 GB at 60 and 14 GB at 240. Now the SDK sends them as data-at; raea-runtime-react keeps each part's text as one Arc<str> (AT3D) while it's the same, and Node3 and Item carry it as at; the look compares frames' texts before parsing one (instances_column), and the fast live path compares the Arc (panel_srcs, now shared text). <Entities>' expansion moves to raea-core-scene (entities_nodes) to keep raea-runtime-react under 2000 lines. Measured: the 20,000 spinning, 621 MB and 18.6 ms a frame at 120 frames (was 2,117 MB, 69.7 ms), 645 MB at 480; 60,000 at 4K60, 1.04 GB at 60 frames and 1.22 GB at 240. About 1 MB a frame still grows. A binary from before this, run on this SDK, draws an <Instances> as its one mesh

shinyobjectzd7f2aaf07630
diff --git a/core/review/src/lib.rs b/core/review/src/lib.rs
index 92fe6d40..642b7e14 100644
--- a/core/review/src/lib.rs
+++ b/core/review/src/lib.rs
@@ -137,7 +137,7 @@ fn place_camera(out: &mut Vec<Item>, eye: [f64; 3], at: [f64; 3], fov: Option<f6
None => {
let mut props = Map::new();
set(&mut props);
- out.push(Item { kind: "camera", props: Arc::new(props), shape: None, material: None, world: Mat4::IDENTITY });
+ out.push(Item { kind: "camera", props: Arc::new(props), shape: None, material: None, at: None, world: Mat4::IDENTITY });
}
}
}
@@ -174,7 +174,7 @@ mod tests {
#[test]
fn a_review_camera_drops_the_scene_cameras_rotation_and_one_is_added_when_there_is_none() {
let props = json!({"position": [0, 2, 6], "lookAt": [0, 1, 0], "rotation": [0.0, 0.0, 0.0, 1.0]}).as_object().cloned().unwrap();
- let mut its = vec![Item { kind: "camera", props: Arc::new(props), shape: None, material: None, world: Mat4::IDENTITY }];
+ let mut its = vec![Item { kind: "camera", props: Arc::new(props), shape: None, material: None, at: None, world: Mat4::IDENTITY }];
place_camera(&mut its, [6.0, 1.7, 0.0], [0.5, 1.5, 0.0], Some(40.0));
let p = &its[0].props;
assert_eq!((p["position"].clone(), p["lookAt"].clone(), p["fov"].clone(), p.get("rotation")), (json!([6.0, 1.7, 0.0]), json!([0.5, 1.5, 0.0]), json!(40.0), None));
diff --git a/core/scene/src/lib.rs b/core/scene/src/lib.rs
index a72f2097..e103db56 100644
--- a/core/scene/src/lib.rs
+++ b/core/scene/src/lib.rs
@@ -23,6 +23,9 @@ pub struct Node3 {
/// rows by reference (ZeroHeap: a live 3D frame parsed and copied every part's props)
pub props: std::sync::Arc<Map<String, Value>>,
pub shape: Option<std::sync::Arc<str>>,
+ /// an <Instances>' placements, its data-at text (9 numbers a copy, JSON): shared across frames while it's the same
+ /// text, outside props, so a set whose other props change each frame keeps one list, not one a frame (#84)
+ pub at: Option<std::sync::Arc<str>>,
/// shared: a subtree no commit touched is the last frame's, handed on for an Arc's count (docs/control.feature
/// FC1b: many_cubes' 10,000 parts were re-read each frame for a camera's move). Build from a Vec with `.into()`
pub kids: std::sync::Arc<[Node3]>,
@@ -34,6 +37,8 @@ pub struct Item {
pub kind: &'static str,
pub props: std::sync::Arc<Map<String, Value>>,
pub shape: Option<std::sync::Arc<str>>,
+ /// its Node3's `at`
+ pub at: Option<std::sync::Arc<str>>,
pub material: Option<Node3>,
pub world: Mat4,
}
@@ -87,3 +92,17 @@ pub fn filled(track: &[Option<Item>]) -> Vec<Item> {
last.clone()
}).collect()
}
+
+/// An <Entities>' scene (a world's, already in world space) as the meshes it holds, each with its material.
+pub fn entities_nodes(props: &Map<String, Value>) -> Vec<Node3> {
+ let nodes = props.get("scene").and_then(Value::as_array).into_iter().flatten().filter(|n| n["kind"] == "Mesh");
+ nodes
+ .map(|n| {
+ let mesh = n["mesh"].as_object().cloned().unwrap_or_default();
+ let p: Map<String, Value> = ["position", "rotation", "scale"].iter().map(|k| (k.to_string(), n[*k].clone())).collect();
+ let mat: Map<String, Value> = ["color", "roughness", "metalness"].iter().filter_map(|k| Some((k.to_string(), mesh.get(*k)?.clone()))).collect();
+ let material = Node3 { kind: "MeshStandardMaterial".into(), props: std::sync::Arc::new(mat), shape: None, at: None, kids: Vec::new().into() };
+ Node3 { kind: "Mesh".into(), props: std::sync::Arc::new(p), shape: mesh.get("shape").and_then(Value::as_str).map(Into::into), at: None, kids: std::sync::Arc::new([material]) }
+ })
+ .collect()
+}
diff --git a/engine/web/src/scene.rs b/engine/web/src/scene.rs
index bbd07090..ff130b14 100644
--- a/engine/web/src/scene.rs
+++ b/engine/web/src/scene.rs
@@ -52,6 +52,6 @@ impl Parts {
Some(k) => k.iter().map(|n| self.node(n, seen)).collect::<Result<Vec<_>, _>>()?,
None => Vec::new(),
};
- Ok(Node3 { kind: kind.into(), props, shape, kids: kids.into() })
+ Ok(Node3 { kind: kind.into(), props, shape, at: None, kids: kids.into() })
}
}
diff --git a/runtime/live/tests/live_sheet.rs b/runtime/live/tests/live_sheet.rs
index b0cfa5eb..6ca29fdb 100644
--- a/runtime/live/tests/live_sheet.rs
+++ b/runtime/live/tests/live_sheet.rs
@@ -5,7 +5,7 @@ use raea_runtime_react::scene::{LiveScene, Node3, Shot};
fn plane(src: &str, grid: [u32; 2], frame: u32) -> Vec<Node3> {
let props = serde_json::json!({"name": "film", "src": src, "width": 1, "grid": grid, "frame": frame});
- vec![Node3 { kind: "ImagePlane".into(), props: std::sync::Arc::new(props.as_object().unwrap().clone()), shape: None, kids: Vec::new().into() }]
+ vec![Node3 { kind: "ImagePlane".into(), props: std::sync::Arc::new(props.as_object().unwrap().clone()), shape: None, at: None, kids: Vec::new().into() }]
}
/// Each frame sends the cell, and a swap to a sheet of another grid sends its src and grid, on the fast path as on the
diff --git a/runtime/look/src/active.rs b/runtime/look/src/active.rs
index 93e86202..a7f31519 100644
--- a/runtime/look/src/active.rs
+++ b/runtime/look/src/active.rs
@@ -47,7 +47,7 @@ mod tests {
if let Some(a) = active {
props.insert("active".into(), Value::Bool(a));
}
- Item { kind: "camera", props: std::sync::Arc::new(props), shape: None, material: None, world: bevy::math::Mat4::IDENTITY }
+ Item { kind: "camera", props: std::sync::Arc::new(props), shape: None, material: None, at: None, world: bevy::math::Mat4::IDENTITY }
}
#[test]
diff --git a/runtime/look/src/instances.rs b/runtime/look/src/instances.rs
index 251c467e..5f5001aa 100644
--- a/runtime/look/src/instances.rs
+++ b/runtime/look/src/instances.rs
@@ -23,23 +23,36 @@ fn packed(at: &[Value]) -> Option<String> {
Some(nums.join(" "))
}
+/// An item's placements as its text: its data-at (#84, shared across frames while unchanged), or an `at` prop written
+/// out (a tree from before data-at). Two frames' lists are the same when their texts are.
+fn at_text(it: &Item) -> Option<std::borrow::Cow<'_, str>> {
+ match (&it.at, it.props.get("at")) {
+ (Some(t), _) => Some(std::borrow::Cow::Borrowed(&**t)),
+ (None, Some(a @ Value::Array(_))) => Some(std::borrow::Cow::Owned(a.to_string())),
+ _ => None,
+ }
+}
+
/// The `inst` column of a mesh or model row whose part is an <Instances>: its first frame's placements. When they change
/// over the shot (#85), every list it shows goes in `inst_all` ("|" between lists) and which one each frame shows is keyed
/// as `inst_k`, as a panel's pictures are (src_k): the engine moves its copies to the frame's (scene3d sync_instances).
/// The count is the first frame's: a frame with another count holds the list before it.
pub fn instances_column(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {
- let Some(Value::Array(at)) = its[0].props.get("at") else { return };
- let Some(first) = packed(at) else { return };
- // each frame's list against the one before it only (a frame's list is the frame before's object when React kept it)
- let (mut lists, mut k, mut before, mut recounted) = (vec![first], Vec::with_capacity(its.len()), at, false);
+ let parse = |t: &str| serde_json::from_str::<Vec<Value>>(t).ok();
+ let Some(first_text) = at_text(&its[0]) else { return };
+ let Some(at) = parse(&first_text) else { return };
+ let Some(first) = packed(&at) else { return };
+ // each frame's list against the one before it only, by its text (the same Arc when React kept it): parsed only
+ // when it differs (a frame without one holds the one before)
+ let (mut lists, mut k, mut before, mut recounted) = (vec![first], Vec::with_capacity(its.len()), first_text, false);
for it in its {
- let a = match it.props.get("at") { Some(Value::Array(a)) => a, _ => before };
- if !std::ptr::eq(a, before) && a != before {
- if a.len() == at.len() && let Some(s) = packed(a) {
- lists.push(s);
- before = a;
- } else {
- recounted = true;
+ if let Some(t) = at_text(it).filter(|t| *t != before) {
+ match parse(&t).filter(|a| a.len() == at.len()).and_then(|a| packed(&a)) {
+ Some(s) => {
+ lists.push(s);
+ before = t;
+ }
+ None => recounted = true,
}
}
k.push((lists.len() - 1) as f64);
@@ -71,7 +84,7 @@ mod tests {
fn part(x: f64) -> Item {
let at = serde_json::json!({"at": [x, 0, 0, 0, 0, 0, 1, 1, 1, x + 1.0, 0, 0, 0, 0, 0, 1, 1, 1]});
- Item { kind: "mesh", props: std::sync::Arc::new(at.as_object().unwrap().clone()), shape: None, material: None, world: Default::default() }
+ Item { kind: "mesh", props: std::sync::Arc::new(at.as_object().unwrap().clone()), shape: None, material: None, at: None, world: Default::default() }
}
// #85: a video drew the first frame's placements on every frame
diff --git a/runtime/look/src/parts.rs b/runtime/look/src/parts.rs
index 211333de..10a0af5b 100644
--- a/runtime/look/src/parts.rs
+++ b/runtime/look/src/parts.rs
@@ -148,7 +148,7 @@ mod tests {
/// cells (the grid was the first frame's: 0.1.1's showreel, 11-10).
#[test]
fn a_sheets_grid_is_keyed() {
- let plane = |grid: [u32; 2], frame: u32| Item { kind: "panel", props: std::sync::Arc::new(serde_json::json!({"grid": grid, "frame": frame}).as_object().unwrap().clone()), shape: None, material: None, world: Default::default() };
+ let plane = |grid: [u32; 2], frame: u32| Item { kind: "panel", props: std::sync::Arc::new(serde_json::json!({"grid": grid, "frame": frame}).as_object().unwrap().clone()), shape: None, material: None, at: None, world: Default::default() };
let (mut p, mut row) = (Program::default(), BTreeMap::new());
sheet(&mut p, &mut row, "plane0", &[plane([2, 1], 0), plane([1, 2], 1)]);
let keyed = |c: &str| p.keys.get(&("plane0".to_string(), c.to_string())).map(|k| k.iter().map(|(f, v, _)| (*f, *v)).collect::<Vec<_>>());
diff --git a/runtime/look/src/post.rs b/runtime/look/src/post.rs
index b7123d0c..8308e277 100644
--- a/runtime/look/src/post.rs
+++ b/runtime/look/src/post.rs
@@ -296,7 +296,7 @@ mod tests {
use super::*;
fn item(kind: &'static str, props: Value) -> Item {
- Item { kind, props: std::sync::Arc::new(props.as_object().cloned().unwrap_or_default()), shape: None, material: None, world: Default::default() }
+ Item { kind, props: std::sync::Arc::new(props.as_object().cloned().unwrap_or_default()), shape: None, material: None, at: None, world: Default::default() }
}
#[test]
diff --git a/runtime/look/tests/camera.rs b/runtime/look/tests/camera.rs
index 6e7cf096..ba126a77 100644
--- a/runtime/look/tests/camera.rs
+++ b/runtime/look/tests/camera.rs
@@ -11,7 +11,7 @@ use raea_runtime_look::camera;
use serde_json::json;
fn cam(props: serde_json::Value) -> Item {
- Item { kind: "camera", props: Arc::new(props.as_object().unwrap().clone()), shape: None, material: None, world: Mat4::IDENTITY }
+ Item { kind: "camera", props: Arc::new(props.as_object().unwrap().clone()), shape: None, material: None, at: None, world: Mat4::IDENTITY }
}
#[test]
diff --git a/runtime/react/src/scene.rs b/runtime/react/src/scene.rs
index 124505e6..8fd9a725 100644
--- a/runtime/react/src/scene.rs
+++ b/runtime/react/src/scene.rs
@@ -42,6 +42,8 @@ thread_local! {
static PROPS3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(String, std::sync::Arc<Map<String, Value>>, u64)>> = std::cell::RefCell::new(Default::default());
/// each part's data-3d and data-shape as last read, shared
static NAMES3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(std::sync::Arc<str>, Option<std::sync::Arc<str>>)>> = std::cell::RefCell::new(Default::default());
+ /// each part's data-at (an <Instances>' placements) as last read, shared while its text is the same (issue 84)
+ static AT3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<std::sync::Arc<str>>> = std::cell::RefCell::new(Default::default());
/// scenes read (scene_of): what's in PROPS3D but not read in the last two is let go
static SCENE3D: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
diff --git a/runtime/react/src/scene/holders.rs b/runtime/react/src/scene/holders.rs
index fd8e2b69..17edc6fc 100644
--- a/runtime/react/src/scene/holders.rs
+++ b/runtime/react/src/scene/holders.rs
@@ -7,6 +7,7 @@ pub fn scene_of(world: &mut World) -> Vec<Node3> {
let now = SCENE3D.with(|g| { g.set(g.get() + 1); g.get() });
if now % 120 == 0 {
PROPS3D.with(|c| c.borrow_mut().retain(|_, v| v.2 + 2 >= now));
+ AT3D.with_borrow_mut(|a| PROPS3D.with_borrow(|p| a.retain(|e, _| p.contains_key(e))));
if world.contains_resource::<Kept3d>() {
world.resource_scope(|w, mut k: Mut<Kept3d>| k.of.retain(|e, _| w.get_entity(*e).is_ok()));
}
diff --git a/runtime/react/src/scene/read.rs b/runtime/react/src/scene/read.rs
index 846c9654..0e7e4222 100644
--- a/runtime/react/src/scene/read.rs
+++ b/runtime/react/src/scene/read.rs
@@ -161,25 +161,20 @@ pub(crate) fn read3d(world: &World, e: Entity, kept: &mut Kept3d, dirty: &bevy::
let props = props3d(e, p.0.get("data-props").and_then(|v| v.as_str()));
// a world's entities (<Entities>): its scene, already in world space, as meshes with their materials
if &*kind == "Entities" {
- let kids = props.get("scene").and_then(Value::as_array).into_iter().flatten().filter(|n| n["kind"] == "Mesh").map(|n| {
- let mesh = n["mesh"].as_object().cloned().unwrap_or_default();
- let mut p = Map::new();
- p.insert("position".into(), n["position"].clone());
- p.insert("rotation".into(), n["rotation"].clone());
- p.insert("scale".into(), n["scale"].clone());
- let mut mat = Map::new();
- for k in ["color", "roughness", "metalness"] {
- if let Some(x) = mesh.get(k) {
- mat.insert(k.into(), x.clone());
- }
- }
- Node3 { kind: "Mesh".into(), props: std::sync::Arc::new(p), shape: mesh.get("shape").and_then(Value::as_str).map(Into::into), kids: std::sync::Arc::new([Node3 { kind: "MeshStandardMaterial".into(), props: std::sync::Arc::new(mat), shape: None, kids: Vec::new().into() }]) }
- }).collect::<Vec<_>>();
- return Some(Node3 { kind, props: std::sync::Arc::default(), shape: None, kids: kids.into() });
+ return Some(Node3 { kind, props: std::sync::Arc::default(), shape: None, at: None, kids: raea_core_scene::entities_nodes(&props).into() });
}
let mut kids = Vec::new();
kids3d(world, e, kept, dirty, &mut kids);
- Some(Node3 { kind, props, shape, kids: kids.into() })
+ Some(Node3 { kind, props, shape, at: at3d(e, p.0.get("data-at").and_then(|v| v.as_str())), kids: kids.into() })
+}
+
+/// A part's data-at, the same Arc while its text is the same: kept frames share one list (issue 84)
+fn at3d(e: Entity, text: Option<&str>) -> Option<std::sync::Arc<str>> {
+ let text = text?;
+ AT3D.with_borrow_mut(|c| match c.get(&e) {
+ Some(a) if &**a == text => Some(a.clone()),
+ _ => Some(c.entry(e).insert(text.into()).get().clone()),
+ })
}
/// The 3D children of `e` through plain elements between them (a Sequence's or a component's wrapper div), a kept
diff --git a/runtime/scene/src/fast.rs b/runtime/scene/src/fast.rs
index c9ac9408..44c0c210 100644
--- a/runtime/scene/src/fast.rs
+++ b/runtime/scene/src/fast.rs
@@ -61,9 +61,9 @@ impl LiveScene {
return None;
}
// a panel showing another picture (`current` kept the last): the full path, which sends the new src
- if it.kind == "panel" && self.panel_srcs.get(key.as_str()).map(String::as_str) != it.props.get("src").and_then(Value::as_str) { return None }
+ if it.kind == "panel" && self.panel_srcs.get(key.as_str()).map(|s| &**s) != it.props.get("src").and_then(Value::as_str) { return None }
// an <Instances> placed elsewhere (`current` sent its list): the full path, which sends the new one (#85)
- if self.rows[id].sent.contains_key("inst") && { let mut r = BTreeMap::new(); instances_column(&mut Program::default(), &mut r, id, std::slice::from_ref(it)); r.get("inst") != self.rows[id].sent.get("inst") } { return None }
+ if let Some(at) = &it.at && self.panel_srcs.get(key.as_str()).is_none_or(|s| !std::sync::Arc::ptr_eq(s, at) && s != at) { return None }
parts.push((i, id));
}
}
diff --git a/runtime/scene/src/lib.rs b/runtime/scene/src/lib.rs
index f6f52326..2c76e885 100644
--- a/runtime/scene/src/lib.rs
+++ b/runtime/scene/src/lib.rs
@@ -39,7 +39,7 @@ const BY_PARENT: [(&str, &str); 19] = [("AmbientLight", "ambient"), ("Bloom", "b
("AmbientOcclusion", "ssao"), ("AntiAliasing", "aa"), ("Shadows", "shadows"), ("Look", "framelook"), ("Outline", "outline"), ("Fisheye", "fisheye"), ("LensDistortion", "distortion"), ("MotionBlur", "mblur"), ("BevyResource", "resource")];
fn walk(n: &Node3, parent: Mat4, out: &mut Vec<Item>) {
- let item = |kind: &'static str, world: Mat4, material: Option<Node3>| Item { kind, props: n.props.clone(), shape: n.shape.clone(), material, world };
+ let item = |kind: &'static str, world: Mat4, material: Option<Node3>| Item { kind, props: n.props.clone(), shape: n.shape.clone(), at: n.at.clone(), material, world };
match &*n.kind {
"Group" => {
let w = parent * local(&n.props);
diff --git a/runtime/scene/src/live.rs b/runtime/scene/src/live.rs
index 30777355..c0e6666b 100644
--- a/runtime/scene/src/live.rs
+++ b/runtime/scene/src/live.rs
@@ -25,8 +25,9 @@ pub struct LiveScene {
pub(crate) cam: BTreeMap<String, V>,
/// frame 0 was stepped when play opened (live.rs), and nothing since
pub warm: bool,
- /// identity -> a panel's `src` as written when the full path last made its row (the fast path leaves it a new one)
- pub(crate) panel_srcs: std::collections::HashMap<String, String>,
+ /// 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
pub(crate) light_sig: String,
@@ -148,7 +149,10 @@ impl LiveScene {
let tr = Tracks::of(&all);
rows_into_of(&all, &tr, &mut p);
for (key, src) in tr.panels.iter().filter_map(|(k, t)| Some((k, t[0].as_ref()?.props.get("src")?.as_str()?))) {
- self.panel_srcs.insert(key.clone(), src.to_string());
+ self.panel_srcs.insert(key.clone(), src.into());
+ }
+ for (key, at) in tr.meshes.iter().chain(&tr.models).filter_map(|(k, t)| Some((k, t[0].as_ref()?.at.clone()?))) {
+ self.panel_srcs.insert(key.clone(), at);
}
// each local row (this frame's tracks, numbered as rows_into numbers them) by its identity
let mut local: std::collections::HashMap<String, &String> = std::collections::HashMap::new();
@@ -384,7 +388,7 @@ mod tests {
use serde_json::json;
fn model(props: Value) -> Node3 {
- Node3 { kind: "Model".into(), props: std::sync::Arc::new(props.as_object().unwrap().clone()), shape: None, kids: Vec::new().into() }
+ Node3 { kind: "Model".into(), props: std::sync::Arc::new(props.as_object().unwrap().clone()), shape: None, at: None, kids: Vec::new().into() }
}
fn person(who: &str) -> Vec<Node3> {
@@ -408,7 +412,7 @@ mod tests {
/// A glyph faded in (`reveal`: 0, 0.5, 1) is opaque once done, not left at its last fade (#38: bevy/text3d's tag).
#[test]
fn a_faded_glyph_is_opaque_once_done() {
- let text = |o: f64| vec![Node3 { kind: "RichText".into(), props: std::sync::Arc::new(json!({"spans": [{"t": "a"}], "glyphs": [{"at": 0, "span": 0, "ch": "a", "o": o}]}).as_object().unwrap().clone()), shape: None, kids: Vec::new().into() }];
+ let text = |o: f64| vec![Node3 { kind: "RichText".into(), props: std::sync::Arc::new(json!({"spans": [{"t": "a"}], "glyphs": [{"at": 0, "span": 0, "ch": "a", "o": o}]}).as_object().unwrap().clone()), shape: None, at: None, kids: Vec::new().into() }];
let mut ls = LiveScene::default();
ls.open(Shot { scene: &text(0.5), clear: None }, 64, 64, 30.0);
let (set, _) = ls.frame(Shot { scene: &text(1.0), clear: None });
@@ -419,7 +423,7 @@ mod tests {
/// the first camera is back, so a live engine draws both frames as cuts (RR2, Engine::set_rows).
#[test]
fn a_cut_back_sends_the_first_shot() {
- let cams = |on: usize| -> Vec<Node3> { (0..2).map(|i| Node3 { kind: "PerspectiveCamera".into(), props: std::sync::Arc::new(json!({"position": [i, 1, 5], "active": i == on}).as_object().unwrap().clone()), shape: None, kids: Vec::new().into() }).collect() };
+ let cams = |on: usize| -> Vec<Node3> { (0..2).map(|i| Node3 { kind: "PerspectiveCamera".into(), props: std::sync::Arc::new(json!({"position": [i, 1, 5], "active": i == on}).as_object().unwrap().clone()), shape: None, at: None, kids: Vec::new().into() }).collect() };
let shot = |set: &[raea_core_program::eval::Tup]| set.iter().find(|t| t.kind == "camera").and_then(|t| t.vals.get("shot").cloned());
let mut ls = LiveScene::default();
ls.open(Shot { scene: &cams(0), clear: None }, 64, 64, 30.0);
diff --git a/runtime/scene/src/parts.rs b/runtime/scene/src/parts.rs
index 2d513831..b4cb63f7 100644
--- a/runtime/scene/src/parts.rs
+++ b/runtime/scene/src/parts.rs
@@ -358,7 +358,7 @@ pub(crate) fn texts_rows(tr: &Tracks, names: &[String], p: &mut Program) {
m.insert(to.into(), v.clone());
}
}
- Item { kind: "glyph", props: std::sync::Arc::new(Map::new()), shape: None, material: None, world: local(&m) }
+ Item { kind: "glyph", props: std::sync::Arc::new(Map::new()), shape: None, material: None, at: None, world: local(&m) }
}).collect();
placement(p, &mut row, &gid, &moved);
let colors: Vec<String> = gs.iter().map(|g| hex(g.get("c")).unwrap_or("#ffffff".into())).collect();
@@ -397,7 +397,7 @@ mod light_rotation_tests {
use super::*;
fn sun(props: serde_json::Value, world: Mat4) -> Item {
- Item { kind: "directional", props: std::sync::Arc::new(props.as_object().unwrap().clone()), shape: None, material: None, world }
+ Item { kind: "directional", props: std::sync::Arc::new(props.as_object().unwrap().clone()), shape: None, material: None, at: None, world }
}
#[test]
diff --git a/runtime/world/src/scene.rs b/runtime/world/src/scene.rs
index 8af7c45b..80ca5d05 100644
--- a/runtime/world/src/scene.rs
+++ b/runtime/world/src/scene.rs
@@ -133,7 +133,7 @@ mod tests {
use std::sync::Arc;
fn item(kind: &'static str, props: Value, shape: Option<&str>, world: Mat4) -> Item {
- Item { kind, props: Arc::new(props.as_object().cloned().unwrap_or_default()), shape: shape.map(Arc::from), material: None, world }
+ Item { kind, props: Arc::new(props.as_object().cloned().unwrap_or_default()), shape: shape.map(Arc::from), material: None, at: None, world }
}
#[test]
diff --git a/sdk/raea/conformance/instances.test.tsx b/sdk/raea/conformance/instances.test.tsx
index 4ae8f07c..ea4c56b7 100644
--- a/sdk/raea/conformance/instances.test.tsx
+++ b/sdk/raea/conformance/instances.test.tsx
@@ -11,6 +11,12 @@ const props = (h: string, kind: string) => {
if (!m) throw new Error(`no ${kind} in ${h.slice(0, 300)}`);
return JSON.parse(m[1].replace(/&quot;/g, '"').replace(/&amp;/g, "&"));
};
+// the placements: their own attribute, not data-props, so the engine shares one list across frames (#84)
+const placed = (h: string, kind: string) => {
+ const m = h.match(new RegExp(`data-3d="${kind}"[^>]*data-at="([^"]*)"`));
+ if (!m) throw new Error(`no ${kind} data-at in ${h.slice(0, 300)}`);
+ return JSON.parse(m[1].replace(/&quot;/g, '"').replace(/&amp;/g, "&"));
+};
describe("Instances", () => {
test("the mesh form: a Mesh node with its shape and the placements, 9 numbers a copy", () => {
@@ -18,13 +24,14 @@ describe("Instances", () => {
const h = html(<Instances at={at} shadow={false}><Cuboid args={[1, 1, 1]} /><MeshStandardMaterial color="#336633" /></Instances>);
expect(h).toContain('data-shape="');
const p = props(h, "Mesh");
- expect(p.at).toEqual([1, 0, 2, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1.5, 0, 2, 2, 2]);
+ expect(placed(h, "Mesh")).toEqual([1, 0, 2, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1.5, 0, 2, 2, 2]);
+ expect(p.at).toBeUndefined();
expect(p.shadow).toBe(false);
});
test("the glTF form: a Model node", () => {
- const p = props(html(<Instances src="daisy.glb" at={[{ position: [0, 0, 0] }]} />), "Model");
- expect(p.src).toBe("daisy.glb");
- expect(p.at).toHaveLength(9);
+ const h = html(<Instances src="daisy.glb" at={[{ position: [0, 0, 0] }]} />);
+ expect(props(h, "Model").src).toBe("daisy.glb");
+ expect(placed(h, "Model")).toHaveLength(9);
});
test("a buffer mesh is a shape", () => {
const h = html(<Instances at={[{ position: [0, 0, 0] }]}><BufferMesh positions={[0, 0, 0, 1, 0, 0, 0, 1, 0]} /><MeshStandardMaterial /></Instances>);
@@ -32,8 +39,8 @@ describe("Instances", () => {
});
test("the same list is packed once", () => {
const at = scatter({ area: { min: [0, 0], max: [4, 4] }, count: 50 });
- const a = props(html(<Instances src="a.glb" at={at} />), "Model").at;
- const b = props(html(<Instances src="a.glb" at={at} />), "Model").at;
+ const a = placed(html(<Instances src="a.glb" at={at} />), "Model");
+ const b = placed(html(<Instances src="a.glb" at={at} />), "Model");
expect(a).toEqual(b);
});
test("errors say what's wrong", () => {
diff --git a/sdk/render/src/3d/instances.tsx b/sdk/render/src/3d/instances.tsx
index 4e9e7f60..2ec522b9 100644
--- a/sdk/render/src/3d/instances.tsx
+++ b/sdk/render/src/3d/instances.tsx
@@ -87,13 +87,16 @@ export function Instances(props: InstancesProps) {
checkPass(owner, props.pass);
const at = packInstances(owner, props.at);
const { position = [0, 0, 0], rotation = [0, 0, 0], scale = 1 } = props;
- if (props.src !== undefined) return node3d("Model", { ...props, shape: undefined, at, position, rotation, scale }, props.children);
+ // the placements in an attribute of their own, not data-props: the engine shares one list across frames while its text
+ // is the same, where a set whose other props change was parsed whole into each frame's props (#84)
+ const placed = { "data-at": JSON.stringify(at) };
+ if (props.src !== undefined) return node3d("Model", { ...props, shape: undefined, at: undefined, position, rotation, scale }, props.children, placed);
const manifold = props.shape instanceof Solid ? props.shape.expr : props.shape ?? shapeFromChildren(props.children);
if (manifold === undefined) throw new TypeError("Instances: give a glTF `src`, or a geometry child (<Cuboid />, <BufferMesh />, ...) or `shape`");
let toon = false;
Children.forEach(props.children, (c) => { if (isValidElement(c) && c.type === MeshToonMaterial) toon = true; });
if (toon) throw new TypeError("Instances: the copies take a MeshStandardMaterial, MeshPhysicalMaterial or MeshBasicMaterial (a toon surface isn't instanced)");
- return node3d("Mesh", { ...props, shape: undefined, at, position, rotation, scale }, props.children, { "data-shape": manifold as string });
+ return node3d("Mesh", { ...props, shape: undefined, at: undefined, position, rotation, scale }, props.children, { ...placed, "data-shape": manifold as string });
}
/** A box on the plan (x, z, metres): the room SDK's Footprint, or any { min, max }. */
diff --git a/systems/contact/src/assets.rs b/systems/contact/src/assets.rs
index 020e0fe1..d32f899a 100644
--- a/systems/contact/src/assets.rs
+++ b/systems/contact/src/assets.rs
@@ -58,7 +58,7 @@ mod tests {
fn item(kind: &'static str, props: serde_json::Value) -> Item {
let Some(m) = props.as_object().cloned() else { unreachable!() };
- Item { kind, props: Arc::new(m), shape: None, material: None, world: Mat4::IDENTITY }
+ Item { kind, props: Arc::new(m), shape: None, material: None, at: None, world: Mat4::IDENTITY }
}
#[test]