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.

PV1: the live stage picks 3D parts, a free camera, and props set as it plays

shinyobjectzafb3eb6dc680
diff --git a/apps/media/src/ff.rs b/apps/media/src/ff.rs
index 706cd388..4e5cf69f 100644
--- a/apps/media/src/ff.rs
+++ b/apps/media/src/ff.rs
@@ -170,7 +170,7 @@ pub(crate) fn ffmpeg(args: &[String]) -> R<()> {
if vf.is_some() {
return Err(format!("-vf on a still isn't read here: take the still (raea media still), then crop or scale it in an edit; {VERBS_HINT}"));
}
- still(&path, from.unwrap_or(0.0), Path::new(&out))?;
+ still(&path, from.unwrap_or(0.0), Path::new(&out), None)?;
return Ok(());
}
// video: concat, trim, scale
diff --git a/apps/media/src/lib.rs b/apps/media/src/lib.rs
index f6459fb9..c23f5807 100644
--- a/apps/media/src/lib.rs
+++ b/apps/media/src/lib.rs
@@ -2,7 +2,7 @@
//! What agents used ffmpeg and ffprobe for, on raea-media (the platform's decoders and encoders, Symphonia's audio):
//!
//! raea media probe FILE duration, size, fps, codec, audio (JSON)
-//! raea media still FILE --at S -o OUT.png|.jpg the frame showing at S
+//! raea media still FILE --at S [--width W] -o OUT.png|.jpg the frame showing at S (an image: itself), W px wide at most
//! raea media sheet FILE... [--n 12] [--width 240] -o OUT a contact sheet (n frames of one file, or each file's middle)
//! raea media audio FILE [--rate 16000] [--mono] [--from S --to S] -o OUT.wav|- (- is f32le on stdout)
//! raea media loudness FILE [--from S --to S] integrated LUFS, mean and peak dB, true peak
@@ -116,7 +116,7 @@ fn run(verb: &str, pos: &[String], fl: &BTreeMap<String, String>) -> R<Option<Va
"probe" => probe(&file()?).map(Some),
"still" => {
let at = num(fl, "at")?.unwrap_or(0.0);
- still(&file()?, at, &out()?).map(Some)
+ still(&file()?, at, &out()?, fl.get("width").and_then(|n| n.parse().ok())).map(Some)
}
"sheet" => {
let files: Vec<PathBuf> = pos.iter().map(PathBuf::from).collect();
diff --git a/apps/media/src/picture.rs b/apps/media/src/picture.rs
index cbb80839..1e14dd17 100644
--- a/apps/media/src/picture.rs
+++ b/apps/media/src/picture.rs
@@ -25,12 +25,17 @@ pub(crate) fn frame(path: &Path, t: f64) -> R<image::RgbaImage> {
to_image(d.frame_at(t)?)
}
-pub fn still(path: &Path, at: f64, out: &Path) -> R<Value> {
+/// `width`: the still made that wide (its height in proportion) when the picture is wider; never made bigger.
+pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
let img = if IMAGE_EXTS.contains(&ext(path).as_str()) {
image::open(path).map_err(|e| format!("{}: {e}", path.display()))?.to_rgba8()
} else {
frame(path, at)?
};
+ let img = match width.filter(|w| *w > 0 && *w < img.width()) {
+ Some(w) => image::imageops::resize(&img, w, ((img.height() as f64 * w as f64 / img.width() as f64).round() as u32).max(1), image::imageops::FilterType::CatmullRom),
+ None => img,
+ };
save(&img, out)?;
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
}
diff --git a/apps/play/src/offscreen.rs b/apps/play/src/offscreen.rs
index a038acc4..f5062c93 100644
--- a/apps/play/src/offscreen.rs
+++ b/apps/play/src/offscreen.rs
@@ -48,10 +48,32 @@ pub(crate) fn offscreen(mut run: Run, json: Option<String>, flat_out: bool, snap
// (bench/timelines/check.sh compares these with renders)
let seeks: Vec<(i64, String)> = std::env::args().collect::<Vec<_>>().windows(3).filter(|w| w[0] == "--seek").filter_map(|w| Some((w[1].parse().ok()?, w[2].clone()))).collect();
if !seeks.is_empty() {
+ // --view YAW,PITCH,DISTANCE[,X,Y,Z]: the 3D drawn from that orbit (radians, metres, about X,Y,Z) instead of
+ // the composition's camera; --pick X,Y (repeatable): what's under that point of each seeked frame (page px),
+ // the page and its 3D as one picture, a line of JSON each (docs/preview.feature PV1)
+ let args: Vec<String> = std::env::args().collect();
+ let nums = |flag: &str| -> Vec<Vec<f64>> { args.windows(2).filter(|w| w[0] == flag).map(|w| w[1].split(',').filter_map(|v| v.trim().parse().ok()).collect()).collect() };
+ let view = nums("--view").into_iter().find(|v| v.len() == 3 || v.len() == 6);
+ let picks: Vec<(f64, f64)> = nums("--pick").into_iter().filter(|p| p.len() == 2).map(|p| (p[0], p[1])).collect();
+ let mut said = Vec::new();
for (f, out) in &seeks {
live.step(*f, &[], None)?;
+ if let Some(v) = &view {
+ // the scene's engine opens at the first draw
+ live.snapshot()?;
+ let t = if v.len() == 6 { [v[3] as f32, v[4] as f32, v[5] as f32] } else { [0.0; 3] };
+ if !live.set_view(Some((v[0] as f32, v[1] as f32, v[2] as f32, t))) {
+ return Err("--view: this composition has no 3D to look around".into());
+ }
+ }
live.save_snapshot(std::path::Path::new(out))?;
eprintln!("seek to {f} -> {out}");
+ for (x, y) in &picks {
+ said.push(serde_json::json!({"frame": f, "x": x, "y": y, "pick": live.pick(*x, *y)}).to_string());
+ }
+ }
+ if !said.is_empty() {
+ return Ok(said.join("\n"));
}
return Ok(format!("SEEKED {} frames", seeks.len()));
}
diff --git a/docs/manual/reference/cli/media.md b/docs/manual/reference/cli/media.md
index 8280cc63..66169dd9 100644
--- a/docs/manual/reference/cli/media.md
+++ b/docs/manual/reference/cli/media.md
@@ -30,7 +30,7 @@ what they can't read is refused with the verb or edit that does it.
What agents used ffmpeg and ffprobe for, on raea-media (the platform's decoders and encoders, Symphonia's audio):
raea media probe FILE duration, size, fps, codec, audio (JSON)
- raea media still FILE --at S -o OUT.png|.jpg the frame showing at S
+ raea media still FILE --at S [--width W] -o OUT.png|.jpg the frame showing at S (an image: itself), W px wide at most
raea media sheet FILE... [--n 12] [--width 240] -o OUT a contact sheet (n frames of one file, or each file's middle)
raea media audio FILE [--rate 16000] [--mono] [--from S --to S] -o OUT.wav|- (- is f32le on stdout)
raea media loudness FILE [--from S --to S] integrated LUFS, mean and peak dB, true peak
diff --git a/docs/preview.feature b/docs/preview.feature
new file mode 100644
index 00000000..9b78f247
--- /dev/null
+++ b/docs/preview.feature
@@ -0,0 +1,105 @@
+@spec
+Feature: Preview: anything in a project opens at once, in its space, with its props, and can be pointed at
+ Shane, 2026-11-09: "all components and compositions have a really hard time loading. we should have the ability to
+ recognize how/what it is and view it in 3d space with all that is included and see and mess with props. This will
+ require us to be comprehensive with any type of media, if time is a factor or not or can be seen in playback, if we
+ need to proxy it or not ... a complete proxy management solution and LOD solution. as well we should be turning on
+ selected components for scenes so they're pointable. i have yet to see a single one actually make it so i can point
+ and click on objects in 3d space. and within components, assets, compositions being able to have that level of
+ control is also good. i might even have notes for a 3d asset"
+
+ What there is today (read 11-09):
+ - A component's page shows a still the host renders per change (host/props.ts preview: a throwaway composition and
+ a `raea render`, about 2 s each after a 450 ms wait). No time, no 3D view, nothing in it can be picked.
+ - A composition shows its last render's mp4; with no render it shows nothing until one is made. Live (the bolt)
+ puts the engine's stage in its place, off by default.
+ - A render the host makes carries its layers (review.feature R2c, on by default), so the player's Select picks 3D
+ parts in a finished video. The live stage's pick (stage.pick) is the page's hit test only: over 3D it answers
+ the element holding the scene, never the part. So a game, a Live composition and every component have no
+ pointable 3D.
+ - Proxies are a render's 540-line copy only (host/proxy.ts). Footage, stills, sound and models in a project have
+ none; an asset's card loads the file itself. Nothing lists, sizes or clears them.
+ - An asset opens in the browser or its Mac app; a model has no viewer and nothing can carry a note.
+
+ The model this file sets:
+ 1. One description. Any file in a project has one answer to "what is this": its kind (composition, component,
+ image, video, sound, model, font, document), whether time is part of it (length, rate) and it plays, whether it
+ is 3D, 2D or both, whether it takes input (a game), its props, what it includes (media, components, models),
+ and its weight (bytes, pixels, triangles), from which whether it needs a proxy follows.
+ 2. One proxy store. Every heavy thing has light copies made once and kept by what it was made from: a poster for
+ anything drawn, a 540-line copy for video, peaks for sound, lower levels of detail for a model. The store says
+ what it holds, what each copy is of, its size and state, and is cleared or rebuilt from one place.
+ 3. One preview. A component, a composition and an asset open in the same surface: the poster at once, then the
+ engine's stage playing it live (in the raea app), with the time bar only when time is part of it, a free camera
+ when it is 3D, the outline of what it includes, and its props as controls that change the picture as they move.
+ 4. Everything drawn is pointable. On the live stage as in a render: hover outlines the frontmost thing (a 3D part,
+ an element, a text), a click selects it, and the selection is a place in the code with its props.
+ 5. A note goes on anything: a moment, a part, a point on a model's surface.
+
+ Background:
+ Given the app's code is apps/app (raea-feed) src/compositions, src/detail, host; the engine's is engine/page/stage,
+ runtime/live, systems/frame and systems/layers
+ And plain `raea render FILE -o OUT` output stays as it is: nothing here changes a render's defaults
+
+ Rule: PV1. The live stage picks 3D parts (engine)
+
+ Scenario: PV1a. A part under the pointer
+ Given a composition with 3D meshes playing on the stage
+ When stage.pick is asked a point over a mesh
+ Then it answers that part: its layer key (file:line:col, its list index, its uses), name, kind "mesh", its box
+ on the stage, the point hit in the world and its distance, the nearest mesh along the pointer's ray as the
+ frame was drawn (skinned meshes as posed)
+ And a page element in front of the 3D is answered instead, and the 3D where the page over it is see-through
+
+ Scenario: PV1b. The stage's compositions are stamped
+ Then a composition the stage opens is bundled with its source stamps, so every part and element has its key
+
+ Scenario: PV1c. A free camera
+ When stage.view is given an orbit (yaw, pitch, distance, target) and the scene is 3D
+ Then the frame is drawn from there until stage.view null puts the composition's own camera back
+ And picking uses the camera the frame was drawn from
+
+ Rule: PV2. What a thing is (app host)
+
+ Scenario: PV2a. One description of any file
+ When the host is asked what a project's file is
+ Then it answers kind, timed (seconds, fps), plays, space (2d, 3d, both), input, props, includes and weight, and
+ whether a proxy is needed, for a composition, a component, an image, a video, a sound, a model and a font
+
+ Rule: PV3. Proxies and levels of detail (app host)
+
+ Scenario: PV3a. Every medium has its light copies
+ Then an image has a thumbnail, a video a poster and a 540-line copy, a sound its peaks, a model a poster and
+ lower levels of detail, a composition and a component a poster, each made once and found again by its source's
+ path, size and time
+
+ Scenario: PV3b. The store is managed in one place
+ Then Settings lists the store by project and kind with sizes, and offers Clear and Rebuild; copies whose source
+ is gone are dropped; the store keeps under its limit by dropping the least recently used
+
+ Scenario: PV3c. A model's levels of detail
+ Then a heavy model gets lower levels (triangles halved per level, textures at most 1024 px) and the preview
+ draws the level its size on screen calls for, the full model when still
+
+ Rule: PV4. One preview (app)
+
+ Scenario: PV4a. It opens at once
+ When I open a component, a composition or an asset
+ Then its poster shows in the first frame the page draws, and the live stage takes over when it is ready
+
+ Scenario: PV4b. Props change the picture as they move
+ When I drag a component's number prop
+ Then the stage shows each value without reopening the composition and without a render
+
+ Scenario: PV4c. Time only where there is time
+ Then a still component or an image has no time bar; a timed one plays, loops and scrubs
+
+ Scenario: PV4d. Pointing and selecting
+ When I hover and click a 3D part or an element in the preview
+ Then it is outlined, selected, shown in the outline tree, and its props are the panel's
+
+ Rule: PV5. Notes on anything (app)
+
+ Scenario: PV5a. A note on a model
+ When I click a point on a model in its preview and write a note
+ Then the note is kept with the asset, pinned to that point on that part, and shown there from any camera
diff --git a/engine/page/stage/src/lib.rs b/engine/page/stage/src/lib.rs
index 36162267..1c3ae245 100644
--- a/engine/page/stage/src/lib.rs
+++ b/engine/page/stage/src/lib.rs
@@ -7,10 +7,20 @@
//! stage.show {src, w, h} the composition at `src` (a .tsx), laid out at w x h; src null: nothing
//! 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.pick {x, y} the element under that point of the stage (live.rs element_at), or null
+//! 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
+//! stage.view {yaw, pitch, distance, target} | {free: false}
+//! 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.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
//! 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
@@ -45,10 +55,15 @@ enum Cmd {
Show(Option<PathBuf>, (u32, u32)),
Play(bool),
Step(i64),
+ Seek(i64),
Key(String, bool),
Pointer(f64, f64, bool),
/// the element under a point of the stage, answered from the thread
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<Option<(f32, f32, f32, [f32; 3])>>, Answer),
+ /// props over the composition's defaults, from now
+ Props(Value, 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
@@ -115,6 +130,12 @@ impl Plugin for StagePlugin {
fn build(&self, app: &mut App) {
let image = app.world_mut().resource_mut::<Assets<Image>>().add(Image::new_target_texture(1, 1, TextureFormat::Rgba8UnormSrgb, None));
let stage = Stage { image, slot: Default::default(), status: Default::default(), tx: Default::default() };
+ // what the stage opens is stamped with its place in the code (engine/bundle stamp.rs), so a pick's part or
+ // element has its key (docs/preview.feature PV1b); RAEA_SOURCE_STAMPS=0 in the environment keeps them off
+ if std::env::var_os("RAEA_SOURCE_STAMPS").is_none() {
+ // 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") };
+ }
app.insert_resource(stage)
.init_resource::<HostCalls>()
.add_plugins(ExtractResourcePlugin::<Stage>::default())
@@ -152,6 +173,7 @@ fn calls(mut calls: ResMut<HostCalls>) {
})
.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))));
@@ -169,6 +191,31 @@ fn calls(mut calls: ResMut<HostCalls>) {
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::<Vec<_>>()).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::<Stage>().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::<Stage>().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::<Stage>().tx.lock().unwrap().clone();
@@ -309,6 +356,15 @@ fn run(rx: Receiver<Cmd>, status: Arc<Mutex<Status>>, slot: Arc<Mutex<Painted>>)
}
Some(Cmd::Step(n)) if !playing => steps += n,
Some(Cmd::Step(_)) => {}
+ // the frame before it stands as the last one drawn, and the loop steps to it: one step paused, the clock
+ // from there playing
+ Some(Cmd::Seek(n)) => {
+ frame = n - 1;
+ (base, since) = (n, Instant::now());
+ steps = if playing { 0 } else { 1 };
+ // the input log is a frame each, with nothing held on the frames jumped over
+ log.resize(n.max(0) as usize, (Vec::new(), None));
+ }
Some(Cmd::Key(k, down)) => {
keys.retain(|x| x != &k);
if down {
@@ -317,7 +373,31 @@ 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.element_at(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| on_stage(e, l, stage)).unwrap_or(Value::Null)),
+ 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(()) => {
+ 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"),
+ },
+ Some(Cmd::View(set, answer)) => match live.as_mut() {
+ Some(l) => {
+ if let Some(orbit) = set {
+ repaint = l.set_view(orbit);
+ }
+ answer.ok(l.view().unwrap_or(Value::Null));
+ }
None => answer.ok(Value::Null),
},
Some(Cmd::Inspect(id, answer)) => match live.as_mut() {
@@ -421,5 +501,8 @@ fn on_stage(mut e: Value, l: &raea_runtime_live::Live, size: (u32, u32)) -> Valu
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/render/src/engine/open.rs b/engine/render/src/engine/open.rs
index 529a1f5d..0b2d52eb 100644
--- a/engine/render/src/engine/open.rs
+++ b/engine/render/src/engine/open.rs
@@ -219,6 +219,8 @@ impl Engine {
image.texture_descriptor.view_formats = &[TextureFormat::Rgba8Unorm];
let target = app.world_mut().resource_mut::<Assets<Image>>().add(image);
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));
// 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/bundle/src/entry.rs b/runtime/bundle/src/entry.rs
index 5bce765f..2cda163b 100644
--- a/runtime/bundle/src/entry.rs
+++ b/runtime/bundle/src/entry.rs
@@ -106,7 +106,10 @@ 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)
- const body = useMemo(() => <Catch><C {{...cfg.defaultProps}} />{{(() => {{ const T = (globalThis as any).__raeaToneOut; return T ? <T /> : null; }})()}}</Catch>, {still} ? [] : [f, size, to]);
+ // 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]);
// 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);
@@ -162,7 +165,7 @@ 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 }});
// the composition's element and the Tone graph's output, made once (each frame made them again: lightspeed Z3)
-const COMP = <C {{...cfg.defaultProps}} />;
+let COMP = <C {{...cfg.defaultProps}} />;
let toneEl: any = null;
function toneOut() {{
const T = (globalThis as any).__raeaToneOut;
@@ -197,6 +200,8 @@ 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 = <C {{...cfg.defaultProps}} {{...v}} />; 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) => {{
diff --git a/runtime/live/Cargo.toml b/runtime/live/Cargo.toml
index 3acb718b..ce04d5d6 100644
--- a/runtime/live/Cargo.toml
+++ b/runtime/live/Cargo.toml
@@ -18,6 +18,7 @@ raea-io-net = { path = "../../io/net" }
raea-io-trace = { path = "../../io/trace" }
raea-core-program = { path = "../../core/program" }
raea-sys-mix = { path = "../../systems/mix" }
+raea-sys-frame = { path = "../../systems/frame" }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] }
serde_json = "1"
wgpu = "=30.0.1"
diff --git a/runtime/live/src/lib.rs b/runtime/live/src/lib.rs
index 8613e4ec..5993fb09 100644
--- a/runtime/live/src/lib.rs
+++ b/runtime/live/src/lib.rs
@@ -15,6 +15,7 @@ use raea_runtime_react::{ReactOutbox, ReactPlugin};
mod open;
mod sound;
mod pointer;
+mod pick3d;
pub use sound::warm_audio;
mod draw;
diff --git a/runtime/live/src/pick3d.rs b/runtime/live/src/pick3d.rs
new file mode 100644
index 00000000..7cdcb047
--- /dev/null
+++ b/runtime/live/src/pick3d.rs
@@ -0,0 +1,108 @@
+//! Pointing at the 3D played live (docs/preview.feature PV1): the part under a point of the page, the page's element
+//! and the 3D's part answered as one pick, and a free camera over the scene.
+
+use super::*;
+use raea_sys_frame::view::{FreeView, Orbit};
+
+impl Live {
+ /// The 3D part under the point (`x`, `y` in page px) as the frame was last drawn (raea-sys-frame pick.rs): its
+ /// key, name, box in page px, the point hit in the world and its distance. None with no 3D or over none of it.
+ pub fn part_at(&mut self, x: f64, y: f64) -> Option<Value> {
+ let (w, h) = (self.w.max(1) as f64, self.h.max(1) as f64);
+ let hit = raea_sys_frame::pick::part_at(self.scene.as_mut()?.world_mut(), (x / w) as f32, (y / h) as f32)?;
+ let r = hit.rect;
+ // the part's JSX as React has it now: the 3D element whose own props (data-props, the SDK's JSON) carry the
+ // same stamp, answered as an element is, with those props as its props and its 3D kind as its kind
+ let node = hit.key.as_deref().and_then(|key| {
+ let loc = key.split(['#', '|']).next().unwrap_or(key);
+ let w = self.app.world_mut();
+ let mut q = w.query::<(&raea_runtime_react::ReactNode, &raea_runtime_react::ReactProps)>();
+ q.iter(w).find_map(|(n, p)| {
+ let own = p.0.get("data-props")?.as_str().filter(|t| t.contains(loc))?;
+ let own: serde_json::Map<String, Value> = serde_json::from_str(own).ok()?;
+ (raea_sys_frame::layer::key_from_props(&own).as_deref() == Some(key)).then(|| (n.0, p.0.get("data-3d").cloned().unwrap_or_default(), own))
+ })
+ });
+ let mut out = match node {
+ Some((id, kind, mut own)) => {
+ let mut e = self.element(id).unwrap_or_else(|| json!({"owner": "", "text": ""}));
+ own.retain(|k, v| k != "children" && !k.starts_with("data-raea-") && !v.is_null());
+ e["props"] = Value::Object(own);
+ e["kind"] = kind;
+ e
+ }
+ None => json!({"owner": "", "props": {}, "text": "", "kind": "mesh"}),
+ };
+ out["entity"] = json!(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))] {
+ out[k] = v;
+ }
+ Some(out)
+ }
+
+ /// What's under the point, the page and the 3D as one picture: the page's element when it is in front of the 3D
+ /// (with the part behind it as `under`), else the 3D's part (the page there is the 3D's holder, which shows it
+ /// through), else the element.
+ pub fn pick(&mut self, x: f64, y: f64) -> Option<Value> {
+ let hit = self.page.hit(x as f32, y as f32);
+ let part = self.part_at(x, y);
+ let through = match hit {
+ None => true,
+ Some(id) => {
+ let world = self.app.world();
+ id == raea_runtime_react::ROOT_ID || self.holders.iter().any(|&e| world.get::<raea_runtime_react::ReactNode>(e).is_some_and(|n| n.0 == id))
+ }
+ };
+ match (part, through) {
+ (Some(p), true) => Some(p),
+ (p, _) => {
+ let mut e = self.element(hit?)?;
+ if let Some(k) = e["props"].as_object().and_then(raea_sys_frame::layer::key_from_props) {
+ e["key"] = json!(k);
+ }
+ if let Some(p) = p {
+ e["under"] = p;
+ }
+ Some(e)
+ }
+ }
+ }
+
+ /// 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 {
+ let Some(e) = self.scene.as_mut() else { return false };
+ let Some(mut v) = e.world_mut().get_resource_mut::<FreeView>() else { return false };
+ v.orbit = orbit.map(|(yaw, pitch, distance, t)| Orbit { yaw, pitch, distance, target: Vec3::from(t) });
+ self.dirty = true;
+ true
+ }
+
+ /// The scene's camera as an orbit about the middle of what's drawn, and the scene's radius: where a free camera
+ /// starts from. None with no 3D or no camera.
+ pub fn view(&mut self) -> Option<Value> {
+ let world = self.scene.as_mut()?.world_mut();
+ if let Some(o) = world.get_resource::<FreeView>().and_then(|v| v.orbit) {
+ return Some(json!({"yaw": o.yaw, "pitch": o.pitch, "distance": o.distance, "target": o.target.to_array(), "free": true}));
+ }
+ let (mid, radius) = raea_sys_frame::view::bounds(world).unwrap_or((Vec3::ZERO, 1.0));
+ let mut cams = world.query_filtered::<(&Camera, &GlobalTransform), With<Camera3d>>();
+ let (_, at) = cams.iter(world).filter(|(c, _)| c.is_active).min_by_key(|(c, _)| c.order)?;
+ let o = raea_sys_frame::view::orbit_of(at, mid);
+ 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);
+ }
+}
diff --git a/systems/frame/src/layer.rs b/systems/frame/src/layer.rs
index 50421a33..5f0d1273 100644
--- a/systems/frame/src/layer.rs
+++ b/systems/frame/src/layer.rs
@@ -56,7 +56,7 @@ pub fn record(world: &mut World, f: i64) {
}
/// A mesh's vertices in the world: posed by its joints' matrices (a skin's, in place of its transform) or `place`.
-fn posed(mesh: &Mesh, pos: &[[f32; 3]], joints: Option<&[Mat4]>, place: Mat4) -> Vec<Vec3> {
+pub(crate) fn posed(mesh: &Mesh, pos: &[[f32; 3]], joints: Option<&[Mat4]>, place: Mat4) -> Vec<Vec3> {
use bevy::mesh::VertexAttributeValues as A;
let joints = joints.filter(|_| !raea_sys_layers::mutant("bind"));
let skin = joints.zip(mesh.try_attribute_option(Mesh::ATTRIBUTE_JOINT_INDEX).ok().flatten()).zip(mesh.try_attribute_option(Mesh::ATTRIBUTE_JOINT_WEIGHT).ok().flatten());
diff --git a/systems/frame/src/lib.rs b/systems/frame/src/lib.rs
index f1f5b5f2..25a17a8b 100644
--- a/systems/frame/src/lib.rs
+++ b/systems/frame/src/lib.rs
@@ -14,6 +14,10 @@ pub mod bevy_api;
pub mod camera;
/// layer keys (docs/review.feature R2)
pub mod layer;
+/// the part under a point of the frame (docs/preview.feature PV1a)
+pub mod pick;
+/// a free camera over the scene (docs/preview.feature PV1c)
+pub mod view;
/// 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
diff --git a/systems/frame/src/pick.rs b/systems/frame/src/pick.rs
new file mode 100644
index 00000000..9e8d557b
--- /dev/null
+++ b/systems/frame/src/pick.rs
@@ -0,0 +1,126 @@
+//! The part under a point of the frame (docs/preview.feature PV1a): the nearest mesh along the pointer's ray from the
+//! frame's camera, as the layer pass draws it (layer.rs: the same camera, skinned meshes as posed), answered as the
+//! nearest part up from it with a LayerKey. What the live stage's pick answers over 3D; a render's layers answer the
+//! same question from its mask.
+
+use bevy::prelude::*;
+
+use crate::layer::{LayerKey, posed};
+
+/// A part hit: its key when it or a parent is stamped, its name, where the ray met it and how far along, and the box
+/// on the frame (x, y, w, h in 0..1) of every mesh of that part.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PartHit {
+ pub key: Option<String>,
+ pub name: String,
+ pub entity: Entity,
+ pub point: Vec3,
+ pub distance: f32,
+ pub rect: [f32; 4],
+}
+
+/// The part under (`nx`, `ny`), 0..1 across and down the frame; None over no mesh, or with no 3D camera.
+pub fn part_at(world: &mut World, nx: f32, ny: f32) -> Option<PartHit> {
+ let mut cams = world.query_filtered::<(&Camera, &GlobalTransform), With<Camera3d>>();
+ let (cam, at) = cams.iter(world).filter(|(c, _)| c.is_active).min_by_key(|(c, _)| c.order)?;
+ let ndc = |z: f32| cam.ndc_to_world(at, Vec3::new(nx * 2.0 - 1.0, 1.0 - ny * 2.0, z));
+ let (near, far) = (ndc(1.0)?, ndc(0.01)?);
+ let dir = (far - near).normalize_or_zero();
+ if dir == Vec3::ZERO {
+ return None;
+ }
+ let clip_from_world = cam.clip_from_view() * Mat4::from(at.affine().inverse());
+ let mut parts = world.query::<(Entity, &Mesh3d, &GlobalTransform, Option<&InheritedVisibility>, Option<&bevy::mesh::skinning::SkinnedMesh>)>();
+ let (meshes, binds) = (world.resource::<Assets<Mesh>>(), world.resource::<Assets<bevy::mesh::skinning::SkinnedMeshInverseBindposes>>());
+ // each mesh drawn: the part it belongs to and its box on the frame, and the nearest hit among them
+ let mut drawn: Vec<(Entity, [f32; 4])> = Vec::new();
+ let mut best: Option<(f32, Vec3, Entity)> = None;
+ for (e, m, place, shown, skin) in parts.iter(world) {
+ if shown.is_some_and(|s| !s.get()) {
+ continue;
+ }
+ let Some(mesh) = meshes.get(&m.0).filter(|m| m.primitive_topology() == bevy::mesh::PrimitiveTopology::TriangleList) else { continue };
+ let Ok(Some(bevy::mesh::VertexAttributeValues::Float32x3(pos))) = mesh.try_attribute_option(Mesh::ATTRIBUTE_POSITION) else { continue };
+ let joints = skin.and_then(|s| Some((s, binds.get(&s.inverse_bindposes)?))).map(|(s, b)| s.joints.iter().zip(b.iter()).map(|(j, ib)| world.get::<GlobalTransform>(*j).map_or(Mat4::IDENTITY, |g| Mat4::from(g.affine()) * *ib)).collect::<Vec<_>>());
+ let posed = posed(mesh, pos, joints.as_deref(), Mat4::from(place.affine()));
+ let root = root_of(world, e);
+ let (mut lo, mut hi) = (Vec2::splat(f32::MAX), Vec2::splat(f32::MIN));
+ for p in &posed {
+ let c = clip_from_world * p.extend(1.0);
+ if c.w > 1e-5 {
+ let s = Vec2::new((c.x / c.w + 1.0) * 0.5, (1.0 - c.y / c.w) * 0.5);
+ (lo, hi) = (lo.min(s), hi.max(s));
+ }
+ }
+ if lo.x <= hi.x {
+ drawn.push((root, [lo.x, lo.y, hi.x, hi.y]));
+ }
+ let corners: Vec<usize> = match mesh.try_indices_option() {
+ Ok(Some(ix)) => ix.iter().collect(),
+ _ => (0..posed.len()).collect(),
+ };
+ for t in corners.chunks_exact(3) {
+ let (Some(p0), Some(p1), Some(p2)) = (posed.get(t[0]), posed.get(t[1]), posed.get(t[2])) else { continue };
+ if let Some(d) = ray_tri(near, dir, *p0, *p1, *p2) {
+ if best.is_none_or(|b| d < b.0) {
+ best = Some((d, near + dir * d, root));
+ }
+ }
+ }
+ }
+ let (distance, point, root) = best?;
+ let rect = drawn.iter().filter(|(r, _)| *r == root).fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |a, (_, b)| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]);
+ let (x0, y0, x1, y1) = (rect[0].clamp(0.0, 1.0), rect[1].clamp(0.0, 1.0), rect[2].clamp(0.0, 1.0), rect[3].clamp(0.0, 1.0));
+ Some(PartHit {
+ key: world.get::<LayerKey>(root).map(|k| k.0.clone()),
+ name: world.get::<Name>(root).map_or("mesh".into(), |n| n.as_str().to_string()),
+ entity: root,
+ point,
+ distance,
+ rect: [x0, y0, x1 - x0, y1 - y0],
+ })
+}
+
+/// 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;
+ loop {
+ if world.get::<LayerKey>(at).is_some() {
+ return at;
+ }
+ match world.get::<ChildOf>(at) {
+ Some(p) => at = p.parent(),
+ None => return e,
+ }
+ }
+}
+
+/// Where along the ray (origin `o`, unit direction `d`) it meets the triangle, either face (Möller-Trumbore).
+pub fn ray_tri(o: Vec3, d: Vec3, p0: Vec3, p1: Vec3, p2: Vec3) -> Option<f32> {
+ let (e1, e2) = (p1 - p0, p2 - p0);
+ let pv = d.cross(e2);
+ let det = e1.dot(pv);
+ if det.abs() < 1e-12 {
+ return None;
+ }
+ let tv = o - p0;
+ let u = tv.dot(pv) / det;
+ let qv = tv.cross(e1);
+ let v = d.dot(qv) / det;
+ let t = e2.dot(qv) / det;
+ (u >= 0.0 && v >= 0.0 && u + v <= 1.0 && t > 0.0).then_some(t)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_ray_meets_the_triangle_in_front_of_it_and_not_one_beside_or_behind() {
+ let (a, b, c) = (Vec3::new(-1.0, -1.0, -5.0), Vec3::new(1.0, -1.0, -5.0), Vec3::new(0.0, 1.0, -5.0));
+ assert_eq!(ray_tri(Vec3::ZERO, Vec3::NEG_Z, a, b, c), Some(5.0));
+ assert_eq!(ray_tri(Vec3::ZERO, Vec3::NEG_Z, c, b, a), Some(5.0), "either face");
+ assert_eq!(ray_tri(Vec3::new(3.0, 0.0, 0.0), Vec3::NEG_Z, a, b, c), None, "beside it");
+ assert_eq!(ray_tri(Vec3::ZERO, Vec3::Z, a, b, c), None, "behind the ray");
+ }
+}
diff --git a/systems/frame/src/view.rs b/systems/frame/src/view.rs
new file mode 100644
index 00000000..f16abb08
--- /dev/null
+++ b/systems/frame/src/view.rs
@@ -0,0 +1,117 @@
+//! A free camera over a scene (docs/preview.feature PV1c): while `FreeView` holds an orbit, the frame's camera is put
+//! there after the composition's rows have placed it and before transforms propagate, so the frame is drawn (and
+//! picked: pick.rs reads the same camera) from the orbit. Cleared, the camera goes back to where the composition last
+//! put it. Nothing in the composition's rows changes.
+
+use bevy::prelude::*;
+
+/// An orbit about `target`: `yaw` about +Y from +Z, `pitch` up from the ground plane (radians), `distance` metres.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Orbit {
+ pub yaw: f32,
+ pub pitch: f32,
+ pub distance: f32,
+ pub target: Vec3,
+}
+
+impl Orbit {
+ pub fn transform(&self) -> Transform {
+ let pitch = self.pitch.clamp(-1.553, 1.553);
+ let dir = Vec3::new(self.yaw.sin() * pitch.cos(), pitch.sin(), self.yaw.cos() * pitch.cos());
+ Transform::from_translation(self.target + dir * self.distance.max(1e-3)).looking_at(self.target, Vec3::Y)
+ }
+}
+
+/// The orbit the frame is drawn from, if any; and what the override last wrote and what the composition had put
+/// there, to tell the composition's own moves from the override's and to put its camera back.
+#[derive(Resource, Default)]
+pub struct FreeView {
+ pub orbit: Option<Orbit>,
+ wrote: Option<Transform>,
+ own: Option<Transform>,
+}
+
+/// PostUpdate, before transforms propagate.
+pub fn apply(mut view: ResMut<FreeView>, mut cams: Query<(&Camera, &mut Transform), With<Camera3d>>) {
+ // the frame's camera, as pick.rs and layer.rs choose it
+ let Some(mut t) = cams.iter_mut().filter(|(c, _)| c.is_active).min_by_key(|(c, _)| c.order).map(|(_, t)| t) else { return };
+ // a transform that isn't what the override wrote is the composition's own, placed since
+ if view.wrote != Some(*t) {
+ view.own = Some(*t);
+ }
+ match view.orbit {
+ Some(o) => {
+ let to = o.transform();
+ if *t != to {
+ *t = to;
+ }
+ view.wrote = Some(to);
+ }
+ None => {
+ if let (Some(_), Some(own)) = (view.wrote.take(), view.own) {
+ *t = own;
+ }
+ }
+ }
+}
+
+/// The orbit that looks at the scene as its camera does now: the same place, about the point `ahead` metres along
+/// its view (the scene's middle when the caller knows it).
+pub fn orbit_of(camera: &GlobalTransform, target: Vec3) -> Orbit {
+ let off = camera.translation() - target;
+ let distance = off.length().max(1e-3);
+ Orbit { yaw: off.x.atan2(off.z), pitch: (off.y / distance).clamp(-1.0, 1.0).asin(), distance, target }
+}
+
+/// The middle and radius of everything drawn (every shown mesh's place), for a camera to frame.
+pub fn bounds(world: &mut World) -> Option<(Vec3, f32)> {
+ let mut q = world.query::<(&GlobalTransform, &bevy::camera::primitives::Aabb, Option<&InheritedVisibility>)>();
+ let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
+ for (g, a, shown) in q.iter(world) {
+ if shown.is_some_and(|s| !s.get()) {
+ continue;
+ }
+ let (c, h) = (Vec3::from(a.center), Vec3::from(a.half_extents));
+ for k in 0..8 {
+ let corner = c + h * Vec3::new(if k & 1 == 0 { -1.0 } else { 1.0 }, if k & 2 == 0 { -1.0 } else { 1.0 }, if k & 4 == 0 { -1.0 } else { 1.0 });
+ let p = g.transform_point(corner);
+ (lo, hi) = (lo.min(p), hi.max(p));
+ }
+ }
+ (lo.x <= hi.x).then(|| ((lo + hi) * 0.5, ((hi - lo) * 0.5).length()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn an_orbit_read_from_a_camera_puts_the_camera_back_where_it_was() {
+ let cam = Transform::from_xyz(3.0, 4.0, 5.0).looking_at(Vec3::new(0.0, 1.0, 0.0), Vec3::Y);
+ let o = orbit_of(&GlobalTransform::from(cam), Vec3::new(0.0, 1.0, 0.0));
+ let back = o.transform();
+ assert!(back.translation.distance(cam.translation) < 1e-4, "{:?}", back.translation);
+ assert!(back.rotation.angle_between(cam.rotation) < 1e-3);
+ }
+
+ #[test]
+ fn the_override_holds_the_camera_and_gives_it_back() {
+ let mut app = App::new();
+ app.init_resource::<FreeView>().add_systems(PostUpdate, apply);
+ let own = Transform::from_xyz(0.0, 0.0, 5.0);
+ let cam = app.world_mut().spawn((Camera3d::default(), Camera::default(), own)).id();
+ app.update();
+ let orbit = Orbit { yaw: 1.0, pitch: 0.3, distance: 4.0, target: Vec3::ZERO };
+ app.world_mut().resource_mut::<FreeView>().orbit = Some(orbit);
+ app.update();
+ assert_eq!(*app.world().get::<Transform>(cam).unwrap(), orbit.transform());
+ // the composition moves its camera meanwhile: that is where it goes back to
+ let moved = Transform::from_xyz(1.0, 2.0, 3.0);
+ *app.world_mut().get_mut::<Transform>(cam).unwrap() = moved;
+ app.update();
+ assert_eq!(*app.world().get::<Transform>(cam).unwrap(), orbit.transform());
+ app.world_mut().resource_mut::<FreeView>().orbit = None;
+ app.update();
+ assert_eq!(*app.world().get::<Transform>(cam).unwrap(), moved);
+ }
+}