Compare commits

..
Author SHA1 Message Date
shinyobjectz a90420a8bf no-void leaves the component library out: its gradient shader's own name is void 2026-11-30 18:12:05 -08:00
shinyobjectz 7309e95d90 raea help's line for make component says list WORDS searches the library 2026-11-30 18:07:55 -08:00
shinyobjectz 853f77eb1c The component library: 609 open-source effects sorted by use, searched by raea make component list WORDS and copied by add NAME
sdk/raea/library/components holds 475 pieces from remocn, 79 from the React Video Editor templates and 55 from snapcn,
ported to raea's composition API and sorted by what they're for (text, numbers, transitions, screens, HUDs and more),
not by who made them. catalog.json lists each piece's category, type, what it does, its files, the shared helpers it
needs, its fonts and npm packages and its source; CREDITS.md holds the licences and every file's first line names its
source.

- `raea make component list` ends with the library's categories; `list WORDS` searches by category, category/type or
  words (catalog.ts). `add NAME` copies the piece into components/CATEGORY/NAME/ with its helpers under
  components/_lib/, and installs its npm packages through the engine.
- The native host reads the library beside the binary (share/raea, which tools/release.sh already packs from
  sdk/raea/library), in RAEA_HOME, or in the tree a built raea runs from.
- tools/effects-catalog.sh writes the cut-down catalogue raea cloud's dashboard imports (Libraries › Effects).
- tools/size.sh leaves the library out: it's other people's code, kept as they wrote it but for imports.
- conformance/catalog.test.ts: every listed file exists, imports stay inside what a piece copies, none imports another
  video framework, and search finds by use.
2026-11-30 18:06:34 -08:00
196 changed files with 1612 additions and 38430 deletions

No files matched your search

-2
View File
@@ -107,7 +107,5 @@ sdk/raea/.scratch-*/
# examples/materials/wear: its house is made by make-house.ts (media/) and baked at render time (assets/wear/) # examples/materials/wear: its house is made by make-house.ts (media/) and baked at render time (assets/wear/)
/examples/materials/wear/media/ /examples/materials/wear/media/
/examples/materials/wear/assets/ /examples/materials/wear/assets/
# a playable example's generated sounds, made beside it the first time it's rendered or exported (raea's asset store)
/examples/playables/assets/
# tools/bevy-parity links each example folder's assets/ to Bevy's checkout at run time (an absolute, per-machine path) # tools/bevy-parity links each example folder's assets/ to Bevy's checkout at run time (an absolute, per-machine path)
/sdk/raea/bench/bevy-parity/**/assets /sdk/raea/bench/bevy-parity/**/assets
Generated
+4 -37
View File
@@ -13801,7 +13801,6 @@ name = "raea-app-engines"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"dunce", "dunce",
"raea-app-forma",
"raea-app-interchange", "raea-app-interchange",
"raea-app-tools", "raea-app-tools",
"raea-io-home", "raea-io-home",
@@ -13830,14 +13829,6 @@ dependencies = [
"serde_json", "serde_json",
] ]
[[package]]
name = "raea-app-forma"
version = "0.1.0"
dependencies = [
"raea-io-home",
"serde_json",
]
[[package]] [[package]]
name = "raea-app-game" name = "raea-app-game"
version = "0.1.0" version = "0.1.0"
@@ -13987,10 +13978,7 @@ dependencies = [
name = "raea-app-playable" name = "raea-app-playable"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"base64 0.22.1",
"dunce", "dunce",
"raea-core-fonts",
"raea-io-assets",
"raea-io-home", "raea-io-home",
"raea-runtime-bundle", "raea-runtime-bundle",
"regex", "regex",
@@ -14073,7 +14061,6 @@ name = "raea-app-tools"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"dunce", "dunce",
"raea-app-forma",
"raea-app-motion", "raea-app-motion",
"raea-io-assets", "raea-io-assets",
"raea-io-gen", "raea-io-gen",
@@ -15522,7 +15509,6 @@ dependencies = [
"raea-runtime-page", "raea-runtime-page",
"raea-runtime-pagestore", "raea-runtime-pagestore",
"raea-runtime-react", "raea-runtime-react",
"raea-runtime-review",
"raea-runtime-scene", "raea-runtime-scene",
"raea-runtime-scene3d", "raea-runtime-scene3d",
"raea-runtime-sound", "raea-runtime-sound",
@@ -15672,9 +15658,12 @@ version = "0.1.0"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"bevy", "bevy",
"image",
"raea-core-scene", "raea-core-scene",
"raea-core-wire", "raea-core-wire",
"raea-io-assets",
"raea-io-home", "raea-io-home",
"raea-io-media",
"raea-io-net", "raea-io-net",
"raea-page", "raea-page",
"raea-render", "raea-render",
@@ -15683,8 +15672,8 @@ dependencies = [
"raea-runtime-react", "raea-runtime-react",
"raea-runtime-twins", "raea-runtime-twins",
"raea-runtime-view", "raea-runtime-view",
"raea-sys-facetrack",
"raea-sys-fonts", "raea-sys-fonts",
"raea-sys-frame",
"raea-sys-image", "raea-sys-image",
"raea-sys-page", "raea-sys-page",
"raea-sys-screen", "raea-sys-screen",
@@ -15764,17 +15753,6 @@ dependencies = [
"xxhash-rust", "xxhash-rust",
] ]
[[package]]
name = "raea-runtime-review"
version = "0.1.0"
dependencies = [
"image",
"raea-core-facts",
"raea-core-review",
"raea-sys-light-meter",
"serde_json",
]
[[package]] [[package]]
name = "raea-runtime-scene" name = "raea-runtime-scene"
version = "0.1.0" version = "0.1.0"
@@ -16161,17 +16139,6 @@ dependencies = [
"parry3d", "parry3d",
] ]
[[package]]
name = "raea-sys-facetrack"
version = "0.1.0"
dependencies = [
"image",
"raea-io-assets",
"raea-io-media",
"raea-sys-frame",
"serde_json",
]
[[package]] [[package]]
name = "raea-sys-filters" name = "raea-sys-filters"
version = "0.1.0" version = "0.1.0"
-3
View File
@@ -127,7 +127,6 @@ members = [
"systems/page-net", "systems/page-net",
"systems/page-ops", "systems/page-ops",
"systems/frame", "systems/frame",
"systems/facetrack",
"systems/engine-shaders", "systems/engine-shaders",
"systems/shots", "systems/shots",
"systems/hold", "systems/hold",
@@ -185,7 +184,6 @@ members = [
"runtime/react", "runtime/react",
"runtime/track", "runtime/track",
"runtime/pagestore", "runtime/pagestore",
"runtime/review",
"runtime/cssurls", "runtime/cssurls",
"runtime/pid", "runtime/pid",
"bench/bridge", "bench/bridge",
@@ -237,7 +235,6 @@ members = [
"apps/tools", "apps/tools",
"apps/motion", "apps/motion",
"apps/engines", "apps/engines",
"apps/forma",
"apps/interchange", "apps/interchange",
"apps/judge", "apps/judge",
"apps/make", "apps/make",
+1 -2
View File
@@ -213,8 +213,7 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
continue; continue;
} }
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2) // the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
let color = r.middle_color(); let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, color) };
let Some(ratio) = ratio else { continue }; let Some(ratio) = ratio else { continue };
measured += 1; measured += 1;
if ratio < 3.0 { if ratio < 3.0 {
+5 -6
View File
@@ -67,8 +67,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() }, Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() }, Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
]); ]);
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 }; let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 }; let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let (mut issues, mut passed) = (vec![], vec![]); let (mut issues, mut passed) = (vec![], vec![]);
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed); taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect(); let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
@@ -267,7 +267,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
#[test] #[test]
fn a_caption_is_timed_from_the_first_word_it_shows() { fn a_caption_is_timed_from_the_first_word_it_shows() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 }; let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let words: Vec<Word> = [("half", 12.2), ("of", 12.66), ("the", 12.8), ("spend", 12.96)].iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect(); let words: Vec<Word> = [("half", 12.2), ("of", 12.66), ("the", 12.8), ("spend", 12.96)].iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect();
let (mut issues, mut passed) = (vec![], vec![]); let (mut issues, mut passed) = (vec![], vec![]);
// on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later // on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later
@@ -335,7 +335,7 @@ fn safe_area_tests_the_letters_not_the_box() {
#[test] #[test]
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() { fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 }; let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>(); let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]); let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
let (mut issues, mut passed) = (vec![], vec![]); let (mut issues, mut passed) = (vec![], vec![]);
@@ -425,11 +425,10 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
#[test] #[test]
fn a_moving_text_is_read_where_it_is() { fn a_moving_text_is_read_where_it_is() {
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0]; let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], color: String::new(), size: 40.0 }; let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), color: String::new(), size: 40.0 };
let (t, b) = run.middle(30.0); let (t, b) = run.middle(30.0);
assert_eq!(t, 4.0); assert_eq!(t, 4.0);
assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}"); assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}");
let still = Run { boxes: vec![ink(0); 240], box_: [40.0, 1000.0, 60.0, 40.0], ..run }; let still = Run { boxes: vec![ink(0); 240], box_: [40.0, 1000.0, 60.0, 40.0], ..run };
assert_eq!(still.middle(30.0), (4.0, [40.0, 1000.0, 60.0, 40.0])); assert_eq!(still.middle(30.0), (4.0, [40.0, 1000.0, 60.0, 40.0]));
} }
+2 -36
View File
@@ -43,10 +43,6 @@ pub struct Run {
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves /// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
/// through the frame's edges and zones, which only counts against it when no frame shows it clear /// through the frame's edges and zones, which only counts against it when no frame shows it clear
pub boxes: Vec<[f64; 4]>, pub boxes: Vec<[f64; 4]>,
/// its colour on each of those frames, beside `boxes`: a text can change colour while it reads the same (a step
/// chip lighting up, grey on dark to dark on yellow), and its contrast is its colour on the frame it's measured at
pub colors: Vec<String>,
/// its colour on its last frame
pub color: String, pub color: String,
pub size: f64, pub size: f64,
} }
@@ -61,15 +57,6 @@ impl Run {
let (at, [x, y, w, h]) = (self.boxes[n / 2], self.box_); let (at, [x, y, w, h]) = (self.boxes[n / 2], self.box_);
(self.to - (n - n / 2) as f64 / fps, [x + at[0] - last[0], y + at[1] - last[1], w, h]) (self.to - (n - n / 2) as f64 / fps, [x + at[0] - last[0], y + at[1] - last[1], w, h])
} }
/// Its colour on the frame `middle` measures: the one it had there, not the one it ended with.
pub fn middle_color(&self) -> &str {
let n = self.boxes.len();
match self.colors.get(n / 2) {
Some(c) if n > 1 && self.colors.len() == n => c,
_ => &self.color,
}
}
} }
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds /// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
@@ -127,21 +114,18 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
}); });
let mut r = match found { let mut r = match found {
Some(i) => open.remove(i), Some(i) => open.remove(i),
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), color: String::new(), size: 0.0 }, None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), color: String::new(), size: 0.0 },
}; };
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
if text.len() > r.text.len() { if text.len() > r.text.len() {
r.boxes.clear(); r.boxes.clear();
r.colors.clear();
} }
if text.len() >= r.text.len() { if text.len() >= r.text.len() {
r.text = text; r.text = text;
r.box_ = b; r.box_ = b;
r.boxes.push(ink.unwrap_or(b)); r.boxes.push(ink.unwrap_or(b));
r.colors.push(color.clone());
} }
r.to = t + 1.0 / fps; r.to = t + 1.0 / fps;
r.color = color; r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
r.size = x["size"].as_f64().unwrap_or(0.0); r.size = x["size"].as_f64().unwrap_or(0.0);
next.push(r); next.push(r);
} }
@@ -310,21 +294,3 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
passed.push(format!("cues: {checked} texts land on their words")); passed.push(format!("cues: {checked} texts land on their words"));
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_text_that_lights_up_is_measured_in_its_colour_at_the_middle() {
// a step chip: grey on dark for six frames, then dark on yellow for four (the same words)
let m = json!({"fps": 10.0, "frames": (0..10).map(|f| json!({"frame": f, "text": [
{"text": "03 MAP", "box": [500, 120, 130, 52], "size": 23, "color": if f < 6 { "rgb(169, 169, 174)" } else { "rgb(10, 10, 11)" }}
]})).collect::<Vec<_>>()});
let runs = text_runs(&m);
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour");
assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
}
}
-2
View File
@@ -9,8 +9,6 @@ description = "The `raea` verbs that script other engines from TypeScript: Blend
[dependencies] [dependencies]
# Blender found or downloaded, its scripts in Python, and the helpers Godot's setup shares (apps/tools/src/blender.rs) # Blender found or downloaded, its scripts in Python, and the helpers Godot's setup shares (apps/tools/src/blender.rs)
raea-app-tools = { path = "../tools" } raea-app-tools = { path = "../tools" }
# forma, a headless modeller (GPL-3.0-or-later), downloaded and run as its own program, its .glb fixed after (apps/forma)
raea-app-forma = { path = "../forma" }
raea-io-home = { path = "../../io/home" } raea-io-home = { path = "../../io/home" }
# a TypeScript script bundled and run on raea's engine, posting raea/blender's batches to the bridge (blender.post) # a TypeScript script bundled and run on raea's engine, posting raea/blender's batches to the bridge (blender.post)
raea-runtime-bundle = { path = "../../runtime/bundle" } raea-runtime-bundle = { path = "../../runtime/bundle" }
+2 -10
View File
@@ -1,8 +1,6 @@
//! The verbs that script other engines from TypeScript: Blender (`raea setup blender`, `raea blender run SCRIPT.py|.ts`; //! The verbs that script other engines from TypeScript: Blender (`raea setup blender`, `raea blender run SCRIPT.py|.ts`;
//! finding and setting Blender up is apps/tools/src/blender.rs) and Godot with GodotJS (`raea setup godot`, //! finding and setting Blender up is apps/tools/src/blender.rs) and Godot with GodotJS (`raea setup godot`,
//! `raea godot run|types|open`; sdk/blender and sdk/godot are their TypeScript sides). forma, a headless modeller for //! `raea godot run|types|open`; sdk/blender and sdk/godot are their TypeScript sides).
//! hard-surface parts, runs the same way: downloaded, run as its own program, never linked (`raea setup forma`,
//! `raea forma`; apps/forma).
/// the Blender a TypeScript script drives (`raea blender run SCRIPT.ts`, sdk/blender) /// the Blender a TypeScript script drives (`raea blender run SCRIPT.ts`, sdk/blender)
pub mod blender_bridge; pub mod blender_bridge;
@@ -18,16 +16,11 @@ pub mod shot;
pub mod round; pub mod round;
use raea_app_tools::blender; use raea_app_tools::blender;
/// `raea setup forma` and `raea forma`: forma (GPL-3.0-or-later) downloaded and run as its own program (apps/forma)
pub use raea_app_forma as forma;
type R<T> = Result<T, String>; type R<T> = Result<T, String>;
/// The CLI's verbs here, or None for any other: `setup blender|godot|forma`, `blender ...`, `godot ...` and `forma ...`. /// The CLI's verbs here, or None for any other: `setup blender|godot`, `blender ...` and `godot ...`.
pub fn cli(args: &[String]) -> Option<R<String>> { pub fn cli(args: &[String]) -> Option<R<String>> {
if let Some(done) = forma::cli(args) {
return Some(done);
}
let second = args.get(1).map(String::as_str); let second = args.get(1).map(String::as_str);
Some(match (args.first()?.as_str(), second) { Some(match (args.first()?.as_str(), second) {
("setup", Some("blender")) => blender::setup(&args[2..]), ("setup", Some("blender")) => blender::setup(&args[2..]),
@@ -61,6 +54,5 @@ mod tests {
assert!(cli(&args("render edit.tsx")).is_none()); assert!(cli(&args("render edit.tsx")).is_none());
assert!(cli(&[]).is_none()); assert!(cli(&[]).is_none());
assert!(cli(&args("godot")).unwrap().unwrap_err().contains(godot::USAGE)); assert!(cli(&args("godot")).unwrap().unwrap_err().contains(godot::USAGE));
assert!(cli(&args("forma")).is_some());
} }
} }
-12
View File
@@ -1,12 +0,0 @@
[package]
name = "raea-app-forma"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea setup forma` and `raea forma`: forma (GPL-3.0-or-later) downloaded and run as its own program, its .glb fixed after"
[dependencies]
raea-io-home = { path = "../../io/home" }
# the .glb forma writes, read and written back with its colours linear and its normals smoothed (glb.rs)
serde_json = "1"
-340
View File
@@ -1,340 +0,0 @@
//! The .glb forma writes, fixed for a renderer that reads glTF as the spec says (docs/forma.feature FM3, FM4). forma
//! 0.4.4 writes a material's colour as it was typed (sRGB, as a person picks one) into baseColorFactor, which glTF reads
//! as linear, so every colour comes out pale; and it writes one normal per face, so a cylinder shows its facets. The fix
//! converts the colours, and gives each corner the mean of the faces around it that meet its own at under `smooth`
//! degrees, so a box keeps its edges and a cylinder's side turns round. Only the JSON's colours and the normals' bytes
//! change: positions, indices, UVs and the file's layout stay as forma wrote them. A fixed file is marked in
//! asset.extras and left alone after, so fixing twice never darkens it twice.
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet};
use std::path::Path;
type R<T> = Result<T, String>;
/// The mark a fixed file carries in asset.extras.
pub const MARK: &str = "raea_forma";
const JSON: u32 = 0x4E4F_534A;
const BIN: u32 = 0x004E_4942;
const FLOAT: u64 = 5126;
/// What a fix changed.
#[derive(Debug, PartialEq)]
pub struct Fixed {
/// materials whose colour was made linear
pub colours: usize,
/// mesh primitives whose normals were smoothed
pub primitives: usize,
/// the file was fixed before and is unchanged
pub already: bool,
}
/// Fixes a .glb in place (written beside it, then renamed over it).
pub fn fix_file(path: &Path, smooth: Option<f32>) -> R<Fixed> {
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
let (out, fixed) = fix(&bytes, smooth).map_err(|e| format!("{}: {e}", path.display()))?;
if !fixed.already {
let tmp = path.with_extension("raea-tmp");
std::fs::write(&tmp, out).map_err(|e| format!("{}: {e}", tmp.display()))?;
std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))?;
}
Ok(fixed)
}
/// The fixed file's bytes. `smooth`: the largest angle in degrees between two faces whose shared corners are smoothed;
/// None keeps forma's normals.
pub fn fix(glb: &[u8], smooth: Option<f32>) -> R<(Vec<u8>, Fixed)> {
let (mut doc, mut bin) = read(glb)?;
if doc["asset"]["extras"][MARK].is_object() {
return Ok((glb.to_vec(), Fixed { colours: 0, primitives: 0, already: true }));
}
let colours = linear_colours(&mut doc);
let primitives = match smooth {
Some(deg) => smooth_normals(&doc, &mut bin, deg)?,
None => 0,
};
let asset = doc.as_object_mut().ok_or("the glTF JSON isn't an object")?.entry("asset").or_insert_with(|| json!({"version": "2.0"}));
let extras = asset.as_object_mut().ok_or("asset isn't an object")?.entry("extras").or_insert_with(|| json!({}));
if let Some(e) = extras.as_object_mut() {
e.insert(MARK.into(), json!({"colours": "linear", "smooth": smooth}));
}
Ok((write(&doc, &bin), Fixed { colours, primitives, already: false }))
}
/// The JSON chunk and the BIN chunk (empty when there is none).
pub fn read(glb: &[u8]) -> R<(Value, Vec<u8>)> {
let u32_at = |at: usize| glb.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
if glb.get(..4) != Some(b"glTF") || u32_at(4) != Some(2) {
return Err("not a glTF 2.0 binary (.glb)".into());
}
let (len, kind) = (u32_at(12).ok_or("no JSON chunk")? as usize, u32_at(16).ok_or("no JSON chunk")?);
let text = glb.get(20..20 + len).filter(|_| kind == JSON).ok_or("the first chunk isn't JSON")?;
let doc: Value = serde_json::from_slice(text).map_err(|e| format!("the glTF JSON: {e}"))?;
let at = 20 + len;
let bin = match (u32_at(at), u32_at(at + 4)) {
(Some(n), Some(BIN)) => glb.get(at + 8..at + 8 + n as usize).ok_or("the BIN chunk runs past the file")?.to_vec(),
_ => Vec::new(),
};
Ok((doc, bin))
}
/// A .glb of a JSON document and a BIN chunk, each padded to four bytes as glTF asks (the JSON with spaces).
pub fn write(doc: &Value, bin: &[u8]) -> Vec<u8> {
let mut text = serde_json::to_vec(doc).unwrap_or_default();
while !text.len().is_multiple_of(4) {
text.push(b' ');
}
let mut data = bin.to_vec();
while !data.len().is_multiple_of(4) {
data.push(0);
}
let total = 12 + 8 + text.len() + if data.is_empty() { 0 } else { 8 + data.len() };
let mut out = Vec::with_capacity(total);
out.extend_from_slice(b"glTF");
out.extend_from_slice(&2u32.to_le_bytes());
out.extend_from_slice(&(total as u32).to_le_bytes());
out.extend_from_slice(&(text.len() as u32).to_le_bytes());
out.extend_from_slice(&JSON.to_le_bytes());
out.extend_from_slice(&text);
if !data.is_empty() {
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
out.extend_from_slice(&BIN.to_le_bytes());
out.extend_from_slice(&data);
}
out
}
/// sRGB's transfer undone: the linear value glTF's baseColorFactor holds.
pub fn srgb_to_linear(c: f64) -> f64 {
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
}
/// Every material's baseColorFactor made linear (alpha kept); how many there were.
fn linear_colours(doc: &mut Value) -> usize {
let Some(mats) = doc.get_mut("materials").and_then(Value::as_array_mut) else { return 0 };
let mut n = 0;
for m in mats {
if let Some(c) = m.pointer_mut("/pbrMetallicRoughness/baseColorFactor").and_then(Value::as_array_mut) {
for v in c.iter_mut().take(3) {
if let Some(x) = v.as_f64() {
*v = json!(srgb_to_linear(x));
}
}
n += 1;
}
}
n
}
/// Where an accessor's elements are in the BIN chunk: the first's byte, the step between them, how many, the component
/// type, the components in each. None for one this fix doesn't read (sparse, another buffer, or past the chunk).
fn layout(doc: &Value, acc: u64, bin: &[u8]) -> Option<(usize, usize, usize, u64, usize)> {
let a = doc["accessors"].get(acc as usize)?;
if a.get("sparse").is_some() {
return None;
}
let v = doc["bufferViews"].get(a["bufferView"].as_u64()? as usize)?;
if v["buffer"].as_u64().unwrap_or(0) != 0 {
return None;
}
let comp = a["componentType"].as_u64()?;
let size = match comp {
5120 | 5121 => 1,
5122 | 5123 => 2,
5125 | 5126 => 4,
_ => return None,
};
let n = match a["type"].as_str()? {
"SCALAR" => 1,
"VEC2" => 2,
"VEC3" => 3,
"VEC4" => 4,
_ => return None,
};
let start = v["byteOffset"].as_u64().unwrap_or(0) as usize + a["byteOffset"].as_u64().unwrap_or(0) as usize;
let stride = v["byteStride"].as_u64().map_or(size * n, |s| s as usize);
let count = a["count"].as_u64()? as usize;
(count == 0 || start + stride * (count - 1) + size * n <= bin.len()).then_some((start, stride, count, comp, n))
}
fn f32_at(bin: &[u8], at: usize) -> f32 {
f32::from_le_bytes([bin[at], bin[at + 1], bin[at + 2], bin[at + 3]])
}
fn vec3s(doc: &Value, acc: u64, bin: &[u8]) -> Option<Vec<[f32; 3]>> {
let (start, stride, count, comp, n) = layout(doc, acc, bin)?;
(comp == FLOAT && n == 3).then(|| (0..count).map(|i| std::array::from_fn(|k| f32_at(bin, start + i * stride + 4 * k))).collect())
}
fn indices(doc: &Value, prim: &Value, bin: &[u8], verts: usize) -> Option<Vec<usize>> {
let Some(acc) = prim.get("indices").and_then(Value::as_u64) else { return Some((0..verts).collect()) };
let (start, stride, count, comp, n) = layout(doc, acc, bin)?;
if n != 1 {
return None;
}
let at = |i: usize| start + i * stride;
let idx: Vec<usize> = match comp {
5121 => (0..count).map(|i| bin[at(i)] as usize).collect(),
5123 => (0..count).map(|i| u16::from_le_bytes([bin[at(i)], bin[at(i) + 1]]) as usize).collect(),
5125 => (0..count).map(|i| u32::from_le_bytes([bin[at(i)], bin[at(i) + 1], bin[at(i) + 2], bin[at(i) + 3]]) as usize).collect(),
_ => return None,
};
idx.iter().all(|&i| i < verts).then_some(idx)
}
fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 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]]
}
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn unit(a: [f32; 3]) -> Option<[f32; 3]> {
let l = dot(a, a).sqrt();
(l > 1e-20).then(|| [a[0] / l, a[1] / l, a[2] / l])
}
/// New normals for one primitive: each corner takes the area-weighted mean of the triangles at its position (corners
/// forma split per face are joined by position) whose facing is within `deg` of the corner's own normal.
pub fn smoothed(pos: &[[f32; 3]], normals: &[[f32; 3]], idx: &[usize], deg: f32) -> Vec<[f32; 3]> {
let lo = pos.iter().fold([f32::MAX; 3], |m, p| std::array::from_fn(|k| m[k].min(p[k])));
let hi = pos.iter().fold([f32::MIN; 3], |m, p| std::array::from_fn(|k| m[k].max(p[k])));
let eps = (dot(sub(hi, lo), sub(hi, lo)).sqrt() * 1e-6).max(1e-9);
let key = |p: [f32; 3]| p.map(|c| (c / eps).round() as i64);
let mut group: HashMap<[i64; 3], usize> = HashMap::new();
let gid: Vec<usize> = pos.iter().map(|&p| { let n = group.len(); *group.entry(key(p)).or_insert(n) }).collect();
let mut around: Vec<Vec<[f32; 3]>> = vec![Vec::new(); group.len()];
for t in idx.as_chunks::<3>().0 {
let f = cross(sub(pos[t[1]], pos[t[0]]), sub(pos[t[2]], pos[t[0]]));
if unit(f).is_none() {
continue;
}
let mut seen = [usize::MAX; 3];
for (k, &v) in t.iter().enumerate() {
if !seen.contains(&gid[v]) {
around[gid[v]].push(f);
seen[k] = gid[v];
}
}
}
let cos = deg.to_radians().cos();
(0..pos.len())
.map(|v| {
let Some(own) = unit(normals[v]) else { return normals[v] };
let sum = around[gid[v]].iter().filter(|f| unit(**f).is_some_and(|u| dot(u, own) >= cos)).fold([0.0; 3], |s, f| [s[0] + f[0], s[1] + f[1], s[2] + f[2]]);
unit(sum).unwrap_or(own)
})
.collect()
}
/// Every triangle primitive's normals smoothed in the BIN chunk; how many primitives changed. A primitive with tangents
/// is left alone (smoothing would leave them stale), as is one whose data this fix doesn't read.
fn smooth_normals(doc: &Value, bin: &mut [u8], deg: f32) -> R<usize> {
let mut done: HashSet<u64> = HashSet::new();
let mut n = 0;
for mesh in doc["meshes"].as_array().into_iter().flatten() {
for prim in mesh["primitives"].as_array().into_iter().flatten() {
let attrs = &prim["attributes"];
let (Some(p), Some(nm)) = (attrs["POSITION"].as_u64(), attrs["NORMAL"].as_u64()) else { continue };
if prim["mode"].as_u64().unwrap_or(4) != 4 || attrs.get("TANGENT").is_some() || !done.insert(nm) {
continue;
}
let (Some(pos), Some(normals)) = (vec3s(doc, p, bin), vec3s(doc, nm, bin)) else { continue };
let Some(idx) = indices(doc, prim, bin, pos.len()).filter(|_| pos.len() == normals.len()) else { continue };
let new = smoothed(&pos, &normals, &idx, deg);
let (start, stride, ..) = layout(doc, nm, bin).ok_or("the normals moved")?;
for (i, v) in new.iter().enumerate() {
for (k, c) in v.iter().enumerate() {
let at = start + i * stride + 4 * k;
bin[at..at + 4].copy_from_slice(&c.to_le_bytes());
}
}
n += 1;
}
}
Ok(n)
}
#[cfg(test)]
mod tests {
use super::*;
/// Two triangles forma-style (corners split per face, flat normals) meeting along x at `fold` degrees, with
/// a red material typed as sRGB.
fn hinge(fold: f32) -> Vec<u8> {
let (s, c) = fold.to_radians().sin_cos();
let pos: [[f32; 3]; 6] = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, -c, s], [1.0, 0.0, 0.0]];
let b = unit(cross(sub(pos[4], pos[3]), sub(pos[5], pos[3]))).unwrap();
let nrm: [[f32; 3]; 6] = [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], b, b, b];
let mut bin = Vec::new();
for v in pos.iter().chain(nrm.iter()) {
for c in v {
bin.extend_from_slice(&c.to_le_bytes());
}
}
for i in 0u16..6 {
bin.extend_from_slice(&i.to_le_bytes());
}
let doc = json!({
"asset": {"version": "2.0", "generator": "forma"},
"materials": [{"pbrMetallicRoughness": {"baseColorFactor": [0.72, 0.36, 0.0, 0.5]}}],
"meshes": [{"primitives": [{"attributes": {"POSITION": 0, "NORMAL": 1}, "indices": 2, "material": 0}]}],
"accessors": [
{"bufferView": 0, "componentType": 5126, "count": 6, "type": "VEC3"},
{"bufferView": 0, "byteOffset": 72, "componentType": 5126, "count": 6, "type": "VEC3"},
{"bufferView": 1, "componentType": 5123, "count": 6, "type": "SCALAR"}
],
"bufferViews": [{"buffer": 0, "byteLength": 144}, {"buffer": 0, "byteOffset": 144, "byteLength": 12}],
"buffers": [{"byteLength": 156}]
});
write(&doc, &bin)
}
fn normals_of(glb: &[u8]) -> Vec<[f32; 3]> {
let (doc, bin) = read(glb).unwrap();
vec3s(&doc, 1, &bin).unwrap()
}
#[test]
fn colours_become_linear_once() {
let (out, f) = fix(&hinge(10.0), None).unwrap();
assert_eq!(f, Fixed { colours: 1, primitives: 0, already: false });
let (doc, _) = read(&out).unwrap();
let c: Vec<f64> = doc["materials"][0]["pbrMetallicRoughness"]["baseColorFactor"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
assert!((c[0] - 0.4770).abs() < 1e-3 && (c[1] - 0.1065).abs() < 1e-3 && c[2] == 0.0 && c[3] == 0.5, "{c:?}");
assert_eq!(doc["asset"]["generator"], "forma");
let (again, f2) = fix(&out, Some(40.0)).unwrap();
assert!(f2.already && again == out);
}
#[test]
fn a_shallow_fold_turns_round_and_a_sharp_one_stays() {
let (out, f) = fix(&hinge(10.0), Some(40.0)).unwrap();
assert_eq!(f.primitives, 1);
let n = normals_of(&out);
// the corners on the shared edge lean halfway; the corners on one face alone keep its facing
let tilt = |v: [f32; 3]| dot(v, [0.0, 0.0, 1.0]).acos().to_degrees();
assert!((tilt(n[0]) - 5.0).abs() < 0.01 && (tilt(n[1]) - 5.0).abs() < 0.01 && (tilt(n[3]) - 5.0).abs() < 0.01, "{n:?}");
assert!(tilt(n[2]) < 1e-3 && (tilt(n[4]) - 10.0).abs() < 0.01, "{n:?}");
for v in &n {
assert!((dot(*v, *v) - 1.0).abs() < 1e-5);
}
let (sharp, _) = fix(&hinge(60.0), Some(40.0)).unwrap();
assert_eq!(normals_of(&sharp), normals_of(&hinge(60.0)));
}
#[test]
fn the_file_keeps_its_layout() {
let src = hinge(10.0);
let (out, _) = fix(&src, Some(40.0)).unwrap();
assert_eq!(out.len() % 4, 0);
assert_eq!(u32::from_le_bytes([out[8], out[9], out[10], out[11]]) as usize, out.len());
let ((_, a), (_, b)) = (read(&src).unwrap(), read(&out).unwrap());
assert_eq!(a.len(), b.len());
assert_eq!(a[..72], b[..72], "positions untouched");
assert_eq!(a[144..], b[144..], "indices untouched");
assert!(fix(b"not a glb", None).is_err());
}
}
-347
View File
@@ -1,347 +0,0 @@
//! `raea setup forma` and `raea forma` (docs/forma.feature). forma (github.com/wrong-nebula/forma) is a headless
//! modeller for hard-surface parts: a few lines of its pipe language make a watertight mesh with exact sizes in
//! milliseconds (gears, brackets, threads, enclosures, a lathed vase, a table). forma is GPL-3.0-or-later and raea is
//! FSL, so raea never links forma or ships it: setup downloads forma's own release into ~/.raea/tools/forma, as
//! `raea setup blender` does Blender, and `raea forma` runs it as a program of its own, then fixes the .glb it wrote
//! (glb.rs). What forma makes belongs to whoever made it; the GPL covers forma alone.
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
/// the .glb forma writes, its colours made linear and its normals smoothed
pub mod glb;
type R<T> = Result<T, String>;
/// The forma raea downloads and is tested with.
pub const VERSION: &str = "0.4.4";
/// Linux: forma's static musl binary from its GitHub release, which needs no Node; each archive's sha256, pinned.
const LINUX: [(&str, &str); 2] = [
("x86_64", "52ffc3d60787a9aab9989064624729115e6b1b8d29e53540fde0188443af9470"),
("aarch64", "c4788352ce97c432a818d4c8e6f16d60e74e193909ac56ea5b1a066cf967bb5d"),
];
/// Elsewhere: the npm package forma-3d (forma built for WebAssembly, with its CLI and MCP server), run by Node 18+ or
/// Bun; the tarball's sha512, pinned (npm's own integrity for it, in hex).
const NPM_SHA512: &str = "676e7990b32dbc3a035079509c5ac9baa86bd24423a53e57e9b586f4b7ff45b07bda75842f58e795c7a128b8a35bc94bc1eafc8e2f94126bcc5f1c3200626a95";
/// The angle under which `raea forma` smooths a .glb's normals unless --smooth says.
pub const SMOOTH: f32 = 40.0;
pub const USAGE: &str = "raea setup forma [--check] [--download] (find forma or download it into ~/.raea/tools/forma: forma 0.4.4, a headless modeller for hard-surface parts (GPL-3.0-or-later, so raea runs it as its own program and never ships it), its static binary on Linux, else its npm package run by Node 18+ or Bun, each checked against its pinned hash)\n raea forma SCRIPT.forma -o OUT.glb|.stl|.obj|.3mf|.step [--unit m|cm|mm|um|in|ft] [--render PREVIEW.png] [--draw BLUEPRINT.svg] [--size PX] [--smooth DEG] [--flat] [--no-strict] (a forma script made into OUT, each named part its own node; a mesh that isn't watertight is refused with forma's reason unless --no-strict; a .glb's colours are made linear, as glTF reads them, and its normals smoothed where faces meet under DEG degrees (40 unless given; --flat keeps forma's faceted ones); --render's preview draws the last part, raea render draws them all)\n raea forma fix FILE.glb... [--smooth DEG] [--flat] (the same fix on a .glb forma wrote by itself (its MCP server's export, its own CLI): colours linear, normals smoothed; a file fixed before is left alone)\n raea forma spec [--topic deform|curves|uv|remesh|scene] [--gbnf] (forma's language reference, about 500 tokens: its primitives, operations and selectors)";
/// How forma is run: its own binary, or its npm package's CLI by a JavaScript runtime.
#[derive(Debug, Clone, PartialEq)]
pub enum Forma {
Native(PathBuf),
Js { runtime: PathBuf, cli: PathBuf },
}
impl Forma {
pub fn command(&self) -> Command {
match self {
Forma::Native(bin) => Command::new(bin),
Forma::Js { runtime, cli } => {
let mut c = Command::new(runtime);
c.arg(cli);
c
}
}
}
fn path(&self) -> &Path {
match self {
Forma::Native(p) | Forma::Js { cli: p, .. } => p,
}
}
}
/// Where raea keeps its download of forma.
pub fn own_dir() -> R<PathBuf> {
Ok(raea_io_home::user_home().ok_or("no home folder (HOME)")?.join(".raea/tools/forma"))
}
fn on_path(name: &str) -> Option<PathBuf> {
let exe = if cfg!(windows) { format!("{name}.exe") } else { name.to_string() };
std::env::split_paths(&std::env::var_os("PATH")?).map(|d| d.join(&exe)).find(|p| p.is_file())
}
/// Node, else Bun: what runs forma's npm package.
fn js_runtime() -> R<PathBuf> {
on_path("node").or_else(|| on_path("bun")).ok_or_else(|| "forma runs here on Node.js 18 or later, or Bun, and neither is on PATH: install one (https://nodejs.org), then raea setup forma again".into())
}
/// A forma at a path: a .mjs or .js is forma's npm CLI, anything else its binary.
fn at(p: PathBuf) -> R<Forma> {
Ok(if p.extension().is_some_and(|x| x == "mjs" || x == "js") { Forma::Js { runtime: js_runtime()?, cli: p } } else { Forma::Native(p) })
}
fn run(cmd: &mut Command, what: &str) -> R<String> {
let o = cmd.output().map_err(|e| format!("{what}: {e}"))?;
if !o.status.success() {
return Err(format!("{what} failed: {}{}", String::from_utf8_lossy(&o.stderr).trim(), String::from_utf8_lossy(&o.stdout).trim()));
}
Ok(String::from_utf8_lossy(&o.stdout).into_owned())
}
/// The forma to use and where it came from: `git config --global raea.forma` (a binary or forma's bin/forma.mjs),
/// raea's download, then a `forma` on PATH that says it is forma.
pub fn find() -> R<Option<(Forma, &'static str)>> {
let configured = run(Command::new("git").args(["config", "--global", "raea.forma"]), "git config").ok().map(|o| PathBuf::from(o.trim()));
if let Some(p) = configured.filter(|p| p.is_file()) {
return Ok(Some((at(p)?, "raea.forma in git config")));
}
let dir = own_dir()?;
for p in [dir.join(if cfg!(windows) { "forma.exe" } else { "forma" }), dir.join("package/bin/forma.mjs")] {
if p.is_file() {
return Ok(Some((at(p)?, "raea's download")));
}
}
Ok(on_path("forma").map(Forma::Native).filter(|f| version(f).is_ok()).map(|f| (f, "PATH")))
}
/// `forma --version`'s first line ("forma 0.4.4 (WASM)"); an error when the program isn't forma.
pub fn version(f: &Forma) -> R<String> {
let out = run(f.command().arg("--version"), "forma --version")?;
out.lines().map(str::trim).find(|l| l.starts_with("forma")).map(str::to_string).ok_or_else(|| format!("{} --version didn't say forma", f.path().display()))
}
/// A file's sha256 or sha512 in hex, by the platform's own tool (as blender.rs and godot.rs check their downloads).
pub fn digest(file: &Path, bits: u32) -> R<String> {
let out = if cfg!(windows) {
run(Command::new("certutil").arg("-hashfile").arg(file).arg(format!("SHA{bits}")), "certutil")?.lines().nth(1).unwrap_or_default().replace(' ', "")
} else if on_path("shasum").is_some() {
run(Command::new("shasum").args(["-a", &bits.to_string()]).arg(file), "shasum")?.split_whitespace().next().unwrap_or_default().to_string()
} else {
run(Command::new(format!("sha{bits}sum")).arg(file), "sha sum")?.split_whitespace().next().unwrap_or_default().to_string()
};
Ok(out.to_lowercase())
}
/// Downloads forma into ~/.raea/tools/forma, checked against its pinned hash: Linux's binary, else the npm package.
fn download() -> R<(Forma, String)> {
let linux = LINUX.iter().find(|(arch, _)| cfg!(target_os = "linux") && *arch == std::env::consts::ARCH);
let (url, bits, want, file) = match linux {
Some((arch, sum)) => (format!("https://github.com/wrong-nebula/forma/releases/download/v{VERSION}/forma-linux-{arch}-musl.tar.gz"), 256, *sum, "forma.tar.gz"),
None => {
js_runtime()?; // before downloading what nothing here could run
(format!("https://registry.npmjs.org/forma-3d/-/forma-3d-{VERSION}.tgz"), 512, NPM_SHA512, "forma-3d.tgz")
}
};
let dir = own_dir()?;
let tmp = dir.with_file_name("forma.download");
let _ = std::fs::remove_dir_all(&tmp);
let unpacked = tmp.join("unpacked");
std::fs::create_dir_all(&unpacked).map_err(|e| format!("{}: {e}", unpacked.display()))?;
let got = tmp.join(file);
run(Command::new("curl").args(["-fL", "--retry", "3", "-o"]).arg(&got).arg(&url), "downloading forma")?;
if digest(&got, bits)? != want {
return Err(format!("{url} doesn't match its pinned sha{bits}; nothing installed (it's in {})", tmp.display()));
}
run(Command::new("tar").arg("-xzf").arg(&got).arg("-C").arg(&unpacked), "unpacking forma")?;
let _ = std::fs::remove_dir_all(&dir);
std::fs::rename(&unpacked, &dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let _ = std::fs::remove_dir_all(&tmp);
let what = if linux.is_some() { "its Linux binary from github.com/wrong-nebula/forma" } else { "its npm package forma-3d" };
let f = find()?.filter(|(_, from)| *from == "raea's download").ok_or_else(|| format!("{url} held no forma"))?.0;
Ok((f, format!("downloaded forma {VERSION}, {what}")))
}
/// `raea setup forma [--check] [--download]`.
pub fn setup(args: &[String]) -> R<String> {
let check = args.iter().any(|a| a == "--check");
let fresh = args.iter().any(|a| a == "--download");
let (f, from) = match find()?.filter(|_| !fresh) {
Some((f, from)) => (f, from.to_string()),
None if check => return Ok(format!("CHECKED no forma found (raea.forma, {}, PATH): raea setup forma downloads forma {VERSION}", own_dir()?.display())),
None => download()?,
};
let v = version(&f)?;
let pinned = if v.contains(VERSION) { String::new() } else { format!(" (raea is tested with {VERSION}: raea setup forma --download fetches it)") };
let head = if check { "CHECKED " } else { "APPLIED " };
Ok(format!("{head} {v} ({from}){pinned}\n {}\n make: raea forma SCRIPT.forma -o OUT.glb; its language: raea forma spec; agents: the `forma` MCP server (raea skills install adds it)\n forma is GPL-3.0-or-later and runs as its own program; what it makes is yours", f.path().display()))
}
/// `raea forma`'s arguments, read.
#[derive(Debug, Default, PartialEq)]
pub struct Make {
pub script: String,
pub out: String,
pub unit: Option<String>,
pub render: Option<String>,
pub draw: Option<String>,
pub size: Option<String>,
pub smooth: Option<f32>,
pub strict: bool,
}
/// Reads `raea forma SCRIPT -o OUT ...` (args without the verb).
pub fn parse(args: &[String]) -> R<Make> {
let mut m = Make { smooth: Some(SMOOTH), strict: true, ..Default::default() };
let mut it = args.iter();
while let Some(a) = it.next() {
let mut val = |flag: &str| it.next().cloned().ok_or_else(|| format!("{flag} takes a value: {USAGE}"));
match a.as_str() {
"-o" | "--out" => m.out = val(a)?,
"--unit" => m.unit = Some(val(a)?),
"--render" => m.render = Some(val(a)?),
"--draw" => m.draw = Some(val(a)?),
"--size" => m.size = Some(val(a)?),
"--smooth" => m.smooth = Some(val(a)?.parse().map_err(|_| "--smooth takes degrees, 40 say".to_string())?),
"--flat" => m.smooth = None,
"--no-strict" => m.strict = false,
f if f.starts_with('-') && f != "-" => return Err(format!("raea forma has no {f}: {USAGE}")),
s if m.script.is_empty() => m.script = s.to_string(),
s => return Err(format!("one script at a time ({} and {s})", m.script)),
}
}
if m.script.is_empty() || m.out.is_empty() {
return Err(format!("usage: {USAGE}"));
}
Ok(m)
}
/// forma's own arguments for a make: always one node per named part in a .glb.
pub fn forma_args(m: &Make) -> Vec<String> {
let mut a: Vec<String> = vec!["eval".into(), if m.strict { "--strict" } else { "--no-strict" }.into()];
if m.out.to_lowercase().ends_with(".glb") {
a.push("--scene".into());
}
a.extend(["--out".into(), m.out.clone()]);
for (flag, v) in [("--unit", &m.unit), ("--render", &m.render), ("--size", &m.size), ("--draw", &m.draw)] {
if let Some(v) = v {
a.extend([flag.to_string(), v.clone()]);
}
}
a.push(m.script.clone());
a
}
/// `raea forma fix FILE.glb... [--smooth DEG] [--flat]` (args after `fix`): needs no forma, only its files.
pub fn fix(args: &[String]) -> R<String> {
let mut smooth = Some(SMOOTH);
let mut files = Vec::new();
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--smooth" => smooth = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--smooth takes degrees, 40 say")?),
"--flat" => smooth = None,
f if f.starts_with('-') => return Err(format!("raea forma fix has no {f}: {USAGE}")),
f if f.to_lowercase().ends_with(".glb") => files.push(f),
f => return Err(format!("{f} isn't a .glb: forma's .stl, .obj, .3mf and .step carry no colours to fix")),
}
}
if files.is_empty() {
return Err(format!("which .glb: {USAGE}"));
}
let mut out = Vec::new();
for f in files {
let fixed = glb::fix_file(Path::new(f), smooth)?;
out.push(if fixed.already { format!("CHECKED {f}: fixed before, left alone") } else { format!("APPLIED {f}: {} colours made linear, {} meshes' normals smoothed", fixed.colours, fixed.primitives) });
}
Ok(out.join("\n"))
}
/// `raea forma ...` (args with the verb): `spec` passes through to forma; a make runs forma, then fixes the .glb.
pub fn forma(args: &[String]) -> R<String> {
if args.get(1).map(String::as_str) == Some("fix") {
return fix(&args[2..]);
}
let (f, _) = find()?.ok_or("no forma: raea setup forma finds or downloads it")?;
if args.get(1).map(String::as_str) == Some("spec") {
return run(f.command().arg("spec").args(&args[2..]), "forma spec");
}
let m = parse(&args[1..])?;
if m.script != "-" && !Path::new(&m.script).is_file() {
return Err(format!("no script {}", m.script));
}
let o = f.command().args(forma_args(&m)).stdin(Stdio::inherit()).output().map_err(|e| format!("{}: {e}", f.path().display()))?;
let (out, err) = (String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
if !o.status.success() {
let why = if o.status.code() == Some(3) { " (not watertight: --no-strict writes it anyway)" } else { "" };
return Err(format!("forma refused {}{why}: {}{}", m.script, err.trim(), if out.trim().is_empty() { String::new() } else { format!("\n{}", out.trim()) }));
}
let mut report = out.trim_end().to_string();
if m.out.to_lowercase().ends_with(".glb") {
let fixed = glb::fix_file(Path::new(&m.out), m.smooth)?;
let normals = match m.smooth {
Some(d) => format!("{} meshes' normals smoothed under {d}°", fixed.primitives),
None => "normals flat as forma wrote them".into(),
};
report += &format!("\nAPPLIED {}: {} colours made linear, {normals}", m.out, fixed.colours);
} else {
report += &format!("\nAPPLIED {}", m.out);
}
Ok(report)
}
/// The verbs here, or None for any other: `setup forma` and `forma ...`.
pub fn cli(args: &[String]) -> Option<R<String>> {
match (args.first()?.as_str(), args.get(1).map(String::as_str)) {
("setup", Some("forma")) => Some(setup(&args[2..])),
("forma", _) => Some(forma(args)),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn args(s: &str) -> Vec<String> {
s.split_whitespace().map(str::to_string).collect()
}
#[test]
fn a_make_reads_its_flags_and_passes_forma_its_own() {
let m = parse(&args("bolt.forma -o bolt.glb --unit mm --render b.png --smooth 30")).unwrap();
assert_eq!((m.smooth, m.strict, m.unit.as_deref()), (Some(30.0), true, Some("mm")));
assert_eq!(forma_args(&m).join(" "), "eval --strict --scene --out bolt.glb --unit mm --render b.png bolt.forma");
let flat = parse(&args("p.forma -o p.stl --flat --no-strict")).unwrap();
assert_eq!((flat.smooth, flat.strict), (None, false));
assert_eq!(forma_args(&flat).join(" "), "eval --no-strict --out p.stl p.forma");
assert_eq!(parse(&args("p.forma -o p.glb")).unwrap().smooth, Some(SMOOTH));
}
#[test]
fn a_make_refuses_what_it_cant_read() {
assert!(parse(&args("p.forma")).unwrap_err().starts_with("usage:"));
assert!(parse(&args("p.forma -o p.glb --bogus")).unwrap_err().contains("no --bogus"));
assert!(parse(&args("a.forma b.forma -o p.glb")).unwrap_err().contains("one script"));
assert!(parse(&args("p.forma -o p.glb --smooth soft")).is_err());
assert!(parse(&args("p.forma -o")).unwrap_err().contains("takes a value"));
}
#[test]
fn every_flag_is_in_the_usage() {
for f in ["--check", "--download", "--unit", "--render", "--draw", "--size", "--smooth", "--flat", "--no-strict", "--topic", "--gbnf"] {
assert!(USAGE.contains(&format!("[{f}")), "{f}");
}
assert!(cli(&args("setup blender")).is_none() && cli(&args("render x.tsx")).is_none() && cli(&[]).is_none());
}
#[test]
fn digests_of_a_known_file() {
let f = std::env::temp_dir().join(format!("raea-forma-digest-{}", std::process::id()));
std::fs::write(&f, b"abc").unwrap();
let (a, b) = (digest(&f, 256), digest(&f, 512));
let _ = std::fs::remove_file(&f);
assert_eq!(a.unwrap(), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
assert!(b.unwrap().starts_with("ddaf35a193617aba"));
}
#[test]
fn fix_takes_only_glb_files() {
assert!(fix(&args("part.stl")).unwrap_err().contains("isn't a .glb"));
assert!(fix(&args("--flat")).unwrap_err().starts_with("which .glb"));
assert!(fix(&args("a.glb --soft")).unwrap_err().contains("no --soft"));
let d = std::env::temp_dir().join(format!("raea-forma-fix-{}.glb", std::process::id()));
std::fs::write(&d, glb::write(&serde_json::json!({"asset": {"version": "2.0"}, "materials": [{"pbrMetallicRoughness": {"baseColorFactor": [0.5, 0.5, 0.5, 1.0]}}]}), &[])).unwrap();
let p = d.to_string_lossy().to_string();
let (first, again) = (fix(std::slice::from_ref(&p)), fix(&[p]));
let _ = std::fs::remove_file(&d);
assert!(first.unwrap().contains("1 colours made linear") && again.unwrap().contains("fixed before"));
}
#[test]
fn a_path_names_its_kind() {
assert_eq!(at(PathBuf::from("/x/forma")).unwrap(), Forma::Native(PathBuf::from("/x/forma")));
}
}
+1 -1
View File
@@ -142,7 +142,7 @@ fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
let what = match job.make.kind { let what = match job.make.kind {
goal::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1", goal::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
goal::Kind::Shot => "raea make framing --out review/r1", goal::Kind::Shot => "raea make framing --out review/r1",
goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules | goal::Kind::Playable => "raea render EDIT.tsx --review review/r1", goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules => "raea render EDIT.tsx --review review/r1",
}; };
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))]; return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
}; };
+3 -3
View File
@@ -3,7 +3,7 @@
use std::path::PathBuf; use std::path::PathBuf;
use image::{Rgba, RgbaImage}; use image::{Rgba, RgbaImage};
use raea_core_brief::{goal::Goal as Make, read}; use raea_core_brief::{make::Make, read};
use crate::sheet::{Tile, sheet}; use crate::sheet::{Tile, sheet};
@@ -148,7 +148,7 @@ fn a_shot_frames_its_start_middle_and_end() {
// a shot with no composition can't be framed, and says what's needed // a shot with no composition can't be framed, and says what's needed
let d = dir("framing"); let d = dir("framing");
assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition")); assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition"));
assert!(raea_core_brief::goal::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition"))); assert!(raea_core_brief::make::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
} }
// MK18: the floor plan draws every placed footprint (invented ones dashed); the blockout boxes them from the entrance // MK18: the floor plan draws every placed footprint (invented ones dashed); the blockout boxes them from the entrance
@@ -193,7 +193,7 @@ fn a_quote_reads_as_one_line() {
#[test] #[test]
fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() { fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() {
use raea_core_brief::goal::Object; use raea_core_brief::make::Object;
let stapler: Object = serde_json::from_value(serde_json::json!({"id": "stapler", "label": "Stapler", "dims": [0.05, 0.17, 0.07]})).unwrap(); let stapler: Object = serde_json::from_value(serde_json::json!({"id": "stapler", "label": "Stapler", "dims": [0.05, 0.17, 0.07]})).unwrap();
// long across (x) where the plan's is front to back (z): a quarter turn // long across (x) where the plan's is front to back (z): a quarter turn
assert_eq!(crate::kit::fit_args(&stapler, Some([1.9, 0.72, 0.58])), ["--dims", "0.05,0.17,0.07", "--h", "0.07", "--turn", "90"]); assert_eq!(crate::kit::fit_args(&stapler, Some([1.9, 0.72, 0.58])), ["--dims", "0.05,0.17,0.07", "--h", "0.07", "--turn", "90"]);
+4 -26
View File
@@ -40,29 +40,6 @@ pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()})) Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
} }
/// `f(0..n)`, up to four at a time, in order: a sheet's frames are each a seek and a decode of their own (16 of a 4K
/// interview: 7 s one after another, 4 s so).
fn at_once<T: Send>(n: usize, f: impl Fn(usize) -> R<T> + Sync) -> R<Vec<T>> {
use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}};
let workers = std::thread::available_parallelism().map_or(2, |c| c.get()).clamp(1, 4).min(n.max(1));
let next = AtomicUsize::new(0);
let out: Vec<Mutex<Option<R<T>>>> = (0..n).map(|_| Mutex::new(None)).collect();
std::thread::scope(|s| {
for _ in 0..workers {
s.spawn(|| {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= n {
break;
}
*out[i].lock().unwrap() = Some(f(i));
}
});
}
});
out.into_iter().map(|m| m.into_inner().unwrap().unwrap_or_else(|| Err("a frame wasn't read".into()))).collect()
}
pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> { pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
if files.is_empty() { if files.is_empty() {
return Err("raea media sheet FILE... -o OUT: which files?".into()); return Err("raea media sheet FILE... -o OUT: which files?".into());
@@ -70,9 +47,10 @@ pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
let mut tiles = Vec::new(); let mut tiles = Vec::new();
if files.len() == 1 { if files.len() == 1 {
let p = probe_of(&files[0])?; let p = probe_of(&files[0])?;
let at: Vec<f64> = (0..n.max(1)).map(|i| (i as f64 + 0.5) / n.max(1) as f64 * p.duration).collect(); for i in 0..n.max(1) {
let read = at_once(at.len(), |i| frame(&files[0], at[i]))?; let t = (i as f64 + 0.5) / n.max(1) as f64 * p.duration;
tiles.extend(at.into_iter().zip(read)); tiles.push((t, frame(&files[0], t)?));
}
} else { } else {
for f in files { for f in files {
let p = probe_of(f)?; let p = probe_of(f)?;
+63 -70
View File
@@ -1,7 +1,6 @@
//! `media probe`: what a file is (duration, size, fps, codec, audio), with the MP4 boxes read directly for a track's own timing. //! `media probe`: what a file is (duration, size, fps, codec, audio), with the MP4 boxes read directly for a track's own timing.
use super::*; use super::*;
use raea_io_media::mp4box::{be32, be64, boxes, child, moov_of};
pub(crate) fn round3(x: f64) -> f64 { pub(crate) fn round3(x: f64) -> f64 {
(x * 1000.0).round() / 1000.0 (x * 1000.0).round() / 1000.0
@@ -39,11 +38,7 @@ pub fn probe_of(path: &Path) -> R<Probe> {
} }
i i
}); });
// what the file states, when it does; else the track decoded (WAV, MP3, a container read no other way) let audio = soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration()));
let audio = match audio_track(path) {
Some(a) => Some(a),
None => soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration())),
};
if video.is_none() && audio.is_none() { if video.is_none() && audio.is_none() {
// what each backend said about the picture: a missing FFmpeg, a codec none of them reads // what each backend said about the picture: a missing FFmpeg, a codec none of them reads
let why = why.map(|w| format!(" ({})", w.split_once(": no backend reads it (").map_or(w.as_str(), |(_, r)| r.trim_end_matches(')')).to_string())).unwrap_or_default(); let why = why.map(|w| format!(" ({})", w.split_once(": no backend reads it (").map_or(w.as_str(), |(_, r)| r.trim_end_matches(')')).to_string())).unwrap_or_default();
@@ -129,37 +124,74 @@ impl Track {
} }
} }
/// The first sound track as the file states it (rate, channels, seconds), for MP4 and QuickTime files: `media probe` /// The boxes inside `b` (a box's payload): (type, payload).
/// decoded the whole track to learn these, which read every byte of a 1 GB interview (two minutes on a network disk). pub(crate) fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
pub fn audio_track(path: &Path) -> Option<(u32, usize, f64)> { let mut out = Vec::new();
audio_in(&moov_of(path)?) let mut i = 0usize;
while i + 8 <= b.len() {
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
let mut hdr = 8;
if size == 1 && i + 16 <= b.len() {
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
hdr = 16;
} else if size == 0 {
size = b.len() - i;
}
if size < hdr || i + size > b.len() {
break;
}
out.push((kind, &b[i + hdr..i + size]));
i += size;
}
out
} }
pub(crate) fn audio_in(moov: &[u8]) -> Option<(u32, usize, f64)> { pub(crate) fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
for (k, trak) in boxes(moov) { boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
if &k != b"trak" { }
continue;
} pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
let Some(mdia) = child(trak, b"mdia") else { continue }; Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"soun"[..]) { }
continue;
} pub(crate) fn be64(b: &[u8], at: usize) -> Option<u64> {
let mdhd = child(mdia, b"mdhd")?; Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
let (scale, dur) = if mdhd.first() == Some(&1) { (be32(mdhd, 20)? as f64, be64(mdhd, 24)? as f64) } else { (be32(mdhd, 12)? as f64, be32(mdhd, 16)? as f64) };
// the first sample description: version at 24, channels at 32, rate (16.16) at 40; QuickTime's version 2 states
// them again as a double at 48 and a count at 56
let stsd = child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?;
let v2 = stsd.get(24..26) == Some(&[0u8, 2][..]);
let rate = if v2 { f64::from_bits(be64(stsd, 48)?) } else { be32(stsd, 40)? as f64 / 65536.0 };
let channels = if v2 { be32(stsd, 56)? as usize } else { u16::from_be_bytes(stsd.get(32..34)?.try_into().ok()?) as usize };
return (scale > 0.0 && dur > 0.0 && rate >= 1.0 && (1..=64).contains(&channels)).then_some((rate.round() as u32, channels, dur / scale));
}
None
} }
/// The first video track's timing, for MP4 and QuickTime files. /// The first video track's timing, for MP4 and QuickTime files.
pub fn video_track(path: &Path) -> Option<Track> { pub fn video_track(path: &Path) -> Option<Track> {
let moov = moov_of(path)?; use std::io::{Read, Seek, SeekFrom};
let mut f = std::fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
// the top-level boxes, to moov (read alone: mdat can be gigabytes)
let mut at = 0u64;
let moov = loop {
if at + 8 > len {
return None;
}
let mut h = [0u8; 16];
f.seek(SeekFrom::Start(at)).ok()?;
f.read_exact(&mut h[..8]).ok()?;
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
let mut hdr = 8u64;
if size == 1 {
f.read_exact(&mut h[8..]).ok()?;
size = u64::from_be_bytes(h[8..].try_into().ok()?);
hdr = 16;
} else if size == 0 {
size = len - at;
}
if size < hdr {
return None;
}
if &h[4..8] == b"moov" {
let mut m = vec![0u8; (size - hdr).min(256 << 20) as usize];
f.read_exact(&mut m).ok()?;
break m;
}
at += size;
};
for (k, trak) in boxes(&moov) { for (k, trak) in boxes(&moov) {
if &k != b"trak" { if &k != b"trak" {
continue; continue;
@@ -263,42 +295,3 @@ pub(crate) fn rate_fraction(fps: f64) -> String {
} }
// ---- pictures // ---- pictures
#[cfg(test)]
mod tests {
use super::*;
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
v.extend_from_slice(kind);
v.extend_from_slice(body);
v
}
#[test]
fn a_sound_track_is_read_from_the_file_s_own_tables() {
// mdhd v0: 48 kHz timescale, 10 s; stsd: one mp4a entry, 2 channels, 48000 Hz
let mut mdhd = vec![0u8; 24];
mdhd[12..16].copy_from_slice(&48000u32.to_be_bytes());
mdhd[16..20].copy_from_slice(&480000u32.to_be_bytes());
let mut hdlr = vec![0u8; 24];
hdlr[8..12].copy_from_slice(b"soun");
let mut stsd = vec![0u8; 44];
stsd[7] = 1;
stsd[12..16].copy_from_slice(b"mp4a");
stsd[32..34].copy_from_slice(&2u16.to_be_bytes());
stsd[40..44].copy_from_slice(&(48000u32 << 16).to_be_bytes());
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd)))].concat();
// a picture track ahead of it is passed over
let mut vh = vec![0u8; 24];
vh[8..12].copy_from_slice(b"vide");
let moov = [bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh))), bx(b"trak", &bx(b"mdia", &mdia))].concat();
assert_eq!(audio_in(&moov), Some((48000, 2, 10.0)));
// no sound track, or one that states no rate: nothing (the track is decoded instead)
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh)))), None);
let mut silent = stsd.clone();
silent[40..44].copy_from_slice(&0u32.to_be_bytes());
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &silent)))].concat();
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &mdia))), None);
}
}
-5
View File
@@ -14,9 +14,4 @@ raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-io-home = { path = "../../io/home" } raea-io-home = { path = "../../io/home" }
regex = "1" regex = "1"
serde_json = "1" serde_json = "1"
# the faces the native page draws with (core/fonts), inlined in the page under the families the game names (PA8)
raea-core-fonts = { path = "../../core/fonts" }
# a game's generated sounds made at export, as a render makes them, and FFmpeg to compress them (PA6)
raea-io-assets = { path = "../../io/assets" }
base64 = "0.22"
zip = { version = "9", default-features = false, features = ["deflate-flate2"] } zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
-127
View File
@@ -1,127 +0,0 @@
//! The page's fonts as the native render draws them (docs/playables.feature PA8). A composition's page draws with
//! raea's bundled faces (core/fonts: Fontsource latin subsets, a few weights a family), each family the page names
//! aliased onto one (Helvetica, Arial and SF Pro draw as Inter, Times as EB Garamond, ...) and each weight drawn by the
//! nearest face (core/fonts `face`). A phone has none of them, so brick-rush's Inter fell back to a serif. The export
//! inlines, for every family the game's script names that raea aliases, its faces as @font-face data URLs under that
//! name, each face's weight a range that makes the browser's choice the native one (Inter 400/700/900: 1-550, 551-800,
//! 801-1000; a weight halfway between two faces takes the lighter, as `face`'s first-found minimum does). The page's
//! own default family is Inter, the native page's.
use base64::Engine;
use std::collections::BTreeMap;
/// The family a page with no family of its own draws in
const DEFAULT: &str = "Inter";
/// Each family name the script writes (fontFamily values and CSS font-family declarations), as written, with the
/// bundled family raea draws it as; the default first
pub fn families(script: &str) -> Vec<(String, &'static str)> {
let mut out: Vec<(String, &'static str)> = vec![(DEFAULT.into(), "inter")];
let res = [
r#"fontFamily["']?\s*:\s*["'`]([^"'`]+)["'`]"#,
r#"font-family\s*:\s*([^;"'`}]+)"#,
];
for re in res {
let re = regex::Regex::new(re).expect("a valid pattern");
for cap in re.captures_iter(script) {
for name in cap[1].split(',') {
let name = name.trim().trim_matches(|c| c == '"' || c == '\'').trim();
if let Some(c) = raea_core_fonts::canonical(name) {
if !out.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) {
out.push((name.to_string(), c));
}
}
}
}
}
out
}
/// A bundled family's faces as (weight range, style, woff2): each style's weights split halfway between neighbours,
/// the halfway weight to the lighter face
pub fn faces(canonical: &str) -> Vec<((u16, u16), &'static str, &'static [u8])> {
let mut by_style: BTreeMap<&str, Vec<(u16, &'static [u8])>> = BTreeMap::new();
for (f, w, st, bytes) in raea_core_fonts::BUNDLED {
if *f == canonical {
by_style
.entry(st)
.or_default()
.push((w.parse().unwrap_or(400), bytes));
}
}
let mut out = Vec::new();
for (st, mut ws) in by_style {
ws.sort_by_key(|(w, _)| *w);
let mut lo = 1u16;
for (i, (w, bytes)) in ws.iter().enumerate() {
let hi = ws.get(i + 1).map_or(1000, |(next, _)| (w + next) / 2);
out.push(((lo, hi), st, *bytes));
lo = hi + 1;
}
}
out
}
/// The page's <style>: each family the script names that raea aliases, its faces inlined under that name, and the
/// page's default family
pub fn style(script: &str) -> String {
let b64 = base64::engine::general_purpose::STANDARD;
let mut css = String::from("<style>\n");
for (name, canonical) in families(script) {
for ((lo, hi), st, bytes) in faces(canonical) {
css.push_str(&format!(
"@font-face{{font-family:\"{}\";font-style:{st};font-weight:{lo} {hi};src:url(data:font/woff2;base64,{}) format(\"woff2\")}}\n",
name.replace('"', ""),
b64.encode(bytes)
));
}
}
css.push_str(&format!("html,body{{font-family:\"{DEFAULT}\"}}\n</style>"));
css
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_family_the_game_names_is_aliased_as_the_native_page_does() {
let script = r#"h("div",{style:{fontFamily:"Inter, system-ui, sans-serif",fontWeight:900}});x={fontFamily:'Helvetica Neue'};y="b{font-family: Georgia, serif;}""#;
let f = families(script);
assert_eq!(
f,
[
("Inter".to_string(), "inter"),
("Helvetica Neue".into(), "inter"),
("Georgia".into(), "eb-garamond")
]
);
}
#[test]
fn a_weight_takes_the_face_the_native_page_takes() {
let r: Vec<(u16, u16)> = faces("inter").iter().map(|(r, _, _)| *r).collect();
assert_eq!(r, [(1, 550), (551, 800), (801, 1000)]);
// the native pick for each weight is the face whose range holds it
for w in [100u16, 400, 550, 551, 700, 800, 801, 900] {
let native = raea_core_fonts::face("Inter", w, false).unwrap();
let ours = faces("inter")
.into_iter()
.find(|((lo, hi), _, _)| (*lo..=*hi).contains(&w))
.unwrap()
.2;
assert!(native == ours, "weight {w}");
}
}
#[test]
fn the_style_holds_inter_and_sets_the_default() {
let css = style("var x=1;");
assert_eq!(css.matches("@font-face").count(), 3);
assert!(
css.contains("font-weight:801 1000")
&& css.contains("html,body{font-family:\"Inter\"}")
);
assert!(css.len() < 110_000, "{} bytes", css.len());
}
}
+18 -170
View File
@@ -1,19 +1,15 @@
//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX //! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX
//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with //! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried //! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
//! in the script; three.js only when the lint found a 3D kind, PA15; a sound player only for a game with sound, Tone.js //! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
//! only for a raea/tone graph, and its generated sounds made and carried in the page, PA6), and written as each
//! network's page or ZIP (pages.rs), each checked against its cap.
mod fonts;
mod lint; mod lint;
mod pages; mod pages;
mod sound;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
type R<T> = Result<T, String>; type R<T> = Result<T, String>;
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--name NAME] [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]"; pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad"; pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad";
/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own /// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own
@@ -23,13 +19,12 @@ fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str) args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
} }
/// The folder whose node_modules holds a package the page carries (three.js to draw 3D, Tone.js to play a raea/tone /// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add [email protected]`),
/// graph): the project's own (`raea add [email protected]`), else the copy beside sdk/playable or sdk/r3f in raea's own files /// else the copy beside sdk/playable or sdk/r3f in raea's own files
fn package_dir(game: &Path, home: &Path, name: &str, why: &str, add: &str) -> R<PathBuf> { fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
let has = |d: &Path| d.join("node_modules").join(name).join("package.json").is_file();
let mut d = game.parent(); let mut d = game.parent();
while let Some(dir) = d { while let Some(dir) = d {
if has(dir) { if dir.join("node_modules/three/package.json").is_file() {
return Ok(dir.to_path_buf()); return Ok(dir.to_path_buf());
} }
d = dir.parent(); d = dir.parent();
@@ -37,80 +32,21 @@ fn package_dir(game: &Path, home: &Path, name: &str, why: &str, add: &str) -> R<
["sdk/playable", "sdk/r3f"] ["sdk/playable", "sdk/r3f"]
.iter() .iter()
.map(|p| home.join(p)) .map(|p| home.join(p))
.find(|d| has(d)) .find(|d| d.join("node_modules/three/package.json").is_file())
.ok_or_else(|| format!("a playable {why} with {name}, which this project doesn't have: `raea add {add}` in it")) .ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add [email protected]` in it".into())
}
/// runtime/ecs as wasm (sdk/playable/ecs/build.sh), base64
fn ecs_wasm(home: &Path) -> R<String> {
use base64::Engine;
let f = home.join("sdk/playable/src/host/ecs.wasm");
let b = std::fs::read(&f).map_err(|e| format!("{}: raea/ecs's world as wasm isn't there ({e}): bash sdk/playable/ecs/build.sh", f.display()))?;
Ok(base64::engine::general_purpose::STANDARD.encode(b))
}
/// What sound a game makes, as the lint found it: none, media only (<Audio>, generated sounds) or a raea/tone graph
#[derive(Clone, Copy, PartialEq, Debug)]
enum Sounds {
None,
Media,
Tone,
}
/// What a page carries beside the game and the host, as the lint found the game needs it
#[derive(Clone, Copy, PartialEq, Debug)]
struct Carry {
/// a 3D drawer (Bevy's programs, its scene read by three.js), for a game with a 3D kind (PA11, PA15)
with_3d: bool,
sounds: Sounds,
/// Bevy's world as wasm, for a game that makes a raea/ecs World (PA12)
ecs: bool,
}
/// The bundle's entry: Bevy's world first for a game on raea/ecs (PA12: a World made as the game's module loads is
/// already Bevy's), the game, then the host started with Bevy's PBR programs as its 3D drawer (PA11) only for a game
/// with 3D (PA15: a 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
/// raea/tone graph (PA6)
fn entry(game: &Path, host: &Path, carry: Carry) -> String {
let Carry { with_3d, sounds, ecs } = carry;
let first = if ecs { format!("import {:?};\n", spec(&host.join("ecs.ts"))) } else { String::new() };
let mut e = format!("{first}import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
if with_3d {
e.push_str(&format!("import {{ bevy3d }} from {:?};\n", spec(&host.join("bevy.ts"))));
}
if sounds != Sounds::None {
e.push_str(&format!("import {{ sound }} from {:?};\n", spec(&host.join("sound.ts"))));
}
if sounds == Sounds::Tone {
e.push_str(&format!("import {{ tone }} from {:?};\n", spec(&host.join("tone.ts"))));
}
let d3 = if with_3d { "bevy3d" } else { "undefined" };
e.push_str(&match sounds {
Sounds::None if with_3d => "start(bevy3d);\n".into(),
Sounds::None => "start();\n".into(),
Sounds::Media => format!("start({d3}, sound());\n"),
Sounds::Tone => format!("start({d3}, sound(tone));\n"),
});
e
} }
/// The game and the host in one minified script that carries its files /// The game and the host in one minified script that carries its files
fn bundle(game: &Path, home: &Path, carry: Carry) -> R<String> { fn bundle(game: &Path, home: &Path) -> R<String> {
let Carry { with_3d, sounds, .. } = carry; let host = home.join("sdk/playable/src/host/main.tsx");
let host = home.join("sdk/playable/src/host"); if !host.is_file() {
if !host.join("main.tsx").is_file() {
return Err(format!("{}: raea's playable host isn't there", host.display())); return Err(format!("{}: raea's playable host isn't there", host.display()));
} }
let three = three_dir(game, home)?;
let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id())); let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
let mut flags = vec!["--minify".to_string(), "1".into(), "--inline".into(), "1".into()]; let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
if with_3d { let alias = format!("three/={}", three.display());
flags.extend(["--alias".into(), format!("three/={}", package_dir(game, home, "three", "draws its 3D", "[email protected]")?.display())]); let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
}
if sounds == Sounds::Tone {
flags.extend(["--alias".into(), format!("tone/={}", package_dir(game, home, "tone", "plays raea/tone", "[email protected]")?.display())]);
}
let flags: Vec<&str> = flags.iter().map(String::as_str).collect();
let r = raea_runtime_bundle::bundle_entry(&entry(game, &host, carry), &out, &flags);
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string())); let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
let _ = std::fs::remove_file(&out); let _ = std::fs::remove_file(&out);
js js
@@ -130,12 +66,7 @@ pub fn cli(args: &[String]) -> R<String> {
} }
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string(); let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string(); let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
// the files' name: the brief's (`playable({ playable: { name } })`), else the game's file name let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
let stem = game.file_stem().map(|s| s.to_string_lossy().into_owned());
let name = flag(args, "--name").map(str::to_string).or(stem).unwrap_or_else(|| "playable".into());
if name.is_empty() || name.contains(['/', '\\']) {
return Err(format!("--name {name:?}: a file name, no folders"));
}
let mut report = Vec::new(); let mut report = Vec::new();
let found = lint::lint(&game)?; let found = lint::lint(&game)?;
@@ -152,45 +83,16 @@ pub fn cli(args: &[String]) -> R<String> {
return Err(why.join("\n")); return Err(why.join("\n"));
} }
let is = |k: &str| found.sound[k].as_bool() == Some(true); let js = bundle(&game, &raea_io_home::home())?;
let sounds = if is("tone") { Sounds::Tone } else if is("media") { Sounds::Media } else { Sounds::None };
let carry = Carry { with_3d: !found.kinds.is_empty(), sounds, ecs: found.ecs };
let home = raea_io_home::home();
let js = bundle(&game, &home, carry)?;
// its generated sounds, made (or found made) beside the game and carried in the page (PA6)
let assets = found.sound["assets"].as_array().cloned().unwrap_or_default();
let made = sound::make(&game, &assets)?;
report.push(match sounds {
Sounds::None => "sound: none".into(),
_ => format!("sound: {}{} generated ({} KB), played after the first touch", if sounds == Sounds::Tone { "a raea/tone graph, " } else { "" }, made.count, made.bytes / 1024),
});
// Bevy's world, for a game on raea/ecs (PA12): the wasm the host loads before the game
let ecs = if found.ecs { ecs_wasm(&home)? } else { String::new() };
report.push(if found.ecs { format!("ecs: Bevy's world as wasm ({} KB)", ecs.len() * 3 / 4 / 1024) } else { "ecs: none".into() });
let ecs = if ecs.is_empty() { ecs } else { format!("globalThis.__raeaEcsWasm={ecs:?};") };
let js = format!("{ecs}{}{js}", made.script);
// the faces the native page draws with, for the families the game names (PA8)
let style = fonts::style(&js);
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?; std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut over = false; let mut over = false;
let mut written = Vec::new();
for net in networks { for net in networks {
let script = format!("{}\n{js}", pages::preamble(net, &store, &card)); let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
let w = pages::write(net, &name, &script, &out, orientation, &style)?; let w = pages::write(net, &name, &script, &out, orientation)?;
let ok = w.bytes <= pages::CAP; let ok = w.bytes <= pages::CAP;
over |= !ok; over |= !ok;
report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" })); report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" }));
written.push(w);
} }
// what was written, for raea goal's playable pack (sdk/goal packs/playable.ts) and raea cloud's review
let manifest = serde_json::json!({
"name": name, "game": game.display().to_string(), "orientation": orientation, "kinds": found.kinds,
"compositions": found.comps.iter().map(|c| serde_json::json!({"id": c.id, "width": c.width, "height": c.height, "fps": c.fps, "frames": c.frames})).collect::<Vec<_>>(),
"pages": written.iter().map(|w| serde_json::json!({"network": w.network, "file": w.file.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default(), "bytes": w.bytes})).collect::<Vec<_>>(),
"cap": pages::CAP,
});
let mf = out.join(format!("{name}.playable.json"));
std::fs::write(&mf, serde_json::to_string_pretty(&manifest).unwrap_or_default()).map_err(|e| format!("{}: {e}", mf.display()))?;
if over { if over {
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024)); report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
return Err(report.join("\n")); return Err(report.join("\n"));
@@ -198,57 +100,3 @@ pub fn cli(args: &[String]) -> R<String> {
report.push(format!("APPLIED {name} exported as a playable to {}", out.display())); report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
Ok(report.join("\n")) Ok(report.join("\n"))
} }
#[cfg(test)]
mod tests {
use super::{Carry, Sounds, entry};
use std::path::Path;
fn e(with_3d: bool, sounds: Sounds, ecs: bool) -> String {
entry(Path::new("/g/game.tsx"), Path::new("/h/host"), Carry { with_3d, sounds, ecs })
}
#[test]
fn a_2d_game_starts_with_no_drawer() {
let e = e(false, Sounds::None, false);
assert!(e.contains("start();") && !e.contains("three") && !e.contains("sound") && !e.contains("ecs"), "{e}");
}
#[test]
fn a_3d_game_starts_with_three() {
let e = e(true, Sounds::None, false);
assert!(e.contains("bevy3d } from \"/h/host/bevy.ts\"") && e.contains("start(bevy3d);"), "{e}");
}
#[test]
fn a_game_with_sound_starts_with_its_player_and_tone_only_for_a_graph() {
let media = e(false, Sounds::Media, false);
assert!(media.contains("start(undefined, sound());") && !media.contains("tone"), "{media}");
let tone = e(true, Sounds::Tone, false);
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(bevy3d, sound(tone));"), "{tone}");
}
#[test]
fn a_game_on_raea_ecs_loads_bevys_world_before_the_game() {
let e = e(false, Sounds::None, true);
assert!(e.starts_with("import \"/h/host/ecs.ts\";\nimport \"/g/game.tsx\";"), "{e}");
}
#[test]
fn the_carried_ecs_wasm_is_built_from_runtime_ecs_as_it_is() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/ecs/from.sh")).output().expect("bash");
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/ecs.wasm.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "runtime/ecs changed since ecs.wasm was built: bash sdk/playable/ecs/build.sh");
}
#[test]
fn the_carried_bevy_programs_are_made_from_bevys_shaders_as_they_are() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/bevy/from.sh")).output().expect("bash");
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/bevy/programs.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "Bevy's shaders or tools/bevy-glsl changed since programs.ts was made: bash sdk/playable/bevy/build.sh");
}
}
+3 -7
View File
@@ -20,10 +20,6 @@ pub struct Found {
pub kinds: Vec<String>, pub kinds: Vec<String>,
pub notes: Vec<String>, pub notes: Vec<String>,
pub refusals: Vec<String>, pub refusals: Vec<String>,
/// its sound (walk.ts): `tone` (a raea/tone graph), `media` (an <Audio>) and `assets` (each generated sound to make)
pub sound: Value,
/// whether it makes a raea/ecs World (walk.ts), whose page carries Bevy's world as wasm (PA12)
pub ecs: bool,
} }
const SOURCE_RULES: &[(&str, &str)] = &[ const SOURCE_RULES: &[(&str, &str)] = &[
@@ -31,7 +27,7 @@ const SOURCE_RULES: &[(&str, &str)] = &[
(r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"), (r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
(r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"), (r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
(r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"), (r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
(r"<(Video|OffthreadVideo)\b", "<Video> plays footage through the native media stack, which a playable doesn't carry: render the clip as frames or an image sequence"), (r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
]; ];
/// The game's source and its compositions, judged /// The game's source and its compositions, judged
@@ -52,7 +48,7 @@ pub fn lint(game: &Path) -> R<Found> {
let walked = match walk(game) { let walked = match walk(game) {
Ok(w) => w, Ok(w) => w,
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't // what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals, sound: Value::Null, ecs: false }), Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
Err(e) => return Err(e), Err(e) => return Err(e),
}; };
let comps: Vec<Comp> = walked["comps"] let comps: Vec<Comp> = walked["comps"]
@@ -77,7 +73,7 @@ pub fn lint(game: &Path) -> R<Found> {
for k in strings("refused") { for k in strings("refused") {
refusals.push(format!("3D kind {k} isn't drawn in a playable")); refusals.push(format!("3D kind {k} isn't drawn in a playable"));
} }
Ok(Found { comps, kinds: strings("kinds"), notes, refusals, sound: walked["sound"].clone(), ecs: walked["ecs"].as_bool() == Some(true) }) Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
} }
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays /// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
+3 -4
View File
@@ -43,10 +43,9 @@ fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
Ok(()) Ok(())
} }
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip, its /// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
/// `style` (the fonts, fonts.rs) first in the head pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str, style: &str) -> R<Written> { let html = |head: &str, body: &str| page(name, head, body, script);
let html = |head: &str, body: &str| page(name, &format!("{style}\n{head}"), body, script);
let file = match network { let file = match network {
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650) // a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
"google" => { "google" => {
-89
View File
@@ -1,89 +0,0 @@
//! A playable's generated sounds (docs/playables.feature PA6). A game's `sao(...)` effects and TokenSynth notes are
//! made by the native renderer the first time a render meets them (runtime/sound: raea's asset store, beside the edit).
//! A playable makes no requests, so the export makes each one the game describes (sdk/playable walk.ts lists them,
//! each with its model, prompt, seed and params as the renderer passes them, so the store's cache is shared with
//! renders) and carries it in the page as a data URL under its src (`asset:sao/...`), AAC at 64 kb/s mono when FFmpeg
//! is there (a two-second effect is about 16 KB), else the file as made. The host plays it after the first touch.
use super::R;
use base64::Engine;
use serde_json::Value;
use std::path::Path;
/// The page's sounds: a script that sets `__raeaSounds` (src -> data URL), how many and their bytes
pub struct Made {
pub script: String,
pub count: usize,
pub bytes: usize,
}
/// Each generated sound the game describes, made (or found made) beside the game and inlined
pub fn make(game: &Path, assets: &[Value]) -> R<Made> {
let store = raea_io_assets::Store::beside(game);
let ffmpeg = raea_io_assets::ffmpeg_tool("ffmpeg", false).ok();
let mut out = serde_json::Map::new();
let mut bytes = 0;
for a in assets {
let (Some(src), Some(model), Some(prompt)) =
(a["src"].as_str(), a["model"].as_str(), a["prompt"].as_str())
else {
continue;
};
let seed = a["seed"].as_u64().unwrap_or(1);
let made = store
.make(model, prompt, seed, &a["params"])
.map_err(|e| format!("the sound {model} \"{prompt}\" couldn't be made: {e}"))?;
let file = store.path(&made);
let (mime, data) = match ffmpeg.as_deref().and_then(|f| aac(f, &file)) {
Some(d) => ("audio/mp4", d),
None => (
mime(&made.ext),
std::fs::read(&file).map_err(|e| format!("{}: {e}", file.display()))?,
),
};
bytes += data.len();
out.insert(
src.into(),
Value::from(format!(
"data:{mime};base64,{}",
base64::engine::general_purpose::STANDARD.encode(&data)
)),
);
}
let count = out.len();
let script = if count == 0 {
String::new()
} else {
format!("globalThis.__raeaSounds={};", Value::Object(out))
};
Ok(Made {
script,
count,
bytes,
})
}
/// The file as AAC in an MP4 (what WebKit and every other browser decode), mono at 64 kb/s
fn aac(ffmpeg: &Path, file: &Path) -> Option<Vec<u8>> {
let to = std::env::temp_dir().join(format!("raea-playable-sound-{}.m4a", std::process::id()));
let ok = std::process::Command::new(ffmpeg)
.args(["-v", "error", "-y", "-i"])
.arg(file)
.args(["-vn", "-ac", "1", "-c:a", "aac", "-b:a", "64k", "-f", "mp4"])
.arg(&to)
.status()
.is_ok_and(|s| s.success());
let data = if ok { std::fs::read(&to).ok() } else { None };
let _ = std::fs::remove_file(&to);
data
}
fn mime(ext: &str) -> &'static str {
match ext {
"mp3" => "audio/mpeg",
"ogg" => "audio/ogg",
"flac" => "audio/flac",
"m4a" | "mp4" | "aac" => "audio/mp4",
_ => "audio/wav",
}
}
-2
View File
@@ -12,8 +12,6 @@ raea-io-assets = { path = "../../io/assets" }
# generation flows: made.app, fal, Replicate, OpenRouter, Modal, ComfyUI (`raea gen`) # generation flows: made.app, fal, Replicate, OpenRouter, Modal, ComfyUI (`raea gen`)
raea-io-gen = { path = "../../io/gen" } raea-io-gen = { path = "../../io/gen" }
raea-io-home = { path = "../../io/home" } raea-io-home = { path = "../../io/home" }
# the forma version the `forma` MCP server is pinned to (agent_mcp.rs; forma itself is fetched by npx, never linked)
raea-app-forma = { path = "../forma" }
raea-io-media = { path = "../../io/media", default-features = false } raea-io-media = { path = "../../io/media", default-features = false }
serde_json = "1" serde_json = "1"
# the verbs' flags read as a render reads its own # the verbs' flags read as a render reads its own
+29 -56
View File
@@ -1,26 +1,14 @@
//! The MCP servers `raea skills install` offers an agent (docs/skills.feature SK11): `blender`, which drives a running //! The MCP servers `raea skills install` offers an agent (docs/skills.feature SK11): today `blender`, which drives a
//! Blender through the MCP for Blender add-on (`raea setup blender` installs it), and `forma`, forma's own server for //! running Blender through the MCP for Blender add-on (`raea setup blender` installs it). Each agent keeps MCP servers
//! modelling hard-surface parts in a few lines (docs/forma.feature FM6). Each agent keeps MCP servers in its own place; //! in its own place; a server already registered under the name is left as the person set it.
//! a server already registered under the name is left as the person set it.
use serde_json::{json, Value}; use serde_json::{json, Value};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
/// An MCP server raea offers: its name, the program, its arguments. /// The blender MCP server: uv runs it, so nothing is installed until an agent starts it.
pub struct Server { const NAME: &str = "blender";
pub name: &'static str, const CMD: &str = "uvx";
pub cmd: &'static str, const ARGS: [&str; 1] = ["mcp-for-blender"];
pub args: Vec<String>,
}
/// The servers raea offers. Each is fetched by its runner when an agent first starts it, so nothing is installed here:
/// blender by uv's uvx, forma (GPL-3.0-or-later, its own program) by npm's npx at the version raea is tested with.
/// Windows starts npx through cmd, as npx there is a .cmd script.
pub fn servers() -> Vec<Server> {
let forma = ["-y".to_string(), "-p".into(), format!("forma-3d@{}", raea_app_forma::VERSION), "forma-3d-mcp".into()];
let (cmd, args) = if cfg!(windows) { ("cmd", ["/c".to_string(), "npx".into()].into_iter().chain(forma).collect()) } else { ("npx", forma.to_vec()) };
vec![Server { name: "blender", cmd: "uvx", args: vec!["mcp-for-blender".into()] }, Server { name: "forma", cmd, args }]
}
type R<T> = Result<T, String>; type R<T> = Result<T, String>;
@@ -40,18 +28,18 @@ fn json_file(agent: &str) -> R<Option<PathBuf>> {
}) })
} }
/// Adds a server to a JSON config's `mcpServers` unless one of its name is there; true when it added. /// Adds `blender` to a JSON config's `mcpServers` unless one is there; true when it added.
pub fn add_json(path: &Path, sv: &Server) -> R<bool> { pub fn add_json(path: &Path) -> R<bool> {
let mut doc: Value = match std::fs::read_to_string(path) { let mut doc: Value = match std::fs::read_to_string(path) {
Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", path.display()))?, Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", path.display()))?,
_ => json!({}), _ => json!({}),
}; };
let servers = doc.as_object_mut().ok_or_else(|| format!("{} isn't a JSON object", path.display()))?.entry("mcpServers").or_insert_with(|| json!({})); let servers = doc.as_object_mut().ok_or_else(|| format!("{} isn't a JSON object", path.display()))?.entry("mcpServers").or_insert_with(|| json!({}));
let servers = servers.as_object_mut().ok_or_else(|| format!("{}: mcpServers isn't an object", path.display()))?; let servers = servers.as_object_mut().ok_or_else(|| format!("{}: mcpServers isn't an object", path.display()))?;
if servers.contains_key(sv.name) { if servers.contains_key(NAME) {
return Ok(false); return Ok(false);
} }
servers.insert(sv.name.into(), json!({"command": sv.cmd, "args": sv.args})); servers.insert(NAME.into(), json!({"command": CMD, "args": ARGS}));
if let Some(dir) = path.parent() { if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
} }
@@ -61,52 +49,45 @@ pub fn add_json(path: &Path, sv: &Server) -> R<bool> {
Ok(true) Ok(true)
} }
/// Adds a `[mcp_servers.NAME]` table to Codex's config.toml unless one is there; true when it added. /// Adds a `[mcp_servers.blender]` table to Codex's config.toml unless one is there; true when it added.
pub fn add_toml(path: &Path, sv: &Server) -> R<bool> { pub fn add_toml(path: &Path) -> R<bool> {
let text = std::fs::read_to_string(path).unwrap_or_default(); let text = std::fs::read_to_string(path).unwrap_or_default();
let (name, cmd) = (sv.name, sv.cmd); if text.lines().any(|l| l.trim() == format!("[mcp_servers.{NAME}]")) {
if text.lines().any(|l| l.trim() == format!("[mcp_servers.{name}]")) {
return Ok(false); return Ok(false);
} }
let args = sv.args.iter().map(|a| format!("{a:?}")).collect::<Vec<_>>().join(", "); let args = ARGS.iter().map(|a| format!("{a:?}")).collect::<Vec<_>>().join(", ");
let sep = if text.is_empty() || text.ends_with("\n\n") { "" } else if text.ends_with('\n') { "\n" } else { "\n\n" }; let sep = if text.is_empty() || text.ends_with("\n\n") { "" } else if text.ends_with('\n') { "\n" } else { "\n\n" };
if let Some(dir) = path.parent() { if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
} }
std::fs::write(path, format!("{text}{sep}[mcp_servers.{name}]\ncommand = {cmd:?}\nargs = [{args}]\n")).map_err(|e| format!("{}: {e}", path.display()))?; std::fs::write(path, format!("{text}{sep}[mcp_servers.{NAME}]\ncommand = {CMD:?}\nargs = [{args}]\n")).map_err(|e| format!("{}: {e}", path.display()))?;
Ok(true) Ok(true)
} }
/// Registers every server raea offers for an agent, a line each saying what happened. /// Registers the blender MCP server for an agent; the line says what happened. Claude Code rewrites ~/.claude.json while
/// it runs, so its own `claude mcp add` is used when `claude` is on PATH.
pub fn offer(agent: &str) -> R<String> { pub fn offer(agent: &str) -> R<String> {
servers().iter().map(|sv| offer_one(agent, sv)).collect::<R<Vec<_>>>().map(|l| l.join("\n")) let line = |added: bool, at: &Path| if added { format!("{}: MCP server {NAME} added", at.display()) } else { format!("{}: MCP server {NAME} already there", at.display()) };
}
/// Registers one MCP server for an agent; the line says what happened. Claude Code rewrites ~/.claude.json while it
/// runs, so its own `claude mcp add` is used when `claude` is on PATH.
fn offer_one(agent: &str, sv: &Server) -> R<String> {
let name = sv.name;
let line = |added: bool, at: &Path| if added { format!("{}: MCP server {name} added", at.display()) } else { format!("{}: MCP server {name} already there", at.display()) };
if agent == "codex" { if agent == "codex" {
let p = user_home()?.join(".codex/config.toml"); let p = user_home()?.join(".codex/config.toml");
return Ok(line(add_toml(&p, sv)?, &p)); return Ok(line(add_toml(&p)?, &p));
} }
let p = json_file(agent)?.ok_or_else(|| format!("no agent {agent:?}"))?; let p = json_file(agent)?.ok_or_else(|| format!("no agent {agent:?}"))?;
if agent == "claude" { if agent == "claude" {
let listed = Command::new("claude").args(["mcp", "get", name]).output(); let listed = Command::new("claude").args(["mcp", "get", NAME]).output();
match listed { match listed {
Ok(o) if o.status.success() => return Ok(line(false, &p)), Ok(o) if o.status.success() => return Ok(line(false, &p)),
Ok(_) => { Ok(_) => {
let o = Command::new("claude").args(["mcp", "add", "--scope", "user", name, "--", sv.cmd]).args(&sv.args).output().map_err(|e| e.to_string())?; let o = Command::new("claude").args(["mcp", "add", "--scope", "user", NAME, "--", CMD]).args(ARGS).output().map_err(|e| e.to_string())?;
if !o.status.success() { if !o.status.success() {
return Err(format!("claude mcp add {name}: {}", String::from_utf8_lossy(&o.stderr).trim())); return Err(format!("claude mcp add {NAME}: {}", String::from_utf8_lossy(&o.stderr).trim()));
} }
return Ok(line(true, &p)); return Ok(line(true, &p));
} }
Err(_) => {} // no claude on PATH: write its file Err(_) => {} // no claude on PATH: write its file
} }
} }
Ok(line(add_json(&p, sv)?, &p)) Ok(line(add_json(&p)?, &p))
} }
/// A move's guide as a skill of its own, named for the move: its description from the guide's first paragraph. /// A move's guide as a skill of its own, named for the move: its description from the guide's first paragraph.
@@ -134,26 +115,18 @@ mod tests {
let d = std::env::temp_dir().join(format!("raea-agent-mcp-{}", std::process::id())); let d = std::env::temp_dir().join(format!("raea-agent-mcp-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d); let _ = std::fs::remove_dir_all(&d);
let j = d.join("kimi/mcp.json"); let j = d.join("kimi/mcp.json");
let all = servers(); assert!(add_json(&j).unwrap());
let (blender, forma) = (&all[0], &all[1]); assert!(!add_json(&j).unwrap());
assert!(add_json(&j, blender).unwrap());
assert!(!add_json(&j, blender).unwrap());
std::fs::write(&j, r#"{"theme":"dark","mcpServers":{"blender":{"command":"mine"}}}"#).unwrap(); std::fs::write(&j, r#"{"theme":"dark","mcpServers":{"blender":{"command":"mine"}}}"#).unwrap();
assert!(!add_json(&j, blender).unwrap()); assert!(!add_json(&j).unwrap());
assert!(add_json(&j, forma).unwrap());
let kept: Value = serde_json::from_str(&std::fs::read_to_string(&j).unwrap()).unwrap(); let kept: Value = serde_json::from_str(&std::fs::read_to_string(&j).unwrap()).unwrap();
assert_eq!(kept["mcpServers"]["blender"]["command"], "mine"); assert_eq!(kept["mcpServers"]["blender"]["command"], "mine");
assert_eq!(kept["theme"], "dark");
let pinned = format!("forma-3d@{}", raea_app_forma::VERSION);
assert!(kept["mcpServers"]["forma"]["args"].as_array().unwrap().iter().any(|a| a == pinned.as_str()), "{kept}");
let t = d.join("codex/config.toml"); let t = d.join("codex/config.toml");
std::fs::create_dir_all(t.parent().unwrap()).unwrap(); std::fs::create_dir_all(t.parent().unwrap()).unwrap();
std::fs::write(&t, "model = \"x\"\n").unwrap(); std::fs::write(&t, "model = \"x\"\n").unwrap();
assert!(add_toml(&t, blender).unwrap()); assert!(add_toml(&t).unwrap());
assert!(!add_toml(&t, blender).unwrap()); assert!(!add_toml(&t).unwrap());
assert_eq!(std::fs::read_to_string(&t).unwrap(), "model = \"x\"\n\n[mcp_servers.blender]\ncommand = \"uvx\"\nargs = [\"mcp-for-blender\"]\n"); assert_eq!(std::fs::read_to_string(&t).unwrap(), "model = \"x\"\n\n[mcp_servers.blender]\ncommand = \"uvx\"\nargs = [\"mcp-for-blender\"]\n");
assert!(add_toml(&t, forma).unwrap());
assert!(std::fs::read_to_string(&t).unwrap().contains(&format!("[mcp_servers.forma]\ncommand = {:?}\n", forma.cmd)));
let _ = std::fs::remove_dir_all(&d); let _ = std::fs::remove_dir_all(&d);
} }
+1 -1
View File
@@ -10,7 +10,7 @@ pub mod song;
pub mod sound; pub mod sound;
pub mod splat; pub mod splat;
/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender; forma, for hard-surface parts) /// the MCP servers `raea skills install` offers an agent (blender, for a running Blender)
pub mod agent_mcp; pub mod agent_mcp;
pub mod agent_hooks; pub mod agent_hooks;
/// Grok Bot as a `raea skills install` target: its copy staged on this Mac, and the links that finish it in Grok Bot /// Grok Bot as a `raea skills install` target: its copy staged on this Mac, and the links that finish it in Grok Bot
+1
View File
@@ -16,6 +16,7 @@ mkdir -p "$OUT"
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0 export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
expected() { case $1 in expected() { case $1 in
examples/games/animated-character.tsx) echo "its media/RobotExpressive.glb was deleted" ;; examples/games/animated-character.tsx) echo "its media/RobotExpressive.glb was deleted" ;;
examples/playables/brick-rush.tsx) echo "RAEA_LIVE3D_CHECK panics on frame 1: the fast rows carry the sun's rotation and the full rows don't (runtime/scene/src/live.rs; docs/playables.feature PA18)" ;;
sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;; sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;;
esac; } esac; }
SAME=0 DIFF=0 ERR=0 SKIP=0 SAME=0 DIFF=0 ERR=0 SKIP=0
+5 -18
View File
@@ -1,8 +1,8 @@
//! A goal (docs/goal.feature): one step of the work, on a project's brief.ts as `goal:` (one, or several in order: a //! A goal (docs/goal.feature): one step of the work, on a project's brief.ts as `goal:` (one, or several in order: a
//! workflow), written with `cut()`, `shot()`, `kit()`, `scene()`, `playable()` or `rules()` from "raea/brief" before //! workflow), written with `cut()`, `shot()`, `kit()`, `scene()` or `rules()` from "raea/brief" before anything is
//! anything is built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that //! built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that belong
//! belong together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), a //! together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), and
//! playable (a game exported as a playable ad, playable.rs), and rules (any other work: only its own rules). Any goal can carry `rules` and an `aim`. Every object carries its real //! rules (any other work: only its own rules). Any goal can carry `rules` and an `aim`. Every object carries its real
//! size and whether it came from the reference or was invented; every dial its value, where the value came from, and //! size and whether it came from the reference or was invented; every dial its value, where the value came from, and
//! what it meant here. `raea goal check` (sdk/goal) holds each goal to it. //! what it meant here. `raea goal check` (sdk/goal) holds each goal to it.
@@ -25,9 +25,6 @@ pub enum Kind {
Cut, Cut,
/// any other work, held only to its rules: commands that must pass, files that must exist, words a critic judges /// any other work, held only to its rules: commands that must pass, files that must exist, words a critic judges
Rules, Rules,
/// a game exported as a playable ad by `raea playable`: each network's page, the preview, both orientations unless
/// the brief says one (playable.rs, docs/playables.feature PA19)
Playable,
} }
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
@@ -77,8 +74,6 @@ pub struct Goal {
pub rounds: Option<u32>, pub rounds: Option<u32>,
/// a cut job's contract: the brief as rules (cut.rs) /// a cut job's contract: the brief as rules (cut.rs)
pub cut: Option<crate::cut::Cut>, pub cut: Option<crate::cut::Cut>,
/// a playable job's game, networks and orientation (playable.rs)
pub playable: Option<crate::playable::Playable>,
/// what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a /// what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
/// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there /// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
#[serde(default)] #[serde(default)]
@@ -232,7 +227,7 @@ impl Kind {
/// as brief.ts writes it, and as raea judge's rubrics are named /// as brief.ts writes it, and as raea judge's rubrics are named
pub fn name(self) -> &'static str { pub fn name(self) -> &'static str {
// in the enum's order // in the enum's order
["scene", "kit", "shot", "cut", "rules", "playable"][self as usize] ["scene", "kit", "shot", "cut", "rules"][self as usize]
} }
} }
@@ -244,7 +239,6 @@ pub fn dials(kind: Kind) -> &'static [&'static str] {
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"], Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
Kind::Cut => &["look"], Kind::Cut => &["look"],
Kind::Rules => &[], Kind::Rules => &[],
Kind::Playable => &["look"],
} }
} }
@@ -282,7 +276,6 @@ fn by_kind(m: &Goal) -> Vec<String> {
Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(), Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(),
// only its `file` rules, added above // only its `file` rules, added above
Kind::Rules => vec![], Kind::Rules => vec![],
Kind::Playable => m.playable.as_ref().map(crate::playable::deliverables).unwrap_or_default(),
} }
} }
@@ -314,12 +307,6 @@ pub fn doctor(m: &Goal) -> Vec<String> {
(Some(_), k) => out.push(format!("`cut` is for a cut job, not a {k:?}: drop it, or make this `cut({{...}})`")), (Some(_), k) => out.push(format!("`cut` is for a cut job, not a {k:?}: drop it, or make this `cut({{...}})`")),
_ => {} _ => {}
} }
match (&m.playable, m.kind) {
(Some(p), Kind::Playable) => out.extend(crate::playable::doctor(p)),
(None, Kind::Playable) => out.push("no `playable`: the game's TSX (`game`), and its networks and orientation when the brief names them".into()),
(Some(_), k) => out.push(format!("`playable` is for a playable job, not a {k:?}: drop it, or make this `playable({{...}})`")),
_ => {}
}
out.extend(crate::rules::doctor(&m.rules)); out.extend(crate::rules::doctor(&m.rules));
if m.kind == Kind::Rules { if m.kind == Kind::Rules {
if m.aim.as_deref().is_none_or(|a| a.trim().is_empty()) { if m.aim.as_deref().is_none_or(|a| a.trim().is_empty()) {
+3 -21
View File
@@ -7,7 +7,6 @@ pub mod brief;
pub mod cut; pub mod cut;
pub mod goal; pub mod goal;
pub mod parts; pub mod parts;
pub mod playable;
pub mod rules; pub mod rules;
pub mod script; pub mod script;
pub mod taste; pub mod taste;
@@ -31,35 +30,18 @@ macro_rules! decls {
($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] }; ($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] };
} }
/// The file the goal's declarations are written to, beside brief.gen.ts (which re-exports them) /// The TypeScript declarations of every schema, one file's worth: sdk/raea/src/brief.gen.ts is this, checked by a test, and
pub const GOAL_FILE: &str = "brief-goal.gen"; /// `raea/brief` (sdk/raea/src/brief.ts) types its builders with it, so the declarations ship with the SDK.
/// The TypeScript declarations of every schema, two files' worth (a file stays under 500 lines, tools/size.sh):
/// sdk/raea/src/brief.gen.ts is this, the goal's (`goal_declarations`) re-exported from it, each checked by a test,
/// and `raea/brief` (sdk/raea/src/brief.ts) types its builders with them, so the declarations ship with the SDK.
pub fn declarations() -> String { pub fn declarations() -> String {
let cfg = Config::new(); let cfg = Config::new();
let mut out = vec![format!( let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.".to_string()];
"// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.\nimport type {{ Goals }} from \"./{GOAL_FILE}\";\nexport type * from \"./{GOAL_FILE}\";"
)];
out.extend(decls!(cfg; out.extend(decls!(cfg;
brief::Brief, brief::Section, brief::Deliverable, brief::Reference, brief::Agent, brief::Brief, brief::Section, brief::Deliverable, brief::Reference, brief::Agent,
script::Script, script::Scene, script::Beat, script::Line, script::Script, script::Scene, script::Beat, script::Line,
taste::Taste, taste::TasteSection, taste::Rule, taste::RuleCheck, taste::RuleLevel, taste::Check, taste::Taste, taste::TasteSection, taste::Rule, taste::RuleCheck, taste::RuleLevel, taste::Check,
parts::Parts, parts::Concept, parts::Level, parts::Count, parts::Part, parts::Parts, parts::Concept, parts::Level, parts::Count, parts::Part,
));
out.join("\n\n") + "\n"
}
/// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts
pub fn goal_declarations() -> String {
let cfg = Config::new();
// a cut's beats are a script's (script.rs Beat)
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.\nimport type { Beat } from \"./brief.gen\";".to_string()];
out.extend(decls!(cfg;
goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals, goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open, cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
playable::Playable, playable::Orientation,
rules::Rule, rules::Rule,
)); ));
out.join("\n\n") + "\n" out.join("\n\n") + "\n"
-125
View File
@@ -1,125 +0,0 @@
//! A playable goal (docs/playables.feature PA19): a raea game exported as a playable ad by `raea playable`, held to its
//! pages. The game is one TSX that renders as the video ad and exports for each network; the goal names it, the
//! networks it ships to and its orientation (both, unless the brief says one), and its deliverables are what the export
//! writes into out/playable/: each network's page or ZIP, the preview, and the export's manifest, which raea goal's
//! playable pack reads (sizes, compositions, when it was exported).
use serde::{Deserialize, Serialize};
use ts_rs::TS;
/// The networks `raea playable` writes for (apps/playable pages.rs NETWORKS, preview last)
pub const NETWORKS: &[&str] = &[
"applovin",
"unity",
"google",
"meta",
"moloco",
"mintegral",
"tiktok",
"liftoff",
];
/// The networks whose package is a ZIP (the rest are one HTML page)
const ZIPPED: &[&str] = &["google", "mintegral", "tiktok"];
/// Where the export writes, relative to the brief
pub const OUT: &str = "out/playable";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "PlayableOrientation")]
pub enum Orientation {
/// a portrait and a landscape composition, the host playing the one nearest the screen
Both,
Portrait,
Landscape,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields, rename = "PlayableGoal")]
pub struct Playable {
/// the game's TSX, relative to the brief: it renders as the video ad and exports as the playable
pub game: String,
/// the files' name ([a-z0-9_], `NAME-NETWORK.html`); the game's file name when left out
pub name: Option<String>,
/// the networks it ships to (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff); all of them when
/// left out. The preview page is always made: it's what the review plays
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub networks: Vec<String>,
/// both unless the brief says one: Unity, AppLovin, Moloco and Mintegral want both
pub orientation: Option<Orientation>,
/// [least, most] seconds of play before the end card (15 to 60 by default)
pub seconds: Option<[f64; 2]>,
/// the same game rendered as the video ad too, as out/cuts/NAME_9x16.mp4 (PA17)
pub video: Option<bool>,
}
/// The name its files land as: its own, else the game's file name, as `raea playable` names them
pub fn name(p: &Playable) -> String {
p.name.clone().unwrap_or_else(|| {
std::path::Path::new(&p.game)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("playable")
.to_string()
})
}
/// The networks it ships to, in raea's order
pub fn networks(p: &Playable) -> Vec<&'static str> {
NETWORKS
.iter()
.copied()
.filter(|n| p.networks.is_empty() || p.networks.iter().any(|m| m == n))
.collect()
}
/// What the export must have written: each network's page or ZIP, the preview and the manifest, and the video ad
pub fn deliverables(p: &Playable) -> Vec<String> {
let n = name(p);
let mut out: Vec<String> = networks(p)
.iter()
.map(|net| {
format!(
"{OUT}/{n}-{net}.{}",
if ZIPPED.contains(net) { "zip" } else { "html" }
)
})
.collect();
out.push(format!("{OUT}/{n}-preview.html"));
out.push(format!("{OUT}/{n}.playable.json"));
if p.video == Some(true) {
out.push(format!("out/cuts/{n}_9x16.mp4"));
}
out
}
/// What the playable still lacks before it can be built against
pub fn doctor(p: &Playable) -> Vec<String> {
let mut out = Vec::new();
if !p.game.ends_with(".tsx") {
out.push(format!(
"`game` {:?}: the game's TSX beside the brief (playable.tsx)",
p.game
));
}
if let Some(n) = p.name.as_deref().filter(|n| !crate::goal::is_name(n)) {
out.push(format!("playable name `{n}`: names are [a-z0-9_]"));
}
for n in p
.networks
.iter()
.filter(|n| !NETWORKS.contains(&n.as_str()))
{
out.push(format!(
"network `{n}` isn't one raea exports to ({})",
NETWORKS.join(", ")
));
}
if let Some([a, b]) = p.seconds {
if !(a > 0.0 && a <= b) {
out.push(format!("seconds [{a}, {b}]: least then most, both over 0"));
}
}
out
}
+7 -45
View File
@@ -1,18 +1,14 @@
use super::*; use super::*;
#[test] #[test]
fn declarations_match_the_committed_files() { fn declarations_match_the_committed_file() {
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src"); let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/brief.gen.ts");
for (file, now) in [("brief.gen.ts".to_string(), declarations()), (format!("{GOAL_FILE}.ts"), goal_declarations())] { let now = declarations();
let path = format!("{dir}/{file}"); if std::env::var_os("RAEA_WRITE").is_some() {
if std::env::var_os("RAEA_WRITE").is_some() { std::fs::write(path, &now).unwrap();
std::fs::write(&path, &now).unwrap();
}
let committed = std::fs::read_to_string(&path).unwrap_or_default();
assert!(committed == now, "sdk/raea/src/{file} is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
let lines = now.lines().count();
assert!(lines <= 500, "sdk/raea/src/{file} is {lines} lines: split it (tools/size.sh)");
} }
let committed = std::fs::read_to_string(path).unwrap_or_default();
assert!(committed == now, "sdk/raea/src/brief.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
} }
#[test] #[test]
@@ -157,37 +153,3 @@ fn several_goals_are_a_workflow_and_each_is_held_to_its_rules() {
let one: Brief = read("brief.ts", r#"{"title": "x", "goal": {"kind": "rules", "aim": "ship it", "rules": [{"id": "ok", "run": "true"}]}}"#).unwrap(); let one: Brief = read("brief.ts", r#"{"title": "x", "goal": {"kind": "rules", "aim": "ship it", "rules": [{"id": "ok", "run": "true"}]}}"#).unwrap();
assert!(goal::doctor_all(one.goal.as_ref().unwrap()).is_empty()); assert!(goal::doctor_all(one.goal.as_ref().unwrap()).is_empty());
} }
#[test]
fn a_playable_goal_delivers_each_networks_page_the_preview_and_the_manifest() {
let g: crate::goal::Goal = serde_json::from_str(r#"{"kind":"playable","aim":"a runner for a tea brand","playable":{"game":"playable.tsx","networks":["applovin","google"],"video":true}}"#).unwrap();
assert_eq!(
crate::goal::deliverables(&g),
[
"out/playable/playable-applovin.html",
"out/playable/playable-google.zip",
"out/playable/playable-preview.html",
"out/playable/playable.playable.json",
"out/cuts/playable_9x16.mp4"
]
);
assert!(
crate::goal::doctor(&g).is_empty(),
"{:?}",
crate::goal::doctor(&g)
);
// both orientations unless the brief names one: `raea playable`'s own default
assert_eq!(g.playable.as_ref().unwrap().orientation, None);
let bad: crate::goal::Goal = serde_json::from_str(
r#"{"kind":"playable","aim":"x","playable":{"game":"game.ts","networks":["vungle"]}}"#,
)
.unwrap();
let d = crate::goal::doctor(&bad).join("\n");
assert!(d.contains("game.ts") && d.contains("vungle"), "{d}");
let none: crate::goal::Goal = serde_json::from_str(r#"{"kind":"playable","aim":"x"}"#).unwrap();
assert!(
crate::goal::doctor(&none)
.iter()
.any(|l| l.starts_with("no `playable`"))
);
}
-26
View File
@@ -44,32 +44,6 @@ pub struct VideoFit {
pub scale: f32, pub scale: f32,
} }
/// What a page shows this frame as one number, folded into `seed`: each element's place, kind, props and text, and each
/// video's file and time in it. Not an element's id (React's count, which moves when an element is added before it),
/// not an <audio>, not a video's own sound (muted, volume): frames with one key draw one picture while the files they
/// name stay the same (files are named here, not read: whoever keeps pictures by this key holds the files to it).
/// A path under `dir` (the composition's folder) is named from there, so the same piece in another folder (a render
/// farm's job) has the same keys (11-30: the farm's first try had none in common, each clip named under its job).
pub fn key(seed: u64, want: &[Want], videos: &[VideoAt], dir: &std::path::Path) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
seed.hash(&mut h);
let root = dir.to_string_lossy();
let root = format!("{}/", root.trim_end_matches('/'));
let here = |s: String| if root.len() > 1 { s.replace(&root, "") } else { s };
for w in want.iter().filter(|w| w.kind != "audio") {
// (a <style>'s text names its fonts' files as its props name images)
(&w.path, &w.kind, w.text.clone().map(here)).hash(&mut h);
for (k, v) in w.props.iter().filter(|(k, _)| w.kind != "video" || (*k != "muted" && *k != "volume")) {
(k, here(v.to_string())).hash(&mut h);
}
}
for v in videos {
(v.file.strip_prefix(dir).unwrap_or(&v.file), v.at.to_bits(), v.fit.map(|f| [f.at.0, f.at.1, f.to.0, f.to.1, f.scale].map(f32::to_bits))).hash(&mut h);
}
h.finish()
}
/// What the page was last told about an element. /// What the page was last told about an element.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
struct Sent { struct Sent {
-24
View File
@@ -99,27 +99,3 @@ Feature: raea cloud: a synced folder is pictured, understood, embedded and organ
When StreetTalk's four Drive syncs run from empty When StreetTalk's four Drive syncs run from empty
Then every file has a picture, a description and tags; the three client folders are related to their client Then every file has a picture, a description and tags; the three client folders are related to their client
libraries; a search for a shot finds it by what's in it; and the run says its time and what it cost libraries; a search for a shot finds it by what's in it; and the run says its time and what it cost
Rule: every video has a light copy to watch and cut from
Scenario: IG14. A video's proxy is made once, from the download its index already makes
(built 12-02: raea-platform index-run.ts submitProxy/proxyDue, sdk/cloud/deploy/modal/proxy.py)
Given a video in a library, uploaded or synced from Drive
Then raea makes a 540p proxy of it on Modal (540 lines on the short side and never more than the original,
H.264 CRF 28 with a keyframe every second, AAC 96 kbps, faststart) from the same address its index job
fetches, so a synced file is downloaded through its tool once for both
And the proxy is kept in R2 by the original's SHA-256, written through a ticket for the workspace's proxies
alone (the job holds no raea credential), so footage kept twice is made once
And an original already that light (H.264 in MP4, 540 lines or fewer, under 2.5 Mbps) is its own proxy
And a library indexed before proxies gets them a few at a time, 8 running a workspace
Scenario: IG15. People watch the proxy
When a person opens a video in the library
Then it plays from its proxy: no copy of a Drive original through its tool, and no 4K HEVC in the browser
And its original stays one click away (Open)
Scenario: IG16. Agents look and cut from proxies, and finish from originals
When an agent searches its libraries for footage
Then it finds videos by what's in them (what's seen, heard and said, with the seconds where) and by name
And each video comes with its proxy, whose times are the original's, to fetch, watch, transcribe and rough-cut
And the original (an upload's link, or a synced file through library_original) is fetched only for the master
And drafts on the farm read clip copies at the size they're drawn (CR36); masters read the originals
-11
View File
@@ -353,14 +353,3 @@ notes and is worth shipping without it: a person gets word scores, checks and bo
5. **CLAP joins the stack** (Shane, 11-12: "include clap if we can if its not too much work"). It is about 300 lines 5. **CLAP joins the stack** (Shane, 11-12: "include clap if we can if its not too much work"). It is about 300 lines
of Rust on ort: the 48 kHz log-mel front end and the audio session (200), and the text tower with its tokenizer of Rust on ort: the 48 kHz log-mel front end and the audio session (200), and the text tower with its tokenizer
(100), run only when an axis's words change. Both are checked against the spike's vectors at cosine 0.999. (100), run only when an axis's words change. Both are checked against the spike's vectors at cosine 0.999.
6. **Pro and Studio include checks and content intelligence** (Shane, 11-20). Each month's pool (about 8,000 frames
checked on Pro, ten times that on Studio) stops when it's spent and is never billed past. It pays for two things:
- **clef-omni answering the fingerprint's questions** about a render's frames (`POST /v1/clef/ask`), so the agent
reads answers in words and opens only the frames they flag. Its verdicts are another eye's (FP6d), and it serves
the axes with no labels yet.
- **content intelligence for references** (`GET /v1/intel/...`): public posts, videos, transcripts and ads, to find
a videoform's references by what performs and keep them current (docs/videoform.md). A source's views and
engagement are another eye's evidence too, never the person's taste. A reference found this way is still read
once, as VF1 reads any link, and VF1's rights confirmation still applies.
Without a pool, everything here still works locally, and clef runs on the person's own Cloudflare account.
-91
View File
@@ -1,91 +0,0 @@
@spec
Feature: forma, a headless modeller for hard-surface parts, run as its own program
Shane, 2026-12-03, on github.com/wrong-nebula/forma: "can we make this an external package and integration we can
use or allow agents to download... its a gpl license so idk what that means for us". forma is a ~1 MB pure-Rust
modeller built for agents: a few lines of its pipe language (`box(4, 2, 0.4) | bevel(vertical, 0.25) | cut(cyl(0.5,
1))`) make a watertight mesh with exact sizes in milliseconds, with semantic edge and face selectors instead of vertex
indices. On 12-03 ten parts (gears, a flange, a threaded bolt, a mug, an enclosure, a lathed pawn, a lofted bottle,
a table, a desk lamp, a lettered plate) each built in about 0.2 s through its npm CLI, and loaded straight into raea
with <Model>. Two faults showed under raea's light: every colour pale (forma writes the sRGB value it was given into
baseColorFactor, which glTF reads as linear) and every curve faceted (one normal per face). Its text is a blocky
capitals-only face, and it can't make anything organic.
The licence: forma is GPL-3.0-or-later, raea is FSL-1.1, and the two can't be combined into one program. So raea
never links forma's crates or bundles its WebAssembly into the SDK, the CLI or the apps. raea downloads forma's own
release and runs it as a separate program, as it already does Blender (apps/tools/src/blender.rs), and works only
on the files forma writes. The GPL covers forma, not what it makes, and running it on raea cloud isn't distributing
it (GPLv3, not the AGPL).
Where it sits beside raea's own modelling (docs/blender.feature's framing): TSX is the scene; solids, sdf and grow
make what numbers or rules define inside raea; forma is a faster way to make a hard-surface part an agent can check
by its numbers (watertight, volume, box) before anyone looks; Blender stays the workshop for assets that are already
good; raea gen and CC0 libraries make what looks define.
Background:
Given raea pins one forma version (apps/forma VERSION, 0.4.4) with a hash for each download it makes
And forma lives in ~/.raea/tools/forma, or wherever `git config --global raea.forma` points
Rule: Getting forma
@done
Scenario: FM1. raea setup forma finds forma or downloads the pinned version
Given `raea setup forma [--check] [--download]`
When no forma is found (raea.forma, raea's download, a `forma` on PATH that says it is forma)
Then on Linux (x86_64, aarch64) forma's static musl binary is downloaded from its GitHub release and checked
against its pinned sha256: it needs no Node
And elsewhere forma's npm package (forma-3d) is downloaded from the npm registry and checked against its pinned
sha512, to be run by Node 18+ or Bun; with neither on PATH it says so before downloading anything
And a download that doesn't match its hash installs nothing and says where it left the file
And --check only says what would be used; --download replaces what is there
And the report names forma's version, where it came from, and that forma is GPL and runs as its own program
Rule: Making parts
@done
Scenario: FM2. raea forma makes a script's parts, strict by default
Given `raea forma SCRIPT.forma -o OUT.glb|.stl|.obj|.3mf|.step [--unit U] [--render P.png] [--draw B.svg]`
Then forma evaluates the script with --strict, and a .glb gets one node per named part (--scene)
And forma's report (each part's vertices, watertight, volume, box) is printed as it wrote it
And a part that isn't watertight is refused with forma's reason and nothing is written, unless --no-strict
And a flag raea forma doesn't know is refused with the usage
And `raea forma spec [--topic T] [--gbnf]` prints forma's own language reference
@done
Scenario: FM3. A .glb's colours are made linear, as glTF reads them
Given a .glb forma wrote, its baseColorFactor typed as sRGB
Then each material's colour is converted sRGB to linear (alpha kept), so terracotta reads terracotta under raea's
light and not pink
And the file is marked in asset.extras.raea_forma, and a marked file is never converted twice
And `raea forma fix FILE.glb... [--smooth DEG] [--flat]` does FM3 and FM4 to a .glb forma wrote by itself (its
MCP server's export), with no forma needed
@done
Scenario: FM4. A .glb's normals are smoothed where faces meet at under 40 degrees
Given forma's one normal per face
Then each corner takes the area-weighted mean of the faces at its position whose facing is within DEG of its own
(--smooth DEG, 40 unless given), so a box keeps its edges and a cylinder's side turns round
And positions, indices, UVs and the file's layout are kept byte for byte; only the normals' bytes change
And --flat keeps forma's normals; a primitive with tangents, or one in a layout the fix doesn't read, is left alone
Scenario: FM5. The fixed parts under raea's light match what the script asked for
Given the 12-03 table (scratchpad forma-try): ten parts made by `raea forma`, loaded with <Model>, one still
Then each part's lit colour is within a JND of its typed colour lit the same way in a raea <Cuboid>
And no curved part shows facets in a 4x crop
Rule: Agents
@done
Scenario: FM6. raea skills install adds forma's MCP server
Given `raea skills install --agent claude|codex|kimi|gemini`
Then beside `blender`, a `forma` MCP server is registered: `npx -y -p forma-3d@VERSION forma-3d-mcp` (through
`cmd /c` on Windows), fetched by npx when the agent first starts it
And a server the person already registered under the name is left as they set it; --no-mcp adds neither
Scenario: FM7. The raea skill says when forma is the tool and when it isn't
Given the raea skill (raea-skills, skills/raea/3d.md)
Then it names forma for hard-surface parts numbers define (mechanical parts, props with exact sizes, a blockout's
furniture) and `raea forma` over forma's own CLI, so the .glb comes out fixed
And it names what forma is wrong for: anything organic (people, animals, cloth, plants), textures, lettering
that has to look good, and the scene itself, which stays TSX
And it says the MCP server's exports aren't fixed: a part meant for a render goes through `raea forma`, or
`raea forma fix FILE.glb` after the server exported it
+1 -5
View File
@@ -318,7 +318,7 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
Given a goal job Given a goal job
Then `raea goal check` runs every `run` rule at every status, the Stop hook's included, and holds the job on one Then `raea goal check` runs every `run` rule at every status, the Stop hook's included, and holds the job on one
that fails or outlives its timeout, with its exit code and last line ("run") that fails or outlives its timeout, with its exit code and last line ("run")
And a `says` rule is clear only when review/judge/NAME.json, written by `raea goal judge [DIR] [--by claude|kimi|clef]` And a `says` rule is clear only when review/judge/NAME.json, written by `raea goal judge [DIR] [--by claude|kimi]`
(a fresh session that may only read: Read, Grep and Glob), found it true at a time no earlier than the work's (a fresh session that may only read: Read, Grep and Glob), found it true at a time no earlier than the work's
newest file, the job's own review/, .raea/, NOTES.md, .git and node_modules left out, compared at whole seconds newest file, the job's own review/, .raea/, NOTES.md, .git and node_modules left out, compared at whole seconds
("says") ("says")
@@ -456,10 +456,6 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
And the seen pack holds it until its contact sheet has been shown since its last render (FILE.seen.json: the And the seen pack holds it until its contact sheet has been shown since its last render (FILE.seen.json: the
render's time and size, what the agent said it sees and would change, at least 80 characters), and the render's time and size, what the agent said it sees and would change, at least 80 characters), and the
surprise pack, when on, until it names its moment in seconds and what it is surprise pack, when on, until it names its moment in seconds and what it is
And it holds a video until its design is judged too, on its frames at full size (FILE.looks/, six through the
cut, made by `raea goal seen FILE`): `--look "..."`, at least 80 characters on its type, captions, cards and
end beside a reference and what was changed, since a sheet's tiles show what happens and never how it looks
(12-01, Shane on Dutch: "why do components not look good. is it even proofing or reviewing the work?")
And on a Mac the same packs hold through `raea goal seen FILE` (the sheet, shown in the raea app with And on a Mac the same packs hold through `raea goal seen FILE` (the sheet, shown in the raea app with
`raea show`) and `raea goal seen FILE "WHAT I SEE AND WOULD CHANGE"`, which write FILE.seen.json; raea cloud's `raea show`) and `raea goal seen FILE "WHAT I SEE AND WOULD CHANGE"`, which write FILE.seen.json; raea cloud's
publish tool writes it through the same command publish tool writes it through the same command
+4 -10
View File
@@ -13,12 +13,9 @@ every project to import as `@shared/components/NAME`. `raea part` is the old nam
Beside raea's own sets is the library: several hundred open-source components (text reveals, counters, charts, Beside raea's own sets is the library: several hundred open-source components (text reveals, counters, charts,
transitions, product-screen demos, game HUDs and more), sorted by what they're for rather than who made them. transitions, product-screen demos, game HUDs and more), sorted by what they're for rather than who made them.
`raea make component list` ends with its categories; `list WORDS` searches it by a category (`text`), a category and `raea make component list` ends with its categories; `list WORDS` searches it by a category (`text`), a category and
type (`text/reveal`), a name or the name it had upstream, the phrases people ask for it with (`"chat input"`, type (`text/reveal`), or words in a name or description (`"count up"`). `add NAME` copies the component into
`composer`, `"lower third"`, `template`), or words in what it does (`"count up"`). `show NAME` tells one in full: what `components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's first line names
it draws and how it moves, when to use it and when not, the size and length it was designed at, and each prop with its the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
type, default and what it does; `--json` gives the same as JSON, for every hit of a `list`. `add NAME` copies the
component into `components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's
first line names the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
```sh ```sh
raea make component list raea make component list
@@ -26,8 +23,6 @@ raea make component add captions end-card
raea make component add reel --shared raea make component add reel --shared
raea make component list text/reveal raea make component list text/reveal
raea make component list count up raea make component list count up
raea make component list chat input
raea make component show prompt-send
raea make component add soft-blur-in raea make component add soft-blur-in
``` ```
@@ -36,7 +31,7 @@ raea make component add soft-blur-in
## Usage ## Usage
```sh ```sh
raea make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, "count up", "chat input", template; show tells one in full: what it draws, when to use it and when not, its props) raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, "count up")
``` ```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags. Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
@@ -46,7 +41,6 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| Flag | Takes | What it does | | Flag | Takes | What it does |
| --- | --- | --- | | --- | --- | --- |
| `--force` | – | Replace a component's files that are already there. Without it, an existing component is left alone and the command stops. | | `--force` | – | Replace a component's files that are already there. Without it, an existing component is left alone and the command stops. |
| `--json` | – | The library's items as JSON (`list`: every hit, best first; `show`: the one), each with its props, when to use it and when not, and the phrases it's asked for with. |
| `--shared` | – | Copy into the workspace's `shared/components/` instead, where every project in the workspace imports it as `/components/NAME`. | | `--shared` | – | Copy into the workspace's `shared/components/` instead, where every project in the workspace imports it as `/components/NAME`. |
<!-- generated:end --> <!-- generated:end -->
-62
View File
@@ -1,62 +0,0 @@
---
title: "raea forma"
summary: "Make hard-surface parts from a few lines of forma's language: watertight meshes with exact sizes, written as a .glb raea renders."
order: 117
sources: ["apps/forma/src/lib.rs", "apps/forma/src/glb.rs", "apps/tools/src/agent_mcp.rs"]
---
`raea forma` runs [forma](https://github.com/wrong-nebula/forma), a headless modeller for hard-surface parts, on a
script in its pipe language, and writes the parts it makes: gears, brackets, threaded bolts, enclosures, a lathed vase,
a table and its legs. Each named part is its own node in the .glb, every mesh is checked watertight, and a script
evaluates in milliseconds, so an agent can write a part, read forma's report (sizes, volume, whether it is watertight)
and change it in the same turn. Load the .glb with `<Model>` and light it in raea.
forma writes a material's colour as it was typed into the .glb, where glTF reads linear colour, so every part would
render pale; and it writes one normal per face, so a curved side shows its facets. `raea forma` fixes both in the file
after forma writes it: colours made linear, and corners smoothed where faces meet at under 40 degrees (a box keeps its
edges, a cylinder's side turns round). The file is marked as fixed and never fixed twice. `raea forma fix` does the
same to a .glb forma wrote by itself, through its MCP server or its own CLI.
forma is GPL-3.0-or-later, so raea never links it or ships it. [`raea setup forma`](setup.md) downloads forma's own
release into `~/.raea/tools/forma` and `raea forma` runs it as a program of its own. What forma makes is yours.
```sh
raea setup forma
raea forma spec # the language, about 500 tokens
raea forma bracket.forma -o assets/bracket.glb # strict: refused with forma's reason unless watertight
raea forma gears.forma --unit mm -o assets/gears.glb --draw gears.svg
raea forma fix assets/vase.glb # one the MCP server exported
```
Use it for parts that numbers define: mechanical parts, props with exact sizes, a blockout's furniture. It is the wrong
tool for anything organic (people, animals, cloth, plants), for textures, and for the scene itself, which stays TSX.
`raea skills install` adds forma's own MCP server to an agent as `forma`, for modelling a part over several turns.
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
## Usage
```sh
raea forma SCRIPT.forma -o OUT.glb|.stl|.obj|.3mf|.step [--unit m|cm|mm|um|in|ft] [--render PREVIEW.png] [--draw BLUEPRINT.svg] [--size PX] [--smooth DEG] [--flat] [--no-strict] (a forma script made into OUT, each named part its own node; a mesh that isn't watertight is refused with forma's reason unless --no-strict; a .glb's colours are made linear, as glTF reads them, and its normals smoothed where faces meet under DEG degrees (40 unless given; --flat keeps forma's faceted ones); --render's preview draws the last part, raea render draws them all)
raea forma fix FILE.glb... [--smooth DEG] [--flat] (the same fix on a .glb forma wrote by itself (its MCP server's export, its own CLI): colours linear, normals smoothed; a file fixed before is left alone)
raea forma spec [--topic deform|curves|uv|remesh|scene] [--gbnf] (forma's language reference, about 500 tokens: its primitives, operations and selectors)
```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
## Flags
| Flag | Takes | What it does |
| --- | --- | --- |
| `--draw` | `BLUEPRINT.svg` | Also write a dimensioned SVG drawing of the parts. |
| `--flat` | – | Keep forma's normals, one per face, faceted. |
| `--gbnf` | – | With `spec`: print forma's GBNF grammar, for constrained decoding. |
| `--no-strict` | – | Write the mesh even when it isn't watertight. |
| `--render` | `PREVIEW.png` | Also write forma's own PNG preview (four views of the last part). |
| `--size` | `PX` | The preview's size in pixels (512 unless given). |
| `--smooth` | `DEG` | Smooth normals where faces meet at under DEG degrees (40 unless given). |
| `--topic` | `deform\|curves\|uv\|remesh\|scene` | With `spec`: one topic's reference. |
| `--unit` | `m\|cm\|mm\|um\|in\|ft` | The unit the script is written in (metres unless given); a .glb is always in metres. |
| `-o` | `OUT.glb\|.stl\|.obj\|.3mf\|.step` | Where to write the parts; a .glb gets its colours and normals fixed. |
<!-- generated:end -->
+7 -11
View File
@@ -33,7 +33,7 @@ The packs, and what each holds:
| `place` | cut | no text over a face, a person or what the shot is about where a clear place of its size exists | | `place` | cut | no text over a face, a person or what the shot is about where a clear place of its size exists |
| `floor` | cut, floor | no clipped text, low contrast, freeze, flash or loudness out of range | | `floor` | cut, floor | no clipped text, low contrast, freeze, flash or loudness out of range |
| `stills` | every kind, floor | a composition's three stills as it's saved: no clipped or cramped text, nothing out of the safe areas | | `stills` | every kind, floor | a composition's three stills as it's saved: no clipped or cramped text, nothing out of the safe areas |
| `seen` | cut, floor | its contact sheet and its frames at full size looked at since its last render (`raea goal seen FILE`, then `raea goal seen FILE "..." --look "..."`) | | `seen` | cut, floor | its contact sheet looked at since its last render (`raea goal seen FILE`, then `raea goal seen FILE "..."`) |
| `surprise` | when a brief turns it on | one earned surprise named with its moment in seconds | | `surprise` | when a brief turns it on | one earned surprise named with its moment in seconds |
| `naming` | cut | every video and still named client_concept_variant_v#_size | | `naming` | cut | every video and still named client_concept_variant_v#_size |
| `sizes` | cut | one size first: no other size before a person approves the first | | `sizes` | cut | one size first: no other size before a person approves the first |
@@ -54,11 +54,8 @@ findings are then warnings.
A rules goal (`rules({...})`, what raea.app's `/goal` writes) is any other work: the aim in your words and the rules A rules goal (`rules({...})`, what raea.app's `/goal` writes) is any other work: the aim in your words and the rules
that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (300 seconds that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (300 seconds
unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is words that must be true of the unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is words that must be true of the
work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude`, `kimi` or `clef`) and work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude` or `kimi`) and keeps its
keeps its verdict in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's verdict in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's newest file.
newest file. `clef` is clef-omni, as `raea ask` reaches it: it watches and hears the files a rule names (in the rule's
"from A s to B s" window if it has one), else every video under out/, and reads no folder, so a rule about text it
can't see stays open. It is the critic where `RAEA_AGENT_KEY` is set, as on raea cloud; elsewhere the critic is `claude`.
```ts ```ts
import { brief, rules } from "raea/brief" import { brief, rules } from "raea/brief"
@@ -80,7 +77,7 @@ export default brief({
```sh ```sh
raea goal check # done: everything, as the Stop hook runs it raea goal check # done: everything, as the Stop hook runs it
raea goal check out/cuts/acme_dog_hook1_v2_9x16.mp4 --at render raea goal check out/cuts/acme_dog_hook1_v2_9x16.mp4 --at render
raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 && raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 "..." --look "..." raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 && raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 "..."
raea goal tasks --json # the brief's plan, every task raea goal tasks --json # the brief's plan, every task
raea goal next raea goal next
``` ```
@@ -97,8 +94,8 @@ goal's rules are never copied into the plan: the plan is the work, the goal is w
```sh ```sh
raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish) raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base) raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
raea goal seen FILE ["what you see and would change" --look "its design at full size, beside a reference"] [--surprise "SECONDS s: what it is"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size) raea goal seen FILE ["what you see and would change"] [--surprise "SECONDS s: what it is"] (FILE's contact sheet beside it, to look at every frame; with words, what was seen of FILE as it is now)
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude) raea goal judge [--goal NAME] [--by claude|kimi] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks) raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)
raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them) raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them)
``` ```
@@ -111,10 +108,9 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| --- | --- | --- | | --- | --- | --- |
| `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written | | `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written |
| `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). | | `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). |
| `--by` | `claude\|kimi\|clef` | The critic `judge` asks, a fresh session that may only read (default `claude`). | | `--by` | `claude\|kimi` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
| `--goal` | `NAME` | only this goal of the brief's (by its name) | | `--goal` | `NAME` | only this goal of the brief's (by its name) |
| `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. | | `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. |
| `--look` | `"its design` | `seen`: a video's design judged on its frames at full size (FILE.looks/): its type, captions, cards and end beside a reference, and what was changed. |
| `--manifest` | `render.json` | the render's manifest, for the sound pack's takes and effects | | `--manifest` | `render.json` | the render's manifest, for the sound pack's takes and effects |
| `--only` | `ID,...` | `check`: only these checks. Otherwise only these objects (refs, gen, pick-sheet, prep) or shots (framing), by id or name. | | `--only` | `ID,...` | `check`: only these checks. Otherwise only these objects (refs, gen, pick-sheet, prep) or shots (framing), by id or name. |
| `--put` | `PUT.json\|-` | `{plan, base}`: the whole plan written back only while the brief's is still `base` | | `--put` | `PUT.json\|-` | `{plan, base}`: the whole plan written back only while the brief's is still `base` |
+3 -4
View File
@@ -101,7 +101,7 @@ Music read, voices, and the audio setup.
## raea make: the asset tools ## raea make: the asset tools
What a project is made from, each a `raea make TOOL`: components, solids, clothes and motion for SOMA's body, splats, physics, light and weathering bakes, foley and instruments; and generated media, Blender, Godot and forma. What a project is made from, each a `raea make TOOL`: components, solids, clothes and motion for SOMA's body, splats, physics, light and weathering bakes, foley and instruments; and generated media, Blender and Godot.
| Verb | What it does | | Verb | What it does |
| --- | --- | | --- | --- |
@@ -120,7 +120,6 @@ What a project is made from, each a `raea make TOOL`: components, solids, clothe
| [`raea gen`](gen.md) | Generate images, video, music, sound, speech, 3D models and text through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI. | | [`raea gen`](gen.md) | Generate images, video, music, sound, speech, 3D models and text through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI. |
| [`raea blender`](blender.md) | Run a Blender Python script headless, with raea's library of mesh scripts: convert, decimate, repair, split, bake, rig, cloth. | | [`raea blender`](blender.md) | Run a Blender Python script headless, with raea's library of mesh scripts: convert, decimate, repair, split, bake, rig, cloth. |
| [`raea godot`](godot.md) | Run a TypeScript script against Godot's whole API in a headless Godot with GodotJS, record what it draws as frames, or open the editor on the project. | | [`raea godot`](godot.md) | Run a TypeScript script against Godot's whole API in a headless Godot with GodotJS, record what it draws as frames, or open the editor on the project. |
| [`raea forma`](forma.md) | Make hard-surface parts from a few lines of forma's language: watertight meshes with exact sizes, written as a .glb raea renders. |
## Agents and setup ## Agents and setup
@@ -134,8 +133,8 @@ What an agent reads and shows the person, and the tools raea installs.
| [`raea notes`](notes.md) | A person's notes as files the work is held to: each taken word for word, then restated as asks before anything changes. | | [`raea notes`](notes.md) | A person's notes as files the work is held to: each taken word for word, then restated as asks before anything changes. |
| [`raea show`](show.md) | Show the person something in the raea app, as an item they can use and answer: stills, a video, a sound, a script, an interactive .tsx or a question. | | [`raea show`](show.md) | Show the person something in the raea app, as an item they can use and answer: stills, a video, a sound, a script, an interactive .tsx or a question. |
| [`raea skill`](skill.md) | Print the agent skill this raea ships, matched to its version, or one of its references. | | [`raea skill`](skill.md) | Print the agent skill this raea ships, matched to its version, or one of its references. |
| [`raea skills`](skills.md) | Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP servers and hook. | | [`raea skills`](skills.md) | Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP server and hook. |
| [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on; or download forma, Godot and the motion models. | | [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on. |
| [`raea bug`](bug.md) | Report a bug in raea itself to raea's server: a line saying what's wrong and what happened, with raea's version and the OS added, no account needed. | | [`raea bug`](bug.md) | Report a bug in raea itself to raea's server: a line saying what's wrong and what happened, with raea's version and the OS added, no account needed. |
| [`raea ask`](ask.md) | Ask about a piece's picture and sound: clef-omni answers in words and a probability, paid from your raea plan, and every answer is kept so a question can be calibrated. | | [`raea ask`](ask.md) | Ask about a piece's picture and sound: clef-omni answers in words and a probability, paid from your raea plan, and every answer is kept so a question can be calibrated. |
+3 -4
View File
@@ -20,16 +20,15 @@ import the file instead), URLs and network calls, modules that need the native e
kinds the playable's renderer doesn't draw. It notes a game with only one orientation, and one that never imports kinds the playable's renderer doesn't draw. It notes a game with only one orientation, and one that never imports
`raea/playable` (`<EndCard>`, `<InstallButton>`, `install()`) to open the store itself. `raea/playable` (`<EndCard>`, `<InstallButton>`, `install()`) to open the store itself.
The 3D is drawn by Bevy's own PBR shaders, translated to WebGL2 when raea is built, with Bevy's light units, The 3D is drawn by three.js on raea's scene contract, with Bevy's light units and tone mapping. It comes from the
shadows, fog and TonyMcMapface tone mapping. three.js reads the page's 3D parts into a scene for them, so it comes from project (`raea add [email protected]`).
the project (`raea add [email protected]`). A game with no 3D ships without either.
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions --> <!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
## Usage ## Usage
```sh ```sh
raea playable GAME.tsx -o DIR [--name NAME] [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both] (a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad) raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both] (a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad)
``` ```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags. Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
+4 -11
View File
@@ -1,22 +1,16 @@
--- ---
title: "raea setup" title: "raea setup"
summary: "Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on; or download forma, Godot and the motion models." summary: "Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on."
order: 129 order: 129
sources: ["apps/tools/src/blender.rs", "apps/forma/src/lib.rs"] sources: ["apps/tools/src/blender.rs"]
--- ---
`raea setup blender` finds the Blender on this machine (from `git config raea.blender`, raea's own copy, /Applications or the `PATH`), or downloads the current LTS from blender.org into `~/.raea/tools/blender`. It then installs the add-on that `raea setup blender` finds the Blender on this machine (from `git config raea.blender`, raea's own copy, /Applications or the `PATH`), or downloads the current LTS from blender.org into `~/.raea/tools/blender`. It then installs the add-on that
lets an agent drive Blender over MCP. [`raea blender run`](blender.md) uses the Blender it found. lets an agent drive Blender over MCP. [`raea blender run`](blender.md) uses the Blender it found.
`raea setup forma` finds forma (from `git config raea.forma`, raea's own copy or the `PATH`), or downloads forma
itself into `~/.raea/tools/forma`: its static binary on Linux, else its npm package, run by Node 18+ or Bun. Each is
checked against the hash raea pins. forma is GPL-3.0-or-later, so it is fetched from forma's own release and never
shipped with raea; [`raea forma`](forma.md) runs it as a program of its own.
```sh ```sh
raea setup blender --check raea setup blender --check
raea setup blender raea setup blender
raea setup forma
``` ```
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions --> <!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
@@ -25,7 +19,6 @@ raea setup forma
```sh ```sh
raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install raea's add-on and the MCP add-on) raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install raea's add-on and the MCP add-on)
raea setup forma [--check] [--download] (find forma or download it into ~/.raea/tools/forma: forma 0.4.4, a headless modeller for hard-surface parts (GPL-3.0-or-later, so raea runs it as its own program and never ships it), its static binary on Linux, else its npm package run by Node 18+ or Bun, each checked against its pinned hash)
raea setup motion [--check] (what raea make motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU) raea setup motion [--check] (what raea make motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU)
raea setup godot [--check] (download Godot 4.6.1 with GodotJS, its TypeScript bindings (MIT), into ~/.raea/tools/godot: JavaScriptCore on the Mac, QuickJS on Windows and Linux; raea's own build (the Mac's notarized), else GodotJS's, each checked against its pinned sha256) raea setup godot [--check] (download Godot 4.6.1 with GodotJS, its TypeScript bindings (MIT), into ~/.raea/tools/godot: JavaScriptCore on the Mac, QuickJS on Windows and Linux; raea's own build (the Mac's notarized), else GodotJS's, each checked against its pinned sha256)
``` ```
@@ -36,7 +29,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
| Flag | Takes | What it does | | Flag | Takes | What it does |
| --- | --- | --- | | --- | --- | --- |
| `--check` | – | Say which Blender (or forma) would be used, without downloading or installing anything. | | `--check` | – | Say which Blender would be used, without downloading or installing anything. |
| `--download` | – | Download the LTS (or forma's pinned version) even when one is already on this machine. | | `--download` | – | Download the LTS even when a Blender is already on this machine. |
<!-- generated:end --> <!-- generated:end -->
+1 -4
View File
@@ -38,7 +38,6 @@ comment read as asks is a note: it closes when the person retires it, and the ap
raea show out/look-1.png out/look-2.png out/look-3.png --ask "Which of these three?" raea show out/look-1.png out/look-2.png out/look-3.png --ask "Which of these three?"
raea show out/cut.mp4 --replaces i-show-2f9c raea show out/cut.mp4 --replaces i-show-2f9c
raea show --question "Warmer or cooler grade?" --choice Warmer --choice Cooler raea show --question "Warmer or cooler grade?" --choice Warmer --choice Cooler
raea show --choose "Warm grade" out/warm-1.png out/warm-2.png --choose "Cool grade" out/cool-1.png --recommend 2
raea show --question "Which opening?" --choice Slam --preview out/slam.mp4 --choice Drift --preview out/drift.mp4 \ raea show --question "Which opening?" --choice Slam --preview out/slam.mp4 --choice Drift --preview out/drift.mp4 \
--question "Narrator speed?" --preview voice/take.mp3 --choice "As is" --choice Faster --question "Narrator speed?" --preview voice/take.mp3 --choice "As is" --choice Faster
raea show --on i-show-2f9c --working c-3 --sub "grade pass" raea show --on i-show-2f9c --working c-3 --sub "grade pass"
@@ -52,7 +51,7 @@ raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Wa
## Usage ## Usage
```sh ```sh
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --choose LABEL FILE... --choose LABEL FILE... [--recommend N] | 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), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --choose LABEL FILE... once per option (2 to 6) for the person to pick one, --recommend N the one you would (nothing is picked for them), their pick back as {"kind":"answer","choice":LABEL}; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; 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) raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | 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), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; 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)
``` ```
Needs the raea app's host running on this machine; then waits for a person's click in the raea app (to answer). Takes any number of arguments besides its flags. Needs the raea app's host running on this machine; then waits for a person's click in the raea app (to answer). Takes any number of arguments besides its flags.
@@ -64,7 +63,6 @@ Needs the raea app's host running on this machine; then waits for a person's cli
| `--as` | `NAME` | Who's showing it, as the feed names them (your harness's name when left out: Claude Code, Codex, Gemini). | | `--as` | `NAME` | Who's showing it, as the feed names them (your harness's name when left out: Claude Code, Codex, Gemini). |
| `--ask` | `LINE` | What you want from the person, shown with the item. With `--on` and `--working`: one ask you read the comment as (give it once per ask), shown on the comment for the person to correct. | | `--ask` | `LINE` | What you want from the person, shown with the item. With `--on` and `--working`: one ask you read the comment as (give it once per ask), shown on the comment for the person to correct. |
| `--choice` | `A` | With `--question`: one answer to pick; give it once per answer. Stills given instead are the choices. | | `--choice` | `A` | With `--question`: one answer to pick; give it once per answer. Stills given instead are the choices. |
| `--choose` | `LABEL FILE...` | One option for the person to pick, named, its files after it; give it once per option, 2 to 6. Their pick comes back as `{"kind":"answer","choice":LABEL}`. |
| `--clip` | `FILE` | With `--sign`: the clip the person is to sign, cut from the render (`raea notes check` cuts it). | | `--clip` | `FILE` | With `--sign`: the clip the person is to sign, cut from the render (`raea notes check` cuts it). |
| `--despite` | `CHECK WHY` | A check the render still fails, and why it goes to the person anyway; give it once per check. `raea show` refuses a render whose record still holds an error, naming each, and the why is shown on the item. | | `--despite` | `CHECK WHY` | A check the render still fails, and why it goes to the person anyway; give it once per check. `raea show` refuses a render whose record still holds an error, naming each, and the why is shown on the item. |
| `--detail` | `PARAGRAPH` | The paragraph the viewer opens from the `--label` before it. | | `--detail` | `PARAGRAPH` | The paragraph the viewer opens from the `--label` before it. |
@@ -78,7 +76,6 @@ Needs the raea app's host running on this machine; then waits for a person's cli
| `--preview` | `FILE` | A still, video, sound, script or `.md` the person can play or read while answering. After a `--choice` it is that choice's preview, otherwise the question's. | | `--preview` | `FILE` | A still, video, sound, script or `.md` the person can play or read while answering. After a `--choice` it is that choice's preview, otherwise the question's. |
| `--project` | `P` | The project to post to: its id, title or `Workspace/project`. The project this folder is in when left out. | | `--project` | `P` | The project to post to: its id, title or `Workspace/project`. The project this folder is in when left out. |
| `--question` | `Q` | Ask the person this, with `--choice` answers or stills to pick from. | | `--question` | `Q` | Ask the person this, with `--choice` answers or stills to pick from. |
| `--recommend` | `N` | With `--choose`: the option you'd pick, from 1, marked on it. Nothing is picked for the person. |
| `--render` | `HASH` | With `--sign`: the sha256 of the render the clip was cut from, which the person's sign names. | | `--render` | `HASH` | With `--sign`: the sha256 of the render the clip was cut from, which the person's sign names. |
| `--replaces` | `ITEM` | The item this is the next version of, so the feed shows it as that item's new version. | | `--replaces` | `ITEM` | The item this is the next version of, so the feed shows it as that item's new version. |
| `--role` | `ROLE` | With `--as`: the role shown beside the name. | | `--role` | `ROLE` | With `--as`: the role shown beside the name. |
+4 -4
View File
@@ -1,13 +1,13 @@
--- ---
title: "raea skills" title: "raea skills"
summary: "Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP servers and hook." summary: "Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP server and hook."
order: 128 order: 128
sources: ["engine/cli/src/skill.rs"] sources: ["engine/cli/src/skill.rs"]
--- ---
`raea skills install` copies the skill this raea ships into the folder an agent reads skills from, stamped with this `raea skills install` copies the skill this raea ships into the folder an agent reads skills from, stamped with this
version: `~/.claude/skills` for Claude Code, `~/.agents/skills` for Codex, Kimi Code's skills folder, and version: `~/.claude/skills` for Claude Code, `~/.agents/skills` for Codex, Kimi Code's skills folder, and
`~/.gemini/skills` for Gemini. It also adds the Blender and forma MCP servers to the agent, and raea's hooks to every agent `~/.gemini/skills` for Gemini. It also adds the Blender MCP server to the agent, and raea's hooks to every agent
([`raea hook`](hook.md)): media opened in the Mac's viewer goes to `raea show`, and the quick check runs after each ([`raea hook`](hook.md)): media opened in the Mac's viewer goes to `raea show`, and the quick check runs after each
saved composition. A skill folder that's a link (a checkout of raea-skills) is left as it is. saved composition. A skill folder that's a link (a checkout of raea-skills) is left as it is.
@@ -26,7 +26,7 @@ raea skills install --agent claude --pin quieter --pin bolder # /quieter and
## Usage ## Usage
```sh ```sh
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender and forma MCP servers unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server) raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
``` ```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags. Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
@@ -37,7 +37,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
| --- | --- | --- | | --- | --- | --- |
| `--agent` | `claude\|codex\|kimi\|gemini\|grokbot` | Which agent to install for. | | `--agent` | `claude\|codex\|kimi\|gemini\|grokbot` | Which agent to install for. |
| `--no-hooks` | – | Leave Claude Code's settings alone: don't add the quick-check hook. | | `--no-hooks` | – | Leave Claude Code's settings alone: don't add the quick-check hook. |
| `--no-mcp` | – | Don't add the Blender and forma MCP servers to the agent. | | `--no-mcp` | – | Don't add the Blender MCP server to the agent. |
| `--pin` | `MOVE` | Install a note's guide as a skill of its own, so `/MOVE` loads just it (`quieter`, `bolder`, `layout`, `adapt` and the rest). Repeatable. | | `--pin` | `MOVE` | Install a note's guide as a skill of its own, so `/MOVE` loads just it (`quieter`, `bolder`, `layout`, `adapt` and the rest). Repeatable. |
| `--reference` | `cli\|feed\|files\|sdk` | Used by `raea skill`; see [`raea skill`](skill.md). | | `--reference` | `cli\|feed\|files\|sdk` | Used by `raea skill`; see [`raea skill`](skill.md). |
+1 -96
View File
@@ -130,35 +130,14 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
Rule: Next Rule: Next
@done
Scenario: PA6. Sound in a playable Scenario: PA6. Sound in a playable
Given networks keep sound off until the first touch and most players never turn it on Given networks keep sound off until the first touch and most players never turn it on
Then raea/tone's instruments and the export's generated foley (TokenSynth, SAO) play through Web Audio from data Then raea/tone's instruments and the export's generated foley (TokenSynth, SAO) play through Web Audio from data
URLs after input.onFirstTouch, inside the size budget URLs after input.onFirstTouch, inside the size budget
# Status 12-03: built. The lint no longer refuses <Audio>; its walk renders raea/tone's output beside each
# composition (as the native entry does) and lists every generated sound the game describes (raea/asset keeps
# them by src). The export makes each one with the asset store a render uses (apps/playable sound.rs), AAC at
# 64 kb/s mono, and carries it as a data URL; it bundles host/sound.ts only for a game with sound and Tone.js
# (host/tone.ts, the project's `raea add [email protected]`) only for a raea/tone graph, which it builds from Tone's
# own classes and replays event by event. Sound starts in the first gesture, pauses while hidden and fades at
# the end card; a frame stepped past on a slow phone still renders its page, so an <Sfx> on it sounds.
# brick-rush now has a square-wave blip on the paddle and each brick and a generated crack (5 KB) under each
# brick: 1,844 KB a page. Checked in WebKit: nothing sounds before the first touch; after it the context runs,
# six raea/tone events started six oscillators and three cracks played, with no errors. tools/check.ts
# reports sound and fails a page whose sound doesn't decode or never plays.
@done
Scenario: PA8. Fonts inlined Scenario: PA8. Fonts inlined
Given brick-rush's page asks for Inter, which a phone doesn't have (it fell back to a serif in the first check) Given brick-rush's page asks for Inter, which a phone doesn't have (it fell back to a serif in the first check)
Then the export inlines the subset of each font the page uses, as the native render draws it Then the export inlines the subset of each font the page uses, as the native render draws it
# Status 12-03: built (apps/playable fonts.rs). The native page draws with core/fonts' faces (Fontsource latin
# subsets, Inter 400/700/900), each family it names aliased (Helvetica, Arial, SF Pro as Inter, Times as EB
# Garamond) and each weight drawn by the nearest face. The export inlines, for the page's default (Inter) and
# every family the game's script names that raea aliases, those same faces under that name, each face's weight
# a range (Inter 1-550, 551-800, 801-1000) so the browser picks the face core/fonts `face` picks; a test holds
# the two picks equal at every weight. Inter adds about 95 KB a page. Checked: brick-rush's weight-900 "Drag to
# play" draws the same face and weight in WebKit as in `raea render --frame` (it drew Inter SemiBold, then a
# serif, before); parity at frame 90 went from 8.4 to 6.1/255.
@done @needs:PA1 @done @needs:PA1
Scenario: PA9. The playable is held to the native render Scenario: PA9. The playable is held to the native render
@@ -185,7 +164,7 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
curves on the converted units scored Reinhard 14.5, Neutral 21.2, AgX 23.3, none 30.4, ACES 37.9; what is left is curves on the converted units scored Reinhard 14.5, Neutral 21.2, AgX 23.3, none 30.4, ACES 37.9; what is left is
the shading itself (the bricks' side faces a touch darker), PA11's job the shading itself (the bricks' side faces a touch darker), PA11's job
@done @needs:PA9 @needs:PA9
Scenario: PA11. Bevy's own shading in the light renderer Scenario: PA11. Bevy's own shading in the light renderer
Then Bevy's PBR shaders, composed for the pipelines a playable uses, are translated to GLSL ES 3.00 with naga at Then Bevy's PBR shaders, composed for the pipelines a playable uses, are translated to GLSL ES 3.00 with naga at
export time, and the light renderer draws with them instead of three.js's own materials export time, and the light renderer draws with them instead of three.js's own materials
@@ -204,51 +183,11 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
View (784 B), Lights (2,176 B), the cluster offsets, index lists and clustered lights (16 KB each, so the host View (784 B), Lights (2,176 B), the cluster offsets, index lists and clustered lights (16 KB each, so the host
clusters lights on the CPU as Bevy does on WebGL2), the StandardMaterial (192 B), the Mesh batch and Globals. clusters lights on the CPU as Bevy does on WebGL2), the StandardMaterial (192 B), the Mesh batch and Globals.
That packing, and the shadow passes, are PA11's real work; the shaders themselves come over unchanged That packing, and the shadow passes, are PA11's real work; the shaders themselves come over unchanged
# Status 12-03: built. tools/bevy-glsl composes the three programs with Bevy's own ShaderCache (raea's vendored
# bevy_pbr, bevy_render and bevy_core_pipeline 0.20.0, WebGL2's defs, 10 directional lights, Gaussian shadow
# filtering, MSAA, distance fog, the projection's kind read from the view) and naga 30 translates them;
# sdk/playable/bevy/build.sh writes them into host/bevy/programs.ts (105 KB, 21 KB gzipped) with each block's field offsets and which of Bevy's bindings each
# block and sampler is, and apps/playable's test fails when Bevy's shaders or the translator change and it isn't
# rebuilt. host/bevy.ts replaces three.js's renderer (three.ts and tonemap.ts are gone): it reads raea's three.js
# scene graph (scene.ts) for the parts, geometry and transforms, and fills Bevy's blocks as Bevy's render world
# does (bevy/fill.ts: prepare_view_uniforms, prepare_lights, MeshUniform::new, StandardMaterial's uniform; the
# lights back in Bevy's units through units.ts): reverse Z, one 1x1x1 light cluster packed as Bevy packs it for
# WebGL2, one directional shadow cascade (as Bevy on WebGL2 has) fitted to what the camera sees of the scene,
# point and spot lights, distance fog (Bevy's GpuFog from the scene's Fog: linear from near to far, or
# exponential for a density, as the native engine makes it), a forward pass into half float with 4x MSAA, then
# TonyMcMapface through Bevy's table. A Plane3d is drawn as its one face (Bevy's PlaneMeshBuilder), not as the
# flat Box three.js was given, whose top face three points down. Not drawn yet, each warned once in the
# console: an environment's light, a camera's own <Fog> (Bevy's DistanceFog component), normal maps, transmission, vertex colours, point and
# spot shadows, rect lights, a shadow catcher, a paint look
# Measured on brick-rush against `raea render --frame` (mean difference over the drawn pixels / 255, both pages
# against the same native frames; landscape frame 300 rendered with --despite type-over-part): portrait frame 90
# three.js 6.1 -> Bevy 4.3 (PA10 recorded 5.4), landscape frame 300 9.8 -> 7.7, what is left in landscape mostly
# the page's pulsing hint text. star-catch portrait frame 150: 17.0 -> 15.6 over the frame, 6.7 -> 5.0 over the
# 3D above the hint text. A scene of a floor, six boxes, a ball, a sun with shadows, a point light and a spot
# light (frame 10): perspective portrait 1.3, orthographic landscape 0.8, with linear fog 0.7, with exponential
# fog 0.7. The page: brick-rush 1,889 -> 1,794 KB (three's renderer out, the programs in).
# First frame in a fresh WebKit (served from localhost, to the GPU finishing it, 25 interleaved runs): three.js
# median 131 ms, mean 129.8; Bevy median 131 ms, mean 131.8. The GL work is about 5 ms on both pages; the rest
# is script and the page. Chrome's 4x CPU throttle isn't used (raea doesn't test in Chrome); with every WebKit
# process clamped to the efficiency cores at background priority (taskpolicy -b), 142 and 145 ms over 11 runs.
# brick-rush and star-catch play to their end cards and store taps in WebKit (tools/check.ts) in portrait and
# landscape, with instant and 150 ms taps
@done
Scenario: PA12. Bevy systems in a playable Scenario: PA12. Bevy systems in a playable
Given Bevy's logic alone is 0.2 MB gzipped as wasm (PA0b) Given Bevy's logic alone is 0.2 MB gzipped as wasm (PA0b)
Then a game whose rules are Rust (raea/ecs's world, behind the ecs.* native calls) runs them in wasm in the Then a game whose rules are Rust (raea/ecs's world, behind the ecs.* native calls) runs them in wasm in the
playable, its world drawn by the light renderer playable, its world drawn by the light renderer
And the status (12-03): runtime/ecs builds as a cdylib for wasm32 (src/wasm.rs; sdk/playable/ecs/build.sh,
253 KB, 105 KB gzipped, no imports) into sdk/playable/src/host/ecs.wasm, with the hash of its sources beside it
(apps/playable's test fails when runtime/ecs changes and it isn't rebuilt). The lint's walk sees a World made;
the export carries the wasm and its entry loads host/ecs.ts before the game, so raea/ecs's calls (native.ts
ecsCall) reach Bevy's world in the page as they reach it in the engine. World.copy() is a game's next state, and
a store nothing holds frees its world. examples/playables/star-catch.tsx (spawn, aim and catch systems on a
World) exports at 1,824 KB, plays to its end card in WebKit in both orientations with instant and held taps
(7,724 calls answered), and its frame 150 holds the same stars, basket and score as `raea render --frame`
(shading 17.0/255 over the 3D pixels, 0.19% of the frame past 8%: PA11's). conformance/ecs-wasm.test.ts runs
one world's life on the wasm and on the TypeScript tables and finds them equal
@done @done
Scenario: PA13. `raea playable` Scenario: PA13. `raea playable`
@@ -270,16 +209,9 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
And the guide is sdk/guides/craft/motion/playable.md (`raea guide playable`, copied into the skill's motion/), and And the guide is sdk/guides/craft/motion/playable.md (`raea guide playable`, copied into the skill's motion/), and
SKILL.md routes "a playable ad" to it SKILL.md routes "a playable ad" to it
@done
Scenario: PA15. A 2D playable carries no three.js Scenario: PA15. A 2D playable carries no three.js
Given 11-28's tiles bundle: three.js 924 KB of 1,393 KB, react-dom 178 KB, for a game that draws no 3D Given 11-28's tiles bundle: three.js 924 KB of 1,393 KB, react-dom 178 KB, for a game that draws no 3D
Then the export builds the host without the three.js scene when the lint finds no 3D kind (about 470 KB a page) Then the export builds the host without the three.js scene when the lint finds no 3D kind (about 470 KB a page)
# Status 12-03: built. The host asks for its 3D through one interface (host/draw3d.ts); a drawer (three.ts then,
# Bevy's programs in bevy.ts since PA11) draws it, and the export's entry passes it to start() only when the lint
# found a 3D kind, so a 2D game's bundle never imports three.js. Measured (preview page, before -> after, the after with PA8's ~95 KB of Inter):
# tiles 1,345 -> 378 KB, gates 1,347 -> 380 KB, three 2D brand playables 2,752 -> 1,782, 3,409 -> 2,440 and
# 2,693 -> 1,724 KB; brick-rush (3D, keeps three.js) 1,384 -> 1,478 KB. Each of the six played to its end card
# and its store tap in WebKit (tools/check.ts), with instant taps (TAP_MS=0) and 150 ms taps.
Scenario: PA16. Playables in the review (raea cloud and the desktop) Scenario: PA16. Playables in the review (raea cloud and the desktop)
Given the review's own player (raea-platform board-simple review.js PLAYER_DRAWS) is the one view of a shown file Given the review's own player (raea-platform board-simple review.js PLAYER_DRAWS) is the one view of a shown file
@@ -309,31 +241,4 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
Given bench/live-3d/corpus.sh skips brick-rush: under RAEA_LIVE3D_CHECK it panics on frame 1, because the fast Given bench/live-3d/corpus.sh skips brick-rush: under RAEA_LIVE3D_CHECK it panics on frame 1, because the fast
rows (runtime/scene/src/live.rs) carry the sun's rotation and the full rows don't rows (runtime/scene/src/live.rs) carry the sun's rotation and the full rows don't
Then the fast and full rows agree on a light's transform, and brick-rush plays live and leaves the corpus's skips Then the fast and full rows agree on a light's transform, and brick-rush plays live and leaves the corpus's skips
# Status 12-03: the cause: the fast path (runtime/scene fast.rs `put`) rounded every column but a placement's
# to 6 decimals, a light's rotation quaternion too, while the full rows (parts.rs) write it exact; a sun that
# never moved differed on the first fast frame. A rotation and a colour column now go through exact on both.
# runtime/scene/tests/live_light.rs panicked before the change and passes after; corpus.sh no longer skips
# brick-rush.
@done
Scenario: PA19. A brief that asks for a playable
Given a brief's goal was a cut, a shot, a kit, a scene or rules, so a brief asking for a playable planned a cut
Then core/brief has a playable goal (playable.rs: the game's TSX, its name, networks, orientation, seconds, and the
video ad too when asked) whose deliverables are what `raea playable` writes into out/playable/: each network's
page or ZIP, the preview and the export's manifest (NAME.playable.json)
And raea goal's playable pack reads that manifest at publish and done: every page under the 5 MB cap, the
compositions in the orientations asked for (both unless the brief names one), every network written, and the
game unchanged since its export
# Status 12-03: built (core/brief playable.rs, sdk/goal packs/playable.ts, `raea playable --name`, the manifest).
# The generated declarations split in two to stay under 500 lines a file: brief.gen.ts re-exports
# brief-goal.gen.ts. raea cloud's Ideate and brief form write `playable({ playable: {...} })` (raea-platform).
@done
Scenario: PA20. A tap shorter than a frame still reaches the game
Given the host handed the game only what was held when a step read the input, so a tap that went down and up
between two steps never arrived (instant taps left the attract demo running)
Then a press, a finger and a key count as held for the step after they went down, and the next step sees them
let go
# Status 12-03: #310 (host/input.ts). tools/check.ts plays with TAP_MS (0 is an instant tap, 150 by default);
# every playable above was checked both ways.
+6 -22
View File
@@ -12,8 +12,8 @@ Feature: Videoform: the kind of video a person makes again and again, read once
references, its vocabulary, its template and its rules. It's found, inherited, taught and shared as a references, its vocabulary, its template and its rules. It's found, inherited, taught and shared as a
fingerprint is. fingerprint is.
2. Each part flows into the part of raea that does that job already: its ranges into its profile (FP6e), its rules 2. Each part flows into the part of raea that does that job already: its ranges into its profile (FP6e), its rules
into the section's `rules`, each in a taste line's shape (words, a check, its values, a level; DR4, DR8), its into a controller's rule fields (DR4, DR8), its structure into a NAME.script.ts template, its references into
structure into a NAME.script.ts template, its references into brief.ts's `references` shape. brief.ts's `references` shape.
3. A reference is read once, from the local drive or streamed from a URL, and never needed again: its per-shot rows, 3. A reference is read once, from the local drive or streamed from a URL, and never needed again: its per-shot rows,
its vocabulary's vectors, its ranges, its structure and its rules are all that following and checking read. its vocabulary's vectors, its ranges, its structure and its rules are all that following and checking read.
4. What stays the same across the references is the videoform; what varies is content. A rule's strength is its 4. What stays the same across the references is the videoform; what varies is content. A rule's strength is its
@@ -23,26 +23,13 @@ Feature: Videoform: the kind of video a person makes again and again, read once
6. Checks start from the composition: a videoform's rules run in `raea check PROJECT` before any render, and 6. Checks start from the composition: a videoform's rules run in `raea check PROJECT` before any render, and
embeddings only for shots that changed. embeddings only for shots that changed.
Start here (the order of work, and where it touches what exists):
- The order: VF1 and VF2 (a reference in, a videoform made), VF3 (each reference read once into the kept rows), then
VF4 with VF12 (the ranges, judged on the test bench). That pair is the gate: it passes on at least five of the
person's sets before VF1b's platform pages or anything in VF9-VF11 is built.
- New crates hold the work: raea-app-videoform (apps/videoform: ingest, rights, reading, the verbs, the bench),
raea-sys-videoform (systems/videoform: the maths over kept rows) and raea-io-resolve (io/resolve, VF1b). The
videoform section's types are core/brief's videoform.rs.
- Three small hooks into what exists: fingerprint.ts's optional `videoform` field (systems/fingerprint taxonomy.rs,
VF2), `raea context` printing a project's videoform (engine/cli guide.rs, VF2), and `raea check PROJECT` holding
the rules of the fingerprint that judges the piece (apps/direction check.rs, VF8).
- The bench (VF12) runs after every step, on every set, from the kept files alone; its numbers are the progress.
Background: Background:
Given the readers raea has: footage perception (systems/footage), Fingerprint's columns (systems/columns: SigLIP 2, Given the readers raea has: footage perception (systems/footage), Fingerprint's columns (systems/columns: SigLIP 2,
CLAP, YAMNet, cached by content hash), Parakeet's words, Beat This!, HTDemucs and Silero VAD (systems/song), OCR, CLAP, YAMNet, cached by content hash), Parakeet's words, Beat This!, HTDemucs and Silero VAD (systems/song), OCR,
Depth Anything 3, and raea check's one decode of the picture (raea-app-check-read once.rs) Depth Anything 3, and raea check's one decode of the picture (raea-app-check-read once.rs)
And Fingerprint's fingerprint.ts (`about`, `extends`, `applies`, axes, encoder pins), its profiles (FP6e: ranges by And Fingerprint's fingerprint.ts (`about`, `extends`, `applies`, axes, encoder pins), its profiles (FP6e: ranges by
measure name, critique, leave-one-out), `which` (FP14c) and evidence rows (FP2c) measure name, critique, leave-one-out), `which` (FP14c) and evidence rows (FP2c)
And taste lines' checks (raea's six forms, a check by name, a `.ts` check written with raea/check over the world; And controllers' `rule` fields and raea/check's `.ts` checks over the world (DR4), run by `raea check PROJECT`
DR4), run by `raea check PROJECT`
And the crate limits (a file at most 500 lines, a crate at most 2,000): raea-sys-fingerprint, -fingerprint-use and And the crate limits (a file at most 500 lines, a crate at most 2,000): raea-sys-fingerprint, -fingerprint-use and
raea-app-fingerprint are each within 150 lines of theirs, so a videoform's code is its own crates, and the raea-app-fingerprint are each within 150 lines of theirs, so a videoform's code is its own crates, and the
fingerprint crates grow only by a field and a map fingerprint crates grow only by a field and a map
@@ -162,15 +149,12 @@ Feature: Videoform: the kind of video a person makes again and again, read once
And the template is a NAME.script.ts a project made to the videoform starts from, checked by `raea spec` And the template is a NAME.script.ts a project made to the videoform starts from, checked by `raea spec`
@needs:VF6,VF7 @needs:VF6,VF7
Scenario: VF8. Rules, with their strength, in the videoform's rules Scenario: VF8. Rules, with their strength, into a controller
Given the plan Given the plan
| crate | file | lines | job | | crate | file | lines | job |
| raea-sys-videoform | systems/videoform/src/rules.rs | 240 | coverage, order and event rules from the kept rows, each with how strongly it holds; written into the section's `rules`, each a taste line with its check and values | | raea-sys-videoform | systems/videoform/src/rules.rs | 240 | coverage, order and event rules from the kept rows, each with how strongly it holds; written as rule fields of the controller `videoform.rules` names |
| raea-app-direction | apps/direction/src/check.rs | 15 | tastes(): the rules of the fingerprint `which` names for the project, after the person's, the workspace's and the project's taste |
Then a rule that holds in most references (a punch-in when a number is said; a close-up of the counters in every Then a rule that holds in most references (a punch-in when a number is said; a close-up of the counters in every
kitchen) is a line in the section's `rules`, with its strength and its check kitchen) is a rule field with its strength and its check
And `raea check PROJECT` holds a piece to the rules of the fingerprint that judges it (raea-sys-fingerprint-use
`which`), beside the person's, the workspace's and the project's taste
And the person confirms the strongest rules once, on a contact sheet of shot-kind stills, and each answer is And the person confirms the strongest rules once, on a contact sheet of shot-kind stills, and each answer is
evidence in the videoform evidence in the videoform
+8 -7
View File
@@ -49,10 +49,11 @@ not only what was corrected. Notes still matter. They teach what the numbers can
| Fingerprint: `fingerprint.ts` with `about`, `extends`, `applies` kinds and tags; `which` finds one by project, workspace and account; a child inherits its parent's evidence, its own counted more; notes teach the one that judged (FP14a-e) | the home: a videoform is one of these | the fields a kind of video needs | | Fingerprint: `fingerprint.ts` with `about`, `extends`, `applies` kinds and tags; `which` finds one by project, workspace and account; a child inherits its parent's evidence, its own counted more; notes teach the one that judged (FP14a-e) | the home: a videoform is one of these | the fields a kind of video needs |
| Fingerprint's frozen encoders (SigLIP 2, CLAP, YAMNet, EmbeddingGemma 2, Depth Anything 3), columns cached by content hash, word and learned heads, evidence in f16 rows (FP1-FP4) | the per-shot vectors and measures, and where they're kept | no shot vocabulary, no structure | | Fingerprint's frozen encoders (SigLIP 2, CLAP, YAMNet, EmbeddingGemma 2, Depth Anything 3), columns cached by content hash, word and learned heads, evidence in f16 rows (FP1-FP4) | the per-shot vectors and measures, and where they're kept | no shot vocabulary, no structure |
| Fingerprint profiles: ranges from admired work, critique against them, a leave-one-out test (FP6e, `raea fingerprint profile`) | a videoform's ranges, and its validation | few measures (loudness, tilt, cut rate, motion, light, colour, sharpness) | | Fingerprint profiles: ranges from admired work, critique against them, a leave-one-out test (FP6e, `raea fingerprint profile`) | a videoform's ranges, and its validation | few measures (loudness, tilt, cut rate, motion, light, colour, sharpness) |
| Controllers' `rule` fields, a check by name or a `.ts` check on raea/check's world (DR4) | rules that `raea check PROJECT` and every agent hold work to | none written from references |
| Notes become checks, and climb to project, workspace and taste (DR5-DR8, `raea notes keep`) | the path a correction takes to becoming a rule | a videoform's rules start from evidence, not notes | | Notes become checks, and climb to project, workspace and taste (DR5-DR8, `raea notes keep`) | the path a correction takes to becoming a rule | a videoform's rules start from evidence, not notes |
| `raea check`: findings and the record (DR3); who can fix what, carried findings, one decode (raea-app-check-cause, PR #205) | the check every pass runs | a videoform's rules join it as more rules | | `raea check`: findings and the record (DR3); who can fix what, carried findings, one decode (raea-app-check-cause, PR #205) | the check every pass runs | a videoform's rules join it as more rules |
| `NAME.script.ts` (scenes, beats, lines, cut); `brief.ts` (`references`, `look`, `mode`, `deliver`) | a storyboard spec, and a brief that names references | no template made from references; references named, never read | | `NAME.script.ts` (scenes, beats, lines, cut); `brief.ts` (`references`, `look`, `mode`, `deliver`) | a storyboard spec, and a brief that names references | no template made from references; references named, never read |
| `taste.ts` lines: words, and a check that holds them (one of six forms, a check by name, or a `.ts` check on raea/check's world; DR4) | the person's, the workspace's and the project's standing lines, which `raea check PROJECT` and every agent hold work to | none written from references | | `taste.ts`, six checked forms | the person's standing lines | the forms are fixed: mined rules go to controllers, not here |
| Footage perception (`systems/footage`: shots, cuts, camera, faces, words on screen, scene labels, performance, facts.json) | what each reference shot is | read for raw footage, not for references | | Footage perception (`systems/footage`: shots, cuts, camera, faces, words on screen, scene labels, performance, facts.json) | what each reference shot is | read for raw footage, not for references |
| Transcription (Parakeet), beats, stems and voice activity (`raea song`, HTDemucs, Silero VAD), OCR | words, pauses, cuts against beats, music under voice, captions | not gathered into a videoform | | Transcription (Parakeet), beats, stems and voice activity (`raea song`, HTDemucs, Silero VAD), OCR | words, pauses, cuts against beats, music under voice, captions | not gathered into a videoform |
| Index and libraries (SigLIP over a person's media; turbopuffer in the cloud) | finding footage by meaning; vector storage for teams | — | | Index and libraries (SigLIP over a person's media; turbopuffer in the cloud) | finding footage by meaning; vector storage for teams | — |
@@ -82,7 +83,7 @@ Each part of a videoform flows into the part of raea that already does that job:
|---|---|---| |---|---|---|
| ranges (pace, pauses, shot lengths, loudness, colour, captions) | its own profile (FP6e) | `raea fingerprint score --profile` critiques a cut against them, and leave-one-out is already built | | ranges (pace, pauses, shot lengths, loudness, colour, captions) | its own profile (FP6e) | `raea fingerprint score --profile` critiques a cut against them, and leave-one-out is already built |
| the taste taught later | its own evidence and heads (FP2, FP14b-d) | a note on a piece it judged teaches it, never the person's general fingerprint unless they move it up | | the taste taught later | its own evidence and heads (FP2, FP14b-d) | a note on a piece it judged teaches it, never the person's general fingerprint unless they move it up |
| rules (coverage, order, event rules, limits) | the section's `rules`, each in a taste line's shape (words, check, values, level) | `raea check PROJECT` runs them for a piece the videoform judges (`which`), beside the taste | | rules (coverage, order, event rules, limits) | a controller's `rule` fields, which `videoform.rules` names | `raea check PROJECT` runs them, and they're edited in the app like any controller |
| structure (slots, their order and lengths) | a `NAME.script.ts` template, which `videoform.template` names | a project made to the videoform starts from it, and agents plan from it as from any storyboard | | structure (slots, their order and lengths) | a `NAME.script.ts` template, which `videoform.template` names | a project made to the videoform starts from it, and agents plan from it as from any storyboard |
| references | `brief.ts`'s existing `references` shape, `{ target, note }`, with the source kept by content hash | a reference is named the way a brief already names one | | references | `brief.ts`'s existing `references` shape, `{ target, note }`, with the source kept by content hash | a reference is named the way a brief already names one |
@@ -160,7 +161,7 @@ Following and checking need four kinds of thing from the references, and a video
| per-shot rows | each reference shot's SigLIP 2 vector (one pooled vector, a few frames averaged), its CLAP vector over the shot's sound, and its measures (length, scale, camera move, caption boxes, light and colour, words, pauses at its edges, its place in the video) | the shot vocabulary; matching new footage to shot kinds; the embedding checks | | per-shot rows | each reference shot's SigLIP 2 vector (one pooled vector, a few frames averaged), its CLAP vector over the shot's sound, and its measures (length, scale, camera move, caption boxes, light and colour, words, pauses at its edges, its place in the video) | the shot vocabulary; matching new footage to shot kinds; the embedding checks |
| the vocabulary's vectors | each term's phrasings through the text towers, as word heads store them (FP2e) | naming shot kinds; finding domain things in new footage | | the vocabulary's vectors | each term's phrasings through the text towers, as word heads store them (FP2e) | naming shot kinds; finding domain things in new footage |
| the profile | the ranges of every measure across the references (FP6e) | the critique, and composition-first range checks | | the profile | the ranges of every measure across the references (FP6e) | the critique, and composition-first range checks |
| the structure and the rules | the slots with their lengths and shot kinds; the event and coverage rules with their strength | the template, and the rules `raea check` runs | | the structure and the rules | the slots with their lengths and shot kinds; the event and coverage rules with their strength | the template, and the controller rules `raea check` runs |
Also kept: one small still for each shot kind (a thumbnail, a few kilobytes), so the person can see what a kind is when Also kept: one small still for each shot kind (a thumbnail, a few kilobytes), so the person can see what a kind is when
confirming rules, and the evidence the person adds over time. The reference videos aren't kept. confirming rules, and the evidence the person adds over time. The reference videos aren't kept.
@@ -225,8 +226,8 @@ working as it was. This is the one time a reference is needed again, and it's th
(open, sections, close), each with its length range, its shot kinds and what's on screen. This becomes the script (open, sections, close), each with its length range, its shot kinds and what's on screen. This becomes the script
template. template.
5. **The event rules.** How often one thing comes with another across the references ("a punch-in when a number is 5. **The event rules.** How often one thing comes with another across the references ("a punch-in when a number is
said", "a close-up of the counters in every kitchen"). Those that hold in most references become the videoform's said", "a close-up of the counters in every kitchen"). Those that hold in most references become controller rules,
rules, each stating how strongly it holds. each stating how strongly it holds.
6. **The person confirms the strongest rules once,** on a contact sheet ("countertop close-up in every kitchen: 9 of 6. **The person confirms the strongest rules once,** on a contact sheet ("countertop close-up in every kitchen: 9 of
10"). Each yes or no is evidence in the videoform, as any label is in a fingerprint. 10"). Each yes or no is evidence in the videoform, as any label is in a fingerprint.
@@ -246,7 +247,7 @@ working as it was. This is the one time a reference is needed again, and it's th
- shot lengths and pauses (the voice's cut points are in the composition); - shot lengths and pauses (the voice's cut points are in the composition);
- caption places and sizes. - caption places and sizes.
These are the videoform's rules, run by `raea check PROJECT` with the taste. These are the controller rules, run by `raea check PROJECT` as today.
2. **On the render manifest and measures, in seconds:** loudness, light and colour against the profile (`raea 2. **On the render manifest and measures, in seconds:** loudness, light and colour against the profile (`raea
fingerprint score --profile`). fingerprint score --profile`).
3. **On embeddings, only for shots that changed:** each shot against its slot's shot kind (one SigLIP frame a shot); 3. **On embeddings, only for shots that changed:** each shot against its slot's shot kind (one SigLIP frame a shot);
@@ -297,7 +298,7 @@ The sets, their answers and their verdicts are kept as fixtures, so each step of
| | VF5 | the vocabulary loop with the person's AI, as word heads | medium-high | word heads already score from text; the report is new | | | VF5 | the vocabulary loop with the person's AI, as word heads | medium-high | word heads already score from text; the report is new |
| | VF6 | the shot vocabulary (clusters named from the vocabulary) | medium | clustering is plain; naming quality varies by domain | | | VF6 | the shot vocabulary (clusters named from the vocabulary) | medium | clustering is plain; naming quality varies by domain |
| | VF7 | the structure template | medium | alignment across varied videos is the hard part | | | VF7 | the structure template | medium | alignment across varied videos is the hard part |
| | VF8 | event rules into the videoform's rules, with strength, confirmed by the person; `raea check` holds them | medium | co-occurrence is plain; telling habit from style needs the person | | | VF8 | event rules into controller rules, with strength, confirmed by the person | medium | co-occurrence is plain; telling habit from style needs the person |
| | VF8b | when it doesn't hold together: too few, mixed kinds (split into videoforms), traits that vary, outliers | medium-high | groups and spreads come from the kept rows | | | VF8b | when it doesn't hold together: too few, mixed kinds (split into videoforms), traits that vary, outliers | medium-high | groups and spreads come from the kept rows |
| | VF8c | adding and removing references from kept rows; encoder pins and `refresh` | high | Fingerprint keeps evidence across upgrades the same way (FP8c) | | | VF8c | adding and removing references from kept rows; encoder pins and `refresh` | high | Fingerprint keeps evidence across upgrades the same way (FP8c) |
| 3, use | VF9 | following: context, coverage gaps, planning to the template | medium-high | context and scripts exist | | 3, use | VF9 | following: context, coverage gaps, planning to the template | medium-high | context and scripts exist |
+2 -36
View File
@@ -1,10 +1,9 @@
// The component library (sdk/raea/library/components, catalog.ts): every listed file is there, every relative import // The component library (sdk/raea/library/components, catalog.ts): every listed file is there, every relative import
// in it lands on a file of the library, nothing imports another video framework, the search finds by use and by the // in it lands on a file of the library, nothing imports another video framework, and the search finds by use.
// words people ask with, and each item carries what an agent picks by (tools/library-meta.sh writes it).
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { existsSync, readFileSync } from "node:fs"; import { existsSync, readFileSync } from "node:fs";
import { dirname, join, normalize } from "node:path"; import { dirname, join, normalize } from "node:path";
import { listed, searched, shown, terms, type Item } from "../src/catalog"; import { listed, type Item } from "../src/catalog";
const lib = join(import.meta.dir, "../../../sdk/raea/library/components"); const lib = join(import.meta.dir, "../../../sdk/raea/library/components");
const cat = JSON.parse(readFileSync(join(lib, "catalog.json"), "utf8")) as { sources: Record<string, { licence: string }>; items: Item[] }; const cat = JSON.parse(readFileSync(join(lib, "catalog.json"), "utf8")) as { sources: Record<string, { licence: string }>; items: Item[] };
@@ -46,37 +45,4 @@ describe("the component library", () => {
expect(listed(cat.items, ["count", "up"]).split("\n")[0]).toContain("count"); expect(listed(cat.items, ["count", "up"]).split("\n")[0]).toContain("count");
expect(listed(cat.items, ["zzqx"])).toContain("no component in the library"); expect(listed(cat.items, ["zzqx"])).toContain("no component in the library");
}); });
test("each item says what it draws, when to use it and not, how it's asked for, and its props", () => {
const thin = cat.items.filter((i) => !i.what || !i.use_when?.length || !i.avoid_when?.length || !i.asked_as?.length || !Array.isArray(i.props) || !i.aspect);
expect(thin.map((i) => i.name)).toEqual([]);
// its props are the ones its file declares
const flash = cat.items.find((i) => i.name === "flash-count")!;
expect(flash.props!.find((p) => p.name === "value")).toMatchObject({ type: "number", default: "3600" });
});
test("its words name no other library or its tooling: the components are raea's", () => {
const named = cat.items.flatMap((i) => [i.what ?? "", ...(i.use_when ?? []), ...(i.avoid_when ?? [])].filter((s) => /\b(remotion|remocn|snapcn|snap-cn|shadcn)\b/i.test(s)).map((s) => `${i.name}: ${s}`));
expect(named).toEqual([]);
});
test("search by the words people use: a product's UI, a composer, a chat input, a template, an AI prompt", () => {
const top = (q: string, n = 3) => searched(cat.items, terms([q])).slice(0, n).map((i) => `${i.category}/${i.name}`);
expect(top("claude code").every((n) => /terminal|agent/.test(n))).toBe(true);
expect(top("composer")).toEqual(expect.arrayContaining(["ui/prompt-send"]));
expect(top("chat input", 5)).toEqual(expect.arrayContaining(["ui/input", "ui/prompt-send"]));
expect(top("AI prompt").every((n) => n.startsWith("ui/prompt-"))).toBe(true);
expect(top("composer animations with claude")).toEqual(expect.arrayContaining(["ui/prompt-send"]));
// the upstream name is a search alias: snapcn's terminal-simulator is ui/terminal-session here
expect(top("terminal simulator", 2).sort()).toEqual(["ui/terminal-session", "ui/terminal-simulator"]);
// "template" alone: the items that are one, and how to narrow it
expect(listed(cat.items, ["template"])).toContain("say what it shows to narrow it");
expect(listed(cat.items, ["cli"])).not.toContain("click-type");
});
test("show: one item in full, with its props and when to use it", () => {
const i = cat.items.find((i) => i.name === "prompt-send")!;
const s = shown(i);
for (const want of ["ui/prompt-send", "use it when:", "not when:", "props:", "text?: string", "raea make component add prompt-send", 'import { PromptSend } from "./components/ui/prompt-send"']) expect(s).toContain(want);
});
}); });
+2 -2
View File
@@ -14,8 +14,8 @@ pub const GOAL_TS: &[&str] = &["check", "tasks", "seen", "judge"];
/// The goal verbs' usage, under the help's (usage.rs reads each verb's flags from it). /// The goal verbs' usage, under the help's (usage.rs reads each verb's flags from it).
pub const GOAL_USAGE: &str = "raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish) pub const GOAL_USAGE: &str = "raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base) raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
raea goal seen FILE [\"what you see and would change\" --look \"its design at full size, beside a reference\"] [--surprise \"SECONDS s: what it is\"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size) raea goal seen FILE [\"what you see and would change\"] [--surprise \"SECONDS s: what it is\"] (FILE's contact sheet beside it, to look at every frame; with words, what was seen of FILE as it is now)
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude) raea goal judge [--goal NAME] [--by claude|kimi] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)"; raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)";
/// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an /// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an
+24 -88
View File
@@ -6,15 +6,7 @@
import { existsSync, readFileSync, realpathSync } from "node:fs"; import { existsSync, readFileSync, realpathSync } from "node:fs";
import { dirname, join } from "node:path"; import { dirname, join } from "node:path";
/** One of a component's props, read from its Props type: its type as written, its default, a line on what it does */ export type Item = { name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string };
export type Prop = { name: string; type: string; default?: string; says?: string; required?: boolean };
/** An item; the fields after `from` are tools/library-meta.sh's: the upstream component it was matched to by content
* (a search alias, never its name here), what it draws and how it moves, when to use it and when not, the phrases
* people ask for it with, its props, and the length, frame rate, size, aspect and feel it was designed at */
export type Item = {
name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string;
upstream?: string; what?: string; use_when?: string[]; avoid_when?: string[]; asked_as?: string[]; props?: Prop[]; length?: number; fps?: number; size?: string; aspect?: string; vibe?: string;
};
type Catalog = { sources: Record<string, { url: string; licence: string }>; items: Item[] }; type Catalog = { sources: Record<string, { url: string; licence: string }>; items: Item[] };
export type Got = { item: Item; licence: string; files: Record<string, string> }; export type Got = { item: Item; licence: string; files: Record<string, string> };
@@ -25,9 +17,6 @@ function home(raea: string, env: Record<string, string | undefined>): string | u
return [env.RAEA_HOME && join(env.RAEA_HOME, rel), join(bin, "../share/raea", rel), join(bin, "../..", rel)].find((p) => p && existsSync(join(p, "catalog.json"))); return [env.RAEA_HOME && join(env.RAEA_HOME, rel), join(bin, "../share/raea", rel), join(bin, "../..", rel)].find((p) => p && existsSync(join(p, "catalog.json")));
} }
/** An item by its name, category/name or category/type/name */
export const found = (items: Item[], want: string) => items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
/** Host op "components": {op: "list"} is every item, {op: "get", name} one item with its files' text (by its path in /** Host op "components": {op: "list"} is every item, {op: "get", name} one item with its files' text (by its path in
* the library, which is its path under components/). No library beside this raea: an empty list, and no item. */ * the library, which is its path under components/). No library beside this raea: an empty list, and no item. */
export function componentsHost(raea: string, env: Record<string, string | undefined>, a: Record<string, unknown>): Item[] | Got | null { export function componentsHost(raea: string, env: Record<string, string | undefined>, a: Record<string, unknown>): Item[] | Got | null {
@@ -36,99 +25,46 @@ export function componentsHost(raea: string, env: Record<string, string | undefi
const cat = JSON.parse(readFileSync(join(dir, "catalog.json"), "utf8")) as Catalog; const cat = JSON.parse(readFileSync(join(dir, "catalog.json"), "utf8")) as Catalog;
if (a.op !== "get") return cat.items; if (a.op !== "get") return cat.items;
const want = String(a.name).replace(/^\/+|\/+$/g, ""); const want = String(a.name).replace(/^\/+|\/+$/g, "");
const item = found(cat.items, want); const item = cat.items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
if (!item) return null; if (!item) return null;
const files = Object.fromEntries([...item.files, ...item.needs].map((f) => [f, readFileSync(join(dir, f), "utf8")])); const files = Object.fromEntries([...item.files, ...item.needs].map((f) => [f, readFileSync(join(dir, f), "utf8")]));
return { item, licence: cat.sources[item.from]?.licence ?? "", files }; return { item, licence: cat.sources[item.from]?.licence ?? "", files };
} }
// what a row says: the item's own line, or what it draws when that line is a few words const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${i.says.split(". ")[0].slice(0, 110)}`;
const line = (i: Item) => (i.says.length >= 40 || !i.what ? i.says : i.what).split(". ")[0];
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${line(i).slice(0, 110)}`;
// words that say nothing about which one ("a", "animation", "component") are skipped; "template", "effect" and
// "preset" narrow to the items that are one when they're all a search says, and only rank otherwise
const FILLER = new Set(["a", "an", "the", "with", "for", "of", "and", "in", "on", "to", "my", "our", "some", "please", "use", "using", "raea", "component", "components", "animation", "animations", "animated", "thing", "something", "from", "like", "one"]);
const SOFT = new Set(["template", "templates", "effect", "effects", "preset", "presets"]);
const esc = (w: string) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// a word at a word's start ("count" finds "counter"); a short one only whole ("cli" isn't "click", "ai" isn't "aim")
const finds = (w: string) => (w.length <= 3 ? new RegExp(`(^|[^a-z0-9])${esc(w)}(s|es)?($|[^a-z0-9])`, "i") : new RegExp(`(^|[^a-z0-9])${esc(w.replace(/s$/, ""))}`, "i"));
/** How well an item answers the words: 0 when a word that matters isn't anywhere in it. The name, the upstream name
* and the phrases people ask for it with count most; what it does and when to use it count once */
export function scored(i: Item, ws: string[]): number {
const asked = (i.asked_as ?? []).join(" | ");
const told = [i.says, i.what ?? "", ...(i.use_when ?? [])].join(" ");
const named = (n: string | undefined, w: string) => (!n ? 0 : n.split("-").includes(w) ? 3 : w.length > 3 && n.includes(w) ? 2 : 0);
const key = ws.filter((w) => !SOFT.has(w));
let s = 0;
// the words together, as written: a phrase people ask with, a name, or a sentence of what it does
const phrase = key.join(" ");
if (key.length > 1) s += (i.asked_as ?? []).some((a) => a.toLowerCase().includes(phrase)) ? 6 : [i.name, i.upstream ?? ""].includes(key.join("-")) ? 6 : told.toLowerCase().includes(phrase) ? 3 : 0;
for (const w of ws) {
const [c, t] = w.split("/");
const re = finds(w);
let got = 0;
if (w.includes("/")) got = i.category === c && (!t || i.type === t) ? 4 : 0;
else if (i.category === w || i.type === w) got = 4;
// its name (or upstream's), the phrases it's asked for with, and its own words each add
else got = Math.max(named(i.name, w), named(i.upstream, w)) + (re.test(asked) ? 3 : 0) + (re.test(told) || i.from === w ? 1 : 0);
if (!got && !SOFT.has(w)) return 0;
s += got;
}
return s;
}
/** `raea make component list`'s lines for the library: with no words, each category and its types; with words, the /** `raea make component list`'s lines for the library: with no words, each category and its types; with words, the
* items they name. A word is a category ("text"), a category/type ("text/reveal"), a name or upstream name, or * items they name. A word is a category ("text"), a category/type ("text/reveal"), or anything in a name or in what
* anything in the phrases people ask with, what it does or when to use it; every word that matters must be found */ * an item does; every word must be found, and a name's own words count first. */
export function listed(items: Item[], words: string[]): string { export function listed(items: Item[], words: string[]): string {
if (!items.length) return ""; if (!items.length) return "";
const ws = terms(words); if (!words.length) {
if (!ws.length) {
const cats = [...new Set(items.map((i) => i.category))].sort(); const cats = [...new Set(items.map((i) => i.category))].sort();
const line = (c: string) => { const line = (c: string) => {
const of = items.filter((i) => i.category === c); const of = items.filter((i) => i.category === c);
const types = [...new Set(of.map((i) => i.type))].sort().map((t) => `${t} ${of.filter((i) => i.type === t).length}`); const types = [...new Set(of.map((i) => i.type))].sort().map((t) => `${t} ${of.filter((i) => i.type === t).length}`);
return `${c.padEnd(14)} ${String(of.length).padStart(3)} ${types.join(", ")}`; return `${c.padEnd(14)} ${String(of.length).padStart(3)} ${types.join(", ")}`;
}; };
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "chat input", list "count up"; show NAME tells one in full; add NAME copies one):\n${cats.map(line).join("\n")}\n`; return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "count up"; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
} }
const found = searched(items, ws); const ws = words.join(" ").toLowerCase().split(/\s+/).filter(Boolean);
const phrase = ws.join(" ");
const score = (i: Item) => {
// the words together, as written, in what it does: ahead of the same words scattered
let s = ws.length > 1 && i.says.toLowerCase().includes(phrase) ? 3 : 0;
for (const w of ws) {
const [c, t] = w.split("/");
if (w.includes("/") ? i.category === c && (!t || i.type === t) : i.category === w || i.type === w) s += 4;
else if (i.name.split("-").includes(w)) s += 3;
else if (i.name.includes(w)) s += 2;
else if (i.says.toLowerCase().includes(w)) s += 1;
else return 0;
}
return s;
};
const found = items.map((i) => [score(i), i] as const).filter(([s]) => s > 0).sort((a, b) => b[0] - a[0] || a[1].name.localeCompare(b[1].name));
if (!found.length) return `no component in the library for "${words.join(" ")}" (raea make component list shows the categories)\n`; if (!found.length) return `no component in the library for "${words.join(" ")}" (raea make component list shows the categories)\n`;
// "template" or "effect" alone: the items that are one, a page of them, and how to narrow it return found.map(([, i]) => row(i)).join("\n") + "\n";
if (ws.every((w) => SOFT.has(w))) {
const top = found.slice(0, 30);
return `${found.length} components are a ${ws[0].replace(/s$/, "")}; say what it shows to narrow it (list ${ws[0]} chat, list ${ws[0]} logo, list "${ws[0]} product demo"):\n${top.map(row).join("\n")}\n${found.length > top.length ? `... and ${found.length - top.length} more\n` : ""}`;
}
return found.map(row).join("\n") + "\n";
}
/** A search's words that matter, in lower case */
export const terms = (words: string[]) => words.join(" ").toLowerCase().split(/\s+/).filter((w) => w && !FILLER.has(w));
/** The items the words find, best first */
export function searched(items: Item[], ws: string[]): Item[] {
// equal scores: the one more of whose asked-for phrases the words are in is more about them
const res = ws.filter((w) => !w.includes("/")).map(finds);
const fit = (i: Item) => (i.asked_as ?? []).filter((a) => res.some((re) => re.test(a))).length;
return items
.map((i) => [scored(i, ws), fit(i), i] as const)
.filter(([s]) => s > 0)
.sort((a, b) => b[0] - a[0] || b[1] - a[1] || a[2].name.localeCompare(b[2].name))
.map(([, , i]) => i);
}
/** `raea make component show NAME`: everything an agent picks by, without opening the file */
export function shown(i: Item, from = "./components"): string {
const list = (head: string, xs?: string[]) => (xs?.length ? `${head}\n${xs.map((x) => ` - ${x}`).join("\n")}\n` : "");
const made = [i.size && `${i.size} (${i.aspect})`, !i.size && i.aspect, i.length && `${i.length} frames at ${i.fps ?? 30} fps`, i.vibe && `feels ${i.vibe}`].filter(Boolean).join(", ");
const props = (i.props ?? []).map((p) => ` ${p.name}${p.required ? "" : "?"}: ${p.type}${p.default !== undefined ? ` = ${p.default}` : ""}${p.says ? `\n ${p.says}` : ""}`);
return `${i.category}/${i.name} (${i.type}; from ${i.from}${i.upstream ? `, ${i.upstream} there` : ""})
${i.what ?? i.says}
${list("use it when:", i.use_when)}${list("not when:", i.avoid_when)}${i.asked_as?.length ? `asked for as: ${i.asked_as.join("; ")}\n` : ""}${made ? `designed at: ${made}\n` : ""}${props.length ? `props:\n${props.join("\n")}\n` : "props: none (its words and colours are written in the file)\n"}add it: raea make component add ${i.name}
import ${i.default ? i.component : `{ ${i.component} }`} from "${from}/${i.category}/${i.name}";
`;
} }
/** What `add` says of a copied item: where it is, how to import it, the fonts it loads, whose it was */ /** What `add` says of a copied item: where it is, how to import it, the fonts it loads, whose it was */
+5 -6
View File
@@ -136,7 +136,7 @@ pub fn run(args: &[String]) -> R<String> {
IN_HELP.set(was); IN_HELP.set(was);
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage // `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage
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 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] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --choose LABEL FILE... --choose LABEL FILE... [--recommend N] | 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), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --choose LABEL FILE... once per option (2 to 6) for the person to pick one, --recommend N the one you would (nothing is picked for them), their pick back as {{\"kind\":\"answer\",\"choice\":LABEL}}; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; 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)"); let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | 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), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; 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)");
// clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts // clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts
let usage = format!("{usage}\n raea make clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder, and the first use of any step makes the Python environment the clothes run in there (by uv); no step needs Blender)"); let usage = format!("{usage}\n raea make clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder, and the first use of any step makes the Python environment the clothes run in there (by uv); no step needs Blender)");
// body motion made by Kimodo, on MLX on a Mac and on PyTorch elsewhere (docs/character.feature CH15c): // body motion made by Kimodo, on MLX on a Mac and on PyTorch elsewhere (docs/character.feature CH15c):
@@ -146,10 +146,10 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run] (a bug in raea itself, not in your own composition, sent to raea's server with raea's version and the OS, no account needed: words only, paths, emails and keys taken out before it goes; five a day from a machine, the same bug again counted on the first report; --dry-run prints what would go and sends nothing)"); let usage = format!("{usage}\n raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run] (a bug in raea itself, not in your own composition, sent to raea's server with raea's version and the OS, no account needed: words only, paths, emails and keys taken out before it goes; five a day from a machine, the same bug again counted on the first report; --dry-run prints what would go and sends nothing)");
let usage = format!("{usage}\n {} ({})\n {} ({})", raea_sys_fixes::USAGE, raea_sys_fixes::ABOUT, raea_app_voice::USAGE, raea_app_voice::ABOUT); // a problem looked up before it's guessed at (systems/fixes); speech to speech (apps/voice) let usage = format!("{usage}\n {} ({})\n {} ({})", raea_sys_fixes::USAGE, raea_sys_fixes::ABOUT, raea_app_voice::USAGE, raea_app_voice::ABOUT); // a problem looked up before it's guessed at (systems/fixes); speech to speech (apps/voice)
// a workspace's files and specs (docs/projects.feature), listed under render's usage like library // 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|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\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 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 {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::forma::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE); let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\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 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 {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE); let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
let apps = format!(" {}\n {}\n {}\n {}\n {}\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_ask::USAGE, format!("{GOAL_USAGE}\n {}", raea_app_make::USAGE), raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE); let apps = format!(" {}\n {}\n {}\n {}\n {}\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_ask::USAGE, format!("{GOAL_USAGE}\n {}", raea_app_make::USAGE), raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
return Ok(usage::under_make(&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 words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\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 make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, \"count up\", \"chat input\", template; show tells one in full: what it draws, when to use it and when not, its props)\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 {} ({})\n {capcut}\n {layers}\n {xml}\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 {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\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 {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\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)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE))); return Ok(usage::under_make(&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 words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\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 make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, \"count up\")\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 {} ({})\n {capcut}\n {layers}\n {xml}\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 {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\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 {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\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)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
} }
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6) // `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") { if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
@@ -196,8 +196,7 @@ pub fn run(args: &[String]) -> R<String> {
if args[0] == "setup" && args.get(1).map(String::as_str) == Some("motion") { if args[0] == "setup" && args.get(1).map(String::as_str) == Some("motion") {
return tools::motion::setup(&args[2..]); return tools::motion::setup(&args[2..]);
} }
// `setup blender|godot|forma`, `blender ...`, `godot ...` and `forma ...`: Blender and Godot scripted, forma run (SK11, // `setup blender|godot`, `blender ...` and `godot ...`: Blender and Godot scripted (SK11, apps/engines)
// apps/engines, apps/forma)
if let Some(done) = raea_app_engines::cli(args) { if let Some(done) = raea_app_engines::cli(args) {
return done; return done;
} }
@@ -385,7 +384,7 @@ pub fn run(args: &[String]) -> R<String> {
} }
if args.first().map(String::as_str) != Some("render") || args.len() < 2 { if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
return Err(format!( return Err(format!(
"raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--keys keys.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it) "raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|share|lod|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help) raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|share|lod|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help)
raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea make sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)", raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea make sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)",
tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE
+8 -21
View File
@@ -28,7 +28,7 @@ import { absolute, fromCwd, labelsIn, showVerb } from "./show";
// `raea make clothes` (clothes.ts): garments for SOMA's body from words // `raea make clothes` (clothes.ts): garments for SOMA's body from words
import { clothesVerb } from "./clothes"; import { clothesVerb } from "./clothes";
// the component library (catalog.ts): open components sorted by use, listed and copied by `raea make component` // the component library (catalog.ts): open components sorted by use, listed and copied by `raea make component`
import { added, found, listed, searched, shown as inFull, terms, type Got, type Item } from "./catalog"; import { added, listed, type Got, type Item } from "./catalog";
// `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server // `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server
import { bugVerb } from "./bug"; import { bugVerb } from "./bug";
@@ -80,14 +80,11 @@ A video edit as a React + TypeScript project, rendered by raea.
- cuts.ts: the clips (\`raea cut\` writes it, with cuts.json and words.json beside it; re-run it rather than editing - cuts.ts: the clips (\`raea cut\` writes it, with cuts.json and words.json beside it; re-run it rather than editing
by hand, or captions and checks lose their timing). components/: components you added (\`raea make component add\`), yours to change. by hand, or captions and checks lose their timing). components/: components you added (\`raea make component add\`), yours to change.
- brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from the brand's site). edit.tsx loads them with the project's - brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from the brand's site). edit.tsx loads them with the project's
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). The brand's colours and Tailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). Style only with the brand
faces are the palette, as classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg), classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg), text-brand-on-surface,
text-brand-on-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body (where text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body; size text-display,
the brand's face is missing, install a free face close to it, never a system fallback); the --brand-* variables text-title, text-caption, text-body, text-label (scaled for a 1080-wide frame); corners rounded-brand. Where a
where a class can't reach. Never a colour from outside the brand. The design is yours: size, weight, shape, layout class can't reach, the --brand-* variables. Never a colour, font or size of your own.
and motion are chosen for this piece, against how the brand's own best work looks, not from a default. The sizes
text-display, text-title, text-caption, text-body, text-label (scaled for a 1080-wide frame) and rounded-brand are
a start, not a limit.
- \`raea render edit.tsx -o final.mp4 --manifest render.json\`, then \`raea check final.mp4 --manifest render.json - \`raea render edit.tsx -o final.mp4 --manifest render.json\`, then \`raea check final.mp4 --manifest render.json
--words words.json --perception perception.json\` says what's wrong; \`raea render edit.tsx --at 105 -o stills/\` --words words.json --perception perception.json\` says what's wrong; \`raea render edit.tsx --at 105 -o stills/\`
gives frame 105 to look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX); gives frame 105 to look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX);
@@ -199,18 +196,8 @@ export function raeaHandler(host?: Host, engine?: Engine) {
// the library beside this raea (none in a shell with no host: raea's own sets are all it lists) // the library beside this raea (none in a shell with no host: raea's own sets are all it lists)
const shelf = (): Item[] => (host ? (host("components", { op: "list" }) as Item[]) : []); const shelf = (): Item[] => (host ? (host("components", { op: "list" }) as Item[]) : []);
if (args[1] === undefined) return out(parts() + listed(shelf(), []), 0, was); if (args[1] === undefined) return out(parts() + listed(shelf(), []), 0, was);
const ws = clean(args.slice(2)); if (args[1] === "list") return out(clean(args.slice(2)).length ? listed(shelf(), clean(args.slice(2))) : parts() + listed(shelf(), []), 0, was);
// --json: the items found (each with its props, when to use it and when not) for an agent to pick from if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force]\n`);
if (args[1] === "list" && args.includes("--json")) return out(`${JSON.stringify(ws.length ? searched(shelf(), terms(ws)) : shelf(), null, 1)}\n`, 0, was);
if (args[1] === "list") return out(ws.length ? listed(shelf(), ws) : parts() + listed(shelf(), []), 0, was);
// show: one item in full, so it can be picked without opening its file
if (args[1] === "show") {
const item = ws[0] ? found(shelf(), ws[0]) : undefined;
if (!item) return out("", 1, `${was}raea make component show: no "${ws[0] ?? ""}" in the library (raea make component list WORDS finds one)\n`);
const at = (await c.fs.exists(p("compositions"))) ? "../components" : "./components";
return out(args.includes("--json") ? `${JSON.stringify(item, null, 1)}\n` : inFull(item, at), 0, was);
}
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] [--json] | show NAME [--json] | add NAME ... [--shared] [--force]\n`);
const names = clean(args.slice(2)); const names = clean(args.slice(2));
if (!names.length) return out("", 2, `${was}raea make component add NAME ... (raea make component list shows them)\n`); if (!names.length) return out("", 2, `${was}raea make component add NAME ... (raea make component list shows them)\n`);
const force = args.includes("--force"); const force = args.includes("--force");
+1 -1
View File
@@ -221,7 +221,7 @@ function cut(a: { take: string; lines: string[]; spans: number[][]; keep: Clip[]
return { edit, cuts: clips, words: timeline, perception: perception(edit, clips), said: [head, ...said, ...notes.map((n) => `note: ${n}`)].join("\n") }; return { edit, cuts: clips, words: timeline, perception: perception(edit, clips), said: [head, ...said, ...notes.map((n) => `note: ${n}`)].join("\n") };
} }
/** raea-perceive, as `raea song` finds it (raea-io-assets perceive_bin): $RAEA_PERCEIVE, else beside raea, else on PATH */ /** raea-perceive, as `raea song` finds it (runtime/react/src/runtime/page/src/faces.rs perceive_bin): $RAEA_PERCEIVE, else beside raea, else on PATH */
function perceive(): string { function perceive(): string {
// raea's path (a bare name, as a test may pass, is found on PATH) // raea's path (a bare name, as a test may pass, is found on PATH)
const self = raea.includes("/") ? raea : (process.env.PATH ?? "").split(delimiter).map((d) => `${d}/${raea}`).find((p) => existsSync(p)) ?? raea; const self = raea.includes("/") ? raea : (process.env.PATH ?? "").split(delimiter).map((d) => `${d}/${raea}`).find((p) => existsSync(p)) ?? raea;
+4 -29
View File
@@ -32,9 +32,6 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
raea show FILE... --fyi raea show FILE... --fyi
Only for the person to look at, nothing to approve: they say Got it (you hear {"kind":"seen"}), and anything they Only for the person to look at, nothing to approve: they say Got it (you hear {"kind":"seen"}), and anything they
want to say back comes through the chat. Without it a show is a version for them to approve or send notes on. want to say back comes through the chat. Without it a show is a version for them to approve or send notes on.
raea show --choose "Warm grade" A.png B.png --choose "Cool grade" C.png [--recommend 2] [--title T] [--ask TEXT]
The person picks one: 2 to 6 options, each named, its files after it. --recommend N marks the one you'd pick (from
1); nothing is picked for them. Their pick comes back as {"kind":"answer","choice":"Cool grade"}.
raea show --group "Day: sun through the doors" A.png B.png --group "Night: practicals only" C.png [--title T] raea show --group "Day: sun through the doors" A.png B.png --group "Night: practicals only" C.png [--title T]
Lay the files out in groups the person sees side by side, each titled before the colon and said after it in a plain Lay the files out in groups the person sees side by side, each titled before the colon and said after it in a plain
line (never shorthand); the files after a --group are its own. Keep it short: enough to know what each group is. line (never shorthand); the files after a --group are its own. Keep it short: enough to know what each group is.
@@ -61,7 +58,7 @@ raea show FILE... --replaces ITEM --done ID...
closes when the person retires it, never with --done. raea notes post sends all of these from the notes. closes when the person retires it, never with --done. raea notes post sends all of these from the notes.
`; `;
const WITH_VALUE = new Set(["--group", "--choose", "--recommend", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]); const WITH_VALUE = new Set(["--group", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const FLAGS = new Set(["--open", "--fyi", "--playable"]); const FLAGS = new Set(["--open", "--fyi", "--playable"]);
/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts /** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
@@ -121,26 +118,6 @@ export function parseShow(args: string[], cwd: string) {
}); });
const empty = groups.find((g) => !g.files.length); const empty = groups.find((g) => !g.files.length);
if (empty) throw new Error(`the group "${empty.title}" has no files: put its files after its --group\n${SHOW_USAGE}`); if (empty) throw new Error(`the group "${empty.title}" has no files: put its files after its --group\n${SHOW_USAGE}`);
// the options to choose from (raea-platform home.feature HM5): each --choose "Label" holds the files after it
const options: { label: string; files: string[]; recommended?: true }[] = [];
args.forEach((a, i) => {
if (a === "--choose" && args[i + 1] !== undefined) options.push({ label: args[i + 1].trim(), files: [] });
else if (a === "--group" && options.length) throw new Error(`--choose and --group don't mix: each option is its own group\n${SHOW_USAGE}`);
else if (options.length && isFile(a, i)) options.at(-1)!.files.push(abs(a));
});
if (options.length) {
if (options.length < 2 || options.length > 6) throw new Error(`--choose gives 2 to 6 options, each with its files\n${SHOW_USAGE}`);
const bare = options.find((o) => !o.label || !o.files.length);
if (bare) throw new Error(`the option "${bare.label}" ${bare.label ? "has no files: put its files after its --choose" : "needs a name"}\n${SHOW_USAGE}`);
if (files.length !== options.flatMap((o) => o.files).length) throw new Error(`with --choose, every file goes after the option it's in\n${SHOW_USAGE}`);
if (args.includes("--question") || args.includes("--fyi")) throw new Error(`--choose is its own question: no --question or --fyi with it\n${SHOW_USAGE}`);
}
const recommend = one("--recommend");
if (recommend !== undefined) {
const n = Number(recommend);
if (!options.length || !Number.isInteger(n) || n < 1 || n > options.length) throw new Error(`--recommend N names one of the --choose options, from 1${options.length ? ` to ${options.length}` : ""}\n${SHOW_USAGE}`);
options[n - 1].recommended = true;
}
const despite = args.flatMap((a, i) => { const despite = args.flatMap((a, i) => {
if (a !== "--despite") return []; if (a !== "--despite") return [];
const [check, why] = [args[i + 1], args[i + 2]]; const [check, why] = [args[i + 1], args[i + 2]];
@@ -180,7 +157,7 @@ export function parseShow(args: string[], cwd: string) {
if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`); if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`);
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`); if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`); if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`);
return { groups, options, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") }; return { groups, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
} }
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */ /** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
@@ -241,7 +218,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
a.files = [(ask("playable", { file: a.files[0], cwd }) as { page: string }).page]; a.files = [(ask("playable", { file: a.files[0], cwd }) as { page: string }).page];
a.title ??= a.files[0].replace(/^.*[\\/]/, "").replace(/-preview\.html$/, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase()); a.title ??= a.files[0].replace(/^.*[\\/]/, "").replace(/-preview\.html$/, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
} }
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : a.options.length ? { intent: "choose", options: a.options } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
| { opened: string[] } | { opened: string[] }
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean }; | { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean };
if ("opened" in r) return `The raea app isn't on this Mac, so ${r.opened.length === 1 ? "it opened" : `${r.opened.length} files opened`} in the Mac's own viewer: nothing was posted and nothing comes back. Install raea (raea.io) to show work as items the person can answer.\n`; if ("opened" in r) return `The raea app isn't on this Mac, so ${r.opened.length === 1 ? "it opened" : `${r.opened.length} files opened`} in the Mac's own viewer: nothing was posted and nothing comes back. Install raea (raea.io) to show work as items the person can answer.\n`;
@@ -265,9 +242,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
? `Shown in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}); the window is on it.` ? `Shown in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}); the window is on it.`
: `Posted in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}), with a notice; the window stayed where the person is.`, : `Posted in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}), with a notice; the window stayed where the person is.`,
...settled, ...settled,
a.options.length a.fyi
? `They pick one of ${a.options.length}: {"kind":"answer","choice":"<the option's name>"} comes to ${inbox}. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and carry on with their pick.`
: a.fyi
? `Only to look at: when they've seen it, {"kind":"seen"} comes to ${inbox}; nothing to wait for.` ? `Only to look at: when they've seen it, {"kind":"seen"} comes to ${inbox}; nothing to wait for.`
: `What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`, : `What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
"", "",
+2 -2
View File
@@ -4,7 +4,7 @@
//! `raea --version` the agent reads `raea skill` instead. //! `raea --version` the agent reads `raea skill` instead.
use super::*; use super::*;
pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender and forma MCP servers unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)"; pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)";
/// `raea doctor [--fix] [DIR]` (SK10): what doesn't match this raea, an agent's skill reinstalled by --fix. /// `raea doctor [--fix] [DIR]` (SK10): what doesn't match this raea, an agent's skill reinstalled by --fix.
pub fn doctor(args: &[String]) -> R<String> { pub fn doctor(args: &[String]) -> R<String> {
@@ -117,7 +117,7 @@ pub fn install(args: &[String]) -> R<String> {
if agent == "grokbot" { return tools::agent_grokbot::stage(&to, out); } if agent == "grokbot" { return tools::agent_grokbot::stage(&to, out); }
// every agent's hooks (A5d, SK10), in its own config: --no-hooks leaves it alone // every agent's hooks (A5d, SK10), in its own config: --no-hooks leaves it alone
if !args.iter().any(|a| a == "--no-hooks") { out += &tools::agent_hooks::install(agent)?; } if !args.iter().any(|a| a == "--no-hooks") { out += &tools::agent_hooks::install(agent)?; }
// the MCP servers raea offers (SK11): blender, for a running Blender, and forma (FM6); --no-mcp leaves the agent's servers alone // the MCP servers raea offers (SK11): blender, for a running Blender; --no-mcp leaves the agent's servers alone
if !args.iter().any(|a| a == "--no-mcp") { if !args.iter().any(|a| a == "--no-mcp") {
out += &tools::agent_mcp::offer(agent)?; out += &tools::agent_mcp::offer(agent)?;
out += "\n"; out += "\n";
+1 -1
View File
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str())); let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect(); let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
assert!(missing.is_empty(), "not in raea help: {missing:?}"); assert!(missing.is_empty(), "not in raea help: {missing:?}");
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_playable::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_engines::forma::USAGE, raea_app_lightbake::USAGE] { for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_playable::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
assert!(help.contains(usage), "{usage}"); assert!(help.contains(usage), "{usage}");
} }
} }
+3 -8
View File
@@ -30,11 +30,11 @@ const EXTS: &[&str] = &["", ".ts", ".tsx", ".mts", ".js", ".mjs", ".cjs", ".json
/// `spec` imported from a file in `dir` (`esm`: an import, else a require), to the file it names /// `spec` imported from a file in `dir` (`esm`: an import, else a require), to the file it names
pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String> { pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String> {
let raw = spec.strip_prefix("file://").unwrap_or(spec); let raw = spec.strip_prefix("file://").unwrap_or(spec);
// (a path whole on Windows too, `D:\..`: the React raea ships, found, was asked for again by its path and read as a package's name, #278) if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." {
if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." || Path::new(raw).is_absolute() { let want = if raw.starts_with('/') { PathBuf::from(raw) } else { dir.join(raw) };
let want = if raw.starts_with('/') || Path::new(raw).is_absolute() { PathBuf::from(raw) } else { dir.join(raw) };
return as_file(&want).ok_or_else(|| format!("Cannot find module '{spec}' from {}", dir.display())); return as_file(&want).ok_or_else(|| format!("Cannot find module '{spec}' from {}", dir.display()));
} }
// a package: its name (a scope takes two parts) and the subpath after it
let mut parts = raw.splitn(if raw.starts_with('@') { 3 } else { 2 }, '/'); let mut parts = raw.splitn(if raw.starts_with('@') { 3 } else { 2 }, '/');
let name = if raw.starts_with('@') { format!("{}/{}", parts.next().unwrap_or(""), parts.next().unwrap_or("")) } else { parts.next().unwrap_or("").to_string() }; let name = if raw.starts_with('@') { format!("{}/{}", parts.next().unwrap_or(""), parts.next().unwrap_or("")) } else { parts.next().unwrap_or("").to_string() };
let sub = parts.next().map(|s| format!("./{s}")).unwrap_or_else(|| ".".into()); let sub = parts.next().map(|s| format!("./{s}")).unwrap_or_else(|| ".".into());
@@ -53,11 +53,6 @@ pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String
return Ok(f); return Ok(f);
} }
} }
// a package raea ships, imported by a file with no node_modules of its own: raea's (sdk/app), or a project's brief.ts or scene (#278)
let own = raea_io_home::home().join("sdk/react/js/node_modules").join(&name);
if own.is_dir() {
return package_entry(&own, &sub, esm).ok_or_else(|| format!("Cannot find module '{spec}': {} has no {sub}", own.display()));
}
Err(format!("Cannot find package '{name}' imported from {}", dir.display())) Err(format!("Cannot find package '{name}' imported from {}", dir.display()))
} }
-36
View File
@@ -1,36 +0,0 @@
//! A file importing a package raea ships (raea's own, or a project's with no node_modules) finds it in the React runtime's node_modules (#278): a release has
//! no node_modules above sdk/app, so `raea goal check` ended every render "Cannot find package 'react'". Its own test
//! binary: raea's home is read once a process.
#![cfg(feature = "modules")]
use std::fs;
#[test]
fn raeas_own_file_finds_the_react_raea_ships() {
let home = std::env::temp_dir().join(format!("raea-native-shipped-{}", std::process::id()));
let (pkg, own, theirs) = (home.join("sdk/react/js/node_modules/react"), home.join("sdk/app/src"), std::env::temp_dir().join("raea-native-elsewhere"));
for d in [&pkg, &own] {
fs::create_dir_all(d).unwrap();
}
fs::write(pkg.join("package.json"), r#"{"name":"react","main":"index.js"}"#).unwrap();
fs::write(pkg.join("index.js"), "module.exports = {}").unwrap();
// SAFETY: the one test here, before anything reads the environment
unsafe { std::env::set_var("RAEA_HOME", &home) };
assert_eq!(raea_native::node::resolve_file("react", &own, true).unwrap(), pkg.join("index.js"));
// a project's file with no node_modules of its own gets the same React (brief.ts, a scene it registers): a release's
// render was applied and then failed its checks on "Cannot find package 'react'"
fs::create_dir_all(&theirs).unwrap();
assert_eq!(raea_native::node::resolve_file("react", &theirs, true).unwrap(), pkg.join("index.js"));
// its own copy, when it has one, wins
let mine = theirs.join("node_modules/react");
fs::create_dir_all(&mine).unwrap();
fs::write(mine.join("package.json"), r#"{"name":"react","main":"index.js"}"#).unwrap();
fs::write(mine.join("index.js"), "module.exports = {}").unwrap();
assert_eq!(raea_native::node::resolve_file("react", &theirs, true).unwrap(), mine.join("index.js"));
// a file asked for by its whole path is that file, on Windows too (`D:\..` was read as a package's name)
let whole = pkg.join("index.js");
assert_eq!(raea_native::node::resolve_file(whole.to_str().unwrap(), &theirs, true).unwrap(), whole);
// and a package raea doesn't ship is still not found
assert!(raea_native::node::resolve_file("left-pad", &own, true).unwrap_err().contains("Cannot find package 'left-pad'"));
fs::remove_dir_all(&theirs).ok();
fs::remove_dir_all(&home).ok();
}
+16 -79
View File
@@ -74,88 +74,45 @@ pub fn picture(doc: &mut blitz_dom::BaseDocument, n: blitz_dom::NodeId, w: u32,
node.mark_ancestors_dirty(); node.mark_ancestors_dirty();
} }
/// One reader of a file: its decoder, the frame it gave last (its index and picture), and when it was last asked. /// Video elements' frames: a decoder per file, and the frame each element shows (file, frame index), so a frame
struct Reader { /// already shown isn't decoded again.
dec: Box<dyn raea_io_media::VideoDecoder>,
last: Option<(i64, raea_io_media::Frame)>,
used: u64,
}
/// The most readers one file gets: elements past this many, each at its own place in the file, share the one asked
/// longest ago.
const READERS: usize = 4;
/// How far ahead of its last frame a reader is still the one to read on with (frames): a decoder reads on faster
/// than it seeks.
const AHEAD: i64 = 60;
/// Video elements' frames: a file's readers, and the frame each element shows (file, frame index), so a frame already
/// shown isn't decoded again. One decoder a file made two elements on one clip seek it back and forth: the same
/// frame asked for twice restarted the ffmpeg CLI's decoder at every frame (11-30: 1.66 s a frame on the farm where
/// one element took 0.23 s). So a frame a reader just gave is given again, and an element at another place in the
/// file reads with a reader of its own.
#[derive(Default)] #[derive(Default)]
pub struct Videos { pub struct Videos {
readers: HashMap<std::path::PathBuf, Vec<Reader>>, decoders: HashMap<std::path::PathBuf, Box<dyn raea_io_media::VideoDecoder>>,
shown: HashMap<u64, (std::path::PathBuf, i64)>, shown: HashMap<u64, (std::path::PathBuf, i64)>,
tick: u64,
}
/// Which of a file's readers gives frame `key`: (the reader, whether its last frame is that one). The one that gave
/// it last; else the nearest one behind it within AHEAD; else one that has read nothing; else None (open another, or
/// take the one asked longest ago).
fn pick(last: &[Option<i64>], key: i64) -> Option<(usize, bool)> {
if let Some(i) = last.iter().position(|l| *l == Some(key)) {
return Some((i, true));
}
let behind = last.iter().enumerate().filter_map(|(i, l)| l.filter(|l| *l < key && key - *l <= AHEAD).map(|l| (key - l, i))).min();
behind.map(|(_, i)| (i, false)).or_else(|| last.iter().position(|l| l.is_none()).map(|i| (i, false)))
} }
impl Videos { impl Videos {
/// `v`'s frame at its time, or None when its element shows that frame already. A time past the source's last /// `v`'s frame at its time, or None when its element shows that frame already. A time past the source's last
/// frame (a looped or held clip run long) gives its last frame, as raea-runtime-js's page does. /// frame (a looped or held clip run long) gives its last frame, as raea-runtime-js's page does.
pub fn frame(&mut self, v: &raea_core_wire::tree::VideoAt) -> R<Option<raea_io_media::Frame>> { pub fn frame(&mut self, v: &raea_core_wire::tree::VideoAt) -> R<Option<raea_io_media::Frame>> {
if !self.readers.contains_key(&v.file) { if !self.decoders.contains_key(&v.file) {
self.readers.insert(v.file.clone(), vec![Reader { dec: raea_io_media::open_video(&v.file)?, last: None, used: 0 }]); // RAEA_MEDIA's, the platform's, the portable one, then the ffmpeg CLI, the first that opens it: a WebM is read
// by ffmpeg alone (#113: it was refused, "no video track", where the platform's was the only one asked)
let mut why = Vec::new();
let d = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(&v.file).map_err(|e| why.push(format!("{}: {e}", b.name()))).ok());
let d = d.ok_or_else(|| format!("{}: can't be decoded ({})", v.file.display(), why.join("; ")))?;
self.decoders.insert(v.file.clone(), d);
} }
let rs = self.readers.get_mut(&v.file).unwrap(); let d = self.decoders.get_mut(&v.file).unwrap();
let index = rs[0].dec.index_at(v.at).map(|i| i as i64); let key = d.index_at(v.at).map(|i| i as i64).unwrap_or((v.at * 1e6) as i64 + (1 << 40));
let key = index.unwrap_or((v.at * 1e6) as i64 + (1 << 40));
if self.shown.get(&v.id).is_some_and(|k| k.0 == v.file && k.1 == key) { if self.shown.get(&v.id).is_some_and(|k| k.0 == v.file && k.1 == key) {
return Ok(None); return Ok(None);
} }
self.tick += 1; let f = match d.frame_at(v.at) {
// a source with no frame times has one reader, asked for whatever comes
let i = match index.map(|_| pick(&rs.iter().map(|r| r.last.as_ref().map(|l| l.0)).collect::<Vec<_>>(), key)) {
None => 0,
Some(Some((i, true))) => {
rs[i].used = self.tick;
return Ok(rs[i].last.as_ref().map(|l| l.1.clone()));
}
Some(Some((i, false))) => i,
Some(None) if rs.len() < READERS => {
rs.push(Reader { dec: raea_io_media::open_video(&v.file)?, last: None, used: 0 });
rs.len() - 1
}
Some(None) => rs.iter().enumerate().min_by_key(|(_, r)| r.used).map_or(0, |(i, _)| i),
};
let r = &mut rs[i];
r.used = self.tick;
let f = match r.dec.frame_at(v.at) {
Ok(f) => f, Ok(f) => f,
Err(e) => { Err(e) => {
let i = r.dec.info(); let i = d.info();
let end = (i.duration - 0.5 / i.fps.max(1.0)).max(0.0); let end = (i.duration - 0.5 / i.fps.max(1.0)).max(0.0);
if v.at > end { r.dec.frame_at(end).map_err(|e2| format!("{}: {e2} (asked for {:.3} s: {e})", v.file.display(), v.at))? } else { return Err(format!("{}: {e}", v.file.display())) } if v.at > end { d.frame_at(end).map_err(|e2| format!("{}: {e2} (asked for {:.3} s: {e})", v.file.display(), v.at))? } else { return Err(format!("{}: {e}", v.file.display())) }
} }
}; };
r.last = Some((key, f.clone()));
Ok(Some(f)) Ok(Some(f))
} }
/// `v`'s frame is now its element's picture. /// `v`'s frame is now its element's picture.
pub fn shows(&mut self, v: raea_core_wire::tree::VideoAt) { pub fn shows(&mut self, v: raea_core_wire::tree::VideoAt) {
let Some(d) = self.readers.get_mut(&v.file).and_then(|rs| rs.first_mut()).map(|r| &mut r.dec) else { return }; let Some(d) = self.decoders.get_mut(&v.file) else { return };
let key = d.index_at(v.at).map(|i| i as i64).unwrap_or((v.at * 1e6) as i64 + (1 << 40)); let key = d.index_at(v.at).map(|i| i as i64).unwrap_or((v.at * 1e6) as i64 + (1 << 40));
self.shown.insert(v.id, (v.file, key)); self.shown.insert(v.id, (v.file, key));
} }
@@ -461,23 +418,3 @@ pub fn shots(size: (u32, u32), root: Option<&Path>, fonts: Option<&Path>) -> R<(
} }
Ok(()) Ok(())
} }
#[cfg(test)]
mod readers {
use super::pick;
#[test]
fn a_frame_just_given_is_given_again_and_another_place_gets_its_own_reader() {
// two elements on one clip at one time: the second takes the first's frame
assert_eq!(pick(&[Some(154)], 154), Some((0, true)));
// the next frame reads on with the reader just behind it
assert_eq!(pick(&[Some(154)], 155), Some((0, false)));
// a frame behind every reader, or far ahead, is no reader's: another opens
assert_eq!(pick(&[Some(154)], 153), None);
assert_eq!(pick(&[Some(154)], 154 + super::AHEAD + 1), None);
// of two readers, the nearest behind; a reader that has read nothing only when none is behind
assert_eq!(pick(&[Some(100), Some(790)], 791), Some((1, false)));
assert_eq!(pick(&[Some(100), None], 101), Some((0, false)));
assert_eq!(pick(&[Some(100), None], 900), Some((1, false)));
}
}
-24
View File
@@ -39,30 +39,6 @@ impl BlitzPage {
} }
} }
/// How large each video element is drawn this frame, in page px, with nothing decoded (`render --keys`,
/// docs/cloud-render.feature CR36): its box as drawn (transforms applied, getBoundingClientRect's) times a framed
/// take's punch-in, so a clip's frames are never needed larger than this. None for one with no box yet: its size
/// isn't known, and whoever sizes the clip by these mustn't shrink it.
pub fn drawn_sizes(&mut self, videos: &[raea_core_wire::tree::VideoAt]) -> Vec<(std::path::PathBuf, Option<[f32; 2]>)> {
if videos.is_empty() {
return Vec::new();
}
if let Some((now, _, _)) = self.clock {
let mut docs = self.app.world_mut().non_send_mut::<Docs>();
if let Some(doc) = docs.0.get_mut(&self.page) {
doc.resolve(now);
}
}
videos
.iter()
.map(|v| {
let zoom = v.fit.map_or(1.0, |f| f.scale.max(1.0));
let size = self.client_box(v.id).filter(|b| b[2] > 0.0 && b[3] > 0.0).map(|b| [b[2] * zoom, b[3] * zoom]);
(v.file.clone(), size)
})
.collect()
}
/// Each video element's frame at its time, decoded and set as its picture (`place_picture`). A frame already /// Each video element's frame at its time, decoded and set as its picture (`place_picture`). A frame already
/// shown isn't decoded again. /// shown isn't decoded again.
pub fn place_videos(&mut self, videos: Vec<raea_core_wire::tree::VideoAt>) -> R<()> { pub fn place_videos(&mut self, videos: Vec<raea_core_wire::tree::VideoAt>) -> R<()> {
+1 -17
View File
@@ -3,7 +3,7 @@
// the paddle, three misses or a cleared wall ends it on an EndCard that opens the store. One game, two compositions // the paddle, three misses or a cleared wall ends it on an EndCard that opens the store. One game, two compositions
// (portrait and landscape) so each network's either orientation gets its own layout. Rendered with `raea render`, no // (portrait and landscape) so each network's either orientation gets its own layout. Rendered with `raea render`, no
// one touches it: the paddle follows the ball, and the same file is the video ad. // one touches it: the paddle follows the ball, and the same file is the video ad.
import { AbsoluteFill, Audio, Composition, Sequence, registerRoot, sao, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea"; import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
import { Sphere } from "raea/3d"; import { Sphere } from "raea/3d";
import { LinearRgba, Srgba } from "raea/color"; import { LinearRgba, Srgba } from "raea/color";
import { StandardMaterial } from "raea/pbr"; import { StandardMaterial } from "raea/pbr";
@@ -12,7 +12,6 @@ import { AmbientLight, DirectionalLight } from "raea/light";
import { Transform } from "raea/transform"; import { Transform } from "raea/transform";
import { Camera3d } from "raea/camera"; import { Camera3d } from "raea/camera";
import { EndCard } from "raea/playable"; import { EndCard } from "raea/playable";
import { Sfx, Synth } from "raea/tone";
const FPS = 30; const FPS = 30;
const COLS = 6, ROWS = 4, LIVES = 3; const COLS = 6, ROWS = 4, LIVES = 3;
@@ -22,12 +21,6 @@ const COLORS = ["#ef476f", "#f78c6b", "#06d6a0", "#118ab2"];
interface Game { px: number; bx: number; by: number; vx: number; vy: number; alive: boolean[]; broke: number[]; hit: number; missed: number; lives: number; touched: boolean; over: "" | "won" | "lost" } interface Game { px: number; bx: number; by: number; vx: number; vy: number; alive: boolean[]; broke: number[]; hit: number; missed: number; lives: number; touched: boolean; over: "" | "won" | "lost" }
const INITIAL: Game = { px: 0, bx: 0, by: 0.6, vx: 0.06, vy: 0.1, alive: Array(COLS * ROWS).fill(true), broke: Array(COLS * ROWS).fill(-99), hit: -99, missed: -99, lives: LIVES, touched: false, over: "" }; const INITIAL: Game = { px: 0, bx: 0, by: 0.6, vx: 0.06, vy: 0.1, alive: Array(COLS * ROWS).fill(true), broke: Array(COLS * ROWS).fill(-99), hit: -99, missed: -99, lives: LIVES, touched: false, over: "" };
// its sound (docs/playables.feature PA6): a square blip on the paddle and each brick, a low one on a miss, and a
// generated crack under each brick that breaks
const blip = new Synth({ oscillator: { type: "square" }, envelope: { attack: 0.002, decay: 0.09, sustain: 0, release: 0.05 }, volume: -14 }).toDestination();
const CRACK = sao("short dry ceramic brick crack, arcade game hit, no reverb", { seconds: 0.6 });
const NOTES = ["E6", "C6", "A5", "E5"];
const brickPos = (i: number): [number, number] => [(i % COLS - (COLS - 1) / 2) * (W / COLS), TOP - 0.5 - Math.floor(i / COLS) * 0.5]; const brickPos = (i: number): [number, number] => [(i % COLS - (COLS - 1) / 2) * (W / COLS), TOP - 0.5 - Math.floor(i / COLS) * 0.5];
/** The camera's distance that fits the whole field on a screen of this aspect */ /** The camera's distance that fits the whole field on a screen of this aspect */
@@ -109,15 +102,6 @@ function BrickRush() {
{`👆 Drag to play`} {`👆 Drag to play`}
</div> </div>
) : null} ) : null}
{/* the state shown at a frame is the step's of the frame before (useGameState), so an event stamped f shows at f + 1 */}
<Sfx name="paddle" when={g.hit === now - 1} play={(t) => blip.triggerAttackRelease("C5", "32n", t)} />
<Sfx name="brick" when={last === now - 1} play={(t) => blip.triggerAttackRelease(NOTES[Math.floor(g.broke.indexOf(last) / COLS)] ?? "E5", "16n", t)} />
<Sfx name="miss" when={g.missed === now - 1} play={(t) => blip.triggerAttackRelease("C3", "8n", t, 0.8)} />
{last >= 0 ? (
<Sequence key={last} from={last}>
<Audio src={CRACK} volume={0.5} />
</Sequence>
) : null}
<EndCard show={!!g.over} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle={g.over === "won" ? "300 more levels inside" : "Can you clear the wall?"} cta={g.over === "won" ? "Keep playing" : "Try again"} /> <EndCard show={!!g.over} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle={g.over === "won" ? "300 more levels inside" : "Can you clear the wall?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
</AbsoluteFill> </AbsoluteFill>
); );
-143
View File
@@ -1,143 +0,0 @@
// A playable whose rules are raea/ecs systems (docs/playables.feature PA12): stars fall, a basket catches them, and
// every rule (where a star starts, how it falls, what the basket catches, the score) runs on a World. Natively the
// World's tables are Bevy's, in raea's engine; in the playable they're Bevy's too, carried in the page as wasm, so the
// game plays the same in both. Each frame's state is the World copied and stepped once, with where the person points
// written into it as a resource. Rendered with `raea render`, no one touches it: the basket follows the lowest star.
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
import { createWorld, type World } from "raea/ecs";
import { Sphere } from "raea/3d";
import { LinearRgba, Srgba } from "raea/color";
import { StandardMaterial } from "raea/pbr";
import { Cuboid, Mesh3d } from "raea/mesh";
import { AmbientLight, DirectionalLight } from "raea/light";
import { Transform } from "raea/transform";
import { Camera3d } from "raea/camera";
import { EndCard } from "raea/playable";
const FPS = 30;
const W = 6, TOP = 8; // field: x in [-W/2, W/2], y from 0 (the basket) to TOP
const FOV = 0.733; // radians, vertical
const GOAL = 10, MISSES = 3;
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
/** The game's rules: a World with a basket, the score and misses as resources, and its systems */
function rules(): World {
const w = createWorld();
w.spawn("basket", { x: 0 });
for (const r of ["score", "missed"]) w.resource(r, 0);
for (const r of ["caught", "lost"]) w.resource(r, -99);
// a star every 20 frames, where the frame number puts it
w.system((world, f) => {
if (f % 20 === 0) world.spawn("star", { x: (((f * 7919) % 97) / 97 - 0.5) * (W - 1), y: TOP, v: 0.05 + ((f * 31) % 7) * 0.006 });
});
// the basket eases toward where the person points, or toward the lowest star before they touch
w.system((world) => {
const [b] = world.query("basket");
const x = world.get(b).x as number;
let want = world.resource<number>("aim");
if (typeof want !== "number") {
const low = world.query("star").map((id) => world.get(id)).sort((a, c) => (a.y as number) - (c.y as number))[0];
want = low ? (low.x as number) : 0;
}
world.set(b, { x: clamp(x + clamp(want - x, -0.3, 0.3), -W / 2 + 0.8, W / 2 - 0.8) });
});
// each star falls; the basket catches one at its height, and one past it is missed
w.system((world, f) => {
const bx = world.get(world.query("basket")[0]).x as number;
for (const id of world.query("star")) {
const s = world.get(id);
const y = (s.y as number) - (s.v as number);
if (y < 0.35 && y > -0.15 && Math.abs((s.x as number) - bx) < 0.85) {
world.despawn(id);
world.resource("score", (world.resource<number>("score") ?? 0) + 1);
world.resource("caught", f);
} else if (y < -1) {
world.despawn(id);
world.resource("missed", (world.resource<number>("missed") ?? 0) + 1);
world.resource("lost", f);
} else world.set(id, { y });
}
});
return w;
}
interface Game { w: World; touched: boolean; over: "" | "won" | "lost" }
/** The camera's distance that fits the whole field on a screen of this aspect */
const distance = (aspect: number) => Math.max((TOP + 1.5) / 2, (W + 1) / 2 / aspect) / Math.tan(FOV / 2);
/** A pointer's x on screen, in field units at the basket's depth */
function fieldX(input: FrameInput, width: number, height: number): number | undefined {
const p = input.touches?.[0] ?? input.pointer;
if (!p) return undefined;
const halfH = Math.tan(FOV / 2) * distance(width / height);
return ((p.x / width) * 2 - 1) * halfH * (width / height);
}
const stepFor = (width: number, height: number) => (s: Game, input: FrameInput, frame: number): Game => {
if (s.over) return s;
const touched = s.touched || !!input.pointer?.down || !!input.touches?.length;
const w = s.w.copy();
const x = touched ? fieldX(input, width, height) : undefined;
if (x !== undefined) w.resource("aim", x);
w.step(frame);
const over = (w.resource<number>("score") ?? 0) >= GOAL ? "won" : (w.resource<number>("missed") ?? 0) >= MISSES ? "lost" : "";
return { w, touched, over };
};
const steps = new Map<string, ReturnType<typeof stepFor>>();
const stepOf = (w: number, h: number) => steps.get(`${w}x${h}`) ?? steps.set(`${w}x${h}`, stepFor(w, h)).get(`${w}x${h}`)!;
let first: Game | null = null;
function StarCatch() {
const { width, height } = useVideoConfig();
first ??= { w: rules(), touched: false, over: "" };
const g = useGameState(first, stepOf(width, height));
const now = useCurrentFrame();
const bx = g.w.get(g.w.query("basket")[0]).x as number;
const score = g.w.resource<number>("score") ?? 0;
const missed = g.w.resource<number>("missed") ?? 0;
const pop = Math.max(0, 1 - (now - (g.w.resource<number>("caught") ?? -99)) / 8);
const flash = Math.max(0, 1 - (now - (g.w.resource<number>("lost") ?? -99)) / 12);
const d = distance(width / height);
const s = width / 1080;
return (
<AbsoluteFill style={{ background: `rgb(${12 + 80 * flash}, 16, ${40 + 20 * pop})` }}>
<Camera3d transform={Transform.fromXyz(0, TOP / 2, d).lookingAt([0, TOP / 2, 0])} projection={{ Perspective: { fov: FOV } }} />
<AmbientLight brightness={200} />
<DirectionalLight transform={Transform.fromXyz(2, 10, 6).lookingAt([0, 0, 0])} illuminance={9000} />
<Mesh3d transform={Transform.fromXyz(bx, 0, 0).withScale([1 + 0.2 * pop, 1 - 0.3 * pop, 1])} name="basket">
<Cuboid half_size={[0.8, 0.15, 0.3]} />
<StandardMaterial base_color="#2ec4b6" perceptual_roughness={0.45} />
</Mesh3d>
{g.w.query("star").map((id) => {
const st = g.w.get(id);
return (
<Mesh3d key={id} transform={Transform.fromXyz(st.x as number, st.y as number, 0)} name={`star-${id}`}>
<Sphere radius={0.22} />
<StandardMaterial base_color="#ffd166" emissive={LinearRgba.from(Srgba.hex("#ffd166")).mul(0.7)} />
</Mesh3d>
);
})}
<div style={{ position: "absolute", left: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#f0ebd8" }}>
{`★ ${score} / ${GOAL}`}
</div>
<div style={{ position: "absolute", right: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#ef476f" }}>
{"✕".repeat(missed)}
</div>
{!g.touched ? (
<div style={{ position: "absolute", left: 0, right: 0, bottom: height * 0.12, textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontWeight: 900, fontSize: 64 * s, color: "#ffffff", opacity: 0.6 + 0.4 * Math.sin(now / 5) ** 2 }}>
{"👆 Drag to catch"}
</div>
) : null}
<EndCard show={!!g.over} title={g.over === "won" ? "Ten stars!" : "So close!"} subtitle={g.over === "won" ? "The night sky is waiting" : "Can you catch ten?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
</AbsoluteFill>
);
}
registerRoot(() => (
<>
<Composition id="star-catch-portrait" component={StarCatch} width={1080} height={1920} fps={FPS} durationInFrames={FPS * 40} />
<Composition id="star-catch-landscape" component={StarCatch} width={1920} height={1080} fps={FPS} durationInFrames={FPS * 40} />
</>
));
-1
View File
@@ -5,7 +5,6 @@
pub mod audio; pub mod audio;
pub mod mezz; pub mod mezz;
pub mod mp4box;
#[cfg(feature = "mux")] #[cfg(feature = "mux")]
pub mod remux; pub mod remux;
pub mod samples; pub mod samples;
-73
View File
@@ -1,73 +0,0 @@
//! An MP4 or QuickTime file's boxes, read directly: what `media probe` and the ffmpeg backend take a track's own facts
//! from (its frame times, its sound's rate) without reading the gigabytes of pictures beside them.
use std::io::{Read, Seek, SeekFrom};
use std::path::Path;
/// The boxes inside `b` (a box's payload): (type, payload).
pub fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
let mut out = Vec::new();
let mut i = 0usize;
while i + 8 <= b.len() {
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
let mut hdr = 8;
if size == 1 && i + 16 <= b.len() {
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
hdr = 16;
} else if size == 0 {
size = b.len() - i;
}
if size < hdr || i + size > b.len() {
break;
}
out.push((kind, &b[i + hdr..i + size]));
i += size;
}
out
}
pub fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
}
pub fn be32(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
pub fn be64(b: &[u8], at: usize) -> Option<u64> {
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
}
/// The file's moov box, read alone (mdat can be gigabytes).
pub fn moov_of(path: &Path) -> Option<Vec<u8>> {
let mut f = std::fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
let mut at = 0u64;
loop {
if at + 8 > len {
return None;
}
let mut h = [0u8; 16];
f.seek(SeekFrom::Start(at)).ok()?;
f.read_exact(&mut h[..8]).ok()?;
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
let mut hdr = 8u64;
if size == 1 {
f.read_exact(&mut h[8..]).ok()?;
size = u64::from_be_bytes(h[8..].try_into().ok()?);
hdr = 16;
} else if size == 0 {
size = len - at;
}
if size < hdr {
return None;
}
if &h[4..8] == b"moov" {
let mut m = vec![0u8; usize::try_from(size - hdr).ok().filter(|n| *n <= 256 << 20)?];
f.read_exact(&mut m).ok()?;
return Some(m);
}
at += size;
}
}
+31 -95
View File
@@ -9,8 +9,6 @@ use raea_io_codec::{
Audio, Backend, EncodeOpts, EncodeStats, Frame, Info, R, VideoDecoder, VideoEncoder, as_of, Audio, Backend, EncodeOpts, EncodeStats, Frame, Info, R, VideoDecoder, VideoEncoder, as_of,
}; };
mod mov;
pub struct Ffmpeg; pub struct Ffmpeg;
/// The ffmpeg or ffprobe to run: the PATH's, else raea's own (raea_io_assets::ffmpeg_tool). Opening a video (`fetch`) /// The ffmpeg or ffprobe to run: the PATH's, else raea's own (raea_io_assets::ffmpeg_tool). Opening a video (`fetch`)
@@ -52,86 +50,17 @@ fn says(option: &str) -> String {
/// phone): libx264 where ffmpeg was built with it (Homebrew's, Linux distributions'), else the system's own (Windows' /// phone): libx264 where ffmpeg was built with it (Homebrew's, Linux distributions'), else the system's own (Windows'
/// Media Foundation, h264_mf, in the LGPL build raea ships there; macOS's VideoToolbox) at 8 Mb/s; None without one. /// Media Foundation, h264_mf, in the LGPL build raea ships there; macOS's VideoToolbox) at 8 Mb/s; None without one.
pub fn h264() -> Option<Vec<&'static str>> { pub fn h264() -> Option<Vec<&'static str>> {
let enc = listed()?; static ENCODERS: std::sync::OnceLock<String> = std::sync::OnceLock::new();
let have = ENCODERS.get_or_init(|| says("-encoders"));
let has = |c: &str| have.split_whitespace().any(|w| w == c);
let enc = ["libx264", "h264_mf", "h264_videotoolbox"].into_iter().find(|c| has(c))?;
let rate: &[&'static str] = if enc == "libx264" { &[] } else { &["-b:v", "8M"] }; let rate: &[&'static str] = if enc == "libx264" { &[] } else { &["-b:v", "8M"] };
Some([&["-c:v", enc][..], rate, &["-pix_fmt", "yuv420p"]].concat()) Some([&["-c:v", enc][..], rate, &["-pix_fmt", "yuv420p"]].concat())
} }
/// The first of libx264, Media Foundation's and VideoToolbox's H.264 encoders this machine's ffmpeg lists
fn listed() -> Option<&'static str> {
["libx264", "h264_mf", "h264_videotoolbox"].into_iter().find(|c| lists("-encoders", c))
}
/// `codec` is among what this machine's ffmpeg prints for `option` (-encoders, -decoders), each asked once
fn lists(option: &'static str, codec: &str) -> bool {
static PRINTED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<&'static str, String>>> = std::sync::OnceLock::new();
let mut printed = PRINTED.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
printed.entry(option).or_insert_with(|| says(option)).split_whitespace().any(|w| w == codec)
}
/// A render's encoder and its rate, as ffmpeg's arguments: NVENC and libx264 at a constant quality when one is asked
/// (0.85 -> 13, 0.95 -> 11, 0.6 -> 18), else the average bitrate. The system's own encoders (h264_mf, h264_videotoolbox)
/// have no CRF, so they take the bitrate either way: the LGPL ffmpeg raea ships on Windows has no libx264, and
/// RAEA_MEDIA=ffmpeg failed there on `-c:v libx264` (#279)
fn video_args(enc: &str, o: &EncodeOpts) -> Vec<String> {
let rate = || vec!["-b:v".to_string(), format!("{}k", o.kbps), "-maxrate".to_string(), format!("{}k", o.kbps * 3 / 2), "-bufsize".to_string(), format!("{}k", o.kbps * 2)];
let q = |q: f32| format!("{:.0}", 30.0 - 20.0 * q.clamp(0.0, 1.0));
let (nvenc, x264) = (NVENC.map(String::from).to_vec(), ["-c:v", "libx264", "-preset", "medium"].map(String::from).to_vec());
match (enc, o.quality) {
("h264_nvenc", Some(v)) => [nvenc, vec!["-rc".into(), "constqp".into(), "-qp".into(), q(v)]].concat(),
("h264_nvenc", None) => [nvenc, rate()].concat(),
("libx264", Some(v)) => [x264, vec!["-crf".into(), q(v)]].concat(),
("libx264", None) => [x264, rate()].concat(),
_ => [vec!["-c:v".into(), enc.to_string()], rate()].concat(),
}
}
/// RAEA_NV=1 (the render farm sets it on a GPU's runs of a piece with 3D in it, docs/cloud-render.feature CR34): NVIDIA's
/// encoder (`enc`, NVENC) or decoder (NVDEC, through CUDA) in place of libx264 and ffmpeg's own, each only once a
/// one-frame try of it worked on this machine (a GPU without the driver's video libraries keeps libx264, said once).
fn nv(enc: bool) -> bool {
std::env::var("RAEA_NV").as_deref() == Ok("1") && nv_works(enc)
}
/// Whether NVENC (`enc`) or NVDEC worked on this machine, tried once on one frame
fn nv_works(enc: bool) -> bool {
static ENC: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
static DEC: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let tried = |args: &[&str]| cli("ffmpeg", false).ok().and_then(|mut c| c.args(["-v", "error"]).args(args).args(["-f", "null", "-"]).output().ok()).is_some_and(|o| o.status.success());
let (cell, what, args): (_, _, &[&str]) = if enc {
(&ENC, "NVENC", &["-f", "lavfi", "-i", "color=s=256x256:d=0.1", "-c:v", "h264_nvenc"])
} else {
(&DEC, "NVDEC", &["-init_hw_device", "cuda=gpu", "-f", "lavfi", "-i", "nullsrc=s=256x256:d=0.04"])
};
// the answer kept for the machine's later runs too (a farm container's runs after its first): a try starts CUDA,
// and on the farm it doubled the timed run's frames (8 frames, 232 to 498 ms a frame on a T4, 11-30)
let kept = std::env::temp_dir().join(format!("raea-{}.tried", what.to_lowercase()));
*cell.get_or_init(|| {
if let Ok(said) = std::fs::read_to_string(&kept) {
return said == "1";
}
let ok = tried(args);
let _ = std::fs::write(&kept, if ok { "1" } else { "0" });
if !ok {
eprintln!("raea: RAEA_NV=1 but {what} didn't work on this machine, so ffmpeg's own is used");
}
ok
})
}
/// NVENC's arguments in libx264's place: at a CRF, constant QP at its number (on 300 frames of a 1080x1920 ad on a T4,
/// SSIM 0.9925 against libx264's 0.9924 at 11% more bytes, 11-30); else its average bitrate
const NVENC: [&str; 14] = ["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq", "-bf", "2", "-g", "60", "-spatial-aq", "1", "-temporal-aq", "1"];
/// The facts, the presentation times, whether the colour matrix is untagged, and the decoder a VP8 or VP9 stream with /// The facts, the presentation times, whether the colour matrix is untagged, and the decoder a VP8 or VP9 stream with
/// alpha needs (libvpx: ffmpeg's own VP9 decoder drops the alpha WebM keeps beside the picture, #113). /// alpha needs (libvpx: ffmpeg's own VP9 decoder drops the alpha WebM keeps beside the picture, #113).
fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> { fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
probe_with(path, mov::frame_times(path))
}
/// `tabled`: the frame times the file's own tables state (mov.rs). Without them ffprobe is asked for every packet's
/// time, which reads the whole file.
fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
let out = cli("ffprobe", named_video(path))? let out = cli("ffprobe", named_video(path))?
.args([ .args([
"-v", "-v",
@@ -140,9 +69,11 @@ fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool,
"v:0", "v:0",
"-show_entries", "-show_entries",
"stream=codec_name,width,height,r_frame_rate,color_space:stream_tags=alpha_mode:stream_side_data=rotation:format=duration", "stream=codec_name,width,height,r_frame_rate,color_space:stream_tags=alpha_mode:stream_side_data=rotation:format=duration",
"-show_entries",
"packet=pts_time",
"-of",
"json",
]) ])
.args(if tabled.is_none() { &["-show_entries", "packet=pts_time"][..] } else { &[] })
.args(["-of", "json"])
.arg(path) .arg(path)
.output() .output()
.map_err(|e| format!("ffprobe: {e}"))?; .map_err(|e| format!("ffprobe: {e}"))?;
@@ -165,15 +96,12 @@ fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool,
.and_then(|r| r.split_once('/')) .and_then(|r| r.split_once('/'))
.map(|(n, d)| n.parse::<f64>().unwrap_or(30.0) / d.parse::<f64>().unwrap_or(1.0)) .map(|(n, d)| n.parse::<f64>().unwrap_or(30.0) / d.parse::<f64>().unwrap_or(1.0))
.unwrap_or(30.0); .unwrap_or(30.0);
let mut pts: Vec<f64> = match tabled { let mut pts: Vec<f64> = j["packets"]
Some(t) => t, .as_array()
None => j["packets"] .into_iter()
.as_array() .flatten()
.into_iter() .filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
.flatten() .collect();
.filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
.collect(),
};
pts.sort_by(f64::total_cmp); pts.sort_by(f64::total_cmp);
let duration = j["format"]["duration"] let duration = j["format"]["duration"]
.as_str() .as_str()
@@ -189,7 +117,9 @@ fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool,
_ => None, _ => None,
}; };
// an ffmpeg built without libvpx decodes the picture alone, as before // an ffmpeg built without libvpx decodes the picture alone, as before
let alpha = alpha.filter(|c| lists("-decoders", c)); static DECODERS: std::sync::OnceLock<String> = std::sync::OnceLock::new();
let have = DECODERS.get_or_init(|| says("-decoders"));
let alpha = alpha.filter(|c| have.split_whitespace().any(|w| w == *c));
Ok(( Ok((
Info { Info {
codec: s["codec_name"].as_str().unwrap_or("?").into(), codec: s["codec_name"].as_str().unwrap_or("?").into(),
@@ -225,12 +155,7 @@ impl Decoder {
} }
let start = self.pts[at] - self.pts[0]; let start = self.pts[at] - self.pts[0];
let mut cmd = cli("ffmpeg", false)?; let mut cmd = cli("ffmpeg", false)?;
cmd.args(["-v", "error"]).args(self.vpx.map(|c| ["-c:v", c]).into_iter().flatten()); cmd.args(["-v", "error"]).args(self.vpx.map(|c| ["-c:v", c]).into_iter().flatten()).args(["-ss", &format!("{start:.6}"), "-i"]).arg(&self.path);
// (a VP8/VP9 with alpha keeps libvpx: NVDEC drops the alpha as ffmpeg's own VP9 decoder does)
if self.vpx.is_none() && nv(false) {
cmd.args(["-hwaccel", "cuda"]);
}
cmd.args(["-ss", &format!("{start:.6}"), "-i"]).arg(&self.path);
if self.bt709 { if self.bt709 {
cmd.args(["-vf", "scale=in_color_matrix=bt709:in_range=tv"]); cmd.args(["-vf", "scale=in_color_matrix=bt709:in_range=tv"]);
} }
@@ -433,7 +358,6 @@ impl Backend for Ffmpeg {
} }
fn encoder(&self, out: &Path, o: &EncodeOpts) -> R<Box<dyn VideoEncoder>> { fn encoder(&self, out: &Path, o: &EncodeOpts) -> R<Box<dyn VideoEncoder>> {
let video = out.with_extension("video.mp4"); let video = out.with_extension("video.mp4");
let enc = if nv(true) { "h264_nvenc" } else { listed().ok_or("this machine's ffmpeg has no H.264 encoder (libx264, h264_mf or h264_videotoolbox)")? };
let child = cli("ffmpeg", false)? let child = cli("ffmpeg", false)?
.args([ .args([
"-v", "-v",
@@ -450,7 +374,19 @@ impl Backend for Ffmpeg {
"-i", "-i",
"-", "-",
]) ])
.args(video_args(enc, o)) .args(["-c:v", "libx264", "-preset", "medium"])
// constant quality as CRF (0.85 -> 13, 0.95 -> 11, 0.6 -> 18), else the average bitrate
.args(match o.quality {
Some(q) => vec!["-crf".to_string(), format!("{:.0}", 30.0 - 20.0 * q.clamp(0.0, 1.0))],
None => vec![
"-b:v".to_string(),
format!("{}k", o.kbps),
"-maxrate".to_string(),
format!("{}k", o.kbps * 3 / 2),
"-bufsize".to_string(),
format!("{}k", o.kbps * 2),
],
})
.args([ .args([
"-pix_fmt", "-pix_fmt",
"yuv420p", "yuv420p",
-81
View File
@@ -1,81 +0,0 @@
//! An MP4 or QuickTime file's frame times from its own sample tables. Opening a video asked ffprobe for every packet's
//! time, and for these files ffprobe reads every packet to say it: each open of a 1 GB interview read 1 GB (two
//! minutes on a cloud Sprite's disk, 12-01), and a contact sheet opened its file once a frame.
use std::path::Path;
use raea_io_codec::mp4box::{be32, be64, boxes, child, moov_of};
/// Every frame's presentation time in seconds, sorted, as ffprobe's packets give them up to one shift of them all
/// (the decoder uses them from the first on). None for a file that isn't MP4 or QuickTime, one in fragments (mvex), and one
/// whose edit list does more than set where the track starts: those are asked of ffprobe as before.
pub(crate) fn frame_times(path: &Path) -> Option<Vec<f64>> {
let ext = path.extension()?.to_string_lossy().to_ascii_lowercase();
if !["mp4", "mov", "m4v"].contains(&ext.as_str()) {
return None;
}
times_in(&moov_of(path)?)
}
fn times_in(moov: &[u8]) -> Option<Vec<f64>> {
if child(moov, b"mvex").is_some() {
return None;
}
for (k, trak) in boxes(moov) {
if &k != b"trak" {
continue;
}
let Some(mdia) = child(trak, b"mdia") else { continue };
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"vide"[..]) {
continue;
}
// an edit list that plays the track from one place on is a shift of every time; one with a gap ahead of it,
// or more than one piece, moves frames apart
if let Some(elst) = child(trak, b"edts").and_then(|e| child(e, b"elst")) {
if be32(elst, 4)? != 1 {
return None;
}
let from = if elst.first() == Some(&1) { be64(elst, 16)? as i64 } else { be32(elst, 12)? as i32 as i64 };
if from < 0 {
return None;
}
}
let mdhd = child(mdia, b"mdhd")?;
let scale = if mdhd.first() == Some(&1) { be32(mdhd, 20)? } else { be32(mdhd, 12)? } as f64;
if scale <= 0.0 {
return None;
}
let stbl = child(child(mdia, b"minf")?, b"stbl")?;
let stts = child(stbl, b"stts")?;
let mut times: Vec<i64> = Vec::new();
let mut dts = 0i64;
for e in 0..be32(stts, 4)? as usize {
let (n, d) = (be32(stts, 8 + e * 8)?, be32(stts, 12 + e * 8)? as i64);
// a table that claims more frames than a day of 240 a second isn't one to trust
if times.len() + n as usize > 20_736_000 {
return None;
}
for _ in 0..n {
times.push(dts);
dts += d;
}
}
if let Some(ctts) = child(stbl, b"ctts") {
let mut i = 0usize;
for e in 0..be32(ctts, 4)? as usize {
// signed whatever the version says: QuickTime writes negative offsets in version 0 boxes
let (n, off) = (be32(ctts, 8 + e * 8)? as usize, be32(ctts, 12 + e * 8)? as i32 as i64);
for t in times.iter_mut().skip(i).take(n) {
*t += off;
}
i += n;
}
}
if times.is_empty() {
return None;
}
times.sort_unstable();
return Some(times.into_iter().map(|t| t as f64 / scale).collect());
}
None
}
-69
View File
@@ -32,72 +32,3 @@ fn vp9_webm_keeps_its_alpha() {
} }
let _ = std::fs::remove_dir_all(&dir); let _ = std::fs::remove_dir_all(&dir);
} }
/// Where NVIDIA's encoder and decoder don't work (this Mac, a GPU without the driver's video libraries) the one-frame
/// tries fail, so RAEA_NV=1 keeps libx264 and ffmpeg's own decoders instead of refusing (CR34)
#[test]
fn nv_falls_back_where_nvidia_isnt() {
if Command::new("ffmpeg").arg("-version").output().is_err() {
return eprintln!("skipped: no ffmpeg here");
}
if !Command::new("nvidia-smi").output().is_ok_and(|o| o.status.success()) {
assert!(!nv_works(true) && !nv_works(false), "no NVIDIA here, so neither is used");
}
if std::env::var_os("RAEA_NV").is_none() {
assert!(!nv(true) && !nv(false), "off without RAEA_NV=1");
}
}
/// libx264's arguments are what they were, and the system's encoder (macOS's here, Windows' Media Foundation the same
/// way) takes a bitrate even when a quality is asked, and encodes with them (#279)
#[test]
fn a_system_encoder_takes_the_bitrate() {
let o = |quality| EncodeOpts { width: 256, height: 256, fps: 30.0, kbps: 900, quality, nv12: false, realtime: false };
assert_eq!(video_args("libx264", &o(Some(0.85))), ["-c:v", "libx264", "-preset", "medium", "-crf", "13"]);
assert_eq!(video_args("libx264", &o(None)), ["-c:v", "libx264", "-preset", "medium", "-b:v", "900k", "-maxrate", "1350k", "-bufsize", "1800k"]);
let args = video_args("h264_videotoolbox", &o(Some(0.85)));
assert_eq!(args, ["-c:v", "h264_videotoolbox", "-b:v", "900k", "-maxrate", "1350k", "-bufsize", "1800k"]);
if !lists("-encoders", "h264_videotoolbox") {
return eprintln!("skipped the encode: no h264_videotoolbox in this ffmpeg");
}
let out = std::env::temp_dir().join(format!("raea-ffmpeg-system-{}.mp4", std::process::id()));
let ok = Command::new("ffmpeg").args(["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=red:s=256x256:d=0.3"]).args(&args).args(["-pix_fmt", "yuv420p"]).arg(&out).status().is_ok_and(|s| s.success());
assert!(ok && std::fs::metadata(&out).is_ok_and(|m| m.len() > 500), "ffmpeg encodes with the system encoder's arguments");
let _ = std::fs::remove_file(&out);
}
/// An MP4's and a QuickTime file's frame times, read from their own tables, are the ones ffprobe's packets give (up to
/// one shift of them all), with B-frames, at a rate that isn't whole, and the same frames come out either way.
#[test]
fn a_file_s_own_tables_give_ffprobe_s_frame_times() {
let dir = std::env::temp_dir().join(format!("raea-ffmpeg-tables-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let make = |name: &str, args: &[&str]| {
let p = dir.join(name);
let ok = Command::new("ffmpeg").args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=128x72:r=30000/1001:d=2", "-pix_fmt", "yuv420p"]).args(args).arg(&p).status().is_ok_and(|s| s.success());
ok.then_some(p)
};
let files = [make("b.mp4", &["-c:v", "libx264", "-bf", "3"]), make("b.mov", &["-c:v", "libx264", "-bf", "2", "-g", "12"]), make("plain.mp4", &["-c:v", "mpeg4"])];
let mut seen = 0;
for f in files.into_iter().flatten() {
let Some(tabled) = mov::frame_times(&f) else { panic!("{}: its tables weren't read", f.display()) };
let (_, asked, ..) = probe_with(&f, None).unwrap();
assert_eq!(tabled.len(), asked.len(), "{}: as many frames", f.display());
for (a, b) in tabled.iter().zip(&asked) {
assert!(((a - tabled[0]) - (b - asked[0])).abs() < 2e-4, "{}: {a} against {b}", f.display());
}
// and the decoder gives the same picture at a time either way
let (info, pts, ..) = probe(&f).unwrap();
assert_eq!(pts.len(), info.frames);
let mut d = Ffmpeg.open_video(&f).unwrap();
let at = d.frame_at(1.0).unwrap();
assert!((at.pts - 1.0).abs() < 0.04, "{}: the frame at 1 s is at {}", f.display(), at.pts);
seen += 1;
}
let _ = std::fs::remove_dir_all(&dir);
if seen == 0 {
eprintln!("skipped: no ffmpeg here to make a file with");
}
// a file in fragments, or of another kind, is asked of ffprobe as before
assert!(mov::frame_times(Path::new("a.webm")).is_none());
}
-8
View File
@@ -71,14 +71,6 @@ pub fn backend_unsigned(name: &str) -> R<Box<dyn Backend>> {
pub mod sign; pub mod sign;
pub use sign::signs; pub use sign::signs;
/// `file`'s decoder: the first of `preferred` that opens it, else what each said. A WebM is read by ffmpeg alone (#113:
/// it was refused, "no video track", where the platform's was the only one asked).
pub fn open_video(file: &Path) -> Result<Box<dyn VideoDecoder>, String> {
let mut why = Vec::new();
let d = preferred().into_iter().find_map(|b| b.open_video(file).map_err(|e| why.push(format!("{}: {e}", b.name()))).ok());
d.ok_or_else(|| format!("{}: no backend reads it ({})", file.display(), why.join("; ")))
}
/// The backends to try for a file, in order: RAEA_MEDIA's, the platform's, the portable one, then the ffmpeg CLI /// The backends to try for a file, in order: RAEA_MEDIA's, the platform's, the portable one, then the ffmpeg CLI
/// (which reads what the others don't: VP9 WebM). /// (which reads what the others don't: VP9 WebM).
pub fn preferred() -> Vec<Box<dyn Backend>> { pub fn preferred() -> Vec<Box<dyn Backend>> {
+12 -1
View File
@@ -83,7 +83,18 @@ fn encode_at(src: &Path, part: &Path, range: Option<(usize, usize)>, p: &Probe,
Some((a, b)) => (a as f64 * p.frame_secs(), (b + 1) as f64 * p.frame_secs()), Some((a, b)) => (a as f64 * p.frame_secs(), (b + 1) as f64 * p.frame_secs()),
None => (0.0, p.secs), None => (0.0, p.secs),
}; };
let mut dec = crate::open_video(src)?; let mut why = Vec::new();
let mut dec = None;
for b in crate::preferred() {
match b.open_video(src) {
Ok(d) => {
dec = Some(d);
break;
}
Err(e) => why.push(format!("{}: {e}", b.name())),
}
}
let mut dec = dec.ok_or_else(|| format!("{}: no backend reads it ({})", src.display(), why.join("; ")))?;
let info = dec.info().clone(); let info = dec.info().clone();
if info.width % 2 == 1 || info.height % 2 == 1 { if info.width % 2 == 1 || info.height % 2 == 1 {
return Err(format!("{}: {}x{} has an odd side (H.264's 4:2:0 wants even ones)", src.display(), info.width, info.height)); return Err(format!("{}: {}x{} has an odd side (H.264's 4:2:0 wants even ones)", src.display(), info.width, info.height));
+1 -22
View File
@@ -58,23 +58,7 @@ pub struct Track {
/// A file's first video track's display rotation (clockwise degrees; 0 when it has none or isn't an MP4/MOV). /// A file's first video track's display rotation (clockwise degrees; 0 when it has none or isn't an MP4/MOV).
pub fn rotation_of(path: &Path) -> i32 { pub fn rotation_of(path: &Path) -> i32 {
// the moov box alone, as a file of that one box (the whole file was read for it: gigabytes, for a matrix) std::fs::read(path).map(|b| mp4_rotation(&b)).unwrap_or(0)
let Some(moov) = raea_io_codec::mp4box::moov_of(path) else { return 0 };
let mut b = ((moov.len() + 8) as u32).to_be_bytes().to_vec();
b.extend_from_slice(b"moov");
b.extend_from_slice(&moov);
mp4_rotation(&b)
}
/// The first video track's sample entry (avc1, hvc1, av01, ...), from the moov box alone.
fn video_fourcc(path: &Path) -> Option<[u8; 4]> {
use raea_io_codec::mp4box::{boxes, child, moov_of};
let moov = moov_of(path)?;
boxes(&moov).into_iter().filter(|(k, _)| k == b"trak").find_map(|(_, trak)| {
let mdia = child(trak, b"mdia")?;
(child(mdia, b"hdlr")?.get(8..12)? == b"vide").then_some(())?;
child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?.get(12..16)?.try_into().ok()
})
} }
/// The first video track's display rotation, from its tkhd matrix (QuickTime's 16.16 a, b, c, d). /// The first video track's display rotation, from its tkhd matrix (QuickTime's 16.16 a, b, c, d).
@@ -123,11 +107,6 @@ fn mp4_rotation(b: &[u8]) -> i32 {
} }
pub fn demux(path: &Path, want: &str) -> R<Track> { pub fn demux(path: &Path, want: &str) -> R<Track> {
// another codec's file is refused before it is read: every open of a 4K HEVC interview on Linux read its whole
// gigabyte here to learn it wasn't H.264, then went to the backend that reads it (two minutes on a cloud disk)
if let Some(is) = video_fourcc(path).filter(|f| want.len() >= 3 && f[..3] != want.as_bytes()[..3]) {
return Err(format!("{}: {}, not {want} (this backend reads {want} mezzanines)", path.display(), String::from_utf8_lossy(&is)));
}
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?; let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
let mp4 = re_mp4::Mp4::read_bytes(&bytes).map_err(|e| format!("{}: {e}", path.display()))?; let mp4 = re_mp4::Mp4::read_bytes(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
let (_, t) = mp4 let (_, t) = mp4
-37
View File
@@ -1,37 +0,0 @@
//! A file of another codec is refused from its moov box alone, and a rotation is read from it, without the file's
//! pictures being read (a 1 GB HEVC interview was read whole on every open to learn it wasn't H.264).
use std::path::{Path, PathBuf};
use std::process::Command;
fn made(dir: &Path, name: &str, args: &[&str]) -> Option<PathBuf> {
let p = dir.join(name);
Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).arg(&p).status().is_ok_and(|s| s.success()).then_some(p)
}
#[test]
fn another_codec_is_refused_by_its_tables_and_a_rotation_read_from_them() {
let dir = std::env::temp_dir().join(format!("raea-soft-refuse-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let src = ["-f", "lavfi", "-i", "testsrc2=s=128x72:r=30:d=1", "-pix_fmt", "yuv420p"];
let Some(other) = made(&dir, "other.mp4", &[&src[..], &["-c:v", "mpeg4"]].concat()) else { return eprintln!("skipped: no ffmpeg here") };
let e = raea_io_soft::demux(&other, "avc1").err().expect("an MPEG-4 file isn't H.264");
assert!(e.contains("mp4v, not avc1"), "{e}");
// cut short after its moov, the refusal is the same: nothing past the tables was needed
if let Some(front) = made(&dir, "front.mp4", &[&src[..], &["-c:v", "mpeg4", "-movflags", "+faststart"]].concat()) {
let bytes = std::fs::read(&front).unwrap();
let mdat = bytes.windows(4).position(|w| w == b"mdat").unwrap();
std::fs::write(&front, &bytes[..mdat + 4]).unwrap();
assert!(raea_io_soft::demux(&front, "avc1").err().unwrap().contains("mp4v, not avc1"));
assert_eq!(raea_io_soft::rotation_of(&front), 0);
}
// an H.264 file is read as before, and one turned on its side says so
if let Some(h264) = made(&dir, "h264.mp4", &[&src[..], &["-c:v", "libx264"]].concat()) {
assert!(raea_io_soft::demux(&h264, "avc1").is_ok());
assert_eq!(raea_io_soft::rotation_of(&h264), 0);
let h = h264.to_string_lossy().to_string();
if let Some(turned) = made(&dir, "turned.mp4", &["-display_rotation:v:0", "90", "-i", &h, "-c", "copy"]) {
assert_eq!(raea_io_soft::rotation_of(&turned).rem_euclid(180), 90);
}
}
let _ = std::fs::remove_dir_all(&dir);
}
-3
View File
@@ -20,9 +20,6 @@ use serde_json::{Map, Value, json};
type R<T> = Result<T, String>; type R<T> = Result<T, String>;
#[cfg(target_arch = "wasm32")]
mod wasm;
/// One world: Bevy's, plus our ids, the component names, resources and this frame's events. /// One world: Bevy's, plus our ids, the component names, resources and this frame's events.
struct BWorld { struct BWorld {
w: World, w: World,
-63
View File
@@ -1,63 +0,0 @@
//! The ecs.* calls as a wasm module (docs/playables.feature PA12): a playable carries Bevy's own world, so a game on
//! raea/ecs keeps the tables, queries and parent/child it has natively. sdk/playable/ecs/build.sh builds it as a
//! cdylib for wasm32-unknown-unknown; the page's host/ecs.ts calls `raea_call` the way raea's V8 calls `__raea_call`.
//! Strings cross as UTF-8 in memory the page asks for with `raea_alloc`; the answer is `o` and the value's JSON, or
//! `e` and the message, where `raea_call` returns (its address in the high 32 bits, its length in the low), until the
//! next call.
use std::cell::RefCell;
thread_local! {
static OUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}
/// `len` bytes the page writes a call's name or arguments into, freed by `raea_free`
#[unsafe(no_mangle)]
pub extern "C" fn raea_alloc(len: usize) -> *mut u8 {
let mut v = Vec::<u8>::with_capacity(len.max(1));
let p = v.as_mut_ptr();
std::mem::forget(v);
p
}
/// # Safety
/// `p` came from `raea_alloc(len)` and isn't used after
#[unsafe(no_mangle)]
pub unsafe extern "C" fn raea_free(p: *mut u8, len: usize) {
// SAFETY: raea_alloc made it with this capacity
drop(unsafe { Vec::from_raw_parts(p, 0, len.max(1)) });
}
/// # Safety
/// each pointer holds that many bytes of UTF-8 the page wrote (raea_alloc's)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn raea_call(
name: *const u8,
name_len: usize,
args: *const u8,
args_len: usize,
) -> u64 {
// SAFETY: the page wrote these bytes where raea_alloc said
let (name, args) = unsafe {
(
std::slice::from_raw_parts(name, name_len),
std::slice::from_raw_parts(args, args_len),
)
};
let answer = match (
std::str::from_utf8(name),
serde_json::from_slice::<serde_json::Value>(args),
) {
(Ok(n), Ok(a)) => super::call(n, &a).map(|v| v.to_string()),
_ => Err("a call's name and arguments are UTF-8 JSON".into()),
};
OUT.with(|o| {
let mut o = o.borrow_mut();
*o = match answer {
Ok(v) => format!("o{v}"),
Err(e) => format!("e{e}"),
}
.into_bytes();
((o.as_ptr() as u64) << 32) | o.len() as u64
})
}
-2
View File
@@ -45,8 +45,6 @@ raea-sys-light-meter = { path = "../../systems/light-meter" }
raea-runtime-scene3d = { path = "../scene3d" } raea-runtime-scene3d = { path = "../scene3d" }
# --review: the fixed cameras # --review: the fixed cameras
raea-core-review = { path = "../../core/review" } raea-core-review = { path = "../../core/review" }
# render --review's tiles and sheets
raea-runtime-review = { path = "../review" }
raea-sys-mix = { path = "../../systems/mix" } raea-sys-mix = { path = "../../systems/mix" }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] } bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] }
image = { version = "0.25", default-features = false, features = ["png", "hdr"] } image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
-8
View File
@@ -245,14 +245,6 @@ pub(crate) fn bevy_page_frame(world: &mut World, page: &mut raea_runtime_page::B
Ok((px, pics)) Ok((px, pics))
} }
/// React told the frame is `f` (with `tell`) and settled there, a layout read answered from the page as it is then.
pub(crate) fn step_react(app: &mut App, page: &mut raea_runtime_page::BevyPage, cx: &mut Ctx, (f, fps): (i64, f64), tell: bool) -> R<()> {
if tell { app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f})); }
settle_with(app, Some(f), 20.0, &mut |w, q| layout_answer(w, page, cx, f, fps, q))?;
cx.now = f;
Ok(())
}
/// A composition's layout read answered by the frame's page (`page.layout`, docs/layout-reads.feature LR1): the page made /// A composition's layout read answered by the frame's page (`page.layout`, docs/layout-reads.feature LR1): the page made
/// to match the React World as it is mid-settle, at frame `f`'s time, laid out, and every element's boxes by React id. /// to match the React World as it is mid-settle, at frame `f`'s time, laid out, and every element's boxes by React id.
/// Nothing is drawn; the frame's own sync redoes what this did once the frame settles. /// Nothing is drawn; the frame's own sync redoes what this did once the frame settles.
+5 -1
View File
@@ -246,7 +246,11 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
} }
let t_react = std::time::Instant::now(); let t_react = std::time::Instant::now();
engine_before(app, cx, f); engine_before(app, cx, f);
step_react(app, bevy, cx, (f, fps), asked != Some(f))?; if asked != Some(f) {
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f}));
}
settle_with(app, Some(f), 20.0, &mut |w, q| layout_answer(w, bevy, cx, f, fps, q))?;
cx.now = f;
// the next frame asked for now, so React renders it on its own thread while this one's 3D and page are // the next frame asked for now, so React renders it on its own thread while this one's 3D and page are
// drawn here: its commits wait in the inbox until the next settle applies them, so nothing this frame // drawn here: its commits wait in the inbox until the next settle applies them, so nothing this frame
// reads changes (the frames come in order; one asked for out of order is asked for again) // reads changes (the frames come in order; one asked for out of order is asked for again)
-44
View File
@@ -1,44 +0,0 @@
//! `render --keys PATH`: what each frame of the composition draws, as a key, with nothing drawn, no clip read and no
//! sound made (docs/rerender.feature RR4, docs/cloud-render.feature CR30). React is stepped through every frame as a
//! render steps it and the page made to match its tree; a frame's key is the page's (raea_core_wire::tree::key: its
//! elements and each video's file and time) with the frame's 3D rows. A render farm holds a run of frames it drew
//! before to its frames' keys, and draws again only the runs whose keys changed: a caption edited in one shot redraws
//! that shot's runs, a change to the sound alone redraws none.
//!
//! A key is a frame's own: the same key at another frame number isn't the same picture (an element's CSS animation
//! runs on the page's clock, not in its props), and neither is the same key over other files (they're named, not
//! read). Whoever keeps pictures by these holds both to them. With 3D, a frame's picture can hang on the frames before
//! it (physics, particles, a path tracer's light), which `has3d` says.
//!
//! The piece's sounds are written beside the keys as a render's manifest holds them (`sounds`): a run taken from a
//! farm's cache brings the manifest of the render that drew it, whose sounds are that render's, not this edit's.
use super::*;
pub(crate) fn write(to: &Path, app: &mut App, page: &mut raea_runtime_page::BevyPage, cx: &mut Ctx, (w, h, fps, total): (u32, u32, f64, i64)) -> R<String> {
use std::hash::{Hash, Hasher};
page.keyed = Some(0);
let (mut keys, mut has3d) = (Vec::with_capacity(total.max(0) as usize), false);
let (mut frames, mut tones) = (Vec::new(), Vec::new());
for f in 0..total {
step_react(app, page, cx, (f, fps), true)?;
page.at_frame(f, fps);
bevy_page_sync(app.world_mut(), page, cx)?;
let mut h = std::collections::hash_map::DefaultHasher::new();
(page.keyed, format!("{:?}{:?}", cx.scene, cx.clear)).hash(&mut h);
has3d |= !cx.scene.is_empty();
keys.push(format!("{:016x}", h.finish()));
tones.push(raea_runtime_sound::tone_at(app.world_mut(), f, fps, cx.dir, media_path, true));
frames.push((f, Frame { mix: cx.mix, page: None, sounds: cx.sounds.clone(), scene: Vec::new(), clear: None, same: false, screens: Vec::new() }));
}
to.parent().map_or(Ok(()), std::fs::create_dir_all).map_err(|e| format!("{}: {e}", to.display()))?;
std::fs::write(to, json!({"width": w, "height": h, "fps": fps, "length": total, "has3d": has3d, "keys": keys, "sounds": heard(&frames, &tones, cx, fps), "drawn": drawn(page, cx.dir)}).to_string()).map_err(|e| format!("{}: {e}", to.display()))?;
Ok(format!("APPLIED {total} frames' keys written to {} (nothing drawn)", to.display()))
}
/// The largest each clip was drawn, by its path from the composition's folder: {"media/a.mp4": [w, h]} in output px,
/// null where a frame's size wasn't known (CR36)
fn drawn(page: &raea_runtime_page::BevyPage, dir: &Path) -> Value {
let size = |s: &[f32; 2]| if s.iter().all(|v| v.is_finite()) { json!([s[0].ceil(), s[1].ceil()]) } else { Value::Null };
Value::Object(page.drawn.iter().map(|(f, s)| (f.strip_prefix(dir).unwrap_or(f).to_string_lossy().into_owned(), size(s))).collect())
}
-4
View File
@@ -31,7 +31,6 @@ pub(crate) use raea_runtime_react::{ReactKind, ReactOutbox, ReactPlugin, ReactPr
mod bevy_frame; mod bevy_frame;
use bevy_frame::*; use bevy_frame::*;
mod keys;
mod pages; mod pages;
use pages::*; use pages::*;
mod program; mod program;
@@ -65,9 +64,6 @@ pub(crate) struct Sound {
bus: Option<String>, bus: Option<String>,
} }
/// `render --keys PATH`: each frame's key written there and nothing drawn (keys.rs).
pub(crate) static KEYS: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
/// `render --manifest PATH` (the CLI's; render_bundle keeps its signature for the iPhone): where render.json goes. /// `render --manifest PATH` (the CLI's; render_bundle keeps its signature for the iPhone): where render.json goes.
static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None); static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
-9
View File
@@ -65,12 +65,6 @@ pub fn render(args: &[String]) -> R<String> {
(_, Some(at)) => Some(at.split(',').map(|f| f.trim().parse::<i64>().map_err(|_| "--at takes frame numbers".to_string())).collect::<R<_>>()?), (_, Some(at)) => Some(at.split(',').map(|f| f.trim().parse::<i64>().map_err(|_| "--at takes frame numbers".to_string())).collect::<R<_>>()?),
_ => None, _ => None,
}; };
if let Some(k) = flag(args, "--keys") {
*KEYS.lock().unwrap() = Some(PathBuf::from(k));
let said = render_bundle_with(&js, &dir, &out, None, false, None, false);
let _ = std::fs::remove_file(&js);
return said;
}
raea_sys_layers::start(layers_on, &out, &tsx); raea_sys_layers::start(layers_on, &out, &tsx);
*MANIFEST.lock().unwrap() = Some(flag(args, "--manifest").map_or_else(|| raea_sys_layers::manifest_for(&out, &tsx), PathBuf::from)); *MANIFEST.lock().unwrap() = Some(flag(args, "--manifest").map_or_else(|| raea_sys_layers::manifest_for(&out, &tsx), PathBuf::from));
TEN_BIT.store(args.iter().any(|a| a == "--10bit"), std::sync::atomic::Ordering::Relaxed); TEN_BIT.store(args.iter().any(|a| a == "--10bit"), std::sync::atomic::Ordering::Relaxed);
@@ -303,9 +297,6 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
raea_gpu_device::check::mem_fits(w, h, None)?; raea_gpu_device::check::mem_fits(w, h, None)?;
let mut page = raea_runtime_page::BevyPage::new(w, h, dir)?; let mut page = raea_runtime_page::BevyPage::new(w, h, dir)?;
let mut cx = Ctx { dir, work: &work, sounds: Vec::new(), scene: Vec::new(), clear: None, marker: None, mix: None, audible: HashMap::new(), brand: page_css(dir, w, js), manifest: MANIFEST.lock().unwrap().as_ref().map(|_| Vec::new()), now: 0, said: Default::default(), made: HashMap::new(), scene3d: None, live3d: None }; let mut cx = Ctx { dir, work: &work, sounds: Vec::new(), scene: Vec::new(), clear: None, marker: None, mix: None, audible: HashMap::new(), brand: page_css(dir, w, js), manifest: MANIFEST.lock().unwrap().as_ref().map(|_| Vec::new()), now: 0, said: Default::default(), made: HashMap::new(), scene3d: None, live3d: None };
if let Some(to) = KEYS.lock().unwrap().take() {
return crate::keys::write(&to, &mut app, &mut page, &mut cx, (w, h, fps, total));
}
if fed { if fed {
if let Some(p) = scene { if let Some(p) = scene {
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?); aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
+60 -2
View File
@@ -7,7 +7,7 @@
use super::*; use super::*;
use crate::scene::items; use crate::scene::items;
use raea_core_review::{boxes_of, cameras, ceiling, inside, parts_box, whole}; use raea_core_review::{TILE_W, VIEWS, boxes_of, cameras, ceiling, inside, parts_box, passed, whole};
pub fn review(args: &[String], dir_out: &Path) -> R<String> { pub fn review(args: &[String], dir_out: &Path) -> R<String> {
let tsx = dunce::canonicalize(&PathBuf::from(&args[1])).map_err(|e| format!("{}: {e}", args[1]))?; let tsx = dunce::canonicalize(&PathBuf::from(&args[1])).map_err(|e| format!("{}: {e}", args[1]))?;
@@ -31,5 +31,63 @@ pub fn review(args: &[String], dir_out: &Path) -> R<String> {
let ceil = ceiling(&all, wlo, whi); let ceil = ceiling(&all, wlo, whi);
let fixed = match ceil { Some(y) => inside(wlo, whi, y), None => cameras(lo, hi, aspect) }; let fixed = match ceil { Some(y) => inside(wlo, whi, y), None => cameras(lo, hi, aspect) };
cams.extend(fixed.into_iter().map(|(v, e, t, f)| (v, Some((e, t, f))))); cams.extend(fixed.into_iter().map(|(v, e, t, f)| (v, Some((e, t, f)))));
raea_runtime_review::sheets(&tsx, args, dir_out, &cams, raea_runtime_review::Shot { frame, aspect, parts: (lo, hi), interior: ceil.is_some() }) let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let rest = passed(args);
let mut tiles = Vec::new();
let mut said = Vec::new();
for (view, cam) in &cams {
for mode in ["colour", "clay"] {
let out = dir_out.join(format!("{view}-{mode}.png"));
let mut cmd = std::process::Command::new(&exe);
cmd.arg("render").arg(&tsx).args(&rest).args(["--frame", &frame.to_string(), "-o"]).arg(&out);
// a tile is part of this render: the review keeps the one entry in the project's record (DR3)
cmd.env_remove("RAEA_CAMERA").env_remove("RAEA_CLAY").env("RAEA_RECORD", "off");
if let Some((e, t, f)) = cam {
cmd.env("RAEA_CAMERA", format!("{},{},{},{},{},{},{}", e[0], e[1], e[2], t[0], t[1], t[2], f));
}
if mode == "clay" {
cmd.env("RAEA_CLAY", "1");
}
let run = cmd.output().map_err(|e| format!("--review: {e}"))?;
if !run.status.success() || !out.is_file() {
let text = format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
return Err(format!("--review: the {view} {mode} render failed: {}", text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
}
}
let colour = dir_out.join(format!("{view}-colour.png"));
let (_, ev) = raea_sys_light_meter::exposure::of_pngs(std::slice::from_ref(&colour))?;
// what a tile's exposure found, counted with the render's findings (DR3)
let tile: Vec<raea_core_facts::Finding> = ev["found"].as_array().into_iter().flatten().filter_map(|f| {
raea_core_facts::Finding::of_value(&json!({"check": "exposure", "level": f["level"], "says": format!("{view} tile: {}", f["says"].as_str().unwrap_or("").trim_start_matches("the frame: "))}), "raea render")
}).collect();
raea_core_facts::finding::said(&tile);
said.extend(tile);
tiles.push(json!({"view": view, "colour": format!("{view}-colour.png"), "clay": format!("{view}-clay.png"), "exposure": ev["exposure"],
"camera": cam.map(|(e, t, f)| json!({"eye": e, "target": t, "fov": f}))}));
}
// the sheets: three across, two down, each tile TILE_W wide
let th = (TILE_W as f64 / aspect).round().max(1.0) as u32;
for mode in ["colour", "clay"] {
let mut sheet = image::RgbaImage::from_pixel(TILE_W * 3, th * 2, image::Rgba([0, 0, 0, 255]));
for (i, view) in VIEWS.iter().enumerate() {
let img = image::open(dir_out.join(format!("{view}-{mode}.png"))).map_err(|e| format!("{view}-{mode}.png: {e}"))?.to_rgba8();
let small = image::imageops::resize(&img, TILE_W, th, image::imageops::FilterType::Triangle);
image::imageops::overlay(&mut sheet, &small, (i as u32 % 3 * TILE_W) as i64, (i as u32 / 3 * th) as i64);
}
sheet.save(dir_out.join(format!("{mode}.png"))).map_err(|e| format!("{mode}.png: {e}"))?;
}
for (i, t) in tiles.iter_mut().enumerate() {
t["rect"] = json!([i as u32 % 3 * TILE_W, i as u32 / 3 * th, TILE_W, th]);
}
let cameras: Vec<Value> = tiles.iter().map(|t| json!({"view": t["view"], "camera": t["camera"]})).collect();
std::fs::write(dir_out.join("cameras.json"), serde_json::to_string_pretty(&json!({"frame": frame, "box": {"min": lo, "max": hi}, "interior": ceil.is_some(), "cameras": cameras})).unwrap_or_default()).map_err(|e| e.to_string())?;
let doc = json!({"frame": frame, "sheets": {"colour": "colour.png", "clay": "clay.png"}, "size": [TILE_W * 3, th * 2],
"caption": if ceil.is_some() { "An interior, seen from inside: tiles left to right, top to bottom: hero, front, right, top (under the ceiling), iso, low (0.3 m). Clay: every standard surface light grey and matte." } else { "Tiles left to right, top to bottom: hero, front, right, top, iso, low (0.3 m). Clay: every standard surface light grey and matte." },
"box": {"min": lo, "max": hi}, "tiles": tiles, "found": said});
std::fs::write(dir_out.join("review.json"), serde_json::to_string_pretty(&doc).unwrap_or_default()).map_err(|e| e.to_string())?;
let mut msg = format!("APPLIED review of frame {frame}: {} and {} (hero, front, right, top, iso, low), cameras and exposure in {}", dir_out.join("colour.png").display(), dir_out.join("clay.png").display(), dir_out.join("review.json").display());
for f in &said {
msg.push_str(&format!("\n{}", f.line()));
}
Ok(msg)
} }
+4 -2
View File
@@ -9,8 +9,8 @@ description = "A composition's page in Bevy: React's elements laid out and paint
[dependencies] [dependencies]
raea-runtime-view = { path = "../view" } raea-runtime-view = { path = "../view" }
raea-runtime-appscreen = { path = "../appscreen" } raea-runtime-appscreen = { path = "../appscreen" }
# a take's face track, for <Video framing="face"> raea-sys-frame = { path = "../../systems/frame" }
raea-sys-facetrack = { path = "../../systems/facetrack" } raea-io-assets = { path = "../../io/assets" }
raea-io-net = { path = "../../io/net" } raea-io-net = { path = "../../io/net" }
raea-io-home = { path = "../../io/home" } raea-io-home = { path = "../../io/home" }
raea-runtime-react = { path = "../../runtime/react", default-features = false } raea-runtime-react = { path = "../../runtime/react", default-features = false }
@@ -26,7 +26,9 @@ raea-sys-image = { path = "../../systems/image" }
raea-runtime-twins = { path = "../twins" } raea-runtime-twins = { path = "../twins" }
raea-runtime-input = { path = "../input" } raea-runtime-input = { path = "../input" }
raea-core-wire = { path = "../../core/wire" } raea-core-wire = { path = "../../core/wire" }
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] } bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] }
image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
serde_json = "1" serde_json = "1"
base64 = "0.22" base64 = "0.22"
wgpu = "=30.0.1" wgpu = "=30.0.1"
+1 -17
View File
@@ -25,11 +25,6 @@ pub struct BevyPage {
pub(crate) surf: Option<Entity>, pub(crate) surf: Option<Entity>,
/// the UiMaterial elements the last sync met: page id and spec (JSON) /// the UiMaterial elements the last sync met: page id and spec (JSON)
pub(crate) ui_mats: Vec<(u64, String)>, pub(crate) ui_mats: Vec<(u64, String)>,
/// `render --keys`: a sync leaves the page's key here (raea_core_wire::tree::key) and reads no video's frame
pub keyed: Option<u64>,
/// `render --keys`: the largest each clip was drawn, [w, h] in page px over the frames synced (infinite where
/// one frame's size wasn't known), so a render farm can read it from a copy no larger (CR36)
pub drawn: HashMap<PathBuf, [f32; 2]>,
} }
impl BevyPage { impl BevyPage {
@@ -39,7 +34,7 @@ impl BevyPage {
// they draw as it is // they draw as it is
let fonts = raea_io_home::home().join("core/fonts"); let fonts = raea_io_home::home().join("core/fonts");
let page = raea_page::motion::BlitzPage::new_on(w, h, Some(&fonts), Some(raea_runtime_view::render_creation()))?; let page = raea_page::motion::BlitzPage::new_on(w, h, Some(&fonts), Some(raea_runtime_view::render_creation()))?;
Ok(BevyPage { page, w, h, dir: dir.to_path_buf(), slot: None, view: None, in_box: false, under: false, app_screens: Vec::new(), apps: Default::default(), walk: Walk::default(), surf: None, ui_mats: Vec::new(), keyed: None, drawn: HashMap::new() }) Ok(BevyPage { page, w, h, dir: dir.to_path_buf(), slot: None, view: None, in_box: false, under: false, app_screens: Vec::new(), apps: Default::default(), walk: Walk::default(), surf: None, ui_mats: Vec::new() })
} }
/// The page made to match the React tree in `react` (the composition's App's World). `holders`: the props elements /// The page made to match the React tree in `react` (the composition's App's World). `holders`: the props elements
@@ -67,7 +62,6 @@ impl BevyPage {
self.walk.begin(self.w, self.h, brand, self.under); self.walk.begin(self.w, self.h, brand, self.under);
walk(react, surf, BODY, At::Str(""), &self.dir, holders, &mut self.walk, &mut videos, &mut screens); walk(react, surf, BODY, At::Str(""), &self.dir, holders, &mut self.walk, &mut videos, &mut screens);
self.walk.end(); self.walk.end();
let mut key = self.keyed.map(|_| raea_core_wire::tree::key(0, self.walk.wants(), &videos, &self.dir));
// an <Img> of a file that isn't there fails the render, naming it (footage.md), never a frame without it; so does // an <Img> of a file that isn't there fails the render, naming it (footage.md), never a frame without it; so does
// a framed take with no face track // a framed take with no face track
let refused = REFUSED.with(|c| std::mem::take(&mut *c.borrow_mut())); let refused = REFUSED.with(|c| std::mem::take(&mut *c.borrow_mut()));
@@ -78,7 +72,6 @@ impl BevyPage {
// each <Screen>'s nested composition: a root of its own at the screen's size, drawn into its own picture // each <Screen>'s nested composition: a root of its own at the screen's size, drawn into its own picture
let mut keep = Vec::new(); let mut keep = Vec::new();
for s in screens { for s in screens {
key = key.map(|k| raea_core_wire::tree::key(k, &s.want, &s.videos, &self.dir));
videos.extend(s.videos); videos.extend(s.videos);
let (mut want, mut order, first) = frame_wants(s.w, s.h, brand); let (mut want, mut order, first) = frame_wants(s.w, s.h, brand);
want.extend(s.want); want.extend(s.want);
@@ -106,15 +99,6 @@ impl BevyPage {
} }
crate::screen::retire(&mut self.apps, &self.app_screens); crate::screen::retire(&mut self.apps, &self.app_screens);
crate::screen::step_all(&mut self.apps, &self.app_screens, &self.dir); crate::screen::step_all(&mut self.apps, &self.app_screens, &self.dir);
if key.is_some() {
self.keyed = key;
for (file, size) in self.page.drawn_sizes(&videos) {
let s = size.unwrap_or([f32::INFINITY; 2]);
let had = self.drawn.entry(file).or_insert([0.0; 2]);
*had = [had[0].max(s[0]), had[1].max(s[1])];
}
return Ok(());
}
self.page.place_videos(videos) self.page.place_videos(videos)
} }
+1 -1
View File
@@ -223,7 +223,7 @@ pub(crate) fn video_fit(props: Option<&Map<String, Value>>, file: &Path, at: f64
if !face { if !face {
return Some(VideoFit { at: (0.5, 0.5), to: (0.5, 0.5), scale }); return Some(VideoFit { at: (0.5, 0.5), to: (0.5, 0.5), scale });
} }
match raea_sys_facetrack::track(file) { match crate::faces::track(file) {
Ok(t) => t.eyes_at(at).map(|eyes| VideoFit { at: eyes, to: (0.5, 0.38), scale }), Ok(t) => t.eyes_at(at).map(|eyes| VideoFit { at: eyes, to: (0.5, 0.38), scale }),
Err(e) => { Err(e) => {
REFUSED.with(|c| c.borrow_mut().push(e)); REFUSED.with(|c| c.borrow_mut().push(e));
@@ -14,14 +14,14 @@ const RATE: f64 = 4.0;
const SIDE: u32 = 640; const SIDE: u32 = 640;
/// The eyes at each sample, in shares of the picture (None: no face in that sample). /// The eyes at each sample, in shares of the picture (None: no face in that sample).
pub struct Track { pub(crate) struct Track {
every: f64, every: f64,
eyes: Vec<Option<(f64, f64)>>, eyes: Vec<Option<(f64, f64)>>,
} }
impl Track { impl Track {
/// The eyes at `t` seconds: between the samples around it, or the nearest sample with a face. /// The eyes at `t` seconds: between the samples around it, or the nearest sample with a face.
pub fn eyes_at(&self, t: f64) -> Option<(f32, f32)> { pub(crate) fn eyes_at(&self, t: f64) -> Option<(f32, f32)> {
let i = (t / self.every).max(0.0); let i = (t / self.every).max(0.0);
let (a, b) = (i.floor() as usize, i.ceil() as usize); let (a, b) = (i.floor() as usize, i.ceil() as usize);
let got = match (self.eyes.get(a).copied().flatten(), self.eyes.get(b).copied().flatten()) { let got = match (self.eyes.get(a).copied().flatten(), self.eyes.get(b).copied().flatten()) {
@@ -44,7 +44,7 @@ thread_local! {
/// `take`'s face track: TAKE.faces.json when it's there and made from the take as it is now, else made (and kept). /// `take`'s face track: TAKE.faces.json when it's there and made from the take as it is now, else made (and kept).
/// An error says why there's none (no raea-perceive, no face in the take), once per take. /// An error says why there's none (no raea-perceive, no face in the take), once per take.
pub fn track(take: &Path) -> Result<Rc<Track>, String> { pub(crate) fn track(take: &Path) -> Result<Rc<Track>, String> {
if let Some(t) = TRACKS.with_borrow(|m| m.get(take).cloned()) { if let Some(t) = TRACKS.with_borrow(|m| m.get(take).cloned()) {
return t; return t;
} }
+1
View File
@@ -36,6 +36,7 @@ pub use world::*;
// app screens (`<Screen app>`): a component on @raea/ui's react-dom in a raea-runtime-js root of its own // app screens (`<Screen app>`): a component on @raea/ui's react-dom in a raea-runtime-js root of its own
pub mod screen; pub mod screen;
// a take's face track (<Video framing="face">) // a take's face track (<Video framing="face">)
pub(crate) mod faces;
type R<T> = Result<T, String>; type R<T> = Result<T, String>;
-16
View File
@@ -1,16 +0,0 @@
[package]
name = "raea-runtime-review"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "render --review's tiles and sheets: each fixed camera rendered by a child raea in colour and in clay, stitched into two sheets, with cameras.json and review.json"
[dependencies]
# the views, a tile's width and the arguments a tile's render takes
raea-core-review = { path = "../../core/review" }
raea-core-facts = { path = "../../core/facts" }
# each colour tile's exposure
raea-sys-light-meter = { path = "../../systems/light-meter" }
image = { version = "0.25", default-features = false, features = ["png"] }
serde_json = "1"
-83
View File
@@ -1,83 +0,0 @@
//! `raea render EDIT.tsx --review DIR`'s tiles and sheets (raea-runtime-export's review measures the frame's parts and
//! places the cameras, raea-core-review): each view rendered by a child raea with RAEA_CAMERA, in colour and (with
//! RAEA_CLAY) in clay, its exposure read, the tiles stitched into DIR/colour.png and DIR/clay.png, and DIR/cameras.json
//! and DIR/review.json written: the cameras, each tile's place on the sheets and its exposure, and what that found.
use raea_core_review::{Box3, TILE_W, VIEWS, passed};
use serde_json::{Value, json};
use std::path::Path;
/// A view and its camera (eye, target, field of view); None is the scene's own camera (hero).
pub type View<'a> = (&'a str, Option<([f64; 3], [f64; 3], f64)>);
/// What the tiles are of: the frame, its picture's aspect, its parts' box, and whether it's seen from inside.
pub struct Shot {
pub frame: i64,
pub aspect: f64,
pub parts: Box3,
pub interior: bool,
}
/// The review of `tsx`'s frame from `cams` into `dir_out`; `args` are the render's own (the ones a tile's render
/// takes too are passed on). Answers the render's APPLIED line and what the tiles' exposure found.
pub fn sheets(tsx: &Path, args: &[String], dir_out: &Path, cams: &[View], Shot { frame, aspect, parts: (lo, hi), interior }: Shot) -> Result<String, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let rest = passed(args);
let mut tiles = Vec::new();
let mut said = Vec::new();
for (view, cam) in cams {
for mode in ["colour", "clay"] {
let out = dir_out.join(format!("{view}-{mode}.png"));
let mut cmd = std::process::Command::new(&exe);
cmd.arg("render").arg(&tsx).args(&rest).args(["--frame", &frame.to_string(), "-o"]).arg(&out);
// a tile is part of this render: the review keeps the one entry in the project's record (DR3)
cmd.env_remove("RAEA_CAMERA").env_remove("RAEA_CLAY").env("RAEA_RECORD", "off");
if let Some((e, t, f)) = cam {
cmd.env("RAEA_CAMERA", format!("{},{},{},{},{},{},{}", e[0], e[1], e[2], t[0], t[1], t[2], f));
}
if mode == "clay" {
cmd.env("RAEA_CLAY", "1");
}
let run = cmd.output().map_err(|e| format!("--review: {e}"))?;
if !run.status.success() || !out.is_file() {
let text = format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
return Err(format!("--review: the {view} {mode} render failed: {}", text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
}
}
let colour = dir_out.join(format!("{view}-colour.png"));
let (_, ev) = raea_sys_light_meter::exposure::of_pngs(std::slice::from_ref(&colour))?;
// what a tile's exposure found, counted with the render's findings (DR3)
let tile: Vec<raea_core_facts::Finding> = ev["found"].as_array().into_iter().flatten().filter_map(|f| {
raea_core_facts::Finding::of_value(&json!({"check": "exposure", "level": f["level"], "says": format!("{view} tile: {}", f["says"].as_str().unwrap_or("").trim_start_matches("the frame: "))}), "raea render")
}).collect();
raea_core_facts::finding::said(&tile);
said.extend(tile);
tiles.push(json!({"view": view, "colour": format!("{view}-colour.png"), "clay": format!("{view}-clay.png"), "exposure": ev["exposure"],
"camera": cam.map(|(e, t, f)| json!({"eye": e, "target": t, "fov": f}))}));
}
// the sheets: three across, two down, each tile TILE_W wide
let th = (TILE_W as f64 / aspect).round().max(1.0) as u32;
for mode in ["colour", "clay"] {
let mut sheet = image::RgbaImage::from_pixel(TILE_W * 3, th * 2, image::Rgba([0, 0, 0, 255]));
for (i, view) in VIEWS.iter().enumerate() {
let img = image::open(dir_out.join(format!("{view}-{mode}.png"))).map_err(|e| format!("{view}-{mode}.png: {e}"))?.to_rgba8();
let small = image::imageops::resize(&img, TILE_W, th, image::imageops::FilterType::Triangle);
image::imageops::overlay(&mut sheet, &small, (i as u32 % 3 * TILE_W) as i64, (i as u32 / 3 * th) as i64);
}
sheet.save(dir_out.join(format!("{mode}.png"))).map_err(|e| format!("{mode}.png: {e}"))?;
}
for (i, t) in tiles.iter_mut().enumerate() {
t["rect"] = json!([i as u32 % 3 * TILE_W, i as u32 / 3 * th, TILE_W, th]);
}
let cameras: Vec<Value> = tiles.iter().map(|t| json!({"view": t["view"], "camera": t["camera"]})).collect();
std::fs::write(dir_out.join("cameras.json"), serde_json::to_string_pretty(&json!({"frame": frame, "box": {"min": lo, "max": hi}, "interior": interior, "cameras": cameras})).unwrap_or_default()).map_err(|e| e.to_string())?;
let doc = json!({"frame": frame, "sheets": {"colour": "colour.png", "clay": "clay.png"}, "size": [TILE_W * 3, th * 2],
"caption": if interior { "An interior, seen from inside: tiles left to right, top to bottom: hero, front, right, top (under the ceiling), iso, low (0.3 m). Clay: every standard surface light grey and matte." } else { "Tiles left to right, top to bottom: hero, front, right, top, iso, low (0.3 m). Clay: every standard surface light grey and matte." },
"box": {"min": lo, "max": hi}, "tiles": tiles, "found": said});
std::fs::write(dir_out.join("review.json"), serde_json::to_string_pretty(&doc).unwrap_or_default()).map_err(|e| e.to_string())?;
let mut msg = format!("APPLIED review of frame {frame}: {} and {} (hero, front, right, top, iso, low), cameras and exposure in {}", dir_out.join("colour.png").display(), dir_out.join("clay.png").display(), dir_out.join("review.json").display());
for f in &said {
msg.push_str(&format!("\n{}", f.line()));
}
Ok(msg)
}
+2 -4
View File
@@ -87,10 +87,8 @@ impl LiveScene {
let mut want: [(&str, Option<f64>); WANT] = [("", None); WANT]; let mut want: [(&str, Option<f64>); WANT] = [("", None); WANT];
let mut nw = 0usize; let mut nw = 0usize;
let mut put = |k: &'static str, v: f64| { let mut put = |k: &'static str, v: f64| {
// a Transform's columns as the World's f32 holds them (FC1d), and a light's own rotation exact as parts.rs // a Transform's columns as the World's f32 holds them (FC1d), the rest to 6 decimals
// writes it (rot_q*: rounded here, a still sun was sent again on the first fast frame, PA18); the rest want[nw] = (k, Some(if PLACE.contains(&k) || k.starts_with("col_") { v } else { r6(v) }));
// to 6 decimals
want[nw] = (k, Some(if PLACE.contains(&k) || k.starts_with("col_") || k.starts_with("rot_q") { v } else { r6(v) }));
nw += 1; nw += 1;
}; };
let mut color: Option<std::borrow::Cow<str>> = None; let mut color: Option<std::borrow::Cow<str>> = None;
-94
View File
@@ -1,94 +0,0 @@
//! A sun placed by its own rotation (a Bevy Transform's, as brick-rush's `Transform.fromXyz(2, 8, 6).lookingAt(...)`)
//! keeps that rotation exact on live play's fast rows as on the full rows (docs/playables.feature PA18): the fast path
//! rounded it to 6 decimals, so a sun that never moved was sent again on the first fast frame, and RAEA_LIVE3D_CHECK
//! panicked there.
use raea_core_scene::Node3;
use raea_runtime_scene::{LiveScene, Shot};
use serde_json::{Value, json};
/// A part as a frame's scene hands it on: its kind, props, shape and children
fn part(kind: &str, props: Value, shape: Option<&str>, kids: Vec<Node3>) -> Node3 {
let props = std::sync::Arc::new(props.as_object().cloned().unwrap_or_default());
Node3 {
kind: kind.into(),
props,
shape: shape.map(Into::into),
at: None,
kids: kids.into(),
}
}
fn scene(q: [f64; 4]) -> Vec<Node3> {
let sun = json!({ "position": [2, 8, 6], "rotation": q, "illuminance": 9600, "shadow_maps_enabled": true });
let paint = part(
"MeshStandardMaterial",
json!({ "color": "#ff6a3d" }),
None,
vec![],
);
vec![
part("DirectionalLight", sun, None, vec![]),
part(
"Mesh",
json!({ "name": "brick" }),
Some("box(1,0.4,0.5)"),
vec![paint],
),
]
}
#[test]
fn a_sun_placed_by_its_rotation_is_the_same_on_both_paths() {
// SAFETY: the only test in this binary, set before anything reads the environment
unsafe { std::env::set_var("RAEA_LIVE3D_CHECK", "1") };
// looking from (2, 8, 6) at the origin: digits past the sixth decimal
let q = [
-0.42470818758010864,
0.33985114097595215,
0.17591990530490875,
0.8204732537269592,
];
let mut ls = LiveScene::default();
let s = scene(q);
ls.open(
Shot {
scene: &s,
clear: None,
},
64,
64,
30.0,
);
for f in 0..3 {
let (set, gone) = ls.frame(Shot {
scene: &s,
clear: None,
});
assert!(gone.is_empty(), "frame {f}: nothing dropped: {gone:?}");
assert!(
set.iter()
.all(|t| !t.vals.keys().any(|k| k.starts_with("rot_q"))),
"frame {f}: a still sun is never sent again: {set:?}"
);
}
// a sun that turns sends the part of its rotation that changed, exact
let q2 = [
-0.42470818758010864,
0.3398512,
0.17591990530490875,
0.8204732537269592,
];
let s2 = scene(q2);
let (set, _) = ls.frame(Shot {
scene: &s2,
clear: None,
});
let sun = set
.iter()
.find(|t| t.vals.contains_key("rot_qy"))
.expect("the turned sun's rotation is sent");
assert_eq!(
sun.vals.get("rot_qy"),
Some(&raea_core_program::ir::V::N(q2[1]))
);
}
+28 -43
View File
@@ -4,7 +4,7 @@
// same whenever it's asked for (a frame of a video is a function of the frame, as rrl's `next:` rules make it). Under // same whenever it's asked for (a frame of a video is a function of the frame, as rrl's `next:` rules make it). Under
// plain bun the tables are TypeScript's own, with the same behaviour, so tests run anywhere. // plain bun the tables are TypeScript's own, with the same behaviour, so tests run anywhere.
import { ecsCall, hasEcs } from "./native"; import { hasNative, native } from "./native";
export type Value = number | string | boolean; export type Value = number | string | boolean;
export type Cols = Record<string, Value>; export type Cols = Record<string, Value>;
@@ -52,83 +52,76 @@ interface Store {
free(): void; free(): void;
} }
/** A store's tables freed when nothing holds it any more: a game's kept states are let go (games.ts KEEP), and the
* engine's (or a playable's wasm) worlds aren't collected with them. Freeing one twice is harmless. */
const unheld = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((world) => ecsCall("ecs.free", { world })) : null;
class NativeStore implements Store { class NativeStore implements Store {
constructor(readonly world: number) { constructor(readonly world: number) {}
unheld?.register(this, world, this);
}
static create(): NativeStore { static create(): NativeStore {
return new NativeStore(ecsCall("ecs.new", {}).world); return new NativeStore(native("ecs.new", {}).world);
} }
spawn(kind: string, cols: Cols) { spawn(kind: string, cols: Cols) {
return ecsCall("ecs.spawn", { world: this.world, kind, cols }).id; return native("ecs.spawn", { world: this.world, kind, cols }).id;
} }
spawnComponents(components: Components, parent?: number) { spawnComponents(components: Components, parent?: number) {
return ecsCall("ecs.spawn", parent === undefined ? { world: this.world, components } : { world: this.world, components, parent }).id; return native("ecs.spawn", parent === undefined ? { world: this.world, components } : { world: this.world, components, parent }).id;
} }
insert(id: number, components: Components) { insert(id: number, components: Components) {
ecsCall("ecs.insert", { world: this.world, id, components }); native("ecs.insert", { world: this.world, id, components });
} }
remove(id: number, names: string[]) { remove(id: number, names: string[]) {
ecsCall("ecs.remove", { world: this.world, id, names }); native("ecs.remove", { world: this.world, id, names });
} }
components(id: number) { components(id: number) {
return ecsCall("ecs.components", { world: this.world, id }) as Components; return native("ecs.components", { world: this.world, id }) as Components;
} }
find(f: Find) { find(f: Find) {
return ecsCall("ecs.find", { world: this.world, with: f.with ?? [], without: f.without ?? [], where: f.where ?? [] }).ids; return native("ecs.find", { world: this.world, with: f.with ?? [], without: f.without ?? [], where: f.where ?? [] }).ids;
} }
setParent(id: number, parent: number | null) { setParent(id: number, parent: number | null) {
ecsCall("ecs.parent", { world: this.world, id, parent }); native("ecs.parent", { world: this.world, id, parent });
} }
parent(id: number) { parent(id: number) {
return ecsCall("ecs.parent", { world: this.world, id }) as number | null; return native("ecs.parent", { world: this.world, id }) as number | null;
} }
children(id: number) { children(id: number) {
return ecsCall("ecs.children", { world: this.world, id }); return native("ecs.children", { world: this.world, id });
} }
resource(name: string, value?: unknown) { resource(name: string, value?: unknown) {
return ecsCall("ecs.resource", value === undefined ? { world: this.world, name } : { world: this.world, name, value }); return native("ecs.resource", value === undefined ? { world: this.world, name } : { world: this.world, name, value });
} }
send(name: string, value: unknown) { send(name: string, value: unknown) {
ecsCall("ecs.send", { world: this.world, name, value }); native("ecs.send", { world: this.world, name, value });
} }
events(name: string) { events(name: string) {
return ecsCall("ecs.events", { world: this.world, name }); return native("ecs.events", { world: this.world, name });
} }
clearEvents() { clearEvents() {
ecsCall("ecs.clear_events", { world: this.world }); native("ecs.clear_events", { world: this.world });
} }
set(id: number, cols: Cols) { set(id: number, cols: Cols) {
ecsCall("ecs.set", { world: this.world, id, cols }); native("ecs.set", { world: this.world, id, cols });
} }
get(id: number) { get(id: number) {
return ecsCall("ecs.get", { world: this.world, id }); return native("ecs.get", { world: this.world, id });
} }
despawn(id: number) { despawn(id: number) {
ecsCall("ecs.despawn", { world: this.world, id }); native("ecs.despawn", { world: this.world, id });
} }
query(kind: string, where: Where) { query(kind: string, where: Where) {
return ecsCall("ecs.query", { world: this.world, kind, where }).ids; return native("ecs.query", { world: this.world, kind, where }).ids;
} }
column(kind: string, col: string) { column(kind: string, col: string) {
return ecsCall("ecs.column", { world: this.world, kind, col }); return native("ecs.column", { world: this.world, kind, col });
} }
count(kind: string) { count(kind: string) {
return ecsCall("ecs.count", { world: this.world, kind }); return native("ecs.count", { world: this.world, kind });
} }
rows() { rows() {
return ecsCall("ecs.rows", { world: this.world }); return native("ecs.rows", { world: this.world });
} }
clone() { clone() {
return new NativeStore(ecsCall("ecs.clone", { world: this.world }).world); return new NativeStore(native("ecs.clone", { world: this.world }).world);
} }
free() { free() {
unheld?.unregister(this); native("ecs.free", { world: this.world });
ecsCall("ecs.free", { world: this.world });
} }
} }
@@ -283,9 +276,7 @@ export class World {
/** A world on `store`: the engine's tables when it has them, else TypeScript's (createWorld picks for you). */ /** A world on `store`: the engine's tables when it has them, else TypeScript's (createWorld picks for you). */
constructor(store?: Store) { constructor(store?: Store) {
this.native = store ? store instanceof NativeStore : hasEcs(); this.native = store ? store instanceof NativeStore : hasNative();
// a playable's export reads this to carry Bevy's world (sdk/playable export/walk.ts, PA12)
(globalThis as { __raeaEcsUsed?: boolean }).__raeaEcsUsed = true;
this.store = store ?? (this.native ? NativeStore.create() : new JsStore()); this.store = store ?? (this.native ? NativeStore.create() : new JsStore());
} }
@@ -376,7 +367,7 @@ export class World {
* hands this to the renderer). From the engine's tables natively; from the world's own store in a browser (raea-web), * hands this to the renderer). From the engine's tables natively; from the world's own store in a browser (raea-web),
* the same list as runtime/calls ecs.scene makes. */ * the same list as runtime/calls ecs.scene makes. */
scene(): unknown[] { scene(): unknown[] {
if (this.store instanceof NativeStore) return ecsCall("ecs.scene", { world: this.store.world }); if (this.store instanceof NativeStore) return native("ecs.scene", { world: this.store.world });
const store = this.store; const store = this.store;
const out: unknown[] = []; const out: unknown[] = [];
for (const id of store.find({ with: ["Mesh"] })) { for (const id of store.find({ with: ["Mesh"] })) {
@@ -403,12 +394,6 @@ export class World {
this.store.clearEvents(); this.store.clearEvents();
for (const s of this.systems) s(this, frame); for (const s of this.systems) s(this, frame);
} }
/** A copy of the world as it is now, with its systems: a game's next state (`useGameState`), stepped on its own. */
copy(): World {
const w = new World(this.store.clone());
w.systems = this.systems;
return w;
}
/** The world after frames 0..frame-1 have run (a copy; this world as built is the state before frame 0). */ /** The world after frames 0..frame-1 have run (a copy; this world as built is the state before frame 0). */
at(frame: number): World { at(frame: number): World {
if (!Number.isInteger(frame) || frame < 0) throw new RangeError(`World.at: a frame number from 0, got ${frame}`); if (!Number.isInteger(frame) || frame < 0) throw new RangeError(`World.at: a frame number from 0, got ${frame}`);
@@ -457,7 +442,7 @@ function compose(p: number[], c: number[]): number[] {
export function createWorld(opts: { native?: boolean } = {}): World { export function createWorld(opts: { native?: boolean } = {}): World {
if (opts.native === false) return new World(new JsStore()); if (opts.native === false) return new World(new JsStore());
if (opts.native === true && !hasEcs()) throw new Error("createWorld({ native: true }) needs the raea engine"); if (opts.native === true && !hasNative()) throw new Error("createWorld({ native: true }) needs the raea engine");
return new World(); return new World();
} }
+1 -17
View File
@@ -20,28 +20,12 @@ export function hasNative(): boolean {
/** One native call; its answer parsed. Throws (with the engine's message) when the call fails. */ /** One native call; its answer parsed. Throws (with the engine's message) when the call fails. */
export function native<K extends NativeName>(name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] { export function native<K extends NativeName>(name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
return through(bridge(), name, args); const call = bridge();
}
function through<K extends NativeName>(call: NativeCall | null, name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
if (!call) throw new Error(`${name} needs the raea engine (raea render or run); it isn't available under plain bun`); if (!call) throw new Error(`${name} needs the raea engine (raea render or run); it isn't available under plain bun`);
const out = call(name, JSON.stringify(args)); const out = call(name, JSON.stringify(args));
return (out === undefined || out === "" ? undefined : JSON.parse(out)) as NativeCalls[K]["answer"]; return (out === undefined || out === "" ? undefined : JSON.parse(out)) as NativeCalls[K]["answer"];
} }
/** raea/ecs's calls: the engine's, else a playable's (Bevy's world as wasm, sdk/playable host/ecs.ts, PA12) */
function ecsBridge(): NativeCall | null {
return bridge() ?? (globalThis as { __raeaEcs?: NativeCall }).__raeaEcs ?? null;
}
/** Whether raea/ecs's calls are here: in the engine, or in a playable that carries Bevy's world. */
export function hasEcs(): boolean {
return ecsBridge() !== null;
}
/** One of raea/ecs's calls (an `ecs.*` name), wherever its world is. */
export function ecsCall<K extends NativeName & `ecs.${string}`>(name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
return through(ecsBridge(), name, args);
}
/** Print a line from a headless run (raea run). */ /** Print a line from a headless run (raea run). */
export function print(...parts: unknown[]): void { export function print(...parts: unknown[]): void {
const text = parts.map((p) => (typeof p === "string" ? p : JSON.stringify(p))).join(" "); const text = parts.map((p) => (typeof p === "string" ? p : JSON.stringify(p))).join(" ");
+3 -9
View File
@@ -38,20 +38,14 @@ function describe(kind: AssetKind, prompt: string, seconds: number): GeneratedAs
return { kind, prompt, seconds, id, src: `asset:${kind}/${id}` }; return { kind, prompt, seconds, id, src: `asset:${kind}/${id}` };
} }
/** Every asset described so far, by src (`raea playable` makes each one at export and carries it in the page, PA6) */
export function describedAssets(): Map<string, GeneratedAsset> {
return ((globalThis as { __raeaGeneratedAssets?: Map<string, GeneratedAsset> }).__raeaGeneratedAssets ??= new Map());
}
const described = (a: GeneratedAsset) => (describedAssets().set(a.src, a), a);
/** Music an older edit generated (30 seconds by default). Retired: a take already made plays, a new one is refused. */ /** Music an older edit generated (30 seconds by default). Retired: a take already made plays, a new one is refused. */
export function lyria(prompt: string, options: { seconds?: number } = {}): GeneratedAsset { export function lyria(prompt: string, options: { seconds?: number } = {}): GeneratedAsset {
return described(describe("lyria", prompt, options.seconds ?? 30)); return describe("lyria", prompt, options.seconds ?? 30);
} }
/** A sound effect to generate (2 seconds by default). */ /** A sound effect to generate (2 seconds by default). */
export function sao(prompt: string, options: { seconds?: number } = {}): GeneratedAsset { export function sao(prompt: string, options: { seconds?: number } = {}): GeneratedAsset {
return described(describe("sao", prompt, options.seconds ?? 2)); return describe("sao", prompt, options.seconds ?? 2);
} }
/** Retired on 2026-11-05: Fish narration is no longer part of raea. Narrate with `<Speech text start>` from /** Retired on 2026-11-05: Fish narration is no longer part of raea. Narrate with `<Speech text start>` from
@@ -69,7 +63,7 @@ export function tokensynthNote(timbre: string, midi: number, options: { seconds?
// params, so the cache key says which precision made the note // params, so the cache key says which precision made the note
const o = { midi, velocity: options.velocity ?? 100, seed: options.seed ?? 1234, device: "cpu", precision: options.precision ?? "fp16" }; const o = { midi, velocity: options.velocity ?? 100, seed: options.seed ?? 1234, device: "cpu", precision: options.precision ?? "fp16" };
const key = `${a.id}:${midi}:${o.velocity}:${o.seed}:${o.precision}`; const key = `${a.id}:${midi}:${o.velocity}:${o.seed}:${o.precision}`;
return described({ ...a, id: key, src: `asset:tokensynth/${key}`, options: o }); return { ...a, id: key, src: `asset:tokensynth/${key}`, options: o };
} }
/** Whether a value is a generated asset (what sao, tokensynthNote and lyria return), not a file path. */ /** Whether a value is a generated asset (what sao, tokensynthNote and lyria return), not a file path. */
-249
View File
@@ -1,249 +0,0 @@
# Where a farm run's seconds go, and what each encoder costs and keeps (docs/cloud-render.feature CR27, CR31): the same
# frames of one project rendered on a GPU container sized as the farm's (farm_plan.RESERVED), once to PNGs (no video
# encoder: the picture every encode is scored against) and once through each encoder, timed. From sdk/cloud:
#
# MODAL_PROFILE=raea modal run bench/encode.py --dir ../../bench/rerender --args "render film.tsx --composition cut" --frames 0-299
# ... --encoders x264,soft,nvenc --out bench/results/encode-film.json
# ... --gpu none --cpu 8 --gib 8 the same on a container with no GPU (lavapipe), sized as said: what a piece
# with no 3D costs where nothing waits on a graphics card
#
# Each encoder's row: s (the run's wall time), ms a frame over the run, cores busy on average, the file's MB, SSIM and
# PSNR against the PNGs (all frames, and the darkest tenth of them alone, where an encoder's blocks show), what
# `raea check` says of its picture (the blotching line), raea's own RAEA_TIMES line, and the ffmpeg command raea ran.
# png raea's frames as PNGs: the reference, and a run with no video encoder
# x264 RAEA_MEDIA=ffmpeg: libx264 medium at the quality's CRF on the container's cores (the farm today)
# soft raea's own portable encoder (openh264 at a bitrate): the farm before 11-30
# nvenc RAEA_MEDIA=ffmpeg with h264_nvenc in libx264's place (constant QP at the CRF's number), on the run's own GPU
# An ephemeral app: it never touches the deployed farm.
import json
import os
import sys
import modal
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(HERE), "deploy", "modal"))
import farm # noqa: E402 the farm's image, so the bench measures what the farm runs
import farm_plan # noqa: E402
app = modal.App("raea-farm-encode-bench", image=farm.image.add_local_python_source("farm"))
CPU, GIB = farm_plan.RESERVED["raea"]
# ffmpeg in the encoder's place: raea's ffmpeg backend names libx264 itself (io/ffmpeg), so the bench swaps the encoder
# where raea calls it. RAEA_BENCH_ENCODER holds the arguments that replace "-c:v libx264 -preset medium -crf N" ({q} is N)
WRAP = r"""#!/usr/bin/env python3
import json, os, sys
a = sys.argv[1:]
said = os.environ.get("RAEA_BENCH_SAID", "/dev/null")
with open(said, "a") as f:
f.write(" ".join(a) + "\n")
enc = json.loads(os.environ.get("RAEA_BENCH_ENCODER") or "null")
if enc and "libx264" in a and "rawvideo" in a:
i = a.index("-c:v")
if "-crf" in a:
j = a.index("-crf") + 2
new = enc["crf"].format(q=a[j - 1])
else:
j = a.index("-bufsize") + 2
new = enc["rate"].format(b=a[a.index("-b:v") + 1], m=a[a.index("-maxrate") + 1], u=a[j - 1])
a = a[:i] + new.split() + a[j:]
with open(said, "a") as f:
f.write("-> " + " ".join(a) + "\n")
os.execv("/usr/bin/ffmpeg", ["ffmpeg", *a])
"""
# what replaces "-c:v libx264 -preset medium" and its rate arguments where raea calls ffmpeg: "crf" when the render
# names a quality ({q} the CRF), "rate" when it doesn't ({b}, {m}, {u}: the bitrate, its ceiling and the buffer)
NV = "-c:v h264_nvenc -preset {p} -tune hq -bf 2 -g 60 -spatial-aq 1 -temporal-aq 1"
ENCODERS = {
"x264": {"RAEA_MEDIA": "ffmpeg"},
"soft": {"RAEA_MEDIA": "soft"},
"nvenc": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": NV.format(p="p5") + " -rc constqp -qp {q}", "rate": NV.format(p="p5") + " -rc vbr -b:v {b} -maxrate {m} -bufsize {u}"})},
"nvenc-p7": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": NV.format(p="p7") + " -rc constqp -qp {q}", "rate": NV.format(p="p7") + " -rc vbr -b:v {b} -maxrate {m} -bufsize {u}"})},
"x264-fast": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": "-c:v libx264 -preset veryfast -crf {q}", "rate": "-c:v libx264 -preset veryfast -b:v {b} -maxrate {m} -bufsize {u}"})},
}
def _sample(stop, rows):
"""What the container's processes are doing while a render runs: every 2 s, each process's name and CPU seconds so
far (ps), so a run's cores can be put to raea's threads or to the ffmpeg children it starts."""
import subprocess
import time
while not stop.is_set():
o = subprocess.run(["ps", "-eLo", "pid,comm,time,args", "--no-headers"], capture_output=True, text=True).stdout
rows.append((time.time(), o))
stop.wait(2)
def _run(cmd, cwd, env, timeout=3600):
import resource
import subprocess
import time
for d in (farm.CACHES["__GL_SHADER_DISK_CACHE_PATH"], farm.CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True)
u0, t = resource.getrusage(resource.RUSAGE_CHILDREN), time.time()
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **farm.CACHES, **env}, timeout=timeout)
u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t
return r.returncode, r.stdout + r.stderr, s, round((u1.ru_utime + u1.ru_stime - u0.ru_utime - u0.ru_stime) / max(s, 0.001), 2)
def _score(video, pngs, first, fps, dark):
"""SSIM and PSNR of `video` against the PNGs: over every frame, and over the darkest tenth (`dark`: frame indexes)."""
import re
import subprocess
def one(select):
vf = f"[0:v]{select}format=yuv420p[a];[1:v]{select}format=yuv420p[b];[a][b]ssim;[0:v]{select}format=yuv420p[c];[1:v]{select}format=yuv420p[d];[c][d]psnr"
r = subprocess.run(["ffmpeg", "-hide_banner", "-i", video, "-framerate", str(fps), "-start_number", str(first), "-i", f"{pngs}/frame-%05d.png", "-lavfi", vf, "-f", "null", "-"], capture_output=True, text=True)
s, p = re.search(r"SSIM .*All:([\d.]+)", r.stderr), re.search(r"PSNR .*average:([\d.inf]+)", r.stderr)
return (float(s.group(1)) if s else None, float(p.group(1)) if p and p.group(1) != "inf" else None)
out = dict(zip(("ssim", "psnr"), one("")))
if dark:
sel = "select='" + "+".join(f"eq(n\\,{i})" for i in dark) + "',"
out |= dict(zip(("ssim_dark", "psnr_dark"), one(sel)))
return out
@app.function(gpu="T4", cpu=CPU, memory=GIB * 1024, volumes={farm.ROOT: farm.vol, "/models": farm.models}, timeout=3600)
def measure(folder: bytes, args: list[str], first: int, last: int, encoders: list[str], check: bool = True, media: list | None = None, cpu_only: bool = False, size: tuple = (CPU, GIB), extra: dict | None = None, png: bool = True) -> dict:
import re
import shutil
import subprocess
import tarfile
import io
import farm_media
say = lambda *a: print(*a, flush=True)
# the job's folder on the volume, where the farm's own jobs are: a media link into the cache resolves there
work = f"{farm.JOBS}/bench-{os.environ.get('MODAL_TASK_ID', 'x')}/work"
shutil.rmtree(work, ignore_errors=True)
os.makedirs(work)
tarfile.open(fileobj=io.BytesIO(folder)).extractall(work)
if media:
with open(f"{work}/{farm_media.MANIFEST}", "w") as f:
json.dump({"objects": media}, f)
farm_media.fetch(work, f"{farm.ROOT}/blobs", say)
base = dict(farm.CPU_ENV) if cpu_only else {}
extra = extra or {}
os.makedirs("/tmp/bin", exist_ok=True)
with open("/tmp/bin/ffmpeg", "w") as f:
f.write(WRAP)
os.chmod("/tmp/bin/ffmpeg", 0o755)
path = "/tmp/bin:" + os.environ["PATH"]
at = ",".join(map(str, range(first, last + 1)))
n = last - first + 1
res = {"gpu": "" if cpu_only else farm.kind(), "cores": size[0], "gib": size[1], "raea": farm.RAEA, "frames": n, "args": args,
"has": subprocess.run("ffmpeg -hide_banner -encoders 2>/dev/null | grep -E '264|hevc|av1' | awk '{print $2}'", shell=True, capture_output=True, text=True).stdout.split(),
"nvidia": subprocess.run(["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv,noheader"], capture_output=True, text=True).stdout.strip(), "rows": {}}
# a first run nobody times: the shader caches, the models, the page's fonts
code, out, s, _ = _run(["raea", *args, "--at", f"{first},{first + 1}", "-o", "/tmp/warm"], work, {**base, "PATH": path})
say(f"warm-up: exit {code} in {s:.1f} s", out[-300:] if code else "")
pngs = "/tmp/png"
shutil.rmtree(pngs, ignore_errors=True)
code, out, s, cores = _run(["raea", *args, "--at", at, "-o", pngs], work, {**base, "PATH": path, "RAEA_TIMES": "1"}) if png else (0, "", 0.0, 0.0)
say(f"png: exit {code}, {n} frames in {s:.1f} s, {cores} cores busy")
made = sorted(x for x in os.listdir(pngs) if x.endswith(".png")) if os.path.isdir(pngs) else []
for i, name in enumerate(made): # named by their frame, as the encodes' frames are counted
os.rename(f"{pngs}/{name}", f"{pngs}/t-{first + i:05d}.png")
for i in range(len(made)):
os.rename(f"{pngs}/t-{first + i:05d}.png", f"{pngs}/frame-{first + i:05d}.png")
fps = 30
m = re.search(r"(\d+(?:\.\d+)?) fps", out)
if made:
# each frame's pixels as a hash, and a few frames whole, to hold one container's picture against another's
md5 = subprocess.run(["ffmpeg", "-v", "error", "-framerate", str(fps), "-start_number", str(first), "-i", f"{pngs}/frame-%05d.png", "-pix_fmt", "rgba", "-f", "framemd5", "-"], capture_output=True, text=True).stdout
res["frame_md5"] = [l.split(",")[-1].strip() for l in md5.splitlines() if l and not l.startswith("#")]
res["frame_png"] = {str(first + i): open(f"{pngs}/frame-{first + i:05d}.png", "rb").read() for i in sorted({0, len(made) // 2, len(made) - 1})} if extra.get("BENCH_KEEP") else {}
res["rows"]["png"] = {"code": code, "s": round(s, 2), "ms": round(1000 * s / n, 1), "cores": cores, "frames": len(made), "times": [l for l in out.splitlines() if " ms" in l][-12:], "out": out[-600:] if code else ""}
# the darkest tenth of the frames, by mean luma
dark = []
if made:
import cv2
lum = [(float(cv2.imread(f"{pngs}/frame-{first + i:05d}.png", cv2.IMREAD_GRAYSCALE)[::8, ::8].mean()), i) for i in range(len(made))]
dark = sorted(i for _, i in sorted(lum)[: max(1, len(lum) // 10)])
res["dark_luma"] = round(sorted(lum)[len(dark) - 1][0], 1)
for name in encoders:
env = {**base, "PATH": path, "RAEA_TIMES": "1", "RAEA_STARTUP_TRACE": "1", **extra, "RAEA_BENCH_SAID": f"/tmp/{name}.said", **ENCODERS[name]}
video = f"/tmp/{name}.mp4"
for p in (video, env["RAEA_BENCH_SAID"]):
if os.path.exists(p):
os.remove(p)
import threading
stop, snaps = threading.Event(), []
th = threading.Thread(target=_sample, args=(stop, snaps), daemon=True)
if extra.get("BENCH_DIAG"):
th.start()
code, out, s, cores = _run(["raea", *args, "--at", at, "-o", video], work, env)
stop.set()
row = {"code": code, "s": round(s, 2), "ms": round(1000 * s / n, 1), "cores": cores, "said_ms": (re.search(r"([\d.]+) ms a frame", out) or [None, None])[1],
"times": [l for l in out.splitlines() if " ms" in l or "raea startup" in l][-40:], "out": out[-800:] if code else ""}
if os.path.exists(env["RAEA_BENCH_SAID"]):
calls = [l for l in open(env["RAEA_BENCH_SAID"]).read().splitlines() if not l.startswith("->")]
row["ffmpeg"] = [l for l in open(env["RAEA_BENCH_SAID"]).read().splitlines() if "rawvideo" in l][-2:]
row["ffmpeg_calls"] = len(calls)
row["ffmpeg_decodes"] = len([l for l in calls if " -ss " in f" {l} "])
row["ffmpeg_decode_sample"] = [l[:260] for l in calls if " -ss " in f" {l} "][:6]
if snaps:
# the middle snapshot's processes, and how many distinct ffmpeg pids were seen over the run
pids = {l.split()[0] for _, o in snaps for l in o.splitlines() if " ffmpeg" in l[:40]}
mid = snaps[len(snaps) // 2][1].splitlines()
row["ps_ffmpeg_pids"] = len(pids)
row["ps_mid"] = sorted({" ".join(l.split()[1:3]) + " " + " ".join(l.split()[3:])[:120] for l in mid if l.split()[2] != "00:00:00"})[:40]
if os.path.exists(video):
row["mb"] = round(os.path.getsize(video) / 1e6, 2)
pr = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames,codec_name,profile,r_frame_rate", "-of", "csv=p=0", video], capture_output=True, text=True).stdout.strip()
row["probe"] = pr
if made:
row |= _score(video, pngs, first, fps, dark)
if check:
c, o, cs, _ = _run(["raea", "check", video], work, {"PATH": os.environ["PATH"]})
row["check"] = {"code": c, "s": round(cs, 1), "lines": [l.strip() for l in o.splitlines() if re.search(r"blotch|flash|freez|FAIL|PASS|passed|failed", l)][:12]}
res["rows"][name] = row
say(f"{name}: exit {code}, {s:.1f} s, {cores} cores busy, {row.get('mb')} MB, ssim {row.get('ssim')} dark {row.get('ssim_dark')}")
shutil.rmtree(os.path.dirname(work), ignore_errors=True)
return res
@app.local_entrypoint()
def main(dir: str, args: str, frames: str = "0-299", encoders: str = "x264,soft,nvenc", out: str = "", check: bool = True, gpu: str = "T4", cpu: int = CPU, gib: int = GIB, env: str = "", png: bool = True):
import hashlib
import io
import tarfile
a, _, b = frames.partition("-")
# files of 4 MB and more go by hash from the farm's cache, where a box's render put them (server/media.ts
# farmInputs); one the farm doesn't hold fails the run, which says so
media = []
def keep(i):
if i.name.startswith(("./out", "./.git", "./ios")):
return None
if i.isfile() and i.size >= 4 << 20:
h = hashlib.sha256()
with open(os.path.join(dir, i.name), "rb") as f:
for blk in iter(lambda: f.read(1 << 20), b""):
h.update(blk)
media.append({"path": i.name[2:], "oid": h.hexdigest(), "size": i.size})
return None
return i
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as t:
t.add(dir, arcname=".", filter=keep)
fn = measure.with_options(gpu=None if gpu == "none" else gpu, cpu=cpu, memory=gib * 1024)
r = fn.remote(buf.getvalue(), args.split(), int(a), int(b or a), [e for e in encoders.split(",") if e], check, media, gpu == "none", (cpu, gib), dict(kv.split("=", 1) for kv in env.split(",") if kv), png)
for n, b in (r.pop("frame_png", None) or {}).items():
if out:
with open(f"{os.path.splitext(out)[0]}-{int(n):05d}.png", "wb") as f:
f.write(b)
print(json.dumps({**r, "frame_md5": len(r.get("frame_md5") or [])}, indent=2))
if out:
with open(out, "w") as f:
json.dump(r, f, indent=2)
-130
View File
@@ -1,130 +0,0 @@
// One farm job, measured (docs/cloud-render.feature CR27): a folder sent the way a CPU box sends one, its log timed
// from the submit, and what the farm said about it read back as numbers. RAEA_CLOUD_GPU_URL and RAEA_CLOUD_GPU_TOKEN
// name the farm (~/.config/raea-cloud/farm.env), so the same job runs on the live farm and on a test deploy of it:
//
// node bench/job.ts DIR OUT.json [--gpus N] [--keep FILE] -- render film.tsx --composition cut -o out/film.mp4
//
// OUT.json: wall (s from the submit to the video here, on disk), sent and back (bytes), frames, w, h, frame_ms and
// start_s (the farm's timed first run), runs ([{frames, kind, s}]), join_s, billed_usd, up_s (its containers' life
// in all), cores and peak_gb (the busiest run's), first_s (when the first run of frames had landed), exit.
import { spawn, spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { RaeaCloud } from "../src/index.ts"
/** What a farm job's log says, as numbers: `lines` are [seconds from the submit, the line]. */
export function read(lines: [number, string][]) {
const o: Record<string, unknown> = { runs: [] as { frames: number; kind: string; s: number; at: number }[] }
const num = (s: string) => Number(s)
for (const [at, l] of lines) {
let m: RegExpMatchArray | null
if ((m = l.match(/(\d+) frames at (\d+)x(\d+), ([\d.]+) fps; frame 0 on a (\S+) in ([\d.]+) s/))) Object.assign(o, { frames: num(m[1]), w: num(m[2]), h: num(m[3]), fps: num(m[4]), kind: m[5], probe_s: num(m[6]) })
else if ((m = l.match(/([\d.]+) ms a frame, ([\d.]+) s to start; (\d+) frames left on (\d+) (\S+?)s?(?: with no GPU \(no 3D in it\))?(?: in (\d+) parts)?, about \$([\d.]+)/))) Object.assign(o, { frame_ms: num(m[1]), start_s: num(m[2]), gpus: num(m[4]), parts: num(m[6] ?? m[4]), estimate_usd: num(m[7]) })
else if ((m = l.match(/(\d+) frames on a (\S+) in ([\d.]+) s/))) (o.runs as object[]).push({ frames: num(m[1]), kind: m[2], s: num(m[3]), at })
else if ((m = l.match(/joined .* in ([\d.]+) s/))) Object.assign(o, { join_s: num(m[1]), joined_at: at })
else if ((m = l.match(/billed about \$([\d.]+): (\d+) GPU(?: and (\d+) CPU)? containers up ([\d.]+) s in all(?:; at most ([\d.]+) of (\d+) cores busy and ([\d.]+) of (\d+) GB)?/)))
Object.assign(o, { billed_usd: num(m[1]), containers: num(m[2]), cpu_containers: m[3] ? num(m[3]) : 0, up_s: num(m[4]), cores: m[5] ? num(m[5]) : undefined, reserved_cores: m[6] ? num(m[6]) : undefined, peak_gb: m[7] ? num(m[7]) : undefined, reserved_gb: m[8] ? num(m[8]) : undefined })
else if ((m = l.match(/(\d+) runs kept from an earlier render hold (\d+) of (\d+) frames/))) Object.assign(o, { kept_runs: num(m[1]), kept_frames: num(m[2]) })
else if (l.includes("nothing to draw: every frame is in a run kept")) o.all_kept = true
else if ((m = l.match(/its frames' keys read in ([\d.]+) s/))) Object.assign(o, { keys_s: num(m[1]) })
else if ((m = l.match(/first picture at (\S+)/))) Object.assign(o, { first_picture: m[1], first_picture_at: at })
}
const runs = o.runs as { at: number }[]
if (runs.length) o.first_s = runs[0].at
return o
}
/** The job as a box sends it: server/offload.ts in DIR (its media by hash through the farm's cache, the manifest it
* asks for), the box's own check after it left out. Resolves with the timed lines and the exit code. */
function offload(dir: string, args: string[], gpus: string | undefined, cpus: string | undefined, kept: string | undefined, said: (at: number, l: string) => void): Promise<number> {
const here = path.dirname(new URL(import.meta.url).pathname)
const t0 = performance.now()
const env = { ...process.env, RAEA_REAL: "/usr/bin/true", ...(gpus ? { RAEA_CLOUD_GPUS: gpus } : {}), ...(cpus ? { RAEA_CLOUD_CPUS: cpus } : {}), ...(kept === "0" ? { RAEA_CLOUD_KEPT: "0" } : {}) }
const child = spawn(process.execPath, [path.join(here, "..", "server", "offload.ts"), ...args], { cwd: dir, env, stdio: ["ignore", "pipe", "pipe"] })
let rest = ""
const eat = (b: Buffer) => {
const parts = (rest + b.toString()).split("\n")
rest = parts.pop() ?? ""
for (const l of parts) if (l.trim()) said((performance.now() - t0) / 1000, l)
}
child.stdout.on("data", eat)
child.stderr.on("data", eat)
return new Promise((done) => child.on("close", (code) => done(code ?? 1)))
}
async function main() {
const argv = process.argv.slice(2)
const cut = argv.indexOf("--")
if (cut < 2) throw new Error("usage: node bench/job.ts DIR OUT.json [--gpus N] [--cpus N] [--kept 0] [--keep FILE] [--offload] -- ARGS")
const [dir, outJson, ...flags] = argv.slice(0, cut)
const args = argv.slice(cut + 1)
const flag = (n: string) => (flags.includes(n) ? flags[flags.indexOf(n) + 1] : undefined)
const url = process.env.RAEA_CLOUD_GPU_URL
const token = process.env.RAEA_CLOUD_GPU_TOKEN
if (!url || !token) throw new Error("set RAEA_CLOUD_GPU_URL and RAEA_CLOUD_GPU_TOKEN (the farm's)")
if (flags.includes("--offload")) {
const lines: [number, string][] = []
const t0 = performance.now()
const exit = await offload(dir, args, flag("--gpus"), flag("--cpus"), flag("--kept"), (at, l) => {
lines.push([at, l])
console.log(`${at.toFixed(1).padStart(6)} s ${l}`)
})
const wall = (performance.now() - t0) / 1000
const o = args.indexOf("-o")
const video = o >= 0 ? path.resolve(dir, args[o + 1]) : ""
const size = video && existsSync(video) ? statSync(video).size : 0
const sentMb = lines.map(([, l]) => l.match(/\(([\d.]+) MB\) sent/)).find(Boolean)
const res = { args, farm: new URL(url).host, via: "offload", exit, wall: Number(wall.toFixed(1)), sent: sentMb ? Math.round(Number(sentMb[1]) * 1e6) : undefined, ...read(lines), bytes: size, log: lines.map(([t, l]) => `${t.toFixed(1)} ${l}`) }
writeFileSync(outJson, JSON.stringify(res, null, 2))
console.log(`${wall.toFixed(1).padStart(6)} s exit ${exit}; ${JSON.stringify({ ...res, log: undefined, args: undefined })}`)
const keep = flag("--keep")
if (keep && size) spawnSync("cp", [video, keep])
process.exitCode = exit
return
}
const tmp = mkdtempSync(path.join(os.tmpdir(), "raea-farm-bench-"))
try {
const sent = path.join(tmp, "in.tgz")
const pack = spawnSync("tar", ["-czf", sent, "--no-mac-metadata", "--exclude=./out", "--exclude=./.git", "-C", dir, "."], { env: { ...process.env, COPYFILE_DISABLE: "1" }, encoding: "utf8" })
if (pack.status) throw new Error(`the folder didn't pack: ${pack.stderr}`)
const folder = new Uint8Array(readFileSync(sent))
const cloud = new RaeaCloud({ url, token })
const t0 = performance.now()
const now = () => (performance.now() - t0) / 1000
const lines: [number, string][] = []
console.log(`${now().toFixed(1).padStart(6)} s ${(folder.length / 1e6).toFixed(2)} MB to ${new URL(url).host}: raea ${args.join(" ")}`)
const gpus = flag("--gpus")
const { exit, files } = await cloud.job(args, folder, {
as: "gz",
farm: { ...(gpus ? { gpus: Number(gpus) } : {}), ...(flag("--cpus") ? { cpus: Number(flag("--cpus")) } : {}) },
onOutput: (t) =>
t.split("\n").filter(Boolean).forEach((l) => {
lines.push([now(), l])
console.log(`${now().toFixed(1).padStart(6)} s ${l}`)
}),
})
const back = path.join(tmp, "out.tgz")
writeFileSync(back, files)
spawnSync("tar", ["-xzf", back, "-C", tmp])
const wall = now()
const o = args.indexOf("-o")
const video = o >= 0 ? path.join(tmp, args[o + 1]) : ""
const probe = video ? spawnSync("ffprobe", ["-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames,width,height:format=size", "-of", "json", video], { encoding: "utf8" }) : null
let got: Record<string, unknown> = {}
try {
const j = JSON.parse(probe?.stdout || "{}")
got = { got_frames: Number(j.streams?.[0]?.nb_read_frames), got_w: j.streams?.[0]?.width, got_h: j.streams?.[0]?.height, bytes: Number(j.format?.size) }
} catch {}
const res = { args, farm: new URL(url).host, exit, wall: Number(wall.toFixed(1)), sent: folder.length, back: files.length, ...read(lines), ...got, log: lines.map(([t, l]) => `${t.toFixed(1)} ${l}`) }
writeFileSync(outJson, JSON.stringify(res, null, 2))
console.log(`${wall.toFixed(1).padStart(6)} s exit ${exit}; ${JSON.stringify({ ...res, log: undefined, args: undefined })}`)
const keep = flag("--keep")
if (keep && video) spawnSync("cp", [video, keep])
process.exitCode = exit
} finally {
rmSync(tmp, { recursive: true, force: true })
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === new URL(import.meta.url).pathname) await main()
-98
View File
@@ -1,98 +0,0 @@
# A Linux raea built on Modal from a source folder, into the farm's volume (/farm/builds/NAME): how an engine change is
# measured on a test farm before a release carries it (docs/cloud-render.feature CR28). The farm's image installs the
# released raea, so without this an engine change couldn't be timed there at all. A test farm deployed with
# RAEA_FARM_BUILD=NAME runs this build's raea, with the released one's own files (share/raea) as its home:
#
# git archive TAG | tar -x -C SRC # the release's source; put the change's files over it
# MODAL_PROFILE=raea modal run deploy/modal/build.py --src SRC --name NAME
# RAEA_FARM_APP=raea-farm-m RAEA_FARM_BUILD=NAME modal deploy deploy/modal/farm.py
#
# The source's file times are kept (git archive gives every file its commit's), and cargo's registry, target folder
# and source are kept as one tar each on a volume of their own and unpacked onto the container's disk, so a second
# build compiles only the crates whose files changed. (Left as folders on the volume, cargo read the crates index one
# file at a time, about 4 a second: 13 min before it compiled anything, 11-30.)
import io
import os
import subprocess
import tarfile
import time
import modal
RUST = "1.99.1" # rust-toolchain.toml's
# release.yml's "Linux libraries", and what cargo's build scripts call
LIBS = ["build-essential", "pkg-config", "cmake", "ninja-build", "nasm", "clang", "git", "curl", "ca-certificates", "python3",
"libxkbcommon-dev", "libxkbcommon-x11-dev", "libasound2-dev", "libfontconfig1-dev", "libvulkan-dev", "libudev-dev", "libssl-dev"]
image = (
# the farm image's Debian, so the build links against the libraries it runs with
modal.Image.from_registry("debian:trixie-slim", add_python="3.12")
.apt_install(*LIBS)
.run_commands(f"curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain {RUST}")
.env({"PATH": "/root/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "CARGO_HOME": "/work/cargo", "CARGO_TARGET_DIR": "/work/target",
"RUSTUP_HOME": "/root/.rustup",
# no debug info: the farm's copy was stripped anyway (2.8 GB with it), and the link is far shorter
"CARGO_PROFILE_DIST_DEBUG": "0"})
)
KEPT = ("cargo", "target", "src")
app = modal.App("raea-farm-build", image=image)
farm = modal.Volume.from_name("raea-farm", create_if_missing=True, version=2)
cache = modal.Volume.from_name("raea-build", create_if_missing=True, version=2)
# (the target folder on the container's own disk, not the volume; Modal's smallest disk request is 512 GiB, so the default)
@app.function(cpu=32, memory=64 * 1024, timeout=4 * 3600, volumes={"/farm": farm, "/cache": cache})
def build(src: bytes, name: str, features: str) -> dict:
t = time.time()
os.makedirs("/work/src", exist_ok=True)
for d in KEPT:
if os.path.exists(f"/cache/{d}.tar"):
subprocess.run(["tar", "-xf", f"/cache/{d}.tar", "-C", "/work"], check=True)
print(f"build: the last build's folders unpacked in {time.time() - t:.0f} s", flush=True)
# over the last build's source, in place: an unchanged file keeps its time, so its crate isn't compiled again
with tarfile.open(fileobj=io.BytesIO(src), mode="r:gz") as tar:
tar.extractall("/work/src", filter="tar")
cmd = ["cargo", "build", "--profile", "dist", "--locked", "-p", "raea-cli", "--bin", "raea", "--no-default-features", "--features", features]
print("build:", " ".join(cmd), flush=True)
code = subprocess.run(cmd, cwd="/work/src").returncode
out = f"/farm/builds/{name}"
made = {}
if not code:
os.makedirs(out, exist_ok=True)
for f in ("raea", "libraea_bundle.so"):
p = f"/work/target/dist/{f}"
# without its debug info, as the release's is (2.8 GB with it, read from the volume at every container's start)
subprocess.run(["strip", "--strip-debug", "-o", f"{out}/{f}", p], check=True)
made[f] = os.path.getsize(f"{out}/{f}")
said = subprocess.run([f"{out}/raea", "--version"], capture_output=True, text=True, env={**os.environ, "RAEA_HOME": "/nonexistent"})
made["version"] = (said.stdout + said.stderr).strip()[-200:]
farm.commit()
for d in KEPT:
subprocess.run(["tar", "-cf", f"/cache/{d}.tar.part", "-C", "/work", d], check=True)
os.replace(f"/cache/{d}.tar.part", f"/cache/{d}.tar")
cache.commit()
return {"code": code, "s": round(time.time() - t), "out": out, **made}
@app.function(cpu=2, memory=8 * 1024, timeout=1800, volumes={"/farm": farm})
def slim(name: str) -> dict:
"""A build already in the volume, without its debug info."""
out = {}
for f in ("raea", "libraea_bundle.so"):
p = f"/farm/builds/{name}/{f}"
subprocess.run(["strip", "--strip-debug", p], check=True)
out[f] = os.path.getsize(p)
farm.commit()
return out
@app.local_entrypoint()
def main(src: str, name: str, features: str = ""):
if not features:
features = subprocess.run(["bash", "tools/bevy-plugins.sh", "features", "sdk/raea/bench/bevy-plugins"], cwd=src, capture_output=True, text=True).stdout.strip().splitlines()[-1]
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz", compresslevel=3) as tar:
tar.add(src, arcname=".")
print(f"build: {len(buf.getvalue()) / 1e6:.0f} MB of source, features {features}")
print(build.remote(buf.getvalue(), name, features))
+60 -232
View File
@@ -32,7 +32,6 @@ import re
import resource import resource
import shutil import shutil
import subprocess import subprocess
import threading
import time import time
import uuid import uuid
@@ -80,12 +79,6 @@ GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit;
# one job's GPUs unless it asks for more: a 1,150-frame cut took all 10 (each drawing 10-20 s), so every other render in # one job's GPUs unless it asks for more: a 1,150-frame cut took all 10 (each drawing 10-20 s), so every other render in
# the workspace queued behind it with nothing said (11-30, StreetTalk's three agents); 4 lets two or three render at once # the workspace queued behind it with nothing said (11-30, StreetTalk's three agents); 4 lets two or three render at once
JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4")) JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4"))
# the containers with no GPU a job's video with no 3D is drawn on at once (raea_cpu_run), and the farm's in all: no
# workspace limit holds these back as it does GPUs
# 32 since 12-01: at 8, a 34 s ad's 16 parts ran two after another on each container, 53 s of a 104 s render, and
# at 16 a 35 s one still drew for 73 s beside another job; the containers' seconds, and so the bill, are the same
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "32"))
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "128"))
ROOT = "/farm" ROOT = "/farm"
JOBS = f"{ROOT}/jobs" JOBS = f"{ROOT}/jobs"
@@ -93,7 +86,7 @@ image = (
modal.Image.from_registry("debian:trixie-slim", add_python="3.12") modal.Image.from_registry("debian:trixie-slim", add_python="3.12")
.apt_install( .apt_install(
"ca-certificates", "curl", "xz-utils", "zstd", "procps", "ffmpeg", "ca-certificates", "curl", "xz-utils", "zstd", "procps", "ffmpeg",
"libasound2t64", "libfontconfig1", "fonts-noto-color-emoji", "libvulkan1", "mesa-vulkan-drivers", "vulkan-tools", "libasound2t64", "libfontconfig1", "libvulkan1", "mesa-vulkan-drivers", "vulkan-tools",
"libxext6", "libx11-6", "libgl1", "libegl1", "libxext6", "libx11-6", "libgl1", "libegl1",
"libxi6", "libxxf86vm1", "libxfixes3", "libxrender1", "libxkbcommon0", "libsm6", "libice6", "libxi6", "libxxf86vm1", "libxfixes3", "libxrender1", "libxkbcommon0", "libsm6", "libice6",
) )
@@ -145,10 +138,7 @@ image = (
# bitrate: openh264's near-blacks stepped into blocks even at master's 37.7 Mbps, raea check's blotching # bitrate: openh264's near-blacks stepped into blocks even at master's 37.7 Mbps, raea check's blotching
# failed every Dutch cut, and its agent re-encoded each one with x264 after the render (11-30) # failed every Dutch cut, and its agent re-encoded each one with x264 after the render (11-30)
"RAEA_MEDIA": "ffmpeg"}) "RAEA_MEDIA": "ffmpeg"})
# a test farm's own raea (deploy/modal/build.py: an engine change built into the volume, timed here before a release .add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene")
# carries it): RAEA_FARM_BUILD=NAME at the deploy. The live farm has none, and runs the release above
.env({"RAEA_FARM_BUILD": os.environ.get("RAEA_FARM_BUILD", "")})
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene", "farm_keys", "farm_proxy")
) )
app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image) app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image)
@@ -158,15 +148,8 @@ models = modal.Volume.from_name("raea-models", create_if_missing=True, version=2
logs = modal.Dict.from_name("raea-farm-logs", create_if_missing=True) logs = modal.Dict.from_name("raea-farm-logs", create_if_missing=True)
# the farm's token (RAEA_CLOUD_TOKEN), its own: a CPU box names it as RAEA_CLOUD_GPU_TOKEN # the farm's token (RAEA_CLOUD_TOKEN), its own: a CPU box names it as RAEA_CLOUD_GPU_TOKEN
secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_SECRET", "raea-farm")) secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_SECRET", "raea-farm"))
# /v1/words hears with this Modal app (words.py), in the languages Parakeet TDT v3 knows (its 25 European ones);
# others, and any failure, go to Whisper on OpenRouter
WORDS_APP = os.environ.get("RAEA_WORDS_APP", "raea-words")
WORDS_LANGUAGES = {"bg", "hr", "cs", "da", "nl", "en", "et", "fi", "fr", "de", "el", "hu", "it", "lv", "lt", "mt", "pl", "pt", "ro", "sk", "sl", "es", "sv", "ru", "uk"}
# OPENROUTER_API_KEY for /v1/words: raea cloud's own key, the one its library index transcribes with # OPENROUTER_API_KEY for /v1/words: raea cloud's own key, the one its library index transcribes with
words_secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_WORDS_SECRET", "raea-farm-words")) words_secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_WORDS_SECRET", "raea-farm-words"))
# GROQ_API_KEY (12-03, Shane: "if we are going to use whisper, use groq"): the same Whisper large-v3, many times faster
groq_secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_GROQ_SECRET", "raea-farm-groq"))
GROQ_WHISPER = os.environ.get("RAEA_GROQ_WHISPER", "whisper-large-v3")
# a CPU render (the coordinator's sound pass) on lavapipe, with EGL's vendors hidden (docs/cloud.feature CL13) # a CPU render (the coordinator's sound pass) on lavapipe, with EGL's vendors hidden (docs/cloud.feature CL13)
CPU_ENV = {"VK_DRIVER_FILES": "/usr/share/vulkan/icd.d/lvp_icd.json", "__EGL_VENDOR_LIBRARY_DIRS": "/nonexistent"} CPU_ENV = {"VK_DRIVER_FILES": "/usr/share/vulkan/icd.d/lvp_icd.json", "__EGL_VENDOR_LIBRARY_DIRS": "/nonexistent"}
@@ -178,8 +161,6 @@ CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}
# the scene reader's models, loaded once a container (/v1/scene) # the scene reader's models, loaded once a container (/v1/scene)
SCENE = None SCENE = None
# one reading at a time a container: the models aren't safe to run from two threads
SCENE_LOCK = threading.Lock()
# when this container's Python started, for the job's bill (farm_plan.Bill) # when this container's Python started, for the job's bill (farm_plan.Bill)
BOOTED = time.time() BOOTED = time.time()
@@ -199,10 +180,6 @@ def run(cmd, cwd=None, env=None, timeout=6 * 3600):
t = time.time() t = time.time()
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"]): for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True) os.makedirs(d, exist_ok=True)
build = os.environ.get("RAEA_FARM_BUILD")
if build and cmd[0] == "raea":
# the build's raea, with the release's own files as its home
cmd, env = [f"{ROOT}/builds/{build}/raea", *cmd[1:]], {"RAEA_HOME": "/opt/raea/share/raea", **(env or {})}
u0 = resource.getrusage(resource.RUSAGE_CHILDREN) u0 = resource.getrusage(resource.RUSAGE_CHILDREN)
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **CACHES, **(env or {})}, timeout=timeout) r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **CACHES, **(env or {})}, timeout=timeout)
u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t
@@ -211,21 +188,16 @@ def run(cmd, cwd=None, env=None, timeout=6 * 3600):
def snapshot(d): def snapshot(d):
# each file's stat is a trip to the volume (about 19 ms): one after another, 511 files took 9.7 s at each end of out = {}
# every job, drawn or not (12-01). Asked 32 at once for base, _, files in os.walk(d):
from concurrent.futures import ThreadPoolExecutor for f in files:
p = os.path.join(base, f)
paths = [os.path.join(base, f) for base, _, files in os.walk(d) for f in files] try:
s = os.stat(p)
def one(p): except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's
try: continue
s = os.stat(p) out[os.path.relpath(p, d)] = f"{s.st_size}:{s.st_mtime_ns}"
except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's return out
return None
return os.path.relpath(p, d), f"{s.st_size}:{s.st_mtime_ns}"
with ThreadPoolExecutor(32) as pool:
return dict(x for x in pool.map(one, paths) if x)
class Log: class Log:
@@ -245,10 +217,6 @@ class Log:
# a GPU stays up this long after its last run, billed (farm_plan.SCALEDOWN): at 60 s, the farm's jobs of 11-17 billed # a GPU stays up this long after its last run, billed (farm_plan.SCALEDOWN): at 60 s, the farm's jobs of 11-17 billed
# about five times their GPUs' working seconds # about five times their GPUs' working seconds
SCALEDOWN = 2 SCALEDOWN = 2
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it
CPU_SCALEDOWN = 60
def on(gpus, job): def on(gpus, job):
@@ -262,85 +230,24 @@ def on(gpus, job):
return dict(gpu=gpus, cpu=cpu, memory=gib * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=GPUS, scaledown_window=SCALEDOWN) return dict(gpu=gpus, cpu=cpu, memory=gib * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=GPUS, scaledown_window=SCALEDOWN)
def reserved(job):
import sys
if HERE not in sys.path:
sys.path.insert(0, HERE)
import farm_plan
return farm_plan.RESERVED[job]
farm_cpu = reserved("cpu")
def raea_path():
"""The raea a job runs: a test farm's build (RAEA_FARM_BUILD), else the release in the image"""
build = os.environ.get("RAEA_FARM_BUILD")
return f"{ROOT}/builds/{build}/raea" if build else shutil.which("raea") or "/usr/local/bin/raea"
def kind(): def kind():
"""This container's GPU by its price list name (prices.py), for the planner's estimate; "CPU" with none.""" """This container's GPU by its price list name (prices.py), for the planner's estimate."""
import prices import prices
try: name = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], capture_output=True, text=True).stdout
name = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], capture_output=True, text=True).stdout
except FileNotFoundError:
return "CPU"
# a GPU whose name isn't in the price list is still a GPU ("", which the planner prices as its fallback GPU): 11-30,
# `or "CPU"` here priced one of a GPU job's containers as a CPU's
return prices.kind_of(name) return prices.kind_of(name)
def work_ms(out):
"""What raea's own clocks (RAEA_TIMES) say a run's frames took in all, ms: React, the page recorded and collected,
and raea-render's pass (the clips read, the draw, the encode). None when the run didn't say."""
a = re.search(r"raea times: react (\d+) ms, page recorded and submitted (\d+) ms, page collected and stored (\d+) ms", out)
b = re.search(r"raea times: raea-render's render[^\n]*? (\d+) ms", out)
return sum(map(int, a.groups())) + int(b.group(1)) if a and b else None
@app.function(**on(RAEA_GPUS, "raea")) @app.function(**on(RAEA_GPUS, "raea"))
def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False, nv: bool = False) -> dict: def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False) -> dict:
"""raea ARGS in the job's folder. With `frames`: those frames to the job's frames/ folder, from frame `first` on, """raea ARGS in the job's folder. With `frames`: those frames to the job's frames/ folder, from frame `first` on,
as one H.264 run (frames/run-FIRST.mp4, joined by the coordinator without encoding again) when `video`, else PNGs. as one H.264 run (frames/run-FIRST.mp4, joined by the coordinator without encoding again) when `video`, else PNGs.
With `probe`: frame 0 and the piece's length, size and rate (its manifest). One function for all three, so the With `probe`: frame 0 and the piece's length, size and rate (its manifest). One function for all three, so the
container that rendered frame 0 is warm for the next run. With `nv` (a piece with 3D in it, which keeps its GPU): container that rendered frame 0 is warm for the next run."""
NVIDIA's encoder and decoder in place of libx264 and ffmpeg's own (RAEA_NV, CR34)."""
return raea_frames(id, args, frames, first, probe, video, {"RAEA_NV": "1"} if nv else None)
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=CPU_SCALEDOWN)
def raea_cpu_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False, nv: bool = False) -> dict:
"""raea_run on a container with no GPU (lavapipe draws), for a video with no 3D in it: the planner sends those
here after frame 0 (farm_plan.raea_render), and a run that fails here or has 3D in it goes back to a GPU."""
return raea_frames(id, args, frames, first, probe, video, CPU_ENV)
@app.function(cpu=8, memory=8 * 1024, volumes={ROOT: vol}, timeout=3600, max_containers=CPUS, scaledown_window=SCALEDOWN)
def raea_proxy(src: str, dest: str, w: int, h: int, matrix: str) -> dict:
"""One clip's copy at the size a job draws it (farm_proxy.py), written beside the others and kept by hash"""
import farm_proxy
vol.reload()
os.makedirs(os.path.dirname(dest), exist_ok=True)
part = f"{dest}.part-{uuid.uuid4().hex[:8]}{os.path.splitext(dest)[1]}"
code, out, s = run(farm_proxy.command(src, part, w, h, matrix))
if not code:
os.replace(part, dest)
vol.commit()
elif os.path.exists(part):
os.remove(part)
return {"code": code, "out": out[-1000:], "s": s}
def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=None):
vol.reload() vol.reload()
work = f"{JOBS}/{id}/work" work = f"{JOBS}/{id}/work"
if probe: if probe:
code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work, env=env) code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work)
m = json.load(open("/tmp/probe.json")) if os.path.exists("/tmp/probe.json") else {} m = json.load(open("/tmp/probe.json")) if os.path.exists("/tmp/probe.json") else {}
return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), "manifest": m, **life()} return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), "manifest": m, **life()}
if frames is None: if frames is None:
@@ -355,7 +262,7 @@ def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=No
# the run's own manifest (its frames, each sound cut to them): the coordinator joins the runs' into the render's # the run's own manifest (its frames, each sound cut to them): the coordinator joins the runs' into the render's
# (farm_plan.joined), so a cut's whole edit comes back, not frame 0's alone (11-29, Dutch) # (farm_plan.joined), so a cut's whole edit comes back, not frame 0's alone (11-29, Dutch)
man = f"/tmp/run-{first:05d}.json" man = f"/tmp/run-{first:05d}.json"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work, env={**(env or {}), "RAEA_TIMES": "1"}) code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work)
if os.path.exists(seg): if os.path.exists(seg):
shutil.move(seg, f"{dest}/run-{first:05d}.mp4") shutil.move(seg, f"{dest}/run-{first:05d}.mp4")
vol.commit() vol.commit()
@@ -364,9 +271,9 @@ def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=No
m = json.load(open(man)) m = json.load(open(man))
except Exception: except Exception:
m = None m = None
return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "first": first, "ms": float(ms.group(1)) if ms else None, "work_ms": work_ms(out), "kind": kind(), "manifest": m, **life()} return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "ms": float(ms.group(1)) if ms else None, "kind": kind(), "manifest": m, **life()}
tmp = f"/tmp/{uuid.uuid4().hex}" tmp = f"/tmp/{uuid.uuid4().hex}"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp], cwd=work, env=env) code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp], cwd=work)
# raea names --at's stills in order (frame-00000.png is the first frame asked for), beside its manifest # raea names --at's stills in order (frame-00000.png is the first frame asked for), beside its manifest
made = sorted(n for n in os.listdir(tmp) if re.fullmatch(r"frame-\d+\.png", n)) if os.path.isdir(tmp) else [] made = sorted(n for n in os.listdir(tmp) if re.fullmatch(r"frame-\d+\.png", n)) if os.path.isdir(tmp) else []
# a frame's time from when the stills were written (raea's stills path doesn't say it), the start excluded # a frame's time from when the stills were written (raea's stills path doesn't say it), the start excluded
@@ -377,7 +284,7 @@ def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=No
if frames[i] >= first: if frames[i] >= first:
shutil.move(os.path.join(tmp, name), f"{dest}/frame-{frames[i]:05d}.png") shutil.move(os.path.join(tmp, name), f"{dest}/frame-{frames[i]:05d}.png")
vol.commit() vol.commit()
return {"code": code, "out": out[-2000:], "s": s, "frames": len(made), "first": first, "ms": ms, "kind": kind(), **life()} return {"code": code, "out": out[-2000:], "s": s, "frames": len(made), "ms": ms, "kind": kind(), **life()}
BLENDER_SETUP = """ BLENDER_SETUP = """
@@ -429,9 +336,7 @@ def coordinate(id: str, args: list[str], opts: dict):
log = Log(id) log = Log(id)
log(f"raea farm: raea {' '.join(args)}") log(f"raea farm: raea {' '.join(args)}")
t_start = [time.time()]
vol.reload() vol.reload()
t_start.append(time.time())
work = f"{JOBS}/{id}/work" work = f"{JOBS}/{id}/work"
try: try:
farm_media.fetch(work, f"{ROOT}/blobs", log) farm_media.fetch(work, f"{ROOT}/blobs", log)
@@ -443,30 +348,14 @@ def coordinate(id: str, args: list[str], opts: dict):
return return
# the media just linked (or fetched) into the job, committed before any GPU container reloads to render it: without # the media just linked (or fetched) into the job, committed before any GPU container reloads to render it: without
# this a still on this container found the footage and every GPU run of a video didn't ("No such file", 11-25) # this a still on this container found the footage and every GPU run of a video didn't ("No such file", 11-25)
t_start.append(time.time())
vol.commit() vol.commit()
t_start.append(time.time())
before = snapshot(work) before = snapshot(work)
t_start.append(time.time())
# where a job's start goes, said when it's slow, as its end is
if t_start[-1] - t_start[0] > 5:
d = [b - a for a, b in zip(t_start, t_start[1:])]
log(f"raea farm: the job's start took {sum(d):.0f} s: reloading {d[0]:.1f} s, its media {d[1]:.1f} s, saving {d[2]:.1f} s, listing its files {d[3]:.1f} s")
try: try:
# a video's frames' keys (farm_keys.py): its runs kept by them under the raea that drew them (a release's code = farm_plan.dispatch(args, {**opts, "id": id}, work, log, raea_run, blender_run, CPU_ENV, run, vol.reload)
# version and the build's own file, so a new engine starts a store of its own; kept=0 draws every frame), and
# its clips read from copies at the size they're drawn (farm_proxy.py, made on containers with no GPU)
exe = os.path.realpath(raea_path())
st = os.stat(exe)
opts = {**opts, "keys": f"{ROOT}/kept", "raea": f"{exe}:{st.st_size}:{int(st.st_mtime)}", "proxies": f"{ROOT}/proxies", "proxy_commit": vol.commit,
"proxy_make": lambda todo: raea_proxy.starmap(todo, order_outputs=False, return_exceptions=True)}
code = farm_plan.dispatch(args, {**opts, "id": id}, work, log, raea_run, blender_run, CPU_ENV, run, vol.reload, raea_cpu_run if opts.get("cpus") else None)
except Exception as e: # the job's own failure, said in its log; the farm goes on except Exception as e: # the job's own failure, said in its log; the farm goes on
log(f"raea farm: {e!r}", err=True) log(f"raea farm: {e!r}", err=True)
code = 1 code = 1
t_end = [time.time()]
vol.commit() vol.commit()
t_end.append(time.time())
# what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a # what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a
# reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20). # reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20).
# Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again, # Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again,
@@ -480,9 +369,7 @@ def coordinate(id: str, args: list[str], opts: dict):
log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True) log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True)
else: else:
time.sleep(pause) time.sleep(pause)
t_end.append(time.time())
after = snapshot(work) after = snapshot(work)
t_end.append(time.time())
changed = [p for p, v in after.items() if before.get(p) != v] changed = [p for p, v in after.items() if before.get(p) != v]
if opts.get("media"): if opts.get("media"):
# the job's media stays here until the box names where in R2 it goes (POST media); the rest comes back in /out # the job's media stays here until the box names where in R2 it goes (POST media); the rest comes back in /out
@@ -494,67 +381,11 @@ def coordinate(id: str, args: list[str], opts: dict):
with open(f"{JOBS}/{id}/changed.txt", "w") as f: with open(f"{JOBS}/{id}/changed.txt", "w") as f:
f.write("".join(p + "\n" for p in changed)) f.write("".join(p + "\n" for p in changed))
shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True) shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True)
t_end.append(time.time())
vol.commit() vol.commit()
t_end.append(time.time())
# where a job's end goes, said when it's slow (12-01: 17-60 s between the join and the box hearing it's done)
if t_end[-1] - t_end[0] > 5:
d = [b - a for a, b in zip(t_end, t_end[1:])]
log(f"raea farm: the job's end took {sum(d):.0f} s: saving {d[0]:.1f} s, reloading {d[1]:.1f} s, listing what changed {d[2]:.1f} s, clearing its frames {d[3]:.1f} s, saving again {d[4]:.1f} s")
log.end(code) log.end(code)
def seams(g): @app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600)
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
def read_scenes(frames):
"""Each base64 JPEG's scene (farm_scene.Scene.read and its seams), None for one that isn't a picture"""
import base64
import cv2
import numpy as np
import farm_scene
global SCENE
with SCENE_LOCK:
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return out
# A cut's frames went through the API's one core one after another, inside its event loop: 70 frames of a 35 s ad took
# 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow; 12-01).
# More than SCENE_HERE frames are shared out to these, SCENE_PART each; fewer are read in the API on a thread.
SCENE_HERE = 4
SCENE_PART = 6
@app.function(cpu=2, memory=4096, timeout=600, max_containers=CPUS, scaledown_window=60)
def scene_run(frames: list[str]) -> list:
return read_scenes(frames)
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret, groq_secret], timeout=3600)
@modal.concurrent(max_inputs=32) @modal.concurrent(max_inputs=32)
@modal.asgi_app() @modal.asgi_app()
def api(): def api():
@@ -634,10 +465,23 @@ def api():
return {"raea": RAEA, "blender": BLENDER, "device": {"renders": "gpu", "name": f"raea on {'/'.join(RAEA_GPUS)}, Blender on {'/'.join(BLENDER_GPUS)}, up to {GPUS} at once"}, "farm": True, "jobs": []} return {"raea": RAEA, "blender": BLENDER, "device": {"renders": "gpu", "name": f"raea on {'/'.join(RAEA_GPUS)}, Blender on {'/'.join(BLENDER_GPUS)}, up to {GPUS} at once"}, "farm": True, "jobs": []}
# what's said in a piece of sound, word by word, for a box's `raea words` (server/words.ts): a box has no # what's said in a piece of sound, word by word, for a box's `raea words` (server/words.ts): a box has no
# transcriber of its own (raea's is parakeet-mlx, Mac only), so the same model on a GPU hears it here (raea-words), # transcriber of its own (raea's is parakeet-mlx, Mac only), so the same Whisper large-v3 on OpenRouter that raea
# Whisper large-v3 on OpenRouter when that can't. The body is one MP3 piece (16 kHz mono, # cloud's library index uses (apps/app host/library/words.ts) hears it here. The body is one MP3 piece (16 kHz mono,
# at most 10 minutes; the box cuts the pieces), the answer its words in the piece's own seconds. 11-25, Shane: "give # at most 10 minutes; the box cuts the pieces), the answer its words in the piece's own seconds. 11-25, Shane: "give
# it whatever we use for indexing and libraries and sync", so agents check the words their cuts say. # it whatever we use for indexing and libraries and sync", so agents check the words their cuts say.
def seams(g):
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
@web.post("/v1/scene") @web.post("/v1/scene")
async def scene(req: Request): async def scene(req: Request):
@@ -646,6 +490,11 @@ def api():
(each face [x, y, w, h, "face", score]), a grid of where people are, and its things (each face [x, y, w, h, "face", score]), a grid of where people are, and its things
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts (COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts
[x, y, w, h, "the text", score], in that frame's pixels""" [x, y, w, h, "the text", score], in that frame's pixels"""
import base64
import cv2
import numpy as np
import farm_scene
check(req) check(req)
body = await req.json() body = await req.json()
frames = body.get("frames") if isinstance(body, dict) else None frames = body.get("frames") if isinstance(body, dict) else None
@@ -653,11 +502,18 @@ def api():
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}') raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
if len(frames) > 400: if len(frames) > 400:
raise HTTPException(413, "at most 400 frames a call") raise HTTPException(413, "at most 400 frames a call")
if len(frames) <= SCENE_HERE: global SCENE
out = await asyncio.to_thread(read_scenes, frames) if SCENE is None:
else: SCENE = farm_scene.Scene()
parts = [frames[i:i + SCENE_PART] for i in range(0, len(frames), SCENE_PART)] out = []
out = [r async for part in scene_run.map.aio(parts) for r in part] for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out} return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
@web.post("/v1/words") @web.post("/v1/words")
@@ -669,9 +525,8 @@ def api():
check(req) check(req)
key = os.environ.get("OPENROUTER_API_KEY", "") key = os.environ.get("OPENROUTER_API_KEY", "")
groq = os.environ.get("GROQ_API_KEY", "") if not key:
if not key and not groq: raise HTTPException(503, "the farm has no OpenRouter key for words (Modal secret raea-farm-words)")
raise HTTPException(503, "the farm has no Whisper key for words (Modal secrets raea-farm-groq, raea-farm-words)")
mp3 = await req.body() mp3 = await req.body()
if not mp3: if not mp3:
raise HTTPException(400, "the body is the sound: an MP3, 16 kHz mono, at most 10 minutes") raise HTTPException(400, "the body is the sound: an MP3, 16 kHz mono, at most 10 minutes")
@@ -681,26 +536,7 @@ def api():
if req.query_params.get("language"): if req.query_params.get("language"):
body["language"] = req.query_params["language"] body["language"] = req.query_params["language"]
def ask_groq():
fields = [("model", GROQ_WHISPER), ("response_format", "verbose_json"), ("timestamp_granularities[]", "word"), ("timestamp_granularities[]", "segment")]
if req.query_params.get("language"):
fields.append(("language", req.query_params["language"]))
b = "raea" + os.urandom(12).hex()
data = b"".join(f'--{b}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode() for k, v in fields)
data += f'--{b}\r\nContent-Disposition: form-data; name="file"; filename="piece.mp3"\r\nContent-Type: audio/mpeg\r\n\r\n'.encode() + mp3 + f"\r\n--{b}--\r\n".encode()
r = urllib.request.Request("https://api.groq.com/openai/v1/audio/transcriptions", data=data, headers={"authorization": f"Bearer {groq}", "content-type": f"multipart/form-data; boundary={b}", "user-agent": "raea-farm"})
try:
with urllib.request.urlopen(r, timeout=300) as f:
return 200, _json.load(f)
except urllib.error.HTTPError as e:
return e.code, {"error": e.read()[:500].decode("utf8", "replace")}
def ask(): def ask():
if groq:
code, got = ask_groq()
if code == 200 or not key:
return code, {**got, "_model": f"groq/{GROQ_WHISPER}"}
print(f"words: Groq said {code}, so OpenRouter hears it: {got.get('error', '')[:200]}", flush=True)
r = urllib.request.Request("https://openrouter.ai/api/v1/audio/transcriptions", data=_json.dumps(body).encode(), headers={"authorization": f"Bearer {key}", "content-type": "application/json", "x-title": "raea cloud words"}) r = urllib.request.Request("https://openrouter.ai/api/v1/audio/transcriptions", data=_json.dumps(body).encode(), headers={"authorization": f"Bearer {key}", "content-type": "application/json", "x-title": "raea cloud words"})
try: try:
with urllib.request.urlopen(r, timeout=300) as f: with urllib.request.urlopen(r, timeout=300) as f:
@@ -708,19 +544,11 @@ def api():
except urllib.error.HTTPError as e: except urllib.error.HTTPError as e:
return e.code, {"error": e.read()[:500].decode("utf8", "replace")} return e.code, {"error": e.read()[:500].decode("utf8", "replace")}
# raea-words first (words.py, 12-03): Parakeet on a GPU, each word's edges on its sound, as raea hears on a Mac.
# Whisper's word times are guessed (StreetTalk's out points sat on them, mid-word); it stays as the fallback
if not req.query_params.get("language") or req.query_params["language"] in WORDS_LANGUAGES:
try:
hear = modal.Cls.from_name(WORDS_APP, "Hear")
return await hear().words.remote.aio(mp3)
except Exception as e:
print(f"words: {WORDS_APP} failed, so Whisper hears it: {str(e)[-300:]}", flush=True)
code, got = await asyncio.to_thread(ask) code, got = await asyncio.to_thread(ask)
if code != 200: if code != 200:
raise HTTPException(502, f"Whisper said {code}: {got.get('error', '')}") raise HTTPException(502, f"OpenRouter's Whisper said {code}: {got.get('error', '')}")
ws = [{"text": w.get("word", "").strip(), "start": float(w.get("start", 0)), "end": float(w.get("end", w.get("start", 0)))} for w in got.get("words") or [] if w.get("word", "").strip()] ws = [{"text": w.get("word", "").strip(), "start": float(w.get("start", 0)), "end": float(w.get("end", w.get("start", 0)))} for w in got.get("words") or [] if w.get("word", "").strip()]
return {"model": got.get("_model", "openai/whisper-large-v3"), "duration": got.get("duration"), "text": got.get("text", ""), "words": ws} return {"model": "openai/whisper-large-v3", "duration": got.get("duration"), "text": got.get("text", ""), "words": ws}
@web.post("/v1/jobs") @web.post("/v1/jobs")
async def start(req: Request): async def start(req: Request):
@@ -729,7 +557,7 @@ def api():
if not isinstance(args, list) or not all(isinstance(a, str) for a in args): if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments") raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments")
q = req.query_params q = req.query_params
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "cpus": min(int(q.get("cpus", JOB_CPUS)), CPUS), "kept": q.get("kept", "1") != "0", "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"} opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
id = str(uuid.uuid4()) id = str(uuid.uuid4())
work = f"{JOBS}/{id}/work" work = f"{JOBS}/{id}/work"
async with gate.use(): async with gate.use():
-148
View File
@@ -1,148 +0,0 @@
# A video's runs kept by what their frames draw (docs/cloud-render.feature CR30): `raea render --keys` says each frame's
# key with nothing drawn, and a run a job drew is kept on the farm's volume under its frames' keys. The next job of the
# piece draws only the frames no kept run holds: a caption edited in one shot draws that shot's runs again, a change
# to the sound alone draws none (the sound is made again and joined to the kept pictures).
#
# read(...) the piece's keys, read on the coordinator's CPU: None when this raea has no --keys
# base(...) what a kept run is only good under: the raea that drew it, the render's arguments, the
# picture's size and rate, and every file in the job that isn't sound, by its content
# cover(store, keys) (hits, gaps): the kept runs whose frames' keys are the piece's at the same frames, and
# the stretches of frames left to draw
# put(store, keys, ...) a run just drawn, kept
#
# A key names files, it doesn't read them, and a frame's picture hangs on the page's styles and the engine too: all of
# that is in `base`, so a changed clip, font, stylesheet or raea starts a store of its own. Pieces with 3D in them
# aren't kept (a frame's picture can hang on the frames before it: physics, particles, a path tracer's light).
import hashlib
import json
import os
import re
import shutil
import time
SOUND = set("mp3 wav aiff aif flac m4a ogg opus caf".split())
# the piece's code (the keys hold what of it reaches the picture), and what a job leaves behind. A .json the code
# imports is code too (a caption's words reach the page as text); one it doesn't is a file something may read by path
CODE = set("tsx ts jsx js mjs".split())
SKIP = CODE | set("md lock log".split())
IMPORT = re.compile(r"""(?:from|import|require\()\s*["']([^"']+\.json)["']""")
KEEP_DAYS = 14
NAME = re.compile(r"(\d+)-(\d+)-([0-9a-f]{32})\.mp4")
def read(args, work, run, env, path):
"""{length, width, height, fps, has3d, keys, sounds} and the seconds it took, or (None, s) when raea didn't say"""
code, _, s = run(["raea", *args, "--keys", path, "-o", "/tmp/keys.mp4"], cwd=work, env=env)
try:
k = json.load(open(path)) if not code else None
except Exception:
k = None
return (k if k and len(k.get("keys") or []) == k.get("length") else None), s
def files(work):
"""Every file of the job a picture could hang on that the keys don't hold, as [path, content]: a link into the
farm's cache by the hash it's named for, anything else by its own."""
out, seen, imported = [], [], set()
for dirpath, dirs, names in os.walk(work):
dirs[:] = [d for d in dirs if d not in ("out", "node_modules", ".git", ".raea")]
for n in names:
p = os.path.join(dirpath, n)
ext = n.rsplit(".", 1)[-1].lower() if "." in n else ""
if ext in CODE and os.path.isfile(p):
with open(p, errors="replace") as f:
imported |= {os.path.normpath(os.path.join(dirpath, m)) for m in IMPORT.findall(f.read())}
seen.append((p, ext))
for p, ext in seen:
if True:
if ext in SOUND or ext in SKIP or not os.path.isfile(p) or (ext == "json" and os.path.normpath(p) in imported):
continue
real = os.path.realpath(p)
oid = os.path.basename(real)
if not (os.path.islink(p) and len(oid) == 64):
h = hashlib.sha256()
with open(p, "rb") as f:
for b in iter(lambda: f.read(1 << 20), b""):
h.update(b)
oid = h.hexdigest()
out.append([os.path.relpath(p, work), oid])
return sorted(out)
def base(raea, args, k, work):
said = json.dumps([raea, args, k["width"], k["height"], k["fps"], k["length"], files(work)])
return hashlib.sha256(said.encode()).hexdigest()[:32]
def of(keys, first, n):
return hashlib.sha256("\n".join(keys[first : first + n]).encode()).hexdigest()[:32]
def cover(store, keys):
"""The kept runs that hold this piece's frames, longest first where two overlap, and the frames left."""
kept = []
for name in os.listdir(store) if os.path.isdir(store) else []:
m = NAME.fullmatch(name)
if m and int(m[1]) + int(m[2]) <= len(keys) and of(keys, int(m[1]), int(m[2])) == m[3]:
kept.append((int(m[1]), int(m[2]), os.path.join(store, name)))
hits, taken = [], [False] * len(keys)
for first, n, path in sorted(kept, key=lambda r: (-r[1], r[0])):
if not any(taken[first : first + n]):
taken[first : first + n] = [True] * n
hits.append((first, n, path))
gaps, f = [], 0
while f < len(keys):
if taken[f]:
f += 1
continue
e = f
while e + 1 < len(keys) and not taken[e + 1]:
e += 1
gaps.append((f, e))
f = e + 1
return sorted(hits), gaps
def take(hits, frames_dir):
"""The kept runs into the job's frames, as its own runs lie there; each one's manifest, as a run's result"""
os.makedirs(frames_dir, exist_ok=True)
got = []
for first, n, path in hits:
shutil.copyfile(path, f"{frames_dir}/run-{first:05d}.mp4")
os.utime(path)
try:
m = json.load(open(path[:-4] + ".json"))
except Exception:
m = None
got.append({"code": 0, "first": first, "frames": n, "manifest": m, "kept": True})
return got
def put(store, keys, results, frames_dir):
"""The runs a job drew, kept under their frames' keys; stores no job has touched in KEEP_DAYS go."""
os.makedirs(store, exist_ok=True)
for r in results:
src = f"{frames_dir}/run-{r.get('first', 0):05d}.mp4"
if r.get("code") or r.get("kept") or not r.get("frames") or not os.path.exists(src):
continue
to = f"{store}/{r['first']}-{r['frames']}-{of(keys, r['first'], r['frames'])}"
shutil.copyfile(src, to + ".part")
os.replace(to + ".part", to + ".mp4")
with open(to + ".json", "w") as f:
json.dump(r.get("manifest"), f)
os.utime(store)
root, old = os.path.dirname(store), time.time() - KEEP_DAYS * 86400
for d in os.listdir(root):
p = os.path.join(root, d)
if p != store and os.path.isdir(p) and os.stat(p).st_mtime < old:
shutil.rmtree(p, ignore_errors=True)
def spans(gaps, n0, parts):
"""The frames left after the timed run's first n0 (of the first gap), as (first, last) stretches, and each one's
share of `parts` runs by its length (one at least)."""
rest = [(a + (n0 if i == 0 else 0), b) for i, (a, b) in enumerate(gaps)]
rest = [(a, b) for a, b in rest if a <= b]
left = sum(b - a + 1 for a, b in rest)
return [(a, b, max(1, round(parts * (b - a + 1) / left))) for a, b in rest]
+45 -176
View File
@@ -8,9 +8,6 @@ import os
import re import re
import shutil import shutil
import threading import threading
import farm_keys
import farm_proxy
import time import time
import prices import prices
@@ -90,23 +87,16 @@ def gpus_for(frames, frame_s, start_s, most):
# a GPU takes up to this many parts of a long job, one after another from the job's queue, so a slow card (an L4 among # a GPU takes up to this many parts of a long job, one after another from the job's queue, so a slow card (an L4 among
# L40Ss) ends up drawing fewer frames instead of holding up the job # L40Ss) ends up drawing fewer frames instead of holding up the job
PARTS = 4 PARTS = 4
# containers with no GPU are all the same machine, so a queue only evens out frames that cost more in one stretch than
# another: 2 parts each. At 4 an 894-frame ad went out as 32 parts of 28 frames, each paying about 5 s to start
# (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30)
CPU_PARTS = 2
# a video part's start is never planned at less than this (s): the timed run's own start is measured on a warm
# container with the clips' first frames, and came out at 2.8-3.6 s where the parts after it paid about 5
PART_START = 5.0
def parts_per_gpu(frames, k, frame_s, start_s, most=PARTS): def parts_per_gpu(frames, k, frame_s, start_s):
"""How many parts each of `k` containers takes from the queue: the most (up to `most`) that keep a part's own start """How many parts each of `k` GPUs takes from the queue: the most (up to PARTS) that keep a part's own start
(start_s, more than a warm one needs) at most SHARE of the part. Above 1 only when the limit capped `k`.""" (start_s, more than a warm GPU needs) at most SHARE of the part. Above 1 only when the GPU limit capped `k`."""
if k <= 0 or frame_s <= 0: if k <= 0 or frame_s <= 0:
return 1 return 1
least = start_s * (1 - SHARE) / SHARE / frame_s # the frames a part needs for its start to be worth it least = start_s * (1 - SHARE) / SHARE / frame_s # the frames a part needs for its start to be worth it
m = 1 m = 1
while m < most and frames / (k * (m + 1)) >= least: while m < PARTS and frames / (k * (m + 1)) >= least:
m += 1 m += 1
return m return m
@@ -128,18 +118,11 @@ def runs(first, last, k, warm=0):
# What a GPU container reserves beside its GPU, billed whether used or not; a run that takes more is billed for what # What a GPU container reserves beside its GPU, billed whether used or not; a run that takes more is billed for what
# it takes (Modal has no limit set here), so these are floors, not caps. raea's were 4 cores and 16 GiB until 11-29, # it takes (Modal has no limit set here), so these are floors, not caps. raea's were 4 cores and 16 GiB until 11-29,
# when a 1080p cut measured 1.4 cores busy and 2.7 GB (the job's last line says each job's); Blender's is unmeasured. # when a 1080p cut measured 1.4 cores busy and 2.7 GB (the job's last line says each job's); Blender's is unmeasured.
# "cpu" is a container with no GPU (farm.py's raea_cpu_run), for a video with no 3D in it: on 60 frames of a 1080x1920 RESERVED = {"raea": (2, 8), "blender": (4, 16)}
# ad cut from 4K footage a T4 container took 11.1 s with 2.5 cores busy and 8 cores alone took 13.9 s with 4.7 busy
# (11-30), the same picture at SSIM 0.9999, for about half the price a frame.
RESERVED = {"raea": (2, 8), "blender": (4, 16), "cpu": (4, 8)}
CPU = "CPU" # a container with no GPU, as a run's kind
def price(kind, seconds, cpu=None, memory_gib=None, busy=0.0): def price(kind, seconds, cpu=RESERVED["raea"][0], memory_gib=RESERVED["raea"][1]):
"""What `seconds` of a container of `kind` cost: its GPU, its memory, and the cores it reserves or, when it kept return prices.cost(kind, cpu=cpu, memory_gib=memory_gib, seconds=seconds)
more than that busy, those (Modal bills a container's use above what it reserves)."""
c, g = RESERVED["cpu" if kind == CPU else "raea"]
return prices.cost(kind, cpu=max(cpu or c, busy or 0), memory_gib=memory_gib or g, seconds=seconds)
SCALEDOWN = 2 # s a GPU container stays up after its last run (farm.py), billed SCALEDOWN = 2 # s a GPU container stays up after its last run (farm.py), billed
@@ -156,23 +139,16 @@ class Bill:
def add(self, r): def add(self, r):
if isinstance(r, dict) and r.get("task"): if isinstance(r, dict) and r.get("task"):
b, e = max(r["boot"], self.t0), r["end"] b, e = max(r["boot"], self.t0), r["end"]
k, b0, e0, c0 = self.tasks.get(r["task"], (r.get("kind"), b, e, 0.0)) k, b0, e0 = self.tasks.get(r["task"], (r.get("kind"), b, e))
# a container's cores: its busiest run's, an upper bound on what it's billed above its reservation self.tasks[r["task"]] = (k or r.get("kind"), min(b, b0), max(e, e0))
self.tasks[r["task"]] = (k or r.get("kind"), min(b, b0), max(e, e0), max(c0, r.get("cores") or 0))
self.cores, self.peak_mb = max(self.cores, r.get("cores") or 0), max(self.peak_mb, r.get("peak_mb") or 0) self.cores, self.peak_mb = max(self.cores, r.get("cores") or 0), max(self.peak_mb, r.get("peak_mb") or 0)
return r return r
def usd(self):
return sum(price(k or "L4", e - b + BOOT + SCALEDOWN, *((None, None) if k == CPU else (self.cpu, self.gib)), busy=c) for k, b, e, c in self.tasks.values())
def line(self): def line(self):
up = [(k or "L4", e - b + BOOT + SCALEDOWN) for k, b, e, _ in self.tasks.values()] up = [(k or "L4", e - b + BOOT + SCALEDOWN) for k, b, e in self.tasks.values()]
# the busiest run's cores and biggest process, against what a GPU container reserves (farm.py on()) # the busiest run's cores and biggest process, against what each container reserves (farm.py on())
used = f"; at most {self.cores:.1f} of {self.cpu} cores busy and {self.peak_mb / 1024:.1f} of {self.gib} GB in one process" if self.cores else "" used = f"; at most {self.cores:.1f} of {self.cpu} cores busy and {self.peak_mb / 1024:.1f} of {self.gib} GB in one process" if self.cores else ""
flat = sum(1 for k, _ in up if k == CPU) return f"raea farm: billed about ${sum(price(k, s, self.cpu, self.gib) for k, s in up):.3f}: {len(up)} GPU containers up {sum(s for _, s in up):.0f} s in all{used}"
# the containers by what they are: a job with no 3D has one GPU container (frame 0's) and the rest with none
what = f"{len(up)} GPU containers" if not flat else f"{len(up) - flat} GPU and {flat} CPU containers"
return f"raea farm: billed about ${self.usd():.3f}: {what} up {sum(s for _, s in up):.0f} s in all{used}"
def encode(frames_dir, out, fps, sound, run, start=0, frames=None): def encode(frames_dir, out, fps, sound, run, start=0, frames=None):
@@ -186,34 +162,19 @@ def encode(frames_dir, out, fps, sound, run, start=0, frames=None):
return run(cmd) return run(cmd)
def join(frames_dir, out, sound, run, seconds=None): def join(frames_dir, out, sound, run):
"""The runs' H.264 videos (run-FIRST.mp4) as OUT, one after another without encoding again, with the sound, cut at """The runs' H.264 videos (run-FIRST.mp4) as OUT, one after another without encoding again, with the sound."""
`seconds` (the piece's length). Only the runs' video tracks are read: each run has an AAC track too, whose encoder
delay (1024 samples) moved the joined video 21 ms after the sound, and -shortest then ended it 2 frames early
(the 894-frame ad came back as 892 on every farm render before 11-30, the live farm's included)."""
runs_ = sorted(n for n in os.listdir(frames_dir) if re.fullmatch(r"run-\d+\.mp4", n)) runs_ = sorted(n for n in os.listdir(frames_dir) if re.fullmatch(r"run-\d+\.mp4", n))
listing = os.path.join(frames_dir, "runs.txt") listing = os.path.join(frames_dir, "runs.txt")
track = video_track(os.path.join(frames_dir, runs_[0]), run) if runs_ else None
with open(listing, "w") as f: with open(listing, "w") as f:
if track:
f.write(f"ffconcat version 1.0\nstream\nexact_stream_id {track}\n")
f.writelines(f"file '{n}'\n" for n in runs_) f.writelines(f"file '{n}'\n" for n in runs_)
cmd = ["ffmpeg", "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", listing] cmd = ["ffmpeg", "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", listing]
if sound and os.path.exists(sound) and os.path.getsize(sound) > 44: if sound and os.path.exists(sound) and os.path.getsize(sound) > 44:
cmd += ["-i", sound, "-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "256k"] cmd += ["-i", sound, "-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "256k", "-shortest"]
if seconds:
cmd += ["-t", f"{seconds:.6f}"]
cmd += ["-c:v", "copy", "-movflags", "+faststart", out] cmd += ["-c:v", "copy", "-movflags", "+faststart", out]
return run(cmd) return run(cmd)
def video_track(path, run):
"""A video file's video track id (0x1), as the concat demuxer's exact_stream_id takes it; None when not said."""
c, o, _ = run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=id", "-of", "csv=p=0", path])
o = (o or "").strip().splitlines()
return o[0].strip() if not c and o and o[0].strip().startswith("0x") else None
def keep(frames_dir, out, start=0): def keep(frames_dir, out, start=0):
"""The frames as a folder of PNGs, named as raea names them (frame-00000.png is the first).""" """The frames as a folder of PNGs, named as raea names them (frame-00000.png is the first)."""
os.makedirs(out, exist_ok=True) os.makedirs(out, exist_ok=True)
@@ -221,49 +182,30 @@ def keep(frames_dir, out, start=0):
shutil.move(os.path.join(frames_dir, name), os.path.join(out, f"frame-{i:05d}.png")) shutil.move(os.path.join(frames_dir, name), os.path.join(out, f"frame-{i:05d}.png"))
def spread(fn, kind, calls, log, what, bill=None, most=None, got=None, again=None): def spread(fn, kind, calls, log, what, bill=None, most=None, got=None):
"""`calls` on `fn`, at most `most` containers at once when there are more calls than that (each takes the next call """`calls` on `fn`, at most `most` GPUs at once when there are more calls than that (each GPU takes the next call
as it finishes one); each finished run said in the log as it lands, and kept in `got` when given. The first as it finishes one); each finished run said in the log as it lands, and kept in `got` when given. The first
failure's code, else 0. With `again` (a list): a run that failed, or drew 3D, isn't the job's failure: its call failure's code, else 0."""
goes in `again`, for a GPU to take."""
code = 0 code = 0
if most and len(calls) > most: if most and len(calls) > most:
fn = fn.with_options(max_containers=most) fn = fn.with_options(max_containers=most)
left = {c[3]: c for c in calls if len(c) > 3} if again is not None else {}
for r in fn.starmap(calls, order_outputs=False, return_exceptions=True): for r in fn.starmap(calls, order_outputs=False, return_exceptions=True):
if isinstance(r, Exception): if isinstance(r, Exception):
# (with `again`, said too: 11-30 a run went back to a GPU and nothing said why) log(f"raea farm: a run failed: {r!r}", err=True)
log(f"raea farm: a run failed{' without a GPU' if again is not None else ''}: {r!r}"[:600], err=again is None) code = code or 1
code = code if again is not None else code or 1
continue continue
if bill: if bill:
bill.add(r) bill.add(r)
if again is not None and (r["code"] or (r.get("manifest") or {}).get("has3d")):
why = "it drew 3D" if not r["code"] else f"exit {r['code']}: " + " | ".join((r.get("out") or "").strip().splitlines()[-3:])
log(f"raea farm: frames from {r.get('first')} didn't draw without a GPU ({why})"[:600])
continue
left.pop(r.get("first"), None)
if got is not None: if got is not None:
got.append(r) got.append(r)
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s") log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
if r["code"]: if r["code"]:
log(r["out"], err=True) log(r["out"], err=True)
code = code or r["code"] code = code or r["code"]
if again is not None:
again.extend(left.values())
return code return code
def timed(r, n): def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None, bill=None):
"""A timed run's (seconds a frame, seconds to start): the frame from raea's own clocks over the whole frame (React,
the page, the clips read, the draw, the encode: farm.py's work_ms) when the run says them, else from its "N ms a
frame" line, which is React and the page alone. That line read 47 ms on a 3D film whose frames took 151 ms, so
the plan put 892 frames on one GPU, and 205 ms on an ad whose slow stretch took 1,600 (11-30)."""
frame_s = (r.get("work_ms") / n if r.get("work_ms") else r.get("ms") or 1000 * r["s"] / n) / 1000
return frame_s, max(0.0, r["s"] - frame_s * n)
def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None, bill=None, cpu_render=None):
bill = bill or Bill() bill = bill or Bill()
id = opts["id"] id = opts["id"]
rest, out = split_out(args) rest, out = split_out(args)
@@ -276,100 +218,35 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
if out.endswith(VIDEO): if out.endswith(VIDEO):
t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env)) t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env))
t.start() t.start()
video = out.endswith(VIDEO) p = bill.add(waited(render, log, id, rest, probe=True))
can_flat = bool(video and cpu_render and not opts.get("gpu")) if p["code"] or not p["length"]:
# what each frame draws, as a key (farm_keys.py): read here with nothing drawn, when this raea has --keys log(p["out"], err=True)
keyed, keys_s = farm_keys.read(rest, work, run, cpu_env, f"/tmp/{id}-keys.json") if video and opts.get("keys") else (None, 0) if not p["code"]:
log("raea farm: frame 0 rendered but didn't say the piece's length, so its frames can't be shared out", err=True)
def probed(): return p["code"] or 1
p = bill.add(waited(render, log, id, rest, probe=True))
if p["code"] or not p["length"]:
log(p["out"], err=True)
if not p["code"]:
log("raea farm: frame 0 rendered but didn't say the piece's length, so its frames can't be shared out", err=True)
return p, p["code"] or 1
log(f"raea farm: {p['length']} frames at {p['w']}x{p['h']}, {p['fps'] or 30} fps; frame 0 on a {p.get('kind') or opts.get('gpu') or 'T4'} in {p['s']:.1f} s")
return p, 0
if keyed and keyed["has3d"] is False and can_flat:
# its keys say the length, the size and that there's no 3D in it: no frame 0 on a GPU first
p = {"code": 0, "length": keyed["length"], "fps": keyed["fps"], "w": keyed["width"], "h": keyed["height"], "s": 0.0, "keys": True,
"manifest": {k: keyed[k] for k in ("width", "height", "fps", "length", "has3d")}}
log(f"raea farm: {p['length']} frames at {p['w']}x{p['h']}, {p['fps'] or 30} fps; its frames' keys read in {keys_s:.1f} s, no 3D in it")
else:
p, code = probed()
if code:
return code
length, fps, kind = p["length"], p["fps"] or 30, p.get("kind") or opts.get("gpu") or "T4" length, fps, kind = p["length"], p["fps"] or 30, p.get("kind") or opts.get("gpu") or "T4"
# the runs an earlier render of the piece left (kept by their frames' keys), and the frames no kept run holds log(f"raea farm: {length} frames at {p['w']}x{p['h']}, {fps} fps; frame 0 on a {kind} in {p['s']:.1f} s")
store, hits, gaps = None, [], [(0, length - 1)] video = out.endswith(VIDEO)
if keyed and not keyed["has3d"] and keyed["length"] == length and opts.get("kept", True): n0 = min(length, FIRST)
store = f"{opts['keys']}/{farm_keys.base(opts.get('raea'), rest, keyed, work)}" r0 = bill.add(waited(render, log, id, rest, list(range(n0)), 0, video=video))
hits, gaps = farm_keys.cover(store, keyed["keys"]) if r0["code"]:
if hits:
held = sum(n for _, n, _ in hits)
log(f"raea farm: {len(hits)} runs kept from an earlier render hold {held} of {length} frames, so {length - held} are drawn")
# the clips read from copies no larger than the page draws them (farm_proxy.py), after the store's name is read
# from the originals: a draft at half size reads most of a 4K cut's footage at a quarter of its pixels
if keyed and keyed.get("drawn") and opts.get("proxies") and gaps:
if farm_proxy.use(farm_proxy.plan(keyed["drawn"], work, run, opts["proxies"]), opts["proxy_make"], log, reload):
opts.get("proxy_commit", lambda: None)()
todo = sum(b - a + 1 for a, b in gaps)
n0, at0 = min(todo, FIRST, gaps[0][1] - gaps[0][0] + 1 if gaps else 0), gaps[0][0] if gaps else 0
# a video with no 3D in it (frame 0's manifest says) is drawn by containers with no GPU: the page, the clips and
# the encode are the CPU's work either way. A named GPU (opts gpu) keeps the job on it.
gpu_render, gpu_kind = render, kind
# a piece with 3D in it keeps its GPU, and its runs use the GPU's encoder and decoder too (CR34): on a 2D piece NVENC
# bought nothing (300 frames: 210 s against libx264's 215 s, 11% more bytes), the page and the clips are the work
nv = bool((p.get("manifest") or {}).get("has3d"))
flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False)
r0 = None
first = list(range(at0, at0 + n0))
if flat and n0:
r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video))
if r0["code"] or (r0.get("manifest") or {}).get("has3d"):
log("raea farm: the first frames didn't draw without a GPU, so the job stays on GPUs")
flat, r0 = False, None
if p.get("keys"): # no frame 0 was drawn on a GPU yet: its time is what a cold GPU's start is planned by
p, code = probed()
if code:
return code
kind = gpu_kind = p.get("kind") or opts.get("gpu") or "T4"
if flat:
render, kind, most = cpu_render, CPU, opts.get("cpus") or opts["gpus"]
else:
most = opts["gpus"]
if n0:
r0 = bill.add(waited(render, log, id, rest, first, at0, video=video, **({"nv": True} if nv else {})))
if r0 and r0["code"]:
log(r0["out"], err=True) log(r0["out"], err=True)
return r0["code"] return r0["code"]
frame_s, start_s = timed(r0, n0) if r0 else (0.0, 0.0) frame_s = (r0["ms"] or 1000 * r0["s"] / n0) / 1000
left = todo - n0 start_s = max(0.0, r0["s"] - frame_s * n0)
# a container beyond the first starts cold: frame 0's whole time, less its one frame (the first is warm by now) left = length - n0
cold_s = start_s if flat else max(start_s, p["s"] - frame_s) k = gpus_for(left, frame_s, start_s, opts["gpus"])
k = gpus_for(left, frame_s, cold_s, most) m = parts_per_gpu(left, k, frame_s, start_s)
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS) cost = price(kind, p["s"] + r0["s"] + k * m * start_s + left * frame_s)
cost = price(gpu_kind, p["s"]) + price(kind, (r0["s"] if r0 else 0) + k * m * start_s + (k - 1) * (cold_s - start_s) + left * frame_s, busy=(r0 or {}).get("cores") or 0)
parts = f" in {k * m} parts" if m > 1 else "" parts = f" in {k * m} parts" if m > 1 else ""
on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)" log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {k} {kind}s{parts}, about ${cost:.3f} in all")
if r0:
log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {on}{parts}, about ${cost:.3f} in all")
else:
log("raea farm: nothing to draw: every frame is in a run kept from an earlier render")
if opts.get("max_usd") is not None and cost > opts["max_usd"]: if opts.get("max_usd") is not None and cost > opts["max_usd"]:
log(f"raea farm: about ${cost:.3f} is over max_usd ${opts['max_usd']:.3f}, so the rest don't start", err=True) log(f"raea farm: about ${cost:.3f} is over max_usd ${opts['max_usd']:.3f}, so the rest don't start", err=True)
return 3 return 3
# a video's runs can't drop warm-up frames without encoding again, so they have none # a video's runs can't drop warm-up frames without encoding again, so they have none
warm = 0 if video else opts.get("warm", 0) warm = 0 if video else opts.get("warm", 0)
got = [r0] if r0 else [] got = [r0]
calls = [(id, rest, f, at, False, video, *([True] if nv and not flat else [])) for a, b, share in farm_keys.spans(gaps, n0, k * m) for f, at in runs(a, b, share, warm)] if left else [] code = spread(render, kind, [(id, rest, f, at, False, video) for f, at in runs(n0, length - 1, k * m, warm)], log, "frames", bill, k, got) if left else 0
again = [] if flat else None
code = spread(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
if again:
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it again
log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)")
code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got)
if code: if code:
return code return code
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other # the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
@@ -379,22 +256,14 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
reload() # the other containers' frames reload() # the other containers' frames
frames = f"{os.path.dirname(work)}/frames" frames = f"{os.path.dirname(work)}/frames"
dest = os.path.join(work, out) dest = os.path.join(work, out)
# (a run that drew 3D after all isn't kept: its frames can hang on the frames before them)
if store and not any((r.get("manifest") or {}).get("has3d") for r in got):
farm_keys.put(store, keyed["keys"], got, frames)
got += farm_keys.take(hits, frames)
if manifest and p.get("manifest"): if manifest and p.get("manifest"):
path = os.path.join(work, manifest) path = os.path.join(work, manifest)
os.makedirs(os.path.dirname(path) or ".", exist_ok=True) os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
whole = joined(p["manifest"], [r.get("manifest") for r in got])
if hits and keyed.get("sounds"):
# a kept run's manifest holds the sounds of the render that drew it: the piece's own, as its keys' pass heard them
whole["sounds"] = keyed["sounds"]
with open(path, "w") as f: with open(path, "w") as f:
json.dump(whole, f, indent=2) json.dump(joined(p["manifest"], [r.get("manifest") for r in got]), f, indent=2)
if video: if video:
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True) os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
c, o, s = join(frames, dest, sound, run, length / fps) c, o, s = join(frames, dest, sound, run)
log(f"raea farm: joined {out} in {s:.1f} s" if not c else o, err=bool(c)) log(f"raea farm: joined {out} in {s:.1f} s" if not c else o, err=bool(c))
return c return c
keep(frames, dest) keep(frames, dest)
@@ -512,7 +381,7 @@ def blender(args, opts, work, log, render, run, reload=lambda: None, bill=None):
return 0 return 0
def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload=lambda: None, cpu_render=None): def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload=lambda: None):
"""The job: a split raea render, a split Blender render, or `raea ARGS` whole on one GPU.""" """The job: a split raea render, a split Blender render, or `raea ARGS` whole on one GPU."""
if opts.get("gpu"): if opts.get("gpu"):
render, blender_render = (f.with_options(gpu=opts["gpu"]) for f in (render, blender_render)) render, blender_render = (f.with_options(gpu=opts["gpu"]) for f in (render, blender_render))
@@ -523,7 +392,7 @@ def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload
return code return code
bill = Bill() bill = Bill()
if splittable(args): if splittable(args):
code = raea_render(args, opts, work, log, render, cpu_env, run, reload, bill, cpu_render) code = raea_render(args, opts, work, log, render, cpu_env, run, reload, bill)
else: else:
r = bill.add(waited(render, log, opts["id"], args)) r = bill.add(waited(render, log, opts["id"], args))
log(r["out"], err=bool(r["code"])) log(r["out"], err=bool(r["code"]))
-120
View File
@@ -1,120 +0,0 @@
# A job's clips read from copies no larger than they're drawn (docs/cloud-render.feature CR36): `raea render --keys`
# says the largest each clip is drawn over the piece (its box as drawn, transforms and a framed take's punch-in
# applied, in output px), and a clip much larger than that is read from a copy at that size, kept on the farm's volume
# by the source's hash and the size, so it's made once across every job. The picture can't lose detail: no copy is
# smaller than the largest the page draws the clip, and none is made for a clip whose size wasn't known for a frame.
#
# plan(drawn, work, run) [(path, source, w, h, copy)]: the clips worth a copy (at most AT of the width)
# use(plans, make, log) each copy made where missing (in parallel, `make` on containers with no GPU), then
# the job's link pointed at it
#
# A 1080x1920 cut from 4K landscape footage needs most of each clip (a 9:16 crop of 2160 rows into 1920, and punch-ins
# above 1): its master render gets no copies. A half-size draft (--scale 0.5) reads six of its seven clips from copies
# at 27-59% of the width.
import json
import os
AT = 0.75 # a copy at most this much of the source's width (56% of its pixels), or none: below that it's barely worth it
CRF = 12 # visually lossless (libx264 medium): the page scales the copy, so any loss would show only at 1:1
EVEN = lambda v: max(2, int(v + 1.999) // 2 * 2) # noqa: E731 - up to an even number of px (yuv420p)
def probe(path, run):
c, o, _ = run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,color_space:stream_side_data=rotation",
"-of", "json", path])
try:
s = json.loads(o)["streams"][0]
except Exception:
return None
rot = any(abs(int(d.get("rotation", 0))) in (90, 270) for d in s.get("side_data_list") or [])
return int(s["width"]), int(s["height"]), s.get("color_space") or "", rot
def source_id(path):
"""The file's content id: a link into the farm's cache is named for its hash; anything else is hashed here"""
real = os.path.realpath(path)
name = os.path.basename(real)
if os.path.islink(path) and len(name) == 64 and all(c in "0123456789abcdef" for c in name):
return name
import hashlib
h = hashlib.sha256()
with open(real, "rb") as f:
for b in iter(lambda: f.read(1 << 20), b""):
h.update(b)
return h.hexdigest()
def plan(drawn, work, run, store):
"""The clips worth reading from a copy: [(path in the job, its source, copy w, copy h, copy path, matrix)]"""
out = []
for rel, size in (drawn or {}).items():
path = os.path.join(work, rel)
if not size or not os.path.isfile(path) or not os.path.realpath(path).startswith("/"):
continue
p = probe(path, run)
if not p or p[3]: # (a rotated clip's drawn size is in its turned frame: left as it is)
continue
w, h, matrix, _ = p
need = max(size[0] / w, size[1] / h)
if need > AT:
continue
cw, ch = EVEN(w * need), EVEN(h * need)
ext = os.path.splitext(rel)[1].lower() or ".mp4"
# untagged HD is read as BT.709 (io/ffmpeg's decoder, as Apple and browsers read it): the copy is tagged so,
# or a copy under 720 lines would be read as BT.601 and shift its colours
matrix = matrix if matrix in ("bt709", "bt470bg", "smpte170m", "bt2020nc") else ("bt709" if h >= 720 else "smpte170m")
out.append((path, os.path.realpath(path), cw, ch, os.path.join(store, f"{source_id(path)}-{cw}x{ch}{ext}"), matrix))
return out
def command(src, dest, w, h, matrix):
"""ffmpeg making one copy: scaled with lanczos in the source's own matrix, every frame at its own time, the sound copied"""
tag = {"bt709": "bt709", "bt470bg": "bt470bg", "smpte170m": "smpte170m", "bt2020nc": "bt2020nc"}[matrix]
return ["ffmpeg", "-v", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a?", "-vf",
f"scale={w}:{h}:flags=lanczos:in_color_matrix={tag if tag != 'bt2020nc' else 'bt2020'}:out_color_matrix={tag if tag != 'bt2020nc' else 'bt2020'}",
"-fps_mode", "passthrough", "-c:v", "libx264", "-preset", "medium", "-crf", str(CRF), "-pix_fmt", "yuv420p",
"-colorspace", tag, "-c:a", "copy", "-movflags", "+faststart", "-f", "mov" if dest.endswith(".mov") else "mp4", dest]
def use(plans, make, log, reload=lambda: None):
"""Each copy made where it isn't kept yet (`make`: a function's starmap over (src, dest, w, h, matrix)), then each
clip's link in the job pointed at its copy. Returns the number of clips swapped."""
todo = [(src, copy, w, h, m) for _, src, w, h, copy, m in plans if not os.path.exists(copy)]
made = 0
if todo:
for r in make(todo):
if isinstance(r, Exception) or (r or {}).get("code"):
log(f"raea farm: a clip's copy wasn't made, so it's read whole: {r if isinstance(r, Exception) else r.get('out', '')}"[:400])
else:
made += 1
reload()
used = 0
for path, src, w, h, copy, _ in plans:
if os.path.exists(copy):
tmp = f"{path}.proxy-link"
os.symlink(copy, tmp)
os.replace(tmp, path)
keep_faces(path, copy)
used += 1
if plans:
log(f"raea farm: {used} clips read from copies at the size they're drawn ({made} made now, {used - made if used >= made else 0} kept from before)")
return used
def keep_faces(path, copy):
"""A framed take's face track (TAKE.faces.json, made from the original by the keys pass) stamped for the copy, so
the page frames on the original's faces and doesn't find them again in the copy (runtime/page/src/faces.rs reads a
track only when its stamp is the take's own size and time)"""
side = os.path.splitext(path)[0] + ".faces.json"
if not os.path.exists(side):
return
try:
with open(side) as f:
t = json.load(f)
st = os.stat(copy)
t["take"] = {"bytes": st.st_size, "modified": int(st.st_mtime)}
with open(side, "w") as f:
f.write(json.dumps(t) + "\n")
except Exception:
pass
-2
View File
@@ -40,6 +40,4 @@ def kind_of(name):
for k in ("B300", "B200", "H200", "H100", "L40S", "A10", "L4", "T4"): for k in ("B300", "B200", "H200", "H100", "L40S", "A10", "L4", "T4"):
if re.search(rf"\b{k}\b", n): if re.search(rf"\b{k}\b", n):
return k return k
if re.search(r"\bA10G\b", n): # AWS's A10 (Modal's "A10" on some hosts)
return "A10"
return "" return ""
-178
View File
@@ -1,178 +0,0 @@
# raea cloud's library proxies on Modal (index-run.ts, 12-02): a video's 540p copy, made once per version of the file and
# kept in R2 by its source's SHA-256. Its own app, beside raea-ingest's indexer, so it deploys without the indexer's
# bundle. From sdk/cloud:
#
# MODAL_PROFILE=raea modal deploy deploy/modal/proxy.py
#
# POST /v1/proxy-jobs {url, put, ticket} a job: the file fetched from url, its proxy written through the Worker's
# put (/u/<prefix>/) with ticket (exp=&sig=) -> {id}
# GET /v1/proxy-jobs/ID {state: running} | {state: done, sha256, proxy, bytes...} | {state: failed, error}
# GET /healthz
#
# Every call but /healthz carries Authorization: Bearer RAEA_INGEST_TOKEN (Modal secret raea-ingest, as raea-ingest's).
import os
import subprocess
import tempfile
import modal
app = modal.App("raea-proxy", image=modal.Image.debian_slim(python_version="3.12").apt_install("ffmpeg").pip_install("fastapi[standard]"))
secret = modal.Secret.from_name("raea-ingest")
@app.function(cpu=1, memory=1024, secrets=[secret], timeout=300, scaledown_window=120)
@modal.concurrent(max_inputs=16)
@modal.asgi_app()
def api():
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import PlainTextResponse
web = FastAPI()
token = os.environ["RAEA_INGEST_TOKEN"]
def check(req: Request):
if req.headers.get("authorization", "").removeprefix("Bearer ") != token:
raise HTTPException(401, "a raea ingest token is needed (Authorization: Bearer)")
@web.post("/v1/proxy-jobs")
async def submit(req: Request):
check(req)
b = await req.json()
if not isinstance(b.get("url"), str) or not b["url"].startswith("https://"):
raise HTTPException(400, "url is the file's https address")
if not isinstance(b.get("put"), str) or not b["put"].startswith("https://") or not b["put"].endswith("/") or not isinstance(b.get("ticket"), str):
raise HTTPException(400, "put is the Worker's /u/<prefix>/ and ticket its exp=&sig=")
call = await proxy_job.spawn.aio(b["url"], b["put"], b["ticket"])
return {"id": call.object_id}
@web.get("/v1/proxy-jobs/{job}")
async def collect(job: str, req: Request):
check(req)
try:
out = await modal.FunctionCall.from_id(job).get.aio(timeout=0)
except modal.exception.FunctionTimeoutError:
return {"state": "failed", "error": "the file took over an hour"}
except (TimeoutError, modal.exception.TimeoutError):
return {"state": "running"}
except Exception as e:
return {"state": "failed", "error": str(e)[:300]}
return {"state": "failed", **out} if out.get("error") else {"state": "done", **out}
@web.get("/healthz")
def healthz():
return PlainTextResponse("ok")
return web
# ---- the proxy ----
# What people watch and agents look, search and rough-cut from: 540 lines on the short side (never larger than the
# original), H.264 CRF 28 veryfast, a keyframe every second so a seek lands anywhere, AAC 96 kbps stereo, faststart. On
# one StreetTalk take (4K HEVC, 254 s, 726 MB) it was 45 MB. Written into R2 by its source's SHA-256 through the
# Worker's /u/<prefix>/<file id> with a ticket (files.ts putTicket): the job holds no raea credential, and footage kept
# twice is made once. A video already that light (H.264 in MP4, 540 lines or fewer, under 2.5 Mbps) is its own proxy.
PROXY_SHORT = 540
PROXY_LIGHT_BPS = 2_500_000
PART = 64 << 20
AGENT = {"user-agent": "raea-ingest/1"}
def _probe(path: str) -> dict:
import json
r = subprocess.run(["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", path], capture_output=True, text=True, timeout=120)
try:
return json.loads(r.stdout or "{}")
except ValueError:
return {}
def _picture(info: dict):
"""(width, height as shown, codec) of its first video stream, or None"""
v = next((s for s in info.get("streams", []) if s.get("codec_type") == "video" and s.get("disposition", {}).get("attached_pic") != 1), None)
if not v:
return None
w, h = int(v.get("width") or 0), int(v.get("height") or 0)
rot = 0
for sd in v.get("side_data_list", []) or []:
if "rotation" in sd:
rot = int(float(sd["rotation"]))
rot = rot or int(float((v.get("tags") or {}).get("rotate", 0) or 0))
if abs(rot) % 180 == 90:
w, h = h, w
return w, h, v.get("codec_name", "")
def _http(method: str, url: str, body=None, json_body=None, timeout=600) -> dict:
import json
import urllib.request
headers = dict(AGENT)
data = body
if json_body is not None:
data = json.dumps(json_body).encode()
headers["content-type"] = "application/json"
if data is not None:
headers["content-length"] = str(len(data))
with urllib.request.urlopen(urllib.request.Request(url, data=data, method=method, headers=headers), timeout=timeout) as r:
return json.loads(r.read() or b"{}")
@app.function(cpu=8, memory=8192, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=60)
def proxy_job(url: str, put: str, ticket: str) -> dict:
import hashlib
import urllib.error
import urllib.request
with tempfile.TemporaryDirectory() as d:
src, out = os.path.join(d, "in.media"), os.path.join(d, "proxy.mp4")
h, got = hashlib.sha256(), 0
try:
with urllib.request.urlopen(urllib.request.Request(url, headers=AGENT), timeout=300) as r, open(src, "wb") as f:
while chunk := r.read(8 << 20):
h.update(chunk)
got += len(chunk)
f.write(chunk)
except urllib.error.HTTPError as e:
return {"error": f"couldn't fetch the file: {e.code}", "fetched": e.code}
except Exception as e:
return {"error": f"couldn't fetch the file: {e}"[:300]}
sha = h.hexdigest()
info = _probe(src)
pic = _picture(info)
fmt = info.get("format", {})
bps = int(float(fmt.get("bit_rate") or 0)) or (int(got * 8 / float(fmt["duration"])) if float(fmt.get("duration") or 0) > 0 else 0)
base = {"sha256": sha, "source_bytes": got, "seconds": round(float(fmt.get("duration") or 0), 2)}
if not pic:
return {**base, "proxy": None, "why": "no picture in it"}
w, hgt, codec = pic
if min(w, hgt) <= PROXY_SHORT and codec == "h264" and "mp4" in fmt.get("format_name", "") and 0 < bps <= PROXY_LIGHT_BPS:
return {**base, "proxy": None, "why": "light enough to be its own", "width": w, "height": hgt}
fid = f"file-{sha[:24]}"
at = f"{put}{fid}?{ticket}"
try:
began = _http("POST", f"{at}&step=begin", json_body={})
except urllib.error.HTTPError as e:
return {"error": f"the Worker refused the proxy's upload: {e.code}"}
if began.get("have"):
return {**base, "proxy": fid, "kept": True}
scale = f"scale='if(gt(iw,ih),-2,trunc(min({PROXY_SHORT},iw)/2)*2)':'if(gt(iw,ih),trunc(min({PROXY_SHORT},ih)/2)*2,-2)',format=yuv420p"
r = subprocess.run(
["ffmpeg", "-v", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a:0?", "-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", "28",
"-force_key_frames", "expr:gte(t,n_forced*1)", "-c:a", "aac", "-b:a", "96k", "-ac", "2", "-movflags", "+faststart", out],
capture_output=True, text=True, timeout=3300,
)
if r.returncode != 0 or not os.path.exists(out):
return {"error": f"ffmpeg stopped ({r.returncode}): {(r.stderr or '')[-300:]}"}
size, parts = os.path.getsize(out), []
with open(out, "rb") as f:
n = 1
while chunk := f.read(PART):
parts.append(_http("PUT", f"{at}&upload={began['upload']}&part={n}", body=chunk))
n += 1
done = _http("POST", f"{at}&step=complete&upload={began['upload']}", json_body={"parts": parts})
pw = _picture(_probe(out))
return {**base, "proxy": done.get("id", fid), "bytes": size, "width": pw[0] if pw else None, "height": pw[1] if pw else None}
-128
View File
@@ -1,128 +0,0 @@
# raea cloud's ears (12-03): what's said in a piece of sound, word by word, timed to its sound. NVIDIA's Parakeet TDT
# 0.6B v3 (CC-BY-4.0; NeMo, Apache-2.0) on a GPU: the model raea hears with on a Mac (parakeet-mlx), so a cut's words
# are timed the same in the cloud as at home. Whisper large-v3 on OpenRouter, which this replaces, guessed its word
# times and heard a clipped word whole, and StreetTalk's cuts put their out points on those times ("really goo-").
# Parakeet hears the words; Qwen3-ForcedAligner-0.6B (Apache-2.0) then times each one on the sound, where it knows the
# language; each word is then widened onto the gaps around its sound (words_edges.py), so a cut on its edge is in a
# pause. Measured 12-03 on StreetTalk's takes against the sound's own edges: word ends early (a cut there clips the
# word) 12% of the time, against Whisper's 57% and Parakeet's own 28%; starts within 35 ms (median); and a word clipped
# in the take is timed to where its sound stops (3 of 25 placed past it, Whisper 22). About 1.3 s for 20 s of sound.
# The farm's POST /v1/words calls it (farm.py), falling back to Whisper (Groq) when it can't be reached.
#
# MODAL_PROFILE=raea modal deploy deploy/modal/words.py
# Hear().words.remote(mp3_bytes) -> {model, duration, text, words: [{text, start, end}]} (s)
import os
import subprocess
import tempfile
import modal
MODEL = "nvidia/parakeet-tdt-0.6b-v3"
app = modal.App(os.environ.get("RAEA_WORDS_APP", "raea-words"))
# the weights once, in the models volume the farm already keeps
models = modal.Volume.from_name("raea-models", create_if_missing=True, version=2)
image = (
modal.Image.debian_slim(python_version="3.11")
.apt_install("ffmpeg", "libsndfile1")
.pip_install("nemo_toolkit[asr]==2.7.3", "numpy<2.3")
.env({"HF_HOME": "/models/hf", "TOKENIZERS_PARALLELISM": "false"})
.add_local_python_source("words_edges")
)
align_image = (
modal.Image.debian_slim(python_version="3.11")
.apt_install("ffmpeg", "libsndfile1")
.pip_install("qwen-asr==0.0.6", "torch==2.6.0", "torchaudio==2.6.0")
.env({"HF_HOME": "/models/hf"})
)
# the aligner's languages, by the ISO code a caller gives
ALIGNS = {"en": "English", "zh": "Chinese", "yue": "Cantonese", "fr": "French", "de": "German", "it": "Italian", "ja": "Japanese", "ko": "Korean", "pt": "Portuguese", "ru": "Russian", "es": "Spanish"}
@app.cls(gpu="L4", image=align_image, volumes={"/models": models}, timeout=900, max_containers=2, scaledown_window=60)
class Align:
@modal.enter()
def load(self):
import torch
from qwen_asr import Qwen3ForcedAligner
self.m = Qwen3ForcedAligner.from_pretrained("Qwen/Qwen3-ForcedAligner-0.6B", dtype=torch.bfloat16, device_map="cuda:0")
models.commit()
@modal.method()
def align(self, pcm: bytes, text: str, language: str) -> list:
import numpy as np
x = np.frombuffer(pcm, np.int16).astype(np.float32) / 32768
r = self.m.align(audio=(x, 16000), text=text, language=language)[0]
return [{"text": u.text, "start": float(u.start_time), "end": float(u.end_time)} for u in r]
def aligned(heard: list, got: list) -> "list | None":
"""the heard words (their spelling and punctuation) on the aligner's times, matched in order by their letters; a
word the aligner split or spelt otherwise keeps Parakeet's times. None if under 80% of the words matched"""
import difflib
import re
key = lambda t: re.sub(r"[^\w]", "", t.lower())
got = [g for g in got if key(g["text"])]
sm = difflib.SequenceMatcher(None, [key(h["text"]) for h in heard], [key(g["text"]) for g in got], autojunk=False)
out = [dict(h) for h in heard]
n = 0
for a, b, size in sm.get_matching_blocks():
for k in range(size):
g = got[b + k]
out[a + k].update(start=g["start"], end=max(g["end"], g["start"] + 0.02))
n += 1
return out if heard and n / len(heard) >= 0.8 else None
# full attention holds about this much sound on a T4; longer pieces read with local attention (NeMo's own advice)
FULL_S = 180
@app.cls(gpu="T4", image=image, volumes={"/models": models}, timeout=900, max_containers=2, scaledown_window=60)
class Hear:
@modal.enter()
def load(self):
import nemo.collections.asr as asr
self.m = asr.models.ASRModel.from_pretrained(MODEL)
self.m.eval()
self.local = False
models.commit()
def attention(self, local: bool):
if local != self.local:
self.m.change_attention_model("rel_pos_local_attn", [256, 256]) if local else self.m.change_attention_model("rel_pos")
self.local = local
@modal.method()
def words(self, sound: bytes, language: str = "") -> dict:
import numpy as np
import words_edges
with tempfile.TemporaryDirectory() as d:
src, wav = f"{d}/in", f"{d}/in.wav"
open(src, "wb").write(sound)
r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", src, "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", wav], capture_output=True, text=True)
if r.returncode:
raise ValueError(f"the sound couldn't be read: {r.stderr.strip()[-300:]}")
pcm = np.fromfile(wav, dtype=np.int16, offset=44).astype(np.float32) / 32768
duration = len(pcm) / 16000
self.attention(duration > FULL_S)
h = self.m.transcribe([wav], timestamps=True, batch_size=1, verbose=False)[0]
heard = [{"text": w["word"].strip(), "start": float(w["start"]), "end": float(w["end"])} for w in (h.timestamp or {}).get("word", []) if w.get("word", "").strip()]
model = MODEL
# timed by the aligner where it knows the language (English when none is given and the words read as Latin)
lang = ALIGNS.get(language.lower()[:3].rstrip("-_")) or ALIGNS.get(language.lower()[:2]) or ("English" if not language and heard and all(ord(c) < 0x250 for c in h.text) else None)
if lang and heard:
try:
got = aligned(heard, Align().align.remote((pcm * 32768).clip(-32768, 32767).astype(np.int16).tobytes(), " ".join(w["text"] for w in heard), lang))
if got:
heard, model = got, f"{MODEL}+Qwen/Qwen3-ForcedAligner-0.6B"
else:
print("words: the aligner's words didn't pair with Parakeet's, so Parakeet's times stand", flush=True)
except Exception as e:
print(f"words: the aligner failed, so Parakeet's times stand: {str(e)[-300:]}", flush=True)
words = words_edges.edges(heard, words_edges.levels(pcm, 16000))
return {"model": model, "duration": duration, "text": h.text, "words": words}
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff. Show more