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.

stage: hold a part, say where it stands, wireframe (docs/scene-feed.feature SF4c, SF4d, SF3e)

shinyobjectze60a8bc5fe68
diff --git a/engine/page/stage/src/calls.rs b/engine/page/stage/src/calls.rs
index 30983e8e..f7b8119f 100644
--- a/engine/page/stage/src/calls.rs
+++ b/engine/page/stage/src/calls.rs
@@ -86,6 +86,42 @@ pub(super) fn calls(mut calls: ResMut<HostCalls>) {
None => answer.err("the stage shows nothing"),
}
})
+ .on("stage.part", move |w, a, answer| {
+ let key = a.get("key").and_then(Value::as_str).unwrap_or_default().to_string();
+ let tx = w.resource::<Stage>().tx.lock().unwrap().clone();
+ match tx {
+ Some(tx) => {
+ let _ = tx.send(Cmd::Part(key, answer));
+ }
+ None => answer.ok(Value::Null),
+ }
+ })
+ .on("stage.hold", move |w, a, answer| {
+ let key = a.get("key").and_then(Value::as_str).unwrap_or_default().to_string();
+ let list = |k: &str, n: usize| a.get(k).and_then(Value::as_array).map(|v| v.iter().filter_map(Value::as_f64).map(|x| x as f32).collect::<Vec<_>>()).filter(|v| v.len() == n && v.iter().all(|x| x.is_finite()));
+ let to = match (a.get("release").and_then(Value::as_bool), list("translation", 3), list("rotation", 4), list("scale", 3)) {
+ (Some(true), ..) => None,
+ (_, Some(t), Some(r), Some(s)) => Some(([t[0], t[1], t[2]], [r[0], r[1], r[2], r[3]], [s[0], s[1], s[2]])),
+ _ => return answer.err("stage.hold takes a key with translation [x, y, z], rotation [x, y, z, w] and scale [x, y, z], or release: true"),
+ };
+ let tx = w.resource::<Stage>().tx.lock().unwrap().clone();
+ match tx {
+ Some(tx) => {
+ let _ = tx.send(Cmd::Hold(key, to, answer));
+ }
+ None => answer.ok(json!(false)),
+ }
+ })
+ .on("stage.wire", move |w, a, answer| {
+ let on = a.get("on").and_then(Value::as_bool).unwrap_or(true);
+ let tx = w.resource::<Stage>().tx.lock().unwrap().clone();
+ match tx {
+ Some(tx) => {
+ let _ = tx.send(Cmd::Wire(on, answer));
+ }
+ None => answer.ok(json!(false)),
+ }
+ })
.on("stage.inspect", move |w, a, answer| {
let id = a.get("id").and_then(Value::as_u64).unwrap_or(0);
let tx = w.resource::<Stage>().tx.lock().unwrap().clone();
diff --git a/engine/page/stage/src/lib.rs b/engine/page/stage/src/lib.rs
index 21022e75..31c1d4f9 100644
--- a/engine/page/stage/src/lib.rs
+++ b/engine/page/stage/src/lib.rs
@@ -24,6 +24,13 @@
//! note's pin follow what they are on)
//! stage.props {props} the composition's props set over its defaults as it plays (PV4b): the frame it is on is
//! drawn again with them; nothing is reopened or written
+//! stage.part {key} the part that key names as it stands now ({entity_key, placed}), or null
+//! (docs/scene-feed.feature SF4c); a pick's part carries the same `placed`: {local,
+//! world: {translation, rotation [x, y, z, w], scale}, parent: 16 numbers | null}
+//! stage.hold {key, translation, rotation, scale} | {key, release: true}
+//! that part drawn at a place in its parent's space until it is let go of: a drag
+//! as it looks while it is dragged; nothing is written
+//! stage.wire {on} every mesh drawn as its edges over its shading (SF3e); answers whether it can
//! stage.inspect {id} that element as it is now (its owner, kind, box, props, text), or null once it's gone
//! stage.tweak {changes} [{owner, kind, prop, value}]: the props written into the composition as its next
//! version (raea-sys-tweak), which the stage then shows at the same frame, its input replayed
@@ -69,6 +76,12 @@ enum Cmd {
Locate(Vec<String>, Vec<[f32; 3]>, Answer),
/// props over the composition's defaults, from now
Props(Value, Answer),
+ /// a part by its key, as it stands now
+ Part(String, Answer),
+ /// a part held at a place in its parent's space (None: let go of)
+ Hold(String, Option<([f32; 3], [f32; 4], [f32; 3])>, Answer),
+ /// the scene as wireframe, or as it is
+ Wire(bool, Answer),
/// an element as it is now, by id
Inspect(u64, Answer),
/// props written into the next version, which then plays from the same frame
@@ -144,6 +157,8 @@ impl Plugin for StagePlugin {
// SAFETY: the app is being built on its main thread; the stage's thread starts at the first show
unsafe { std::env::set_var("RAEA_SOURCE_STAMPS", "1") };
}
+ // the stage's scenes can be drawn as wireframe (docs/scene-feed.feature SF3e): asked for before any opens
+ raea_runtime_live::want_wire();
app.insert_resource(stage)
.init_resource::<HostCalls>()
.add_plugins(ExtractResourcePlugin::<Stage>::default())
@@ -214,6 +229,8 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
};
// paused: the frames asked for and not yet stepped (at most 4 a turn, as playing)
let mut steps = 0i64;
+ // the scene shown as wireframe (stage.wire), and a file just opened that hasn't taken it yet
+ let (mut wire, mut rewire) = (false, false);
// RAEA_STAGE_TRACE=1: each frame stepped and its keys, on stderr
let trace = std::env::var("RAEA_STAGE_TRACE").as_deref() == Ok("1");
// the stage's size, which the page's points are in
@@ -256,6 +273,7 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
Ok(l) => {
status.lock().unwrap().fps = l.fps;
live = Some(l);
+ rewire = wire;
}
Err(e) => set_error(e),
}
@@ -328,6 +346,18 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
}
None => answer.ok(Value::Null),
},
+ Some(Cmd::Part(key, answer)) => answer.ok(live.as_mut().and_then(|l| l.part(&key)).unwrap_or(Value::Null)),
+ Some(Cmd::Hold(key, to, answer)) => {
+ let held = live.as_mut().is_some_and(|l| l.hold(&key, to));
+ repaint |= held;
+ answer.ok(json!(held));
+ }
+ Some(Cmd::Wire(on, answer)) => {
+ wire = on;
+ let can = live.as_mut().is_some_and(|l| l.wire(on));
+ repaint |= can;
+ answer.ok(json!(can));
+ }
Some(Cmd::Inspect(id, answer)) => match live.as_mut() {
Some(l) => answer.ok(l.element(id).map(|e| on_stage(e, l, stage)).unwrap_or(Value::Null)),
None => answer.ok(Value::Null),
@@ -352,6 +382,12 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
None => {}
}
let Some(l) = live.as_mut() else { continue };
+ // a file opened again while the scene was shown as wireframe: its 3D is made on a thread, so it is asked each
+ // turn until it is there to take it
+ if rewire && l.wire(true) {
+ rewire = false;
+ repaint = true;
+ }
let due = if playing { base + (since.elapsed().as_secs_f64() * l.fps) as i64 } else { frame + steps };
let mut stepped = 0;
while frame < due && stepped < 4 {
diff --git a/engine/render/src/engine/open.rs b/engine/render/src/engine/open.rs
index 14cf203d..8b38156b 100644
--- a/engine/render/src/engine/open.rs
+++ b/engine/render/src/engine/open.rs
@@ -189,6 +189,10 @@ impl Engine {
let backend = raea_io_media::backend(&media_backend())?;
app.insert_non_send(Media { backend, decoders: HashMap::new(), dir: dir.to_path_buf() });
}
+ // the app's stage can draw a scene as wireframe (docs/scene-feed.feature SF3e): only where it asked
+ if live {
+ raea_sys_frame::hold::add_wire(&mut app);
+ }
mem_mark("engine: plugins built (DefaultPlugins, the render device)");
Ok(Opening { app, prog: prog.clone(), inserted: inserted.to_vec(), dir: dir.to_path_buf(), timeline, live })
}
@@ -223,6 +227,8 @@ impl Engine {
app.insert_resource(TagRowTarget(target.clone())).init_resource::<ViewBox>().add_systems(PostUpdate, tag_row_view.before(bevy::camera::CameraUpdateSystems));
// a free camera over the scene (docs/preview.feature PV1c): off until a preview asks for one
app.init_resource::<raea_sys_frame::view::FreeView>().add_systems(PostUpdate, raea_sys_frame::view::apply.before(bevy::transform::TransformSystems::Propagate));
+ // a part held where a hand has it (docs/scene-feed.feature SF4c): nothing until an inspector holds one
+ app.init_resource::<raea_sys_frame::hold::Held>().add_systems(PostUpdate, raea_sys_frame::hold::apply.before(bevy::transform::TransformSystems::Propagate));
// without native nothing ever comes back (frames are read back only to be encoded or analysed)
let nv12 = !STILLS_RGBA.load(std::sync::atomic::Ordering::Relaxed) && std::env::var("RAEA_READBACK").map(|v| v != "rgba").unwrap_or(true);
// stills through the GPU composite: its RGBA words and the tag word, unpadded
diff --git a/runtime/live/src/lib.rs b/runtime/live/src/lib.rs
index 4d691e79..70cf264b 100644
--- a/runtime/live/src/lib.rs
+++ b/runtime/live/src/lib.rs
@@ -16,6 +16,7 @@ mod open;
mod sound;
mod pointer;
mod pick3d;
+pub use pick3d::want_wire;
pub use sound::warm_audio;
mod draw;
diff --git a/runtime/live/src/pick3d.rs b/runtime/live/src/pick3d.rs
index 869ff47f..8d7125e1 100644
--- a/runtime/live/src/pick3d.rs
+++ b/runtime/live/src/pick3d.rs
@@ -34,6 +34,10 @@ impl Live {
None => json!({"owner": "", "props": {}, "text": "", "kind": "mesh"}),
};
out["entity"] = json!(hit.entity.to_bits());
+ // where it stands (docs/scene-feed.feature SF4c): what its handles are drawn from
+ if let Some(w) = self.scene.as_mut().map(|e| e.world_mut()) {
+ out["placed"] = placed_json(raea_sys_frame::hold::placed(w, hit.entity));
+ }
// how a part with no key is asked for again (locate): its entity, as text (its bits don't fit a page's number)
out["entity_key"] = json!(format!("entity:{}", hit.entity.to_bits()));
for (k, v) in [("part", json!(true)), ("key", json!(hit.key)), ("name", json!(hit.name)), ("rect", json!([r[0] as f64 * w, r[1] as f64 * h, r[2] as f64 * w, r[3] as f64 * h])), ("point", json!(hit.point.to_array())), ("distance", json!(hit.distance))] {
@@ -79,6 +83,40 @@ impl Live {
}
}
+ /// The part a key names, as it stands now: its entity (as "entity:BITS") and where it stands. None when nothing
+ /// drawn has that key. A picked part asked for again after the scene's code changed (a new world, new entities).
+ pub fn part(&mut self, key: &str) -> Option<Value> {
+ let w = self.scene.as_mut()?.world_mut();
+ let e = raea_sys_frame::hold::part_of(w, key)?;
+ Some(json!({"entity_key": format!("entity:{}", e.to_bits()), "placed": placed_json(raea_sys_frame::hold::placed(w, e))}))
+ }
+
+ /// The part a key names held at a place in its parent's space (translation, rotation as a quaternion, scale), or
+ /// let go of (None): drawn there until then, its code untouched. False with no 3D or no such part.
+ pub fn hold(&mut self, key: &str, to: Option<([f32; 3], [f32; 4], [f32; 3])>) -> bool {
+ let Some(w) = self.scene.as_mut().map(|e| e.world_mut()) else { return false };
+ let Some(e) = raea_sys_frame::hold::part_of(w, key) else { return false };
+ let Some(mut held) = w.get_resource_mut::<raea_sys_frame::hold::Held>() else { return false };
+ match to {
+ Some((t, r, s)) => {
+ held.parts.insert(e, Transform { translation: Vec3::from(t), rotation: Quat::from_array(r).normalize(), scale: Vec3::from(s) });
+ }
+ None => {
+ held.parts.remove(&e);
+ }
+ }
+ self.dirty = true;
+ true
+ }
+
+ /// Every mesh drawn as its edges over its shading, or as it is. False with no 3D or no wireframe pass.
+ pub fn wire(&mut self, on: bool) -> bool {
+ let Some(w) = self.scene.as_mut().map(|e| e.world_mut()) else { return false };
+ let ok = raea_sys_frame::hold::set_wire(w, on);
+ self.dirty |= ok;
+ ok
+ }
+
/// The scene drawn from an orbit (yaw and pitch in radians, distance in metres, about `target`) until None puts
/// the composition's camera back. False with no 3D.
pub fn set_view(&mut self, orbit: Option<(f32, f32, f32, [f32; 3])>) -> bool {
@@ -131,3 +169,19 @@ impl Live {
})
}
}
+
+/// Where a part stands, for the page: its place in its parent's space and in the world (translation, rotation as a
+/// quaternion [x, y, z, w], scale), and its parent's matrix in the world (16 numbers, column by column; null at the top).
+fn placed_json(p: raea_sys_frame::hold::Placed) -> Value {
+ let trs = |t: Transform| json!({"translation": t.translation.to_array(), "rotation": t.rotation.to_array(), "scale": t.scale.to_array()});
+ json!({
+ "local": trs(p.local),
+ "world": trs(p.world.compute_transform()),
+ "parent": p.parent.map(|g| Mat4::from(g.affine()).to_cols_array().to_vec()),
+ })
+}
+
+/// Scenes opened from here on can be drawn as wireframe (`Live::wire`): the app's stage asks once, before any opens.
+pub fn want_wire() {
+ raea_sys_frame::hold::want_wire();
+}
diff --git a/systems/frame/src/hold.rs b/systems/frame/src/hold.rs
new file mode 100644
index 00000000..6c587c53
--- /dev/null
+++ b/systems/frame/src/hold.rs
@@ -0,0 +1,136 @@
+//! A part held where a hand has it, and the scene drawn as wireframe (docs/scene-feed.feature SF4c, SF3e): while
+//! `Held` names a part, its Transform is put where the hold says after the composition's rows have placed it and
+//! before transforms propagate, so the frame draws the part (and all under it) there. Let go, it goes back to where
+//! the composition last put it. Nothing in the composition's rows changes: a hold is how a drag looks while it is
+//! dragged, and the release writes the scene's code. The same shape as the free camera (view.rs).
+
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+use bevy::prelude::*;
+
+use crate::layer::LayerKey;
+
+/// The parts held and where; and what the hold last wrote and what the composition had put there, to tell the
+/// composition's own moves from the hold's and to put each part back.
+#[derive(Resource, Default)]
+pub struct Held {
+ pub parts: HashMap<Entity, Transform>,
+ wrote: HashMap<Entity, Transform>,
+ own: HashMap<Entity, Transform>,
+}
+
+/// PostUpdate, before transforms propagate.
+pub fn apply(mut held: ResMut<Held>, mut places: Query<&mut Transform>) {
+ let Held { parts, wrote, own } = &mut *held;
+ // let go of: back where the composition had it
+ let gone: Vec<Entity> = wrote.keys().filter(|e| !parts.contains_key(*e)).copied().collect();
+ for e in gone {
+ wrote.remove(&e);
+ if let (Some(o), Ok(mut t)) = (own.remove(&e), places.get_mut(e)) {
+ *t = o;
+ }
+ }
+ for (e, to) in parts.iter() {
+ let Ok(mut t) = places.get_mut(*e) else { continue };
+ // a transform that isn't what the hold wrote is the composition's own, placed since
+ if wrote.get(e) != Some(&*t) {
+ own.insert(*e, *t);
+ }
+ if *t != *to {
+ *t = *to;
+ }
+ wrote.insert(*e, *to);
+ }
+}
+
+/// The part a key names: its LayerKey, or a part with none by its entity ("entity:BITS", as a pick names it).
+pub fn part_of(world: &mut World, key: &str) -> Option<Entity> {
+ if let Some(bits) = key.strip_prefix("entity:").and_then(|b| b.parse::<u64>().ok()) {
+ let mut all = world.query::<Entity>();
+ return all.iter(world).find(|e| e.to_bits() == bits);
+ }
+ let mut keyed = world.query::<(Entity, &LayerKey)>();
+ keyed.iter(world).find(|(_, k)| k.0 == key).map(|(e, _)| e)
+}
+
+/// Where a part stands: in its parent's space, in the world, and its parent in the world (None at the top). What a
+/// handle is drawn from and a drag is turned into the part's own numbers with.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Placed {
+ pub local: Transform,
+ pub world: GlobalTransform,
+ pub parent: Option<GlobalTransform>,
+}
+
+pub fn placed(world: &World, e: Entity) -> Placed {
+ Placed {
+ // as the composition has it, not as a hold has moved it
+ local: world.get_resource::<Held>().and_then(|h| h.own.get(&e).copied()).or_else(|| world.get::<Transform>(e).copied()).unwrap_or_default(),
+ world: world.get::<GlobalTransform>(e).copied().unwrap_or_default(),
+ parent: world.get::<ChildOf>(e).and_then(|p| world.get::<GlobalTransform>(p.parent()).copied()),
+ }
+}
+
+static WIRE: AtomicBool = AtomicBool::new(false);
+
+/// Engines opened from here on can draw as wireframe (the app's stage asks; a render never does: Bevy's wireframe
+/// pass is one more pass in every frame's graph).
+pub fn want_wire() {
+ WIRE.store(true, Ordering::Relaxed);
+}
+
+/// Bevy's wireframe pass added to an engine being built, when asked for (`want_wire`): off until `set_wire`.
+pub fn add_wire(app: &mut App) {
+ if WIRE.load(Ordering::Relaxed) && !app.is_plugin_added::<bevy::pbr::wireframe::WireframePlugin>() {
+ app.add_plugins(bevy::pbr::wireframe::WireframePlugin::default());
+ }
+}
+
+/// Every mesh drawn as its edges over its shading (on), or as it is (off). False where the engine has no wireframe
+/// pass (it wasn't asked for, or the GPU can't draw lines).
+pub fn set_wire(world: &mut World, on: bool) -> bool {
+ let Some(mut c) = world.get_resource_mut::<bevy::pbr::wireframe::WireframeConfig>() else { return false };
+ if c.global != on {
+ c.global = on;
+ }
+ true
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_hold_places_the_part_and_letting_go_gives_it_back() {
+ let mut app = App::new();
+ app.init_resource::<Held>().add_systems(PostUpdate, apply);
+ let own = Transform::from_xyz(1.0, 0.0, 0.0);
+ let part = app.world_mut().spawn(own).id();
+ app.update();
+ let to = Transform::from_xyz(3.0, 2.0, 0.0);
+ app.world_mut().resource_mut::<Held>().parts.insert(part, to);
+ app.update();
+ assert_eq!(*app.world().get::<Transform>(part).unwrap(), to);
+ // where it stands in its code is still what a reader is told
+ assert_eq!(placed(app.world(), part).local, own);
+ // the composition moves it meanwhile: the hold stands, and that is where it goes back to
+ let moved = Transform::from_xyz(5.0, 0.0, 0.0);
+ *app.world_mut().get_mut::<Transform>(part).unwrap() = moved;
+ app.update();
+ assert_eq!(*app.world().get::<Transform>(part).unwrap(), to);
+ app.world_mut().resource_mut::<Held>().parts.clear();
+ app.update();
+ assert_eq!(*app.world().get::<Transform>(part).unwrap(), moved);
+ }
+
+ #[test]
+ fn a_part_is_found_by_its_key_or_its_entity() {
+ let mut world = World::new();
+ let keyed = world.spawn(LayerKey("room.tsx:4:7".into())).id();
+ let bare = world.spawn_empty().id();
+ assert_eq!(part_of(&mut world, "room.tsx:4:7"), Some(keyed));
+ assert_eq!(part_of(&mut world, &format!("entity:{}", bare.to_bits())), Some(bare));
+ assert_eq!(part_of(&mut world, "room.tsx:9:9"), None);
+ }
+}
diff --git a/systems/frame/src/lib.rs b/systems/frame/src/lib.rs
index a8b00455..c2fc81dd 100644
--- a/systems/frame/src/lib.rs
+++ b/systems/frame/src/lib.rs
@@ -22,6 +22,8 @@ pub mod pick;
pub mod shadow;
/// a free camera over the scene (docs/preview.feature PV1c)
pub mod view;
+/// a part held where a hand has it, and the scene as wireframe (docs/scene-feed.feature SF4c, SF3e)
+pub mod hold;
/// pipelined updates: the render world drawing the last frame while the main world runs this one
pub mod pipe;
// the edit's rows as entities, each column a component of its own, found by kind and id