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.

BL36, BL37, BL38, BL39, GD11, GD12, GD13: Blender and Godot in a raea project: shots drawn by them, the scene sent to them and its changes read back. `raea scene export EDIT.tsx -o DIR [--frame N | --at A-B]` writes the composition's 3D as scene.json (each part's id, kind, name, TSX line from the bundle's source stamps, placement, material, primitive sizes; other meshes as .glb, models copied with their sidecars; lights, camera, ambient, background; what doesn't cross listed in left) (new crate apps/interchange). `raea blender open` builds it in Blender through raea/blender (sdk/blender scene.ts: Blender's own meshes, Principled BSDFs, lights and camera keyed on --at, raea_id on each object) and opens the .blend; `raea blender back` and `raea godot back` read the file back and say each move, colour, light, camera and deletion as an edit at its TSX line, and write objects made there as media/NAME.glb. `raea godot export` writes a Godot project that runs (native meshes, StandardMaterial3D, an AnimationPlayer for --at, still channels left out, nodes named for their parts); `raea godot run` takes --scene with no script (host/none.ts). <BlenderShot> and <GodotShot> (raea/blender/shot, raea/godot/shot) render their frames once per bundle, file, props, size, fps and length, sized from their Sequence's end, kept in the asset store (native calls blender.shot, godot.shot; `raea blender shot`, `raea godot shot`). register_natives() gathers every native call a composition's thread answers, so `raea types` lists them all. Tests: apps/interchange (9), apps/engines

shinyobjectzb85ce4f97df2
diff --git a/Cargo.lock b/Cargo.lock
index b2ea663d..5f62034e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13652,6 +13652,7 @@ name = "raea-app-engines"
version = "0.1.0"
dependencies = [
"dunce",
+ "raea-app-interchange",
"raea-app-tools",
"raea-io-home",
"raea-runtime-bundle",
@@ -13680,6 +13681,18 @@ dependencies = [
"winit",
]
+[[package]]
+name = "raea-app-interchange"
+version = "0.1.0"
+dependencies = [
+ "raea-core-scene",
+ "raea-core-shape",
+ "raea-runtime-bundle",
+ "raea-runtime-export",
+ "raea-runtime-scene",
+ "serde_json",
+]
+
[[package]]
name = "raea-app-judge"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index aa26b538..ef52e061 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -163,6 +163,7 @@ members = [
"apps/ci",
"apps/tools",
"apps/engines",
+ "apps/interchange",
"apps/judge",
"apps/solid",
"apps/media",
diff --git a/apps/engines/Cargo.toml b/apps/engines/Cargo.toml
index 34948897..4c720423 100644
--- a/apps/engines/Cargo.toml
+++ b/apps/engines/Cargo.toml
@@ -14,6 +14,9 @@ raea-io-home = { path = "../../io/home" }
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-runtime-export = { path = "../../runtime/export" }
raea-runtime-calls = { path = "../../runtime/calls" }
+# a composition's 3D as scene.json, a Godot project from it, and changes read back (raea scene export, raea godot export|back,
+# raea blender open|back)
+raea-app-interchange = { path = "../interchange" }
serde_json = "1"
# Godot with GodotJS, unpacked from its release zip (`raea setup godot`), and the script path the bundler imports
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
diff --git a/apps/engines/src/blender_ts.rs b/apps/engines/src/blender_ts.rs
index a5e496d0..91c46f88 100644
--- a/apps/engines/src/blender_ts.rs
+++ b/apps/engines/src/blender_ts.rs
@@ -1,38 +1,59 @@
//! `raea blender run SCRIPT.ts [FILE.blend] [ARGS...]`: a headless Blender with raea's bridge (FILE.blend opened, ARGS
//! its sys.argv after --), the script on raea's engine with each batch posted to it (blender.post), Blender quit after.
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use raea_runtime_calls::blender::{BRIDGE, post};
use serde_json::json;
use crate::{R, blender_bridge};
-/// What the script's entry does after it: its default export called and awaited, then the session closed
-/// (sdk/blender/src/blender.ts's __raea_blender_end), so a failure in Blender the script never awaited fails the run,
-/// as an uncaught Python exception would.
-const END: &str = "Promise.resolve().then(() => (typeof (M as any).default === \"function\" ? (M as any).default() : undefined)).then(() => (globalThis as any).__raea_blender_end?.()).then(() => call(\"done\", JSON.stringify({ code: 0 })), (e: any) => { call(\"print\", JSON.stringify({ text: \"error: \" + String(e) + (e && e.name === \"BlenderError\" ? (e.pythonTrace ? \"\\n\" + e.pythonTrace : \"\") : e && e.stack ? \"\\n\" + e.stack : \"\") })); call(\"done\", JSON.stringify({ code: 1 })); });";
+/// What an entry does once its work is a promise: the session closed (sdk/blender/src/blender.ts's
+/// __raea_blender_end), so a failure in Blender the script never awaited fails the run, as an uncaught Python exception
+/// would; then the run's exit.
+pub(crate) const CLOSE: &str = ".then(() => (globalThis as any).__raea_blender_end?.()).then(() => call(\"done\", JSON.stringify({ code: 0 })), (e: any) => { call(\"print\", JSON.stringify({ text: \"error: \" + String(e) + (e && e.name === \"BlenderError\" ? (e.pythonTrace ? \"\\n\" + e.pythonTrace : \"\") : e && e.stack ? \"\\n\" + e.stack : \"\") })); call(\"done\", JSON.stringify({ code: 1 })); });";
-pub fn run(args: &[String]) -> R<String> {
- let ts = PathBuf::from(&args[2]).canonicalize().map_err(|e| format!("{}: {e}", args[2]))?;
- let (bin, _) = raea_app_tools::blender::find().ok_or("no Blender: raea setup blender finds or downloads one")?;
- let file = args.get(3).filter(|a| a.ends_with(".blend")).map(PathBuf::from);
- // ARGS for Blender's sys.argv, without raea's own --timeout SECS
- let mut rest = args[if file.is_some() { 4 } else { 3 }..].to_vec();
+/// The script's default export, called and awaited.
+pub(crate) const DEFAULT: &str = "Promise.resolve().then(() => (typeof (M as any).default === \"function\" ? (M as any).default() : undefined))";
+
+/// `--timeout SECS` taken out of ARGS (Blender's sys.argv), and its seconds.
+pub(crate) fn timeout(rest: &mut Vec<String>) -> f64 {
let mut secs = 3600.0;
if let Some(i) = rest.iter().position(|a| a == "--timeout") {
secs = rest.get(i + 1).and_then(|t| t.parse().ok()).unwrap_or(secs);
rest.drain(i..(i + 2).min(rest.len()));
}
- let bridge = blender_bridge::start(&bin, file.as_deref(), &rest)?;
+ secs
+}
+
+/// An entry's bundle run against a headless Blender started with the bridge (`file` opened, `rest` its sys.argv):
+/// the bundle's exit code. Blender is quit after, and killed if the run ends any other way.
+pub(crate) fn session(entry: &str, file: Option<&Path>, rest: &[String], secs: f64) -> R<i32> {
+ let (bin, _) = raea_app_tools::blender::find().ok_or("no Blender: raea setup blender finds or downloads one")?;
+ let bridge = blender_bridge::start(&bin, file, rest)?;
*BRIDGE.lock().map_err(|e| e.to_string())? = Some((bridge.port, bridge.token.clone()));
let out = std::env::temp_dir().join(format!("raea-blender-{}.js", std::process::id()));
- let ran = raea_runtime_bundle::bundle_module(&ts, &out, END).and_then(|_| raea_runtime_export::run_bundle(&out, secs));
+ let ran = raea_runtime_bundle::bundle_entry(entry, &out, &[]).and_then(|_| raea_runtime_export::run_bundle(&out, secs));
let _ = std::fs::remove_file(&out);
let _ = post(&json!({ "sid": "raea", "ops": [{ "o": "quit" }] }));
*BRIDGE.lock().map_err(|e| e.to_string())? = None;
bridge.wait();
- let (code, _) = ran?;
+ Ok(ran?.0)
+}
+
+/// A path as an entry's import specifier (Windows' verbatim prefix dropped, as raea-runtime-bundle does).
+pub(crate) fn spec(p: &Path) -> String {
+ format!("{:?}", dunce::simplified(p).display().to_string())
+}
+
+pub fn run(args: &[String]) -> R<String> {
+ let ts = PathBuf::from(&args[2]).canonicalize().map_err(|e| format!("{}: {e}", args[2]))?;
+ let file = args.get(3).filter(|a| a.ends_with(".blend")).map(PathBuf::from);
+ // ARGS for Blender's sys.argv, without raea's own --timeout SECS
+ let mut rest = args[if file.is_some() { 4 } else { 3 }..].to_vec();
+ let secs = timeout(&mut rest);
+ let entry = format!("import * as M from {};\nconst call = (globalThis as any).__raea_call;\n{DEFAULT}{CLOSE}\n", spec(&ts));
+ let code = session(&entry, file.as_deref(), &rest, secs)?;
if code != 0 {
return Err(format!("{} ended with exit {code}", args[2]));
}
diff --git a/apps/engines/src/godot_run.rs b/apps/engines/src/godot_run.rs
index 0d55413c..15e566ed 100644
--- a/apps/engines/src/godot_run.rs
+++ b/apps/engines/src/godot_run.rs
@@ -1,4 +1,5 @@
-//! `raea godot run SCRIPT.ts [--project DIR] [--window] [--movie FILE [--fps N]] [--size WxH] [--timeout S] [ARGS...]`:
+//! `raea godot run SCRIPT.ts [--project DIR] [--window] [--movie FILE [--fps N] [--frames N]] [--scene res://X.tscn] [--size WxH]
+//! [--timeout S] [ARGS...]`:
//! a TypeScript script against Godot's whole API (raea/godot, sdk/godot). raea's bundler makes one CommonJS file of the
//! script, with GodotJS's modules ("godot", "godot.annotations", ...) aliased to sdk/godot/src/shim's stand-ins, which
//! read GodotJS's own when the script runs. It goes into the project's .godot/raea/<pid>/ as run.js, beside
@@ -26,14 +27,20 @@ struct Opts {
movie: Option<PathBuf>,
fps: u32,
size: Option<String>,
+ /// Godot quits after this many frames (--quit-after), not when the script returns: a shot's length (GD11)
+ frames: Option<u32>,
+ /// a scene of the project added to the tree before the script runs, playing as it would in the game (GD11)
+ scene: Option<String>,
rest: Vec<String>,
}
fn opts(args: &[String]) -> R<Opts> {
- let script = args.get(2).ok_or("raea godot run SCRIPT.ts [--project DIR] [--window] [--movie FILE [--fps N]] [--size WxH] [--timeout S] [ARGS...]")?;
- let script = PathBuf::from(script).canonicalize().map_err(|e| format!("{script}: {e}"))?;
- let mut o = Opts { script, project: None, window: false, timeout: 3600.0, movie: None, fps: 30, size: None, rest: Vec::new() };
- let mut it = args[3..].iter();
+ let script = args.get(2).ok_or("raea godot run SCRIPT.ts [--project DIR] [--window] [--movie FILE [--fps N] [--frames N]] [--scene res://X.tscn] [--size WxH] [--timeout S] [ARGS...]")?;
+ // no script, only flags: the project's --scene plays with nothing of yours added (sdk/godot/src/host/none.ts)
+ let bare = script.starts_with("--");
+ let script = if bare { raea_io_home::home().join("sdk/godot/src/host/none.ts") } else { PathBuf::from(script).canonicalize().map_err(|e| format!("{script}: {e}"))? };
+ let mut o = Opts { script, project: None, window: false, timeout: 3600.0, movie: None, fps: 30, size: None, frames: None, scene: None, rest: Vec::new() };
+ let mut it = args[if bare { 2 } else { 3 }..].iter();
while let Some(a) = it.next() {
match a.as_str() {
"--project" => o.project = Some(PathBuf::from(it.next().ok_or("--project needs a folder")?)),
@@ -41,6 +48,8 @@ fn opts(args: &[String]) -> R<Opts> {
"--timeout" => o.timeout = it.next().and_then(|s| s.parse().ok()).ok_or("--timeout needs seconds")?,
"--movie" => o.movie = Some(std::path::absolute(it.next().ok_or("--movie needs a file (frames.png or film.avi)")?).map_err(|e| e.to_string())?),
"--fps" => o.fps = it.next().and_then(|s| s.parse().ok()).filter(|n| *n > 0).ok_or("--fps needs frames a second")?,
+ "--frames" => o.frames = Some(it.next().and_then(|s| s.parse().ok()).filter(|n| *n > 0).ok_or("--frames needs a number of frames")?),
+ "--scene" => o.scene = Some(it.next().filter(|s| s.starts_with("res://")).ok_or("--scene needs a scene of the project, res://PATH.tscn")?.clone()),
"--size" => {
let s = it.next().filter(|s| s.split_once('x').is_some_and(|(w, h)| w.parse::<u32>().is_ok() && h.parse::<u32>().is_ok()));
o.size = Some(s.ok_or("--size needs WxH")?.clone());
@@ -50,6 +59,9 @@ fn opts(args: &[String]) -> R<Opts> {
_ => o.rest.push(a.clone()),
}
}
+ if bare && o.scene.is_none() {
+ return Err("raea godot run without a script plays a scene: give --scene res://PATH.tscn (and --project DIR)".into());
+ }
Ok(o)
}
@@ -220,6 +232,13 @@ pub fn run(args: &[String]) -> R<String> {
if let Some(s) = &o.size {
cmd.arg("--resolution").arg(s);
}
+ // a set length: Godot stops after it, and main.js doesn't quit when the script returns
+ if let Some(n) = o.frames {
+ cmd.arg("--quit-after").arg(n.to_string()).env("RAEA_GODOT_HOLD", "1");
+ }
+ if let Some(sc) = &o.scene {
+ cmd.env("RAEA_GODOT_SCENE", sc);
+ }
cmd.arg("--path").arg(&project).arg("--script").arg(format!("res://.godot/raea/{pid}/main.js")).arg("--").args(&o.rest);
cmd.env("RAEA_GODOT_LOADED", work.join("loaded"));
// Godot runs in the project's folder: raea/godot's cwd() and resolve() read where raea was run from
diff --git a/apps/engines/src/lib.rs b/apps/engines/src/lib.rs
index 66e3801b..6bcc3778 100644
--- a/apps/engines/src/lib.rs
+++ b/apps/engines/src/lib.rs
@@ -10,6 +10,10 @@ pub mod blender_ts;
pub mod godot;
/// `raea godot run SCRIPT.ts`: a TypeScript script in Godot through GodotJS
pub mod godot_run;
+/// `raea blender shot`, `raea godot shot`: a shot's frames drawn by Blender or Godot (<BlenderShot>, <GodotShot>)
+pub mod shot;
+/// `raea scene export`, `raea godot export|back`, `raea blender open|back`: a raea scene sent to Blender or Godot and back
+pub mod round;
use raea_app_tools::blender;
@@ -22,6 +26,13 @@ pub fn cli(args: &[String]) -> Option<R<String>> {
("setup", Some("blender")) => blender::setup(&args[2..]),
("setup", Some("godot")) => godot::setup(&args[2..]),
("blender", Some("run")) if args.get(2).is_some_and(|s| blender_bridge::is_ts(s)) => blender_ts::run(args),
+ ("blender", Some("shot")) => shot::blender(args),
+ ("godot", Some("shot")) => shot::godot(args),
+ ("scene", Some("export")) => round::scene_export(args),
+ ("godot", Some("export")) => round::godot_export(args),
+ ("godot", Some("back")) => round::godot_back(args),
+ ("blender", Some("open")) => round::blender_open(args),
+ ("blender", Some("back")) => round::blender_back(args),
("blender", _) => blender::blender(args),
("godot", _) => godot::godot(args),
_ => return None,
diff --git a/apps/engines/src/round.rs b/apps/engines/src/round.rs
new file mode 100644
index 00000000..ba01e028
--- /dev/null
+++ b/apps/engines/src/round.rs
@@ -0,0 +1,146 @@
+//! A raea scene sent to Blender or Godot and its changes read back (docs/blender.feature BL37-BL39, docs/godot.feature
+//! GD12-GD13): the verbs, running Blender (sdk/blender/src/scene.ts) and Godot (sdk/godot/src/host/back.ts) on what
+//! raea-app-interchange writes and compares.
+//! raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]
+//! raea godot export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]
+//! raea godot back DIR [--json]
+//! raea blender open EDIT.tsx [--frame N | --at A-B] [-o DIR] [--no-window] | FILE.blend|.glb|.gltf|.obj|.fbx
+//! raea blender back FILE.blend [--json]
+
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+
+use raea_app_interchange::{back, export, godot};
+use serde_json::Value;
+
+use crate::{R, blender_ts};
+
+pub const USAGE: &str = "raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B] (the composition's 3D as data other tools build: DIR/scene.json, each part placed (y up, metres) with its shape, material or light, and the camera; meshes/ and models/ beside it)\n raea godot export EDIT.tsx -o DIR [--frame N | --at A-B] (the composition's 3D as a Godot project that runs: project.godot and main.tscn, each part Godot's own node, --at's frames an AnimationPlayer)\n raea godot back DIR (what changed in Godot's main.tscn since the export, as edits to the TSX at their lines; nodes added there written as media/NAME.glb; --json)\n raea blender open EDIT.tsx [--frame N | --at A-B] [-o DIR] [--no-window] | FILE.blend|.glb (the composition's 3D built in Blender, saved as DIR/NAME.blend (out/blender/NAME/ unless -o) and opened in a Blender window; a model or .blend opened as it is)\n raea blender back FILE.blend (what changed in Blender since raea blender open, as edits to the TSX at their lines; meshes made there written as media/NAME.glb; --json)";
+
+fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a String> {
+ args.iter().position(|a| a == k).and_then(|i| args.get(i + 1))
+}
+
+fn read_json(p: &Path) -> R<Value> {
+ serde_json::from_slice(&std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?).map_err(|e| format!("{}: {e}", p.display()))
+}
+
+/// The scene export's folder for an edit: -o DIR, else out/blender/NAME/ beside it.
+fn export_to(args: &[String], default_sub: &str) -> R<(PathBuf, Value)> {
+ let mut a = args.to_vec();
+ if flag(args, "-o").is_none() {
+ let edit = PathBuf::from(args.get(2).ok_or(USAGE)?);
+ let stem = edit.file_stem().and_then(|s| s.to_str()).unwrap_or("scene").to_string();
+ let dir = edit.parent().unwrap_or(Path::new(".")).join("out").join(default_sub).join(&stem);
+ a.extend(["-o".into(), dir.to_string_lossy().into_owned()]);
+ }
+ export::export(&a)
+}
+
+/// The edits from scene.json in `dir` to what `now` holds, said (or as JSON).
+fn compared(dir: &Path, now: &Path, json: bool) -> R<String> {
+ let sent = read_json(&dir.join("scene.json"))?;
+ let held = read_json(now)?;
+ let _ = std::fs::remove_file(now);
+ let edits = back::compare(&sent, &held);
+ let tsx = PathBuf::from(sent["from"].as_str().unwrap_or(""));
+ Ok(if json { serde_json::to_string_pretty(&edits).unwrap_or_default() } else { back::said(&edits, &tsx) })
+}
+
+/// The project's media folder for models made in Blender or Godot: beside the edit the scene came from.
+fn media_of(dir: &Path) -> R<PathBuf> {
+ let sent = read_json(&dir.join("scene.json"))?;
+ let tsx = PathBuf::from(sent["from"].as_str().ok_or("scene.json names no edit")?);
+ Ok(tsx.parent().unwrap_or(Path::new(".")).join("media"))
+}
+
+pub fn scene_export(args: &[String]) -> R<String> {
+ let (out, v) = export::export(args)?;
+ Ok(export::said(&out, &v))
+}
+
+pub fn godot_export(args: &[String]) -> R<String> {
+ let (out, v) = export_to(args, "godot")?;
+ let name = Path::new(&args[2]).file_stem().and_then(|s| s.to_str()).unwrap_or("raea").to_string();
+ let said = godot::project(&out, &v, &name)?;
+ let left = export::said(&out, &v);
+ let left = left.split_once("; ").map(|(_, l)| format!("; {l}")).unwrap_or_default();
+ Ok(format!("a Godot project in {}: {said}{left}\nrun it: raea godot run SCRIPT.ts --project {0} (or --movie); edit it: raea godot open {0}; then raea godot back {0}", out.display()))
+}
+
+pub fn godot_back(args: &[String]) -> R<String> {
+ let dir = PathBuf::from(args.get(2).ok_or(USAGE)?).canonicalize().map_err(|e| format!("{}: {e}", args[2]))?;
+ let media = media_of(&dir)?;
+ let now = dir.join(".raea-now.json");
+ let script = raea_io_home::home().join("sdk/godot/src/host/back.ts");
+ let run: Vec<String> = ["godot", "run"].iter().map(|s| s.to_string())
+ .chain([script.to_string_lossy().into_owned(), "--project".into(), dir.to_string_lossy().into_owned(), "--".into(), now.to_string_lossy().into_owned(), media.to_string_lossy().into_owned()])
+ .collect();
+ crate::godot_run::run(&run)?;
+ compared(&dir, &now, args.iter().any(|a| a == "--json"))
+}
+
+/// A Blender window on `file`, left running as the person's.
+fn window(file: &Path, python: Option<String>) -> R<()> {
+ let (bin, _) = raea_app_tools::blender::find().ok_or("no Blender: raea setup blender finds or downloads one")?;
+ let mut cmd = Command::new(&bin);
+ match python {
+ Some(code) => cmd.arg("--python-expr").arg(code),
+ None => cmd.arg(file),
+ };
+ cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn().map_err(|e| format!("{}: {e}", bin.display()))?;
+ Ok(())
+}
+
+pub fn blender_open(args: &[String]) -> R<String> {
+ let src = args.get(2).ok_or(USAGE)?;
+ let path = std::path::absolute(src).map_err(|e| e.to_string())?;
+ let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
+ match ext.as_str() {
+ "blend" => {
+ window(&path, None)?;
+ return Ok(format!("APPLIED Blender is opening {}", path.display()));
+ }
+ "glb" | "gltf" | "obj" | "fbx" => {
+ let op = match ext.as_str() {
+ "obj" => "bpy.ops.wm.obj_import",
+ "fbx" => "bpy.ops.import_scene.fbx",
+ _ => "bpy.ops.import_scene.gltf",
+ };
+ let code = format!("import bpy\nbpy.ops.wm.read_homefile(use_empty=True)\n{op}(filepath={:?})", path.to_string_lossy());
+ window(&path, Some(code))?;
+ return Ok(format!("APPLIED Blender is opening {}", path.display()));
+ }
+ _ => {}
+ }
+ let (dir, v) = export_to(args, "blender")?;
+ let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("scene");
+ let blend = dir.join(format!("{stem}.blend"));
+ let call = format!("build({:?}, {:?})", dir.to_string_lossy(), blend.to_string_lossy());
+ let entry = format!("import {{ build }} from \"@raea/blender/scene\";\nconst call = (globalThis as any).__raea_call;\nPromise.resolve().then(() => {call}){}\n", blender_ts::CLOSE);
+ let code = blender_ts::session(&entry, None, &[], 900.0)?;
+ if code != 0 || !blend.is_file() {
+ return Err(format!("Blender couldn't build {} (above)", dir.join("scene.json").display()));
+ }
+ if !args.iter().any(|a| a == "--no-window") {
+ window(&blend, None)?;
+ }
+ Ok(format!("{}\nbuilt in Blender: {}; after changing it there, save and run: raea blender back {}", export::said(&dir, &v), blend.display(), blend.display()))
+}
+
+pub fn blender_back(args: &[String]) -> R<String> {
+ let blend = PathBuf::from(args.get(2).filter(|a| a.ends_with(".blend")).ok_or(USAGE)?).canonicalize().map_err(|e| format!("{}: {e}", args[2]))?;
+ let dir = blend.parent().ok_or("the .blend's folder")?.to_path_buf();
+ if !dir.join("scene.json").is_file() {
+ return Err(format!("{} has no scene.json beside it: raea blender back reads a .blend raea blender open made", blend.display()));
+ }
+ let media = media_of(&dir)?;
+ let now = dir.join(".raea-now.json");
+ let call = format!("readBack({:?}, {:?})", now.to_string_lossy(), media.to_string_lossy());
+ let entry = format!("import {{ readBack }} from \"@raea/blender/scene\";\nconst call = (globalThis as any).__raea_call;\nPromise.resolve().then(() => {call}){}\n", blender_ts::CLOSE);
+ let code = blender_ts::session(&entry, Some(&blend), &[], 900.0)?;
+ if code != 0 {
+ return Err(format!("Blender couldn't read {} (above)", blend.display()));
+ }
+ compared(&dir, &now, args.iter().any(|a| a == "--json"))
+}
diff --git a/apps/engines/src/shot.rs b/apps/engines/src/shot.rs
new file mode 100644
index 00000000..0d9c7f5e
--- /dev/null
+++ b/apps/engines/src/shot.rs
@@ -0,0 +1,236 @@
+//! A shot's frames made by another engine, numbered from DIR/0000.png (docs/blender.feature BL36, docs/godot.feature
+//! GD11): what <BlenderShot> and <GodotShot> show, made through their native calls (runtime/react's scene/shots.rs).
+//! raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--file FILE.blend]
+//! [--engine eevee|cycles|workbench] [--samples S] [--transparent] [--timeout S] [-- ARGS]
+//! raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] [--scene res://X]
+//! [--timeout S] [-- ARGS]
+
+use std::path::{Path, PathBuf};
+
+use serde_json::json;
+
+use crate::{R, blender_ts};
+
+pub const BLENDER_USAGE: &str = "raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--file FILE.blend] [--engine eevee|cycles|workbench] [--samples S] [--transparent] [--timeout S] [-- ARGS]";
+/// Both, as raea's help says them.
+pub const USAGE: &str = "raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--engine eevee|cycles|workbench] [--samples S] [--transparent] (a shot's frames rendered by Blender, DIR/0000.png on: a raea/blender script's scene or a .blend's animation; what <BlenderShot> shows, from raea/blender/shot)\n raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] (a shot's frames recorded by Godot's Movie Maker, DIR/0000.png on, its sound as sound.wav; what <GodotShot> shows, from raea/godot/shot)";
+pub const GODOT_USAGE: &str = "raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] [--scene res://X.tscn] [--timeout S] [-- ARGS]";
+
+#[derive(Debug)]
+struct Shot {
+ src: String,
+ out: PathBuf,
+ frames: u32,
+ fps: f64,
+ size: (u32, u32),
+ flags: Vec<(String, Option<String>)>,
+ rest: Vec<String>,
+}
+
+impl Shot {
+ fn flag(&self, k: &str) -> Option<&str> {
+ self.flags.iter().find(|(f, _)| f == k).and_then(|(_, v)| v.as_deref())
+ }
+ fn has(&self, k: &str) -> bool {
+ self.flags.iter().any(|(f, _)| f == k)
+ }
+}
+
+/// args[2] the source, then the flags (each taking a value but --transparent), then -- and the script's own.
+fn parse(args: &[String], usage: &str) -> R<Shot> {
+ let src = args.get(2).filter(|a| !a.starts_with('-')).ok_or(usage)?.clone();
+ let mut flags = Vec::new();
+ let mut rest = Vec::new();
+ let mut it = args[3..].iter();
+ while let Some(a) = it.next() {
+ match a.as_str() {
+ "--" => rest.extend(it.by_ref().cloned()),
+ "--transparent" => flags.push((a.clone(), None)),
+ f if f.starts_with('-') => flags.push((a.clone(), Some(it.next().ok_or_else(|| format!("{a} needs a value: {usage}"))?.clone()))),
+ _ => return Err(format!("{a}: not a flag of this verb: {usage}")),
+ }
+ }
+ let get = |k: &str| flags.iter().find(|(f, _): &&(String, Option<String>)| f == k).and_then(|(_, v)| v.clone());
+ let out = std::path::absolute(get("-o").ok_or(usage)?).map_err(|e| e.to_string())?;
+ let frames = get("--frames").and_then(|n| n.parse().ok()).filter(|n| *n > 0).ok_or("--frames needs a number of frames over 0")?;
+ let fps = get("--fps").map_or(Ok(30.0), |f| f.parse::<f64>().ok().filter(|f| *f > 0.0).ok_or("--fps needs frames a second"))?;
+ let size = match get("--size") {
+ Some(s) => s.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))).ok_or("--size needs WxH")?,
+ None => (1920, 1080),
+ };
+ Ok(Shot { src, out, frames, fps, size, flags, rest })
+}
+
+/// The frames a run wrote in `dir` (Blender's 0001.png on, Godot's f00000000.png on), by their number: the first
+/// `n` renamed 0000.png on, any past them removed. Too few is the run's failure.
+pub(crate) fn renumber(dir: &Path, n: u32) -> R<()> {
+ let number = |p: &Path| p.file_stem()?.to_str()?.trim_start_matches(|c: char| !c.is_ascii_digit()).parse::<u64>().ok();
+ let mut made: Vec<(u64, PathBuf)> = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| p.extension().is_some_and(|e| e == "png"))
+ .filter_map(|p| Some((number(&p)?, p)))
+ .collect();
+ made.sort();
+ if made.len() < n as usize {
+ return Err(format!("{} frames were made of the {n} asked for ({})", made.len(), dir.display()));
+ }
+ // through a name of their own first, so 0001.png -> 0000.png never meets a frame not yet moved
+ let mut moved = Vec::new();
+ for (i, (_, p)) in made.iter().enumerate() {
+ if i < n as usize {
+ let tmp = dir.join(format!("raea-{i:06}.tmp"));
+ std::fs::rename(p, &tmp).map_err(|e| format!("{}: {e}", p.display()))?;
+ moved.push((i, tmp));
+ } else {
+ let _ = std::fs::remove_file(p);
+ }
+ }
+ for (i, tmp) in moved {
+ std::fs::rename(&tmp, dir.join(format!("{i:04}.png"))).map_err(|e| e.to_string())?;
+ }
+ Ok(())
+}
+
+fn fresh(out: &Path) -> R<()> {
+ let _ = std::fs::remove_dir_all(out);
+ std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))
+}
+
+/// `raea blender shot ...`: the script's default export run (or the .blend opened), then sdk/blender's shoot().
+pub fn blender(args: &[String]) -> R<String> {
+ let s = parse(args, BLENDER_USAGE)?;
+ let src = std::path::absolute(&s.src).map_err(|e| e.to_string())?;
+ let is_blend = s.src.ends_with(".blend");
+ let file = if is_blend { Some(src.clone()) } else { s.flag("--file").map(PathBuf::from) };
+ if let Some(f) = file.as_ref().filter(|f| !f.is_file()) {
+ return Err(format!("{}: no such .blend", f.display()));
+ }
+ fresh(&s.out)?;
+ let mut opts = json!({ "out": s.out.to_string_lossy(), "frames": s.frames, "fps": s.fps, "width": s.size.0, "height": s.size.1, "transparent": s.has("--transparent") });
+ if let Some(e) = s.flag("--engine") {
+ opts["engine"] = json!(e);
+ }
+ if let Some(n) = s.flag("--samples") {
+ opts["samples"] = json!(n.parse::<u32>().map_err(|_| "--samples needs a whole number")?);
+ }
+ let shoot = "import { shoot } from \"@raea/blender/shoot\";\nconst call = (globalThis as any).__raea_call;\n";
+ let entry = if is_blend {
+ format!("{shoot}Promise.resolve().then(() => shoot({opts})){}\n", blender_ts::CLOSE)
+ } else {
+ let ts = src.canonicalize().map_err(|e| format!("{}: {e}", s.src))?;
+ format!("import * as M from {};\n{shoot}{}.then(() => shoot({opts})){}\n", blender_ts::spec(&ts), blender_ts::DEFAULT, blender_ts::CLOSE)
+ };
+ let mut rest = s.rest.clone();
+ let secs = s.flag("--timeout").and_then(|t| t.parse().ok()).unwrap_or_else(|| blender_ts::timeout(&mut rest));
+ let code = blender_ts::session(&entry, file.as_deref(), &rest, secs)?;
+ if code != 0 {
+ return Err(format!("{} ended with exit {code}", s.src));
+ }
+ renumber(&s.out, s.frames)?;
+ Ok(format!("{} frames by Blender in {}", s.frames, s.out.display()))
+}
+
+/// Godot's window size for the shot: an override.cfg in the project (Godot reads it over project.godot) for the
+/// length of the run, since Movie Maker records the window the project opens; put back as it was after.
+struct Override {
+ path: PathBuf,
+ before: Option<Vec<u8>>,
+}
+
+impl Override {
+ fn set(project: &Path, (w, h): (u32, u32)) -> R<Override> {
+ let path = project.join("override.cfg");
+ let before = std::fs::read(&path).ok();
+ let mut text = before.as_deref().map(String::from_utf8_lossy).unwrap_or_default().into_owned();
+ text.push_str(&format!("\n[display]\nwindow/size/viewport_width={w}\nwindow/size/viewport_height={h}\n"));
+ std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
+ Ok(Override { path, before })
+ }
+}
+
+impl Drop for Override {
+ fn drop(&mut self) {
+ let _ = match &self.before {
+ Some(b) => std::fs::write(&self.path, b),
+ None => std::fs::remove_file(&self.path),
+ };
+ }
+}
+
+/// `raea godot shot ...`: `raea godot run` with --movie, --frames and --scene, its frames renumbered; the sound Movie
+/// Maker writes beside them kept as sound.wav.
+pub fn godot(args: &[String]) -> R<String> {
+ let s = parse(args, GODOT_USAGE)?;
+ let none = raea_io_home::home().join("sdk/godot/src/host/none.ts");
+ let (script, scene) = match s.src.strip_prefix("res://") {
+ Some(_) => (none.to_string_lossy().into_owned(), Some(s.src.clone())),
+ None => (s.src.clone(), s.flag("--scene").map(str::to_string)),
+ };
+ fresh(&s.out)?;
+ let mut run = vec!["godot".to_string(), "run".into(), script, "--movie".into(), s.out.join("f.png").to_string_lossy().into_owned()];
+ run.extend(["--fps".into(), s.fps.round().to_string(), "--frames".into(), s.frames.to_string()]);
+ let _over = match s.flag("--project") {
+ Some(p) => {
+ run.extend(["--project".into(), p.to_string()]);
+ Some(Override::set(Path::new(p), s.size)?)
+ }
+ None => {
+ run.extend(["--size".into(), format!("{}x{}", s.size.0, s.size.1)]);
+ None
+ }
+ };
+ if let Some(sc) = scene {
+ run.extend(["--scene".into(), sc]);
+ }
+ if let Some(t) = s.flag("--timeout") {
+ run.extend(["--timeout".into(), t.to_string()]);
+ }
+ if !s.rest.is_empty() {
+ run.push("--".into());
+ run.extend(s.rest.iter().cloned());
+ }
+ crate::godot_run::run(&run)?;
+ let wav = s.out.join("f.wav");
+ if wav.is_file() {
+ let _ = std::fs::rename(&wav, s.out.join("sound.wav"));
+ }
+ renumber(&s.out, s.frames)?;
+ Ok(format!("{} frames by Godot in {}", s.frames, s.out.display()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn frames_are_numbered_from_zero_by_their_own_numbers() {
+ let d = std::env::temp_dir().join(format!("raea-shot-renumber-{}", std::process::id()));
+ fresh(&d).unwrap();
+ for f in ["0001.png", "0002.png", "0003.png", "10000.png", "notes.txt"] {
+ std::fs::write(d.join(f), f).unwrap();
+ }
+ renumber(&d, 3).unwrap();
+ assert_eq!(std::fs::read_to_string(d.join("0000.png")).unwrap(), "0001.png");
+ assert_eq!(std::fs::read_to_string(d.join("0002.png")).unwrap(), "0003.png");
+ assert!(!d.join("10000.png").exists() && !d.join("0003.png").exists() && d.join("notes.txt").exists());
+ // Godot's names, and too few
+ fresh(&d).unwrap();
+ for f in ["f00000000.png", "f00000001.png"] {
+ std::fs::write(d.join(f), f).unwrap();
+ }
+ assert!(renumber(&d, 3).unwrap_err().contains("2 frames were made of the 3"));
+ renumber(&d, 2).unwrap();
+ assert_eq!(std::fs::read_to_string(d.join("0001.png")).unwrap(), "f00000001.png");
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ #[test]
+ fn a_shot_needs_its_out_and_length() {
+ let a = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
+ assert!(parse(&a("blender shot x.ts --frames 3"), BLENDER_USAGE).is_err());
+ assert!(parse(&a("blender shot x.ts -o d"), BLENDER_USAGE).unwrap_err().contains("--frames"));
+ let s = parse(&a("godot shot res://m.tscn -o d --frames 4 --size 640x360 --project p -- go"), GODOT_USAGE).unwrap();
+ assert_eq!((s.frames, s.size, s.flag("--project"), s.rest.clone()), (4, (640, 360), Some("p"), vec!["go".to_string()]));
+ }
+}
diff --git a/apps/interchange/Cargo.toml b/apps/interchange/Cargo.toml
new file mode 100644
index 00000000..9c8a6a2a
--- /dev/null
+++ b/apps/interchange/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "raea-app-interchange"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "A composition's 3D as data another tool builds (`raea scene export`: scene.json, its meshes and models), a Godot project written from it, and what changed in Blender or Godot read back as edits to the TSX (docs/blender.feature BL37-BL39, docs/godot.feature GD12-GD13)"
+
+[dependencies]
+# the composition bundled and stepped to its frames' 3D (raea-runtime-export's scene_frames), walked into parts
+raea-runtime-bundle = { path = "../../runtime/bundle" }
+raea-runtime-export = { path = "../../runtime/export" }
+raea-runtime-scene = { path = "../../runtime/scene" }
+raea-core-scene = { path = "../../core/scene" }
+# a mesh that isn't a primitive written as a .glb (Manifold's)
+raea-core-shape = { path = "../../core/shape" }
+serde_json = "1"
diff --git a/apps/interchange/src/back.rs b/apps/interchange/src/back.rs
new file mode 100644
index 00000000..4b65bed1
--- /dev/null
+++ b/apps/interchange/src/back.rs
@@ -0,0 +1,204 @@
+//! What changed in Blender or Godot, as edits to the TSX at their lines (docs/blender.feature BL39, docs/godot.feature
+//! GD13). The scene went out as scene.json; Blender's or Godot's reader (sdk/blender/src/scene.ts's readBack,
+//! sdk/godot/src/host/back.ts) writes what it holds now in the same terms (raea's axes, each object's raea_id), and this
+//! compares the two at the first frame sent. Nothing in the TSX is changed here: the agent makes the edits.
+
+use std::path::Path;
+
+use serde_json::{Value, json};
+
+/// A placement's numbers (x y z, qx qy qz qw, sx sy sz), or None.
+fn nums(a: &Value) -> Option<Vec<f64>> {
+ let v: Vec<f64> = a.as_array()?.iter().filter_map(Value::as_f64).collect();
+ (v.len() >= 10).then_some(v)
+}
+
+fn r4(x: f64) -> f64 {
+ (x * 1e4).round() / 1e4
+}
+
+/// A quaternion (x y z w) as Euler angles X, Y, Z in radians, applied X then Y then Z (three.js' and raea's default
+/// order for `rotation={[x, y, z]}`).
+pub fn euler_xyz(q: &[f64]) -> [f64; 3] {
+ let (x, y, z, w) = (q[0], q[1], q[2], q[3]);
+ let m02 = 2.0 * (x * z + y * w);
+ let (m12, m22) = (2.0 * (y * z - x * w), 1.0 - 2.0 * (x * x + y * y));
+ let (m01, m00) = (2.0 * (x * y - z * w), 1.0 - 2.0 * (y * y + z * z));
+ let ey = m02.clamp(-1.0, 1.0).asin();
+ let (ex, ez) = if m02.abs() < 0.999_999 { ((-m12).atan2(m22), (-m01).atan2(m00)) } else { ((2.0 * (y * z + x * w)).atan2(1.0 - 2.0 * (x * x + z * z)), 0.0) };
+ [r4(ex), r4(ey), r4(ez)]
+}
+
+/// The angle between two rotations, in degrees.
+fn turned(a: &[f64], b: &[f64]) -> f64 {
+ let d = (a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]).abs().min(1.0);
+ 2.0 * d.acos().to_degrees()
+}
+
+fn edit(part: &Value, what: &str, prop: &str, from: Value, to: Value, said: String) -> Value {
+ json!({ "id": part["id"], "name": part["source"]["name"], "loc": part["source"]["loc"], "change": what, "prop": prop, "from": from, "to": to, "says": said })
+}
+
+fn surface(p: &Value, sent: &Value, now: &Value, out: &mut Vec<Value>) {
+ if !now.is_object() {
+ return;
+ }
+ if let (Some(a), Some(b)) = (sent["color"].as_str(), now["color"].as_str())
+ && !a.eq_ignore_ascii_case(b)
+ {
+ out.push(edit(p, "recoloured", "color", json!(a), json!(b), format!("color {a} -> {b}")));
+ }
+ for (k, prop) in [("roughness", "roughness"), ("metallic", "metalness"), ("intensity", "intensity")] {
+ if let (Some(a), Some(b)) = (sent[k].as_f64(), now[k].as_f64())
+ && (a - b).abs() > 0.005 * a.abs().max(1.0)
+ {
+ out.push(edit(p, if k == "intensity" { "relit" } else { "resurfaced" }, prop, json!(r4(a)), json!(r4(b)), format!("{prop} {} -> {}", r4(a), r4(b))));
+ }
+ }
+ if now["emissive"].as_str().is_some() && sent["emissive"].as_str() != now["emissive"].as_str() {
+ out.push(edit(p, "glows", "emissive", sent["emissive"].clone(), now["emissive"].clone(), format!("emissive {} -> {}", sent["emissive"].as_str().unwrap_or("none"), now["emissive"].as_str().unwrap_or("none"))));
+ }
+}
+
+fn placement(p: &Value, a: &[f64], b: &[f64], out: &mut Vec<Value>) {
+ let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
+ if d.iter().any(|x| x.abs() > 1e-3) {
+ let to = [r4(b[0]), r4(b[1]), r4(b[2])];
+ out.push(edit(p, "moved", "position", json!([r4(a[0]), r4(a[1]), r4(a[2])]), json!(to), format!("moved by [{}, {}, {}] to {to:?} (world)", r4(d[0]), r4(d[1]), r4(d[2]))));
+ }
+ if turned(&a[3..7], &b[3..7]) > 0.05 {
+ let e = euler_xyz(&b[3..7]);
+ out.push(edit(p, "turned", "rotation", json!(euler_xyz(&a[3..7])), json!(e), format!("turned {:.1} degrees: rotation {e:?} (radians, X Y Z; world), quaternion [{}, {}, {}, {}]", turned(&a[3..7], &b[3..7]), r4(b[3]), r4(b[4]), r4(b[5]), r4(b[6]))));
+ }
+ if (0..3).any(|k| (a[7 + k] - b[7 + k]).abs() > 1e-3 * a[7 + k].abs().max(1.0)) {
+ let to = [r4(b[7]), r4(b[8]), r4(b[9])];
+ out.push(edit(p, "scaled", "scale", json!([r4(a[7]), r4(a[8]), r4(a[9])]), json!(to), format!("scale {to:?}")));
+ }
+}
+
+/// The edits from `sent` (scene.json) to `now` (what Blender or Godot holds), at the first frame sent.
+pub fn compare(sent: &Value, now: &Value) -> Vec<Value> {
+ let mut out = Vec::new();
+ let held: Vec<&Value> = now["parts"].as_array().into_iter().flatten().collect();
+ for p in sent["parts"].as_array().into_iter().flatten() {
+ let Some(n) = held.iter().find(|n| n["id"] == p["id"]) else {
+ out.push(edit(p, "deleted", "", Value::Null, Value::Null, "deleted".into()));
+ continue;
+ };
+ let first = p["at"].as_array().into_iter().flatten().find(|a| !a.is_null()).and_then(nums);
+ if let (Some(a), Some(b)) = (first, nums(&n["at"])) {
+ placement(p, &a, &b, &mut out);
+ }
+ surface(p, &p["material"], &n["material"], &mut out);
+ surface(p, &p["light"], &n["light"], &mut out);
+ }
+ let cam = sent["camera"].as_array().into_iter().flatten().find(|c| c.is_object());
+ if let (Some(c), Some(n)) = (cam, now["camera"].as_object()) {
+ let me = json!({ "id": "camera", "source": { "name": "camera" } });
+ if let (Some(a), Some(b)) = (nums(&c["at"]), n.get("at").and_then(nums)) {
+ placement(&me, &a, &b, &mut out);
+ }
+ if let (Some(a), Some(b)) = (c["fov"].as_f64(), n.get("fov").and_then(Value::as_f64))
+ && (a - b).abs() > 0.05
+ {
+ out.push(edit(&me, "lens", "fov", json!(r4(a)), json!(r4(b)), format!("fov {} -> {} (degrees, vertical)", r4(a), r4(b))));
+ }
+ }
+ for n in now["new"].as_array().into_iter().flatten() {
+ let file = n["file"].as_str().unwrap_or("");
+ let at = nums(&n["at"]).map(|v| format!(" at [{}, {}, {}]", r4(v[0]), r4(v[1]), r4(v[2]))).unwrap_or_default();
+ out.push(json!({ "id": Value::Null, "name": n["name"], "loc": Value::Null, "change": "added", "prop": "", "from": Value::Null, "to": n["at"],
+ "says": format!("added: <Model src={{staticFile(\"{}\")}} />{at}, written as {file} with its sidecar", file.trim_start_matches("media/")) }));
+ }
+ out
+}
+
+/// Where a part is written in the TSX: its stamp, else the line naming it (`name="crate"`), else for the camera and
+/// a light that has no name the Nth line writing its element (the id's `#N`: `<DirectionalLight`), else None.
+pub fn line_of(tsx: &Path, e: &Value) -> Option<String> {
+ if let Some(loc) = e["loc"].as_str() {
+ return Some(loc.to_string());
+ }
+ let text = std::fs::read_to_string(tsx).ok()?;
+ let file = tsx.file_name()?.to_string_lossy();
+ let at = |i: usize| format!("{file}:{}", i + 1);
+ if let Some(name) = e["name"].as_str().filter(|&n| n != "camera" || e["id"] != "camera") {
+ return text.lines().position(|l| l.contains(&format!("name=\"{name}\"")) || l.contains(&format!("name: \"{name}\""))).map(at);
+ }
+ let id = e["id"].as_str()?;
+ let (tag, n) = match id.split_once('|') {
+ None if id == "camera" => ("<Camera3d", 0),
+ Some((kind, rest)) => {
+ let tag = match kind {
+ "directional" => "<DirectionalLight",
+ "point" => "<PointLight",
+ "spot" => "<SpotLight",
+ "rect" => "<RectLight",
+ _ => return None,
+ };
+ (tag, rest.rsplit_once('#').and_then(|(_, n)| n.parse().ok()).unwrap_or(0))
+ }
+ None => return None,
+ };
+ text.lines().enumerate().filter(|(_, l)| l.contains(tag) && !l.contains(&format!("{tag}s"))).nth(n).map(|(i, _)| at(i))
+}
+
+/// The edits as lines, each with where it goes in the TSX.
+pub fn said(edits: &[Value], tsx: &Path) -> String {
+ if edits.is_empty() {
+ return "nothing changed".into();
+ }
+ edits.iter().map(|e| {
+ let who = e["name"].as_str().map(|n| format!("\"{n}\"")).unwrap_or_else(|| e["id"].as_str().unwrap_or("").to_string());
+ let at = line_of(tsx, e).map(|l| format!(" ({l})")).unwrap_or_default();
+ format!("{who}{at}: {}", e["says"].as_str().unwrap_or(""))
+ }).collect::<Vec<_>>().join("\n")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sent() -> Value {
+ json!({ "parts": [
+ { "id": "mesh|a#0", "kind": "mesh", "source": { "name": "crate" }, "at": [[0, 0.5, 0, 0, 0, 0, 1, 1, 1, 1]], "material": { "color": "#ff0000", "roughness": 0.5, "metallic": 0 } },
+ { "id": "point|#0", "kind": "light", "source": {}, "at": [[0, 3, 0, 0, 0, 0, 1, 1, 1, 1]], "light": { "color": "#ffffff", "intensity": 1 } }
+ ], "camera": [{ "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 }] })
+ }
+
+ #[test]
+ fn nothing_changed_says_so() {
+ let s = sent();
+ let now = json!({ "parts": [
+ { "id": "mesh|a#0", "at": [0, 0.5, 0, 0, 0, 0, 1, 1, 1, 1], "material": { "color": "#FF0000", "roughness": 0.5, "metallic": 0 } },
+ { "id": "point|#0", "at": [0, 3, 0, 0, 0, 0, 1, 1, 1, 1], "light": { "color": "#ffffff", "intensity": 1.0001 } }
+ ], "camera": { "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 } });
+ assert_eq!(compare(&s, &now), Vec::<Value>::new());
+ }
+
+ #[test]
+ fn each_change_is_one_edit() {
+ let h = std::f64::consts::FRAC_1_SQRT_2;
+ let now = json!({ "parts": [
+ { "id": "mesh|a#0", "at": [1, 0.5, 0, 0, h, 0, h, 2, 2, 2], "material": { "color": "#00ff00", "roughness": 0.2, "metallic": 0 } }
+ ], "camera": { "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 30 }, "new": [{ "name": "Cube", "file": "media/cube.glb", "at": [2, 0, 0, 0, 0, 0, 1, 1, 1, 1] }] });
+ let e = compare(&sent(), &now);
+ let changes: Vec<&str> = e.iter().map(|x| x["change"].as_str().unwrap()).collect();
+ assert_eq!(changes, ["moved", "turned", "scaled", "recoloured", "resurfaced", "deleted", "lens", "added"]);
+ assert_eq!(e[1]["to"], json!([0.0, 1.5708, 0.0]));
+ assert!(e[7]["says"].as_str().unwrap().contains("staticFile(\"cube.glb\")"));
+ }
+
+ #[test]
+ fn a_part_is_found_by_its_name() {
+ let f = std::env::temp_dir().join(format!("raea-back-{}.tsx", std::process::id()));
+ std::fs::write(&f, "a\n <Cuboid name=\"crate\" size={[1, 1, 1]} />\n <Camera3d transform={t} />\n <PointLight intensity={1} />\n <PointLight intensity={2} />\n").unwrap();
+ let file = f.file_name().unwrap().to_string_lossy().to_string();
+ assert_eq!(line_of(&f, &json!({ "name": "crate" })).unwrap(), format!("{file}:2"));
+ assert_eq!(line_of(&f, &json!({ "id": "camera", "name": "camera" })).unwrap(), format!("{file}:3"));
+ assert_eq!(line_of(&f, &json!({ "id": "point|#1", "name": null })).unwrap(), format!("{file}:5"));
+ assert_eq!(line_of(&f, &json!({ "id": "spot|#0", "name": null })), None);
+ assert_eq!(line_of(&f, &json!({ "name": "lamp", "loc": "edit.tsx:9:3" })).unwrap(), "edit.tsx:9:3");
+ let _ = std::fs::remove_file(&f);
+ }
+}
diff --git a/apps/interchange/src/export.rs b/apps/interchange/src/export.rs
new file mode 100644
index 00000000..ad11c311
--- /dev/null
+++ b/apps/interchange/src/export.rs
@@ -0,0 +1,314 @@
+//! `raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]` (docs/blender.feature BL37): the
+//! composition's 3D at a frame, or on every frame of a span, as DIR/scene.json, with each mesh that isn't a primitive in
+//! DIR/meshes/ and each model's file in DIR/models/. Every part is placed in the world (y up, metres; a quaternion
+//! x y z w), so Blender (sdk/blender/src/scene.ts) and Godot (godot.rs) each build it with their own parts.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use raea_core_scene::{Item, hex, light_power, n, num, tracks_of, vec3};
+use serde_json::{Value, json};
+
+use crate::R;
+
+pub const USAGE: &str = "raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]";
+
+/// The frames asked for: --frame N, every frame of --at A-B, else 0.
+fn frames_of(args: &[String]) -> R<Vec<i64>> {
+ let fl = |k: &str| args.iter().position(|a| a == k).and_then(|i| args.get(i + 1));
+ if let Some(span) = fl("--at") {
+ let (a, b) = span.split_once('-').ok_or("--at takes A-B, the first and last frame")?;
+ let (a, b): (i64, i64) = (a.trim().parse().map_err(|_| "--at A-B: A is a frame")?, b.trim().parse().map_err(|_| "--at A-B: B is a frame")?);
+ if b < a || b - a > 10_000 {
+ return Err("--at A-B: B at or after A, at most 10 000 frames".into());
+ }
+ return Ok((a..=b).collect());
+ }
+ Ok(vec![fl("--frame").map(|f| f.parse().map_err(|_| "--frame takes a frame number")).transpose()?.unwrap_or(0)])
+}
+
+fn r6(x: f32) -> f64 {
+ (x as f64 * 1e6).round() / 1e6
+}
+
+/// A rotation turning -Z (the way a camera and a light face, in glTF, Blender and Godot alike) to `dir`, +Y towards
+/// `up`: x y z w.
+pub fn look_quat(dir: [f64; 3], up: [f64; 3]) -> [f64; 4] {
+ let norm = |v: [f64; 3]| {
+ let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
+ if l < 1e-12 { None } else { Some([v[0] / l, v[1] / l, v[2] / l]) }
+ };
+ let cross = |a: [f64; 3], b: [f64; 3]| [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+ let Some(f) = norm(dir) else { return [0.0, 0.0, 0.0, 1.0] };
+ let z = [-f[0], -f[1], -f[2]];
+ let x = norm(cross(up, z)).or_else(|| norm(cross([0.0, 0.0, 1.0], z))).unwrap_or([1.0, 0.0, 0.0]);
+ let y = cross(z, x);
+ // the rotation matrix's columns x, y, z as a quaternion
+ let (m00, m11, m22) = (x[0], y[1], z[2]);
+ let t = m00 + m11 + m22;
+ let q = if t > 0.0 {
+ let s = (t + 1.0).sqrt() * 2.0;
+ [(y[2] - z[1]) / s, (z[0] - x[2]) / s, (x[1] - y[0]) / s, 0.25 * s]
+ } else if m00 > m11 && m00 > m22 {
+ let s = (1.0 + m00 - m11 - m22).sqrt() * 2.0;
+ [0.25 * s, (y[0] + x[1]) / s, (z[0] + x[2]) / s, (y[2] - z[1]) / s]
+ } else if m11 > m22 {
+ let s = (1.0 + m11 - m00 - m22).sqrt() * 2.0;
+ [(y[0] + x[1]) / s, 0.25 * s, (z[1] + y[2]) / s, (z[0] - x[2]) / s]
+ } else {
+ let s = (1.0 + m22 - m00 - m11).sqrt() * 2.0;
+ [(z[0] + x[2]) / s, (z[1] + y[2]) / s, 0.25 * s, (x[1] - y[0]) / s]
+ };
+ q.map(|v| (v * 1e6).round() / 1e6)
+}
+
+/// A mesh or model's placement: position, rotation (x y z w), scale.
+fn placed(it: &Item) -> Value {
+ let (s, q, t) = it.world.to_scale_rotation_translation();
+ let q = if q.is_finite() { [q.x, q.y, q.z, q.w] } else { [0.0, 0.0, 0.0, 1.0] };
+ json!([r6(t.x), r6(t.y), r6(t.z), r6(q[0]), r6(q[1]), r6(q[2]), r6(q[3]), r6(s.x), r6(s.y), r6(s.z)])
+}
+
+/// A light's placement: where it is, turned to face its target (a sun's from its position to its target too).
+fn light_placed(it: &Item) -> Value {
+ let p = vec3(&it.props, "position", if it.kind == "directional" { [0.0, 1.0, 0.0] } else { [0.0; 3] });
+ let w = it.world.transform_point3([p[0] as f32, p[1] as f32, p[2] as f32].into());
+ let t = vec3(&it.props, "target", [0.0; 3]);
+ let w = [w.x as f64, w.y as f64, w.z as f64];
+ let q = look_quat([t[0] - w[0], t[1] - w[1], t[2] - w[2]], [0.0, 1.0, 0.0]);
+ let r = |x: f64| (x * 1e6).round() / 1e6;
+ json!([r(w[0]), r(w[1]), r(w[2]), q[0], q[1], q[2], q[3], 1, 1, 1])
+}
+
+/// What a mesh is made of, as the parts another tool has: a primitive with its sizes, else its Manifold mesh as a .glb.
+fn shape(expr: &str, out: &Path, meshes: &mut BTreeMap<String, String>) -> R<Value> {
+ if let Some(s) = raea_core_shape::cuboid_of(expr) {
+ return Ok(json!({ "type": "cuboid", "size": s }));
+ }
+ if let Some(raea_core_shape::SphereOf::Ico { radius, .. } | raea_core_shape::SphereOf::Uv { radius, .. }) = raea_core_shape::sphere_of(expr) {
+ return Ok(json!({ "type": "sphere", "radius": radius }));
+ }
+ if let Some((radius, height)) = raea_core_shape::cylinder_of(expr) {
+ return Ok(json!({ "type": "cylinder", "radius": radius, "height": height }));
+ }
+ if let Some((_, size)) = raea_core_shape::plane_of(expr).filter(|(n, _)| *n == [0.0, 1.0, 0.0]) {
+ return Ok(json!({ "type": "plane", "size": size }));
+ }
+ let k = meshes.len();
+ let file = match meshes.get(expr) {
+ Some(f) => f.clone(),
+ None => {
+ let f = format!("meshes/mesh{k}.glb");
+ let m = raea_core_shape::solid(expr)?;
+ raea_core_shape::export(&m, &out.join(&f).to_string_lossy(), "glb")?;
+ // and as an .obj, which Godot imports as a mesh of its own (a .glb comes in as a scene)
+ raea_core_shape::export(&m, &out.join(f.replace(".glb", ".obj")).to_string_lossy(), "obj")?;
+ meshes.insert(expr.to_string(), f.clone());
+ f
+ }
+ };
+ Ok(json!({ "type": "mesh", "file": file, "obj": file.replace(".glb", ".obj") }))
+}
+
+/// A file the scene names (a model, a texture) copied into `sub` of the export with its licence sidecar: its path there.
+fn copied(dir: &Path, src: &str, out: &Path, sub: &str, files: &mut BTreeMap<PathBuf, String>) -> R<String> {
+ let from = raea_core_scene::media_path(dir, if src.starts_with('/') || src.contains("://") { src.to_string() } else { format!("/media/{src}") }.as_str());
+ let from = if from.exists() { from } else { raea_core_scene::media_path(dir, src) };
+ if let Some(f) = files.get(&from) {
+ return Ok(f.clone());
+ }
+ let name = from.file_name().and_then(|n| n.to_str()).ok_or_else(|| format!("{src}: no file"))?;
+ let mut rel = format!("{sub}/{name}");
+ if files.values().any(|v| *v == rel) {
+ rel = format!("{sub}/{}-{name}", files.len());
+ }
+ std::fs::create_dir_all(out.join(sub)).map_err(|e| e.to_string())?;
+ std::fs::copy(&from, out.join(&rel)).map_err(|e| format!("{}: {e}", from.display()))?;
+ for side in [format!("{}.json", from.display()), format!("{}.json", from.with_extension("").display())] {
+ if Path::new(&side).is_file() {
+ let _ = std::fs::copy(&side, out.join(format!("{rel}.json")));
+ break;
+ }
+ }
+ files.insert(from, rel.clone());
+ Ok(rel)
+}
+
+/// A part's surface: three.js-style props as the renderer reads them (runtime/scene's meshes_rows).
+fn material(it: &Item, dir: &Path, out: &Path, files: &mut BTreeMap<PathBuf, String>) -> Value {
+ let Some(m) = &it.material else { return json!({ "color": "#cccccc", "roughness": 0.5, "metallic": 0.0 }) };
+ let p = &m.props;
+ let mut v = json!({ "color": hex(p.get("color")).unwrap_or("#cccccc".into()), "roughness": n(p, "roughness", 0.5), "metallic": n(p, "metalness", 0.0) });
+ if let Some(e) = hex(p.get("emissive")).filter(|e| e != "#000000") {
+ v["emissive"] = json!(e);
+ v["emissive_strength"] = json!(raea_core_scene::emissive_power(p));
+ }
+ if let Some(o) = num(p, "opacity").filter(|o| *o < 1.0) {
+ v["opacity"] = json!(o);
+ }
+ if &*m.kind == "MeshBasicMaterial" || p.get("unlit") == Some(&Value::Bool(true)) {
+ v["unlit"] = json!(true);
+ }
+ for (prop, key) in [("map", "color_map"), ("normalMap", "normal_map"), ("roughnessMap", "roughness_map"), ("metalnessMap", "metallic_map"), ("emissiveMap", "emissive_map")] {
+ if let Some(src) = p.get(prop).and_then(Value::as_str)
+ && let Ok(f) = copied(dir, src, out, "textures", files)
+ {
+ v[key] = json!(f);
+ }
+ }
+ v
+}
+
+/// The light another tool sets: its kind, colour, intensity as raea reads it (1 is a 3d.tsx light's default) and in
+/// Bevy's units (lux for a sun, lumens else), reach and cone.
+fn light(it: &Item) -> Value {
+ let p = &it.props;
+ let power = light_power(it.kind, p);
+ let unit = if it.kind == "directional" { raea_core_scene::LUX } else { raea_core_scene::LUMENS };
+ let mut v = json!({ "type": it.kind, "color": hex(p.get("color")).unwrap_or("#ffffff".into()), "intensity": power / unit });
+ v[if it.kind == "directional" { "lux" } else { "lumens" }] = json!(power);
+ if let Some(d) = num(p, "distance").filter(|d| *d > 0.0) {
+ v["range"] = json!(d);
+ }
+ if it.kind == "spot" {
+ v["angle"] = json!(n(p, "angle", std::f64::consts::FRAC_PI_3));
+ v["penumbra"] = json!(n(p, "penumbra", 0.0));
+ }
+ if it.kind == "rect" {
+ v["width"] = json!(n(p, "width", 1.0));
+ v["height"] = json!(n(p, "height", 1.0));
+ }
+ v
+}
+
+/// Where the part is written in the TSX, when the bundle stamped it, and its name.
+fn source(it: &Item) -> Value {
+ let s = |k: &str| it.props.get(k).and_then(Value::as_str).map(str::to_string);
+ json!({ "name": s("name"), "loc": s("data-raea-loc"), "use": s("data-raea-use") })
+}
+
+/// The parts of every frame asked for (`all`, one list of items each), written into `out`: scene.json's value.
+pub fn scene(all: &[Vec<Item>], frames: &[i64], dir: &Path, out: &Path) -> R<Value> {
+ let (mut meshes, mut files) = (BTreeMap::new(), BTreeMap::new());
+ let mut parts = Vec::new();
+ for (id, track) in tracks_of(all, &["mesh", "model", "directional", "point", "spot", "rect"]) {
+ let Some(first) = track.iter().flatten().next() else { continue };
+ let mut part = json!({ "id": id, "kind": if first.kind == "mesh" || first.kind == "model" { first.kind } else { "light" }, "source": source(first) });
+ match first.kind {
+ // an <Instances> set is many copies of one mesh: left out (counted in `left`)
+ "mesh" if first.at.is_some() => continue,
+ "mesh" => {
+ let Some(expr) = first.shape.as_deref() else { continue };
+ part["shape"] = shape(expr, out, &mut meshes)?;
+ part["material"] = material(first, dir, out, &mut files);
+ }
+ "model" => {
+ let src = first.props.get("src").and_then(Value::as_str).unwrap_or_default();
+ part["model"] = json!(copied(dir, src, out, "models", &mut files)?);
+ }
+ _ => part["light"] = light(first),
+ }
+ let at: Vec<Value> = track.iter().map(|t| t.as_ref().map_or(Value::Null, |it| if part["kind"] == "light" { light_placed(it) } else { placed(it) })).collect();
+ part["at"] = json!(at);
+ parts.push(part);
+ }
+ // the camera: the first drawing one each frame, from its position to what it looks at
+ let cam: Vec<Value> = all.iter().map(|its| {
+ its.iter().find(|i| i.kind == "camera").map_or(Value::Null, |c| {
+ let (p, l, up) = (vec3(&c.props, "position", [0.0, 0.0, 5.0]), vec3(&c.props, "lookAt", [0.0; 3]), vec3(&c.props, "up", [0.0, 1.0, 0.0]));
+ let q = look_quat([l[0] - p[0], l[1] - p[1], l[2] - p[2]], up);
+ json!({ "at": [p[0], p[1], p[2], q[0], q[1], q[2], q[3], 1, 1, 1], "look": l, "fov": n(&c.props, "fov", 50.0) })
+ })
+ }).collect();
+ let ambient = all[0].iter().find(|i| i.kind == "ambient").map(|a| json!({ "color": hex(a.props.get("color")).unwrap_or("#ffffff".into()), "nits": light_power("ambient", &a.props) }));
+ // what doesn't cross, by kind, counted on the first frame
+ let mut left: BTreeMap<&str, usize> = BTreeMap::new();
+ for i in all[0].iter().filter(|i| !matches!(i.kind, "mesh" | "model" | "directional" | "point" | "spot" | "rect" | "camera" | "ambient")) {
+ *left.entry(i.kind).or_default() += 1;
+ }
+ let copies = all[0].iter().filter(|i| i.kind == "mesh" && i.at.is_some()).count();
+ if copies > 0 {
+ left.insert("instances", copies);
+ }
+ Ok(json!({ "raea": "scene/1", "frames": frames, "parts": parts, "camera": cam, "ambient": ambient, "left": left }))
+}
+
+/// `raea scene export ...`: scene.json written, and its value.
+pub fn export(args: &[String]) -> R<(PathBuf, Value)> {
+ let edit = args.get(2).ok_or(USAGE)?;
+ let tsx = PathBuf::from(edit).canonicalize().map_err(|e| format!("{edit}: {e}"))?;
+ let dir = tsx.parent().ok_or("the edit's folder")?.to_path_buf();
+ let out = args.iter().position(|a| a == "-o").and_then(|i| args.get(i + 1)).ok_or(USAGE)?;
+ let out = std::path::absolute(out).map_err(|e| e.to_string())?;
+ let frames = frames_of(args)?;
+ let js = std::env::temp_dir().join(format!("raea-scene-export-{}.js", std::process::id()));
+ // each part's place in the TSX (data-raea-loc), which raea blender back and raea godot back say their edits at
+ // SAFETY: the CLI sets it before the bundle starts any thread that reads the environment
+ unsafe { std::env::set_var("RAEA_SOURCE_STAMPS", "1") };
+ raea_runtime_bundle::bundle_composition(&tsx, &js, &raea_runtime_bundle::comp_opts(args)?, None)?;
+ let got = raea_runtime_export::scene_frames(&js, &dir, frames[frames.len() - 1] + 1, false, &frames);
+ let _ = std::fs::remove_file(&js);
+ let (got, w, h, fps) = got?.ok_or("the composition has no 3D")?;
+ let all: Vec<Vec<Item>> = frames.iter().map(|f| got.iter().find(|(k, _)| k == f).map(|(_, fr)| raea_runtime_scene::items_of(&fr.scene)).unwrap_or_default()).collect();
+ if all.iter().all(Vec::is_empty) {
+ return Err(format!("{edit}: no 3D on frame {}", frames[0]));
+ }
+ let _ = std::fs::remove_dir_all(out.join("meshes"));
+ std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
+ let mut v = scene(&all, &frames, &dir, &out)?;
+ v["from"] = json!(tsx.to_string_lossy());
+ v["fps"] = json!(fps);
+ v["size"] = json!([w, h]);
+ std::fs::write(out.join("scene.json"), serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| e.to_string())?;
+ Ok((out, v))
+}
+
+/// The summary line of an export.
+pub fn said(out: &Path, v: &Value) -> String {
+ let parts = v["parts"].as_array().map_or(0, Vec::len);
+ let frames = v["frames"].as_array().map_or(0, Vec::len);
+ let left: Vec<String> = v["left"].as_object().into_iter().flatten().map(|(k, n)| format!("{n} {k}")).collect();
+ let left = if left.is_empty() { String::new() } else { format!("; not carried: {}", left.join(", ")) };
+ format!("{parts} parts on {frames} frame{} in {}{left}", if frames == 1 { "" } else { "s" }, out.join("scene.json").display())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_rotation_faces_where_it_is_turned() {
+ // looking down -Z is no turn; looking down +X turns -90 degrees about Y
+ assert_eq!(look_quat([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]), [0.0, 0.0, 0.0, 1.0]);
+ let q = look_quat([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]);
+ assert!((q[1] + std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6 && (q[3] - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6, "{q:?}");
+ // straight down still has a way up
+ let q = look_quat([0.0, -1.0, 0.0], [0.0, 1.0, 0.0]);
+ assert!(q.iter().all(|v| v.is_finite()) && (q.iter().map(|v| v * v).sum::<f64>() - 1.0).abs() < 1e-5);
+ }
+
+ #[test]
+ fn frames_are_one_or_a_span() {
+ let a = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
+ assert_eq!(frames_of(&a("scene export e.tsx")).unwrap(), vec![0]);
+ assert_eq!(frames_of(&a("scene export e.tsx --frame 12")).unwrap(), vec![12]);
+ assert_eq!(frames_of(&a("scene export e.tsx --at 3-5")).unwrap(), vec![3, 4, 5]);
+ assert!(frames_of(&a("scene export e.tsx --at 5-3")).is_err());
+ }
+
+ #[test]
+ fn primitives_cross_as_themselves_and_the_rest_as_a_mesh() {
+ let out = std::env::temp_dir().join(format!("raea-interchange-shape-{}", std::process::id()));
+ std::fs::create_dir_all(out.join("meshes")).unwrap();
+ let mut m = BTreeMap::new();
+ assert_eq!(shape("box(1, 2, 3)", &out, &mut m).unwrap(), json!({ "type": "cuboid", "size": [1.0, 2.0, 3.0] }));
+ assert_eq!(shape("sphere(0.5)", &out, &mut m).unwrap()["type"], "sphere");
+ assert_eq!(shape("rotate(cone(0.5, 0.5, 2), -90, 0, 0)", &out, &mut m).unwrap()["height"], 2.0);
+ let v = shape("difference(box(1, 1, 1), sphere(0.6))", &out, &mut m).unwrap();
+ assert_eq!(v["type"], "mesh");
+ assert!(out.join(v["file"].as_str().unwrap()).is_file());
+ // the same mesh twice is one file
+ assert_eq!(shape("difference(box(1, 1, 1), sphere(0.6))", &out, &mut m).unwrap(), v);
+ let _ = std::fs::remove_dir_all(&out);
+ }
+}
diff --git a/apps/interchange/src/godot.rs b/apps/interchange/src/godot.rs
new file mode 100644
index 00000000..b5f3dfcb
--- /dev/null
+++ b/apps/interchange/src/godot.rs
@@ -0,0 +1,293 @@
+//! A raea scene as a Godot project (docs/godot.feature GD12): scene export's folder made into project.godot and
+//! main.tscn, each part Godot's own node (a primitive its own mesh with a StandardMaterial3D, any other mesh an imported
+//! .obj, a model its .glb instanced, lights, the camera, a WorldEnvironment), named for the part and carrying its id;
+//! a span's frames an AnimationPlayer that plays as the project runs.
+
+use std::collections::BTreeSet;
+use std::fmt::Write as _;
+use std::path::Path;
+
+use serde_json::Value;
+
+use crate::R;
+
+/// `#rrggbb` as Godot's Color (sRGB, as Godot's albedo and light colours are given).
+fn color(hex: &str, a: f64) -> String {
+ let h = hex.trim_start_matches('#');
+ let c = |i: usize| u8::from_str_radix(h.get(i..i + 2).unwrap_or("cc"), 16).unwrap_or(204) as f64 / 255.0;
+ format!("Color({:.4}, {:.4}, {:.4}, {a})", c(0), c(2), c(4))
+}
+
+/// A placement (x y z, qx qy qz qw, sx sy sz) as Godot's Transform3D: the basis by rows, the rotation's columns scaled.
+pub fn transform(at: &Value) -> String {
+ let v: Vec<f64> = at.as_array().into_iter().flatten().filter_map(Value::as_f64).collect();
+ if v.len() < 10 {
+ return "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)".into();
+ }
+ let (x, y, z, w) = (v[3], v[4], v[5], v[6]);
+ let r = [
+ [1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y - z * w), 2.0 * (x * z + y * w)],
+ [2.0 * (x * y + z * w), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z - x * w)],
+ [2.0 * (x * z - y * w), 2.0 * (y * z + x * w), 1.0 - 2.0 * (x * x + y * y)],
+ ];
+ let s = [v[7], v[8], v[9]];
+ let b: Vec<String> = (0..3).flat_map(|i| (0..3).map(move |j| (i, j))).map(|(i, j)| num(r[i][j] * s[j])).collect();
+ format!("Transform3D({}, {}, {}, {})", b.join(", "), num(v[0]), num(v[1]), num(v[2]))
+}
+
+fn num(x: f64) -> String {
+ let r = (x * 1e6).round() / 1e6;
+ if r == 0.0 { "0".into() } else { format!("{r}") }
+}
+
+/// A node name Godot takes (no . : @ / " %), unique in the scene.
+fn node_name(want: &str, taken: &mut BTreeSet<String>) -> String {
+ let base: String = want.chars().map(|c| if ".:@/\"%#|".contains(c) || c.is_control() { '_' } else { c }).collect();
+ let base = if base.trim().is_empty() { "Part".to_string() } else { base.trim().to_string() };
+ let mut name = base.clone();
+ let mut k = 2;
+ while !taken.insert(name.clone()) {
+ name = format!("{base}{k}");
+ k += 1;
+ }
+ name
+}
+
+/// A part's node name: its name in the TSX, else what it is ("Sun", "PointLight", "Cuboid", the model's file).
+pub fn wanted(p: &Value) -> String {
+ if let Some(n) = p["source"]["name"].as_str() {
+ return n.to_string();
+ }
+ let what = match (p["kind"].as_str(), p["light"]["type"].as_str(), p["shape"]["type"].as_str()) {
+ (_, Some("directional"), _) => "Sun",
+ (_, Some("point"), _) => "PointLight",
+ (_, Some("spot"), _) => "SpotLight",
+ (_, Some("rect"), _) => "AreaLight",
+ (Some("model"), _, _) => return p["model"].as_str().and_then(|m| Path::new(m).file_stem()?.to_str()).unwrap_or("Model").to_string(),
+ (_, _, Some("cuboid")) => "Cuboid",
+ (_, _, Some("sphere")) => "Sphere",
+ (_, _, Some("cylinder")) => "Cylinder",
+ (_, _, Some("plane")) => "Plane",
+ _ => "Mesh",
+ };
+ what.to_string()
+}
+
+/// The tscn's resources and nodes, written in order: ext_resources, sub_resources, then nodes.
+#[derive(Default)]
+struct Tscn {
+ ext: String,
+ sub: String,
+ nodes: String,
+ n_ext: usize,
+ n_sub: usize,
+}
+
+impl Tscn {
+ fn ext(&mut self, kind: &str, path: &str) -> String {
+ self.n_ext += 1;
+ let _ = writeln!(self.ext, "[ext_resource type=\"{kind}\" path=\"res://{path}\" id=\"{}\"]", self.n_ext);
+ format!("ExtResource(\"{}\")", self.n_ext)
+ }
+ fn sub(&mut self, kind: &str, body: &str) -> String {
+ self.n_sub += 1;
+ let _ = write!(self.sub, "\n[sub_resource type=\"{kind}\" id=\"{kind}_{}\"]\n{body}", self.n_sub);
+ format!("SubResource(\"{kind}_{}\")", self.n_sub)
+ }
+}
+
+fn material(m: &Value) -> String {
+ let f = |k: &str, d: f64| m[k].as_f64().unwrap_or(d);
+ let mut s = format!("albedo_color = {}\nmetallic = {}\nroughness = {}\n", color(m["color"].as_str().unwrap_or("#cccccc"), f("opacity", 1.0)), num(f("metallic", 0.0)), num(f("roughness", 0.5)));
+ if let Some(e) = m["emissive"].as_str() {
+ let _ = write!(s, "emission_enabled = true\nemission = {}\nemission_energy_multiplier = {}\n", color(e, 1.0), num(f("emissive_strength", 1.0)));
+ }
+ if m["opacity"].as_f64().is_some_and(|o| o < 1.0) {
+ s.push_str("transparency = 1\n");
+ }
+ if m["unlit"] == true {
+ s.push_str("shading_mode = 0\n");
+ }
+ // its textures need their files' ext_resources: part() adds them
+ s
+}
+
+/// One part's node (and its resources); the first frame it's in places it.
+fn part(t: &mut Tscn, p: &Value, name: &str) {
+ let first = p["at"].as_array().into_iter().flatten().find(|a| !a.is_null()).cloned().unwrap_or(Value::Null);
+ let meta = format!("metadata/raea_id = \"{}\"\n", p["id"].as_str().unwrap_or("").replace('"', "'"));
+ let tr = transform(&first);
+ match p["kind"].as_str() {
+ Some("mesh") => {
+ let sh = &p["shape"];
+ let mesh = match sh["type"].as_str() {
+ Some("cuboid") => {
+ let s = &sh["size"];
+ t.sub("BoxMesh", &format!("size = Vector3({}, {}, {})\n", num(s[0].as_f64().unwrap_or(1.0)), num(s[1].as_f64().unwrap_or(1.0)), num(s[2].as_f64().unwrap_or(1.0))))
+ }
+ Some("sphere") => {
+ let r = sh["radius"].as_f64().unwrap_or(0.5);
+ t.sub("SphereMesh", &format!("radius = {}\nheight = {}\n", num(r), num(2.0 * r)))
+ }
+ Some("cylinder") => {
+ let r = num(sh["radius"].as_f64().unwrap_or(0.5));
+ t.sub("CylinderMesh", &format!("top_radius = {r}\nbottom_radius = {r}\nheight = {}\n", num(sh["height"].as_f64().unwrap_or(1.0))))
+ }
+ Some("plane") => {
+ let s = &sh["size"];
+ t.sub("PlaneMesh", &format!("size = Vector2({}, {})\n", num(s[0].as_f64().unwrap_or(1.0)), num(s[1].as_f64().unwrap_or(1.0))))
+ }
+ _ => t.ext("ArrayMesh", sh["obj"].as_str().unwrap_or("")),
+ };
+ let mut mat = material(&p["material"]);
+ if let Some(f) = p["material"]["color_map"].as_str() {
+ let tex = t.ext("Texture2D", f);
+ let _ = writeln!(mat, "albedo_texture = {tex}");
+ }
+ if let Some(f) = p["material"]["normal_map"].as_str() {
+ let tex = t.ext("Texture2D", f);
+ let _ = writeln!(mat, "normal_enabled = true\nnormal_texture = {tex}");
+ }
+ let mat = t.sub("StandardMaterial3D", &mat);
+ let _ = write!(t.nodes, "\n[node name=\"{name}\" type=\"MeshInstance3D\" parent=\".\"]\ntransform = {tr}\nmesh = {mesh}\nsurface_material_override/0 = {mat}\n{meta}");
+ }
+ Some("model") => {
+ let scene = t.ext("PackedScene", p["model"].as_str().unwrap_or(""));
+ let _ = write!(t.nodes, "\n[node name=\"{name}\" parent=\".\" instance={scene}]\ntransform = {tr}\n{meta}");
+ }
+ _ => {
+ let l = &p["light"];
+ let kind = match l["type"].as_str() {
+ Some("directional") => "DirectionalLight3D",
+ Some("spot") => "SpotLight3D",
+ _ => "OmniLight3D",
+ };
+ let mut body = format!("transform = {tr}\nlight_color = {}\nlight_energy = {}\nshadow_enabled = true\n", color(l["color"].as_str().unwrap_or("#ffffff"), 1.0), num(l["intensity"].as_f64().unwrap_or(1.0)));
+ let range = num(l["range"].as_f64().unwrap_or(20.0));
+ match kind {
+ "SpotLight3D" => {
+ let _ = write!(body, "spot_range = {range}\nspot_angle = {}\n", num(l["angle"].as_f64().unwrap_or(std::f64::consts::FRAC_PI_3).to_degrees().min(89.0)));
+ }
+ "OmniLight3D" => {
+ let _ = writeln!(body, "omni_range = {range}");
+ }
+ _ => {}
+ }
+ let _ = write!(t.nodes, "\n[node name=\"{name}\" type=\"{kind}\" parent=\".\"]\n{body}{meta}");
+ }
+ }
+}
+
+/// A placement track of the animation: each frame the node is in, as (time, transition, values...).
+fn tracks(anim: &mut String, k: &mut usize, path: &str, at: &[Value], fps: f64, f0: i64, frames: &[i64]) {
+ let keyed: Vec<(f64, Vec<f64>)> = at.iter().zip(frames).filter_map(|(a, f)| {
+ let v: Vec<f64> = a.as_array()?.iter().filter_map(Value::as_f64).collect();
+ (v.len() >= 10).then(|| ((f - f0) as f64 / fps, v))
+ }).collect();
+ if keyed.windows(2).all(|w| w[0].1 == w[1].1) {
+ return;
+ }
+ for (kind, range) in [("position_3d", 0..3), ("rotation_3d", 3..7), ("scale_3d", 7..10)] {
+ // a channel that holds still isn't a track: a part that only turns keys its rotation alone
+ if keyed.windows(2).all(|w| w[0].1[range.clone()] == w[1].1[range.clone()]) {
+ continue;
+ }
+ let keys: Vec<String> = keyed.iter().flat_map(|(t, v)| [num(*t), "1".into()].into_iter().chain(v[range.clone()].iter().map(|x| num(*x)))).collect();
+ let _ = write!(anim, "tracks/{k}/type = \"{kind}\"\ntracks/{k}/imported = false\ntracks/{k}/enabled = true\ntracks/{k}/path = NodePath(\"{path}\")\ntracks/{k}/interp = 1\ntracks/{k}/loop_wrap = true\ntracks/{k}/keys = PackedFloat32Array({})\n", keys.join(", "));
+ *k += 1;
+ }
+}
+
+/// project.godot and main.tscn in `dir` (scene export's folder), from its scene.json `v`: the name of the project.
+pub fn project(dir: &Path, v: &Value, name: &str) -> R<String> {
+ let fps = v["fps"].as_f64().unwrap_or(30.0);
+ let frames: Vec<i64> = v["frames"].as_array().into_iter().flatten().filter_map(Value::as_i64).collect();
+ let f0 = frames.first().copied().unwrap_or(0);
+ let (w, h) = (v["size"][0].as_u64().unwrap_or(1920), v["size"][1].as_u64().unwrap_or(1080));
+ let mut t = Tscn::default();
+ let mut taken = BTreeSet::from(["WorldEnvironment".to_string(), "Camera3D".to_string(), "AnimationPlayer".to_string()]);
+ let mut anim = String::new();
+ let mut k = 0;
+ for p in v["parts"].as_array().into_iter().flatten() {
+ let name = node_name(&wanted(p), &mut taken);
+ part(&mut t, p, &name);
+ if frames.len() > 1 {
+ tracks(&mut anim, &mut k, &name, p["at"].as_array().map(Vec::as_slice).unwrap_or(&[]), fps, f0, &frames);
+ }
+ }
+ // the ambient and a background: Bevy's own clear colour unless the scene says otherwise
+ let amb = &v["ambient"];
+ let mut env = "background_mode = 1\nbackground_color = Color(0.1686, 0.1725, 0.1843, 1)\ntonemap_mode = 3\n".to_string();
+ if amb.is_object() {
+ let _ = write!(env, "ambient_light_source = 2\nambient_light_color = {}\nambient_light_energy = {}\n", color(amb["color"].as_str().unwrap_or("#ffffff"), 1.0), num(amb["nits"].as_f64().unwrap_or(400.0) / 400.0));
+ }
+ let env = t.sub("Environment", &env);
+ let mut nodes = format!("\n[node name=\"WorldEnvironment\" type=\"WorldEnvironment\" parent=\".\"]\nenvironment = {env}\n");
+ nodes.push_str(&t.nodes);
+ let cams: Vec<Value> = v["camera"].as_array().into_iter().flatten().cloned().collect();
+ if let Some(c) = cams.iter().find(|c| c.is_object()) {
+ let _ = write!(nodes, "\n[node name=\"Camera3D\" type=\"Camera3D\" parent=\".\"]\ntransform = {}\nfov = {}\ncurrent = true\n", transform(&c["at"]), num(c["fov"].as_f64().unwrap_or(50.0)));
+ if frames.len() > 1 {
+ let at: Vec<Value> = cams.iter().map(|c| c["at"].clone()).collect();
+ tracks(&mut anim, &mut k, "Camera3D", &at, fps, f0, &frames);
+ }
+ }
+ if k > 0 {
+ let len = (frames.len().saturating_sub(1)) as f64 / fps;
+ let a = t.sub("Animation", &format!("resource_name = \"raea\"\nlength = {}\n{anim}", num(len.max(1.0 / fps))));
+ let lib = t.sub("AnimationLibrary", &format!("_data = {{\n&\"raea\": {a}\n}}\n"));
+ let _ = write!(nodes, "\n[node name=\"AnimationPlayer\" type=\"AnimationPlayer\" parent=\".\"]\nlibraries = {{\n&\"\": {lib}\n}}\nautoplay = &\"raea\"\n");
+ }
+ let tscn = format!("[gd_scene load_steps={} format=3]\n\n{}{}\n[node name=\"{}\" type=\"Node3D\"]\n{nodes}", t.n_ext + t.n_sub + 1, t.ext, t.sub, node_name(name, &mut BTreeSet::new()));
+ std::fs::write(dir.join("main.tscn"), tscn).map_err(|e| e.to_string())?;
+ let godot = format!(
+ "; written by raea godot export (docs/godot.feature GD12)\nconfig_version=5\n\n[application]\nconfig/name=\"{}\"\nrun/main_scene=\"res://main.tscn\"\nconfig/features=PackedStringArray(\"4.6\", \"Forward Plus\")\n\n[display]\nwindow/size/viewport_width={w}\nwindow/size/viewport_height={h}\n\n[rendering]\nrenderer/rendering_method=\"forward_plus\"\n",
+ name.replace('"', "'")
+ );
+ std::fs::write(dir.join("project.godot"), godot).map_err(|e| e.to_string())?;
+ Ok(format!("{} parts{}", v["parts"].as_array().map_or(0, Vec::len), if k > 0 { format!(", {k} animation track{} over {} frames", if k == 1 { "" } else { "s" }, frames.len()) } else { String::new() }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn a_placement_is_a_transform_by_rows() {
+ assert_eq!(transform(&json!([1, 2, 3, 0, 0, 0, 1, 1, 1, 1])), "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 2, 3)");
+ // a quarter turn about Y, then scaled by 2 along x: the x column is twice as long
+ let h = std::f64::consts::FRAC_1_SQRT_2;
+ assert_eq!(transform(&json!([0, 0, 0, 0, h, 0, h, 2, 1, 1])), "Transform3D(0, 0, 1, 0, 1, 0, -2, 0, 0, 0, 0, 0)");
+ }
+
+ #[test]
+ fn names_are_godots_and_unique() {
+ let mut t = BTreeSet::new();
+ assert_eq!(node_name("crate", &mut t), "crate");
+ assert_eq!(node_name("crate", &mut t), "crate2");
+ assert_eq!(node_name("mesh|a.b#0", &mut t), "mesh_a_b_0");
+ }
+
+ #[test]
+ fn a_scene_becomes_a_project_that_moves() {
+ let dir = std::env::temp_dir().join(format!("raea-godot-project-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let v = json!({ "fps": 30, "size": [640, 360], "frames": [0, 1],
+ "parts": [
+ { "id": "mesh|box(1, 1, 1)#0", "kind": "mesh", "source": { "name": "crate" }, "shape": { "type": "cuboid", "size": [1, 1, 1] }, "material": { "color": "#ff0000", "roughness": 0.4, "metallic": 0 }, "at": [[0, 0.5, 0, 0, 0, 0, 1, 1, 1, 1], [1, 0.5, 0, 0, 0, 0, 1, 1, 1, 1]] },
+ { "id": "directional|#0", "kind": "light", "source": {}, "light": { "type": "directional", "color": "#ffffff", "intensity": 1 }, "at": [[0, 5, 0, 0, 0, 0, 1, 1, 1, 1], [0, 5, 0, 0, 0, 0, 1, 1, 1, 1]] }
+ ],
+ "camera": [{ "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 }, { "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 }], "ambient": null });
+ let said = project(&dir, &v, "box test").unwrap();
+ // the crate only moves: its position is keyed, its rotation and scale aren't tracks
+ assert!(said.contains("1 animation track over 2 frames"), "{said}");
+ let tscn = std::fs::read_to_string(dir.join("main.tscn")).unwrap();
+ assert!(!tscn.contains("tracks/1/"), "{tscn}");
+ for want in ["[node name=\"crate\" type=\"MeshInstance3D\"", "size = Vector3(1, 1, 1)", "albedo_color = Color(1.0000, 0.0000, 0.0000, 1)", "[node name=\"Sun\" type=\"DirectionalLight3D\"", "fov = 40", "tracks/0/type = \"position_3d\"", "autoplay = &\"raea\"", "tracks/0/path = NodePath(\"crate\")", "metadata/raea_id = \"mesh|box(1, 1, 1)#0\""] {
+ assert!(tscn.contains(want), "{want} in\n{tscn}");
+ }
+ assert!(std::fs::read_to_string(dir.join("project.godot")).unwrap().contains("window/size/viewport_width=640"));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/apps/interchange/src/lib.rs b/apps/interchange/src/lib.rs
new file mode 100644
index 00000000..7ffdf58f
--- /dev/null
+++ b/apps/interchange/src/lib.rs
@@ -0,0 +1,13 @@
+//! A composition's 3D for other tools, and back (docs/blender.feature BL37-BL39, docs/godot.feature GD12-GD13):
+//! `raea scene export` writes the parts of a frame (or a span) as scene.json with their meshes and models; godot.rs
+//! makes that folder a Godot project; back.rs compares scene.json with what Blender or Godot holds after a person
+//! changed it there, as edits to the TSX at their lines. apps/engines runs Blender and Godot for these verbs.
+
+/// `raea scene export`: scene.json, meshes/, models/
+pub mod export;
+/// scene export's folder as a Godot project: project.godot, main.tscn
+pub mod godot;
+/// what changed in Blender or Godot, as edits to the TSX
+pub mod back;
+
+type R<T> = Result<T, String>;
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index 51bb145c..73aff44d 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -135,7 +135,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item, each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
// 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, ~/Documents/raea 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 {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE);
+ 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, ~/Documents/raea 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 {}\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::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 {capcut}\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)"));
@@ -282,8 +282,9 @@ pub fn run(args: &[String]) -> R<String> {
return Ok(format!("APPLIED {} bundled to {}", ts.display(), out.display()));
}
if args.first().map(String::as_str) == Some("types") {
- // the native calls' TypeScript, from the registry (sdk/raea/src/native-calls.ts)
- raea_runtime_react::native::register();
+ // the native calls' TypeScript, from the registry (sdk/raea/src/native-calls.ts): every call a composition's
+ // thread answers
+ raea_runtime_react::register_natives();
let ts = raea_native::typescript();
match flag(args, "-o") {
Some(o) => {
diff --git a/runtime/react/src/lib.rs b/runtime/react/src/lib.rs
index cc19ddac..90a44b20 100644
--- a/runtime/react/src/lib.rs
+++ b/runtime/react/src/lib.rs
@@ -27,6 +27,7 @@ use serde_json::Value;
mod thread;
use thread::*;
+pub use thread::register_natives;
mod commits;
use commits::*;
diff --git a/runtime/react/src/scene.rs b/runtime/react/src/scene.rs
index 8fd9a725..b9ee7d9c 100644
--- a/runtime/react/src/scene.rs
+++ b/runtime/react/src/scene.rs
@@ -36,6 +36,8 @@ pub(crate) use contact::register as register_scene;
pub mod physics;
// matchmove: `track` and the matchmove.solve native call (scene/track.rs)
pub mod track;
+// shots drawn by Blender and Godot: <BlenderShot>, <GodotShot> as native calls made by `raea blender|godot shot` (scene/shots.rs)
+pub mod shots;
thread_local! {
/// each part's data-props as last parsed: its text and the props, and the scene it was last read in
diff --git a/runtime/react/src/scene/shots.rs b/runtime/react/src/scene/shots.rs
new file mode 100644
index 00000000..72153d72
--- /dev/null
+++ b/runtime/react/src/scene/shots.rs
@@ -0,0 +1,195 @@
+//! Shots for compositions: <BlenderShot> and <GodotShot> (sdk/blender/src/shot.tsx, sdk/godot/src/shot.tsx) as native
+//! calls (docs/blender.feature BL36, docs/godot.feature GD11). A shot's frames are made by `raea blender shot` or
+//! `raea godot shot`, run as a process of their own (this program), once for what they're made from: the request, the
+//! script and the files beside it, the .blend, the Godot project's files. They're kept in the composition's asset
+//! store under that key, so a render, a `render --at` and a play read the same frames and nothing is drawn by another
+//! engine at a frame.
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use serde_json::{Value, json};
+
+type R<T> = Result<T, String>;
+
+const GIVES: &str = "{ dir: string; frames: number }";
+
+pub(crate) fn register() {
+ raea_native::register(
+ "blender.shot",
+ "{ script?: string; file?: string; engine?: string; samples?: number; transparent?: boolean; args?: string[]; fps: number; width: number; height: number; frames: number }",
+ GIVES,
+ "a layer drawn by Blender (<BlenderShot>): a raea/blender script's scene or a .blend's animation rendered frame for frame, made once and kept (0000.png on in dir)",
+ |v| shot("blender", v),
+ );
+ raea_native::register(
+ "godot.shot",
+ "{ project?: string; script?: string; scene?: string; args?: string[]; fps: number; width: number; height: number; frames: number }",
+ GIVES,
+ "a layer drawn by Godot's Movie Maker (<GodotShot>): a raea/godot script's scene or a project's scene recorded frame for frame, made once and kept (0000.png on in dir)",
+ |v| shot("godot", v),
+ );
+}
+
+/// FNV-1a over everything a shot is made from, twice with different seeds: a 128-bit key for the asset store.
+struct Key([u64; 2]);
+
+impl Key {
+ fn new() -> Self {
+ Key([0xcbf2_9ce4_8422_2325, 0x6c62_272e_07bb_0142])
+ }
+ fn write(&mut self, b: &[u8]) {
+ for h in self.0.iter_mut() {
+ for &x in b.iter().chain(&[0xff]) {
+ *h ^= u64::from(x);
+ *h = h.wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ }
+ }
+ fn hex(&self) -> String {
+ format!("{:016x}{:016x}", self.0[0], self.0[1])
+ }
+}
+
+/// The files under `root` a shot depends on, in a stable order: dot folders (.godot, .git) and node_modules left out.
+fn files(root: &Path, out: &mut Vec<PathBuf>) {
+ let Ok(rd) = std::fs::read_dir(root) else { return };
+ let mut es: Vec<_> = rd.flatten().map(|e| e.path()).collect();
+ es.sort();
+ for p in es {
+ let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
+ if name.starts_with('.') || name == "node_modules" || out.len() > 20_000 {
+ continue;
+ }
+ if p.is_dir() { files(&p, out) } else { out.push(p) }
+ }
+}
+
+/// A file's identity: its contents for source (small), its size and time for anything else (a .blend, a project's
+/// textures).
+fn identity(k: &mut Key, p: &Path) {
+ k.write(p.to_string_lossy().as_bytes());
+ let source = matches!(p.extension().and_then(|e| e.to_str()), Some("ts" | "tsx" | "js" | "mjs" | "json" | "py" | "gd" | "tscn" | "tres" | "godot"));
+ match std::fs::metadata(p) {
+ Ok(m) if source && m.len() < 4 << 20 => k.write(&std::fs::read(p).unwrap_or_default()),
+ Ok(m) => {
+ let t = m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_nanos());
+ k.write(format!("{} {t}", m.len()).as_bytes());
+ }
+ Err(_) => k.write(b"missing"),
+ }
+}
+
+/// `raea blender shot` / `raea godot shot`'s arguments for this request, the source first.
+fn command(engine: &str, v: &Value, dir: &Path, out: &Path) -> R<Vec<String>> {
+ let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
+ let n = |k: &str| v.get(k).and_then(Value::as_f64).ok_or_else(|| format!("{engine}.shot: {k} is a number"));
+ let at = |p: String| if p.starts_with("res://") { p } else { dir.join(p).to_string_lossy().into_owned() };
+ let src = match engine {
+ "blender" => s("script").or_else(|| s("file")).ok_or("BlenderShot: give script or file")?,
+ _ => s("script").or_else(|| s("scene")).ok_or("GodotShot: give script or scene")?,
+ };
+ let (w, h) = (n("width")?.round() as u32, n("height")?.round() as u32);
+ let mut a = vec![engine.to_string(), "shot".into(), at(src), "-o".into(), out.to_string_lossy().into_owned()];
+ a.extend(["--frames".into(), (n("frames")?.round() as u32).to_string(), "--fps".into(), n("fps")?.to_string(), "--size".into(), format!("{w}x{h}")]);
+ if engine == "blender" {
+ if let (Some(_), Some(f)) = (s("script"), s("file")) {
+ a.extend(["--file".into(), at(f)]);
+ }
+ if let Some(e) = s("engine") {
+ a.extend(["--engine".into(), e]);
+ }
+ if let Some(x) = v.get("samples").and_then(Value::as_f64) {
+ a.extend(["--samples".into(), (x.round() as u32).to_string()]);
+ }
+ if v.get("transparent").and_then(Value::as_bool) == Some(true) {
+ a.push("--transparent".into());
+ }
+ } else {
+ if let Some(p) = s("project") {
+ a.extend(["--project".into(), at(p)]);
+ }
+ if let (Some(_), Some(sc)) = (s("script"), s("scene")) {
+ a.extend(["--scene".into(), sc]);
+ }
+ }
+ let extra: Vec<String> = v.get("args").and_then(Value::as_array).into_iter().flatten().filter_map(|x| x.as_str().map(str::to_string)).collect();
+ if !extra.is_empty() {
+ a.push("--".into());
+ a.extend(extra);
+ }
+ Ok(a)
+}
+
+fn shot(engine: &str, v: &Value) -> R<Value> {
+ let dir = crate::native::composition_dir().unwrap_or_else(|| PathBuf::from("."));
+ let frames = v.get("frames").and_then(Value::as_u64).filter(|n| *n > 0).ok_or_else(|| format!("{engine}.shot: frames must be a whole number over 0"))?;
+ // what the frames are made from
+ let mut k = Key::new();
+ k.write(engine.as_bytes());
+ k.write(v.to_string().as_bytes());
+ k.write(env!("CARGO_PKG_VERSION").as_bytes());
+ let mut deps = Vec::new();
+ for key in ["script", "file", "project"] {
+ let Some(p) = v.get(key).and_then(Value::as_str).map(|p| dir.join(p)) else { continue };
+ match key {
+ "script" => files(p.parent().unwrap_or(&dir), &mut deps),
+ "project" => files(&p, &mut deps),
+ _ => deps.push(p),
+ }
+ }
+ deps.sort();
+ deps.dedup();
+ for p in &deps {
+ identity(&mut k, p);
+ }
+ let shots = raea_io_assets::Store::beside(&dir.join("edit.tsx")).dir.join("shots");
+ let out = shots.join(k.hex());
+ if let Some(n) = std::fs::read(out.join("shot.json")).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()).and_then(|j| j["frames"].as_u64()) {
+ return Ok(json!({ "dir": out.to_string_lossy(), "frames": n }));
+ }
+ let part = shots.join(format!("{}.part", k.hex()));
+ let _ = std::fs::remove_dir_all(&part);
+ std::fs::create_dir_all(&part).map_err(|e| format!("{}: {e}", part.display()))?;
+ let args = command(engine, v, &dir, &part)?;
+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;
+ eprintln!("raea: {} shot, made once and kept: raea {}", if engine == "blender" { "Blender's" } else { "Godot's" }, args.join(" "));
+ let st = raea_sys_bake::making(|| Command::new(&exe).args(&args).current_dir(&dir).status()).map_err(|e| format!("{}: {e}", exe.display()))?;
+ if !st.success() {
+ let _ = std::fs::remove_dir_all(&part);
+ return Err(format!("{}Shot: raea {} failed ({st}; its output above)", if engine == "blender" { "Blender" } else { "Godot" }, args[..3].join(" ")));
+ }
+ std::fs::write(part.join("shot.json"), json!({ "frames": frames, "made_by": args }).to_string()).map_err(|e| e.to_string())?;
+ let _ = std::fs::remove_dir_all(&out);
+ std::fs::rename(&part, &out).map_err(|e| format!("{}: {e}", out.display()))?;
+ Ok(json!({ "dir": out.to_string_lossy(), "frames": frames }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_shot_is_keyed_by_what_it_is_made_from() {
+ let key = |s: &str| {
+ let mut k = Key::new();
+ k.write(s.as_bytes());
+ k.hex()
+ };
+ assert_eq!(key("a").len(), 32);
+ assert_eq!(key("a"), key("a"));
+ assert_ne!(key("a"), key("b"));
+ }
+
+ #[test]
+ fn the_command_says_the_shot() {
+ let dir = Path::new("/p/src");
+ let v = json!({ "script": "blender/orbit.ts", "file": "set.blend", "engine": "cycles", "samples": 64, "transparent": true, "fps": 30, "width": 1920, "height": 1080, "frames": 90, "args": ["fast"] });
+ let a = command("blender", &v, dir, Path::new("/o")).unwrap().join(" ");
+ assert_eq!(a, "blender shot /p/src/blender/orbit.ts -o /o --frames 90 --fps 30 --size 1920x1080 --file /p/src/set.blend --engine cycles --samples 64 --transparent -- fast");
+ let v = json!({ "project": "godot", "scene": "res://main.tscn", "fps": 24, "width": 1280, "height": 720, "frames": 48 });
+ let a = command("godot", &v, dir, Path::new("/o")).unwrap().join(" ");
+ assert_eq!(a, "godot shot res://main.tscn -o /o --frames 48 --fps 24 --size 1280x720 --project /p/src/godot");
+ assert!(command("godot", &json!({ "fps": 30, "width": 1, "height": 1, "frames": 1 }), dir, Path::new("/o")).is_err());
+ }
+}
diff --git a/runtime/react/src/thread.rs b/runtime/react/src/thread.rs
index 10307250..f2bded95 100644
--- a/runtime/react/src/thread.rs
+++ b/runtime/react/src/thread.rs
@@ -33,6 +33,18 @@ fn log(a: &[String]) -> Result<Ret, String> {
Ok(Ret::Undefined)
}
+/// Every native call a composition's thread answers: the calls crate's, the page's and the scene's. `raea types` writes
+/// sdk/raea/src/native-calls.ts from the same list, so a call registered here is typed there.
+pub fn register_natives() {
+ native::register();
+ raea_native::register("page.viewBox", "{}", "[number, number, number, number] | null", "the box (x, y, w, h in frame px) a camera in a page element draws its view in, as last laid out; null when it draws under the whole frame (3D picking in the box, docs/sdk.feature S3a)", |_| Ok(serde_json::json!(*VIEW_BOX.lock().unwrap())));
+ // matchmove.solve (scene/track.rs), physics.* for <Physics> and <Goo> (systems/bake), scene.bounds and facing
+ // (scene/contact.rs), blender.shot and godot.shot (scene/shots.rs)
+ for register in [scene::track::register, scene::physics::register, scene::shots::register, scene::register_scene] {
+ register();
+ }
+}
+
/// The JS thread: the prelude, the shims, the bundle, then timers and Bevy's events. Both engines run promise jobs as
/// each call returns, so there are no microtask checkpoints to make.
pub(crate) fn js_thread(bundle: PathBuf, tx: Sender<Batch>, events: Receiver<String>) {
@@ -60,12 +72,7 @@ pub(crate) fn js_thread(bundle: PathBuf, tx: Sender<Batch>, events: Receiver<Str
return;
}
}
- native::register();
- raea_native::register("page.viewBox", "{}", "[number, number, number, number] | null", "the box (x, y, w, h in frame px) a camera in a page element draws its view in, as last laid out; null when it draws under the whole frame (3D picking in the box, docs/sdk.feature S3a)", |_| Ok(serde_json::json!(*VIEW_BOX.lock().unwrap())));
- // matchmove.solve (scene/track.rs), physics.* for <Physics> and <Goo> (systems/bake), scene.bounds and facing (scene/contact.rs)
- for register in [scene::track::register, scene::physics::register, scene::register_scene] {
- register();
- }
+ register_natives();
for (src, name) in [(PRELUDE, "prelude.js")] {
if let Err(e) = ctx.eval(src, name) {
error!("raea-runtime-react: {name}: {e}");
diff --git a/sdk/blender/package.json b/sdk/blender/package.json
index 96e64d74..ec74401d 100644
--- a/sdk/blender/package.json
+++ b/sdk/blender/package.json
@@ -9,7 +9,9 @@
"exports": {
".": "./src/index.ts",
"./mathutils": "./src/mathutils/index.ts",
- "./types": "./src/types.ts"
+ "./types": "./src/types.ts",
+ "./shot": "./src/shot.tsx",
+ "./shoot": "./src/shoot.ts"
},
"files": ["src", "python", "tools", "README.md"]
}
diff --git a/sdk/blender/src/scene.ts b/sdk/blender/src/scene.ts
new file mode 100644
index 00000000..f7da10f7
--- /dev/null
+++ b/sdk/blender/src/scene.ts
@@ -0,0 +1,306 @@
+// A raea scene in Blender and back (docs/blender.feature BL38, BL39): `raea blender open EDIT.tsx` exports the
+// composition's 3D (raea scene export: scene.json, meshes/, models/) and build() makes it in a headless Blender, saved
+// as a .blend the person opens; `raea blender back FILE.blend` runs readBack() on it, and raea compares what it finds
+// with scene.json. Everything sits under one empty, "raea", turned a quarter about X: inside it the axes are raea's
+// (y up, -z forward), so each part's placement is raea's own numbers both ways.
+import { blender } from "./blender";
+import type * as types from "./gen/rna";
+import { Matrix } from "./mathutils";
+import type { Ptr } from "./types";
+
+type V3 = [number, number, number];
+/** x y z, qx qy qz qw, sx sy sz */
+type At = number[];
+
+interface Surface {
+ color?: string;
+ roughness?: number;
+ metallic?: number;
+ emissive?: string;
+ emissive_strength?: number;
+ opacity?: number;
+ unlit?: boolean;
+ color_map?: string;
+}
+interface Light {
+ type: "directional" | "point" | "spot" | "rect";
+ color: string;
+ intensity: number;
+ range?: number;
+ angle?: number;
+ penumbra?: number;
+ width?: number;
+ height?: number;
+}
+interface Part {
+ id: string;
+ kind: "mesh" | "model" | "light";
+ source: { name?: string | null };
+ shape?: { type: "cuboid" | "sphere" | "cylinder" | "plane" | "mesh"; size?: number[]; radius?: number; height?: number; obj?: string };
+ model?: string;
+ material?: Surface;
+ light?: Light;
+ at: (At | null)[];
+}
+interface Scene {
+ frames: number[];
+ fps: number;
+ size: [number, number];
+ parts: Part[];
+ camera: ({ at: At; fov: number } | null)[];
+ ambient: { color: string; nits: number } | null;
+}
+
+/** raea's light units: a 3d.tsx light's intensity 1 is 8000 lux for a sun and 900 000 lumens else (core/scene props.rs) */
+const LUX = 8000;
+const LUMENS = 9e5;
+/** Blender's watts are radiant: 683 lumens to the watt */
+const LM_PER_W = 683;
+/** raea's camera (EV100 9.7) shows 1.2 x 2^9.7 nits as white; Blender shows 683: this many stops apart */
+const EXPOSURE = Math.log2(683 / (1.2 * 2 ** 9.7));
+
+const srgb = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
+const toHex = (c: number) => Math.round(Math.max(0, Math.min(1, c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055)) * 255).toString(16).padStart(2, "0");
+/** `#rrggbb` (sRGB) as linear RGB */
+function linear(hex: string | undefined, fallback = "#cccccc"): V3 {
+ const h = (hex ?? fallback).replace("#", "");
+ return [0, 2, 4].map((i) => srgb(parseInt(h.slice(i, i + 2), 16) / 255)) as V3;
+}
+
+/** An empty's data: Python takes None (gen types object_data as ID; Blender's RNA leaves it nullable) */
+const EMPTY = null as never;
+
+const read = (path: string) => blender.py.exec<string>("result = open(path).read()", { path });
+
+/** A material that is one Principled BSDF with the part's surface. */
+function principled(name: string, s: Surface, dir: string): Ptr<types.Material> {
+ const { bpy } = blender;
+ const m = bpy.data.materials.new(name);
+ m.use_nodes = true;
+ const nodes = m.node_tree!.nodes;
+ nodes.clear();
+ const p = nodes.new("ShaderNodeBsdfPrincipled");
+ m.node_tree!.links.new(p.outputs.$["BSDF"], nodes.new("ShaderNodeOutputMaterial").inputs.$["Surface"]);
+ p.inputs.$["Base Color"].default_value = [...linear(s.color), 1];
+ p.inputs.$["Roughness"].default_value = s.roughness ?? 0.5;
+ p.inputs.$["Metallic"].default_value = s.metallic ?? 0;
+ if (s.emissive) {
+ p.inputs.$["Emission Color"].default_value = [...linear(s.emissive), 1];
+ p.inputs.$["Emission Strength"].default_value = s.emissive_strength ?? 1;
+ }
+ if (s.opacity !== undefined) p.inputs.$["Alpha"].default_value = s.opacity;
+ if (s.color_map) {
+ const t = nodes.new("ShaderNodeTexImage");
+ t.image = bpy.data.images.load(`${dir}/${s.color_map}`);
+ m.node_tree!.links.new(t.outputs.$["Color"], p.inputs.$["Base Color"]);
+ }
+ return m;
+}
+
+/** The part's mesh as Blender's own: a primitive made at its size in raea's axes, any other an .obj read as it is. */
+function mesh(p: Part, dir: string): Ptr<types.Object> {
+ const { bpy } = blender;
+ const sh = p.shape!;
+ const quarter = Matrix.Rotation(-Math.PI / 2, 4, "X"); // Blender's z up as raea's y up, in the mesh
+ if (sh.type === "mesh") {
+ bpy.ops.wm.obj_import({ filepath: `${dir}/${sh.obj}`, forward_axis: "Y", up_axis: "Z" });
+ } else if (sh.type === "cuboid") bpy.ops.mesh.primitive_cube_add({ size: 1 });
+ else if (sh.type === "sphere") bpy.ops.mesh.primitive_uv_sphere_add({ radius: sh.radius ?? 0.5, segments: 48, ring_count: 24 });
+ else if (sh.type === "cylinder") bpy.ops.mesh.primitive_cylinder_add({ radius: sh.radius ?? 0.5, depth: sh.height ?? 1, vertices: 64 });
+ else bpy.ops.mesh.primitive_plane_add({ size: 1 });
+ const o = blender.py.pin(bpy.context.active_object!);
+ const data = o.data as Ptr<types.Mesh>;
+ if (sh.type === "cylinder" || sh.type === "plane") data.transform(quarter);
+ if (sh.type === "cuboid") data.transform(Matrix.Diagonal([sh.size![0], sh.size![1], sh.size![2], 1]));
+ if (sh.type === "plane") data.transform(Matrix.Diagonal([sh.size![0], 1, sh.size![1], 1]));
+ if (sh.type === "sphere" || sh.type === "cylinder") data.shade_smooth();
+ data.materials.append(principled(named(p), p.material ?? {}, dir));
+ return o;
+}
+
+/** A light as Blender's, its power in watts. */
+function light(p: Part): Ptr<types.Object> {
+ const { bpy } = blender;
+ const l = p.light!;
+ const kind = l.type === "directional" ? "SUN" : l.type === "spot" ? "SPOT" : l.type === "rect" ? "AREA" : "POINT";
+ const d = bpy.data.lights.new(p.id, kind);
+ d.color = linear(l.color, "#ffffff");
+ d.energy = l.type === "directional" ? (l.intensity * LUX) / LM_PER_W : (l.intensity * LUMENS) / LM_PER_W;
+ if (l.type === "spot") (d as Ptr<types.SpotLight>).spot_size = 2 * (l.angle ?? Math.PI / 3);
+ if (l.type === "rect") {
+ const a = d as Ptr<types.AreaLight>;
+ a.shape = "RECTANGLE";
+ a.size = l.width ?? 1;
+ a.size_y = l.height ?? 1;
+ }
+ return bpy.data.objects.new(p.id, d);
+}
+
+/** A key per frame on each channel of a property, straight into the action's curves. */
+function keys(id: Ptr<types.ID>, act: Ptr<types.Action>, path: string, frames: number[], channels: number[][]) {
+ channels.forEach((values, index) => {
+ const fc = act.fcurve_ensure_for_datablock(id, path, { index });
+ fc.keyframe_points.add(values.length);
+ fc.keyframe_points.foreach_set("co", values.flatMap((v, k) => [frames[k], v]));
+ fc.update();
+ });
+}
+
+/** An object placed by raea's numbers inside the root, keyed on each frame when it moves. */
+function place(o: Ptr<types.Object>, at: (At | null)[], frames: number[], name: string) {
+ const { bpy } = blender;
+ const kept = at.map((a, k) => [a, frames[k]] as const).filter((x): x is readonly [At, number] => x[0] !== null);
+ if (!kept.length) return;
+ const [a] = kept[0];
+ o.rotation_mode = "QUATERNION";
+ o.location = [a[0], a[1], a[2]];
+ o.rotation_quaternion = [a[6], a[3], a[4], a[5]];
+ o.scale = [a[7], a[8], a[9]];
+ if (kept.every(([b]) => b.every((v, i) => v === a[i]))) return;
+ const act = bpy.data.actions.new(name);
+ o.animation_data_create().action = act;
+ const fs = kept.map(([, f]) => f);
+ keys(o, act, "location", fs, [0, 1, 2].map((i) => kept.map(([b]) => b[i])));
+ keys(o, act, "rotation_quaternion", fs, [6, 3, 4, 5].map((i) => kept.map(([b]) => b[i])));
+ keys(o, act, "scale", fs, [7, 8, 9].map((i) => kept.map(([b]) => b[i])));
+}
+
+/** A part's object name: its name in the TSX, else what it is ("Sun", "PointLight", "Cuboid", the model's file), as
+ * raea godot export names its nodes; Blender numbers a second one (.001). */
+function named(p: Part): string {
+ if (p.source.name) return p.source.name;
+ if (p.light) return { directional: "Sun", point: "PointLight", spot: "SpotLight", rect: "AreaLight" }[p.light.type];
+ if (p.kind === "model") return (p.model ?? "Model").split("/").pop()!.replace(/\.[^.]+$/, "");
+ return { cuboid: "Cuboid", sphere: "Sphere", cylinder: "Cylinder", plane: "Plane", mesh: "Mesh" }[p.shape?.type ?? "mesh"];
+}
+
+/** scene.json in `dir` built in this Blender, then saved as `out` (a .blend). */
+export async function build(dir: string, out: string): Promise<void> {
+ const { bpy, py } = blender;
+ const s: Scene = JSON.parse(await read(`${dir}/scene.json`));
+ bpy.ops.wm.read_factory_settings({ use_empty: true });
+ const scene = bpy.context.scene;
+ const root = bpy.data.objects.new("raea", EMPTY);
+ scene.collection.objects.link(root);
+ root.rotation_euler = [Math.PI / 2, 0, 0];
+ root.$["raea_scene"] = `${dir}/scene.json`;
+ for (const p of s.parts) {
+ let o: Ptr<types.Object>;
+ if (p.kind === "mesh") o = mesh(p, dir);
+ else if (p.kind === "light") {
+ o = light(p);
+ scene.collection.objects.link(o);
+ } else {
+ // a model: its glTF imported (Blender turns it to z up), held by an empty placed by raea's numbers, the import
+ // turned back to raea's axes inside it
+ o = bpy.data.objects.new(p.id, EMPTY);
+ scene.collection.objects.link(o);
+ await py.exec(
+ "import bpy, mathutils\nbpy.ops.object.select_all(action='DESELECT')\nbpy.ops.import_scene.gltf(filepath=path)\nback = mathutils.Matrix.Rotation(-1.5707963267948966, 4, 'X')\nfor t in [x for x in bpy.context.selected_objects if x.parent is None]:\n w = t.matrix_world.copy()\n t.parent = holder\n t.matrix_parent_inverse = mathutils.Matrix.Identity(4)\n t.matrix_basis = back @ w",
+ { path: `${dir}/${p.model}`, holder: o },
+ );
+ }
+ o.name = named(p);
+ o.parent = root;
+ o.$["raea_id"] = p.id;
+ place(o, p.at, s.frames, p.id);
+ }
+ // the camera: its lens as raea's vertical field of view
+ const c0 = s.camera.find((c) => c !== null);
+ if (c0) {
+ const lens = bpy.data.cameras.new("camera");
+ lens.sensor_fit = "VERTICAL";
+ lens.sensor_height = 24;
+ lens.lens = 12 / Math.tan((c0.fov * Math.PI) / 360);
+ const cam = bpy.data.objects.new("camera", lens);
+ scene.collection.objects.link(cam);
+ cam.parent = root;
+ cam.$["raea_id"] = "camera";
+ place(cam, s.camera.map((c) => c?.at ?? null), s.frames, "camera");
+ scene.camera = cam;
+ }
+ // the ambient as the world's light, at raea's exposure
+ const world = bpy.data.worlds.new("raea");
+ world.use_nodes = true;
+ const wn = world.node_tree!.nodes;
+ wn.clear();
+ const bg = wn.new("ShaderNodeBackground");
+ bg.inputs.$["Color"].default_value = [...linear(s.ambient?.color, "#2b2c2f"), 1];
+ bg.inputs.$["Strength"].default_value = s.ambient ? s.ambient.nits / LM_PER_W : 0.3;
+ world.node_tree!.links.new(bg.outputs.$["Background"], wn.new("ShaderNodeOutputWorld").inputs.$["Surface"]);
+ scene.world = world;
+ scene.view_settings.exposure = EXPOSURE;
+ const r = scene.render;
+ r.resolution_x = s.size[0];
+ r.resolution_y = s.size[1];
+ r.fps = Math.round(s.fps);
+ scene.frame_start = s.frames[0];
+ scene.frame_end = s.frames[s.frames.length - 1];
+ scene.frame_set(s.frames[0]);
+ bpy.ops.wm.save_as_mainfile({ filepath: out });
+}
+
+/** What the scene holds now, in raea's terms, written to `now` as JSON: each object with a raea_id placed inside the
+ * root, its surface or light, the camera; each mesh made in Blender (no raea_id) written as a .glb into `media`. */
+export async function readBack(now: string, media: string): Promise<void> {
+ const { py } = blender;
+ await py.exec(READ_BACK, { now, media, lux: LUX, lumens: LUMENS, lm: LM_PER_W });
+}
+
+// in Python: one pass over the file's objects (a round trip a property would cost hundreds)
+const READ_BACK = `
+import bpy, json, os, mathutils
+# placements are compared with the first frame sent: read them there, whatever frame the file was saved on
+bpy.context.scene.frame_set(bpy.context.scene.frame_start)
+root = bpy.data.objects.get("raea")
+if root is None:
+ raise RuntimeError("this .blend has no raea root: it wasn't made by raea blender open")
+inv = root.matrix_world.inverted()
+def at(o):
+ l, q, s = (inv @ o.matrix_world).decompose()
+ return [round(v, 6) for v in (l.x, l.y, l.z, q.x, q.y, q.z, q.w, s.x, s.y, s.z)]
+def hexof(c):
+ f = lambda v: max(0, min(255, round((v * 12.92 if v <= 0.0031308 else 1.055 * v ** (1 / 2.4) - 0.055) * 255)))
+ return "#%02x%02x%02x" % (f(c[0]), f(c[1]), f(c[2]))
+def under_raea(o):
+ p = o.parent
+ while p is not None:
+ if "raea_id" in p:
+ return True
+ p = p.parent
+ return False
+parts, new, cam = [], [], None
+for o in bpy.data.objects:
+ rid = o.get("raea_id")
+ if rid == "camera" and o.type == "CAMERA":
+ cam = {"at": at(o), "fov": round(o.data.angle_y * 180 / 3.141592653589793, 4)}
+ continue
+ if rid is not None:
+ p = {"id": rid, "at": at(o)}
+ if o.type == "MESH" and o.active_material is not None:
+ n = next((n for n in o.active_material.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None)
+ if n is not None:
+ p["material"] = {"color": hexof(n.inputs["Base Color"].default_value), "roughness": round(n.inputs["Roughness"].default_value, 4), "metallic": round(n.inputs["Metallic"].default_value, 4)}
+ if n.inputs["Emission Strength"].default_value > 0 and any(n.inputs["Emission Color"].default_value[:3]):
+ p["material"]["emissive"] = hexof(n.inputs["Emission Color"].default_value)
+ if o.type == "LIGHT":
+ unit = lux if o.data.type == "SUN" else lumens
+ p["light"] = {"color": hexof(o.data.color), "intensity": round(o.data.energy * lm / unit, 6)}
+ parts.append(p)
+ elif o.type == "MESH" and (o.parent is None or o.parent == root) and not under_raea(o):
+ # made in Blender: written at the origin as a y-up .glb; its placement turned into raea's axes
+ name = bpy.path.clean_name(o.name)
+ os.makedirs(media, exist_ok=True)
+ out = os.path.join(media, name + ".glb")
+ w = o.matrix_world.copy()
+ l, q, s = (inv @ w @ root.matrix_world).decompose()
+ o.matrix_world = mathutils.Matrix.Identity(4)
+ bpy.ops.object.select_all(action="DESELECT")
+ o.select_set(True)
+ bpy.context.view_layer.objects.active = o
+ bpy.ops.export_scene.gltf(filepath=out, use_selection=True, export_apply=True)
+ o.matrix_world = w
+ json.dump({"source": bpy.data.filepath, "license": "own work", "credit": ""}, open(out + ".json", "w"))
+ new.append({"name": o.name, "file": "media/" + name + ".glb", "at": [round(v, 6) for v in (l.x, l.y, l.z, q.x, q.y, q.z, q.w, s.x, s.y, s.z)]})
+json.dump({"parts": parts, "camera": cam, "new": new}, open(now, "w"), indent=1)
+`;
diff --git a/sdk/blender/src/shoot.ts b/sdk/blender/src/shoot.ts
new file mode 100644
index 00000000..4e156871
--- /dev/null
+++ b/sdk/blender/src/shoot.ts
@@ -0,0 +1,52 @@
+// A shot's frames rendered by the script's Blender (docs/blender.feature BL36): `raea blender shot` calls this after the
+// script's default export has built the scene (or on a .blend as it opened), and <BlenderShot> through it. Blender
+// writes OUT/0001.png on (its frame numbers); raea numbers them from 0000.png after.
+import { blender } from "./blender";
+
+export type ShotEngine = "eevee" | "cycles" | "workbench";
+
+export interface ShootOptions {
+ /** the folder the frames go into */
+ out: string;
+ frames: number;
+ fps: number;
+ width: number;
+ height: number;
+ /** eevee unless given */
+ engine?: ShotEngine;
+ /** EEVEE's or Cycles' render samples; the file's or Blender's own when not given */
+ samples?: number;
+ /** a picture with alpha where nothing is drawn (film_transparent, RGBA PNGs) */
+ transparent?: boolean;
+}
+
+const ENGINES = { eevee: "BLENDER_EEVEE", cycles: "CYCLES", workbench: "BLENDER_WORKBENCH" } as const;
+
+export async function shoot(o: ShootOptions): Promise<void> {
+ const { bpy, py } = blender;
+ const scene = bpy.context.scene;
+ if (!(await py.exec<boolean>("result = bpy.context.scene.camera is not None"))) {
+ throw new Error("the shot has no camera: the script sets bpy.context.scene.camera, or the .blend has one");
+ }
+ const engine = o.engine ?? "eevee";
+ const r = scene.render;
+ r.engine = ENGINES[engine];
+ r.resolution_x = o.width;
+ r.resolution_y = o.height;
+ r.resolution_percentage = 100;
+ r.fps = Math.round(o.fps);
+ r.fps_base = Math.round(o.fps) / o.fps;
+ r.film_transparent = !!o.transparent;
+ r.image_settings.file_format = "PNG";
+ r.image_settings.color_mode = o.transparent ? "RGBA" : "RGB";
+ if (o.samples !== undefined) {
+ if (engine === "cycles") await py.exec(`bpy.context.scene.cycles.samples = ${Math.max(1, Math.round(o.samples))}`);
+ else if (engine === "eevee") scene.eevee.taa_render_samples = Math.max(1, Math.round(o.samples));
+ }
+ const start = await scene.frame_start;
+ scene.frame_end = start + o.frames - 1;
+ r.filepath = o.out.endsWith("/") ? o.out : `${o.out}/`;
+ bpy.ops.render.render({ animation: true });
+ // the render is sent without waiting, as every call is: a read after it returns once Blender has drawn every frame
+ await scene.frame_end;
+}
diff --git a/sdk/blender/src/shot.tsx b/sdk/blender/src/shot.tsx
new file mode 100644
index 00000000..04758d7e
--- /dev/null
+++ b/sdk/blender/src/shot.tsx
@@ -0,0 +1,81 @@
+// <BlenderShot>: a layer of a composition drawn by Blender, frame for frame (docs/blender.feature BL36).
+// import { BlenderShot } from "raea/blender/shot";
+// <Sequence from={30} durationInFrames={90}><BlenderShot script="blender/orbit.ts" /></Sequence>
+// The frames are rendered once (native call blender.shot, which runs `raea blender shot`) and kept in the
+// composition's asset store, made again when the script, the .blend, the props or the size change.
+import { useContext, type CSSProperties } from "react";
+import { useCurrentFrame, useLocalTime, useVideoConfig } from "@raea/app/clock";
+import { MediaEndContext } from "raea/media";
+import { hasNative, native } from "@raea/app/native";
+import type { ShotEngine } from "./shoot";
+
+export interface BlenderShotProps {
+ /** a raea/blender script whose default export builds or changes the scene, run before the frames are drawn */
+ script?: string;
+ /** a .blend: its own animation from its first frame, or the file the script opens */
+ file?: string;
+ /** eevee (the default), cycles or workbench */
+ engine?: ShotEngine;
+ samples?: number;
+ /** alpha where Blender draws nothing, so the layers under it show */
+ transparent?: boolean;
+ /** the script's sys.argv after -- */
+ args?: string[];
+ /** the shot's own size and length; the composition's (or its Sequence's) when not given */
+ width?: number;
+ height?: number;
+ frames?: number;
+ style?: CSSProperties;
+}
+
+interface Shot {
+ dir: string;
+ frames: number;
+}
+
+const made = new Map<string, Shot>();
+
+/** The shot's frames for these props, made once and kept. */
+export function useBlenderShot(p: BlenderShotProps): Shot {
+ const { fps, width, height, durationInFrames } = useVideoConfig();
+ // as long as what is left of its Sequence (the composition frame media under it stops at), else of the composition
+ const end = useContext(MediaEndContext);
+ const { origin } = useLocalTime("Shot");
+ const left = Math.max(1, (Number.isFinite(end) ? end : durationInFrames) - origin);
+ if (!p.script && !p.file) throw new Error("BlenderShot: give script (a raea/blender script) or file (a .blend)");
+ const req = {
+ script: p.script,
+ file: p.file,
+ engine: p.engine,
+ samples: p.samples,
+ transparent: p.transparent,
+ args: p.args,
+ fps,
+ width: p.width ?? width,
+ height: p.height ?? height,
+ frames: p.frames ?? left,
+ };
+ const key = JSON.stringify(req);
+ let s = made.get(key);
+ if (!s) {
+ if (!hasNative()) throw new Error("BlenderShot: its frames are made by Blender through the raea engine (raea render)");
+ s = native("blender.shot", req as never) as Shot;
+ made.set(key, s);
+ }
+ return s;
+}
+
+/** Frame n of a shot's folder (0000.png on), held at its last frame past its end. */
+export const shotFrame = (s: Shot, n: number) => `${s.dir}/${String(Math.min(Math.max(Math.floor(n), 0), s.frames - 1)).padStart(4, "0")}.png`;
+
+export function BlenderShot(p: BlenderShotProps) {
+ const s = useBlenderShot(p);
+ const f = useCurrentFrame();
+ return (
+ <img
+ fetchPriority="low"
+ src={shotFrame(s, f)}
+ style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", ...p.style }}
+ />
+ );
+}
diff --git a/sdk/godot/package.json b/sdk/godot/package.json
index cab2da4e..185f5b15 100644
--- a/sdk/godot/package.json
+++ b/sdk/godot/package.json
@@ -7,7 +7,8 @@
"type": "module",
"main": "src/index.ts",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./shot": "./src/shot.tsx"
},
"files": ["src", "tools", "README.md"]
}
diff --git a/sdk/godot/src/host/back.ts b/sdk/godot/src/host/back.ts
new file mode 100644
index 00000000..8afa1560
--- /dev/null
+++ b/sdk/godot/src/host/back.ts
@@ -0,0 +1,66 @@
+// What a project raea godot export wrote holds now (docs/godot.feature GD13): `raea godot back DIR` runs this in it,
+// then compares what it writes with scene.json. Each node with a raea_id is placed in raea's terms (Godot's axes are
+// raea's: y up, -z forward); each node added in Godot is written as MEDIA/NAME.glb with a sidecar.
+// raea godot run back.ts --project DIR -- NOW.json MEDIA
+import { Camera3D, Color, DirAccess, FileAccess, GLTFDocument, GLTFState, Light3D, MeshInstance3D, Node3D, PackedScene, ResourceLoader, StandardMaterial3D, Transform3D, type SceneTree } from "raea/godot";
+
+const r6 = (x: number) => Math.round(x * 1e6) / 1e6;
+const hex = (c: Color) => `#${c.to_html(false)}`;
+
+function at(n: Node3D): number[] {
+ const p = n.position;
+ const q = n.quaternion;
+ const s = n.scale;
+ return [p.x, p.y, p.z, q.x, q.y, q.z, q.w, s.x, s.y, s.z].map(r6);
+}
+
+export default async function (_tree: SceneTree, [now, media]: string[]) {
+ if (!now || !media) throw new Error("usage: raea godot run back.ts --project DIR -- NOW.json MEDIA");
+ const packed = ResourceLoader.load("res://main.tscn");
+ if (!(packed instanceof PackedScene)) throw new Error("res://main.tscn: not here; raea godot back reads a project raea godot export wrote");
+ const root = packed.instantiate()!;
+ const parts: object[] = [];
+ const added: object[] = [];
+ let camera: object | null = null;
+ for (const child of root.get_children()) {
+ if (!(child instanceof Node3D)) continue;
+ if (child instanceof Camera3D) {
+ camera = { at: at(child), fov: r6(child.fov) };
+ continue;
+ }
+ if (child.has_meta("raea_id")) {
+ const part: Record<string, unknown> = { id: String(child.get_meta("raea_id")), at: at(child) };
+ if (child instanceof MeshInstance3D) {
+ const m = child.get_surface_override_material(0);
+ if (m instanceof StandardMaterial3D) {
+ part.material = { color: hex(m.albedo_color), roughness: r6(m.roughness), metallic: r6(m.metallic), ...(m.emission_enabled ? { emissive: hex(m.emission) } : {}) };
+ }
+ }
+ if (child instanceof Light3D) part.light = { color: hex(child.light_color), intensity: r6(child.light_energy) };
+ parts.push(part);
+ continue;
+ }
+ // added in Godot: its own .glb, written where it stands at the origin, placed by where it stands
+ const name = String(child.get_name()).replace(/[^A-Za-z0-9_-]+/g, "_");
+ const was = child.transform;
+ const placed = at(child);
+ child.transform = new Transform3D();
+ DirAccess.make_dir_recursive_absolute(media);
+ const file = `${media}/${name}.glb`;
+ const doc = new GLTFDocument();
+ const state = new GLTFState();
+ let err = doc.append_from_scene(child, state);
+ if (err === 0) err = doc.write_to_filesystem(state, file);
+ child.transform = was;
+ if (err !== 0) throw new Error(`${name}: glTF export failed (Godot error ${err})`);
+ const side = FileAccess.open(`${file}.json`, FileAccess.ModeFlags.WRITE);
+ side?.store_string(JSON.stringify({ source: "res://main.tscn", license: "own work", credit: "" }));
+ side?.close();
+ added.push({ name, file: `media/${name}.glb`, at: placed });
+ }
+ root.free();
+ const f = FileAccess.open(now, FileAccess.ModeFlags.WRITE);
+ if (!f) throw new Error(`${now}: can't write it`);
+ f.store_string(JSON.stringify({ parts, camera, new: added }, null, 1));
+ f.close();
+}
diff --git a/sdk/godot/src/host/main.js b/sdk/godot/src/host/main.js
index f722ae5c..4dce01a7 100644
--- a/sdk/godot/src/host/main.js
+++ b/sdk/godot/src/host/main.js
@@ -40,12 +40,29 @@ const report = (e) => {
console.error(`error: ${text}`);
};
+// `--scene res://X.tscn`: that scene playing in the tree before the script runs; `--frames N`: Godot stops after N
+// frames (--quit-after), so the script returning doesn't end the run (a shot, GD11); a scene in a window (--window)
+// plays until the window is closed
+const scenePath = godot.OS.get_environment("RAEA_GODOT_SCENE");
+const hold = godot.OS.get_environment("RAEA_GODOT_HOLD") === "1" || (scenePath !== "" && godot.DisplayServer.get_name() !== "headless");
+
class RaeaMain extends godot.SceneTree {
_initialize() {
+ if (scenePath) {
+ const packed = godot.ResourceLoader.load(scenePath);
+ if (!(packed instanceof godot.PackedScene)) {
+ report(new Error(`${scenePath}: not a scene this project has`));
+ this.quit(1);
+ return;
+ }
+ this.root.add_child(packed.instantiate());
+ }
Promise.resolve()
.then(() => (typeof main === "function" ? main(this, userArgs()) : undefined))
.then(
- () => this.quit(0),
+ () => {
+ if (!hold) this.quit(0);
+ },
(e) => {
report(e);
this.quit(1);
diff --git a/sdk/godot/src/host/none.ts b/sdk/godot/src/host/none.ts
new file mode 100644
index 00000000..24a8657f
--- /dev/null
+++ b/sdk/godot/src/host/none.ts
@@ -0,0 +1,2 @@
+// The script `raea godot shot res://SCENE.tscn` runs: nothing of its own, the scene playing (main.js adds it, GD11).
+export default function () {}
diff --git a/sdk/godot/src/shot.tsx b/sdk/godot/src/shot.tsx
new file mode 100644
index 00000000..0fe10ca2
--- /dev/null
+++ b/sdk/godot/src/shot.tsx
@@ -0,0 +1,75 @@
+// <GodotShot>: a layer of a composition drawn by Godot's Movie Maker, frame for frame (docs/godot.feature GD11).
+// import { GodotShot } from "raea/godot/shot";
+// <GodotShot project="godot" script="godot/rally.ts" /> or <GodotShot project="godot" scene="res://main.tscn" />
+// The frames are recorded once (native call godot.shot, which runs `raea godot shot`) and kept in the composition's
+// asset store, made again when the script, the project's files, the props or the size change.
+import { useContext, type CSSProperties } from "react";
+import { useCurrentFrame, useLocalTime, useVideoConfig } from "@raea/app/clock";
+import { MediaEndContext } from "raea/media";
+import { hasNative, native } from "@raea/app/native";
+
+export interface GodotShotProps {
+ /** the Godot project's folder (its project.godot); an empty project when not given */
+ project?: string;
+ /** a raea/godot script whose default export builds the scene and returns; the scene plays on after it */
+ script?: string;
+ /** a scene of the project, res://PATH.tscn, playing as it would in the game */
+ scene?: string;
+ /** the script's arguments */
+ args?: string[];
+ /** the shot's own size and length; the composition's (or its Sequence's) when not given */
+ width?: number;
+ height?: number;
+ frames?: number;
+ style?: CSSProperties;
+}
+
+interface Shot {
+ dir: string;
+ frames: number;
+}
+
+const made = new Map<string, Shot>();
+
+/** The shot's frames for these props, made once and kept. */
+export function useGodotShot(p: GodotShotProps): Shot {
+ const { fps, width, height, durationInFrames } = useVideoConfig();
+ // as long as what is left of its Sequence (the composition frame media under it stops at), else of the composition
+ const end = useContext(MediaEndContext);
+ const { origin } = useLocalTime("Shot");
+ const left = Math.max(1, (Number.isFinite(end) ? end : durationInFrames) - origin);
+ if (!p.script && !p.scene) throw new Error("GodotShot: give script (a raea/godot script) or scene (res://PATH.tscn)");
+ const req = {
+ project: p.project,
+ script: p.script,
+ scene: p.scene,
+ args: p.args,
+ fps,
+ width: p.width ?? width,
+ height: p.height ?? height,
+ frames: p.frames ?? left,
+ };
+ const key = JSON.stringify(req);
+ let s = made.get(key);
+ if (!s) {
+ if (!hasNative()) throw new Error("GodotShot: its frames are made by Godot through the raea engine (raea render)");
+ s = native("godot.shot", req as never) as Shot;
+ made.set(key, s);
+ }
+ return s;
+}
+
+/** Frame n of a shot's folder (0000.png on), held at its last frame past its end. */
+export const shotFrame = (s: Shot, n: number) => `${s.dir}/${String(Math.min(Math.max(Math.floor(n), 0), s.frames - 1)).padStart(4, "0")}.png`;
+
+export function GodotShot(p: GodotShotProps) {
+ const s = useGodotShot(p);
+ const f = useCurrentFrame();
+ return (
+ <img
+ fetchPriority="low"
+ src={shotFrame(s, f)}
+ style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", ...p.style }}
+ />
+ );
+}
diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.ts
index a20980f1..61a8be6c 100644
--- a/sdk/raea/src/native-calls.ts
+++ b/sdk/raea/src/native-calls.ts
@@ -1,4 +1,4 @@
-// Generated by `raea types` from raea-native's registry (every host's calls); don't edit by hand.
+// Generated by `raea types` from raea's native-call registry (every host's calls); don't edit by hand.
// native(name, args) is typed by this table: a call that isn't registered, or wrong arguments, fails to check.
export interface NativeCalls {
@@ -24,6 +24,10 @@ export interface NativeCalls {
"bevy.world.answer": { args: { ticket: number }; answer: { value?: unknown; error?: string } | null };
/** a BRP method (world.query, world.mutate_components, a plugin's method...) queued for the live Engine's next update: its ticket */
"bevy.world.send": { args: { method: string; params?: unknown }; answer: number };
+ /** a batch of raea/blender's operations run by the Blender `raea blender run SCRIPT.ts` started (sdk/blender) */
+ "blender.post": { args: { sid: string; ops: unknown[] }; answer: { r: Record<string, unknown>; n: number; err?: { i: number; type: string; msg: string; trace: string } } };
+ /** a layer drawn by Blender (<BlenderShot>): a raea/blender script's scene or a .blend's animation rendered frame for frame, made once and kept (0000.png on in dir) */
+ "blender.shot": { args: { script?: string; file?: string; engine?: string; samples?: number; transparent?: boolean; args?: string[]; fps: number; width: number; height: number; frames: number }; answer: { dir: string; frames: number } };
/** raea's command line (render, play, guide, bundle, types; the media verbs: raea media, raea ffmpeg), run in process in cwd */
"cli.raea": { args: { args: string[]; cwd: string }; answer: { exit: number; stdout: string; stderr: string } };
/** a headless run ends with this exit code */
@@ -138,6 +142,8 @@ export interface NativeCalls {
"fs.utimes": { args: { id: number; path: string; mtimeMs: number }; answer: null };
/** bytes written (or appended) to a file */
"fs.write": { args: { id: number; path: string; data: string; append?: boolean; exclusive?: boolean; mode?: number }; answer: null };
+ /** a layer drawn by Godot's Movie Maker (<GodotShot>): a raea/godot script's scene or a project's scene recorded frame for frame, made once and kept (0000.png on in dir) */
+ "godot.shot": { args: { project?: string; script?: string; scene?: string; args?: string[]; fps: number; width: number; height: number; frames: number }; answer: { dir: string; frames: number } };
/** an environment variable of the host process (null when unset) */
"host.env": { args: { name: string }; answer: string | null };
/** whether this host answers a native call */
diff --git a/sdk/tsconfig.base.json b/sdk/tsconfig.base.json
index bbee5cf4..bdc74f2b 100644
--- a/sdk/tsconfig.base.json
+++ b/sdk/tsconfig.base.json
@@ -47,7 +47,9 @@
"raea/physics": ["./physics/src/physics.tsx"],
"raea/r3f": ["./r3f/src/index.ts"],
"raea/blender": ["./blender/src/index.ts"],
+ "raea/blender/shot": ["./blender/src/shot.tsx"],
"raea/godot": ["./godot/src/index.ts"],
+ "raea/godot/shot": ["./godot/src/shot.tsx"],
"raea/pick": ["./render/src/pick.ts"],
"raea/playtest": ["./app/src/playtest.ts"],
"raea/ragdoll": ["./character/src/ragdoll.ts"],
diff --git a/tools/layers.toml b/tools/layers.toml
index 0c90467d..a90c8b0a 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -149,6 +149,7 @@ raea-app-sound = "apps"
raea-app-ci = "apps"
raea-app-tools = "apps"
raea-app-engines = "apps"
+raea-app-interchange = "apps"
raea-app-judge = "apps"
raea-app-solid = "apps"
raea-app-media = "apps"