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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
H12: what reached the app screens (Routed: routed, logged, read back) in raea-runtime-appscreen, and an app screen's texture handed over as bevy's; live play's needs_react in its own file (raea-runtime-page under 2000 lines, runtime/live/src/lib.rs under 500, no new duplicate groups)
shinyobjectzc30bcfbbef75
diff --git a/Cargo.lock b/Cargo.lockindex 17d37eb8..a178e32a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15004,7 +15004,7 @@ dependencies = ["raea-runtime-jsengine","raea-sys-fonts","raea-sys-page",- "wgpu",+ "serde_json",][[package]]diff --git a/runtime/appscreen/Cargo.toml b/runtime/appscreen/Cargo.tomlindex 55bf87e1..fbc04834 100644--- a/runtime/appscreen/Cargo.toml+++ b/runtime/appscreen/Cargo.toml@@ -10,7 +10,7 @@ description = "App screens (<Screen app>): a module on @raea/ui's react-dom in abevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "bevy_render", "bevy_window"] }blitz-traits = "=0.3.0-beta.4"keyboard-types = "0.8"-wgpu = "=30.0.1"+serde_json = "1"raea-page = { path = "../../engine/page" }raea-runtime-dom = { path = "../dom" }raea-runtime-js = { path = "../js" }diff --git a/runtime/appscreen/src/lib.rs b/runtime/appscreen/src/lib.rsindex 35a49d1a..692f8be8 100644--- a/runtime/appscreen/src/lib.rs+++ b/runtime/appscreen/src/lib.rs@@ -39,6 +39,46 @@ pub struct Input {pub wheel: Vec<f64>,}+/// What reached the app screens in a frame, from live play's routing (runtime/page screen.rs route) or a render's input+/// log of it: the screen with the focus and the keys held for it, the pointer on a screen (its name, x and y on its+/// picture, whether it's down) and the wheel's turns there (`Wheel:Y DY`).+#[derive(Default, Clone, Debug, PartialEq)]+pub struct Routed {+ pub focus: Option<String>,+ pub keys: Vec<String>,+ pub pointer: Option<(String, f64, f64, bool)>,+ pub wheel: Vec<String>,+}++impl Routed {+ /// App screen `name`'s input: the pointer when it's on it (with the wheel turned there), the keys while it has the+ /// focus (a DOM key's name; the live wire's marked keys, "Mouse:Right" or "Pad0:South", aren't keys to it).+ pub fn input_of(&self, name: &str) -> Input {+ let on = self.pointer.as_ref().filter(|p| p.0 == name);+ let focused = self.focus.as_deref() == Some(name);+ Input {+ pointer: on.map(|p| (p.1, p.2, p.3)),+ keys: self.keys.iter().filter(|k| focused && (k.chars().count() == 1 || !k.contains(':'))).cloned().collect(),+ wheel: self.wheel.iter().filter(|_| on.is_some()).filter_map(|w| w.strip_prefix("Wheel:Y ")?.trim().parse().ok()).collect(),+ }+ }++ /// As the input log keeps it (`apps`); None when nothing reached an app screen.+ pub fn logged(&self) -> Option<serde_json::Value> {+ let any = self.focus.is_some() || self.pointer.is_some() || !self.wheel.is_empty();+ any.then(|| serde_json::json!({ "focus": self.focus, "keys": self.keys, "pointer": self.pointer.as_ref().map(|p| serde_json::json!([p.0, p.1, p.2, p.3])), "wheel": self.wheel }))+ }++ /// From a log's entry (`logged`'s); nothing reached them when there's none.+ pub fn from_log(v: Option<&serde_json::Value>) -> Routed {+ let Some(v) = v else { return Routed::default() };+ let texts = |k: &str| v[k].as_array().into_iter().flatten().filter_map(|s| s.as_str().map(String::from)).collect();+ let p = v["pointer"].as_array();+ let pointer = p.and_then(|p| Some((p.first()?.as_str()?.to_string(), p.get(1)?.as_f64()?, p.get(2)?.as_f64()?, p.get(3)?.as_bool()?)));+ Routed { focus: v["focus"].as_str().map(String::from), keys: texts("keys"), pointer, wheel: texts("wheel") }+ }+}+/// Set for the one update a step runs the page's JS in (the draw's later updates, while faces and images load, only/// paint).#[derive(Resource, Default)]@@ -120,8 +160,8 @@ impl AppScreen {/// Its picture as last drawn: its texture on the page's device (sRGB-encoded premultiplied RGBA, as a nested/// <Screen>'s).- pub fn texture(&self) -> Option<wgpu::Texture> {- self.page.texture().map(|t| (*t).clone())+ pub fn texture(&self) -> Option<bevy::render::render_resource::Texture> {+ self.page.texture()}/// Its picture as last drawn, read back: RGBA rows at its size.@@ -245,4 +285,15 @@ mod tests {assert_eq!(key_event("Space", Modifiers::empty(), true).text.as_deref(), Some(" "));assert_eq!(mods_of(&["Shift".into(), "a".into()]), Modifiers::SHIFT);}++ #[test]+ fn the_logged_input_comes_back_the_same() {+ let r = Routed { focus: Some("kit".into()), keys: vec!["a".into(), "Pad0:South".into()], pointer: Some(("kit".into(), 12.5, 40.0, true)), wheel: vec!["Wheel:Y 120".into()] };+ let v = r.logged().unwrap();+ let back = Routed::from_log(Some(&v));+ assert_eq!(back, r);+ assert_eq!(back.input_of("kit"), Input { pointer: Some((12.5, 40.0, true)), keys: vec!["a".into()], wheel: vec![120.0] });+ assert_eq!(back.input_of("other"), Input::default());+ assert_eq!(Routed::from_log(None).logged(), None);+ }}diff --git a/runtime/live/src/lib.rs b/runtime/live/src/lib.rsindex 572e7f1f..4dd8f50a 100644--- a/runtime/live/src/lib.rs+++ b/runtime/live/src/lib.rs@@ -19,6 +19,8 @@ mod pick3d;pub use pick3d::want_wire;pub use sound::warm_audio;mod draw;+mod react;+pub use react::needs_react;type R<T> = Result<T, String>;@@ -326,29 +328,6 @@ fn components_use_config(dir: &Path) -> bool {std::fs::read_dir(dir.join("components")).into_iter().flatten().flatten().any(|e| std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("useVideoConfig(")))}-/// Whether the edit's own sources (its folder, not node_modules) import React Three Fiber (`raea/r3f`,-/// `@react-three/...`): R3F runs a reconciler of its own on React, which live play's runtime (sdk/react/js/lite) isn't,-/// so such a play keeps React, as RAEA_LIVE_REACT=1 does (docs/r3f.feature R3F27)-pub fn needs_react(dir: &Path) -> bool {- fn walk(d: &Path, depth: usize) -> bool {- let Ok(rd) = std::fs::read_dir(d) else { return false };- rd.flatten().any(|e| {- let name = e.file_name();- let name = name.to_string_lossy();- let p = e.path();- if name.starts_with('.') || name == "node_modules" || name == "target" {- false- } else if p.is_dir() {- depth < 4 && walk(&p, depth + 1)- } else {- [".tsx", ".ts", ".jsx", ".js"].iter().any(|x| name.ends_with(x))- && std::fs::read_to_string(&p).is_ok_and(|t| t.contains("raea/r3f") || t.contains("@react-three/"))- }- })- }- walk(dir, 0)-}-/// What a composition's sound is made of: its bundle and every file in its project (path, size, time), hashed, so a/// sound worked out from them (the mastered track) is found again until one of them changes.fn sound_key(js: &Path, dir: &Path) -> u64 {@@ -490,20 +469,3 @@ mod frame_event_tests {}}}--#[cfg(test)]-mod needs_react_tests {- #[test]- fn an_edit_importing_r3f_keeps_react_and_one_whose_packages_do_doesnt() {- let d = std::env::temp_dir().join(format!("raea-needs-react-{}", std::process::id()));- let _ = std::fs::remove_dir_all(&d);- std::fs::create_dir_all(d.join("node_modules/drei")).unwrap();- std::fs::write(d.join("edit.tsx"), "import { Composition } from \"raea\";").unwrap();- std::fs::write(d.join("node_modules/drei/index.js"), "import \"@react-three/fiber\";").unwrap();- assert!(!super::needs_react(&d));- std::fs::create_dir_all(d.join("src/scene")).unwrap();- std::fs::write(d.join("src/scene/ball.tsx"), "import { R3F } from \"raea/r3f\";").unwrap();- assert!(super::needs_react(&d));- let _ = std::fs::remove_dir_all(&d);- }-}diff --git a/runtime/live/src/react.rs b/runtime/live/src/react.rsnew file mode 100644index 00000000..bfb6a1d9--- /dev/null+++ b/runtime/live/src/react.rs@@ -0,0 +1,44 @@+//! Which live plays keep React (docs/r3f.feature R3F27).++use std::path::Path;++/// Whether the edit's own sources (its folder, not node_modules) import React Three Fiber (`raea/r3f`,+/// `@react-three/...`): R3F runs a reconciler of its own on React, which live play's runtime (sdk/react/js/lite) isn't,+/// so such a play keeps React, as RAEA_LIVE_REACT=1 does (docs/r3f.feature R3F27)+pub fn needs_react(dir: &Path) -> bool {+ fn walk(d: &Path, depth: usize) -> bool {+ let Ok(rd) = std::fs::read_dir(d) else { return false };+ rd.flatten().any(|e| {+ let name = e.file_name();+ let name = name.to_string_lossy();+ let p = e.path();+ if name.starts_with('.') || name == "node_modules" || name == "target" {+ false+ } else if p.is_dir() {+ depth < 4 && walk(&p, depth + 1)+ } else {+ [".tsx", ".ts", ".jsx", ".js"].iter().any(|x| name.ends_with(x))+ && std::fs::read_to_string(&p).is_ok_and(|t| t.contains("raea/r3f") || t.contains("@react-three/"))+ }+ })+ }+ walk(dir, 0)+}+++#[cfg(test)]+mod needs_react_tests {+ #[test]+ fn an_edit_importing_r3f_keeps_react_and_one_whose_packages_do_doesnt() {+ let d = std::env::temp_dir().join(format!("raea-needs-react-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(d.join("node_modules/drei")).unwrap();+ std::fs::write(d.join("edit.tsx"), "import { Composition } from \"raea\";").unwrap();+ std::fs::write(d.join("node_modules/drei/index.js"), "import \"@react-three/fiber\";").unwrap();+ assert!(!super::needs_react(&d));+ std::fs::create_dir_all(d.join("src/scene")).unwrap();+ std::fs::write(d.join("src/scene/ball.tsx"), "import { R3F } from \"raea/r3f\";").unwrap();+ assert!(super::needs_react(&d));+ let _ = std::fs::remove_dir_all(&d);+ }+}diff --git a/runtime/page/src/bevy_page.rs b/runtime/page/src/bevy_page.rsindex 02acead8..1b809618 100644--- a/runtime/page/src/bevy_page.rs+++ b/runtime/page/src/bevy_page.rs@@ -162,7 +162,7 @@ impl BevyPage {/// What reached the app screens this frame, for the input log (runtime/page/src/screen.rs `logged`).pub fn app_input(&self) -> Option<Value> {- crate::screen::logged(&self.apps)+ self.apps.r.logged()}/// The page drawn and read back: premultiplied RGBA rows, `w` x `h`.@@ -288,9 +288,8 @@ impl BevyPage {/// Each <Screen>'s picture as last drawn, by name: its texture on the shared device (an app screen's too).pub fn screen_textures(&self) -> Vec<(String, wgpu::Texture)> {- let mut all: Vec<_> = self.page.sub_textures().into_iter().map(|(k, t, _, _)| (k, (*t).clone())).collect();- all.extend(crate::screen::textures(&self.apps));- all+ let apps = crate::screen::textures(&self.apps);+ self.page.sub_textures().into_iter().map(|(k, t, _, _)| (k, t)).chain(apps).map(|(k, t)| (k, (*t).clone())).collect()}/// The page's picture as last drawn, on the shared device (`Rgba8UnormSrgb`, premultiplied).diff --git a/runtime/page/src/screen.rs b/runtime/page/src/screen.rsindex 783ac7e1..fdfee08b 100644--- a/runtime/page/src/screen.rs+++ b/runtime/page/src/screen.rs@@ -10,13 +10,13 @@//! (`step_all`, from the page's sync) and drawn into its picture, which goes to the 3D as a nested screen's does. In//! live play the pointer reaches it through the 3D (`route`: the camera's ray to the screen, Engine::screen_at): a//! press on an app screen gives it the keys, which the game then doesn't get, until a press anywhere else or Escape.-//! What reached the app screens each frame goes in the input log (`logged`), and a render of the log gives them the-//! same (`APP_LOG`), so the render draws what was played.+//! What reached the app screens each frame goes in the input log (Routed::logged), and a render of the log gives them+//! the same (`APP_LOG`), so the render draws what was played.use std::collections::{BTreeMap, HashMap};-use raea_runtime_appscreen::{AppScreen, Input};-use serde_json::{Value, json};+use raea_runtime_appscreen::{AppScreen, Routed};+use serde_json::Value;/// What an app's prebuilt bundle is called beside its module (`chat.tsx` -> `chat.tsx.surface.js`, its CSS/// `chat.tsx.surface.css`): an exported game's (game.rs gather).@@ -35,14 +35,10 @@ pub(crate) struct Apps {pub(crate) frame: Option<(i64, f64)>,/// screens whose app didn't open, with the module (said once)pub(crate) failed: HashMap<String, String>,- /// the app screen the keys go to (the one last pressed on), and the keys held for it- focus: Option<String>,- keys: Vec<String>,- /// where the pointer is on an app screen (its picture's pixels) and whether it's down- pointer: Option<(String, f64, f64, bool)>,+ /// what reaches them this frame: the focus and its keys, the pointer and the wheel+ pub(crate) r: Routed,+ /// whether the pointer was down last frame (a press is its going down)down: bool,- /// the wheel's turns this frame (`Wheel:Y DY`), for the app screen under the pointer- wheel: Vec<String>,}/// Live play's input split between the page and its app screens: the pointer where it lands on an app screen (the@@ -53,39 +49,39 @@ pub fn route(page: &mut crate::BevyPage, engine: &mut raea_render::engine::Enginlet apps = page.app_screens();let a = page.apps();if apps.is_empty() {- a.focus = None;- a.pointer = None;+ a.r.focus = None;+ a.r.pointer = None;return keys.to_vec();}let hit = pointer.and_then(|(x, y, _)| engine.screen_at(x / size.0.max(1) as f64, y / size.1.max(1) as f64));let on = hit.and_then(|(name, u, v)| apps.iter().find(|s| s.0 == name).map(|s| (name, u * s.1 as f64, v * s.2 as f64)));let down = pointer.is_some_and(|p| p.2);if down && !a.down {- a.focus = on.as_ref().map(|o| o.0.clone());+ a.r.focus = on.as_ref().map(|o| o.0.clone());}a.down = down;- a.pointer = on.map(|(name, x, y)| (name, x, y, down));+ let r = &mut a.r;+ r.pointer = on.map(|(name, x, y)| (name, x, y, down));// the wheel over an app screen scrolls it, and the page doesn't get it- a.wheel.clear();- let keys: Vec<String> = match &a.pointer {- Some(_) => keys.iter().filter(|k| !(k.starts_with("Wheel:Y ") && { a.wheel.push(k.to_string()); true })).cloned().collect(),+ r.wheel.clear();+ let keys: Vec<String> = match &r.pointer {+ Some(_) => keys.iter().filter(|k| !(k.starts_with("Wheel:Y ") && { r.wheel.push(k.to_string()); true })).cloned().collect(),None => keys.to_vec(),};- let keys = &keys[..];let (mine, page_keys): (Vec<String>, Vec<String>) = keys.iter().cloned().partition(|k| !(k.starts_with("feed:") || k.starts_with("action:") || k.starts_with("space:")));- match &a.focus {+ match &r.focus {Some(_) if mine.iter().any(|k| k == "Escape") => {- a.focus = None;- a.keys.clear();+ r.focus = None;+ r.keys.clear();page_keys}Some(_) => {- a.keys = mine;+ r.keys = mine;page_keys}None => {- a.keys.clear();- keys.to_vec()+ r.keys.clear();+ keys}}}@@ -98,12 +94,12 @@ pub(crate) fn retire(a: &mut Apps, screens: &[(String, u32, u32, String)]) {// a document goes with its screen, or when the screen shows another module or size (opened again fresh)a.docs.retain(|name, d| screens.iter().any(|s| &s.0 == name && s.3 == d.module && (s.1, s.2) == d.size));let shown = |name: &str| screens.iter().any(|s| s.0 == name);- if a.focus.as_deref().is_some_and(|f| !shown(f)) {- a.focus = None;- a.keys.clear();+ if a.r.focus.as_deref().is_some_and(|f| !shown(f)) {+ a.r.focus = None;+ a.r.keys.clear();}- if a.pointer.as_ref().is_some_and(|p| !shown(&p.0)) {- a.pointer = None;+ if a.r.pointer.as_ref().is_some_and(|p| !shown(&p.0)) {+ a.r.pointer = None;}}@@ -112,7 +108,7 @@ pub(crate) fn retire(a: &mut Apps, screens: &[(String, u32, u32, String)]) {pub(crate) fn step_all(a: &mut Apps, screens: &[(String, u32, u32, String)], dir: &std::path::Path) {let (f, fps) = a.frame.unwrap_or((0, 30.0));if let Some(log) = APP_LOG.lock().unwrap().as_ref() {- set_logged(a, log.get(&f));+ a.r = Routed::from_log(log.get(&f));}for (name, w, h, module) in screens {if a.failed.contains_key(name) || *w == 0 || *h == 0 {@@ -130,69 +126,19 @@ pub(crate) fn step_all(a: &mut Apps, screens: &[(String, u32, u32, String)], dir}}}- let input = input_of(a, name);+ let input = a.r.input_of(name);if let Some(d) = a.docs.get_mut(name) {d.step(f, fps, &input);}}}-/// App screen `name`'s input this frame: the pointer when it's on it (with the wheel turned there), the keys while it-/// has the focus (a DOM key's name; the live wire's marked keys, "Mouse:Right" or "Pad0:South", aren't keys to it).-fn input_of(a: &Apps, name: &str) -> Input {- let on = a.pointer.as_ref().filter(|p| p.0 == name);- let key = |k: &&String| k.chars().count() == 1 || !k.contains(':');- Input {- pointer: on.map(|p| (p.1, p.2, p.3)),- keys: if a.focus.as_deref() == Some(name) { a.keys.iter().filter(key).cloned().collect() } else { Vec::new() },- wheel: if on.is_some() { a.wheel.iter().filter_map(|w| w.strip_prefix("Wheel:Y ")?.trim().parse().ok()).collect() } else { Vec::new() },- }-}--/// What reached the app screens this frame, as the input log keeps it (`apps`): the screen with the focus and its-/// keys, the pointer on a screen (its name, x, y and whether it's down) and the wheel there. None when nothing did.-pub(crate) fn logged(a: &Apps) -> Option<Value> {- if a.focus.is_none() && a.pointer.is_none() && a.wheel.is_empty() {- return None;- }- Some(json!({ "focus": a.focus, "keys": a.keys, "pointer": a.pointer.as_ref().map(|p| json!([p.0, p.1, p.2, p.3])), "wheel": a.wheel }))-}--/// The app screens' input set from a log's entry for the frame (`logged`'s); none when there's none.-fn set_logged(a: &mut Apps, v: Option<&Value>) {- let strings = |v: Option<&Value>| v.and_then(Value::as_array).map(|l| l.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default();- a.focus = v.and_then(|v| v["focus"].as_str()).map(String::from);- a.keys = strings(v.map(|v| &v["keys"]));- a.wheel = strings(v.map(|v| &v["wheel"]));- a.pointer = v.and_then(|v| v["pointer"].as_array()).and_then(|p| Some((p.first()?.as_str()?.to_string(), p.get(1)?.as_f64()?, p.get(2)?.as_f64()?, p.get(3)?.as_bool()?)));-}-/// Each app screen's picture as last drawn, read back: its name, size and RGBA.pub(crate) fn pictures(a: &mut Apps) -> Result<Vec<(String, u32, u32, Vec<u8>)>, String> {a.docs.iter_mut().map(|(name, d)| Ok((name.clone(), d.size.0, d.size.1, d.rgba()?))).collect()}/// Each app screen's picture as last drawn: its texture on the shared device.-pub(crate) fn textures(a: &Apps) -> Vec<(String, wgpu::Texture)> {+pub(crate) fn textures(a: &Apps) -> Vec<(String, bevy::render::render_resource::Texture)> {a.docs.iter().filter_map(|(name, d)| Some((name.clone(), d.texture()?))).collect()}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn the_logged_input_comes_back_the_same() {- let mut a = Apps { focus: Some("kit".into()), keys: vec!["a".into(), "Pad0:South".into()], pointer: Some(("kit".into(), 12.5, 40.0, true)), wheel: vec!["Wheel:Y 120".into()], ..Default::default() };- let v = logged(&a).unwrap();- let mut b = Apps::default();- set_logged(&mut b, Some(&v));- assert_eq!(logged(&b), Some(v));- let i = input_of(&b, "kit");- assert_eq!(i, Input { pointer: Some((12.5, 40.0, true)), keys: vec!["a".into()], wheel: vec![120.0] });- assert_eq!(input_of(&b, "other"), Input::default());- set_logged(&mut a, None);- assert_eq!(logged(&a), None);- }-}-