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.

RT4: the realtime editing work so far

shinyobjectz9f4cce5b0073
diff --git a/Cargo.lock b/Cargo.lock
index efbebc21..a89daf2a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15332,6 +15332,7 @@ dependencies = [
"raea-runtime-export",
"raea-runtime-page",
"raea-runtime-react",
+ "raea-runtime-scene",
"raea-runtime-sound",
"raea-sys-frame",
"raea-sys-hold",
diff --git a/engine/page/stage/src/calls.rs b/engine/page/stage/src/calls.rs
index d565e04d..4ccc22e0 100644
--- a/engine/page/stage/src/calls.rs
+++ b/engine/page/stage/src/calls.rs
@@ -40,7 +40,7 @@ pub(super) fn calls(mut calls: ResMut<HostCalls>) {
_ => 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)));
+ settle(answer, send(w, Cmd::Show(src, size, a.get("render").and_then(Value::as_bool).unwrap_or(false))));
})
.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))))
@@ -96,7 +96,7 @@ pub(super) fn calls(mut calls: ResMut<HostCalls>) {
let tx = w.resource::<Stage>().tx.lock().unwrap().clone();
match tx {
Some(tx) => {
- let _ = tx.send(Cmd::Props(a.get("props").cloned().unwrap_or(Value::Null), answer));
+ let _ = tx.send(Cmd::Props(a.get("props").cloned().unwrap_or(Value::Null), answer, Instant::now()));
}
None => answer.err("the stage shows nothing"),
}
@@ -138,6 +138,9 @@ pub(super) fn calls(mut calls: ResMut<HostCalls>) {
})
.on("stage.status", |w, _a, answer| {
let s = w.resource::<Stage>().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}));
+ let props = json!({"sent": s.props.sent, "drawn": s.props.drawn, "dropped": s.props.dropped, "ms": s.props.ms});
+ let last = s.last_show.map(|(how, ms)| json!({"how": how, "ms": ms}));
+ 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,
+ "render": s.render, "opens": s.opens, "adopted": s.adopted, "last_show": last, "props": props, "held": s.held, "controls": s.controls, "values": s.values}));
});
}
diff --git a/engine/page/stage/src/lib.rs b/engine/page/stage/src/lib.rs
index 31c1d4f9..8f34180c 100644
--- a/engine/page/stage/src/lib.rs
+++ b/engine/page/stage/src/lib.rs
@@ -4,14 +4,22 @@
//! app renders on: main.rs) to Bevy, where it's copied on the GPU into the stage's image. The page shows that image in
//! place of its `<img data-raea-stage>` (raea-page's ElementImages, H7), and drives the stage through host calls:
//!
-//! stage.show {src, w, h} the composition at `src` (a .tsx), laid out at w x h; src null: nothing
+//! stage.show {src, w, h, render?}
+//! the composition at `src` (a .tsx), laid out at w x h; src null: nothing. render: true
+//! draws it as `raea render` does (its own size, seed, clock and length, no live input:
+//! docs/realtime.feature RT4d), what an editor wants; a game leaves it out. A file beside
+//! the one shown that differs from it only in its <Composition defaultProps> values is
+//! taken in place, its frame and play kept, unless the 3D holds what they change (RT4f)
//! stage.play {on} play or pause
//! stage.step {n} paused: n frames on, the keys held as they are
//! stage.seek {frame} to that frame, playing or not (a composition's editor, docs/editing.feature E4a: a
//! composition is its frame, so the frame is drawn as it is; a game's input isn't replayed)
//! stage.key {key, down} a key (DOM name) pressed or let go on the stage
//! stage.pointer {x, y, down} the pointer in the stage's pixels
-//! stage.status what it shows, its frame, whether it plays, frames painted, its size, the last error
+//! stage.status what it shows, its frame, whether it plays, frames painted, its size, the last error;
+//! render, opens and adopted (files opened and taken in place), last_show {how, ms},
+//! props {sent, drawn, dropped, ms}, held, and the composition's controls and the values
+//! its frame is drawn with (RT4b)
//! stage.pick {x, y} what's under that point of the stage, the page and its 3D as one picture
//! (docs/preview.feature PV1a): a 3D part ({part: true, key, name, rect, point,
//! distance}) or an element ({id, kind, owner, key, rect, props, text, under?}), or null
@@ -22,8 +30,11 @@
//! 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.props {props} the composition's props set over its defaults as it plays (PV4b), replacing the last
+//! set: the frame it is on is drawn again with them, paused too (RT4e); nothing is
+//! reopened or written. Answers {frame, held: [{part, kind, cols}]}: what of the 3D the
+//! running world keeps from its first frame they change (RT4g; shown once the file is
+//! opened again), or {frame, dropped: true} when a newer set came first (newest wins)
//! 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}
@@ -62,7 +73,8 @@ pub struct StagePage(pub Entity);
/// What the page asks of the stage's thread.
enum Cmd {
- Show(Option<PathBuf>, (u32, u32)),
+ /// a file at a size, drawn as its render draws it or not
+ Show(Option<PathBuf>, (u32, u32), bool),
Play(bool),
Step(i64),
Seek(i64),
@@ -74,8 +86,8 @@ enum Cmd {
View(Option<Option<(f32, f32, f32, [f32; 3])>>, Answer),
/// where parts and world points are on the stage now
Locate(Vec<String>, Vec<[f32; 3]>, Answer),
- /// props over the composition's defaults, from now
- Props(Value, Answer),
+ /// props over the composition's defaults, from now, and when they were asked for
+ Props(Value, Answer, Instant),
/// 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)
@@ -97,18 +109,6 @@ struct Change {
value: Value,
}
-/// What the stage is doing, for the page's controls (stage.status).
-#[derive(Default, Clone)]
-struct Status {
- showing: Option<String>,
- frame: i64,
- playing: bool,
- fps: f64,
- painted: u64,
- size: (u32, u32),
- error: Option<String>,
-}
-
/// The latest frame painted, and how many have been.
#[derive(Default)]
struct Painted {
@@ -144,6 +144,9 @@ impl Stage {
mod calls;
use calls::calls;
+mod open;
+mod status;
+use status::Status;
pub struct StagePlugin;
@@ -236,42 +239,68 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
// the stage's size, which the page's points are in
let mut stage = (1u32, 1u32);
// what it shows, and the input of each frame stepped since (a tweak's next version replays it)
- let mut shown: Option<PathBuf> = None;
+ let mut shown: Option<open::Shown> = None;
let mut log: Vec<(Vec<String>, Option<(f64, f64, bool)>)> = Vec::new();
+ // commands taken from the channel before their turn: a props change looks past itself for a newer one (newest
+ // wins: a drag sends values faster than a heavy frame draws them, and only the last is drawn; RT4e)
+ let mut ahead: std::collections::VecDeque<Cmd> = Default::default();
+ // the props drawn this turn: when they were asked for, until their frame is painted (status.props.ms)
+ let mut props_at: Option<Instant> = None;
loop {
// until the next frame is due while it plays (or a step is left); for the next command while it doesn't
let due_in = if !playing && steps > 0 { Some(Duration::ZERO) } else { live.as_ref().filter(|_| playing).map(|l| (since + Duration::from_secs_f64((frame - base + 1).max(0) as f64 / l.fps)).saturating_duration_since(Instant::now())) };
- let cmd = match due_in {
- Some(d) => match rx.recv_timeout(d) {
+ let cmd = match (ahead.pop_front(), due_in) {
+ (Some(c), _) => Some(c),
+ (None, Some(d)) => match rx.recv_timeout(d) {
Ok(c) => Some(c),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => return,
},
- None => match rx.recv() {
+ (None, None) => match rx.recv() {
Ok(c) => Some(c),
Err(_) => return,
},
};
let mut repaint = false;
match cmd {
- Some(Cmd::Show(src, size)) => {
+ Some(Cmd::Show(src, size, render)) => 'show: {
+ let t = Instant::now();
+ // a file written from the one shown with only its defaults' values changed: taken in place, its frame and
+ // play kept (RT4f)
+ if let (Some(p), Some(l), Some(was)) = (src.as_ref(), live.as_mut(), shown.as_ref())
+ && frame >= 0
+ && let Some(text) = open::adopt(l, was, p, size, render)
+ {
+ let mut s = status.lock().unwrap();
+ (s.showing, s.adopted, s.last_show) = (Some(p.display().to_string()), s.adopted + 1, Some(("adopted", t.elapsed().as_secs_f64() * 1e3)));
+ (s.held, s.values, s.error) = (Vec::new(), l.values(), None);
+ shown = Some(open::Shown { path: p.clone(), text, size, render });
+ repaint = true;
+ break 'show;
+ }
live = None;
stage = size;
keys.clear();
log.clear();
pointer = None;
- shown = src.clone();
+ shown = None;
(playing, frame, base, since, steps) = (true, -1, 0, Instant::now(), 0);
- *status.lock().unwrap() = Status { showing: src.as_ref().map(|p| p.display().to_string()), playing: true, size, ..default() };
+ {
+ let mut s = status.lock().unwrap();
+ *s = Status { showing: src.as_ref().map(|p| p.display().to_string()), playing: true, size, render, opens: s.opens, adopted: s.adopted, ..default() };
+ }
{
let mut p = slot.lock().unwrap();
p.texture = None;
p.n += 1;
}
if let Some(p) = src {
- match open(&p, size) {
+ match open::open(&p, size, render) {
Ok(l) => {
- status.lock().unwrap().fps = l.fps;
+ let mut s = status.lock().unwrap();
+ (s.fps, s.opens, s.last_show) = (l.fps, s.opens + 1, Some(("opened", t.elapsed().as_secs_f64() * 1e3)));
+ (s.controls, s.values) = (l.controls().clone(), l.values());
+ shown = std::fs::read_to_string(&p).ok().map(|text| open::Shown { path: p, text, size, render });
live = Some(l);
rewire = wire;
}
@@ -303,7 +332,7 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
}
// a point of the stage is the page's (a game that lays out at its own size is scaled to the stage)
Some(Cmd::Pick(x, y, answer)) => match live.as_mut() {
- 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)),
+ 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| open::on_stage(e, l, stage)).unwrap_or(Value::Null)),
None => answer.ok(Value::Null),
},
Some(Cmd::Locate(keys, points, answer)) => match live.as_mut() {
@@ -322,21 +351,33 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
}
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(()) => {
+ Some(Cmd::Props(props, answer, asked)) => {
+ ahead.extend(rx.try_iter());
+ status.lock().unwrap().props.sent += 1;
+ match live.as_mut() {
+ // a newer set is waiting: this one is passed over, never drawn
+ Some(_) if ahead.iter().any(|c| matches!(c, Cmd::Props(..))) => {
+ status.lock().unwrap().props.dropped += 1;
+ answer.ok(json!({"frame": frame, "dropped": true}));
+ }
+ Some(l) if frame >= 0 => match l.set_props(props) {
+ Ok(v) => {
+ answer.ok(json!({"frame": frame, "held": v["held"]}));
+ let mut s = status.lock().unwrap();
+ (s.held, s.values) = (l.held().to_vec(), l.values());
+ (repaint, props_at) = (true, Some(asked));
+ }
+ Err(e) => answer.err(e),
+ },
+ // before its first frame: they are there when it is stepped
+ Some(l) => {
+ l.props_before(props);
+ status.lock().unwrap().values = l.values();
answer.ok(json!({"frame": frame}));
- repaint = true;
}
- Err(e) => answer.err(e),
- },
- // before its first frame: they are there when it is stepped
- Some(l) => {
- l.props_before(props);
- answer.ok(json!({"frame": frame}));
+ None => answer.err("the stage shows nothing"),
}
- None => answer.err("the stage shows nothing"),
- },
+ }
Some(Cmd::View(set, answer)) => match live.as_mut() {
Some(l) => {
if let Some(orbit) = set {
@@ -359,15 +400,16 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
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)),
+ Some(l) => answer.ok(l.element(id).map(|e| open::on_stage(e, l, stage)).unwrap_or(Value::Null)),
None => answer.ok(Value::Null),
},
- Some(Cmd::Tweak(changes, answer)) => match (shown.as_deref(), live.as_ref()) {
- (Some(at), Some(_)) => match next_version(at, &changes, stage, &log[..(frame + 1).max(0) as usize]) {
+ Some(Cmd::Tweak(changes, answer)) => match (shown.as_ref(), live.as_ref()) {
+ (Some(at), Some(_)) => match open::next_version(&at.path, &changes, stage, &log[..(frame + 1).max(0) as usize]) {
Ok((next, l)) => {
answer.ok(json!({"written": next.display().to_string(), "frame": frame}));
status.lock().unwrap().showing = Some(next.display().to_string());
- shown = Some(next);
+ let render = at.render;
+ shown = std::fs::read_to_string(&next).ok().map(|text| open::Shown { path: next, text, size: stage, render });
live = Some(l);
repaint = true;
}
@@ -417,7 +459,11 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
let mut p = slot.lock().unwrap();
p.texture = l.texture();
p.n += 1;
- status.lock().unwrap().painted += 1;
+ let mut s = status.lock().unwrap();
+ s.painted += 1;
+ if let Some(t) = props_at.take() {
+ (s.props.drawn, s.props.ms) = (s.props.drawn + 1, t.elapsed().as_secs_f64() * 1e3);
+ }
}
Err(e) => set_error(e),
}
@@ -426,47 +472,3 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
(s.frame, s.playing) = (frame, playing);
}
}
-
-/// The composition at `p` opened to play, laid out at the stage's box, its sound on (RAEA_AUDIO_MUTE=1: off).
-fn open(p: &std::path::Path, size: (u32, u32)) -> Result<raea_runtime_live::Live, String> {
- let mut l = raea_runtime_live::Live::open_with(p, size, true).map_err(|e| format!("{}: {e}", p.display()))?;
- sound(&mut l);
- Ok(l)
-}
-
-fn sound(l: &mut raea_runtime_live::Live) {
- if std::env::var("RAEA_AUDIO_MUTE").as_deref() != Ok("1") {
- l.open_mixer();
- }
-}
-
-/// The changes written into the next version beside `at` (raea-sys-tweak), opened and stepped through the frames played so
-/// far with the input each had, so it stands where the old one did. The old one plays on when any of it fails.
-fn next_version(at: &std::path::Path, changes: &[Change], size: (u32, u32), log: &[(Vec<String>, Option<(f64, f64, bool)>)]) -> Result<(PathBuf, raea_runtime_live::Live), String> {
- let src = std::fs::read_to_string(at).map_err(|e| format!("{}: {e}", at.display()))?;
- let tweaks: Vec<raea_sys_tweak::Tweak> = changes.iter().map(|c| raea_sys_tweak::Tweak { owner: &c.owner, kind: &c.kind, prop: &c.prop, value: &c.value }).collect();
- let out = raea_sys_tweak::tweak(&src, &tweaks)?;
- let next = raea_sys_tweak::free_name(at);
- std::fs::write(&next, out).map_err(|e| format!("{}: {e}", next.display()))?;
- // its sound only from here on: the replay is silent
- let mut l = raea_runtime_live::Live::open_with(&next, size, true).map_err(|e| format!("{}: {e}", next.display()))?;
- for (f, (keys, pointer)) in log.iter().enumerate() {
- l.step(f as i64, keys, *pointer).map_err(|e| format!("{} at frame {f}: {e}", next.display()))?;
- }
- l.draw()?;
- sound(&mut l);
- eprintln!("raea-page-host: stage: wrote {}, replayed {} frames", next.display(), log.len());
- Ok((next, l))
-}
-
-/// An element's box in the stage's pixels (the page's scaled to the stage), beside its own in page px.
-fn on_stage(mut e: Value, l: &raea_runtime_live::Live, size: (u32, u32)) -> Value {
- let (sx, sy) = (size.0 as f64 / l.w.max(1) as f64, size.1 as f64 / l.h.max(1) as f64);
- if let Some(r) = e["rect"].as_array().map(|r| r.iter().filter_map(Value::as_f64).collect::<Vec<_>>()).filter(|r| r.len() == 4) {
- e["stage"] = json!([r[0] * sx, r[1] * sy, r[2] * sx, r[3] * sy]);
- }
- if e.get("under").is_some_and(Value::is_object) {
- e["under"] = on_stage(e["under"].take(), l, size);
- }
- e
-}
diff --git a/engine/page/stage/src/open.rs b/engine/page/stage/src/open.rs
new file mode 100644
index 00000000..81c08bc0
--- /dev/null
+++ b/engine/page/stage/src/open.rs
@@ -0,0 +1,81 @@
+//! Opening what the stage shows: a composition opened to play or to be drawn as its render draws it, a written file
+//! taken in place of opening it when only its defaults' values changed (docs/realtime.feature RT4f), a tweak's next
+//! version, and an element's box in the stage's pixels.
+
+use super::*;
+
+/// The composition at `p` opened to play, laid out at the stage's box, its sound on (RAEA_AUDIO_MUTE=1: off). With
+/// `render`, drawn as `raea render` draws it (Live::open_render: its own size, seed, clock and length; RT4d): what an
+/// editor shows, where a game (the default) has a session of its own and the person's input.
+pub(super) fn open(p: &std::path::Path, size: (u32, u32), render: bool) -> Result<raea_runtime_live::Live, String> {
+ let l = if render { raea_runtime_live::Live::open_render(p) } else { raea_runtime_live::Live::open_with(p, size, true) };
+ let mut l = l.map_err(|e| format!("{}: {e}", p.display()))?;
+ sound(&mut l);
+ Ok(l)
+}
+
+/// What the stage shows, for taking a file written from it in place of opening that (`adopt`): the file, its text as
+/// opened, its size and whether it is drawn as its render.
+pub(super) struct Shown {
+ pub(super) path: PathBuf,
+ pub(super) text: String,
+ pub(super) size: (u32, u32),
+ pub(super) render: bool,
+}
+
+/// `src` taken in place of opening it, when it sits beside what `shown` holds and differs from it only in its
+/// `<Composition defaultProps>` values (raea_sys_tweak::values_only), shown the same way: its values laid over the
+/// running world (Live::adopt), the frame drawn again. Some(the file's text) when taken; None to open it, as when the
+/// values change something the 3D keeps from its first frame (the answer's held parts), which only an open shows.
+pub(super) fn adopt(l: &mut raea_runtime_live::Live, shown: &Shown, src: &std::path::Path, size: (u32, u32), render: bool) -> Option<String> {
+ if (size, render) != (shown.size, shown.render) || src.parent() != shown.path.parent() {
+ return None;
+ }
+ let text = std::fs::read_to_string(src).ok()?;
+ let values = raea_sys_tweak::values_only(&shown.text, &text)?;
+ match l.adopt(values) {
+ Ok(_) if l.held().is_empty() => Some(text),
+ Ok(_) => None,
+ Err(e) => {
+ eprintln!("raea-page-host: stage: {} not taken in place ({e}): opened", src.display());
+ None
+ }
+ }
+}
+
+fn sound(l: &mut raea_runtime_live::Live) {
+ if std::env::var("RAEA_AUDIO_MUTE").as_deref() != Ok("1") {
+ l.open_mixer();
+ }
+}
+
+/// The changes written into the next version beside `at` (raea-sys-tweak), opened and stepped through the frames played so
+/// far with the input each had, so it stands where the old one did. The old one plays on when any of it fails.
+pub(super) fn next_version(at: &std::path::Path, changes: &[Change], size: (u32, u32), log: &[(Vec<String>, Option<(f64, f64, bool)>)]) -> Result<(PathBuf, raea_runtime_live::Live), String> {
+ let src = std::fs::read_to_string(at).map_err(|e| format!("{}: {e}", at.display()))?;
+ let tweaks: Vec<raea_sys_tweak::Tweak> = changes.iter().map(|c| raea_sys_tweak::Tweak { owner: &c.owner, kind: &c.kind, prop: &c.prop, value: &c.value }).collect();
+ let out = raea_sys_tweak::tweak(&src, &tweaks)?;
+ let next = raea_sys_tweak::free_name(at);
+ std::fs::write(&next, out).map_err(|e| format!("{}: {e}", next.display()))?;
+ // its sound only from here on: the replay is silent
+ let mut l = raea_runtime_live::Live::open_with(&next, size, true).map_err(|e| format!("{}: {e}", next.display()))?;
+ for (f, (keys, pointer)) in log.iter().enumerate() {
+ l.step(f as i64, keys, *pointer).map_err(|e| format!("{} at frame {f}: {e}", next.display()))?;
+ }
+ l.draw()?;
+ sound(&mut l);
+ eprintln!("raea-page-host: stage: wrote {}, replayed {} frames", next.display(), log.len());
+ Ok((next, l))
+}
+
+/// An element's box in the stage's pixels (the page's scaled to the stage), beside its own in page px.
+pub(super) fn on_stage(mut e: Value, l: &raea_runtime_live::Live, size: (u32, u32)) -> Value {
+ let (sx, sy) = (size.0 as f64 / l.w.max(1) as f64, size.1 as f64 / l.h.max(1) as f64);
+ if let Some(r) = e["rect"].as_array().map(|r| r.iter().filter_map(Value::as_f64).collect::<Vec<_>>()).filter(|r| r.len() == 4) {
+ e["stage"] = json!([r[0] * sx, r[1] * sy, r[2] * sx, r[3] * sy]);
+ }
+ if e.get("under").is_some_and(Value::is_object) {
+ e["under"] = on_stage(e["under"].take(), l, size);
+ }
+ e
+}
diff --git a/engine/page/stage/src/status.rs b/engine/page/stage/src/status.rs
new file mode 100644
index 00000000..46e9f468
--- /dev/null
+++ b/engine/page/stage/src/status.rs
@@ -0,0 +1,36 @@
+//! What the stage is doing, as stage.status answers it (calls.rs).
+
+use serde_json::Value;
+
+/// What the stage is doing, for the page's controls (stage.status).
+#[derive(Default, Clone)]
+pub(super) struct Status {
+ pub(super) showing: Option<String>,
+ pub(super) frame: i64,
+ pub(super) playing: bool,
+ pub(super) fps: f64,
+ pub(super) painted: u64,
+ pub(super) size: (u32, u32),
+ pub(super) error: Option<String>,
+ pub(super) render: bool,
+ /// files opened, and files taken in place of opening them (open::adopt)
+ pub(super) opens: u64,
+ pub(super) adopted: u64,
+ /// the last show: "opened" or "adopted", and its milliseconds from the call to the composition ready
+ pub(super) last_show: Option<(&'static str, f64)>,
+ pub(super) props: PropsSeen,
+ /// what the last props held (Live::held), the composition's controls and the values its frame is drawn with
+ pub(super) held: Vec<Value>,
+ pub(super) controls: Value,
+ pub(super) values: Value,
+}
+
+/// Props changes: sent to the stage, drawn, passed over for a newer one, and the last drawn's milliseconds from the
+/// call to its frame painted into the stage's texture.
+#[derive(Default, Clone)]
+pub(super) struct PropsSeen {
+ pub(super) sent: u64,
+ pub(super) drawn: u64,
+ pub(super) dropped: u64,
+ pub(super) ms: f64,
+}
diff --git a/runtime/bundle/src/entry.rs b/runtime/bundle/src/entry.rs
index a23bd224..cd96982f 100644
--- a/runtime/bundle/src/entry.rs
+++ b/runtime/bundle/src/entry.rs
@@ -83,6 +83,13 @@ if (HOST && HOST.op_flush && !HOST.__pure) {{
HOST.op_flush = (...a: any[]) => {{ const r = flush(...a); pureAgain(); return r; }};
HOST.__pure = true;
}}
+// the composition's settings as its marker carries them: its size, rate and length, and the controls it declares with
+// the props they tune (docs/realtime.feature RT4b: what the stage answers in stage.status); props JSON can't write (a
+// cycle, a BigInt) are left out rather than failing the composition
+const CONF = (() => {{
+ const base = {{ width: cfg.width, height: cfg.height, fps: cfg.fps, frames: cfg.durationInFrames }};
+ try {{ return JSON.stringify({{ ...base, props: cfg.defaultProps, controls: (cfg as any).controls ?? {{}} }}); }} catch {{ return JSON.stringify(base); }}
+}})();
// a throw while rendering the composition, caught and put where Rust reads it (settle), with its message (JSC's stack
// leaves it out) and React's component stack, so the render says what went wrong instead of waiting 20 s for a frame that never commits
class Catch extends Component<{{ children?: any }}, {{ err: string | null }}> {{
@@ -115,20 +122,23 @@ function Root() {{
useEffect(() => addEventListener("raea-frames", (v: any) => {{ setTo(v.to); setF(v.from); }}), []);
// 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<any>(null); useEffect(() => addEventListener("raea-props", (v: any) => setOver(v)), []);
- const body = useMemo(() => <Catch><C {{...cfg.defaultProps}} {{...over}} />{{(() => {{ const T = (globalThis as any).__raeaToneOut; return T ? <T /> : null; }})()}}</Catch>, {still} ? [over] : [f, size, to, over]);
+ // props set from outside while it plays (raea-props: a preview's controls, docs/preview.feature PV4b), over its defaults;
+ // each one counted (pn), so the marker says which has landed (docs/realtime.feature RT4e: a paused stage waits for it)
+ const [over, setOver] = useState<any>(null); const [pn, setPn] = useState(0);
+ useEffect(() => addEventListener("raea-props", (v: any) => {{ setOver(v); setPn((n: number) => n + 1); }}), []);
+ // the props it's drawn with, which useVideoConfig().defaultProps and useControl read (RT4c), one object while they hold
+ const props = useMemo(() => (over ? {{ ...cfg.defaultProps, ...over }} : cfg.defaultProps), [over]);
+ const body = useMemo(() => <Catch><C {{...props}} />{{(() => {{ const T = (globalThis as any).__raeaToneOut; return T ? <T /> : null; }})()}}</Catch>, {still} ? [props] : [f, size, to, props]);
// 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
if (f >= 0) pureFrame(f, cfg.fps);
- const conf = JSON.stringify({{ width: cfg.width, height: cfg.height, fps: cfg.fps, frames: cfg.durationInFrames }});
- if (f < 0) return <div data-raea-frame={{-1}} data-raea-config={{conf}} />;
+ if (f < 0) return <div data-raea-frame={{-1}} data-raea-config={{CONF}} data-raea-props={{0}} />;
return (
<>
- <Clock frame={{f}} fps={{cfg.fps}} width={{size ? size.w : cfg.width}} height={{size ? size.h : cfg.height}} durationInFrames={{live || REPLAYS_LIVE ? 1000000000 : cfg.durationInFrames}} id={{cfg.id}} defaultProps={{cfg.defaultProps}} words={{WORDS}} perception={{percAt(f)}} input={{live ? LIVE : INPUT}}>
+ <Clock frame={{f}} fps={{cfg.fps}} width={{size ? size.w : cfg.width}} height={{size ? size.h : cfg.height}} durationInFrames={{live || REPLAYS_LIVE ? 1000000000 : cfg.durationInFrames}} id={{cfg.id}} defaultProps={{props}} words={{WORDS}} perception={{percAt(f)}} input={{live ? LIVE : INPUT}}>
{{body}}
</Clock>
- <Marker f={{f}} to={{to}} conf={{conf}} next={{setF}} />
+ <Marker f={{f}} to={{to}} conf={{CONF}} next={{setF}} pn={{pn}} />
</>
);
}}
@@ -136,9 +146,11 @@ function Root() {{
// marks it, and Rust takes the frame the moment that mark lands (settle), with no waiting for quiet. The mark is this
// component's state, not Root's: marking it in Root rendered the whole composition a second time each frame
// (many_cubes' 10 000 parts, docs/control.feature FC1a)
-function Marker({{ f, to, conf, next }}: {{ f: number; to: number; conf: string; next: (f: number) => void }}) {{
+// The props' pass is marked the same way: data-raea-props is the last raea-props whose commit and effects have run.
+function Marker({{ f, to, conf, next, pn }}: {{ f: number; to: number; conf: string; next: (f: number) => void; pn: number }}) {{
const [done, setDone] = useState(-1);
const [woke, setWoke] = useState(0);
+ const [landed, setLanded] = useState(0);
useEffect(() => {{ const w = () => setWoke((n: number) => n + 1); HOLD.wake.add(w); return () => void HOLD.wake.delete(w); }}, []);
useEffect(() => {{
if (f >= 0 && HOLD.n === 0) setDone(f);
@@ -146,7 +158,8 @@ function Marker({{ f, to, conf, next }}: {{ f: number; to: number; conf: string;
useEffect(() => {{
if (f >= 0 && done === f && f + 1 < to) next(f + 1);
}}, [done]);
- return <div data-raea-frame={{f}} data-raea-done={{done}} data-raea-config={{conf}} />;
+ useEffect(() => setLanded(pn), [pn]);
+ return <div data-raea-frame={{f}} data-raea-done={{done}} data-raea-config={{conf}} data-raea-props={{landed}} />;
}}
mount(<surface id="motion" w={{1}} px={{cfg.width}} pxH={{cfg.height}}><Root /></surface>).catch((globalThis as any).__raea_loop_died);
"#,
@@ -181,9 +194,13 @@ import {{ renderRoot, takeRendered }} from "react";
let live = false;
let f = -1;
let size: {{ w: number; h: number }} | null = null;
-const conf = JSON.stringify({{ width: cfg.width, height: cfg.height, fps: cfg.fps, frames: cfg.durationInFrames }});
+const conf = CONF;
+// the props it's drawn with (raea-props over its defaults; useVideoConfig().defaultProps and useControl read them), and
+// how many raea-props have come, which the marker carries once drawn (docs/realtime.feature RT4e)
+let PROPS: any = cfg.defaultProps;
+let PN = 0;
// the composition's element and the Tone graph's output, made once (each frame made them again: lightspeed Z3)
-let COMP = <C {{...cfg.defaultProps}} />;
+let COMP = <C {{...PROPS}} />;
let toneEl: any = null;
function toneOut() {{
const T = (globalThis as any).__raeaToneOut;
@@ -194,10 +211,10 @@ function toneOut() {{
function tree() {{
// the frame's Math.random and Date, and requestAnimationFrame's callbacks (motion/pure.ts)
if (f >= 0) {{ frameCallbacks(f, cfg.fps); pureFrame(f, cfg.fps); }}
- if (f < 0) return <surface id="motion" w={{1}} px={{cfg.width}} pxH={{cfg.height}}><div data-raea-frame={{-1}} data-raea-config={{conf}} /></surface>;
+ if (f < 0) return <surface id="motion" w={{1}} px={{cfg.width}} pxH={{cfg.height}}><div data-raea-frame={{-1}} data-raea-config={{conf}} data-raea-props={{PN}} /></surface>;
return (
<surface id="motion" w={{1}} px={{cfg.width}} pxH={{cfg.height}}>
- <Clock frame={{f}} fps={{cfg.fps}} width={{size ? size.w : cfg.width}} height={{size ? size.h : cfg.height}} durationInFrames={{live || REPLAYS_LIVE ? 1000000000 : cfg.durationInFrames}} id={{cfg.id}} defaultProps={{cfg.defaultProps}} words={{WORDS}} perception={{percAt(f)}} input={{live ? LIVE : INPUT}}>
+ <Clock frame={{f}} fps={{cfg.fps}} width={{size ? size.w : cfg.width}} height={{size ? size.h : cfg.height}} durationInFrames={{live || REPLAYS_LIVE ? 1000000000 : cfg.durationInFrames}} id={{cfg.id}} defaultProps={{PROPS}} words={{WORDS}} perception={{percAt(f)}} input={{live ? LIVE : INPUT}}>
{{COMP}}{{toneOut()}}
</Clock>
{marker}
@@ -206,7 +223,7 @@ function tree() {{
}}
// --comps (a bake): the marker rendered last, carrying the code of every component this frame rendered
function Marker(p: any) {{
- return <div data-raea-frame={{p.f}} data-raea-done={{HOLD.n ? -3 : p.f}} data-raea-config={{conf}} data-raea-comps={{takeRendered()}} />;
+ return <div data-raea-frame={{p.f}} data-raea-done={{HOLD.n ? -3 : p.f}} data-raea-config={{conf}} data-raea-props={{PN}} data-raea-comps={{takeRendered()}} />;
}}
HOLD.wake.add(() => {{ if (f >= 0) draw(); }});
// a throw while rendering is put where Rust reads it (settle), as React's entry's Catch did
@@ -218,7 +235,7 @@ function draw() {{
}}
}}
addEventListener("raea-size", (v: any) => {{ size = v; if (f >= 0) draw(); }});
-addEventListener("raea-props", (v: any) => {{ COMP = <C {{...cfg.defaultProps}} {{...v}} />; if (f >= 0) draw(); }});
+addEventListener("raea-props", (v: any) => {{ PN++; PROPS = v ? {{ ...cfg.defaultProps, ...v }} : cfg.defaultProps; COMP = <C {{...PROPS}} />; 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
addEventListener("raea-frames", async (v: any) => {{
@@ -244,6 +261,6 @@ draw();
runEventLoop().catch((globalThis as any).__raea_loop_died);
"#,
preamble = &full[start..end],
- marker = if o.comps { "<Marker f={f} />" } else { "<div data-raea-frame={f} data-raea-done={HOLD.n ? -3 : f} data-raea-config={conf} />" },
+ marker = if o.comps { "<Marker f={f} />" } else { "<div data-raea-frame={f} data-raea-done={HOLD.n ? -3 : f} data-raea-config={conf} data-raea-props={PN} />" },
)
}
diff --git a/runtime/live/Cargo.toml b/runtime/live/Cargo.toml
index ac17a03b..4e33793f 100644
--- a/runtime/live/Cargo.toml
+++ b/runtime/live/Cargo.toml
@@ -13,6 +13,8 @@ raea-runtime-page = { path = "../page" }
raea-runtime-sound = { path = "../sound", default-features = false }
raea-runtime-export = { path = "../export" }
raea-runtime-bake = { path = "../bake" }
+# which of a part's columns a running world takes frame by frame (live_dynamic): the rest a props change is held on
+raea-runtime-scene = { path = "../scene" }
raea-render = { path = "../../engine/render", default-features = false, features = ["native"] }
raea-gpu-device = { path = "../../gpu/device" }
raea-io-net = { path = "../../io/net" }
diff --git a/runtime/live/src/lib.rs b/runtime/live/src/lib.rs
index 17471bab..6d32ef7f 100644
--- a/runtime/live/src/lib.rs
+++ b/runtime/live/src/lib.rs
@@ -21,6 +21,7 @@ pub use sound::warm_audio;
mod draw;
mod react;
pub use react::needs_react;
+mod props;
type R<T> = Result<T, String>;
@@ -80,6 +81,10 @@ pub struct Live {
/// this session's seed and the time (ms) its frame 0 is at: its Math.random and Date (motion/pure.ts), sent with each
/// frame and kept in an input log, so a replay draws what was played
session: (u32, f64),
+ /// frames told as `raea render` tells them (open_render): the composition's own seed, clock and length, no input
+ render: bool,
+ /// the props set over its defaults while it plays, and what they change that the 3D holds (props.rs)
+ props: props::Props,
}
/// A live session's seed and start: RAEA_SEED when it's set (a test), else from the clock and the process
@@ -205,6 +210,8 @@ impl Live {
/// `step_at`, its sound synced too when `sound`.
fn step_inner(&mut self, f: i64, keys: &[String], pointer: Option<(f64, f64, bool)>, lag: f64, sound: bool) -> R<()> {
self.lag = (lag, std::time::Instant::now());
+ // the 3D's holds worked out after the last props (props.rs) were this frame's
+ self.props.base = None;
self.frame = f;
self.pads.clear();
self.taken.clear();
@@ -243,16 +250,23 @@ impl Live {
self.app.world().resource::<ReactOutbox>().send(m);
}
}
- self.app.world().resource::<ReactOutbox>().send_raw(frame_event(f, keys, pointer, Some(self.session)));
+ self.app.world().resource::<ReactOutbox>().send_raw(if self.render { format!(r#"{{"t":"event","name":"raea-frame","value":{f}}}"#) } else { frame_event(f, keys, pointer, Some(self.session)) });
// a layout read the composition makes (docs/layout-reads.feature LR2): the live page synced to the World as
// it is mid-settle, laid out, and its boxes; the frame's draw syncs it again with the 3D's holders. Preview,
// play, the app's stage and an exported game all step here
let (page, brand) = (&mut self.page, self.brand.as_deref());
- raea_runtime_react::scene::settle_with(&mut self.app, Some(f), 5.0, &mut |w, q| {
+ let mut lay = |w: &mut World, q: &str| {
page.sync(w, &std::collections::HashMap::new(), brand).map_err(|e| e.to_string())?;
page.lay_out();
Ok(page.layout_snapshot(q))
- })?;
+ };
+ let seen = raea_runtime_react::flushed();
+ raea_runtime_react::scene::settle_with(&mut self.app, Some(f), 5.0, &mut lay)?;
+ // a props pass (set_props): the frame is taken once its marker says the props have landed, not at the mark
+ // the frame already had, which a paused stage drew again unchanged (docs/realtime.feature RT4e)
+ if let Some(n) = self.props.wanted.take() {
+ props::landed(&mut self.app, &mut self.props.marker, n, seen, &mut |app| raea_runtime_react::scene::settle_with(app, Some(f), 5.0, &mut lay).map(drop))?;
+ }
// a game's 3D: this frame's scene, as it was just computed, set on the live engine
if let Some(ls) = self.live3d.as_mut() {
let t = std::time::Instant::now();
diff --git a/runtime/live/src/open.rs b/runtime/live/src/open.rs
index 02f72d60..ef1364ce 100644
--- a/runtime/live/src/open.rs
+++ b/runtime/live/src/open.rs
@@ -13,6 +13,18 @@ impl Live {
/// motion, decks, scenes; open_baked too) keep the composition's own layout at its own size, never re-flowed to the
/// window's box; the legacy app's stage only scales that page uniformly (paint_texture_fit). Don't flip this per kind.
pub fn open_with(tsx: &Path, stage: (u32, u32), may_respond: bool) -> R<Live> {
+ Self::open_as(tsx, stage, may_respond, false)
+ }
+
+ /// The composition in `tsx` opened to be drawn as `raea render` draws it (docs/realtime.feature RT4d): at its own
+ /// size, its frames told as a render tells them, so Math.random and Date are the render's (the composition's seed,
+ /// the render's clock), useVideoConfig's length is its own and it reads no live input. Its frame N is the render's
+ /// frame N; a game, which wants a session of its own and the person's input, opens with `open`.
+ pub fn open_render(tsx: &Path) -> R<Live> {
+ Self::open_as(tsx, (1, 1), false, true)
+ }
+
+ fn open_as(tsx: &Path, stage: (u32, u32), may_respond: bool, render: bool) -> R<Live> {
warm_audio();
// the thread that steps and presents live frames, at the frame threads' QoS (as the JS thread)
raea_runtime_react::interactive_thread();
@@ -37,7 +49,7 @@ impl Live {
raea_runtime_react::scene::bundle_composition(&tsx, &js, &raea_runtime_react::scene::comp_opts(&opts)?, None)?;
let src = std::fs::read_to_string(&tsx).unwrap_or_default();
let responsive = may_respond && (src.contains("useVideoConfig(") || components_use_config(&dir));
- Self::from_bundle(js, dir, stage, responsive)
+ Self::from_bundle(js, dir, stage, responsive, render)
}
/// A composition already bundled for live play (an exported game, game.rs): `js` is copied to the temp folder (the
@@ -46,7 +58,7 @@ impl Live {
raea_runtime_react::interactive_thread();
let tmp = std::env::temp_dir().join(format!("raea-live-{}-{:x}.js", std::process::id(), rand_id()));
std::fs::copy(js, &tmp).map_err(|e| format!("{}: {e}", js.display()))?;
- Self::from_bundle(tmp, dunce::canonicalize(&dir).map_err(|e| format!("{}: {e}", dir.display()))?, stage, responsive)
+ Self::from_bundle(tmp, dunce::canonicalize(&dir).map_err(|e| format!("{}: {e}", dir.display()))?, stage, responsive, false)
}
/// The game's master as worked out ahead of time (an exported game carries it): no second React at run time.
@@ -54,7 +66,7 @@ impl Live {
self.game_gain = g;
}
- pub(crate) fn from_bundle(js: PathBuf, dir: PathBuf, stage: (u32, u32), responsive: bool) -> R<Live> {
+ pub(crate) fn from_bundle(js: PathBuf, dir: PathBuf, stage: (u32, u32), responsive: bool, render: bool) -> R<Live> {
raea_runtime_react::native::open_in(&dir, &js);
let mut app = App::new();
app.add_plugins(MinimalPlugins).add_plugins(ReactPlugin::new(js.clone()));
@@ -65,7 +77,8 @@ impl Live {
let (w, h) = if responsive { (stage.0.max(1), stage.1.max(1)) } else { (cw, ch) };
let page = raea_runtime_page::BevyPage::new(w, h, &dir)?;
let brand = raea_runtime_react::scene::page_css(&dir, w, &js);
- let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), taken: Vec::new(), pointer: Default::default(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session() };
+ let props = crate::props::Props::of(&conf);
+ let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), taken: Vec::new(), pointer: Default::default(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session(), render, props };
if responsive {
live.send("raea-size", json!({"w": w, "h": h}));
}
@@ -117,7 +130,7 @@ impl Live {
raea_runtime_react::scene::one_thread(&mut app);
let page = raea_runtime_page::BevyPage::new(w, h, &dir)?;
let brand = raea_runtime_react::scene::page_css(&dir, w, &js);
- let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive: false, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), taken: Vec::new(), pointer: Default::default(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session() };
+ let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive: false, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), taken: Vec::new(), pointer: Default::default(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session(), render: false, props: Default::default() };
for b in &baked.init {
live.app.world().resource::<raea_runtime_react::ReplayFeed>().feed(b.clone());
}
diff --git a/runtime/live/src/pick3d.rs b/runtime/live/src/pick3d.rs
index 36152d7f..5c61f65e 100644
--- a/runtime/live/src/pick3d.rs
+++ b/runtime/live/src/pick3d.rs
@@ -141,20 +141,6 @@ impl Live {
Some(json!({"yaw": o.yaw, "pitch": o.pitch, "distance": o.distance, "target": o.target.to_array(), "radius": radius, "free": false}))
}
- /// The composition's props set over its defaults while it plays (the entry's raea-props): the frame it is on is
- /// rendered again with them, so the next draw shows them. A game's state is kept; its props only change.
- pub fn set_props(&mut self, props: Value) -> R<()> {
- self.send("raea-props", props);
- // the frame stepped again: its commit with the new props lands in the page as any frame's does
- let f = self.frame;
- self.step_world(f, &[], None, 0.0)
- }
-
- /// `set_props` before any frame is stepped: sent, and drawn with the first frame.
- 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).
diff --git a/runtime/live/src/props.rs b/runtime/live/src/props.rs
new file mode 100644
index 00000000..5d711f9d
--- /dev/null
+++ b/runtime/live/src/props.rs
@@ -0,0 +1,217 @@
+//! A composition's props set while it plays (docs/realtime.feature RT4): laid over its defaults and drawn on the frame
+//! it is on, paused or playing, the frame taken once its marker says they have landed (RT4e); a written file whose only
+//! change is its defaults' values taken in place of opening it (`adopt`, RT4f); and what of the 3D a running world
+//! keeps from a part's first frame that a change touches (`held`, RT4g), which a host shows and opens the file again for.
+
+use std::collections::{BTreeMap, HashMap};
+use std::time::{Duration, Instant};
+
+use raea_core_program::ir::V;
+use serde_json::Map;
+
+use super::*;
+
+/// A frame's 3D parts by identity (the part's name, else its kind and shape or file, counted in order), each with the
+/// columns a running world keeps from the part's first frame.
+type Holds = HashMap<String, BTreeMap<String, V>>;
+
+/// How long a props pass may take to land before the step is refused (a composition that hangs on its new props).
+const LAND_SECS: f64 = 5.0;
+
+#[derive(Default)]
+pub(crate) struct Props {
+ /// the composition's defaultProps and controls, as its settings marker carries them (the bundle's CONF)
+ defaults: Map<String, Value>,
+ controls: Value,
+ /// what an adopted file's defaults change of the bundle's (adopt), and the props set over them (set_props)
+ adopted: Map<String, Value>,
+ over: Map<String, Value>,
+ /// raea-props sent; the pass a step waits for (step_inner), once
+ sent: u64,
+ pub(crate) wanted: Option<u64>,
+ /// the frame marker's entity, once found
+ pub(crate) marker: Option<Entity>,
+ /// what the last props held (each {part, kind, cols}), and the frame's holds after it, until a step
+ held: Vec<Value>,
+ pub(crate) base: Option<(i64, Holds)>,
+}
+
+impl Props {
+ /// From the composition's settings (`props`, `controls`: the bundle's CONF).
+ pub(crate) fn of(conf: &Map<String, Value>) -> Props {
+ Props { defaults: conf.get("props").and_then(Value::as_object).cloned().unwrap_or_default(), controls: conf.get("controls").cloned().unwrap_or_else(|| json!({})), ..Default::default() }
+ }
+}
+
+impl Live {
+ /// The composition's props set over its defaults while it plays (the entry's raea-props), replacing the last set:
+ /// the frame it is on is drawn again with them, paused or playing, once they have landed (RT4e). A game's state is
+ /// kept; its props only change. Answers what of the 3D they change that the running world keeps from a part's
+ /// first frame ({held: [{part, kind, cols}]}, RT4g): those show only when the file is opened again.
+ pub fn set_props(&mut self, props: Value) -> R<Value> {
+ let f = self.frame;
+ let before = self.props.base.take().filter(|(at, _)| *at == f).map(|(_, h)| h).or_else(|| self.holds());
+ self.props.over = props.as_object().cloned().unwrap_or_default();
+ self.send_props();
+ self.props.wanted = Some(self.props.sent);
+ // the frame opened ready (frame 0, its 3D warm) is stepped again all the same: its props' commit is new
+ if let Some(l) = self.live3d.as_mut() {
+ l.warm = false;
+ }
+ self.step_world(f, &[], None, 0.0)?;
+ let after = self.holds();
+ self.props.held = held(before.as_ref(), after.as_ref());
+ if let Some(h) = after {
+ self.props.base = Some((f, h));
+ }
+ Ok(json!({"held": self.props.held}))
+ }
+
+ /// `set_props` before any frame is stepped: sent, and drawn with the first frame.
+ pub fn props_before(&mut self, props: Value) {
+ self.props.over = props.as_object().cloned().unwrap_or_default();
+ self.send_props();
+ }
+
+ /// A file written from this one with only its defaults' values changed (raea_sys_tweak::values_only), taken in place
+ /// of opening it (RT4f): its values laid over the bundle's defaults, the props set over them dropped (a fresh open
+ /// has none), and the frame drawn again, as `set_props` draws it and with its answer. A host opens the file after
+ /// all when that answer holds something.
+ pub fn adopt(&mut self, defaults: Map<String, Value>) -> R<Value> {
+ self.props.adopted = defaults.into_iter().filter(|(k, v)| self.props.defaults.get(k) != Some(v)).collect();
+ self.set_props(Value::Object(Map::new()))
+ }
+
+ /// The props the frame is drawn with: the defaults, an adopted file's values over them, the props set over those.
+ pub fn values(&self) -> Value {
+ let mut v = self.props.defaults.clone();
+ v.extend(self.props.adopted.clone());
+ v.extend(self.props.over.clone());
+ Value::Object(v)
+ }
+
+ /// The controls the composition declares, by defaultProps key (raea's registry: kind, cost, group, ...).
+ pub fn controls(&self) -> &Value {
+ &self.props.controls
+ }
+
+ /// What the last props set (or file adopted) held: [{part, kind, cols}], empty when the running world shows it all.
+ pub fn held(&self) -> &[Value] {
+ &self.props.held
+ }
+
+ fn send_props(&mut self) {
+ let mut v = self.props.adopted.clone();
+ v.extend(self.props.over.clone());
+ self.props.sent += 1;
+ self.send("raea-props", Value::Object(v));
+ }
+
+ /// The 3D's parts at the frame as it stands, with the columns a running world keeps from their first frame (None
+ /// with no 3D played live): a render's rows for the frame (LiveScene::open on a scratch scene), keyed by identity.
+ fn holds(&mut self) -> Option<Holds> {
+ self.live3d.as_ref()?;
+ let (w, h, fps) = (self.w, self.h, self.fps);
+ raea_runtime_react::scene::edit_dir(&self.dir);
+ let world = self.app.world_mut();
+ let scene = raea_runtime_react::scene::scene_of(world);
+ let clear = raea_runtime_react::scene::scene_clear(world);
+ let p = raea_runtime_react::scene::LiveScene::default().open(raea_runtime_react::scene::Shot { scene: &scene, clear: clear.as_deref() }, w, h, fps);
+ let mut out = Holds::new();
+ let mut seen: HashMap<String, usize> = HashMap::new();
+ for (kind, rows) in &p.spawns {
+ if !raea_runtime_scene::LIVE_GROUPS.contains(&kind.as_str()) {
+ continue;
+ }
+ for row in rows {
+ let s = |k: &str| match row.get(k) {
+ Some(V::S(s)) => Some(s.as_str()),
+ _ => None,
+ };
+ let base = s("name").map(|n| format!("{kind}|{n}")).unwrap_or_else(|| format!("{kind}~{}", s("shape").or(s("src")).unwrap_or("")));
+ let n = seen.entry(base.clone()).or_default();
+ *n += 1;
+ let cols = row.iter().filter(|(k, _)| keeps(kind, k)).map(|(k, v)| (k.clone(), v.clone())).collect();
+ out.insert(format!("{base}#{}", *n - 1), cols);
+ }
+ }
+ Some(out)
+ }
+}
+
+/// A column the running world keeps from a part's first frame: not one it takes frame by frame (live_dynamic), nor its
+/// identity (name), nor one live play sends when it changes (a mesh's colour, keyed once it does, and its glow).
+fn keeps(kind: &str, col: &str) -> bool {
+ !matches!(col, "id" | "name") && !raea_runtime_scene::live_dynamic(kind).contains(&col) && !(kind == "mesh" && matches!(col, "color" | "emissive"))
+}
+
+/// The parts a change held: those whose kept columns differ between the frame before it and after it, with which.
+fn held(before: Option<&Holds>, after: Option<&Holds>) -> Vec<Value> {
+ let (Some(a), Some(b)) = (before, after) else { return Vec::new() };
+ let mut out: Vec<Value> = b
+ .iter()
+ .filter_map(|(part, cols)| {
+ let was = a.get(part)?;
+ let changed: Vec<&String> = cols.iter().filter(|(k, v)| was.get(*k) != Some(*v)).map(|(k, _)| k).chain(was.keys().filter(|k| !cols.contains_key(*k))).collect();
+ let kind = part.split(['|', '~']).next().unwrap_or("");
+ (!changed.is_empty()).then(|| json!({"part": part, "kind": kind, "cols": changed}))
+ })
+ .collect();
+ out.sort_by(|x, y| x["part"].as_str().cmp(&y["part"].as_str()));
+ out
+}
+
+/// Stepped (`again`: the frame settled once more) until the frame marker carries props pass `n` (the entry's
+/// data-raea-props), at most LAND_SECS. A bundle whose marker doesn't carry it (made before it did: an exported game)
+/// isn't waited on.
+pub(crate) fn landed(app: &mut App, marker: &mut Option<Entity>, n: u64, mut seen: u64, again: &mut dyn FnMut(&mut App) -> R<()>) -> R<()> {
+ let t0 = Instant::now();
+ loop {
+ match marked(app, marker) {
+ Some(m) if m < n => {}
+ _ => return Ok(()),
+ }
+ if t0.elapsed().as_secs_f64() > LAND_SECS {
+ return Err(format!("the props set weren't drawn within {LAND_SECS} s (pass {n})"));
+ }
+ let ask = app.world().get_resource::<raea_runtime_react::layout::LayoutAsk>().map(|a| a.0.clone());
+ seen = raea_runtime_react::wait_flush(seen, Duration::from_millis(100), ask.as_deref());
+ again(app)?;
+ }
+}
+
+/// The props pass the frame marker says has landed (None: no marker, or one that doesn't say).
+fn marked(app: &mut App, marker: &mut Option<Entity>) -> Option<u64> {
+ let w = app.world_mut();
+ let is_marker = |w: &World, e: Entity| w.get::<raea_runtime_react::ReactProps>(e).is_some_and(|p| p.0.contains_key("data-raea-frame"));
+ if !marker.is_some_and(|e| is_marker(w, e)) {
+ let mut q = w.query::<(Entity, &raea_runtime_react::ReactProps)>();
+ *marker = q.iter(w).find(|(_, p)| p.0.contains_key("data-raea-frame")).map(|(e, _)| e);
+ }
+ w.get::<raea_runtime_react::ReactProps>((*marker)?)?.0.get("data-raea-props")?.as_f64().map(|v| v as u64)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn holds(parts: &[(&str, &[(&str, V)])]) -> Holds {
+ parts.iter().map(|(p, cols)| (p.to_string(), cols.iter().map(|(k, v)| (k.to_string(), v.clone())).collect())).collect()
+ }
+
+ /// A model's file changed by a prop is held (its row keeps its first file); its place, which a running world
+ /// takes frame by frame, never counts; a part with nothing kept changed isn't named.
+ #[test]
+ fn what_a_change_held() {
+ assert!(keeps("model", "src") && keeps("mesh", "shape") && keeps("mesh", "surface"));
+ assert!(!keeps("mesh", "x") && !keeps("mesh", "color") && !keeps("mesh", "emissive") && !keeps("model", "name") && !keeps("light", "lux"));
+ let a = holds(&[("model|hero#0", &[("src", V::S("goose.glb".into()))]), ("mesh~box#0", &[("shape", V::S("box 1".into()))])]);
+ let b = holds(&[("model|hero#0", &[("src", V::S("mayor.glb".into()))]), ("mesh~box#0", &[("shape", V::S("box 1".into()))])]);
+ assert_eq!(held(Some(&a), Some(&b)), vec![json!({"part": "model|hero#0", "kind": "model", "cols": ["src"]})]);
+ assert!(held(Some(&a), Some(&a)).is_empty());
+ // a column gone counts as changed; a part new to the frame is a new row, drawn as it is
+ let c = holds(&[("model|hero#0", &[]), ("mesh~ball#0", &[("shape", V::S("sphere".into()))])]);
+ assert_eq!(held(Some(&a), Some(&c)), vec![json!({"part": "model|hero#0", "kind": "model", "cols": ["src"]})]);
+ assert!(held(None, Some(&a)).is_empty());
+ }
+}