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.

DR1: raea world reads a frame into one world of facts

shinyobjectzca543072235b
diff --git a/Cargo.lock b/Cargo.lock
index f4c56f59..696f12e1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13593,6 +13593,7 @@ name = "raea-app-check"
version = "0.1.0"
dependencies = [
"raea-core-brief",
+ "raea-core-facts",
"serde_json",
]
@@ -13605,6 +13606,15 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-app-direction"
+version = "0.1.0"
+dependencies = [
+ "raea-runtime-bundle",
+ "raea-runtime-world",
+ "serde_json",
+]
+
[[package]]
name = "raea-app-game"
version = "0.1.0"
@@ -13931,6 +13941,7 @@ dependencies = [
"bevy",
"raea-app-check",
"raea-app-ci",
+ "raea-app-direction",
"raea-app-game",
"raea-app-judge",
"raea-app-media",
@@ -15085,6 +15096,23 @@ dependencies = [
"wgpu",
]
+[[package]]
+name = "raea-runtime-world"
+version = "0.1.0"
+dependencies = [
+ "bevy",
+ "raea-core-facts",
+ "raea-core-scene",
+ "raea-runtime-bake",
+ "raea-runtime-bundle",
+ "raea-runtime-page",
+ "raea-runtime-react",
+ "raea-runtime-scene",
+ "raea-sys-layers",
+ "serde_json",
+ "sha2 0.10.9",
+]
+
[[package]]
name = "raea-sdk-props"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 4f4e0e94..bfd7d778 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -123,6 +123,7 @@ members = [
"runtime/dom/media",
"runtime/edit",
"runtime/view",
+ "runtime/world",
"runtime/encode",
"runtime/plugins",
"runtime/input",
@@ -150,6 +151,7 @@ members = [
"runtime/scene2d",
"runtime/shared",
"apps/check",
+ "apps/direction",
"apps/workspace",
"apps/workspace/registry",
"apps/ci",
diff --git a/apps/check/Cargo.toml b/apps/check/Cargo.toml
index 5bb7e74a..88f66cf8 100644
--- a/apps/check/Cargo.toml
+++ b/apps/check/Cargo.toml
@@ -9,4 +9,6 @@ description = "`raea check`: the floor's measurable lines on an export, ranked P
[dependencies]
# taste.ts rules, as the raea CLI evaluates them (docs/projects.feature PJ0)
raea-core-brief = { path = "../../core/brief" }
+# a transcript's words, read as `raea world` reads them (docs/direction.feature DR1)
+raea-core-facts = { path = "../../core/facts" }
serde_json = "1"
diff --git a/apps/check/src/text.rs b/apps/check/src/text.rs
index fddcbc9d..5f795ba8 100644
--- a/apps/check/src/text.rs
+++ b/apps/check/src/text.rs
@@ -251,30 +251,15 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
}
}
-pub(crate) struct Word {
- pub(crate) text: String,
- pub(crate) start: f64,
- /// when the word ends, in seconds (its start when the transcript doesn't say)
- pub(crate) end: f64,
-}
+/// A transcript's word: its text, start and end in seconds (its end is its start when the transcript doesn't say).
+pub(crate) use raea_core_facts::Word;
-/// raea's transcript shape (an array of {text|word, start|from|start_ms, …}), or a flat array of {w, t}
-/// A transcript's words: {text, start} in seconds (or t, or start_ms), or {text, from} in frames at `fps`, as the app's
-/// words.json and `raea render --words` have them.
+/// A transcript's words (raea_core_facts::transcript_words: {text, start} in seconds, or t, start_ms, or {text, from}
+/// in frames at `fps`), as the app's words.json and `raea render --words` have them.
pub(crate) fn transcript(path: &str, fps: f64) -> R<Vec<Word>> {
let v: Value = serde_json::from_str(&std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?).map_err(|e| format!("{path}: {e}"))?;
- let list = v.as_array().ok_or_else(|| format!("{path}: expected an array of words ({{text, start}} in seconds or {{text, from}} in frames)"))?;
- Ok(list
- .iter()
- .filter_map(|w| {
- let text = w.get("text").or_else(|| w.get("word")).or_else(|| w.get("w"))?.as_str()?.to_string();
- // the time keys a transcript may use, each with what turns it into seconds
- let secs = |keys: &[(&str, f64)]| keys.iter().find_map(|(k, to_s)| Some(w.get(*k)?.as_f64()? * to_s));
- let start = secs(&[("start", 1.0), ("t", 1.0), ("a", 1.0), ("start_ms", 0.001), ("from", 1.0 / fps)])?;
- let end = secs(&[("end", 1.0), ("b", 1.0), ("end_ms", 0.001), ("to", 1.0 / fps)]).unwrap_or(start);
- Some(Word { text, start, end })
- })
- .collect())
+ v.as_array().ok_or_else(|| format!("{path}: expected an array of words ({{text, start}} in seconds or {{text, from}} in frames)"))?;
+ Ok(raea_core_facts::transcript_words(&v, fps))
}
pub(crate) fn norm(s: &str) -> String {
diff --git a/apps/direction/Cargo.toml b/apps/direction/Cargo.toml
new file mode 100644
index 00000000..581d4de6
--- /dev/null
+++ b/apps/direction/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "raea-app-direction"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "How raea takes direction (docs/direction.feature): `raea world`, a composition's frame as one world of facts, queried across media"
+
+[dependencies]
+raea-runtime-world = { path = "../../runtime/world" }
+raea-runtime-bundle = { path = "../../runtime/bundle" }
+serde_json = "1"
diff --git a/apps/direction/src/lib.rs b/apps/direction/src/lib.rs
new file mode 100644
index 00000000..c2fadfec
--- /dev/null
+++ b/apps/direction/src/lib.rs
@@ -0,0 +1,5 @@
+//! How raea takes direction (docs/direction.feature). `raea world` (world.rs): a composition's frame as one world of
+//! facts, its 3D, page and timeline as entities with components, printed or queried across media.
+
+mod world;
+pub use world::{cli, find, Find, USAGE};
diff --git a/apps/direction/src/world.rs b/apps/direction/src/world.rs
new file mode 100644
index 00000000..629d41f7
--- /dev/null
+++ b/apps/direction/src/world.rs
@@ -0,0 +1,177 @@
+//! `raea world EDIT.tsx`: a composition's frame as one world (docs/direction.feature DR1), read with React stepped and
+//! nothing drawn; the page laid out unless `--no-layout`. `--find` is one query of it, raea/ecs's find: the entities
+//! with every component `with` names, none `without` names, and each `where` field equal (`"Layer.medium": "2d-type"`).
+
+use raea_runtime_world::{Ask, Entity, Facts};
+use raea_runtime_bundle::flag;
+use serde_json::{json, Value};
+
+pub const USAGE: &str = "raea world EDIT.tsx [--composition ID] [--frame N | --at A-B|A,B] [--find JSON] [--no-layout] [--json] (a frame as one world: its layers, text, parts, camera, shots, clips, cues and lines as entities with components, each measured; --find '{\"with\": [\"Text\", \"Layer\"], \"where\": {\"Layer.medium\": \"2d-type\"}}' is one query across media)";
+
+/// A query: the components an entity has, those it hasn't, and fields (Component.field.field) equal to a value.
+#[derive(Debug, Default, PartialEq)]
+pub struct Find {
+ pub with: Vec<String>,
+ pub without: Vec<String>,
+ pub fields: Vec<(String, Value)>,
+}
+
+impl Find {
+ pub fn parse(s: &str) -> Result<Find, String> {
+ let v: Value = serde_json::from_str(s).map_err(|e| format!("--find takes JSON ({{\"with\": [...], \"without\": [...], \"where\": {{\"Comp.field\": value}}}}): {e}"))?;
+ let names = |k: &str| -> Result<Vec<String>, String> {
+ match &v[k] {
+ Value::Null => Ok(Vec::new()),
+ Value::Array(a) => a.iter().map(|n| n.as_str().map(str::to_string).ok_or_else(|| format!("--find's {k} lists component names"))).collect(),
+ _ => Err(format!("--find's {k} is a list of component names")),
+ }
+ };
+ let fields = match &v["where"] {
+ Value::Null => Vec::new(),
+ Value::Object(m) => m.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
+ _ => return Err("--find's where is an object of \"Component.field\": value".into()),
+ };
+ let known = ["with", "without", "where"];
+ if let Some(k) = v.as_object().and_then(|o| o.keys().find(|k| !known.contains(&k.as_str()))) {
+ return Err(format!("--find has no \"{k}\" (it takes with, without and where)"));
+ }
+ Ok(Find { with: names("with")?, without: names("without")?, fields })
+ }
+
+ fn holds(&self, e: &Entity) -> bool {
+ let at = |path: &str| -> Option<&Value> {
+ let mut keys = path.split('.');
+ let mut v = e.components.get(keys.next()?)?;
+ for k in keys {
+ v = v.get(k)?;
+ }
+ Some(v)
+ };
+ self.with.iter().all(|c| e.components.contains_key(c)) && !self.without.iter().any(|c| e.components.contains_key(c)) && self.fields.iter().all(|(p, v)| at(p) == Some(v))
+ }
+}
+
+/// The entities of `w` that `q` finds, in id order.
+pub fn find<'a>(w: &'a Facts, q: &Find) -> Vec<&'a Entity> {
+ w.entities.iter().filter(|e| q.holds(e)).collect()
+}
+
+fn frames(args: &[String]) -> Result<Vec<i64>, String> {
+ let n = |s: &str, k: &str| s.trim().parse::<i64>().map_err(|_| format!("{k} takes frame numbers, got \"{s}\""));
+ match (flag(args, "--frame").as_deref(), flag(args, "--at").as_deref()) {
+ (Some(_), Some(_)) => Err("give --frame or --at, not both".into()),
+ (Some(f), None) => Ok(vec![n(f, "--frame")?]),
+ // as render's --at: a list (A,B,C), or a range (A-B), each frame its own world
+ (None, Some(r)) => match r.split_once('-') {
+ Some((a, b)) => {
+ let (a, b) = (n(a, "--at")?, n(b, "--at")?);
+ if b < a {
+ return Err(format!("--at {r} runs backwards"));
+ }
+ Ok((a..=b).collect())
+ }
+ None => r.split(',').map(|f| n(f, "--at")).collect(),
+ },
+ (None, None) => Ok(vec![0]),
+ }
+}
+
+/// One entity as a line: its id, parent and each component's gist.
+fn line(e: &Entity) -> String {
+ let s = raea_runtime_world::text_of;
+ let r2 = |v: &Value| v.as_array().map(|a| a.iter().map(|x| format!("{:.2}", x.as_f64().unwrap_or(0.0))).collect::<Vec<_>>().join(", ")).unwrap_or_default();
+ let mut out = format!("#{}{}", e.id, e.parent.map(|p| format!(" in #{p}")).unwrap_or_default());
+ for (name, c) in &e.components {
+ let gist = match name.as_str() {
+ "Layer" => format!("{} at {}{}", s(&c["medium"]), c["order"], if c["opacity"].as_f64().unwrap_or(1.0) < 1.0 { format!(", opacity {}", c["opacity"]) } else { String::new() }),
+ "Text" => format!("\"{}\"{}{}{}", s(&c["words"]), c["size"].as_f64().map(|v| format!(" {v} px")).unwrap_or_default(), if c["box"].is_array() { format!(" box ({})", r2(&c["box"])) } else { String::new() }, c["needs"].as_str().map(|n| format!(" (needs {n})")).unwrap_or_default()),
+ "Part" => format!("{} \"{}\"{}{}", s(&c["kind"]), s(&c["name"]), if c["min"].is_array() { format!(" box ({}) to ({})", r2(&c["min"]), r2(&c["max"])) } else { " (not measured)".into() }, c["triangles"].as_u64().map(|t| format!(", {t} triangles")).unwrap_or_default()),
+ "Camera" => format!("eye ({}) looking at ({}){}", r2(&c["eye"]), r2(&c["look"]), if c["velocity"].is_array() { format!(", moving ({}) m/s", r2(&c["velocity"])) } else { String::new() }),
+ "Shot" => format!("{} frames {} to {}", c["name"].as_str().unwrap_or("(unnamed)"), c["from"], c["to"].as_i64().map_or("the end".into(), |t| t.to_string())),
+ "Clip" => format!("{} at {}s of it, {} words", s(&c["source"]), c["time"].as_f64().map_or("?".into(), |t| format!("{t:.2}")), c["words"].as_array().map_or(0, Vec::len)),
+ "Cue" => format!("{} from {:.2}s{}", s(&c["source"]), c["at"].as_f64().unwrap_or(0.0), c["gain"].as_f64().map(|g| format!(" at {g} dB")).unwrap_or_default()),
+ "Line" => format!("\"{}\" from {:.2}s{}", s(&c["text"]), c["from"].as_f64().unwrap_or(0.0), c["needs"].as_str().map(|n| format!(" (needs {n})")).unwrap_or_default()),
+ "Source" => format!("{}:{}{}", s(&c["file"]), c["line"], c["component"].as_str().map(|n| format!(" <{n}>")).unwrap_or_default()),
+ _ => c.get("to").map_or_else(|| c.to_string(), |t| format!("#{t}")),
+ };
+ out.push_str(&format!(" {name} {gist}"));
+ }
+ out
+}
+
+fn run(args: &[String]) -> Result<String, String> {
+ let edit = args.iter().find(|a| a.ends_with(".tsx")).ok_or(USAGE)?;
+ let q = flag(args, "--find").as_deref().map(Find::parse).transpose()?;
+ let ask = Ask { frames: frames(args)?, layout: !args.iter().any(|a| a == "--no-layout") };
+ let worlds = raea_runtime_world::read(std::path::Path::new(edit), &raea_runtime_bundle::comp_opts(args)?, &ask)?;
+ if args.iter().any(|a| a == "--json") {
+ let one = |w: &Facts| match &q {
+ Some(q) => json!({"frame": w.frame, "found": find(w, q)}),
+ None => serde_json::to_value(w).unwrap_or(Value::Null),
+ };
+ let v = if worlds.len() == 1 { one(&worlds[0]) } else { Value::Array(worlds.iter().map(one).collect()) };
+ return Ok(serde_json::to_string_pretty(&v).unwrap_or_default());
+ }
+ let mut out = Vec::new();
+ for w in &worlds {
+ let shown = q.as_ref().map_or_else(|| w.entities.iter().collect(), |q| find(w, q));
+ out.push(format!("frame {} ({}x{} at {} fps): {} of {} entities", w.frame, w.width, w.height, w.fps, shown.len(), w.entities.len()));
+ out.extend(shown.into_iter().map(line));
+ }
+ Ok(out.join("\n"))
+}
+
+/// `raea world ...`: its exit code.
+pub fn cli(args: &[String]) -> i32 {
+ let got = run(args);
+ match &got {
+ Ok(s) => println!("{s}"),
+ Err(e) => eprintln!("raea world: {e}"),
+ }
+ if got.is_ok() { 0 } else { 2 }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use raea_runtime_world::{Layer, Medium, Part, Text};
+
+ fn world() -> Facts {
+ let mut w = Facts::new(0, 1920, 1080, 30.0);
+ let lyric = w.spawn(None);
+ w.put(lyric, &Layer { medium: Medium::Type2d, order: 2, opacity: 1.0, blend: None });
+ w.put(lyric, &Text { words: "GIVE IT BACK".into(), font: None, size: Some(96.0), box_: Some([0.1, 0.1, 0.6, 0.2]), extruded: 0.0, lines: Some(1), needs: None });
+ let scene = w.spawn(None);
+ w.put(scene, &Layer { medium: Medium::Scene3d, order: 0, opacity: 1.0, blend: None });
+ let sign = w.spawn(Some(scene));
+ w.put(sign, &Text { words: "OPEN".into(), font: None, size: None, box_: None, extruded: 0.2, lines: Some(1), needs: None });
+ w.put(sign, &Part { kind: "text3d".into(), name: "sign".into(), tags: vec![], at: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], min: None, max: None, triangles: None, src: None, material: None, color: None });
+ let hidden = w.spawn(None);
+ w.put(hidden, &Layer { medium: Medium::Type2d, order: 3, opacity: 1.0, blend: None });
+ w.put(hidden, &Text { words: "UNDER".into(), font: None, size: None, box_: None, extruded: 0.0, lines: None, needs: None });
+ w.relate(hidden, "MaskedBy", sign);
+ w
+ }
+
+ #[test]
+ fn one_find_spans_media() {
+ let w = world();
+ let flat = Find::parse(r#"{"with": ["Text", "Layer"], "where": {"Layer.medium": "2d-type"}, "without": ["MaskedBy"]}"#).unwrap();
+ let got: Vec<u32> = find(&w, &flat).iter().map(|e| e.id).collect();
+ assert_eq!(got, vec![0], "the 2D lyric no part masks, not the 3D sign or the masked line");
+ let words_in_3d = Find::parse(r#"{"with": ["Text", "Part"], "where": {"Text.extruded": 0.2}}"#).unwrap();
+ assert_eq!(find(&w, &words_in_3d).len(), 1);
+ assert!(line(&w.entities[0]).contains("\"GIVE IT BACK\" 96 px box (0.10, 0.10, 0.60, 0.20)"), "{}", line(&w.entities[0]));
+ }
+
+ #[test]
+ fn a_bad_query_or_range_says_what_it_takes() {
+ assert!(Find::parse(r#"{"has": ["Text"]}"#).unwrap_err().contains("no \"has\""));
+ assert!(Find::parse("Text").is_err());
+ let a = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
+ assert_eq!(frames(&a(&["e.tsx", "--at", "3-5"])).unwrap(), vec![3, 4, 5]);
+ assert!(frames(&a(&["--at", "5-3"])).unwrap_err().contains("backwards"));
+ assert_eq!(frames(&a(&["--at", "3,7"])).unwrap(), vec![3, 7], "a list, as render's --at");
+ assert_eq!(frames(&a(&["e.tsx"])).unwrap(), vec![0]);
+ }
+}
diff --git a/core/facts/src/components.rs b/core/facts/src/components.rs
index d950a824..089c8e8d 100644
--- a/core/facts/src/components.rs
+++ b/core/facts/src/components.rs
@@ -100,11 +100,14 @@ pub enum Medium {
/// A composited layer of the frame.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+#[ts(optional_fields)]
pub struct Layer {
pub medium: Medium,
/// its place in the stack, 0 at the back
pub order: u32,
pub opacity: f64,
+ /// how it blends with what's under it (CSS mix-blend-mode), when not normally
+ pub blend: Option<String>,
}
/// A run of type, 2D or 3D. `extruded` is its depth in metres (0: flat).
@@ -120,6 +123,8 @@ pub struct Text {
#[ts(rename = "box")]
pub box_: Option<[f64; 4]>,
pub extruded: f64,
+ /// how many lines it was set on (None: not laid out)
+ pub lines: Option<u32>,
/// what it needs before `size` and `box` are known ("render"), when they aren't
pub needs: Option<String>,
}
@@ -144,6 +149,9 @@ pub struct Part {
pub triangles: Option<u32>,
/// a model's file
pub src: Option<String>,
+ /// what its surface is (the material's kind: "standard", "paint" ...) and its base colour, when it says one
+ pub material: Option<String>,
+ pub color: Option<String>,
}
/// The frame's camera.
@@ -158,25 +166,45 @@ pub struct Camera {
pub ortho: Option<f64>,
pub near: f64,
pub far: f64,
+ /// how its eye moves, metres a second, to the next frame (its move: still, a push, a pan's arc)
+ pub velocity: Option<[f64; 3]>,
}
-/// A stretch between two cuts, in frames.
+/// A stretch between two cuts (a Sequence on the timeline), in composition frames: from its first to its end.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+#[ts(optional_fields)]
pub struct Shot {
+ pub name: Option<String>,
pub from: i64,
- pub to: i64,
+ /// None: it runs to the end
+ pub to: Option<i64>,
}
-/// A piece of footage on the timeline.
+/// A word and its times in seconds.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+pub struct Word {
+ pub text: String,
+ pub start: f64,
+ pub end: f64,
+}
+
+/// A piece of footage on the timeline: its file and the file's SHA-256, the source seconds it shows now and from and
+/// to, the composition frame its first frame falls on, and the words its transcript (TAKE.words.json) has in it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
pub struct Clip {
pub source: String,
- /// seconds into the source this frame shows
+ pub hash: Option<String>,
pub time: Option<f64>,
+ #[serde(rename = "in")]
+ #[ts(rename = "in")]
+ pub in_: f64,
+ pub out: Option<f64>,
+ pub at: i64,
+ pub words: Vec<Word>,
}
-/// A sound placed on the timeline: its source, when it starts (seconds) and its gain in dB.
+/// A sound placed on the timeline: its source, when it starts (seconds), its gain in dB and its bus.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
pub struct Cue {
@@ -186,17 +214,23 @@ pub struct Cue {
pub bus: Option<String>,
}
-/// A sung or spoken line: its words with their times in seconds.
+/// A sung or spoken line: its words, when it starts (seconds) and its words' times. A line raea says (<Speech>) has
+/// no word times until it's transcribed: `needs` says so.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+#[ts(optional_fields)]
pub struct Line {
- pub words: Vec<(String, f64, f64)>,
+ pub text: String,
+ pub from: f64,
+ pub to: Option<f64>,
+ pub words: Vec<Word>,
+ pub needs: Option<String>,
}
/// The components' TypeScript declarations, for a check's types (sdk/raea/src/check.ts is generated from these).
pub fn declarations() -> Vec<String> {
let cfg = Config::default();
macro_rules! decls { ($($t:ty),*) => { vec![$(format!("export {}", <$t as TS>::decl(&cfg))),*] }; }
- decls!(Source, Medium, Layer, Text, Part, Camera, Shot, Clip, Cue, Line)
+ decls!(Source, Medium, Layer, Text, Part, Camera, Shot, Word, Clip, Cue, Line)
}
#[cfg(test)]
@@ -207,9 +241,9 @@ mod tests {
fn a_world_is_found_by_component_and_reads_back() {
let mut w = Facts::new(12, 1920, 1080, 30.0);
let layer = w.spawn(None);
- w.put(layer, &Layer { medium: Medium::Type2d, order: 1, opacity: 1.0 });
+ w.put(layer, &Layer { medium: Medium::Type2d, order: 1, opacity: 1.0, blend: None });
let text = w.spawn(Some(layer));
- w.put(text, &Text { words: "OUT".into(), font: None, size: Some(96.0), box_: Some([0.6, 0.2, 0.9, 0.4]), extruded: 0.0, needs: None });
+ w.put(text, &Text { words: "OUT".into(), font: None, size: Some(96.0), box_: Some([0.6, 0.2, 0.9, 0.4]), extruded: 0.0, lines: Some(1), needs: None });
let seat = w.spawn(None);
let rider = w.spawn(None);
w.relate(rider, "Rides", seat);
diff --git a/core/facts/src/lib.rs b/core/facts/src/lib.rs
index 2a8a5890..de4dfb0e 100644
--- a/core/facts/src/lib.rs
+++ b/core/facts/src/lib.rs
@@ -5,3 +5,14 @@
pub mod components;
pub use components::*;
+
+pub mod words;
+pub use words::transcript_words;
+
+/// A JSON value as text: a string as it is, anything else as its JSON (a list key may be a number, a stamp a string).
+pub fn text_of(v: &serde_json::Value) -> String {
+ match v {
+ serde_json::Value::String(s) => s.clone(),
+ other => other.to_string(),
+ }
+}
diff --git a/core/facts/src/words.rs b/core/facts/src/words.rs
new file mode 100644
index 00000000..3cb3e0cb
--- /dev/null
+++ b/core/facts/src/words.rs
@@ -0,0 +1,36 @@
+//! A transcript's words, in every shape raea's transcripts come in: a project's words.json, a take's
+//! TAKE.words.json, `raea render --words`. What `raea check` (apps/check text.rs) and `raea world` (a Clip's and a
+//! Line's words) both read.
+
+use serde_json::Value;
+
+use crate::Word;
+
+/// The words of a transcript: {text|word|w, start|t|a|start_ms|from, end|b|end_ms|to}, seconds unless the key says
+/// milliseconds or frames at `fps`. A word with no end ends at its start; one with no text or start is left out.
+pub fn transcript_words(v: &Value, fps: f64) -> Vec<Word> {
+ let Some(list) = v.as_array() else { return Vec::new() };
+ list.iter()
+ .filter_map(|w| {
+ let text = w.get("text").or_else(|| w.get("word")).or_else(|| w.get("w"))?.as_str()?.to_string();
+ // the time keys a transcript may use, each with what turns it into seconds
+ let secs = |keys: &[(&str, f64)]| keys.iter().find_map(|(k, to_s)| Some(w.get(*k)?.as_f64()? * to_s));
+ let start = secs(&[("start", 1.0), ("t", 1.0), ("a", 1.0), ("start_ms", 0.001), ("from", 1.0 / fps)])?;
+ let end = secs(&[("end", 1.0), ("b", 1.0), ("end_ms", 0.001), ("to", 1.0 / fps)]).unwrap_or(start);
+ Some(Word { text, start, end })
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_shape_of_word_reads_in_seconds() {
+ let v = serde_json::json!([{"text": "a", "start": 1.0, "end": 1.2}, {"word": "b", "start_ms": 1500, "end_ms": 1700}, {"w": "c", "from": 60, "to": 66}, {"text": "d", "t": 3.0}, {"start": 4.0}]);
+ let w = transcript_words(&v, 30.0);
+ assert_eq!(w.iter().map(|w| (w.text.as_str(), w.start, w.end)).collect::<Vec<_>>(), [("a", 1.0, 1.2), ("b", 1.5, 1.7), ("c", 2.0, 2.2), ("d", 3.0, 3.0)]);
+ assert!(transcript_words(&serde_json::json!({"words": []}), 30.0).is_empty());
+ }
+}
diff --git a/docs/direction.feature b/docs/direction.feature
index 70512208..a6175f9c 100644
--- a/docs/direction.feature
+++ b/docs/direction.feature
@@ -154,30 +154,40 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
Scenario: DR1. A composition's frame as a world, with no render
Given the plan
| crate | file | lines | job |
- | raea-core-facts | core/facts/src/components.rs | 260 | an Item, a page box, a clip, a cue as components (the names and fields below) |
- | raea-runtime-world | runtime/world/src/read.rs | 380 | a composition stepped to a frame (runtime/export's scene_frames) and read into a world: 3D items, the page's laid-out boxes, the timeline |
- | raea-app-direction | apps/direction/src/world.rs | 180 | `raea world`: the frame's world as JSON, or one query of it |
+ | raea-core-facts | core/facts/src/components.rs | 300 | an Item, a page box, a clip, a cue as components (the names and fields below) |
+ | raea-runtime-world | runtime/world/src/lib.rs | 140 | a composition bundled and stepped to its frames, as a bake steps them (React only, nothing drawn), each frame read into a world |
+ | raea-runtime-world | runtime/world/src/scene.rs | 200 | the 3D: plates, the 3D layer with its camera and parts (measured from their triangles), 3D text, the 2D drawn over it |
+ | raea-runtime-world | runtime/world/src/timeline.rs | 330 | the page and timeline: layers in document order, shots (Sequences), clips, cues, lines (the project's words.json, <Speech>) |
+ | raea-runtime-world | runtime/world/src/page.rs | 60 | the page laid out with nothing drawn (BevyPage::lay_out) and read as the render's manifest reads it |
+ | raea-runtime-world | runtime/world/src/source.rs | 90 | Source from the stamps: file, line, the component named at the nearest use, the layer key |
+ | raea-app-direction | apps/direction/src/world.rs | 200 | `raea world`: the frame's world as text or JSON, or one query of it |
And three new crates hold Parts 1 and 2 (raea-cli and raea-runtime-export are at their 2,000-line limits, and
raea-app-check is six lines under its own): core/facts, runtime/world, apps/direction
And a project of any kind: a React video, a footage edit, a page, a game, a 3D scene, or several composited
- When `raea world EDIT.tsx [--composition ID] [--frame N | --frames A-B] [--find JSON] [--json]` runs
+ When `raea world EDIT.tsx [--composition ID] [--frame N | --at A-B|A,B] [--find JSON] [--no-layout] [--json]` runs
Then the frame is one world: its 3D items, timeline, clips and cues read as `raea scene lint` reads a 3D frame
today (React stepped, no engine, no GPU)
- And the page's text and boxes come from the page's layout, which today only a render does (the manifest's
+ And the page's text and boxes come from the page's layout, which before this only a render did (the manifest's
"as laid out", which `raea check --quick` gets by rendering three stills): this scenario adds a layout-only
- pass (the page laid out, nothing painted), and until it lands those entities carry `needs: "render"` (DR2)
+ pass (the render's own page synced and laid out by the main world's schedules, the render world's never run,
+ so nothing is drawn); with `--no-layout`, or where the page can't be made, its text carries `needs: "render"`
And its entities carry these components, each field measured, none typed by the author:
| component | on | fields |
| Source | everything | file, line, the component's name and its use chain (review.feature R2a's key) |
| Layer | each composited layer | medium: "2d-type" / "2d-graphic" / "3d" / "footage" / "page"; order; opacity; blend |
| Text | a run of type, 2D or 3D | words, font, size px at 1080, box in the frame, extruded (depth), lines |
| Part | a 3D mesh or model | component, tags, world box, transform, triangles, materials |
- | Camera | the frame's camera | eye, look, lens or ortho height, near, far |
- | Shot | a stretch between two cuts | from, to, its camera's move |
+ | Camera | the frame's camera | eye, look, lens or ortho height, near, far; its velocity to the next frame (its move) |
+ | Shot | a stretch between two cuts | its name, from, to (a Sequence's box: <Sequence> stamps data-raea-end); the shot around it as its parent |
| Clip | a piece of footage on the timeline | source file and its hash, in, out, at; its words (the transcript's) |
- | Cue | a sound placed on the timeline | source, at, gain; its cause's entity when it has one |
- | Line | a sung or spoken line | words with their times |
- And relations are components too: ChildOf, Rides, Holds, StandsOn, HangsFrom, Masks, MaskedBy, SungAt, CausedBy
+ | Cue | a sound placed on the timeline | source, at, gain, bus |
+ | Line | a sung or spoken line | its words with their times (the project's words.json); a <Speech> line's text and start, `needs: "transcript"` for its times |
+ And relations are components too (`Facts::relate`, `{ to }`): ChildOf is every entity's parent here; Rides, Holds,
+ StandsOn and HangsFrom are set by DR16, Masks and MaskedBy by DR19, SungAt by DR19's lyric checks, CausedBy by DR21
+ # Fixed in the code (DR1): the plan gave a Shot "its camera's move" and a Cue "its cause's entity". A world is one
+ # frame, and a shot's whole move needs every frame of it: each frame's Camera carries its velocity instead, and a
+ # range read (--at A-B) is the shot's move frame by frame. A sound's cause is nothing the tree says yet; DR21
+ # gives a cue its cause, so CausedBy is its to set. A <Speech> line has no word times until it's transcribed.
And a query spans media: "every Text whose Layer is 2d-type and that no Part masks during its Line" is one find
And the same frame gives the same world whenever it's asked for, and a range of frames gives one a frame
diff --git a/engine/bundle/src/stamp.rs b/engine/bundle/src/stamp.rs
index 98db05b0..9f84c463 100644
--- a/engine/bundle/src/stamp.rs
+++ b/engine/bundle/src/stamp.rs
@@ -36,8 +36,8 @@ const PARTS3D: &[&str] = &["raea/3d", "raea/mesh", "raea/sprite", "raea"];
/// The parts among them, by the name they're exported as: what draws a thing on its own. Never a shape or a material
/// inside one (a Mesh3d reads its <Cuboid> child's props, and an extra prop there made it no shape at all).
/// raea's page parts too (an Img, a Video, an AbsoluteFill), whose element is written in the SDK, unstamped: their use
-/// is the layer's place in the code
-const PART_NAMES: &[&str] = &["Mesh3d", "Model", "SceneRoot", "Entity", "Sprite", "Text3D", "Text2d", "ImagePlane", "ShaderMesh", "Plate", "Decal", "Splat", "Grass", "Mesh2d", "Screen", "Img", "Video", "OffthreadVideo", "AbsoluteFill"];
+/// is the layer's place in the code; and an Audio, whose use is its cue's place (`raea world`, docs/direction.feature DR1)
+const PART_NAMES: &[&str] = &["Mesh3d", "Model", "SceneRoot", "Entity", "Sprite", "Text3D", "Text2d", "ImagePlane", "ShaderMesh", "Plate", "Decal", "Splat", "Grass", "Mesh2d", "Screen", "Img", "Video", "OffthreadVideo", "AbsoluteFill", "Audio"];
/// Package components that read their children's types, whose children are left as written (a wrapper there would
/// hide a <Series.Sequence> from its <Series>, a <Cuboid> from its <Mesh3d>): every component of raea's 3D, material,
diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.toml
index 739974f2..ac405cc0 100644
--- a/engine/cli/Cargo.toml
+++ b/engine/cli/Cargo.toml
@@ -50,6 +50,7 @@ raea-neural = { path = "../neural" }
regex = "1"
# the app crates' verbs: `raea check`, `raea ci`, and the local tools' (sao, tokensynth, setup-audio, sounds, splat)
raea-app-check = { path = "../../apps/check" }
+raea-app-direction = { path = "../../apps/direction" }
raea-app-ci = { path = "../../apps/ci" }
raea-app-tools = { path = "../../apps/tools" }
# raea solid info|view: a solid file measured and pictured
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index 4c026fa8..544e1733 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -131,7 +131,7 @@ pub fn run(args: &[String]) -> R<String> {
// a workspace's files and specs (docs/projects.feature), listed under render's usage like library
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Studio unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}", skill::USAGE, tools::blender::USAGE);
let (export_game, scene, physics, splat) = (raea_app_game::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
- let apps = format!(" {}\n {}\n {}\n", raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE);
+ let apps = format!(" {}\n {}\n {}\n {}\n", raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE);
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));
}
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
@@ -202,6 +202,7 @@ pub fn run(args: &[String]) -> R<String> {
if args[0] == "check" {
std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?));
}
+ if args[0] == "world" { std::process::exit(raea_app_direction::cli(&args[1..])); } // a frame as one world of facts (docs/direction.feature DR1)
if args.first().map(String::as_str) == Some("traces") {
return traces(args);
}
diff --git a/engine/cli/src/tests.rs b/engine/cli/src/tests.rs
index cb79602d..58e68685 100644
--- a/engine/cli/src/tests.rs
+++ b/engine/cli/src/tests.rs
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
assert!(missing.is_empty(), "not in raea help: {missing:?}");
- for usage in [raea_app_check::USAGE, raea_app_game::USAGE, raea_runtime_export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, tools::blender::USAGE] {
+ for usage in [raea_app_check::USAGE, raea_app_direction::USAGE, raea_app_game::USAGE, raea_runtime_export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, tools::blender::USAGE] {
assert!(help.contains(usage), "{usage}");
}
}
diff --git a/engine/page/src/motion/manifest.rs b/engine/page/src/motion/manifest.rs
index be36a50d..343e847c 100644
--- a/engine/page/src/motion/manifest.rs
+++ b/engine/page/src/motion/manifest.rs
@@ -114,6 +114,13 @@ impl BlitzPage {
};
let mut t = json!({"text": words.join(" "), "box": [r(b.x), r(b.y), r(b.width), r(b.height)], "opacity": (alpha(owner) * 100.0).round() / 100.0,
"color": color, "size": font.font_size.computed_size().px() as f64, "weight": font.font_weight.value() as f64, "align": align});
+ // its first named face and how many lines it was set on (docs/direction.feature DR1's Text)
+ if let Some(f) = font.font_family.families.iter().find_map(|f| match f { style::values::computed::font::SingleFontFamily::FamilyName(n) => Some(n.name.to_string()), _ => None }) {
+ t["family"] = json!(f);
+ }
+ if let Some(l) = node.element_data().and_then(|e| e.inline_layout_data.as_ref()) {
+ t["lines"] = json!(l.layout.len());
+ }
stamps(owner, &mut t);
text.push(t);
}
diff --git a/engine/page/src/motion/read.rs b/engine/page/src/motion/read.rs
index 21ee7c82..c0ac8c97 100644
--- a/engine/page/src/motion/read.rs
+++ b/engine/page/src/motion/read.rs
@@ -17,6 +17,23 @@ impl BlitzPage {
self.layers();
}
+ /// The page laid out and nothing drawn (`raea world`, docs/direction.feature DR1): the main world's schedules run
+ /// (styles, layout) until its fonts and images are in, the render world's never, so the GPU is given no work. What
+ /// `manifest` and `boxes` read after it is what `draw` would have laid out.
+ pub fn lay_out(&mut self) {
+ for _ in 0..LOADING_UPDATES {
+ // the time the render world sends at each drawn update (bevy_render's send_time), or bevy_time warns
+ if let Some(s) = self.app.get_sub_app(bevy::render::RenderApp).and_then(|r| r.world().get_resource::<bevy::time::TimeSender>()) {
+ let _ = s.0.try_send(std::time::Instant::now());
+ }
+ self.app.main_mut().update();
+ if !self.loading() {
+ break;
+ }
+ std::thread::yield_now();
+ }
+ }
+
/// RAEA_PAGE_DUMP leaves this page out: a page beside the composition's (raea-render's image rows, rows2d.rs) wrote
/// its page.html over the composition's.
pub fn not_dumped(&mut self) {
diff --git a/runtime/bake/src/lib.rs b/runtime/bake/src/lib.rs
index 6b687460..1d85dcfe 100644
--- a/runtime/bake/src/lib.rs
+++ b/runtime/bake/src/lib.rs
@@ -191,6 +191,17 @@ fn runtime(js: &Path) -> App {
app
}
+/// Sorted frames as runs of neighbours, each to step as one range (`step_frames`): 3, 4, 5, 9 are 3..6 and 9..10.
+pub fn runs<'a>(frames: impl IntoIterator<Item = &'a i64>) -> Vec<(i64, i64)> {
+ frames.into_iter().fold(Vec::new(), |mut rs: Vec<(i64, i64)>, &f| {
+ match rs.last_mut() {
+ Some(r) if r.1 == f => r.1 = f + 1,
+ _ => rs.push((f, f + 1)),
+ }
+ rs
+ })
+}
+
/// Frames `a..b` stepped as one range (lightspeed T3): React renders them back to back (raea-frames), with no round
/// trip to Rust between frames, and each frame's commit is applied on its own (OneBatch), `each` reading the world
/// after it. Stepped one event a frame, each frame waited on the JS thread and back: most of an incremental bake.
diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rs
index 4c018859..bc2ab62d 100644
--- a/runtime/export/src/fed.rs
+++ b/runtime/export/src/fed.rs
@@ -90,7 +90,7 @@ pub fn scene_frames(js: &Path, dir: &Path, upto: i64, whole: bool, wanted: &[i64
let scenes = 'scenes: {
if !around.is_empty() && around.len() * 2 < total as usize {
// each run of neighbouring frames stepped as one range, the runs one after another in the one runtime
- let runs = around.iter().fold(Vec::<(i64, i64)>::new(), |mut rs, &f| { match rs.last_mut() { Some(r) if r.1 == f => r.1 = f + 1, _ => rs.push((f, f + 1)) } rs });
+ let runs = raea_runtime_bake::runs(&around);
let stepped: Scenes = runs.into_iter().map(|(a, b)| step(&mut app, a, b)).collect::<R<Vec<_>>>()?.into_iter().flatten().collect();
raea_runtime_react::startup_mark(&format!("the 3D's rows: {} of {total} frames stepped (the wanted ones and their neighbours)", stepped.len()));
if !stepped.iter().any(|s| raea_runtime_scene::carries_state(&s.1)) {
diff --git a/runtime/page/src/bevy_page.rs b/runtime/page/src/bevy_page.rs
index e73fd344..147916df 100644
--- a/runtime/page/src/bevy_page.rs
+++ b/runtime/page/src/bevy_page.rs
@@ -44,12 +44,7 @@ impl BevyPage {
let surf = match self.surf.filter(|e| react.get::<ReactKind>(*e).is_some_and(|k| k.0 == "surface")) {
Some(e) => e,
None => {
- let mut q = react.query::<(Entity, &ReactKind, Option<&ReactProps>)>();
- let e = q
- .iter(react)
- .find(|(_, k, p)| k.0 == "surface" && p.and_then(|p| p.0.get("id")).and_then(Value::as_str) == Some("motion"))
- .map(|(e, _, _)| e)
- .ok_or("the composition's surface isn't there")?;
+ let e = raea_runtime_react::scene::surface(react).ok_or("the composition's surface isn't there")?;
self.surf = Some(e);
e
}
@@ -203,6 +198,11 @@ impl BevyPage {
serde_json::json!({"frame": f, "videos": videos, "text": text})
}
+ /// The page laid out, nothing drawn (`raea world`): what `manifest_frame` and `boxes` read after a `sync`.
+ pub fn lay_out(&mut self) {
+ self.page.lay_out();
+ }
+
/// The page drawn, nothing read back (live play): its picture is `texture`.
pub fn draw(&mut self) {
self.page.draw();
diff --git a/runtime/page/src/world.rs b/runtime/page/src/world.rs
index 18d573e8..461d9eea 100644
--- a/runtime/page/src/world.rs
+++ b/runtime/page/src/world.rs
@@ -191,12 +191,7 @@ pub fn world_page_sync(world: &mut World) {
raea_runtime_react::scene::see_through(&mut p);
holders.insert(n.0, p);
}
- let surf = world
- .query::<(Entity, &ReactKind, Option<&ReactProps>)>()
- .iter(world)
- .find(|(_, k, p)| k.0 == "surface" && p.and_then(|p| p.0.get("id")).and_then(Value::as_str) == Some("motion"))
- .map(|(e, _, _)| e);
- if let Some(surf) = surf {
+ if let Some(surf) = raea_runtime_react::scene::surface(world) {
let (mut videos, mut screens) = (Vec::new(), Vec::new());
SCENE_SLOT.with(|c| c.set(None));
IN_3D.with(|c| c.set(0));
diff --git a/runtime/react/src/scene/holders.rs b/runtime/react/src/scene/holders.rs
index 4c687eb2..05d10974 100644
--- a/runtime/react/src/scene/holders.rs
+++ b/runtime/react/src/scene/holders.rs
@@ -14,8 +14,7 @@ pub fn scene_of(world: &mut World) -> Vec<Node3> {
world.resource_scope(|w, mut k: Mut<Kept3d>| k.of.retain(|e, _| w.get_entity(*e).is_ok()));
}
}
- let mut q = world.query::<(Entity, &ReactKind, Option<&ReactProps>)>();
- let Some(surf) = q.iter(world).find(|(_, k, p)| k.0 == "surface" && p.and_then(|p| p.0.get("id")).and_then(|v| v.as_str()) == Some("motion")).map(|(e, _, _)| e) else { return Vec::new() };
+ let Some(surf) = surface(world) else { return Vec::new() };
// the 3D roots under the surface (a data-3d element stops the walk; its 3D is read3d's), each subtree no commit
// touched since the last scene handed on as it was (read.rs Kept3d); the surface's own straight into the scene, not
// kept and copied out (10 000 cubes beside a turning camera were copied three times a frame; FC1b)
@@ -23,6 +22,12 @@ pub fn scene_of(world: &mut World) -> Vec<Node3> {
world.resource_scope(|world, mut kept: Mut<Kept3d>| { let mut v = Vec::new(); kids3d(world, surf, &mut kept, &dirty, &mut v); v })
}
+/// The composition's surface (`<surface id="motion">`): the element its page and its 3D hang from.
+pub fn surface(world: &mut World) -> Option<Entity> {
+ let mut q = world.query::<(Entity, &ReactKind, Option<&ReactProps>)>();
+ q.iter(world).find(|(_, k, p)| k.0 == "surface" && p.and_then(|p| p.0.get("id")).and_then(|v| v.as_str()) == Some("motion")).map(|(e, _, _)| e)
+}
+
/// The elements holding the 3D (holders_of's), into `out` (ZeroHeap: live play's present asks each frame)
pub fn holder_entities(world: &mut World, out: &mut Vec<Entity>) {
out.clear();
diff --git a/runtime/world/Cargo.toml b/runtime/world/Cargo.toml
new file mode 100644
index 00000000..420d2441
--- /dev/null
+++ b/runtime/world/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "raea-runtime-world"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "A composition's frames read into worlds of facts (docs/direction.feature DR1): React stepped with nothing drawn, its 3D, its page laid out and its timeline as entities with components"
+
+[dependencies]
+raea-core-facts = { path = "../../core/facts" }
+raea-core-scene = { path = "../../core/scene" }
+raea-runtime-scene = { path = "../scene" }
+raea-runtime-react = { path = "../react", default-features = false }
+raea-runtime-bake = { path = "../bake" }
+raea-runtime-bundle = { path = "../bundle" }
+# the page laid out with nothing drawn (BevyPage::lay_out), its text and boxes read as a render's manifest reads them
+raea-runtime-page = { path = "../page" }
+raea-sys-layers = { path = "../../systems/layers" }
+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] }
+serde_json = "1"
+# a clip's file's identity (its SHA-256, as raea's asset store names files)
+sha2 = "0.10"
diff --git a/runtime/world/src/lib.rs b/runtime/world/src/lib.rs
new file mode 100644
index 00000000..26d62408
--- /dev/null
+++ b/runtime/world/src/lib.rs
@@ -0,0 +1,107 @@
+//! A composition's frames read into worlds of facts (docs/direction.feature DR1). React is stepped to each frame as
+//! `raea scene lint` steps it, and nothing is drawn: the frame's 3D items (scene.rs), its page laid out with no paint
+//! (page.rs) and its timeline's shots, clips, cues and lines (timeline.rs) become entities with components
+//! (raea-core-facts), so one query can span every medium a piece has.
+
+mod page;
+mod scene;
+mod source;
+mod timeline;
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::Path;
+
+use bevy::prelude::{App, MinimalPlugins};
+pub use raea_core_facts::*;
+use raea_runtime_bundle::{bundle_composition, CompOpts};
+use raea_core_scene::num;
+use serde_json::Value;
+
+type R<T> = Result<T, String>;
+
+/// What a read is asked for: the frames, and whether the page is laid out (without it, its text carries
+/// `needs: "render"`, as no box or size is known).
+pub struct Ask {
+ pub frames: Vec<i64>,
+ pub layout: bool,
+}
+
+/// One stepped frame: its 3D, its React tree, and its page as laid out.
+struct Snap {
+ scene: Vec<raea_core_scene::Item>,
+ tree: Vec<timeline::El>,
+ laid: Option<Value>,
+}
+
+/// The frames of `tsx`'s composition (`o` picks it) as worlds, one a frame, in `ask.frames`' order. The same frame
+/// gives the same world each time: frames are pure.
+pub fn read(tsx: &Path, o: &CompOpts, ask: &Ask) -> R<Vec<Facts>> {
+ let tsx = tsx.canonicalize().map_err(|e| format!("{}: {e}", tsx.display()))?;
+ let dir = tsx.parent().ok_or("the edit has no folder")?.to_path_buf();
+ let js = std::env::temp_dir().join(format!("raea-world-{}.js", std::process::id()));
+ // every element and part stamped with its place in the code, so each entity has its Source (as the stage's
+ // picks have their keys, engine/page/stage); RAEA_SOURCE_STAMPS=0 in the environment keeps them off
+ if std::env::var_os("RAEA_SOURCE_STAMPS").is_none() {
+ // SAFETY: before any thread of the read starts (the bundler and React's runtime start below)
+ unsafe { std::env::set_var("RAEA_SOURCE_STAMPS", "1") };
+ }
+ bundle_composition(&tsx, &js, o, None)?;
+ let got = stepped(&js, &dir, ask, o.words.as_ref());
+ let _ = std::fs::remove_file(&js);
+ got
+}
+
+fn stepped(js: &Path, dir: &Path, ask: &Ask, words: Option<&Value>) -> R<Vec<Facts>> {
+ use raea_runtime_react::scene::{edit_dir, scene_of, settle};
+ edit_dir(dir);
+ let mut app = App::new();
+ app.add_plugins(MinimalPlugins).add_plugins(raea_runtime_react::ReactPlugin::new(js.to_path_buf()));
+ app.insert_resource(raea_runtime_react::OneBatch::default());
+ let conf = settle(&mut app, Some(-1), 20.0)?.ok_or("the composition's settings didn't arrive")?;
+ let (w, h) = (num(&conf, "width").unwrap_or(1080.0) as u32, num(&conf, "height").unwrap_or(1920.0) as u32);
+ let fps = num(&conf, "fps").unwrap_or(30.0);
+ let length = num(&conf, "frames").unwrap_or(60.0) as i64;
+ if let Some(f) = ask.frames.iter().find(|f| **f < 0 || **f >= length) {
+ return Err(format!("there's no frame {f}: the composition has frames 0 to {}", length - 1));
+ }
+ let wanted: BTreeSet<i64> = ask.frames.iter().copied().collect();
+ // and each one's next frame, for what moves (the camera's velocity)
+ let all: BTreeSet<i64> = wanted.iter().flat_map(|&f| [f, f + 1]).filter(|f| *f < length).collect();
+ let mut page = page::Page::new(ask.layout, w, h, dir);
+ let mut snaps: BTreeMap<i64, Snap> = BTreeMap::new();
+ for (a, b) in raea_runtime_bake::runs(&all) {
+ raea_runtime_bake::step_frames(&mut app, a, b, |app, f| {
+ let world = app.world_mut();
+ let scene = raea_runtime_scene::items_of(&scene_of(world));
+ let (tree, laid) = if wanted.contains(&f) { (timeline::tree(world), page.laid_out(world, f, fps)) } else { (Vec::new(), None) };
+ snaps.insert(f, Snap { scene, tree, laid });
+ Ok(())
+ })?;
+ }
+ let lines = timeline::project_lines(words, dir, fps);
+ Ok(ask
+ .frames
+ .iter()
+ .map(|&f| {
+ let now = &snaps[&f];
+ let mut facts = Facts::new(f, w, h, fps);
+ let mut order = 0u32;
+ scene::put(&mut facts, &now.scene, snaps.get(&(f + 1)).map(|n| &n.scene[..]), fps, dir, &mut order);
+ timeline::put(&mut facts, &now.tree, now.laid.as_ref(), (w, h, fps), dir, &mut order);
+ timeline::put_lines(&mut facts, &lines, &now.tree, f, fps);
+ facts
+ })
+ .collect())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn neighbouring_frames_step_as_one_range() {
+ let s: BTreeSet<i64> = [3, 4, 5, 9, 10, 20].into_iter().collect();
+ assert_eq!(raea_runtime_bake::runs(&s), vec![(3, 6), (9, 11), (20, 21)]);
+ assert!(raea_runtime_bake::runs(&BTreeSet::new()).is_empty());
+ }
+}
diff --git a/runtime/world/src/page.rs b/runtime/world/src/page.rs
new file mode 100644
index 00000000..82fab3fa
--- /dev/null
+++ b/runtime/world/src/page.rs
@@ -0,0 +1,48 @@
+//! The page laid out with nothing drawn (docs/direction.feature DR1): the render's own page (raea-runtime-page's
+//! BevyPage) synced to the frame's React tree and laid out by Blitz, its text and boxes read as a render's manifest
+//! reads them. Made at the first frame that asks, once a read. When it can't be made, the reason is said once and the
+//! frames' text carries `needs: "render"`.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+
+use bevy::prelude::World;
+use serde_json::Value;
+
+pub(crate) struct Page {
+ on: bool,
+ size: (u32, u32),
+ dir: PathBuf,
+ page: Option<raea_runtime_page::BevyPage>,
+ failed: bool,
+}
+
+impl Page {
+ pub(crate) fn new(on: bool, w: u32, h: u32, dir: &Path) -> Page {
+ Page { on, size: (w, h), dir: dir.to_path_buf(), page: None, failed: false }
+ }
+
+ /// Frame `f`'s page as laid out: the render manifest's frame entry ({videos, text}); None when the page isn't
+ /// laid out (not asked for, or it couldn't be).
+ pub(crate) fn laid_out(&mut self, react: &mut World, f: i64, fps: f64) -> Option<Value> {
+ if !self.on || self.failed {
+ return None;
+ }
+ let got = (|| {
+ if self.page.is_none() {
+ self.page = Some(raea_runtime_page::BevyPage::new(self.size.0, self.size.1, &self.dir)?);
+ }
+ let page = self.page.as_mut().ok_or("no page")?;
+ page.at_frame(f, fps);
+ // the elements holding 3D keep their own props: they change what's painted under them, not the layout
+ page.sync(react, &HashMap::new(), None)?;
+ page.lay_out();
+ Ok::<Value, String>(page.manifest_frame(f))
+ })();
+ got.map_err(|e| {
+ eprintln!("raea world: the page wasn't laid out ({e}), so its text has no box or size (needs: \"render\")");
+ self.failed = true;
+ })
+ .ok()
+ }
+}
diff --git a/runtime/world/src/scene.rs b/runtime/world/src/scene.rs
new file mode 100644
index 00000000..55dd2d24
--- /dev/null
+++ b/runtime/world/src/scene.rs
@@ -0,0 +1,161 @@
+//! A frame's 3D as entities: footage behind it (a Plate), the 3D layer with its camera and parts under it, and the 2D
+//! drawn over it (Sprite, Shape2D). Parts are measured from their triangles in the world (core/scene own_tris), as the
+//! clipping check measures them.
+
+use std::path::Path;
+
+use bevy::math::{DVec3, Vec3};
+use raea_core_facts::*;
+use raea_core_scene::{num, vec3, Item};
+use serde_json::Value;
+
+/// The frame's camera, its velocity from where its eye is on the next frame.
+pub(crate) fn camera(its: &[Item], next: Option<&[Item]>, fps: f64) -> Option<Camera> {
+ // where a frame's camera is (raea-runtime-look camera.rs: 5 m back when it doesn't say)
+ fn eye_of(its: &[Item]) -> Option<(&Item, [f64; 3])> {
+ let c = its.iter().find(|i| i.kind == "camera")?;
+ Some((c, vec3(&c.props, "position", [0.0, 0.0, 5.0])))
+ }
+ let (c, eye) = eye_of(its)?;
+ let then = next.and_then(eye_of);
+ Some(Camera {
+ eye,
+ look: vec3(&c.props, "lookAt", [0.0, 0.0, 0.0]),
+ // Bevy's perspective by default (raea-runtime-look camera.rs: 50 degrees), its own near and far when given
+ fov: (!c.props.contains_key("ortho")).then(|| num(&c.props, "fov").unwrap_or(50.0)),
+ ortho: num(&c.props, "ortho"),
+ near: num(&c.props, "near").unwrap_or(0.1),
+ far: num(&c.props, "far").unwrap_or(1000.0),
+ velocity: then.map(|(_, t)| ((DVec3::from_array(t) - DVec3::from_array(eye)) * fps).to_array()),
+ })
+}
+
+/// Text3D's words, size, depth and font from its shape (`text3d("WORDS", size, depth, "font", weight)`).
+pub(crate) fn text3d(shape: &str) -> Option<(String, f64, String)> {
+ let inner = shape.strip_prefix("text3d(")?.strip_suffix(')')?;
+ let (words, rest) = inner.strip_prefix('"')?.split_once('"')?;
+ let mut args = rest.trim_start_matches(',').split(',').map(str::trim);
+ let (_size, depth, font) = (args.next()?, args.next()?.parse().ok()?, args.next()?.trim_matches('"').to_string());
+ Some((words.to_string(), depth, font))
+}
+
+fn f3(v: Vec3) -> [f64; 3] {
+ [v.x as f64, v.y as f64, v.z as f64]
+}
+
+/// A mesh's or model's Part: where it is, its world box and triangles (None when raea can't read its triangles).
+pub(crate) fn part(it: &Item) -> Part {
+ let (scale, rot, at) = it.world.to_scale_rotation_translation();
+ let tris = raea_core_scene::own_tris(it).ok();
+ let (mut lo, mut hi, mut n) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN), 0u32);
+ for (_, ts) in tris.iter().flat_map(|t| t.0.iter()) {
+ for t in ts {
+ n += 1;
+ for p in t.map(|p| it.world.transform_point3(p)) {
+ (lo, hi) = (lo.min(p), hi.max(p));
+ }
+ }
+ }
+ let material = it.material.as_ref();
+ Part {
+ kind: if it.shape.as_deref().is_some_and(|s| s.starts_with("text3d(")) { "text3d".into() } else { it.kind.to_string() },
+ name: raea_core_scene::label(it, ""),
+ tags: Vec::new(),
+ at: f3(at),
+ rotation: [rot.x, rot.y, rot.z, rot.w].map(f64::from),
+ scale: f3(scale),
+ min: (n > 0).then(|| f3(lo)),
+ max: (n > 0).then(|| f3(hi)),
+ triangles: tris.is_some().then_some(n),
+ src: it.props.get("src").and_then(Value::as_str).map(str::to_string),
+ material: material.map(|m| m.kind.to_string()),
+ color: material.and_then(|m| m.props.get("base_color").or_else(|| m.props.get("color"))).and_then(Value::as_str).map(str::to_string),
+ }
+}
+
+fn layer(facts: &mut Facts, parent: Option<u32>, medium: Medium, order: &mut u32) -> u32 {
+ let e = facts.spawn(parent);
+ facts.put(e, &Layer { medium, order: *order, opacity: 1.0, blend: None });
+ *order += 1;
+ e
+}
+
+fn sourced(facts: &mut Facts, e: u32, it: &Item, dir: &Path) {
+ if let Some(s) = crate::source::of(&it.props, dir) {
+ facts.put(e, &s);
+ }
+}
+
+/// The frame's 3D into `facts`, from the back: plates, the 3D layer (camera, parts, 3D text), then 2D over it.
+pub(crate) fn put(facts: &mut Facts, its: &[Item], next: Option<&[Item]>, fps: f64, dir: &Path, order: &mut u32) {
+ for it in its.iter().filter(|i| i.kind == "plate") {
+ let e = layer(facts, None, Medium::Footage, order);
+ let src = it.props.get("src").and_then(Value::as_str).unwrap_or_default();
+ facts.put(e, &Clip { source: raea_core_scene::media_path(dir, src).display().to_string(), hash: None, time: num(&it.props, "time"), in_: 0.0, out: None, at: 0, words: Vec::new() });
+ sourced(facts, e, it, dir);
+ }
+ let shown = |i: &&Item| !matches!(i.kind, "plate" | "sprite" | "shape2d");
+ if its.iter().filter(shown).next().is_some() {
+ let l = layer(facts, None, Medium::Scene3d, order);
+ if let Some(c) = camera(its, next, fps) {
+ let e = facts.spawn(Some(l));
+ facts.put(e, &c);
+ }
+ for it in its.iter().filter(|i| matches!(i.kind, "mesh" | "model" | "text")) {
+ let e = facts.spawn(Some(l));
+ if it.kind == "text" {
+ let words = it.props.get("text").and_then(Value::as_str).unwrap_or_default().to_string();
+ let font = it.props.get("spans").and_then(|s| s.get(0)).and_then(|s| s.get("font")).and_then(Value::as_str).map(str::to_string);
+ facts.put(e, &Text { words, font, size: None, box_: None, extruded: num(&it.props, "depth").unwrap_or(0.0), lines: None, needs: None });
+ } else {
+ if let Some((words, depth, font)) = it.shape.as_deref().and_then(text3d) {
+ facts.put(e, &Text { words, font: Some(font), size: None, box_: None, extruded: depth, lines: Some(1), needs: None });
+ }
+ facts.put(e, &part(it));
+ }
+ sourced(facts, e, it, dir);
+ }
+ }
+ for it in its.iter().filter(|i| matches!(i.kind, "sprite" | "shape2d")) {
+ let e = layer(facts, None, Medium::Graphic2d, order);
+ sourced(facts, e, it, dir);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use bevy::math::Mat4;
+ use std::sync::Arc;
+
+ fn item(kind: &'static str, props: Value, shape: Option<&str>, world: Mat4) -> Item {
+ Item { kind, props: Arc::new(props.as_object().cloned().unwrap_or_default()), shape: shape.map(Arc::from), material: None, world }
+ }
+
+ #[test]
+ fn a_text3d_shape_reads_as_its_words_depth_and_font() {
+ assert_eq!(text3d(r#"text3d("OUT NOW", 0.5, 0.2, "Inter", 800)"#), Some(("OUT NOW".into(), 0.2, "Inter".into())));
+ assert_eq!(text3d("box(1, 1, 1)"), None);
+ }
+
+ #[test]
+ fn the_3d_is_one_layer_with_its_camera_and_measured_parts_under_it() {
+ let cam = |z: f64| item("camera", serde_json::json!({"position": [0.0, 1.0, z], "lookAt": [0.0, 0.0, 0.0], "fov": 35.0}), None, Mat4::IDENTITY);
+ let cube = item("mesh", serde_json::json!({"name": "seat"}), Some("box(2, 1, 1)"), Mat4::from_translation(Vec3::new(3.0, 0.5, 0.0)));
+ let word = item("mesh", serde_json::json!({}), Some(r#"text3d("HI", 0.5, 0.2, "Inter", 800)"#), Mat4::IDENTITY);
+ let mut facts = Facts::new(0, 1920, 1080, 30.0);
+ let mut order = 0;
+ put(&mut facts, &[cam(10.0), cube, word], Some(&[cam(9.0)]), 30.0, Path::new("/nowhere"), &mut order);
+ let layers = facts.find(&["Layer"]);
+ assert_eq!(layers.len(), 1);
+ assert_eq!(facts.get::<Layer>(layers[0].id).unwrap().medium, Medium::Scene3d);
+ let c: Camera = facts.get(facts.find(&["Camera"])[0].id).unwrap();
+ assert_eq!((c.fov, c.velocity), (Some(35.0), Some([0.0, 0.0, -30.0])), "a push in: a metre a frame at 30 fps");
+ let seat: Part = facts.get(facts.find(&["Part"])[0].id).unwrap();
+ assert_eq!((seat.name.as_str(), seat.min, seat.max, seat.triangles), ("seat", Some([2.0, 0.0, -0.5]), Some([4.0, 1.0, 0.5]), Some(12)));
+ let t = facts.find(&["Text", "Part"]);
+ assert_eq!(t.len(), 1, "3D text is a Text and a Part");
+ assert_eq!(facts.get::<Text>(t[0].id).unwrap().extruded, 0.2);
+ assert!(facts.find(&["Part"]).iter().all(|p| p.parent == Some(layers[0].id)));
+ }
+}
diff --git a/runtime/world/src/source.rs b/runtime/world/src/source.rs
new file mode 100644
index 00000000..6320fb2f
--- /dev/null
+++ b/runtime/world/src/source.rs
@@ -0,0 +1,82 @@
+//! Where a thing was written (the Source component): the source stamps an element or part carries (engine/bundle
+//! stamp.rs: data-raea-loc, data-raea-use, data-raea-idx), and the component's name read from the code at its nearest
+//! use, or the tag written at its place when it was drawn in no component of the edit's own.
+
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+
+use raea_core_facts::Source;
+use serde_json::{Map, Value};
+
+thread_local! {
+ /// each source file's lines, read once a read
+ static FILES: RefCell<HashMap<PathBuf, String>> = RefCell::new(HashMap::new());
+}
+
+fn text(props: &Map<String, Value>, k: &str) -> Option<String> {
+ props.get(k).map(raea_core_facts::text_of)
+}
+
+/// "file:line:col" as its file, line and column (1-based).
+fn place(loc: &str) -> Option<(String, u32, u32)> {
+ let mut it = loc.rsplitn(3, ':');
+ let col = it.next()?.parse().ok()?;
+ let line = it.next()?.parse().ok()?;
+ Some((it.next()?.to_string(), line, col))
+}
+
+/// The JSX tag written at `file:line:col` under `dir`: `<Rider` gives "Rider".
+pub(crate) fn tag_at(dir: &Path, loc: &str) -> Option<String> {
+ let (file, line, col) = place(loc)?;
+ let path = dir.join(&file);
+ FILES.with(|f| {
+ let mut f = f.borrow_mut();
+ if !f.contains_key(&path) {
+ let read = std::fs::read_to_string(&path).unwrap_or_default();
+ f.insert(path.clone(), read);
+ }
+ let text = &f[&path];
+ // columns count UTF-16 units, as TypeScript does
+ let units: Vec<u16> = text.lines().nth(line.checked_sub(1)? as usize)?.encode_utf16().collect();
+ let rest = String::from_utf16_lossy(units.get(col.checked_sub(1)? as usize..)?);
+ let tag = rest.strip_prefix('<')?;
+ let name = &tag[..tag.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '.')).unwrap_or(tag.len())];
+ (!name.is_empty()).then(|| name.to_string())
+ })
+}
+
+/// A stamped element's or part's Source; None when it carries no stamp (raea's own elements, a package's).
+pub(crate) fn of(props: &Map<String, Value>, dir: &Path) -> Option<Source> {
+ let loc = text(props, "data-raea-loc")?;
+ let uses = text(props, "data-raea-use").unwrap_or_default();
+ let (file, line, _) = place(&loc)?;
+ let near = uses.split('|').find(|u| !u.is_empty());
+ let component = near.and_then(|u| tag_at(dir, u)).or_else(|| tag_at(dir, &loc));
+ Some(Source { file: Some(file), line: Some(line), component, key: raea_sys_layers::key_from_props(props) })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_stamp_reads_as_its_file_line_and_the_component_used_there() {
+ let dir = std::env::temp_dir().join(format!("raea-world-source-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("promo.tsx"), "export const P = () => (\n <Stage>\n <Rider seat=\"a\" />\n </Stage>\n);\n").unwrap();
+ std::fs::write(dir.join("rider.tsx"), "export const Rider = () => <Mesh3d name=\"body\" />;\n").unwrap();
+ let mut props = Map::new();
+ props.insert("data-raea-loc".into(), Value::String("rider.tsx:1:28".into()));
+ props.insert("data-raea-use".into(), Value::String("promo.tsx:3:5".into()));
+ let s = of(&props, &dir).unwrap();
+ assert_eq!((s.file.as_deref(), s.line), (Some("rider.tsx"), Some(1)));
+ assert_eq!(s.component.as_deref(), Some("Rider"), "the use's component, not the tag inside it");
+ assert!(s.key.as_deref().is_some_and(|k| k.starts_with("rider.tsx:1:28")), "{:?}", s.key);
+ // drawn in no component of the edit's: the tag at its place
+ props.remove("data-raea-use");
+ assert_eq!(of(&props, &dir).unwrap().component.as_deref(), Some("Mesh3d"));
+ assert!(of(&Map::new(), &dir).is_none());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/runtime/world/src/timeline.rs b/runtime/world/src/timeline.rs
new file mode 100644
index 00000000..538f9f16
--- /dev/null
+++ b/runtime/world/src/timeline.rs
@@ -0,0 +1,309 @@
+//! A frame's page and timeline as entities: the page's layers in document order (footage, pictures, runs of text),
+//! its Sequences as shots, its sounds as cues and the lines sung or said on it. The page's text comes from its layout
+//! (page.rs) when it was laid out; else from the tree, with `needs: "render"`.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+
+use bevy::prelude::{Children, World};
+use raea_core_facts::*;
+use raea_runtime_react::{ReactKind, ReactProps, ReactText};
+use raea_core_scene::num;
+use serde_json::{Map, Value};
+
+/// An element (or text node) of the frame's page, in document order, with its parent's index.
+pub(crate) struct El {
+ pub(crate) kind: String,
+ pub(crate) props: Map<String, Value>,
+ pub(crate) text: Option<String>,
+ pub(crate) parent: Option<usize>,
+}
+
+/// The page under the composition's surface, in document order; a 3D holder's 3D is the scene's (scene.rs).
+pub(crate) fn tree(world: &mut World) -> Vec<El> {
+ let Some(surf) = raea_runtime_react::scene::surface(world) else { return Vec::new() };
+ let mut out = Vec::new();
+ let mut stack: Vec<(bevy::ecs::entity::Entity, Option<usize>)> = vec![(surf, None)];
+ while let Some((e, parent)) = stack.pop() {
+ let (Some(kind), props) = (world.get::<ReactKind>(e), world.get::<ReactProps>(e)) else { continue };
+ let el = El { kind: kind.0.clone(), props: props.map(|p| p.0.clone()).unwrap_or_default(), text: world.get::<ReactText>(e).map(|t| t.0.clone()), parent };
+ let holds_3d = el.props.contains_key("data-3d");
+ out.push(el);
+ if let (false, Some(kids)) = (holds_3d, world.get::<Children>(e)) {
+ let at = out.len() - 1;
+ stack.extend(kids.iter().rev().map(|k| (*k, Some(at))));
+ }
+ }
+ out
+}
+
+thread_local! {
+ static HASHES: std::cell::RefCell<HashMap<PathBuf, Option<String>>> = std::cell::RefCell::new(HashMap::new());
+}
+
+/// A file's SHA-256, read once a process.
+fn hash(p: &Path) -> Option<String> {
+ use sha2::{Digest, Sha256};
+ HASHES.with(|h| {
+ h.borrow_mut()
+ .entry(p.to_path_buf())
+ .or_insert_with(|| {
+ let mut f = std::fs::File::open(p).ok()?;
+ let mut d = Sha256::new();
+ std::io::copy(&mut f, &mut d).ok()?;
+ Some(format!("{:x}", d.finalize()))
+ })
+ .clone()
+ })
+}
+
+/// A transcript file's words (raea_core_facts::transcript_words, as `raea check` reads them); none when it isn't one.
+pub(crate) fn words(path: &Path, fps: f64) -> Vec<Word> {
+ std::fs::read_to_string(path).ok().and_then(|s| serde_json::from_str::<Value>(&s).ok()).map_or_else(Vec::new, |v| transcript_words(&v, fps))
+}
+
+/// The project's transcript (its words.json) as lines: a line ends at a stop (. ? !) or a pause of half a second.
+pub(crate) fn project_lines(given: Option<&Value>, dir: &Path, fps: f64) -> Vec<Line> {
+ let mut lines: Vec<Line> = Vec::new();
+ let mut open = true;
+ // the transcript `--words` gives the composition, else the project's words.json
+ for w in given.map_or_else(|| words(&dir.join("words.json"), fps), |v| transcript_words(v, fps)) {
+ match lines.last_mut() {
+ Some(l) if open && w.start - l.to.unwrap_or(l.from) < 0.5 => {
+ l.text = format!("{} {}", l.text, w.text);
+ l.to = Some(w.end);
+ l.words.push(w.clone());
+ }
+ _ => lines.push(Line { text: w.text.clone(), from: w.start, to: Some(w.end), words: vec![w.clone()], needs: None }),
+ }
+ open = !w.text.ends_with(['.', '?', '!']);
+ }
+ lines
+}
+
+/// The lines on frame `f`: the project transcript's that span it, and each line raea says (<Speech>) on it.
+pub(crate) fn put_lines(facts: &mut Facts, lines: &[Line], tree: &[El], f: i64, fps: f64) {
+ let t = f as f64 / fps;
+ for l in lines.iter().filter(|l| l.from <= t && t <= l.to.unwrap_or(l.from)) {
+ let e = facts.spawn(None);
+ facts.put(e, l);
+ }
+ for el in tree {
+ let Some(said) = el.props.get("data-speech").and_then(Value::as_str).and_then(|s| serde_json::from_str::<Value>(s).ok()) else { continue };
+ let text = said["text"].as_str().unwrap_or_default().to_string();
+ let from = said["start"].as_f64().unwrap_or(f as f64) / fps;
+ let e = facts.spawn(None);
+ facts.put(e, &Line { text, from, to: None, words: Vec::new(), needs: Some("transcript".into()) });
+ }
+}
+
+/// A run of text the page laid out (a render manifest's text entry) as a Text, in the frame's 0..1 units, its size
+/// in px of a frame 1080 on its short side.
+pub(crate) fn laid_text(t: &Value, (w, h): (u32, u32)) -> Text {
+ let b: Vec<f64> = t["box"].as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
+ let (w, h) = (w as f64, h as f64);
+ Text {
+ words: t["text"].as_str().unwrap_or_default().to_string(),
+ font: t["family"].as_str().map(str::to_string),
+ size: t["size"].as_f64().map(|s| (s * 1080.0 / w.min(h) * 10.0).round() / 10.0),
+ box_: (b.len() == 4).then(|| [b[0] / w, b[1] / h, (b[0] + b[2]) / w, (b[1] + b[3]) / h].map(|v| (v * 1e4).round() / 1e4)),
+ extruded: 0.0,
+ lines: t["lines"].as_u64().map(|n| n as u32),
+ needs: None,
+ }
+}
+
+fn style(props: &Map<String, Value>, k: &str) -> Option<String> {
+ props.get("style").and_then(|s| s.get(k)).map(text_of)
+}
+
+/// A page layer: its place in document order, what it is, the element it is (its props), and its own components.
+#[derive(Default)]
+struct Paged {
+ at: usize,
+ medium: Option<Medium>,
+ opacity: Option<f64>,
+ props: Option<usize>,
+ text: Option<Text>,
+ clip: Option<Clip>,
+ cue: Option<Cue>,
+ source: Option<Source>,
+}
+
+/// The frame's page and timeline into `facts`, its layers after the 3D's (`order` goes on from there).
+pub(crate) fn put(facts: &mut Facts, tree: &[El], laid: Option<&Value>, (w, h, fps): (u32, u32, f64), dir: &Path, order: &mut u32) {
+ let mut paged: Vec<Paged> = Vec::new();
+ let mut shots: HashMap<usize, u32> = HashMap::new();
+ for (i, el) in tree.iter().enumerate() {
+ let p = &el.props;
+ if let Some(from) = num(p, "data-raea-start").filter(|_| p.contains_key("data-sequence") || p.contains_key("data-raea-end")) {
+ // a Sequence's box: a shot, inside the shot around it
+ let up = std::iter::successors(el.parent, |&k| tree[k].parent).find_map(|k| shots.get(&k).copied());
+ let e = facts.spawn(up);
+ facts.put(e, &Shot { name: p.get("data-sequence").and_then(Value::as_str).map(str::to_string), from: from as i64, to: num(p, "data-raea-end").map(|t| t as i64) });
+ shots.insert(i, e);
+ }
+ let src = p.get("src").and_then(Value::as_str).filter(|s| !s.is_empty());
+ // a URL or an asset reference (a generated sound's `asset:sao/...`) as it is; a file where the render finds it
+ let file = src.map(|s| if s.starts_with("http") || s.starts_with("asset:") { PathBuf::from(s) } else { raea_core_scene::media_path(dir, s) });
+ let sounds = num(p, "data-volume").unwrap_or(1.0) > 0.0 && p.get("data-muted").and_then(Value::as_str) != Some("true");
+ let cue = |file: &Path| Cue {
+ source: file.display().to_string(),
+ at: num(p, "data-from").unwrap_or(0.0) / fps,
+ gain: num(p, "data-gain-db").or_else(|| num(p, "data-volume").map(|v| (20.0 * v.log10() * 10.0).round() / 10.0)),
+ bus: p.get("data-bus").and_then(Value::as_str).map(str::to_string),
+ };
+ match (el.kind.as_str(), file) {
+ ("video", Some(file)) => {
+ let (from, out) = (num(p, "data-start-from").unwrap_or(0.0) / fps, num(p, "data-end-at").map(|t| t / fps));
+ let heard = list_words(&file, fps, from, out);
+ let clip = Clip { source: file.display().to_string(), hash: hash(&file), time: num(p, "data-source-time"), in_: from, out, at: num(p, "data-from").unwrap_or(0.0) as i64, words: heard };
+ let cue = sounds.then(|| cue(&file));
+ paged.push(Paged { at: i, medium: Some(Medium::Footage), props: Some(i), clip: Some(clip), cue, ..Default::default() });
+ }
+ ("audio", Some(file)) if sounds => {
+ let e = facts.spawn(None);
+ facts.put(e, &cue(&file));
+ if let Some(s) = crate::source::of(p, dir) {
+ facts.put(e, &s);
+ }
+ }
+ ("img", Some(_)) => paged.push(Paged { at: i, medium: Some(Medium::Graphic2d), props: Some(i), ..Default::default() }),
+ _ => {}
+ }
+ }
+ match laid.and_then(|l| l["text"].as_array()) {
+ Some(texts) => {
+ // each laid-out run at its owner's place in the tree (its stamp and list key), in the page's order
+ let mut used = vec![false; tree.len()];
+ for t in texts {
+ let (loc, idx) = (t["loc"].as_str(), t["index"].as_str());
+ let owner = loc.and_then(|loc| (0..tree.len()).find(|&k| !used[k] && tree[k].props.get("data-raea-loc").and_then(Value::as_str) == Some(loc) && tree[k].props.get("data-raea-idx").map(text_of).as_deref() == idx));
+ if let Some(k) = owner {
+ used[k] = true;
+ }
+ let text = laid_text(t, (w, h));
+ let mut stamp = Map::new();
+ for (k, from) in [("data-raea-loc", "loc"), ("data-raea-idx", "index")] {
+ if let Some(v) = t[from].as_str() {
+ stamp.insert(k.into(), Value::String(v.into()));
+ }
+ }
+ if let Some(u) = t["use"].as_array() {
+ stamp.insert("data-raea-use".into(), Value::String(u.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("|")));
+ }
+ let source = crate::source::of(&stamp, dir);
+ paged.push(Paged { at: owner.unwrap_or(tree.len()), medium: Some(Medium::Type2d), opacity: t["opacity"].as_f64(), props: owner, text: Some(text), source, ..Default::default() });
+ }
+ }
+ None => {
+ // not laid out: each stamped element's words, with no box or size
+ let mut owned: Vec<(usize, Vec<String>)> = Vec::new();
+ for (i, el) in tree.iter().enumerate() {
+ let Some(words) = el.text.as_deref().map(str::trim).filter(|t| !t.is_empty()) else { continue };
+ // a <style>'s or <script>'s text is code, not words on the frame
+ if std::iter::successors(Some(i), |&k| tree[k].parent).any(|k| matches!(tree[k].kind.as_str(), "style" | "script")) {
+ continue;
+ }
+ let owner = std::iter::successors(Some(i), |&k| tree[k].parent).find(|&k| tree[k].props.contains_key("data-raea-loc")).unwrap_or(i);
+ match owned.iter_mut().find(|(o, _)| *o == owner) {
+ Some((_, ws)) => ws.push(words.to_string()),
+ None => owned.push((owner, vec![words.to_string()])),
+ }
+ }
+ for (owner, ws) in owned {
+ let text = Text { words: ws.join(" "), font: style(&tree[owner].props, "fontFamily"), size: None, box_: None, extruded: 0.0, lines: None, needs: Some("render".into()) };
+ paged.push(Paged { at: owner, medium: Some(Medium::Type2d), props: Some(owner), text: Some(text), ..Default::default() });
+ }
+ }
+ }
+ paged.sort_by_key(|p| p.at);
+ for p in paged {
+ let e = facts.spawn(None);
+ let props = p.props.map(|k| &tree[k].props);
+ // laid-out text has its opacity as computed (its parents' with it); anything else its own style's
+ let opacity = p.opacity.or_else(|| props.and_then(|pr| style(pr, "opacity")).and_then(|o| o.parse::<f64>().ok())).unwrap_or(1.0);
+ facts.put(e, &Layer { medium: p.medium.unwrap_or(Medium::Page), order: *order, opacity, blend: props.and_then(|pr| style(pr, "mixBlendMode")).filter(|b| b != "normal") });
+ *order += 1;
+ if let Some(s) = p.source.or_else(|| props.and_then(|pr| crate::source::of(pr, dir))) {
+ facts.put(e, &s);
+ }
+ if let Some(t) = &p.text {
+ facts.put(e, t);
+ }
+ if let Some(c) = &p.clip {
+ facts.put(e, c);
+ }
+ if let Some(c) = &p.cue {
+ facts.put(e, c);
+ }
+ }
+}
+
+/// The words a take's transcript (TAKE.words.json, beside it) has between `from` and `out` seconds of the take.
+fn list_words(take: &Path, fps: f64, from: f64, out: Option<f64>) -> Vec<Word> {
+ words(&take.with_extension("words.json"), fps).into_iter().filter(|w| w.start >= from && out.is_none_or(|o| w.start < o)).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn el(kind: &str, props: Value, text: Option<&str>, parent: Option<usize>) -> El {
+ El { kind: kind.into(), props: props.as_object().cloned().unwrap_or_default(), text: text.map(str::to_string), parent }
+ }
+
+ #[test]
+ fn a_page_reads_as_shots_footage_cues_and_text_in_document_order() {
+ let tree = vec![
+ el("div", serde_json::json!({"data-sequence": "intro", "data-raea-start": 0, "data-raea-end": 90}), None, None),
+ el("video", serde_json::json!({"src": "/abs/take.mp4", "data-source-time": 1.5, "data-start-from": 30, "data-from": 0, "data-volume": 0.5}), None, Some(0)),
+ el("h1", serde_json::json!({"data-raea-loc": "edit.tsx:9:7", "style": {"fontFamily": "Inter"}}), None, Some(0)),
+ el("#text", serde_json::json!({}), Some("OUT NOW"), Some(2)),
+ el("audio", serde_json::json!({"src": "/abs/hit.wav", "data-from": 45, "data-bus": "sfx"}), None, Some(0)),
+ el("style", serde_json::json!({"data-raea-loc": "edit.tsx:3:5"}), None, Some(0)),
+ el("#text", serde_json::json!({}), Some("@font-face { font-family: Inter }"), Some(5)),
+ ];
+ let mut facts = Facts::new(10, 1920, 1080, 30.0);
+ let mut order = 1;
+ put(&mut facts, &tree, None, (1920, 1080, 30.0), Path::new("/nowhere"), &mut order);
+ let shot: Shot = facts.get(facts.find(&["Shot"])[0].id).unwrap();
+ assert_eq!((shot.name.as_deref(), shot.from, shot.to), (Some("intro"), 0, Some(90)));
+ let take = facts.find(&["Clip"])[0];
+ let clip: Clip = facts.get(take.id).unwrap();
+ assert_eq!((clip.in_, clip.time, clip.hash), (1.0, Some(1.5), None), "a file that isn't there has no hash");
+ assert_eq!(facts.get::<Cue>(take.id).unwrap().gain, Some(-6.0), "a sounding take is a cue too");
+ assert_eq!(facts.get::<Layer>(take.id).unwrap().order, 1, "the page's layers go on from the 3D's");
+ assert_eq!(facts.find(&["Text"]).len(), 1, "a <style>'s CSS is not words on the frame");
+ let t = facts.find(&["Text", "Layer"])[0];
+ let text: Text = facts.get(t.id).unwrap();
+ assert_eq!((text.words.as_str(), text.font.as_deref(), text.needs.as_deref()), ("OUT NOW", Some("Inter"), Some("render")));
+ assert_eq!(facts.get::<Layer>(t.id).unwrap().medium, Medium::Type2d);
+ assert_eq!(facts.get::<Source>(t.id).unwrap().line, Some(9));
+ let hit: Cue = facts.get(facts.find(&["Cue"]).iter().find(|e| !e.components.contains_key("Clip")).unwrap().id).unwrap();
+ assert_eq!((hit.at, hit.bus.as_deref()), (1.5, Some("sfx")));
+ }
+
+ #[test]
+ fn laid_out_text_is_in_the_frames_units_at_1080() {
+ let t = serde_json::json!({"text": "OUT", "box": [960.0, 108.0, 480.0, 216.0], "size": 96.0, "family": "Inter", "lines": 2});
+ let text = laid_text(&t, (1920, 1080));
+ assert_eq!((text.box_, text.size, text.lines), (Some([0.5, 0.1, 0.75, 0.3]), Some(96.0), Some(2)));
+ assert_eq!(laid_text(&t, (3840, 2160)).size, Some(48.0), "96 px in a 4K frame is 48 px at 1080");
+ }
+
+ #[test]
+ fn a_transcript_becomes_lines_at_its_stops_and_pauses() {
+ let dir = std::env::temp_dir().join(format!("raea-world-lines-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let ws = serde_json::json!([{"text": "give", "start": 0.0, "end": 0.3}, {"text": "it", "start": 0.35, "end": 0.5}, {"text": "back.", "start": 0.55, "end": 0.9},
+ {"text": "now", "start": 1.0, "end": 1.2}, {"text": "later", "start": 2.5, "end": 3.0}]);
+ std::fs::write(dir.join("words.json"), ws.to_string()).unwrap();
+ let lines = project_lines(None, &dir, 30.0);
+ assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<Vec<_>>(), ["give it back.", "now", "later"]);
+ let mut facts = Facts::new(15, 1080, 1920, 30.0);
+ put_lines(&mut facts, &lines, &[], 15, 30.0);
+ assert_eq!(facts.get::<Line>(facts.find(&["Line"])[0].id).unwrap().text, "give it back.", "frame 15 is 0.5 s, in the first line");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/sdk/video/src/timeline.tsx b/sdk/video/src/timeline.tsx
index 1f76c7dd..88ae18ee 100644
--- a/sdk/video/src/timeline.tsx
+++ b/sdk/video/src/timeline.tsx
@@ -77,9 +77,11 @@ function Shifted(props: {
style?: CSSProperties;
className?: string;
label?: string;
+ /** the composition frame after its last, when it ends (`raea world`'s Shot, docs/direction.feature DR1) */
+ end?: number;
children?: ReactNode;
}) {
- const { owner, time, base, layout, style, className, label, children } = props;
+ const { owner, time, base, layout, style, className, label, end, children } = props;
if (layout !== "absolute-fill" && layout !== "none") {
throw new RangeError(`${owner}: layout must be "absolute-fill" or "none", got "${layout}"`);
}
@@ -91,7 +93,7 @@ function Shifted(props: {
// out the same rendered alone or after the ones before it)
const inner =
layout === "absolute-fill" ? (
- <AbsoluteFill style={style} className={className} data-sequence={label} data-raea-start={time.origin}>
+ <AbsoluteFill style={style} className={className} data-sequence={label} data-raea-start={time.origin} data-raea-end={end}>
{children}
</AbsoluteFill>
) : (
@@ -150,7 +152,7 @@ export function Sequence(props: SequenceProps) {
);
}
return (
- <Shifted owner="Sequence" time={time} base={base} layout={layout} style={style} className={className} label={name}>
+ <Shifted owner="Sequence" time={time} base={base} layout={layout} style={style} className={className} label={name} end={durationInFrames === Infinity ? undefined : time.origin + durationInFrames}>
{props.children}
</Shifted>
);
diff --git a/tools/manual-ref/cli.ts b/tools/manual-ref/cli.ts
index a9507a8f..59037ab7 100644
--- a/tools/manual-ref/cli.ts
+++ b/tools/manual-ref/cli.ts
@@ -27,7 +27,7 @@ const verbs: Verb[] = JSON.parse(run(["help", "--json"])).verbs
const GROUPS: [string, string, string[]][] = [
["Make", "Render, play and package what you wrote.", ["render", "play", "export-game", "bundle", "app", "run"]],
["Projects", "The workspace, its projects and what a project holds.", ["init", "workspace", "project", "controller", "spec", "part", "add", "brand", "library"]],
- ["Check", "What's wrong before anyone watches it.", ["check", "judge", "scene", "solid", "next", "doctor", "hook", "traces"]],
+ ["Check", "What's wrong before anyone watches it.", ["check", "judge", "scene", "world", "solid", "next", "doctor", "hook", "traces"]],
["Footage", "Takes, cuts and the camera, from your own media.", ["media", "cut", "frame", "track", "splat", "mezz", "neural"]],
["Sound", "Music read, foley and instruments made on this machine.", ["song", "sounds", "sao", "tokensynth", "setup-audio"]],
["Generate and 3D tools", "Generated media, physics bakes and Blender.", ["gen", "physics", "blender"]],