From e58ed228a4d728bc63f9dfcb63fcbee2dcfefbcf Mon Sep 17 00:00:00 2001 From: shinyobjectz Date: Mon, 9 Nov 2026 20:15:02 -0800 Subject: [PATCH] PV4d: stage.locate says where parts and world points are on the stage now A selection's box and a note's pin follow what they are on as the camera turns, a prop moves or the frame plays (systems/frame pick.rs locate: a part's meshes' bounds and each point through the frame's camera). The stage's host calls move to calls.rs (lib.rs was past 500 lines); the bundle's raea-props lines are two shorter (its crate was at 2002). --- engine/page/stage/src/calls.rs | 114 +++++++++++++++++++++++++++++++ engine/page/stage/src/lib.rs | 120 +++++++-------------------------- runtime/bundle/src/entry.rs | 4 +- runtime/live/src/pick3d.rs | 14 ++++ systems/frame/src/pick.rs | 34 ++++++++++ 5 files changed, 187 insertions(+), 99 deletions(-) create mode 100644 engine/page/stage/src/calls.rs diff --git a/engine/page/stage/src/calls.rs b/engine/page/stage/src/calls.rs new file mode 100644 index 00000000..04c4c6a7 --- /dev/null +++ b/engine/page/stage/src/calls.rs @@ -0,0 +1,114 @@ +//! The page's host calls for the stage (lib.rs lists them): each read from its arguments and sent to the stage's +//! thread, which answers the ones that ask something of the composition. + +use super::*; + +pub(super) fn settle(answer: raea_runtime_js::calls::Answer, r: Result) { + match r { + Ok(v) => answer.ok(v), + Err(e) => answer.err(e), + } +} + +/// The page's host calls (the module's list). +pub(super) fn calls(mut calls: ResMut) { + let num = |a: &Value, k: &str| a.get(k).and_then(Value::as_f64); + let send = |w: &mut World, c: Cmd| w.resource::().send(c).map(|_| Value::Null); + calls + .on("stage.show", move |w, a, answer| { + if !raea_gpu_device::enabled() { + return answer.err("the stage needs the shared device (RAEA_SHARED_DEVICE=0 turned it off)"); + } + // a feed item names its game as the app's host does (host/make.ts resolve): ~/ is the home + let src = a.get("src").and_then(Value::as_str).map(|s| match (s.strip_prefix("~/"), std::env::var_os("HOME")) { + (Some(rest), Some(home)) => PathBuf::from(home).join(rest), + _ => PathBuf::from(s), + }); + let size = (num(&a, "w").unwrap_or(1280.0).round().max(1.0) as u32, num(&a, "h").unwrap_or(720.0).round().max(1.0) as u32); + settle(answer, send(w, Cmd::Show(src, size))); + }) + .on("stage.play", move |w, a, answer| settle(answer, send(w, Cmd::Play(a.get("on").and_then(Value::as_bool).unwrap_or(true))))) + .on("stage.step", move |w, a, answer| settle(answer, send(w, Cmd::Step(num(&a, "n").unwrap_or(1.0).max(0.0) as i64)))) + .on("stage.seek", move |w, a, answer| settle(answer, send(w, Cmd::Seek(num(&a, "frame").unwrap_or(0.0).max(0.0).round() as i64)))) + .on("stage.key", move |w, a, answer| { + let key = a.get("key").and_then(Value::as_str).unwrap_or_default().to_string(); + settle(answer, send(w, Cmd::Key(key, a.get("down").and_then(Value::as_bool).unwrap_or(true)))); + }) + .on("stage.pointer", move |w, a, answer| { + settle(answer, send(w, Cmd::Pointer(num(&a, "x").unwrap_or(0.0), num(&a, "y").unwrap_or(0.0), a.get("down").and_then(Value::as_bool).unwrap_or(false)))); + }) + .on("stage.pick", move |w, a, answer| { + let (x, y) = (num(&a, "x").unwrap_or(0.0), num(&a, "y").unwrap_or(0.0)); + let tx = w.resource::().tx.lock().unwrap().clone(); + match tx { + Some(tx) => { + let _ = tx.send(Cmd::Pick(x, y, answer)); + } + None => answer.ok(Value::Null), + } + }) + .on("stage.view", move |w, a, answer| { + let f = |k: &str| a.get(k).and_then(Value::as_f64).map(|v| v as f32); + let target = a.get("target").and_then(Value::as_array).map(|t| t.iter().filter_map(Value::as_f64).map(|v| v as f32).collect::>()).filter(|t| t.len() == 3); + let set = match (a.get("free").and_then(Value::as_bool), f("yaw"), f("pitch"), f("distance")) { + (Some(false), ..) => Some(None), + (_, Some(yaw), Some(pitch), Some(distance)) => Some(Some((yaw, pitch, distance, target.map_or([0.0; 3], |t| [t[0], t[1], t[2]])))), + _ => None, + }; + let tx = w.resource::().tx.lock().unwrap().clone(); + match tx { + Some(tx) => { + let _ = tx.send(Cmd::View(set, answer)); + } + None => answer.ok(Value::Null), + } + }) + .on("stage.locate", move |w, a, answer| { + let keys: Vec = a.get("keys").and_then(Value::as_array).into_iter().flatten().filter_map(|k| k.as_str().map(str::to_string)).collect(); + let points: Vec<[f32; 3]> = a.get("points").and_then(Value::as_array).into_iter().flatten().filter_map(|p| { + let p: Vec = p.as_array()?.iter().filter_map(Value::as_f64).map(|v| v as f32).collect(); + (p.len() == 3).then(|| [p[0], p[1], p[2]]) + }).collect(); + let tx = w.resource::().tx.lock().unwrap().clone(); + match tx { + Some(tx) => { + let _ = tx.send(Cmd::Locate(keys, points, answer)); + } + None => answer.ok(Value::Null), + } + }) + .on("stage.props", move |w, a, answer| { + let tx = w.resource::().tx.lock().unwrap().clone(); + match tx { + Some(tx) => { + let _ = tx.send(Cmd::Props(a.get("props").cloned().unwrap_or(Value::Null), answer)); + } + None => answer.err("the stage shows nothing"), + } + }) + .on("stage.inspect", move |w, a, answer| { + let id = a.get("id").and_then(Value::as_u64).unwrap_or(0); + let tx = w.resource::().tx.lock().unwrap().clone(); + match tx { + Some(tx) => { + let _ = tx.send(Cmd::Inspect(id, answer)); + } + None => answer.ok(Value::Null), + } + }) + .on("stage.tweak", move |w, a, answer| { + let s = |c: &Value, k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + let changes: Vec = a.get("changes").and_then(Value::as_array).into_iter().flatten().map(|c| Change { owner: s(c, "owner"), kind: s(c, "kind"), prop: s(c, "prop"), value: c.get("value").cloned().unwrap_or_default() }).collect(); + let tx = w.resource::().tx.lock().unwrap().clone(); + match tx { + Some(tx) => { + let _ = tx.send(Cmd::Tweak(changes, answer)); + } + None => answer.err("the stage shows nothing to change"), + } + }) + .on("stage.status", |w, _a, answer| { + let s = w.resource::().status.lock().unwrap().clone(); + answer.ok(json!({"showing": s.showing, "frame": s.frame, "playing": s.playing, "fps": s.fps, "painted": s.painted, "size": [s.size.0, s.size.1], "error": s.error})); + }); +} diff --git a/engine/page/stage/src/lib.rs b/engine/page/stage/src/lib.rs index 1c3ae245..21022e75 100644 --- a/engine/page/stage/src/lib.rs +++ b/engine/page/stage/src/lib.rs @@ -19,6 +19,9 @@ //! the 3D drawn from that orbit (radians, metres) until free: false puts the //! composition's camera back (PV1c); with neither, only answers. Answers the view as it //! is now ({yaw, pitch, distance, target, radius?, free}), null with no 3D +//! stage.locate {keys, points} where those parts (by key) and world points are on the stage now, px: +//! {parts: [[x, y, w, h] | null], points: [[x, y] | null]} (a selection's box and a +//! 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.inspect {id} that element as it is now (its owner, kind, box, props, text), or null once it's gone @@ -62,6 +65,8 @@ enum Cmd { Pick(f64, f64, Answer), /// a free camera over the 3D (Some(None): the composition's own again; None: only asked), answered with the view View(Option>, Answer), + /// where parts and world points are on the stage now + Locate(Vec, Vec<[f32; 3]>, Answer), /// props over the composition's defaults, from now Props(Value, Answer), /// an element as it is now, by id @@ -124,6 +129,9 @@ impl Stage { } } +mod calls; +use calls::calls; + pub struct StagePlugin; impl Plugin for StagePlugin { @@ -147,102 +155,6 @@ impl Plugin for StagePlugin { } } -fn settle(answer: raea_runtime_js::calls::Answer, r: Result) { - match r { - Ok(v) => answer.ok(v), - Err(e) => answer.err(e), - } -} - -/// The page's host calls (the module's list). -fn calls(mut calls: ResMut) { - let num = |a: &Value, k: &str| a.get(k).and_then(Value::as_f64); - let send = |w: &mut World, c: Cmd| w.resource::().send(c).map(|_| Value::Null); - calls - .on("stage.show", move |w, a, answer| { - if !raea_gpu_device::enabled() { - return answer.err("the stage needs the shared device (RAEA_SHARED_DEVICE=0 turned it off)"); - } - // a feed item names its game as the app's host does (host/make.ts resolve): ~/ is the home - let src = a.get("src").and_then(Value::as_str).map(|s| match (s.strip_prefix("~/"), std::env::var_os("HOME")) { - (Some(rest), Some(home)) => PathBuf::from(home).join(rest), - _ => PathBuf::from(s), - }); - let size = (num(&a, "w").unwrap_or(1280.0).round().max(1.0) as u32, num(&a, "h").unwrap_or(720.0).round().max(1.0) as u32); - settle(answer, send(w, Cmd::Show(src, size))); - }) - .on("stage.play", move |w, a, answer| settle(answer, send(w, Cmd::Play(a.get("on").and_then(Value::as_bool).unwrap_or(true))))) - .on("stage.step", move |w, a, answer| settle(answer, send(w, Cmd::Step(num(&a, "n").unwrap_or(1.0).max(0.0) as i64)))) - .on("stage.seek", move |w, a, answer| settle(answer, send(w, Cmd::Seek(num(&a, "frame").unwrap_or(0.0).max(0.0).round() as i64)))) - .on("stage.key", move |w, a, answer| { - let key = a.get("key").and_then(Value::as_str).unwrap_or_default().to_string(); - settle(answer, send(w, Cmd::Key(key, a.get("down").and_then(Value::as_bool).unwrap_or(true)))); - }) - .on("stage.pointer", move |w, a, answer| { - settle(answer, send(w, Cmd::Pointer(num(&a, "x").unwrap_or(0.0), num(&a, "y").unwrap_or(0.0), a.get("down").and_then(Value::as_bool).unwrap_or(false)))); - }) - .on("stage.pick", move |w, a, answer| { - let (x, y) = (num(&a, "x").unwrap_or(0.0), num(&a, "y").unwrap_or(0.0)); - let tx = w.resource::().tx.lock().unwrap().clone(); - match tx { - Some(tx) => { - let _ = tx.send(Cmd::Pick(x, y, answer)); - } - None => answer.ok(Value::Null), - } - }) - .on("stage.view", move |w, a, answer| { - let f = |k: &str| a.get(k).and_then(Value::as_f64).map(|v| v as f32); - let target = a.get("target").and_then(Value::as_array).map(|t| t.iter().filter_map(Value::as_f64).map(|v| v as f32).collect::>()).filter(|t| t.len() == 3); - let set = match (a.get("free").and_then(Value::as_bool), f("yaw"), f("pitch"), f("distance")) { - (Some(false), ..) => Some(None), - (_, Some(yaw), Some(pitch), Some(distance)) => Some(Some((yaw, pitch, distance, target.map_or([0.0; 3], |t| [t[0], t[1], t[2]])))), - _ => None, - }; - let tx = w.resource::().tx.lock().unwrap().clone(); - match tx { - Some(tx) => { - let _ = tx.send(Cmd::View(set, answer)); - } - None => answer.ok(Value::Null), - } - }) - .on("stage.props", move |w, a, answer| { - let tx = w.resource::().tx.lock().unwrap().clone(); - match tx { - Some(tx) => { - let _ = tx.send(Cmd::Props(a.get("props").cloned().unwrap_or(Value::Null), answer)); - } - None => answer.err("the stage shows nothing"), - } - }) - .on("stage.inspect", move |w, a, answer| { - let id = a.get("id").and_then(Value::as_u64).unwrap_or(0); - let tx = w.resource::().tx.lock().unwrap().clone(); - match tx { - Some(tx) => { - let _ = tx.send(Cmd::Inspect(id, answer)); - } - None => answer.ok(Value::Null), - } - }) - .on("stage.tweak", move |w, a, answer| { - let s = |c: &Value, k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); - let changes: Vec = a.get("changes").and_then(Value::as_array).into_iter().flatten().map(|c| Change { owner: s(c, "owner"), kind: s(c, "kind"), prop: s(c, "prop"), value: c.get("value").cloned().unwrap_or_default() }).collect(); - let tx = w.resource::().tx.lock().unwrap().clone(); - match tx { - Some(tx) => { - let _ = tx.send(Cmd::Tweak(changes, answer)); - } - None => answer.err("the stage shows nothing to change"), - } - }) - .on("stage.status", |w, _a, answer| { - let s = w.resource::().status.lock().unwrap().clone(); - answer.ok(json!({"showing": s.showing, "frame": s.frame, "playing": s.playing, "fps": s.fps, "painted": s.painted, "size": [s.size.0, s.size.1], "error": s.error})); - }); -} - /// Bevy's image the painted texture's size (made again when it changes: its GpuImage follows). fn fit(stage: Res, mut images: ResMut>) { let Some(want) = stage.size() else { return }; @@ -376,6 +288,22 @@ fn run(rx: Receiver, status: Arc>, slot: Arc>) Some(l) => answer.ok(l.pick(x * l.w as f64 / stage.0.max(1) as f64, y * l.h as f64 / stage.1.max(1) as f64).map(|e| on_stage(e, l, stage)).unwrap_or(Value::Null)), None => answer.ok(Value::Null), }, + Some(Cmd::Locate(keys, points, answer)) => match live.as_mut() { + Some(l) => { + // page px to the stage's + let (sx, sy) = (stage.0 as f64 / l.w.max(1) as f64, stage.1 as f64 / l.h.max(1) as f64); + let mut v = l.locate(&keys, &points); + for list in ["parts", "points"] { + for r in v[list].as_array_mut().into_iter().flatten() { + for (i, n) in r.as_array_mut().into_iter().flatten().enumerate() { + *n = json!(n.as_f64().unwrap_or(0.0) * if i % 2 == 0 { sx } else { sy }); + } + } + } + answer.ok(v); + } + None => answer.ok(Value::Null), + }, Some(Cmd::Props(props, answer)) => match live.as_mut() { Some(l) if frame >= 0 => match l.set_props(props) { Ok(()) => { diff --git a/runtime/bundle/src/entry.rs b/runtime/bundle/src/entry.rs index 2cda163b..6132151e 100644 --- a/runtime/bundle/src/entry.rs +++ b/runtime/bundle/src/entry.rs @@ -107,8 +107,7 @@ function Root() {{ // the composition, made again only when what Root passes it changes (by default never, RAEA_STILL_TREE=0 each frame; its parts re-render // when what they read changes, the frame through the Clock's context) // props set from outside while it plays (raea-props: a preview's controls, docs/preview.feature PV4b), over its defaults - const [over, setOver] = useState(null); - useEffect(() => addEventListener("raea-props", (v: any) => setOver(v)), []); + const [over, setOver] = useState(null); useEffect(() => addEventListener("raea-props", (v: any) => setOver(v)), []); const body = useMemo(() => {{(() => {{ const T = (globalThis as any).__raeaToneOut; return T ? : null; }})()}}, {still} ? [over] : [f, size, to, over]); // the frame's Math.random and Date (motion/pure.ts): reseeded as the frame starts rendering, so every component // under it draws the same numbers each time this frame is drawn @@ -200,7 +199,6 @@ function draw() {{ }} }} addEventListener("raea-size", (v: any) => {{ size = v; if (f >= 0) draw(); }}); -// props set from outside while it plays (a preview's controls, docs/preview.feature PV4b), over its defaults addEventListener("raea-props", (v: any) => {{ COMP = ; if (f >= 0) draw(); }}); // a range of frames, rendered back to back, each its own commit (a bake: lightspeed T3); between frames the effects' // state changes render, as between two raea-frame events diff --git a/runtime/live/src/pick3d.rs b/runtime/live/src/pick3d.rs index 7cdcb047..c05024ea 100644 --- a/runtime/live/src/pick3d.rs +++ b/runtime/live/src/pick3d.rs @@ -105,4 +105,18 @@ impl Live { pub fn props_before(&mut self, props: Value) { self.send("raea-props", props); } + + /// Where parts (by key) and world points are on the page now, in page px: `{"parts": [[x, y, w, h] | null], + /// "points": [[x, y] | null]}`, null for a part not drawn or a point behind the camera. A selection's box and a + /// note's pin follow what they are on (raea-sys-frame pick.rs locate). + pub fn locate(&mut self, keys: &[String], points: &[[f32; 3]]) -> Value { + let (w, h) = (self.w.max(1) as f64, self.h.max(1) as f64); + let Some(e) = self.scene.as_mut() else { return json!({"parts": vec![Value::Null; keys.len()], "points": vec![Value::Null; points.len()]}) }; + let pts: Vec = points.iter().map(|p| Vec3::from(*p)).collect(); + let (rects, placed) = raea_sys_frame::pick::locate(e.world_mut(), keys, &pts); + json!({ + "parts": rects.iter().map(|r| r.map(|r| json!([r[0] as f64 * w, r[1] as f64 * h, r[2] as f64 * w, r[3] as f64 * h]))).collect::>(), + "points": placed.iter().map(|p| p.map(|p| json!([p[0] as f64 * w, p[1] as f64 * h]))).collect::>(), + }) + } } diff --git a/systems/frame/src/pick.rs b/systems/frame/src/pick.rs index 9e8d557b..cc9fe1cc 100644 --- a/systems/frame/src/pick.rs +++ b/systems/frame/src/pick.rs @@ -81,6 +81,40 @@ pub fn part_at(world: &mut World, nx: f32, ny: f32) -> Option { }) } +/// Where things are on the frame now (docs/preview.feature PV4d, PV5a): each key's part as its box (x, y, w, h in +/// 0..1; the boxes of its meshes' bounds, so it follows the part as it moves; None when it isn't drawn), and each +/// world point as its place on the frame with whether it is in front of the camera. +pub fn locate(world: &mut World, keys: &[String], points: &[Vec3]) -> (Vec>, Vec>) { + let mut cams = world.query_filtered::<(&Camera, &GlobalTransform), With>(); + let Some((cam, at)) = cams.iter(world).filter(|(c, _)| c.is_active).min_by_key(|(c, _)| c.order) else { return (vec![None; keys.len()], vec![None; points.len()]) }; + let clip_from_world = cam.clip_from_view() * Mat4::from(at.affine().inverse()); + let on_frame = |p: Vec3| { + let c = clip_from_world * p.extend(1.0); + (c.w > 1e-5).then(|| Vec2::new((c.x / c.w + 1.0) * 0.5, (1.0 - c.y / c.w) * 0.5)) + }; + let placed: Vec> = points.iter().map(|p| on_frame(*p).map(|s| s.to_array())).collect(); + let mut boxes: Vec> = vec![None; keys.len()]; + let mut meshes = world.query_filtered::<(Entity, &GlobalTransform, &bevy::camera::primitives::Aabb, Option<&InheritedVisibility>), With>(); + for (e, place, aabb, shown) in meshes.iter(world) { + if shown.is_some_and(|s| !s.get()) { + continue; + } + let Some(k) = world.get::(root_of(world, e)).and_then(|k| keys.iter().position(|x| *x == k.0)) else { continue }; + let (c, h) = (Vec3::from(aabb.center), Vec3::from(aabb.half_extents)); + for i in 0..8 { + let corner = c + h * Vec3::new(if i & 1 == 0 { -1.0 } else { 1.0 }, if i & 2 == 0 { -1.0 } else { 1.0 }, if i & 4 == 0 { -1.0 } else { 1.0 }); + if let Some(s) = on_frame(place.transform_point(corner)) { + boxes[k] = Some(boxes[k].map_or((s, s), |(lo, hi)| (lo.min(s), hi.max(s)))); + } + } + } + let rects = boxes.into_iter().map(|b| b.map(|(lo, hi)| { + let (lo, hi) = (lo.clamp(Vec2::ZERO, Vec2::ONE), hi.clamp(Vec2::ZERO, Vec2::ONE)); + [lo.x, lo.y, hi.x - lo.x, hi.y - lo.y] + })).collect(); + (rects, placed) +} + /// The part a mesh belongs to: the nearest entity up from it (itself first) with a LayerKey, else the mesh itself. fn root_of(world: &World, e: Entity) -> Entity { let mut at = e;