mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ecf1b8b1e | ||
|
|
c3765a13bb | ||
|
|
5301beb62f | ||
|
|
5c2a524369 | ||
|
|
4044e442c2 | ||
|
|
d4e39d41f0 | ||
|
|
c7e5534d38 | ||
|
|
788444e127 | ||
|
|
5b72d2e4dc | ||
|
|
33d34e51b5 | ||
|
|
7cd22cecfc | ||
|
|
76e6b00e04 | ||
|
|
88cacbe7f7 | ||
|
|
4fd7210cfe | ||
|
|
06a48730d1 | ||
|
|
28d89f8ffd | ||
|
|
7b8317764a | ||
|
|
c69e28fac3 | ||
|
|
83da71b62d | ||
|
|
4d896d2b2f | ||
|
|
d4d13925fa | ||
|
|
a8d7263235 |
No files matched your search
@@ -107,5 +107,7 @@ 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/media/
|
||||
/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)
|
||||
/sdk/raea/bench/bevy-parity/**/assets
|
||||
Generated
+3
@@ -13978,7 +13978,10 @@ dependencies = [
|
||||
name = "raea-app-playable"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"raea-core-fonts",
|
||||
"raea-io-assets",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"regex",
|
||||
|
||||
@@ -142,7 +142,7 @@ fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
|
||||
let what = match job.make.kind {
|
||||
goal::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
|
||||
goal::Kind::Shot => "raea make framing --out review/r1",
|
||||
goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules => "raea render EDIT.tsx --review review/r1",
|
||||
goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules | goal::Kind::Playable => "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"))];
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use image::{Rgba, RgbaImage};
|
||||
use raea_core_brief::{make::Make, read};
|
||||
use raea_core_brief::{goal::Goal as Make, read};
|
||||
|
||||
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
|
||||
let d = dir("framing");
|
||||
assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition"));
|
||||
assert!(raea_core_brief::make::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
|
||||
assert!(raea_core_brief::goal::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
|
||||
@@ -193,7 +193,7 @@ fn a_quote_reads_as_one_line() {
|
||||
|
||||
#[test]
|
||||
fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() {
|
||||
use raea_core_brief::make::Object;
|
||||
use raea_core_brief::goal::Object;
|
||||
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
|
||||
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"]);
|
||||
|
||||
@@ -14,4 +14,9 @@ raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
regex = "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"] }
|
||||
@@ -0,0 +1,127 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
+161
-18
@@ -1,15 +1,19 @@
|
||||
//! `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
|
||||
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
|
||||
//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
|
||||
//! 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
|
||||
//! 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 pages;
|
||||
mod sound;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
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 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 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
|
||||
@@ -19,12 +23,13 @@ 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)
|
||||
}
|
||||
|
||||
/// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add [email protected]`),
|
||||
/// else the copy beside sdk/playable or sdk/r3f in raea's own files
|
||||
fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
|
||||
/// The folder whose node_modules holds a package the page carries (three.js to draw 3D, Tone.js to play a raea/tone
|
||||
/// graph): the project's own (`raea add [email protected]`), 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> {
|
||||
let has = |d: &Path| d.join("node_modules").join(name).join("package.json").is_file();
|
||||
let mut d = game.parent();
|
||||
while let Some(dir) = d {
|
||||
if dir.join("node_modules/three/package.json").is_file() {
|
||||
if has(dir) {
|
||||
return Ok(dir.to_path_buf());
|
||||
}
|
||||
d = dir.parent();
|
||||
@@ -32,21 +37,80 @@ fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
|
||||
["sdk/playable", "sdk/r3f"]
|
||||
.iter()
|
||||
.map(|p| home.join(p))
|
||||
.find(|d| d.join("node_modules/three/package.json").is_file())
|
||||
.ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add [email protected]` in it".into())
|
||||
.find(|d| has(d))
|
||||
.ok_or_else(|| format!("a playable {why} with {name}, which this project doesn't have: `raea add {add}` in it"))
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// three.js, for a game with a 3D kind (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 three.js as its 3D drawer 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 {{ three3d }} from {:?};\n", spec(&host.join("three.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 { "three3d" } else { "undefined" };
|
||||
e.push_str(&match sounds {
|
||||
Sounds::None if with_3d => "start(three3d);\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
|
||||
fn bundle(game: &Path, home: &Path) -> R<String> {
|
||||
let host = home.join("sdk/playable/src/host/main.tsx");
|
||||
if !host.is_file() {
|
||||
fn bundle(game: &Path, home: &Path, carry: Carry) -> R<String> {
|
||||
let Carry { with_3d, sounds, .. } = carry;
|
||||
let host = home.join("sdk/playable/src/host");
|
||||
if !host.join("main.tsx").is_file() {
|
||||
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 entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
|
||||
let alias = format!("three/={}", three.display());
|
||||
let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
|
||||
let mut flags = vec!["--minify".to_string(), "1".into(), "--inline".into(), "1".into()];
|
||||
if with_3d {
|
||||
flags.extend(["--alias".into(), format!("three/={}", package_dir(game, home, "three", "draws its 3D", "[email protected]")?.display())]);
|
||||
}
|
||||
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 _ = std::fs::remove_file(&out);
|
||||
js
|
||||
@@ -66,7 +130,12 @@ 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 card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
|
||||
let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
|
||||
// the files' name: the brief's (`playable({ playable: { name } })`), else the game's file name
|
||||
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 found = lint::lint(&game)?;
|
||||
@@ -83,16 +152,45 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
return Err(why.join("\n"));
|
||||
}
|
||||
|
||||
let js = bundle(&game, &raea_io_home::home())?;
|
||||
let is = |k: &str| found.sound[k].as_bool() == Some(true);
|
||||
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()))?;
|
||||
let mut over = false;
|
||||
let mut written = Vec::new();
|
||||
for net in networks {
|
||||
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
|
||||
let w = pages::write(net, &name, &script, &out, orientation)?;
|
||||
let w = pages::write(net, &name, &script, &out, orientation, &style)?;
|
||||
let ok = w.bytes <= pages::CAP;
|
||||
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" }));
|
||||
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 {
|
||||
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
|
||||
return Err(report.join("\n"));
|
||||
@@ -100,3 +198,48 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
|
||||
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("three3d } from \"/h/host/three.ts\"") && e.contains("start(three3d);"), "{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(three3d, 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");
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,10 @@ pub struct Found {
|
||||
pub kinds: Vec<String>,
|
||||
pub notes: 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)] = &[
|
||||
@@ -27,7 +31,7 @@ const SOURCE_RULES: &[(&str, &str)] = &[
|
||||
(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#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
|
||||
(r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
|
||||
(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"),
|
||||
];
|
||||
|
||||
/// The game's source and its compositions, judged
|
||||
@@ -48,7 +52,7 @@ pub fn lint(game: &Path) -> R<Found> {
|
||||
let walked = match walk(game) {
|
||||
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
|
||||
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
|
||||
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals, sound: Value::Null, ecs: false }),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let comps: Vec<Comp> = walked["comps"]
|
||||
@@ -73,7 +77,7 @@ pub fn lint(game: &Path) -> R<Found> {
|
||||
for k in strings("refused") {
|
||||
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
|
||||
}
|
||||
Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
|
||||
Ok(Found { comps, kinds: strings("kinds"), notes, refusals, sound: walked["sound"].clone(), ecs: walked["ecs"].as_bool() == Some(true) })
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -43,9 +43,10 @@ fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
|
||||
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
|
||||
let html = |head: &str, body: &str| page(name, head, body, script);
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip, its
|
||||
/// `style` (the fonts, fonts.rs) first in the head
|
||||
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, &format!("{style}\n{head}"), body, script);
|
||||
let file = match network {
|
||||
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
|
||||
"google" => {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! 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",
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,6 @@ mkdir -p "$OUT"
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
|
||||
expected() { case $1 in
|
||||
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)" ;;
|
||||
esac; }
|
||||
SAME=0 DIFF=0 ERR=0 SKIP=0
|
||||
|
||||
+18
-5
@@ -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
|
||||
//! workflow), written with `cut()`, `shot()`, `kit()`, `scene()` or `rules()` from "raea/brief" before anything is
|
||||
//! built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that belong
|
||||
//! together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), and
|
||||
//! rules (any other work: only its own rules). Any goal can carry `rules` and an `aim`. Every object carries its real
|
||||
//! workflow), written with `cut()`, `shot()`, `kit()`, `scene()`, `playable()` or `rules()` from "raea/brief" before
|
||||
//! anything is built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that
|
||||
//! belong together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), a
|
||||
//! 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
|
||||
//! 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.
|
||||
|
||||
@@ -25,6 +25,9 @@ pub enum Kind {
|
||||
Cut,
|
||||
/// any other work, held only to its rules: commands that must pass, files that must exist, words a critic judges
|
||||
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)]
|
||||
@@ -74,6 +77,8 @@ pub struct Goal {
|
||||
pub rounds: Option<u32>,
|
||||
/// a cut job's contract: the brief as rules (cut.rs)
|
||||
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
|
||||
/// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
|
||||
#[serde(default)]
|
||||
@@ -227,7 +232,7 @@ impl Kind {
|
||||
/// as brief.ts writes it, and as raea judge's rubrics are named
|
||||
pub fn name(self) -> &'static str {
|
||||
// in the enum's order
|
||||
["scene", "kit", "shot", "cut", "rules"][self as usize]
|
||||
["scene", "kit", "shot", "cut", "rules", "playable"][self as usize]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,6 +244,7 @@ pub fn dials(kind: Kind) -> &'static [&'static str] {
|
||||
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
|
||||
Kind::Cut => &["look"],
|
||||
Kind::Rules => &[],
|
||||
Kind::Playable => &["look"],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +282,7 @@ fn by_kind(m: &Goal) -> Vec<String> {
|
||||
Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(),
|
||||
// only its `file` rules, added above
|
||||
Kind::Rules => vec![],
|
||||
Kind::Playable => m.playable.as_ref().map(crate::playable::deliverables).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,6 +314,12 @@ 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({{...}})`")),
|
||||
_ => {}
|
||||
}
|
||||
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));
|
||||
if m.kind == Kind::Rules {
|
||||
if m.aim.as_deref().is_none_or(|a| a.trim().is_empty()) {
|
||||
|
||||
+21
-3
@@ -7,6 +7,7 @@ pub mod brief;
|
||||
pub mod cut;
|
||||
pub mod goal;
|
||||
pub mod parts;
|
||||
pub mod playable;
|
||||
pub mod rules;
|
||||
pub mod script;
|
||||
pub mod taste;
|
||||
@@ -30,18 +31,35 @@ macro_rules! decls {
|
||||
($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] };
|
||||
}
|
||||
|
||||
/// The TypeScript declarations of every schema, one file's worth: sdk/raea/src/brief.gen.ts is this, checked by a test, and
|
||||
/// `raea/brief` (sdk/raea/src/brief.ts) types its builders with it, so the declarations ship with the SDK.
|
||||
/// The file the goal's declarations are written to, beside brief.gen.ts (which re-exports them)
|
||||
pub const GOAL_FILE: &str = "brief-goal.gen";
|
||||
|
||||
/// 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 {
|
||||
let cfg = Config::new();
|
||||
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.".to_string()];
|
||||
let mut out = vec![format!(
|
||||
"// 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;
|
||||
brief::Brief, brief::Section, brief::Deliverable, brief::Reference, brief::Agent,
|
||||
script::Script, script::Scene, script::Beat, script::Line,
|
||||
taste::Taste, taste::TasteSection, taste::Rule, taste::RuleCheck, taste::RuleLevel, taste::Check,
|
||||
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,
|
||||
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
|
||||
playable::Playable, playable::Orientation,
|
||||
rules::Rule,
|
||||
));
|
||||
out.join("\n\n") + "\n"
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//! 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
|
||||
}
|
||||
+45
-7
@@ -1,14 +1,18 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn declarations_match_the_committed_file() {
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/brief.gen.ts");
|
||||
let now = declarations();
|
||||
if std::env::var_os("RAEA_WRITE").is_some() {
|
||||
std::fs::write(path, &now).unwrap();
|
||||
fn declarations_match_the_committed_files() {
|
||||
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src");
|
||||
for (file, now) in [("brief.gen.ts".to_string(), declarations()), (format!("{GOAL_FILE}.ts"), goal_declarations())] {
|
||||
let path = format!("{dir}/{file}");
|
||||
if std::env::var_os("RAEA_WRITE").is_some() {
|
||||
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]
|
||||
@@ -153,3 +157,37 @@ 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();
|
||||
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`"))
|
||||
);
|
||||
}
|
||||
@@ -99,3 +99,27 @@ Feature: raea cloud: a synced folder is pictured, understood, embedded and organ
|
||||
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
|
||||
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
|
||||
@@ -353,3 +353,14 @@ 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
|
||||
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.
|
||||
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.
|
||||
@@ -28,7 +28,7 @@ project (`raea add [email protected]`).
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
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)
|
||||
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)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
|
||||
@@ -130,14 +130,35 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
|
||||
Rule: Next
|
||||
|
||||
@done
|
||||
Scenario: PA6. Sound in a playable
|
||||
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
|
||||
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
|
||||
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
|
||||
# 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
|
||||
Scenario: PA9. The playable is held to the native render
|
||||
@@ -184,10 +205,21 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
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
|
||||
|
||||
@done
|
||||
Scenario: PA12. Bevy systems in a playable
|
||||
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
|
||||
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
|
||||
Scenario: PA13. `raea playable`
|
||||
@@ -209,9 +241,16 @@ 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
|
||||
SKILL.md routes "a playable ad" to it
|
||||
|
||||
@done
|
||||
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
|
||||
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); three.ts draws it with
|
||||
# three.js, 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)
|
||||
Given the review's own player (raea-platform board-simple review.js PLAYER_DRAWS) is the one view of a shown file
|
||||
@@ -241,4 +280,31 @@ 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
|
||||
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
|
||||
# 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.
|
||||
|
||||
+22
-6
@@ -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
|
||||
fingerprint is.
|
||||
2. Each part flows into the part of raea that does that job already: its ranges into its profile (FP6e), its rules
|
||||
into a controller's rule fields (DR4, DR8), its structure into a NAME.script.ts template, its references into
|
||||
brief.ts's `references` shape.
|
||||
into the section's `rules`, each in a taste line's shape (words, a check, its values, a level; DR4, DR8), its
|
||||
structure into a NAME.script.ts template, its references into 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,
|
||||
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
|
||||
@@ -23,13 +23,26 @@ 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
|
||||
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:
|
||||
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,
|
||||
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
|
||||
measure name, critique, leave-one-out), `which` (FP14c) and evidence rows (FP2c)
|
||||
And controllers' `rule` fields and raea/check's `.ts` checks over the world (DR4), run by `raea check PROJECT`
|
||||
And taste lines' checks (raea's six forms, a check by name, a `.ts` check written with raea/check over the world;
|
||||
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
|
||||
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
|
||||
@@ -149,12 +162,15 @@ 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`
|
||||
|
||||
@needs:VF6,VF7
|
||||
Scenario: VF8. Rules, with their strength, into a controller
|
||||
Scenario: VF8. Rules, with their strength, in the videoform's rules
|
||||
Given the plan
|
||||
| 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 as rule fields of the controller `videoform.rules` names |
|
||||
| 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-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
|
||||
kitchen) is a rule field with its strength and its check
|
||||
kitchen) is a line in the section's `rules`, 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
|
||||
evidence in the videoform
|
||||
|
||||
|
||||
+7
-8
@@ -49,11 +49,10 @@ 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'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) |
|
||||
| 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 |
|
||||
| `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 |
|
||||
| `taste.ts`, six checked forms | the person's standing lines | the forms are fixed: mined rules go to controllers, not here |
|
||||
| `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 |
|
||||
| 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 |
|
||||
| Index and libraries (SigLIP over a person's media; turbopuffer in the cloud) | finding footage by meaning; vector storage for teams | — |
|
||||
@@ -83,7 +82,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 |
|
||||
| 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) | a controller's `rule` fields, which `videoform.rules` names | `raea check PROJECT` runs them, and they're edited in the app like any controller |
|
||||
| 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 |
|
||||
| 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 |
|
||||
|
||||
@@ -161,7 +160,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 |
|
||||
| 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 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 |
|
||||
| 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 |
|
||||
|
||||
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.
|
||||
@@ -226,8 +225,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
|
||||
template.
|
||||
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 controller rules,
|
||||
each stating how strongly it holds.
|
||||
said", "a close-up of the counters in every kitchen"). Those that hold in most references become the videoform's
|
||||
rules, 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
|
||||
10"). Each yes or no is evidence in the videoform, as any label is in a fingerprint.
|
||||
|
||||
@@ -247,7 +246,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);
|
||||
- caption places and sizes.
|
||||
|
||||
These are the controller rules, run by `raea check PROJECT` as today.
|
||||
These are the videoform's rules, run by `raea check PROJECT` with the taste.
|
||||
2. **On the render manifest and measures, in seconds:** loudness, light and colour against the profile (`raea
|
||||
fingerprint score --profile`).
|
||||
3. **On embeddings, only for shots that changed:** each shot against its slot's shot kind (one SigLIP frame a shot);
|
||||
@@ -298,7 +297,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 |
|
||||
| | 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 |
|
||||
| | VF8 | event rules into controller rules, with strength, confirmed by the person | medium | co-occurrence is plain; telling habit from style needs the person |
|
||||
| | 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 |
|
||||
| | 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) |
|
||||
| 3, use | VF9 | following: context, coverage gaps, planning to the template | medium-high | context and scripts exist |
|
||||
|
||||
@@ -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
|
||||
// (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.
|
||||
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
|
||||
import { AbsoluteFill, Audio, Composition, Sequence, registerRoot, sao, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
|
||||
import { Sphere } from "raea/3d";
|
||||
import { LinearRgba, Srgba } from "raea/color";
|
||||
import { StandardMaterial } from "raea/pbr";
|
||||
@@ -12,6 +12,7 @@ import { AmbientLight, DirectionalLight } from "raea/light";
|
||||
import { Transform } from "raea/transform";
|
||||
import { Camera3d } from "raea/camera";
|
||||
import { EndCard } from "raea/playable";
|
||||
import { Sfx, Synth } from "raea/tone";
|
||||
|
||||
const FPS = 30;
|
||||
const COLS = 6, ROWS = 4, LIVES = 3;
|
||||
@@ -21,6 +22,12 @@ 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" }
|
||||
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];
|
||||
|
||||
/** The camera's distance that fits the whole field on a screen of this aspect */
|
||||
@@ -102,6 +109,15 @@ function BrickRush() {
|
||||
{`👆 Drag to play`}
|
||||
</div>
|
||||
) : 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"} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// 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} />
|
||||
</>
|
||||
));
|
||||
@@ -20,6 +20,9 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
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.
|
||||
struct BWorld {
|
||||
w: World,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! 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
|
||||
})
|
||||
}
|
||||
@@ -87,8 +87,10 @@ impl LiveScene {
|
||||
let mut want: [(&str, Option<f64>); WANT] = [("", None); WANT];
|
||||
let mut nw = 0usize;
|
||||
let mut put = |k: &'static str, v: f64| {
|
||||
// a Transform's columns as the World's f32 holds them (FC1d), the rest to 6 decimals
|
||||
want[nw] = (k, Some(if PLACE.contains(&k) || k.starts_with("col_") { v } else { r6(v) }));
|
||||
// a Transform's columns as the World's f32 holds them (FC1d), and a light's own rotation exact as parts.rs
|
||||
// writes it (rot_q*: rounded here, a still sun was sent again on the first fast frame, PA18); the rest
|
||||
// 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;
|
||||
};
|
||||
let mut color: Option<std::borrow::Cow<str>> = None;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! 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]))
|
||||
);
|
||||
}
|
||||
+43
-28
@@ -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
|
||||
// plain bun the tables are TypeScript's own, with the same behaviour, so tests run anywhere.
|
||||
|
||||
import { hasNative, native } from "./native";
|
||||
import { ecsCall, hasEcs } from "./native";
|
||||
|
||||
export type Value = number | string | boolean;
|
||||
export type Cols = Record<string, Value>;
|
||||
@@ -52,76 +52,83 @@ interface Store {
|
||||
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 {
|
||||
constructor(readonly world: number) {}
|
||||
constructor(readonly world: number) {
|
||||
unheld?.register(this, world, this);
|
||||
}
|
||||
static create(): NativeStore {
|
||||
return new NativeStore(native("ecs.new", {}).world);
|
||||
return new NativeStore(ecsCall("ecs.new", {}).world);
|
||||
}
|
||||
spawn(kind: string, cols: Cols) {
|
||||
return native("ecs.spawn", { world: this.world, kind, cols }).id;
|
||||
return ecsCall("ecs.spawn", { world: this.world, kind, cols }).id;
|
||||
}
|
||||
spawnComponents(components: Components, parent?: number) {
|
||||
return native("ecs.spawn", parent === undefined ? { world: this.world, components } : { world: this.world, components, parent }).id;
|
||||
return ecsCall("ecs.spawn", parent === undefined ? { world: this.world, components } : { world: this.world, components, parent }).id;
|
||||
}
|
||||
insert(id: number, components: Components) {
|
||||
native("ecs.insert", { world: this.world, id, components });
|
||||
ecsCall("ecs.insert", { world: this.world, id, components });
|
||||
}
|
||||
remove(id: number, names: string[]) {
|
||||
native("ecs.remove", { world: this.world, id, names });
|
||||
ecsCall("ecs.remove", { world: this.world, id, names });
|
||||
}
|
||||
components(id: number) {
|
||||
return native("ecs.components", { world: this.world, id }) as Components;
|
||||
return ecsCall("ecs.components", { world: this.world, id }) as Components;
|
||||
}
|
||||
find(f: Find) {
|
||||
return native("ecs.find", { world: this.world, with: f.with ?? [], without: f.without ?? [], where: f.where ?? [] }).ids;
|
||||
return ecsCall("ecs.find", { world: this.world, with: f.with ?? [], without: f.without ?? [], where: f.where ?? [] }).ids;
|
||||
}
|
||||
setParent(id: number, parent: number | null) {
|
||||
native("ecs.parent", { world: this.world, id, parent });
|
||||
ecsCall("ecs.parent", { world: this.world, id, parent });
|
||||
}
|
||||
parent(id: number) {
|
||||
return native("ecs.parent", { world: this.world, id }) as number | null;
|
||||
return ecsCall("ecs.parent", { world: this.world, id }) as number | null;
|
||||
}
|
||||
children(id: number) {
|
||||
return native("ecs.children", { world: this.world, id });
|
||||
return ecsCall("ecs.children", { world: this.world, id });
|
||||
}
|
||||
resource(name: string, value?: unknown) {
|
||||
return native("ecs.resource", value === undefined ? { world: this.world, name } : { world: this.world, name, value });
|
||||
return ecsCall("ecs.resource", value === undefined ? { world: this.world, name } : { world: this.world, name, value });
|
||||
}
|
||||
send(name: string, value: unknown) {
|
||||
native("ecs.send", { world: this.world, name, value });
|
||||
ecsCall("ecs.send", { world: this.world, name, value });
|
||||
}
|
||||
events(name: string) {
|
||||
return native("ecs.events", { world: this.world, name });
|
||||
return ecsCall("ecs.events", { world: this.world, name });
|
||||
}
|
||||
clearEvents() {
|
||||
native("ecs.clear_events", { world: this.world });
|
||||
ecsCall("ecs.clear_events", { world: this.world });
|
||||
}
|
||||
set(id: number, cols: Cols) {
|
||||
native("ecs.set", { world: this.world, id, cols });
|
||||
ecsCall("ecs.set", { world: this.world, id, cols });
|
||||
}
|
||||
get(id: number) {
|
||||
return native("ecs.get", { world: this.world, id });
|
||||
return ecsCall("ecs.get", { world: this.world, id });
|
||||
}
|
||||
despawn(id: number) {
|
||||
native("ecs.despawn", { world: this.world, id });
|
||||
ecsCall("ecs.despawn", { world: this.world, id });
|
||||
}
|
||||
query(kind: string, where: Where) {
|
||||
return native("ecs.query", { world: this.world, kind, where }).ids;
|
||||
return ecsCall("ecs.query", { world: this.world, kind, where }).ids;
|
||||
}
|
||||
column(kind: string, col: string) {
|
||||
return native("ecs.column", { world: this.world, kind, col });
|
||||
return ecsCall("ecs.column", { world: this.world, kind, col });
|
||||
}
|
||||
count(kind: string) {
|
||||
return native("ecs.count", { world: this.world, kind });
|
||||
return ecsCall("ecs.count", { world: this.world, kind });
|
||||
}
|
||||
rows() {
|
||||
return native("ecs.rows", { world: this.world });
|
||||
return ecsCall("ecs.rows", { world: this.world });
|
||||
}
|
||||
clone() {
|
||||
return new NativeStore(native("ecs.clone", { world: this.world }).world);
|
||||
return new NativeStore(ecsCall("ecs.clone", { world: this.world }).world);
|
||||
}
|
||||
free() {
|
||||
native("ecs.free", { world: this.world });
|
||||
unheld?.unregister(this);
|
||||
ecsCall("ecs.free", { world: this.world });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,7 +283,9 @@ export class World {
|
||||
|
||||
/** A world on `store`: the engine's tables when it has them, else TypeScript's (createWorld picks for you). */
|
||||
constructor(store?: Store) {
|
||||
this.native = store ? store instanceof NativeStore : hasNative();
|
||||
this.native = store ? store instanceof NativeStore : hasEcs();
|
||||
// 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());
|
||||
}
|
||||
|
||||
@@ -367,7 +376,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),
|
||||
* the same list as runtime/calls ecs.scene makes. */
|
||||
scene(): unknown[] {
|
||||
if (this.store instanceof NativeStore) return native("ecs.scene", { world: this.store.world });
|
||||
if (this.store instanceof NativeStore) return ecsCall("ecs.scene", { world: this.store.world });
|
||||
const store = this.store;
|
||||
const out: unknown[] = [];
|
||||
for (const id of store.find({ with: ["Mesh"] })) {
|
||||
@@ -394,6 +403,12 @@ export class World {
|
||||
this.store.clearEvents();
|
||||
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). */
|
||||
at(frame: number): World {
|
||||
if (!Number.isInteger(frame) || frame < 0) throw new RangeError(`World.at: a frame number from 0, got ${frame}`);
|
||||
@@ -442,7 +457,7 @@ function compose(p: number[], c: number[]): number[] {
|
||||
|
||||
export function createWorld(opts: { native?: boolean } = {}): World {
|
||||
if (opts.native === false) return new World(new JsStore());
|
||||
if (opts.native === true && !hasNative()) throw new Error("createWorld({ native: true }) needs the raea engine");
|
||||
if (opts.native === true && !hasEcs()) throw new Error("createWorld({ native: true }) needs the raea engine");
|
||||
return new World();
|
||||
}
|
||||
|
||||
|
||||
+17
-1
@@ -20,12 +20,28 @@ export function hasNative(): boolean {
|
||||
|
||||
/** 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"] {
|
||||
const call = bridge();
|
||||
return through(bridge(), name, args);
|
||||
}
|
||||
|
||||
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`);
|
||||
const out = call(name, JSON.stringify(args));
|
||||
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). */
|
||||
export function print(...parts: unknown[]): void {
|
||||
const text = parts.map((p) => (typeof p === "string" ? p : JSON.stringify(p))).join(" ");
|
||||
|
||||
@@ -38,14 +38,20 @@ function describe(kind: AssetKind, prompt: string, seconds: number): GeneratedAs
|
||||
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. */
|
||||
export function lyria(prompt: string, options: { seconds?: number } = {}): GeneratedAsset {
|
||||
return describe("lyria", prompt, options.seconds ?? 30);
|
||||
return described(describe("lyria", prompt, options.seconds ?? 30));
|
||||
}
|
||||
|
||||
/** A sound effect to generate (2 seconds by default). */
|
||||
export function sao(prompt: string, options: { seconds?: number } = {}): GeneratedAsset {
|
||||
return describe("sao", prompt, options.seconds ?? 2);
|
||||
return described(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
|
||||
@@ -63,7 +69,7 @@ export function tokensynthNote(timbre: string, midi: number, options: { seconds?
|
||||
// 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 key = `${a.id}:${midi}:${o.velocity}:${o.seed}:${o.precision}`;
|
||||
return { ...a, id: key, src: `asset:tokensynth/${key}`, options: o };
|
||||
return described({ ...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. */
|
||||
|
||||
+144
-51
@@ -32,6 +32,7 @@ import re
|
||||
import resource
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
@@ -81,8 +82,10 @@ GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit;
|
||||
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
|
||||
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "8"))
|
||||
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "40"))
|
||||
# 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"
|
||||
JOBS = f"{ROOT}/jobs"
|
||||
|
||||
@@ -90,7 +93,7 @@ image = (
|
||||
modal.Image.from_registry("debian:trixie-slim", add_python="3.12")
|
||||
.apt_install(
|
||||
"ca-certificates", "curl", "xz-utils", "zstd", "procps", "ffmpeg",
|
||||
"libasound2t64", "libfontconfig1", "libvulkan1", "mesa-vulkan-drivers", "vulkan-tools",
|
||||
"libasound2t64", "libfontconfig1", "fonts-noto-color-emoji", "libvulkan1", "mesa-vulkan-drivers", "vulkan-tools",
|
||||
"libxext6", "libx11-6", "libgl1", "libegl1",
|
||||
"libxi6", "libxxf86vm1", "libxfixes3", "libxrender1", "libxkbcommon0", "libsm6", "libice6",
|
||||
)
|
||||
@@ -155,8 +158,15 @@ 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)
|
||||
# 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"))
|
||||
# /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
|
||||
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)
|
||||
CPU_ENV = {"VK_DRIVER_FILES": "/usr/share/vulkan/icd.d/lvp_icd.json", "__EGL_VENDOR_LIBRARY_DIRS": "/nonexistent"}
|
||||
|
||||
@@ -168,6 +178,8 @@ CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}
|
||||
|
||||
# the scene reader's models, loaded once a container (/v1/scene)
|
||||
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)
|
||||
BOOTED = time.time()
|
||||
@@ -199,16 +211,21 @@ def run(cmd, cwd=None, env=None, timeout=6 * 3600):
|
||||
|
||||
|
||||
def snapshot(d):
|
||||
out = {}
|
||||
for base, _, files in os.walk(d):
|
||||
for f in files:
|
||||
p = os.path.join(base, f)
|
||||
try:
|
||||
s = os.stat(p)
|
||||
except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's
|
||||
continue
|
||||
out[os.path.relpath(p, d)] = f"{s.st_size}:{s.st_mtime_ns}"
|
||||
return out
|
||||
# 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
|
||||
# every job, drawn or not (12-01). Asked 32 at once
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
paths = [os.path.join(base, f) for base, _, files in os.walk(d) for f in files]
|
||||
|
||||
def one(p):
|
||||
try:
|
||||
s = os.stat(p)
|
||||
except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's
|
||||
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:
|
||||
@@ -228,6 +245,10 @@ 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
|
||||
# about five times their GPUs' working seconds
|
||||
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):
|
||||
@@ -291,7 +312,7 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
|
||||
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=SCALEDOWN)
|
||||
@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."""
|
||||
@@ -408,7 +429,9 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
|
||||
log = Log(id)
|
||||
log(f"raea farm: raea {' '.join(args)}")
|
||||
t_start = [time.time()]
|
||||
vol.reload()
|
||||
t_start.append(time.time())
|
||||
work = f"{JOBS}/{id}/work"
|
||||
try:
|
||||
farm_media.fetch(work, f"{ROOT}/blobs", log)
|
||||
@@ -420,8 +443,15 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
return
|
||||
# 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)
|
||||
t_start.append(time.time())
|
||||
vol.commit()
|
||||
t_start.append(time.time())
|
||||
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:
|
||||
# a video's frames' keys (farm_keys.py): its runs kept by them under the raea that drew them (a release's
|
||||
# version and the build's own file, so a new engine starts a store of its own; kept=0 draws every frame), and
|
||||
@@ -434,7 +464,9 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
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)
|
||||
code = 1
|
||||
t_end = [time.time()]
|
||||
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
|
||||
# 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,
|
||||
@@ -448,7 +480,9 @@ 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)
|
||||
else:
|
||||
time.sleep(pause)
|
||||
t_end.append(time.time())
|
||||
after = snapshot(work)
|
||||
t_end.append(time.time())
|
||||
changed = [p for p, v in after.items() if before.get(p) != v]
|
||||
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
|
||||
@@ -460,11 +494,67 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
with open(f"{JOBS}/{id}/changed.txt", "w") as f:
|
||||
f.write("".join(p + "\n" for p in changed))
|
||||
shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True)
|
||||
t_end.append(time.time())
|
||||
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)
|
||||
|
||||
|
||||
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600)
|
||||
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
|
||||
|
||||
|
||||
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.asgi_app()
|
||||
def api():
|
||||
@@ -544,23 +634,10 @@ 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": []}
|
||||
|
||||
# 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 Whisper large-v3 on OpenRouter that raea
|
||||
# cloud's library index uses (apps/app host/library/words.ts) hears it here. The body is one MP3 piece (16 kHz mono,
|
||||
# transcriber of its own (raea's is parakeet-mlx, Mac only), so the same model on a GPU hears it here (raea-words),
|
||||
# Whisper large-v3 on OpenRouter when that can't. 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
|
||||
# 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")
|
||||
async def scene(req: Request):
|
||||
@@ -569,11 +646,6 @@ def api():
|
||||
(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
|
||||
[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)
|
||||
body = await req.json()
|
||||
frames = body.get("frames") if isinstance(body, dict) else None
|
||||
@@ -581,18 +653,11 @@ def api():
|
||||
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
|
||||
if len(frames) > 400:
|
||||
raise HTTPException(413, "at most 400 frames a call")
|
||||
global SCENE
|
||||
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)
|
||||
if len(frames) <= SCENE_HERE:
|
||||
out = await asyncio.to_thread(read_scenes, frames)
|
||||
else:
|
||||
parts = [frames[i:i + SCENE_PART] for i in range(0, len(frames), SCENE_PART)]
|
||||
out = [r async for part in scene_run.map.aio(parts) for r in part]
|
||||
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
|
||||
|
||||
@web.post("/v1/words")
|
||||
@@ -604,8 +669,9 @@ def api():
|
||||
|
||||
check(req)
|
||||
key = os.environ.get("OPENROUTER_API_KEY", "")
|
||||
if not key:
|
||||
raise HTTPException(503, "the farm has no OpenRouter key for words (Modal secret raea-farm-words)")
|
||||
groq = os.environ.get("GROQ_API_KEY", "")
|
||||
if not key and not groq:
|
||||
raise HTTPException(503, "the farm has no Whisper key for words (Modal secrets raea-farm-groq, raea-farm-words)")
|
||||
mp3 = await req.body()
|
||||
if not mp3:
|
||||
raise HTTPException(400, "the body is the sound: an MP3, 16 kHz mono, at most 10 minutes")
|
||||
@@ -615,7 +681,26 @@ def api():
|
||||
if req.query_params.get("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():
|
||||
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"})
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=300) as f:
|
||||
@@ -623,11 +708,19 @@ def api():
|
||||
except urllib.error.HTTPError as e:
|
||||
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)
|
||||
if code != 200:
|
||||
raise HTTPException(502, f"OpenRouter's Whisper said {code}: {got.get('error', '')}")
|
||||
raise HTTPException(502, f"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()]
|
||||
return {"model": "openai/whisper-large-v3", "duration": got.get("duration"), "text": got.get("text", ""), "words": ws}
|
||||
return {"model": got.get("_model", "openai/whisper-large-v3"), "duration": got.get("duration"), "text": got.get("text", ""), "words": ws}
|
||||
|
||||
@web.post("/v1/jobs")
|
||||
async def start(req: Request):
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
# 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}
|
||||
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
# 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}
|
||||
@@ -0,0 +1,62 @@
|
||||
# Each heard word's edges moved onto its sound (12-03): a transcriber's word times are its frames' (Parakeet's 80 ms,
|
||||
# Whisper's guesses), so a cut put on a word's end can land on its tail. StreetTalk's Elfster cuts said "really goo-",
|
||||
# "ever sin-": each out point came from words.json. Here a word ends where its sound falls into a gap and starts where it
|
||||
# comes out of one, read every 10 ms, with the same gap the sound check holds edit points to (sdk/goal packs/sound.ts:
|
||||
# 18 dB under the speech, or in a street's noise within 6 dB of its quietest, never closer than 8 dB to the speech).
|
||||
# A word with no gap near it (said straight into the next) keeps the transcriber's time.
|
||||
import numpy as np
|
||||
|
||||
FRAME = 0.01 # s
|
||||
SPEECH_Q = 90
|
||||
FLOOR_Q = 10
|
||||
GAP = 18.0
|
||||
GAP_FLOOR = 6.0
|
||||
GAP_LEAST = 8.0
|
||||
QUIET = 3 # frames under the gap that make a gap: 30 ms
|
||||
LOOK = 0.25 # s a word's end may move later, its start earlier, at most
|
||||
|
||||
|
||||
def levels(x: np.ndarray, rate: int) -> np.ndarray:
|
||||
"""dB of each 10 ms of mono samples in [-1, 1]"""
|
||||
n = int(rate * FRAME)
|
||||
k = len(x) // n
|
||||
if not k:
|
||||
return np.zeros(0)
|
||||
fr = x[: k * n].reshape(k, n).astype(np.float64)
|
||||
return 20 * np.log10(np.sqrt((fr**2).mean(1)) + 1e-9)
|
||||
|
||||
|
||||
def gap_level(db: np.ndarray) -> float:
|
||||
"""the level under which sound is a gap between words"""
|
||||
speech = float(np.percentile(db, SPEECH_Q))
|
||||
floor = float(np.percentile(db, FLOOR_Q))
|
||||
return min(speech - GAP_LEAST, max(speech - GAP, floor + GAP_FLOOR))
|
||||
|
||||
|
||||
def edges(words: list[dict], db: np.ndarray, gap: float | None = None) -> list[dict]:
|
||||
"""words [{text, start, end}] (s), each widened onto the gaps around its sound: its end moved later to where its sound
|
||||
has fallen into a gap, its start earlier to where it came out of one. Never narrowed: a word's quiet edges (an
|
||||
"f", an "s", a breath) sit under the speech's level but are heard, so a cut is never put inside what the
|
||||
transcriber called the word. Not past the words beside it, nor more than LOOK."""
|
||||
if not len(db) or not words:
|
||||
return words
|
||||
g = gap_level(db) if gap is None else gap
|
||||
loud = db >= g
|
||||
n = len(db)
|
||||
at = lambda t: min(n, max(0, int(round(t / FRAME))))
|
||||
quiet = lambda f: f + QUIET <= n and not loud[f : f + QUIET].any()
|
||||
out = [dict(w) for w in words]
|
||||
for i, w in enumerate(out):
|
||||
prev_end = out[i - 1]["end"] if i else 0.0
|
||||
next_start = words[i + 1]["start"] if i + 1 < len(words) else n * FRAME
|
||||
# the end: the first gap at or after the heard end
|
||||
for f in range(at(w["end"]), at(min(w["end"] + LOOK, max(next_start, w["end"]))) + 1):
|
||||
if quiet(f):
|
||||
w["end"] = round(max(f * FRAME, w["end"]), 3)
|
||||
break
|
||||
# the start: the last gap that ends at or before the heard start
|
||||
for f in range(at(w["start"]), at(max(w["start"] - LOOK, prev_end)) - 1, -1):
|
||||
if f - QUIET >= 0 and not loud[f - QUIET : f].any():
|
||||
w["start"] = round(min(f * FRAME, w["start"]), 3)
|
||||
break
|
||||
return out
|
||||
@@ -21,6 +21,12 @@ say packages
|
||||
sudo -E apt-get update -qq
|
||||
sudo -E apt-get install -y -qq --no-install-recommends ca-certificates curl git git-lfs zstd xz-utils procps ripgrep \
|
||||
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools > /dev/null
|
||||
# what every agent reached for and installed itself at each project's start (12-02: `which ffmpeg`, a search of the
|
||||
# disk, then apt, minutes in all): ffmpeg and ffprobe (the montage check reads frames with them too) and the PDF tools a
|
||||
# brief or brand guide is read with
|
||||
for f in ffmpeg poppler-utils; do
|
||||
dpkg -s "$f" > /dev/null 2>&1 || sudo -E apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || say "no $f here"
|
||||
done
|
||||
# faces an ad is set in (12-01: a box had Liberation and DejaVu alone, so every cut fell back to Liberation Sans): the
|
||||
# open families brands are closest to, each taken when this Ubuntu has it
|
||||
for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do
|
||||
|
||||
+57
-12
@@ -34,7 +34,8 @@
|
||||
// Every route but /healthz needs RAEA_CLOUD_TOKEN: `Authorization: Bearer TOKEN`, or ?token= (a browser's WebSocket
|
||||
// can't set headers). The agent and raea get the container's environment without the token or the state keys.
|
||||
|
||||
import { execFileSync, spawn } from "node:child_process"
|
||||
import { claudeStopHook, jobsOf, markedEnd, sessionIn, watchEnd, watchTurnEnd } from "./turn-end.ts"
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { timingSafeEqual } from "node:crypto"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
|
||||
@@ -143,14 +144,16 @@ const withoutKeys = (env: NodeJS.ProcessEnv) => {
|
||||
for (const k of [...AGENT_KEYS, "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS"]) delete out[k]
|
||||
return out
|
||||
}
|
||||
const raeaVersion = () => {
|
||||
try {
|
||||
version ??= execFileSync(RAEA, ["--version"], { encoding: "utf8", timeout: 20_000, env: childEnv() }).trim()
|
||||
} catch {
|
||||
version = "unknown"
|
||||
}
|
||||
return version
|
||||
}
|
||||
/** raea's version, asked once as the server starts and never on a request: asked synchronously, on a Sprite whose
|
||||
* disk was cold it held every request (health included) for 6 s, and up to its 20 s timeout after the restarts on
|
||||
* 12-02, which also left it "unknown" for good. "reading" until it answers */
|
||||
const raeaVersion = () => version ?? "reading"
|
||||
const versionKnown = new Promise<void>((resolve) =>
|
||||
execFile(RAEA, ["--version"], { encoding: "utf8", timeout: 120_000, env: childEnv() }, (e, out) => {
|
||||
version = e ? "unknown" : out.trim()
|
||||
resolve()
|
||||
}),
|
||||
)
|
||||
|
||||
function authorized(req: IncomingMessage, url: URL): boolean {
|
||||
const given = /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1] ?? url.searchParams.get("token") ?? ""
|
||||
@@ -251,6 +254,8 @@ const server = createServer(async (req, res) => {
|
||||
if (!authorized(req, url)) return json(res, { error: "unauthorized" }, 401)
|
||||
try {
|
||||
if (url.pathname === "/v1/health" && req.method === "GET") {
|
||||
// a moment for raea's version on a fresh start, without holding anything else up
|
||||
if (version === undefined) await Promise.race([versionKnown, new Promise((r) => setTimeout(r, 3000))])
|
||||
const def = (() => {
|
||||
try {
|
||||
return spawnFor().id
|
||||
@@ -332,6 +337,8 @@ const server = createServer(async (req, res) => {
|
||||
|
||||
// the WebSocket upgrade checks the token before a socket opens
|
||||
const wss = new WebSocketServer({ noServer: true })
|
||||
/** how many open agents share each Claude Stop hook file (turn-end.ts) */
|
||||
const stopMarks = new Map<string, number>()
|
||||
const agentSockets = new Set<import("ws").WebSocket>()
|
||||
server.on("upgrade", (req, socket, head) => {
|
||||
const url = new URL(req.url ?? "/", "http://raea-cloud")
|
||||
@@ -410,9 +417,46 @@ server.on("upgrade", (req, socket, head) => {
|
||||
child.stdout.setEncoding("utf8").on("data", (c: string) => {
|
||||
heard = Date.now()
|
||||
buf += c
|
||||
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) if (i > 0) ws.send(buf.slice(0, i))
|
||||
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) {
|
||||
if (i <= 0) continue
|
||||
const line = buf.slice(0, i)
|
||||
if (!acpSession || !line.includes(acpSession)) acpSession = sessionIn(line) ?? acpSession
|
||||
ws.send(line)
|
||||
}
|
||||
})
|
||||
ws.on("message", (m) => ((heard = Date.now()), child.stdin.write(m.toString() + "\n")))
|
||||
let heardFromCaller = Date.now()
|
||||
// the ACP session this socket is on, read off its own messages: whose transcript is this turn's (turn-end.ts)
|
||||
let acpSession: string | null = null
|
||||
ws.on("message", (m) => {
|
||||
heard = heardFromCaller = Date.now()
|
||||
const line = m.toString()
|
||||
if (!acpSession || !line.includes(acpSession)) acpSession = sessionIn(line) ?? acpSession
|
||||
child.stdin.write(line + "\n")
|
||||
})
|
||||
// the turn's end from the agent's own transcript, said along the socket (turn-end.ts): raea cloud closes the turn
|
||||
// on it without waiting for an answer to session/prompt that may not come
|
||||
{
|
||||
const tellEnd = (by: string) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/turn_end", params: { by } }))
|
||||
const busy = () => !!child.pid && jobsOf(child.pid, path.dirname(agent.command), WORK).length > 0
|
||||
let stopWatch: (() => void) | undefined
|
||||
if (agent.id === "antigravity-acp" && env.GEMINI_HOME) stopWatch = watchTurnEnd(env.GEMINI_HOME, () => acpSession, () => heardFromCaller, tellEnd, busy)
|
||||
else if (agent.id === "claude-acp" && own && env.CLAUDE_CONFIG_DIR) {
|
||||
// Claude says it itself, through a Stop hook in the socket's own settings (never the box's own home's)
|
||||
try {
|
||||
const mark = claudeStopHook(env.CLAUDE_CONFIG_DIR)
|
||||
// the hook's file is the settings folder's, which every agent on this sign-in shares: while another of
|
||||
// them is open here, a touch of it is either's turn, so nothing is said (the prompt's answer ends the turn)
|
||||
stopMarks.set(mark, (stopMarks.get(mark) ?? 0) + 1)
|
||||
const stop = watchEnd(() => (stopMarks.get(mark) === 1 ? markedEnd(mark) : null), "its Stop hook", () => heardFromCaller, tellEnd, busy)
|
||||
let left = false
|
||||
stopWatch = () => { stop(); if (!left) { left = true; stopMarks.set(mark, (stopMarks.get(mark) ?? 1) - 1) } }
|
||||
} catch {}
|
||||
}
|
||||
if (stopWatch) {
|
||||
ws.on("close", stopWatch)
|
||||
child.on("exit", stopWatch)
|
||||
}
|
||||
}
|
||||
ws.on("close", stopAll)
|
||||
child.on("error", (e) => ws.close(1011, `couldn't start ${agent.id}: ${e.message}`.slice(0, 120)))
|
||||
child.on("exit", (code) => (ws.close(1011, `${agent.id} exited ${code}`), stopAll()))
|
||||
@@ -427,7 +471,8 @@ if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
|
||||
process.stderr.write(line + "\n")
|
||||
for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } }))
|
||||
})
|
||||
server.listen(PORT, () => {
|
||||
server.listen(PORT, async () => {
|
||||
await versionKnown
|
||||
const d = device(childEnv())
|
||||
const gpu = process.env.RAEA_CLOUD_GPU_URL
|
||||
console.log(
|
||||
|
||||
@@ -234,3 +234,22 @@ export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string
|
||||
|
||||
/** tar's exclude-from lines for paths that go by hash: each matched as written (glob characters escaped) */
|
||||
export const excludes = (media: Media[]) => media.map((m) => "./" + m.path.replace(/[\\*?[\]]/g, (c) => "\\" + c)).join("\n") + "\n"
|
||||
|
||||
/** A farm render's manifest with its sound clips named as this machine has them (12-03). Media that went by hash is a
|
||||
* link on the farm to its cache, so the farm's manifest names each take by the cache's file (.../blobs/OID): raea goal
|
||||
* check's sound pack found none of them here and checked no edit point of any farm render, so words cut off at a
|
||||
* clip's end passed every check (StreetTalk's Elfster: "really goo-", "ever sin-"). Each such source becomes the path
|
||||
* the take has in the project; anything else is left as it is. The count of clips renamed. */
|
||||
export function localSources(manifest: { sounds?: { clips?: { src: string }[] } }, media: Pick<Media, "path" | "oid">[], root: string): number {
|
||||
const byOid = new Map(media.map((m) => [m.oid, m.path]))
|
||||
let n = 0
|
||||
for (const c of manifest.sounds?.clips ?? []) {
|
||||
const oid = /(?:^|\/)(?:blobs\/)?([0-9a-f]{64})$/.exec(c.src)?.[1]
|
||||
const p = oid ? byOid.get(oid) : undefined
|
||||
if (p) {
|
||||
c.src = path.join(root, p)
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -21,7 +21,7 @@ import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { RaeaCloud } from "../src/index.ts"
|
||||
import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, outputs } from "./media.ts"
|
||||
import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, localSources, outputs } from "./media.ts"
|
||||
|
||||
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
|
||||
// flags whose value is a path raea writes; the rest of a render's path arguments are read
|
||||
@@ -193,6 +193,15 @@ async function main() {
|
||||
const man = mi >= 0 ? path.resolve(process.cwd(), args[mi + 1] ?? "") : ""
|
||||
const beside = `${made.slice(0, made.length - path.extname(made).length)}.render.json`
|
||||
if (man && man !== beside && existsSync(man)) writeFileSync(beside, readFileSync(man))
|
||||
// its takes named as they are here, not as the farm's cache holds them, so every edit point is checked
|
||||
if (byHash.length && existsSync(beside)) {
|
||||
try {
|
||||
const m = JSON.parse(readFileSync(beside, "utf8"))
|
||||
if (localSources(m, byHash, p.root)) writeFileSync(beside, JSON.stringify(m))
|
||||
} catch (e) {
|
||||
say(`${path.basename(beside)}: ${(e as Error).message}`)
|
||||
}
|
||||
}
|
||||
say(`raea goal check ${path.basename(made)} --at render`)
|
||||
const r = spawnSync(REAL, ["make", "check", made, "--at", "render"], { stdio: "inherit", env: { ...process.env, RAEA_REAL: REAL } })
|
||||
if (r.status === 1) {
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
// A turn's end, read off the agent's own records and said along its socket as a `_raea/turn_end` notification, so raea
|
||||
// cloud closes the turn in seconds whether or not the agent answers its session/prompt (12-01: Gemini wrote its delivery
|
||||
// message and never answered; the run stayed open 45 minutes, until the idle agent was ended here, and was then read
|
||||
// as cut off and started again. Shane: "should not be more than a couple seconds to detect a stall").
|
||||
//
|
||||
// Antigravity keeps a transcript of each session, a JSON line a step. A model step that finished and called no tool is
|
||||
// the end of its turn only when nothing it started still runs: it ends a step the same way to wait on a render it left
|
||||
// in the background (123 of 131 such steps in one run), and is woken when that finishes. So both are read:
|
||||
// the transcript's last line, and the processes that are the agent's own.
|
||||
import { closeSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
|
||||
/** the step a transcript line ends a turn at, and when it was made (ms); null for any other line */
|
||||
export function turnEndOf(line: string): { step: number; at: number } | null {
|
||||
let m: any
|
||||
try {
|
||||
m = JSON.parse(line)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!m || m.type !== "PLANNER_RESPONSE" || m.status !== "DONE" || m.source !== "MODEL") return null
|
||||
if (Array.isArray(m.tool_calls) && m.tool_calls.length) return null
|
||||
const at = Date.parse(m.created_at ?? "")
|
||||
return typeof m.step_index === "number" && Number.isFinite(at) ? { step: m.step_index, at } : null
|
||||
}
|
||||
|
||||
/** a file's last whole line */
|
||||
export function lastLine(file: string, most = 1 << 20): string {
|
||||
const size = statSync(file).size
|
||||
const n = Math.min(size, most)
|
||||
const b = Buffer.alloc(n)
|
||||
const fd = openSync(file, "r")
|
||||
try {
|
||||
readSync(fd, b, 0, n, size - n)
|
||||
} finally {
|
||||
closeSync(fd)
|
||||
}
|
||||
const lines = b.toString("utf8").split("\n").filter(Boolean)
|
||||
return lines.at(-1) ?? ""
|
||||
}
|
||||
|
||||
/** a session's transcript under an Antigravity home (GEMINI_HOME): its folder is named by the ACP session's id */
|
||||
export function transcriptOf(geminiHome: string, session: string): string | null {
|
||||
// an id is a name, never a path
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(session)) return null
|
||||
return path.join(geminiHome, "antigravity-acp", "brain", session, ".system_generated", "logs", "transcript.jsonl")
|
||||
}
|
||||
|
||||
/** the session an ACP message names: a caller's session/prompt or session/load, or the agent's answer to session/new */
|
||||
export function sessionIn(line: string): string | null {
|
||||
// cheap first: most lines (text deltas, tool updates) are the session's own and name it too, which is as good
|
||||
if (!line.includes('"sessionId"')) return null
|
||||
try {
|
||||
const m = JSON.parse(line)
|
||||
const id = m?.params?.sessionId ?? m?.result?.sessionId
|
||||
return typeof id === "string" && id ? id : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** What an agent has running that isn't the agent itself: every process in its session (it's started detached, so
|
||||
* the session is its own), descended from it, or working under `work` (a job started with a session of its own),
|
||||
* but for the agent's own programs (under `agentDir`) and raea cloud's (their command names .raea-cloud). Linux /proc. */
|
||||
export function jobsOf(pid: number, agentDir: string, work: string, proc = "/proc"): number[] {
|
||||
const all: { pid: number; ppid: number; sid: number }[] = []
|
||||
let names: string[] = []
|
||||
try {
|
||||
names = readdirSync(proc)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
for (const n of names) {
|
||||
if (!/^\d+$/.test(n)) continue
|
||||
try {
|
||||
// "pid (comm) state ppid pgrp session ...": comm may hold spaces and brackets, so read from its last ")"
|
||||
const st = readFileSync(path.join(proc, n, "stat"), "utf8")
|
||||
const f = st.slice(st.lastIndexOf(")") + 2).split(" ")
|
||||
all.push({ pid: Number(n), ppid: Number(f[1]), sid: Number(f[3]) })
|
||||
} catch {}
|
||||
}
|
||||
const kids = new Set<number>([pid])
|
||||
for (let grew = true; grew; ) {
|
||||
grew = false
|
||||
for (const p of all) if (!kids.has(p.pid) && kids.has(p.ppid)) (kids.add(p.pid), (grew = true))
|
||||
}
|
||||
const link = (n: number, what: string) => {
|
||||
try {
|
||||
return readlinkSync(path.join(proc, String(n), what))
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
const cmd = (n: number) => {
|
||||
try {
|
||||
return readFileSync(path.join(proc, String(n), "cmdline"), "utf8").replace(/\0/g, " ")
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return all
|
||||
.filter((p) => p.pid !== pid && p.pid !== process.pid)
|
||||
.filter((p) => p.sid === pid || kids.has(p.pid) || (link(p.pid, "cwd") + "/").startsWith(work.replace(/\/?$/, "/")))
|
||||
.filter((p) => !link(p.pid, "exe").startsWith(agentDir) && !cmd(p.pid).includes(".raea-cloud"))
|
||||
.map((p) => p.pid)
|
||||
}
|
||||
|
||||
/** Claude Code's own word that its turn ended: a Stop hook in the agent's settings (CLAUDE_CONFIG_DIR/settings.json)
|
||||
* that touches a file here. Other settings and hooks already there are kept. Returns the file. */
|
||||
export function claudeStopHook(configDir: string): string {
|
||||
const mark = path.join(configDir, ".raea-turn-end")
|
||||
const file = path.join(configDir, "settings.json")
|
||||
let settings: any = {}
|
||||
try {
|
||||
settings = JSON.parse(readFileSync(file, "utf8"))
|
||||
} catch {}
|
||||
if (!settings || typeof settings !== "object" || Array.isArray(settings)) settings = {}
|
||||
const command = `touch '${mark.replace(/'/g, "'\\''")}'`
|
||||
const hooks = (settings.hooks ??= {})
|
||||
const stop: any[] = Array.isArray(hooks.Stop) ? hooks.Stop : (hooks.Stop = [])
|
||||
if (!stop.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h: any) => h?.command === command))) {
|
||||
stop.push({ hooks: [{ type: "command", command }] })
|
||||
writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`)
|
||||
}
|
||||
return mark
|
||||
}
|
||||
|
||||
/** when a Stop hook's file was last touched, as a turn's end; null before the first */
|
||||
export function markedEnd(mark: string): { step: number; at: number } | null {
|
||||
try {
|
||||
const at = statSync(mark).mtimeMs
|
||||
return { step: at, at }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Calls `said` once for each turn's end that `ended` reads (an agent's own record of it) after `told()` (when the
|
||||
* agent was last sent anything: an end from before its newest prompt isn't this turn's), once `busy()` has been
|
||||
* false two looks running. Returns its stop. */
|
||||
export function watchEnd(ended: () => { step: number; at: number } | null, by: string, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
|
||||
let seen = -1
|
||||
let idle = 0
|
||||
const t = setInterval(() => {
|
||||
try {
|
||||
const end = ended()
|
||||
// a second's slack: a transcript's times are whole seconds
|
||||
if (!end || end.step === seen || end.at < told() - 1000 || busy()) return void (idle = 0)
|
||||
if (++idle < 2) return
|
||||
seen = end.step
|
||||
said(`${by}, and nothing of its own running`)
|
||||
} catch {}
|
||||
}, everyMs)
|
||||
t.unref?.()
|
||||
return () => clearInterval(t)
|
||||
}
|
||||
|
||||
/** watchEnd on an Antigravity agent's transcript: the one of `session()`, the ACP session this socket is on. Agents
|
||||
* on one sign-in share a home, so the home's newest transcript is whichever of them wrote last: read that way
|
||||
* (12-01), one chat's last message ended every other turn running beside it with nothing said (12-02: three of ten
|
||||
* chats run two at a time). With no session known yet, nothing is said. */
|
||||
export function watchTurnEnd(geminiHome: string, session: () => string | null, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
|
||||
const ended = () => {
|
||||
const id = session()
|
||||
const file = id ? transcriptOf(geminiHome, id) : null
|
||||
if (!file) return null
|
||||
try {
|
||||
return turnEndOf(lastLine(file))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return watchEnd(ended, "its transcript", told, said, busy, everyMs)
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
// words, say, never and CTA packs hear through this on a box (sdk/goal media.ts).
|
||||
//
|
||||
// raea words FILE [-o OUT.words.json] [--language en]
|
||||
// FILE's sound heard by Whisper large-v3 (the farm's POST /v1/words, the model raea cloud's library index uses)
|
||||
// FILE's sound heard on the farm (POST /v1/words: Parakeet with Qwen3-ForcedAligner's times, Whisper on Groq as its fallback)
|
||||
// into FILE's words.json beside it ([{text, start_ms, end_ms}], what `raea cut`, captions and --words read)
|
||||
//
|
||||
// The sound goes as 16 kHz mono MP3 in 10-minute pieces (`raea media ffmpeg`), to RAEA_CLOUD_GPU_URL with its token.
|
||||
|
||||
+107
-1
@@ -3,13 +3,16 @@
|
||||
// paths read on the worker)
|
||||
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { execSync } from "node:child_process"
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { parseSummary, pick } from "../server/gpu.ts"
|
||||
import { plan, projectRoot } from "../server/offload.ts"
|
||||
import { shellEnv } from "../server/shell-os.ts"
|
||||
import { claudeStopHook, jobsOf, lastLine, markedEnd, sessionIn, transcriptOf, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
|
||||
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
|
||||
import { localSources } from "../server/media.ts"
|
||||
|
||||
const L4 = `Devices:
|
||||
========
|
||||
@@ -107,3 +110,106 @@ console.log("units: ok")
|
||||
console.log("ok google-token")
|
||||
}
|
||||
|
||||
|
||||
{
|
||||
// a turn's end in Antigravity's transcript: a finished model step that called no tool (turn-end.ts)
|
||||
const done = { step_index: 1716, source: "MODEL", type: "PLANNER_RESPONSE", status: "DONE", created_at: "2026-12-02T03:34:18Z", content: "All six cuts are delivered." }
|
||||
assert.deepEqual(turnEndOf(JSON.stringify(done)), { step: 1716, at: Date.parse("2026-12-02T03:34:18Z") })
|
||||
assert.equal(turnEndOf(JSON.stringify({ ...done, tool_calls: [{ name: "run_command" }] })), null)
|
||||
assert.equal(turnEndOf(JSON.stringify({ ...done, status: "RUNNING" })), null)
|
||||
assert.equal(turnEndOf(JSON.stringify({ ...done, type: "RUN_COMMAND" })), null)
|
||||
assert.equal(turnEndOf("not json"), null)
|
||||
const home = mkdtempSync(path.join(os.tmpdir(), "raea-turn-end-"))
|
||||
const logs = path.join(home, "antigravity-acp", "brain", "s1", ".system_generated", "logs")
|
||||
mkdirSync(logs, { recursive: true })
|
||||
const file = path.join(logs, "transcript.jsonl")
|
||||
const now = Date.now()
|
||||
const line = (o: object) => JSON.stringify(o) + "\n"
|
||||
writeFileSync(file, line({ ...done, step_index: 1, created_at: new Date(now - 60_000).toISOString() }))
|
||||
assert.equal(transcriptOf(home, "s1"), file)
|
||||
assert.equal(transcriptOf(home, "../s1"), null)
|
||||
// the session a socket is on, off its own messages: the agent's answer to session/new, a caller's prompt
|
||||
assert.equal(sessionIn(JSON.stringify({ jsonrpc: "2.0", id: 2, result: { sessionId: "s1" } })), "s1")
|
||||
assert.equal(sessionIn(JSON.stringify({ jsonrpc: "2.0", id: 3, method: "session/prompt", params: { sessionId: "s1", prompt: [] } })), "s1")
|
||||
assert.equal(sessionIn(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} })), null)
|
||||
assert.equal(sessionIn("not json sessionId"), null)
|
||||
// another agent on the same sign-in ends its turn beside this one: its transcript is newer, and isn't this turn's
|
||||
const other = path.join(home, "antigravity-acp", "brain", "s2", ".system_generated", "logs")
|
||||
mkdirSync(other, { recursive: true })
|
||||
{
|
||||
const heard: string[] = []
|
||||
let on: string | null = null
|
||||
const stopOther = watchTurnEnd(home, () => on, () => now, (by) => heard.push(by), () => false, 10)
|
||||
writeFileSync(path.join(other, "transcript.jsonl"), line({ ...done, step_index: 9, created_at: new Date(now + 5000).toISOString() }))
|
||||
await new Promise((ok) => setTimeout(ok, 60))
|
||||
// no session known yet: nothing is said, whatever the home holds
|
||||
assert.deepEqual(heard, [])
|
||||
on = "s1"
|
||||
await new Promise((ok) => setTimeout(ok, 60))
|
||||
assert.deepEqual(heard, [])
|
||||
stopOther()
|
||||
}
|
||||
assert.equal(JSON.parse(lastLine(file)).step_index, 1)
|
||||
// an end from before the agent was last told anything isn't this turn's; one after it is said once
|
||||
const said: string[] = []
|
||||
let busy = true
|
||||
const stop = watchTurnEnd(home, () => "s1", () => now, (by) => said.push(by), () => busy, 10)
|
||||
await new Promise((ok) => setTimeout(ok, 60))
|
||||
assert.deepEqual(said, [])
|
||||
writeFileSync(file, line({ ...done, step_index: 2, tool_calls: [{ name: "x" }], created_at: new Date(now + 1000).toISOString() }) + line({ ...done, step_index: 3, created_at: new Date(now + 2000).toISOString() }))
|
||||
// the step ended, but a job the agent started still runs: it's waiting, not done
|
||||
await new Promise((ok) => setTimeout(ok, 80))
|
||||
assert.deepEqual(said, [])
|
||||
busy = false
|
||||
await new Promise((ok) => setTimeout(ok, 80))
|
||||
stop()
|
||||
assert.deepEqual(said, ["its transcript, and nothing of its own running"])
|
||||
// an agent's own jobs, from a made-up /proc: its session's and its children's, not its own programs or raea cloud's
|
||||
const proc = path.join(home, "proc")
|
||||
const put = (pid: number, ppid: number, sid: number, exe: string, cmd: string, cwd = "/") => {
|
||||
mkdirSync(path.join(proc, String(pid)), { recursive: true })
|
||||
writeFileSync(path.join(proc, String(pid), "stat"), `${pid} (a (odd) name) S ${ppid} ${sid} ${sid} 0 -1`)
|
||||
writeFileSync(path.join(proc, String(pid), "cmdline"), cmd.replace(/ /g, "\0"))
|
||||
symlinkSync(exe, path.join(proc, String(pid), "exe"))
|
||||
symlinkSync(cwd, path.join(proc, String(pid), "cwd"))
|
||||
}
|
||||
put(100, 1, 100, "/opt/raea-cloud/agents/antigravity-acp/agy", "agy")
|
||||
put(101, 100, 100, "/opt/raea-cloud/agents/antigravity-acp/localharness_external", "localharness_external")
|
||||
put(50, 1, 50, "/usr/bin/node", "node /opt/raea-cloud/server/main.ts")
|
||||
put(60, 50, 50, "/usr/bin/node", "node .raea-cloud/live/live.cjs", "/srv/work/threads/r1")
|
||||
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc), [])
|
||||
put(200, 101, 100, "/opt/raea/bin/raea", "raea render edit.tsx")
|
||||
put(300, 1, 300, "/usr/bin/ffmpeg", "ffmpeg -i a.mp4", "/srv/work/threads/r1/out")
|
||||
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc).sort(), [200, 300])
|
||||
// Claude's Stop hook: added to the settings there once, what was there kept; its file's touch is the turn's end
|
||||
const cfg = path.join(home, "claude")
|
||||
mkdirSync(cfg, { recursive: true })
|
||||
writeFileSync(path.join(cfg, "settings.json"), JSON.stringify({ model: "opus", hooks: { Stop: [{ hooks: [{ type: "command", command: "true" }] }] } }))
|
||||
const mark = claudeStopHook(cfg)
|
||||
claudeStopHook(cfg)
|
||||
const set = JSON.parse(readFileSync(path.join(cfg, "settings.json"), "utf8"))
|
||||
assert.equal(set.model, "opus")
|
||||
assert.deepEqual(set.hooks.Stop.map((g: any) => g.hooks[0].command), ["true", `touch '${mark}'`])
|
||||
assert.equal(markedEnd(mark), null)
|
||||
const heard: string[] = []
|
||||
const stop2 = watchEnd(() => markedEnd(mark), "its Stop hook", () => Date.now() - 500, (by) => heard.push(by), () => false, 10)
|
||||
await new Promise((ok) => setTimeout(ok, 40))
|
||||
assert.deepEqual(heard, [])
|
||||
execSync(set.hooks.Stop[1].hooks[0].command)
|
||||
await new Promise((ok) => setTimeout(ok, 80))
|
||||
stop2()
|
||||
assert.deepEqual(heard, ["its Stop hook, and nothing of its own running"])
|
||||
rmSync(home, { recursive: true, force: true })
|
||||
console.log("ok turn-end")
|
||||
}
|
||||
|
||||
{
|
||||
// a farm render's manifest names its takes by the farm's cache: they're named as the project has them, so the sound
|
||||
// check finds each one and checks its edit points (12-03: none of a farm render's were checked)
|
||||
const oid = "4defd638ad139af6bbbf5d33345677855654b568447a5c98b06dc5b876482035"
|
||||
const m = { sounds: { clips: [{ src: `/__modal/volumes/vo-F8fh/blobs/${oid}` }, { src: "/work/abc/media/music.mp3" }, { src: "f".repeat(64) }] } }
|
||||
assert.equal(localSources(m, [{ path: "media/raw/a1_hl1.mov", oid }], "/work/project"), 1)
|
||||
assert.deepEqual(m.sounds.clips.map((c) => c.src), ["/work/project/media/raw/a1_hl1.mov", "/work/abc/media/music.mp3", "f".repeat(64)])
|
||||
assert.equal(localSources({}, [], "/x"), 0)
|
||||
console.log("ok localSources")
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// A goal (docs/goal.feature): one step of the work, `goal` on brief.ts, one or several in order (a workflow inline, or
|
||||
// a workflow() module the brief imports). cut, shot, kit, scene and rules are presets of it, each turning its kind's
|
||||
// a workflow() module the brief imports). cut, shot, kit, scene, playable and rules are presets of it, each turning its kind's
|
||||
// packs on; any goal carries `rules` (commands, files, words a critic judges) and an `aim`; `packs` switches any of
|
||||
// raea's by name and `checks` adds the project's own (raea/check `check()`s, imported into brief.ts). `name`, `step`
|
||||
// and `after` place it in a workflow. Pure: brief.ts imports this, and `raea spec` reads brief.ts with no Node.
|
||||
@@ -55,6 +55,7 @@ export const PACKS = {
|
||||
notes: "NOTES.md, with what the skill got wrong",
|
||||
floor: "no clipped text, low contrast, freeze, flash or loudness out of range",
|
||||
stills: "a composition's stills as it's saved: no clipped or cramped text, nothing out of the safe areas",
|
||||
playable: "each network's page under 5 MB, in the orientations asked for, exported since the game last changed",
|
||||
} as const
|
||||
export type PackName = keyof typeof PACKS
|
||||
|
||||
@@ -65,6 +66,7 @@ export const DEFAULTS: Record<GoalKind | "floor", PackName[]> = {
|
||||
scene: ["deliverables", "record", "critic", "notes", "stills"],
|
||||
kit: ["deliverables", "record", "critic", "notes", "stills"],
|
||||
shot: ["deliverables", "record", "critic", "notes", "stills"],
|
||||
playable: ["deliverables", "playable", "stills"],
|
||||
// a project with no `goal`: what any made video is held to, and any composition as it's saved
|
||||
floor: ["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"],
|
||||
}
|
||||
@@ -119,6 +121,9 @@ export const kit = (m: Kindless): Contract => ({ kind: "kit", ...m })
|
||||
export const shot = (m: Kindless): Contract => ({ kind: "shot", ...m })
|
||||
/** cuts of footage from a client's brief: the brief as rules (`cut: {...}`) */
|
||||
export const cut = (m: Kindless): Contract => ({ kind: "cut", ...m })
|
||||
/** a game exported as a playable ad: `playable({ aim, playable: { game: "playable.tsx" } })`, both orientations and
|
||||
* every network unless it names them (docs/playables.feature PA19) */
|
||||
export const playable = (m: Kindless): Contract => ({ kind: "playable", ...m })
|
||||
/** any other work, held only to its rules: `rules({ aim: "the person's words", rules: [...] })` */
|
||||
export const rules = (m: Kindless): Contract => ({ kind: "rules", ...m })
|
||||
/** a shared workflow: its steps in order, each a goal (`after` orders them past it) */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// raea/goal (@raea/goal): the loop's goals (docs/goal.feature): plan, run, check, done, for one goal or a workflow of
|
||||
// them. This entry is pure, as brief.ts imports it: the packs (./packs) and the runner (./run, `raea goal check`) read
|
||||
// files and run programs, and are loaded only by the runner.
|
||||
export { cut, DEFAULTS, goal, goalsOf, kit, momentsOf, nameOf, PACKS, packsOf, rules, scene, shot, unknownPacks, workflow } from "./contract.ts"
|
||||
export { cut, DEFAULTS, goal, goalsOf, kit, momentsOf, nameOf, PACKS, packsOf, playable, rules, scene, shot, unknownPacks, workflow } from "./contract.ts"
|
||||
export type { Contract, Goals, Moment, PackName, Workflow } from "./contract.ts"
|
||||
export { check, found } from "raea/check"
|
||||
export type { Check, Found } from "raea/check"
|
||||
@@ -208,10 +208,23 @@ export async function words(file: string, anyAge = false): Promise<Word[]> {
|
||||
/** frames read a second for the scene, and the width they're read at (places are in shares of the picture) */
|
||||
export const RATE = 2
|
||||
const SIDE = 540
|
||||
/** a video's scene reading, kept beside it */
|
||||
export const SCENE_EXT = "scene.json"
|
||||
|
||||
/** what's in a file's frames (`at`: those seconds, else RATE a second): each frame's faces and seams, and its scene
|
||||
* (people, faces, things, words in the shot) for placement. The farm reads them; with no farm here, Unmet */
|
||||
export async function scene(file: string, at?: number[]): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> {
|
||||
// a video's whole reading is kept beside it, as its words are, and read again only when the file is newer: a cut
|
||||
// checked at its render was read again at publish and again at done, 30 s a file each time, so a done check of 11
|
||||
// files took 334 s (12-01)
|
||||
const whole = !at?.length && !/\.(png|jpe?g|webp)$/i.test(file)
|
||||
if (whole) {
|
||||
const kept = freshBeside(file, SCENE_EXT)
|
||||
try {
|
||||
const k = kept ? (JSON.parse(readFileSync(kept, "utf8")) as { rate: number; side: number; faces: Faces[]; scenes: Scene[] }) : null
|
||||
if (k && k.rate === RATE && k.side === SIDE && Array.isArray(k.scenes) && k.scenes.length) return { rate: k.rate, faces: k.faces, scenes: k.scenes }
|
||||
} catch {}
|
||||
}
|
||||
if (!farm()) throw new Unmet(`no scene reader on this machine for ${path.basename(file)} (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`)
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-scene-"))
|
||||
try {
|
||||
@@ -238,6 +251,11 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
|
||||
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
|
||||
}
|
||||
}
|
||||
if (whole && scenes.length) {
|
||||
try {
|
||||
writeFileSync(`${stem(file)}.${SCENE_EXT}`, `${JSON.stringify({ rate: RATE, side: SIDE, faces, scenes })}\n`)
|
||||
} catch {}
|
||||
}
|
||||
return { rate: at?.length ? 0 : RATE, faces, scenes }
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
|
||||
@@ -21,7 +21,7 @@ import type { TextLine } from "./place.ts"
|
||||
|
||||
/** a line of text the reader found in a frame: [x, y, w, h, text, score], in that frame's pixels */
|
||||
export type Read = TextLine
|
||||
export type Finding = { level: "error" | "warn" | "note"; kind: "shown" | "dropped" | "none"; at: number; says: string }
|
||||
export type Finding = { level: "error" | "warn" | "note"; kind: "shown" | "dropped" | "none" | "uncaptioned"; at: number; says: string }
|
||||
|
||||
/** a word or a line as it's compared: lower case letters and digits, nothing else */
|
||||
export const letters = (s: string) => s.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, "")
|
||||
@@ -199,8 +199,43 @@ export function compare(shown: Shown[], heard: Word[]): Finding[] {
|
||||
return out.sort((a, b) => a.at - b.at)
|
||||
}
|
||||
|
||||
/** speech this long (s) and this many words with no caption up is an error, the shorter a warning */
|
||||
const BARE = { error: { s: 3, words: 6 }, warn: { s: 1.5, words: 3 } }
|
||||
/** the opening a text hook may hold without captions under it (s) */
|
||||
const HOOK_S = 5
|
||||
|
||||
/** captions are a must wherever someone talks (12-03, Shane: "captions are mandatory"; Elfster's cuts with a text hook
|
||||
* had none, read from its brief's "captions OR a text hook"): a cut with talking and no captions at all is an error,
|
||||
* and so is a stretch of talking with none up. A text hook may be on screen beside them; it doesn't stand in for them.
|
||||
* A brief that wants no captions says so, and the render says it with --despite captions WHY */
|
||||
export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) => boolean = () => false): Finding[] {
|
||||
// a brief's "captions OR a text hook, never both" means not both in one frame (12-03, Shane): the hook may hold the
|
||||
// opening alone, so words in the first HOOK_S with other text up are covered by it; anywhere later it's no caption
|
||||
const said = heard.filter((w) => {
|
||||
const k = letters(w.text)
|
||||
return k && !FILLER.has(k) && !(w.start < HOOK_S && textUp(w.start))
|
||||
})
|
||||
if (said.length < BARE.error.words) return []
|
||||
const fix = "caption every line from the words file (whole phrases in the brand's caption style); a text hook goes with the captions, never instead of them. If the brief asks for no captions, render with --despite captions WHY"
|
||||
if (!shown.length) return [{ level: "error", kind: "uncaptioned", at: said[0].start, says: `no captions over the talking: ${said.length} words, ${(said[said.length - 1].end - said[0].start).toFixed(1)} s, and no caption track (captions one after another under ${Math.round(TRACK * 100)}% of what's said, or fewer than ${CARDS} of them). ${fix}` }]
|
||||
const up = (w: Word) => shown.some((s) => w.end >= s.from - 0.6 && w.start <= s.to + 0.3)
|
||||
const out: Finding[] = []
|
||||
for (let i = 0; i < said.length; ) {
|
||||
if (up(said[i])) { i++; continue }
|
||||
let j = i
|
||||
// a bare stretch: words with no caption up, none more than a second after the last
|
||||
while (j + 1 < said.length && !up(said[j + 1]) && said[j + 1].start - said[j].end < 1) j++
|
||||
const run = said.slice(i, j + 1)
|
||||
const long = run[run.length - 1].end - run[0].start
|
||||
const level = long >= BARE.error.s && run.length >= BARE.error.words ? "error" : long >= BARE.warn.s && run.length >= BARE.warn.words ? "warn" : null
|
||||
if (level) out.push({ level, kind: "uncaptioned", at: run[0].start, says: `${long.toFixed(1)} s of talking from ${run[0].start.toFixed(1)} s has no caption ("${run.slice(0, 8).map((w) => w.text).join(" ")}${run.length > 8 ? " ..." : ""}"): ${fix}` })
|
||||
i = j + 1
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "captions", text: "every caption on screen says exactly what's heard there, no word added, changed or left out", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
|
||||
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const heard = await f.words()
|
||||
@@ -209,6 +244,8 @@ export default check<FileFacts>(
|
||||
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
if (!frames.some((f) => f.lines.length) && sc.scenes.some((s) => s && s.texts === undefined)) return void found({ level: "note", says: "the scene reader here doesn't read text yet, so the captions weren't held to what's heard" })
|
||||
const shown = captionsOf(frames, sc.rate || 2, heard)
|
||||
for (const x of compare(shown, heard)) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
const rate = sc.rate || 2
|
||||
const textUp = (t: number) => (frames[Math.round(t * rate)]?.lines ?? []).some(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4)
|
||||
for (const x of [...uncaptioned(shown, heard, textUp), ...compare(shown, heard)].sort((a, b) => a.at - b.at)) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
@@ -4,7 +4,7 @@
|
||||
// stills a composition as it's saved (`raea check EDIT.tsx --quick`): three stills rendered with their manifest, and
|
||||
// the text rules and the person's text taste on them; what it can't see waits for the export's floor
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
@@ -12,7 +12,7 @@ import type { FileFacts } from "../facts.ts"
|
||||
import { RAEA, stem } from "../media.ts"
|
||||
import { bookkeeping } from "./naming.ts"
|
||||
|
||||
type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
|
||||
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
|
||||
|
||||
/** raea's measure of a file, its findings as it wrote them (-o) */
|
||||
function measure(args: string[], cwd: string): Measured[] {
|
||||
@@ -27,12 +27,36 @@ function measure(args: string[], cwd: string): Measured[] {
|
||||
}
|
||||
}
|
||||
|
||||
/** a video's floor report, kept beside it */
|
||||
export const FLOOR_EXT = "floor.json"
|
||||
let version: string | undefined
|
||||
const raeaVersion = () => (version ??= String(spawnSync(RAEA, ["--version"], { encoding: "utf8" }).stdout ?? "").trim())
|
||||
const when = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
|
||||
|
||||
/** A made video's floor findings: kept beside it (FILE.floor.json) and measured again only when the video or its
|
||||
* manifest is newer, raea is another version, or the kept report holds an error. The measure took 26 s a cut and ran
|
||||
* again on the same file at publish and at done (12-01). An error is always measured again, since what it names (a
|
||||
* placeholder brand kit) can be put right without the video changing, and a kept error would hold a finished run. */
|
||||
export function floorOf(abs: string, manifest: string | undefined, cwd: string, by: (args: string[], cwd: string) => Measured[] = measure): Measured[] {
|
||||
const kept = `${stem(abs)}.${FLOOR_EXT}`
|
||||
try {
|
||||
const k = JSON.parse(readFileSync(kept, "utf8")) as { raea: string; findings: Measured[] }
|
||||
const fresh = when(kept) >= when(abs) && (!manifest || when(kept) >= when(manifest))
|
||||
if (fresh && k.raea === raeaVersion() && !k.findings.some((x) => x.level === "error")) return k.findings
|
||||
} catch {}
|
||||
const findings = by([abs, ...(manifest ? ["--manifest", manifest] : [])], cwd)
|
||||
try {
|
||||
writeFileSync(kept, `${JSON.stringify({ raea: raeaVersion(), findings })}\n`)
|
||||
} catch {}
|
||||
return findings
|
||||
}
|
||||
|
||||
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
|
||||
|
||||
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["render", "publish", "done"] }, async (f) => {
|
||||
if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return
|
||||
const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync)
|
||||
for (const x of measure([f.abs, ...(m ? ["--manifest", m] : [])], f.root)) say(x)
|
||||
for (const x of floorOf(f.abs, m, f.root)) say(x)
|
||||
})
|
||||
|
||||
export const stillsPack = check<FileFacts>({ id: "stills", text: "a composition's stills: no clipped or cramped text, nothing out of the safe areas", over: "file", at: ["edit"], needs: "render" }, async (f) => {
|
||||
|
||||
@@ -19,6 +19,11 @@ export const TIMEOUT = 300
|
||||
/** folders that aren't the work: what the job writes about itself, and what tools keep */
|
||||
const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"])
|
||||
|
||||
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
|
||||
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
|
||||
* as older than the work (12-01) */
|
||||
const READING = /\.(check|words|scene|floor|montage)\.json$/
|
||||
|
||||
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
|
||||
export function newest(dir: string): number | null {
|
||||
let best: number | null = null
|
||||
@@ -43,7 +48,7 @@ export function newest(dir: string): number | null {
|
||||
}
|
||||
if (st.isDirectory()) {
|
||||
if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p)
|
||||
} else if (st.isFile() && name !== "NOTES.md" && !name.endsWith(".check.json")) best = Math.max(best ?? 0, st.mtimeMs)
|
||||
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
|
||||
}
|
||||
}
|
||||
return best
|
||||
|
||||
@@ -11,6 +11,7 @@ import { criticPack, deliverablesPack, notesPack, recordPack } from "./job.ts"
|
||||
import { seenPack, surprisePack } from "./look.ts"
|
||||
import naming from "./naming.ts"
|
||||
import place from "./place.ts"
|
||||
import { playablePack } from "./playable.ts"
|
||||
import sizes, { allSizes } from "./sizes.ts"
|
||||
import sound from "./sound.ts"
|
||||
import reading from "./reading.ts"
|
||||
@@ -49,4 +50,5 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
|
||||
notes: [notesPack],
|
||||
floor: [floorPack],
|
||||
stills: [stillsPack],
|
||||
playable: [playablePack],
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import type { Contract } from "../contract.ts"
|
||||
import type { Job } from "../facts.ts"
|
||||
import { RAEA } from "../media.ts"
|
||||
import { deliverables as cutFiles } from "./cut.ts"
|
||||
import { deliverables as playableFiles } from "./playable.ts"
|
||||
import { unregistered } from "../project.ts"
|
||||
|
||||
export const SKILL_HEADING = "What the skill got wrong"
|
||||
@@ -36,6 +37,8 @@ function byKind(m: Contract): string[] {
|
||||
return (m.shots ?? []).map((s) => `out/shots/${s.name}.png|out/shots/${s.name}.mp4`)
|
||||
case "cut":
|
||||
return m.cut ? cutFiles(m.cut) : []
|
||||
case "playable":
|
||||
return m.playable ? playableFiles(m.playable) : []
|
||||
case "rules":
|
||||
return []
|
||||
}
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
// eye, plane and tone are warnings at each cut, in Murch's order; one becomes an error when it breaks at more than half
|
||||
// of a file's cuts (a habit, not a choice). A cut on a word is the sound pack's (edit-on-sound), not this one's.
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { Beat } from "raea/brief.gen"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
@@ -42,9 +45,18 @@ export type Finding = { level: "error" | "warn"; kind: "pace" | "tempo" | "eye"
|
||||
export function read(file: string, fps: number, width: number, height: number): Read {
|
||||
const w = READ_W
|
||||
const h = Math.max(2, Math.round((READ_W * height) / width / 2) * 2)
|
||||
const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 })
|
||||
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
|
||||
const buf = r.stdout as Buffer
|
||||
// into a file, not down a pipe: 13 MB of frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box, and
|
||||
// 4.6 s into a file (12-01)
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "raea-montage-read-"))
|
||||
let buf: Buffer
|
||||
try {
|
||||
const raw = path.join(dir, "frames.raw")
|
||||
const r = spawnSync("ffmpeg", ["-v", "error", "-an", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", raw], { encoding: "utf8" })
|
||||
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
|
||||
buf = readFileSync(raw)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
const size = w * h * 3
|
||||
const frames: Frame[] = []
|
||||
for (let o = 0; o + size <= buf.length; o += size) {
|
||||
@@ -235,6 +247,25 @@ export function acrossCuts(r: Read, cuts: number[], o: { faces?: Faces[]; rate?:
|
||||
return out
|
||||
}
|
||||
|
||||
/** a video's montage findings, kept beside it */
|
||||
export const MONTAGE_EXT = "montage.json"
|
||||
|
||||
/** A video's findings from `measure`, kept beside it (FILE.montage.json) and measured again only when the video is
|
||||
* newer or what they were measured against (`given`: its beats, its scene reading) is another. Reading a 35 s cut's
|
||||
* frames took 7 s each time the goal was checked, on files that hadn't changed (12-01). */
|
||||
export function keptOr(abs: string, given: string, measure: () => Finding[]): Finding[] {
|
||||
const kept = `${abs.replace(/\.[^./]+$/, "")}.${MONTAGE_EXT}`
|
||||
try {
|
||||
const k = JSON.parse(readFileSync(kept, "utf8")) as { given: string; findings: Finding[] }
|
||||
if (statSync(kept).mtimeMs >= statSync(abs).mtimeMs && k.given === given) return k.findings
|
||||
} catch {}
|
||||
const findings = measure()
|
||||
try {
|
||||
writeFileSync(kept, `${JSON.stringify({ given, findings })}\n`)
|
||||
} catch {}
|
||||
return findings
|
||||
}
|
||||
|
||||
const where = ([x, y]: [number, number]) => `${y < 0.34 ? "top" : y > 0.66 ? "bottom" : "middle"} ${x < 0.34 ? "left" : x > 0.66 ? "right" : "centre"}`
|
||||
|
||||
export default check<FileFacts>(
|
||||
@@ -244,9 +275,6 @@ export default check<FileFacts>(
|
||||
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
|
||||
const plan = c ? cutOf(c, f.path) : null
|
||||
const beats = plan?.plan.beats ?? []
|
||||
const r = read(f.abs, f.fps, f.width, f.height)
|
||||
if (r.frames.length < 2) return
|
||||
const cuts = cutsOf(r)
|
||||
let faces: Faces[] | undefined
|
||||
let rate = 0
|
||||
try {
|
||||
@@ -258,7 +286,12 @@ export default check<FileFacts>(
|
||||
if (!(e instanceof Unmet)) throw e
|
||||
}
|
||||
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
|
||||
for (const x of pace(beats, cuts, r.fps, r.frames.length / r.fps)) say(x)
|
||||
for (const x of acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })) say(x)
|
||||
for (const x of keptOr(f.abs, JSON.stringify({ beats, faces: faces?.length ?? null, rate }), () => {
|
||||
const r = read(f.abs, f.fps, f.width!, f.height!)
|
||||
if (r.frames.length < 2) return []
|
||||
const cuts = cutsOf(r)
|
||||
return [...pace(beats, cuts, r.fps, r.frames.length / r.fps), ...acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })]
|
||||
}))
|
||||
say(x)
|
||||
},
|
||||
)
|
||||
@@ -7,6 +7,7 @@
|
||||
// itself, and the box around them a little), then the edges a phone's own buttons and captions cover; open ground is
|
||||
// free. A text's cost is the mean of the cells it covers. A text is badly placed when it covers a face or a thing, or
|
||||
// a person, and a place of the same size costs much less; that place is what's said.
|
||||
// Over a face or a thing it's an error; over a person's body alone, a warning.
|
||||
//
|
||||
// raea make place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
|
||||
// FILE (a take or an export, a picture or a video) read at those seconds (a video: one a second, at most 12):
|
||||
@@ -257,8 +258,12 @@ export function textOver(manifest: any, scenes: Scene[], rate: number): Finding[
|
||||
const q = `${on.text.length > 40 ? `“${on.text.slice(0, 40)}...”` : `“${on.text}”`}${on.lines > 1 ? ` (and the ${on.lines - 1} line${on.lines > 2 ? "s" : ""} under it)` : ""}`
|
||||
const when = on.to - on.from < 0.5 ? `at ${on.from.toFixed(1)} s` : `from ${on.from.toFixed(1)} s to ${on.to.toFixed(1)} s`
|
||||
if (best && best.cost <= here - BETTER) {
|
||||
const face = under.includes("a face")
|
||||
out.push({ level: face || here >= BAD + 1.5 ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea make place shows the clear places in a shot` })
|
||||
// an error only for what a shot can't lose: a face, or the thing it shows (the product, the dog, a phone held
|
||||
// up). A caption over someone's coat with clearer ground elsewhere is a warning with the place said (12-01: two
|
||||
// people fill a 9:16 interview frame, each caption's clearest place is a different one, and an agent spent
|
||||
// hours cropping shots and rendering again to clear errors a steady caption position can't)
|
||||
const hard = under.some((u) => u !== "a person in the shot")
|
||||
out.push({ level: hard ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea make place shows the clear places in a shot` })
|
||||
} else if (under.includes("a face")) {
|
||||
out.push({ level: "error", kind: "text-over", at: on.from, until: on.to, says: `${q} covers a face ${when} and no place of its size is clear: make it smaller, put it on a shot with room, or cut to one` })
|
||||
} else if (here >= BAD + 1.5) {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// The playable pack (docs/playables.feature PA19): a playable goal's export, read from the manifest `raea playable`
|
||||
// writes beside its pages (out/playable/NAME.playable.json). Its pages each under the 5 MB cap, its compositions in the
|
||||
// orientations the goal asks for (both unless it says one), exported since the game last changed, and every network
|
||||
// it ships to written. The deliverables are the core/brief playable.rs list, mirrored here as cut.ts mirrors cut.rs.
|
||||
import { existsSync, readFileSync, statSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { PlayableGoal } from "raea/brief.gen"
|
||||
import type { Contract } from "../contract.ts"
|
||||
import type { Job } from "../facts.ts"
|
||||
|
||||
export const NETWORKS = ["applovin", "unity", "google", "meta", "moloco", "mintegral", "tiktok", "liftoff"] as const
|
||||
const ZIPPED = new Set(["google", "mintegral", "tiktok"])
|
||||
export const OUT = "out/playable"
|
||||
/** every network's cap (apps/playable pages.rs CAP) */
|
||||
export const CAP = 5 * 1024 * 1024
|
||||
|
||||
/** what `raea playable` says it wrote (apps/playable lib.rs Manifest) */
|
||||
export interface PlayableManifest {
|
||||
name: string
|
||||
game: string
|
||||
orientation: "both" | "portrait" | "landscape"
|
||||
kinds: string[]
|
||||
compositions: { id: string; width: number; height: number; fps: number; frames: number }[]
|
||||
pages: { network: string; file: string; bytes: number }[]
|
||||
cap: number
|
||||
}
|
||||
|
||||
/** the name its files land as: its own (`raea playable --name`), else the game's file name */
|
||||
export const nameOf = (p: PlayableGoal) => p.name ?? path.basename(p.game, path.extname(p.game))
|
||||
export const networksOf = (p: PlayableGoal): string[] => NETWORKS.filter((n) => !p.networks?.length || p.networks.includes(n))
|
||||
|
||||
export function deliverables(p: PlayableGoal): string[] {
|
||||
const n = nameOf(p)
|
||||
const out = networksOf(p).map((net) => `${OUT}/${n}-${net}.${ZIPPED.has(net) ? "zip" : "html"}`)
|
||||
out.push(`${OUT}/${n}-preview.html`, `${OUT}/${n}.playable.json`)
|
||||
if (p.video === true) out.push(`out/cuts/${n}_9x16.mp4`)
|
||||
return out
|
||||
}
|
||||
|
||||
/** the playable goal of a job's contract, if it's one */
|
||||
export const playableOf = (c: Contract | null): PlayableGoal | null => (c?.kind === "playable" ? (c.playable ?? null) : null)
|
||||
|
||||
export function readManifest(root: string, p: PlayableGoal): PlayableManifest | string {
|
||||
const rel = `${OUT}/${nameOf(p)}.playable.json`
|
||||
const abs = path.join(root, rel)
|
||||
if (!existsSync(abs)) return `${rel} isn't there: export it with raea playable ${p.game} -o ${OUT}${p.name ? ` --name ${p.name}` : ""}${p.orientation && p.orientation !== "both" ? ` --orientation ${p.orientation}` : ""}`
|
||||
try {
|
||||
return JSON.parse(readFileSync(abs, "utf8")) as PlayableManifest
|
||||
} catch (e) {
|
||||
return `${rel} doesn't read: ${e instanceof Error ? e.message : e}`
|
||||
}
|
||||
}
|
||||
|
||||
export const playablePack = check<Job>({ id: "playable", text: "each network's page under 5 MB, in the orientations asked for, exported since the game last changed", over: "job", at: ["publish", "done"] }, async (j) => {
|
||||
const p = playableOf(j.contract)
|
||||
if (!p) return
|
||||
const m = readManifest(j.root, p)
|
||||
if (typeof m === "string") {
|
||||
found({ says: m, about: [p.game] })
|
||||
return
|
||||
}
|
||||
const want = p.orientation ?? "both"
|
||||
const shapes = new Set(m.compositions.map((c) => (c.height > c.width ? "portrait" : "landscape")))
|
||||
const asked: ("portrait" | "landscape")[] = want === "both" ? ["portrait", "landscape"] : [want]
|
||||
const missing = asked.filter((s) => !shapes.has(s))
|
||||
for (const s of missing)
|
||||
found({ says: `${p.game} registers no ${s} composition (it has ${m.compositions.map((c) => `${c.id} ${c.width}x${c.height}`).join(", ") || "none"})`, about: [p.game], fix: want === "both" ? "register a portrait and a landscape composition of the game, the host plays the one nearest the screen; or say orientation in the brief" : undefined })
|
||||
for (const pg of m.pages.filter((x) => x.bytes > CAP)) found({ says: `${pg.file} is ${Math.round(pg.bytes / 1024)} KB, over the ${CAP / 1024} KB cap`, about: [pg.file] })
|
||||
const written = new Set(m.pages.map((x) => x.network))
|
||||
for (const net of [...networksOf(p), "preview"].filter((n) => !written.has(n))) found({ says: `no ${net} page in the last export`, about: [`${OUT}/${nameOf(p)}-${net}`] })
|
||||
// exported since the game last changed: the manifest newer than the game's TSX
|
||||
const game = path.join(j.root, p.game)
|
||||
const manifest = path.join(j.root, OUT, `${nameOf(p)}.playable.json`)
|
||||
if (existsSync(game) && statSync(game).mtimeMs > statSync(manifest).mtimeMs) found({ says: `${p.game} changed after its last export: export it again`, about: [p.game] })
|
||||
})
|
||||
@@ -11,11 +11,24 @@ import { check, found } from "raea/check"
|
||||
import type { Job } from "../facts.ts"
|
||||
import { adOf, bookkeeping, sizeOf } from "./naming.ts"
|
||||
|
||||
/** The size a made file is in, as a name says one (9x16): its name's, else a video's own shape (1080x1920 is 9x16).
|
||||
* A picture with no size in its name is a still of the work, a sheet or a strip, not a size of an ad. Told by pixels
|
||||
* alone, an ad named _9x16 beside its own 1080x1920 renders and one 540x960 still read as three sizes, and an agent
|
||||
* with one size made couldn't stop for its sign-off (12-01). */
|
||||
export function shapeOf(f: { path: string; kind?: string; width?: number; height?: number }): string | null {
|
||||
const named = sizeOf(f.path)
|
||||
if (named) return named
|
||||
if (f.kind !== "video" || !f.width || !f.height) return null
|
||||
const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a)
|
||||
const g = gcd(f.width, f.height)
|
||||
return `${f.width / g}x${f.height / g}`
|
||||
}
|
||||
|
||||
export default check<Job>({ id: "sizes", text: "one size first: no other size before the first is approved", over: "job", at: ["render", "publish", "done"] }, async (j) => {
|
||||
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image"))
|
||||
const sizes = new Map<string, string[]>()
|
||||
for (const f of made) {
|
||||
const s = sizeOf(f.path) ?? (f.width && f.height ? `${f.width}x${f.height}` : null)
|
||||
const s = shapeOf(f)
|
||||
if (s) sizes.set(s, [...(sizes.get(s) ?? []), f.path])
|
||||
}
|
||||
if (sizes.size < 2) return
|
||||
|
||||
@@ -204,7 +204,11 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
|
||||
const kind = busOf(c)
|
||||
const file = f.take(c.src)
|
||||
if (!file) {
|
||||
out.push({ level: "warn", kind: "manifest", at: c.from / fps, says: `${c.src} isn't on this machine: its clip at ${secs(c.from / fps)} isn't checked` })
|
||||
// a voice clip, or one named only by a hash (a farm's cache: its kind can't be told), that can't be found here is
|
||||
// an edit point no one checked: an error (12-03: every farm render's takes were "not on this machine" warnings, so
|
||||
// words cut off at clips' ends passed)
|
||||
const hashed = /(?:^|\/)[0-9a-f]{64}$/.test(c.src)
|
||||
out.push(kind === "voice" || hashed ? { level: "error", kind: "manifest", at: c.from / fps, says: `${hashed ? "a take named only by its hash" : c.src} isn't on this machine, so its clip at ${secs(c.from / fps)} has edit points no one checked: render with the project's takes in the project (raea cloud's render names them), then check again` } : { level: "warn", kind: "manifest", at: c.from / fps, says: `${c.src} isn't on this machine: its clip at ${secs(c.from / fps)} isn't checked` })
|
||||
continue
|
||||
}
|
||||
const dur = (c.to - c.from) / fps
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { captionsOf, compare, fit, letters } from "../src/packs/captions.ts"
|
||||
import { captionsOf, compare, fit, letters, uncaptioned } from "../src/packs/captions.ts"
|
||||
import { voice } from "../src/packs/voice.ts"
|
||||
|
||||
// what the reader saw, two frames a second: phrase captions in one row (y 120 of 960), as Elfster's cut 1 had them
|
||||
@@ -70,3 +70,26 @@ test("the voice pack: dialogue on top of the mix, every line even", () => {
|
||||
const lv3 = [...lv, ...Array.from({ length: 600 }, (_, f) => (third.slice(40).some((y) => (2300 + f) / 100 >= y.start && (2300 + f) / 100 < y.end) ? -20 : -45))]
|
||||
expect(voice(lv3, third).some((x) => x.kind === "quiet" && x.level === "error")).toBe(true)
|
||||
})
|
||||
|
||||
test("captions are a must: a cut that talks with only a text hook up fails, a bare stretch fails, captioned talking passes", () => {
|
||||
// Elfster's 2 AM cut: a text hook over the open, no captions after it
|
||||
const hook = Array.from({ length: 27 }, (_, i) => ({ h: 960, lines: i < 6 ? [[60, 110, 420, 26, "POV: it's 2 AM and you're still guessing gifts", 0.95] as [number, number, number, number, string, number]] : [] }))
|
||||
const none = uncaptioned(captionsOf(hook, 2, said), said)
|
||||
expect(none.map((x) => [x.kind, x.level])).toEqual([["uncaptioned", "error"]])
|
||||
expect(none[0].says).toMatch(/^no captions over the talking/)
|
||||
// a track with gaps: captioned to 7 s, then 5 s bare (an error); a 2 s gap earlier is about a second once the caption
|
||||
// around it counts its own words' edges, under the warning
|
||||
const track = shownLines.filter(([a]) => a < 7.1 && (a < 3.8 || a >= 5.9)).map(([from, to, text]) => ({ text, key: letters(text), from, to, y: 0.12 }))
|
||||
const bare = uncaptioned(track, said)
|
||||
expect(bare.map((x) => [x.level, Math.floor(x.at)])).toEqual([["error", 7]])
|
||||
// every line captioned (and a hook beside them is fine): nothing
|
||||
expect(uncaptioned(captionsOf(frames, 2, said), said)).toEqual([])
|
||||
// a hook alone over the opening, captions after it (the brief's "never both" as one frame): nothing
|
||||
const hookThenCaps = frames.map((f, i) => (i / 2 < 2.6 ? { h: 960, lines: [[60, 300, 420, 26, "POV: the gift you pretend to love", 0.95] as [number, number, number, number, string, number]] } : f))
|
||||
const hookUp = (t: number) => t < 2.6
|
||||
expect(uncaptioned(captionsOf(hookThenCaps, 2, said), said, hookUp)).toEqual([])
|
||||
// text up all through doesn't stand in for captions after the opening
|
||||
expect(uncaptioned(track, said, () => true).map((x) => x.level)).toEqual(["error"])
|
||||
// a cut with hardly any talking needs none
|
||||
expect(uncaptioned([], said.slice(0, 4))).toEqual([])
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
// A made video's floor report is kept beside it and measured again only for cause (packs/floor.ts)
|
||||
import { expect, test } from "bun:test"
|
||||
import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { floorOf, type Measured } from "../src/packs/floor.ts"
|
||||
import { keptOr } from "../src/packs/montage.ts"
|
||||
|
||||
test("a floor report is kept: measured once, again when the video is newer, and always while it holds an error", () => {
|
||||
const d = mkdtempSync(path.join(tmpdir(), "raea-floor-kept-"))
|
||||
const v = path.join(d, "a.mp4")
|
||||
writeFileSync(v, "x")
|
||||
let runs = 0
|
||||
let out: Measured[] = [{ level: "warn", says: "quiet" }]
|
||||
const by = () => (runs++, out)
|
||||
expect(floorOf(v, undefined, d, by)).toEqual(out)
|
||||
expect(floorOf(v, undefined, d, by)).toEqual(out)
|
||||
expect(runs).toBe(1)
|
||||
// the video made again
|
||||
const later = new Date(Date.now() + 60_000)
|
||||
utimesSync(v, later, later)
|
||||
floorOf(v, undefined, d, by)
|
||||
expect(runs).toBe(2)
|
||||
utimesSync(path.join(d, "a.floor.json"), new Date(Date.now() + 120_000), new Date(Date.now() + 120_000))
|
||||
floorOf(v, undefined, d, by)
|
||||
expect(runs).toBe(2)
|
||||
// an error isn't kept as an answer
|
||||
utimesSync(v, new Date(Date.now() + 180_000), new Date(Date.now() + 180_000))
|
||||
out = [{ level: "error", says: "a placeholder brand kit" }]
|
||||
floorOf(v, undefined, d, by)
|
||||
utimesSync(path.join(d, "a.floor.json"), new Date(Date.now() + 240_000), new Date(Date.now() + 240_000))
|
||||
floorOf(v, undefined, d, by)
|
||||
expect(runs).toBe(4)
|
||||
rmSync(d, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test("montage findings are kept: measured again when the video is newer or its beats are others", () => {
|
||||
const d = mkdtempSync(path.join(tmpdir(), "raea-montage-kept-"))
|
||||
const v = path.join(d, "a.mp4")
|
||||
writeFileSync(v, "x")
|
||||
let runs = 0
|
||||
const by = () => (runs++, [{ level: "warn" as const, kind: "pace" as const, at: 1, says: "long" }])
|
||||
keptOr(v, "a", by)
|
||||
expect(keptOr(v, "a", by)).toEqual([{ level: "warn", kind: "pace", at: 1, says: "long" }])
|
||||
expect(runs).toBe(1)
|
||||
keptOr(v, "b", by)
|
||||
expect(runs).toBe(2)
|
||||
utimesSync(v, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000))
|
||||
keptOr(v, "b", by)
|
||||
expect(runs).toBe(3)
|
||||
rmSync(d, { recursive: true, force: true })
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
// The rule packs (MK29, ported from Rust's goal gate tests): run rules pass or say why, says rules need a fresh critic;
|
||||
// any goal carries rules.
|
||||
import { expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"
|
||||
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { clefVerdict, lastVerdict, newest } from "../src/packs/goal.ts"
|
||||
@@ -80,3 +80,15 @@ test("clef judges a rule on the file it names, else on every video made, and say
|
||||
const empty = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
|
||||
expect(clefVerdict(g, empty, () => []).all?.why).toContain("names no file on disk")
|
||||
})
|
||||
|
||||
test("a reading kept beside a file isn't the work changing", () => {
|
||||
const d = mkdtempSync(path.join(tmpdir(), "raea-newest-"))
|
||||
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
|
||||
const cut = path.join(d, "out/cuts/a_b_c_v1_9x16.mp4")
|
||||
writeFileSync(cut, "x")
|
||||
utimesSync(cut, 1000, 1000)
|
||||
for (const ext of ["words.json", "scene.json", "check.json", "floor.json", "montage.json"]) writeFileSync(path.join(d, `out/cuts/a_b_c_v1_9x16.${ext}`), "{}")
|
||||
expect(newest(d)).toBe(1_000_000)
|
||||
writeFileSync(path.join(d, "out/cuts/a_b_c_v1_9x16.render.json"), "{}")
|
||||
expect(newest(d)!).toBeGreaterThan(1_000_000)
|
||||
})
|
||||
@@ -1,6 +1,9 @@
|
||||
import { test } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { RATE, scene, SCENE_EXT, useSender } from "../src/media.ts"
|
||||
import { placeReport, textOver } from "../src/packs/place.ts"
|
||||
|
||||
test("the place pack's model", async () => {
|
||||
@@ -42,4 +45,31 @@ test("the place pack's model", async () => {
|
||||
assert.ok(b.every((x) => x.level === "warn"), JSON.stringify(b))
|
||||
ok("a caption over a person who fills the frame is at most a warning")
|
||||
|
||||
// a: a caption across the woman's body with clear ground above her: a warning that names the place, never an error
|
||||
// (12-01: errors here had an agent cropping interview shots and rendering again for hours)
|
||||
for (const y of [300, 400, 500]) {
|
||||
const d = textOver(man([t("Did you know you", 480, y, 536, 88)]), [sc.a], 1).filter((x) => /covers a person in the shot (at|from)/.test(x.says))
|
||||
assert.ok(d.length === 1 && d[0].level === "warn", JSON.stringify(d))
|
||||
}
|
||||
assert.match(textOver(man([t("Did you know you", 480, 400, 536, 88)]), [sc.a], 1)[0].says, /covers a person in the shot at 0\.0 s: move it to left \d+ px, top \d+ px/)
|
||||
ok("a caption over a body with clearer ground elsewhere is a warning with the place said")
|
||||
|
||||
})
|
||||
|
||||
test("a video's scene reading is kept beside it and read again only when the video is newer", async () => {
|
||||
const d = mkdtempSync(path.join(tmpdir(), "raea-scene-kept-"))
|
||||
const cut = path.join(d, "a_b_c_v1_9x16.mp4")
|
||||
writeFileSync(cut, "not a real video")
|
||||
const kept = { rate: RATE, side: 540, faces: [null], scenes: [{ w: 540, h: 960, grid: { cols: 1, rows: 1, people: ["0"] }, things: [], faces: [] }] }
|
||||
writeFileSync(path.join(d, `a_b_c_v1_9x16.${SCENE_EXT}`), JSON.stringify(kept))
|
||||
let asked = 0
|
||||
useSender(async () => (asked++, { status: 500, ok: false, text: "" }))
|
||||
delete process.env.RAEA_CLOUD_GPU_URL
|
||||
// no farm here at all, and the reading still comes back: from beside the file
|
||||
const r = await scene(cut)
|
||||
assert.equal(r.scenes.length, 1)
|
||||
assert.equal(r.rate, RATE)
|
||||
assert.equal(asked, 0)
|
||||
// a reading at named seconds is never the whole file's
|
||||
await assert.rejects(scene(cut, [1, 2]), /no scene reader/)
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
// The playable goal (docs/playables.feature PA19): its deliverables are each network's page, the preview and the
|
||||
// export's manifest; the playable pack reads the manifest for both orientations, the 5 MB cap and a fresh export.
|
||||
import { expect, test } from "bun:test"
|
||||
import { goalCheck } from "../src/run.ts"
|
||||
import { deliverables } from "../src/packs/playable.ts"
|
||||
import { project, put, touch } from "./project.ts"
|
||||
|
||||
const goal = (playable: object) => ({ kind: "playable", aim: "a runner for a running brand", playable })
|
||||
const comp = (id: string, width: number, height: number) => ({ id, width, height, fps: 30, frames: 900 })
|
||||
const manifest = (compositions: object[], pages: { network: string; bytes: number }[]) =>
|
||||
JSON.stringify({ name: "runner", game: "runner.tsx", orientation: "both", kinds: [], compositions, pages: pages.map((p) => ({ ...p, file: `runner-${p.network}.html` })), cap: 5 * 1024 * 1024 })
|
||||
|
||||
test("its deliverables are each network's page, the preview and the manifest", () => {
|
||||
expect(deliverables({ game: "runner.tsx", networks: ["applovin", "tiktok"], video: true })).toEqual([
|
||||
"out/playable/runner-applovin.html", "out/playable/runner-tiktok.zip", "out/playable/runner-preview.html", "out/playable/runner.playable.json", "out/cuts/runner_9x16.mp4",
|
||||
])
|
||||
})
|
||||
|
||||
test("a game with one orientation, a page over the cap and a stale export are each found", async () => {
|
||||
const d = project(goal({ game: "runner.tsx", networks: ["applovin"] }))
|
||||
put(d, "out/playable/runner.playable.json", manifest([comp("portrait", 1080, 1920)], [{ network: "applovin", bytes: 6 * 1024 * 1024 }, { network: "preview", bytes: 1000 }]))
|
||||
touch(put(d, "runner.tsx", "export {}"), 60)
|
||||
const said = (await goalCheck({ cwd: d, at: "done" })).findings.filter((x) => x.check === "playable").map((x) => x.says)
|
||||
expect(said.some((s) => s.includes("no landscape composition"))).toBe(true)
|
||||
expect(said.some((s) => s.includes("over the 5120 KB cap"))).toBe(true)
|
||||
expect(said.some((s) => s.includes("changed after its last export"))).toBe(true)
|
||||
})
|
||||
|
||||
test("an export in both orientations under the cap passes", async () => {
|
||||
const d = project(goal({ game: "runner.tsx", networks: ["applovin"] }))
|
||||
touch(put(d, "runner.tsx", "export {}"), -60)
|
||||
put(d, "out/playable/runner.playable.json", manifest([comp("portrait", 1080, 1920), comp("landscape", 1920, 1080)], [{ network: "applovin", bytes: 1000 }, { network: "preview", bytes: 1000 }]))
|
||||
const f = (await goalCheck({ cwd: d, at: "done" })).findings
|
||||
expect(f.filter((x) => x.check === "playable")).toEqual([])
|
||||
// the pages themselves still have to be there
|
||||
expect(f.filter((x) => x.check === "deliverables").map((x) => x.says)).toContain("missing: out/playable/runner-applovin.html")
|
||||
})
|
||||
|
||||
test("no export yet says how to make one", async () => {
|
||||
const d = project(goal({ game: "runner.tsx", orientation: "portrait" }))
|
||||
const said = (await goalCheck({ cwd: d, at: "done" })).findings.filter((x) => x.check === "playable").map((x) => x.says)
|
||||
expect(said[0]).toContain("raea playable runner.tsx -o out/playable --orientation portrait")
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import { beforeAll, expect, test } from "bun:test"
|
||||
import { goalCheck } from "../src/run.ts"
|
||||
import { CLIP, project, put } from "./project.ts"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { shapeOf } from "../src/packs/sizes.ts"
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.RAEA_REAL = "/usr/bin/false"
|
||||
@@ -31,3 +32,13 @@ test("every size of the newest version passes; a person's answer can say fewer",
|
||||
expect((await all(answered, sizes)).filter((x) => x.check === "sizes-all")).toEqual([])
|
||||
expect((await all(answered, ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4"])).filter((x) => x.check === "sizes-all")).toEqual([])
|
||||
})
|
||||
|
||||
test("one size is one size however it's told: a name's 9x16, a 1080x1920 video, never a still", () => {
|
||||
expect(shapeOf({ path: "out/cuts/dutch_vetbill_hooka_v1_9x16.mp4", kind: "video", width: 1080, height: 1920 })).toBe("9x16")
|
||||
expect(shapeOf({ path: "out/cuts/hooka.mp4", kind: "video", width: 1080, height: 1920 })).toBe("9x16")
|
||||
expect(shapeOf({ path: "out/cuts/hooka_small.mp4", kind: "video", width: 540, height: 960 })).toBe("9x16")
|
||||
expect(shapeOf({ path: "out/cuts/hooka.mp4", kind: "video", width: 1080, height: 1350 })).toBe("4x5")
|
||||
expect(shapeOf({ path: "out/stills/a1_38.jpg", kind: "image", width: 540, height: 960 })).toBe(null)
|
||||
expect(shapeOf({ path: "out/stills/strip.png", kind: "image", width: 1080, height: 480 })).toBe(null)
|
||||
expect(shapeOf({ path: "out/stills/dutch_vetbill_end_v1_1x1.png", kind: "image", width: 1080, height: 1080 })).toBe("1x1")
|
||||
})
|
||||
@@ -2,7 +2,7 @@ import { test } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import type { Clip } from "../src/facts.ts"
|
||||
import type { Levels } from "../src/media.ts"
|
||||
import { balance, busOf, editPoints, nearestGap, type Heard } from "../src/packs/sound.ts"
|
||||
import { balance, busOf, editPoints, nearestGap, soundOf, type Heard } from "../src/packs/sound.ts"
|
||||
|
||||
test("the sound pack's measures", async () => {
|
||||
// the sound pack's measures, on made-up takes
|
||||
@@ -85,3 +85,15 @@ test("the sound pack's measures", async () => {
|
||||
ok("a clip's kind from its bus, or its file's name when it has none")
|
||||
|
||||
})
|
||||
|
||||
test("a voice clip, or a take named only by a farm cache's hash, that isn't here fails: its edit points went unchecked", async () => {
|
||||
const oid = "4defd638ad139af6bbbf5d33345677855654b568447a5c98b06dc5b876482035"
|
||||
const f = {
|
||||
manifest: { fps: 30, sounds: { clips: [{ src: `/__modal/volumes/vo-1/blobs/${oid}`, from: 0, to: 30, at: 2 }, { src: "media/raw/a1_hl1.mov", from: 30, to: 60, at: 5 }, { src: "media/music/bed.mp3", from: 0, to: 60, at: 0 }] } },
|
||||
take: () => null,
|
||||
} as never
|
||||
const { findings } = await soundOf(f)
|
||||
// in time order: the music bed (0 s) only warns; the hashed take (0 s) and the missing voice take (1 s) fail
|
||||
assert.deepEqual(findings.map((x) => [x.level, x.at]), [["error", 0], ["warn", 0], ["error", 1]])
|
||||
assert.match(findings[0].says, /^a take named only by its hash isn't on this machine/)
|
||||
})
|
||||
@@ -52,30 +52,62 @@ import { EndCard, InstallButton, install } from "raea/playable";
|
||||
- Any URL, `fetch`, XHR or WebSocket. Networks refuse a page that makes a request.
|
||||
- Modules that need the native engine: raea/native, raea/ml, raea/character, raea/physics, raea/media,
|
||||
raea/matchmove and raea/modelling.
|
||||
- `<Video>` and `<Audio>`, until sound comes to playables.
|
||||
- `<Video>`: footage stays in the video ad. Render a clip as an image sequence if the game needs it.
|
||||
- 3D outside what the host draws: meshes (box, sphere, plane, cylinder, cone, torus, capsule, circle, ring), the
|
||||
standard, physical and basic materials, perspective and orthographic cameras, the five light kinds, fog, tone
|
||||
mapping, shadows and anti-aliasing. Models, splats and water stay in the video ad.
|
||||
|
||||
## Rules on raea/ecs
|
||||
|
||||
A game whose rules are systems on a raea/ecs `World` keeps Bevy's world in the playable: the export sees a World made
|
||||
and carries runtime/ecs as wasm (about 250 KB in the page), loaded before the game, so the tables, queries, parents and
|
||||
`scene()` answer as they do in `raea render`. Keep the World as the game's state: each step copies it, writes the
|
||||
input in as a resource, and runs its systems once.
|
||||
|
||||
```tsx
|
||||
const step = (s: Game, input: FrameInput, frame: number): Game => {
|
||||
const w = s.w.copy(); // the next state, with the World's systems
|
||||
if (input.pointer) w.resource("aim", input.pointer.x);
|
||||
w.step(frame);
|
||||
return { w, over: (w.resource<number>("score") ?? 0) >= 10 };
|
||||
};
|
||||
```
|
||||
|
||||
Draw its entities with the elements the host draws (`<Mesh3d>` with a `<Cuboid>` or `<Sphere>`), not `<Entities>`,
|
||||
whose Manifold shapes need the engine. examples/playables/star-catch.tsx is the whole pattern.
|
||||
|
||||
## Sound
|
||||
|
||||
A playable is silent until the person touches it, as every network requires, and then plays what the video ad
|
||||
plays. `<Audio>` with an imported file (`import hit from "./hit.wav"`) or a generated one (`sao("glass ping", {
|
||||
seconds: 0.5 })`, `tokensynthNote(...)`) and raea/tone (instruments, effects, `<Sfx>` one-shots, the Transport) all
|
||||
work. The export makes each generated sound, compressed to AAC, and carries it in the page. A raea/tone graph is
|
||||
played by Tone.js, which a project with one adds once (`raea add [email protected]`, about 360 KB a page). Fire a game's
|
||||
one-shots from its state: the state a frame shows is the step's of the frame before (`useGameState`), so an event the
|
||||
step stamps with `frame` shows on `frame + 1`. `<Sfx when={s.hit === now - 1} ...>` sounds on the frame it's seen.
|
||||
|
||||
A font is carried the same way: import it (`import arvo from "./Arvo-Bold.ttf"`) and name it in an `@font-face` in a
|
||||
`<style>`, ``src: url(${arvo})``. A font named but not imported isn't there on a phone, which draws its own sans-serif.
|
||||
`<style>`, ``src: url(${arvo})``. The families raea draws with its own faces (Inter, and the ones it stands in for:
|
||||
Helvetica, Arial and SF Pro as Inter, Times and Georgia as EB Garamond, Montserrat, Roboto and the rest of its set) are
|
||||
carried for you, as the video ad draws them. Any other family named but not imported isn't there on a phone.
|
||||
`<EndCard>` takes `font`, `color` and `button` (a style for its button), so a brand's card is in the brand's type.
|
||||
|
||||
## Export and check
|
||||
|
||||
```sh
|
||||
raea add [email protected] # once per project: the playable's 3D renderer
|
||||
raea add [email protected] # once per project, if it uses raea/tone
|
||||
raea render game.tsx -o out/video-ad.mp4 # the video ad
|
||||
raea playable game.tsx -o out/playable --ios https://apps.apple.com/app/id123 --android https://play.google.com/store/apps/details?id=com.example
|
||||
```
|
||||
|
||||
It prints each network's file and its size against the 5 MB cap; a page is usually 1.3 to 1.5 MB, most of it
|
||||
three.js. `--networks applovin,google,preview` makes fewer, `--title` and `--cta` set the host's own card, and
|
||||
It prints each network's file and its size against the 5 MB cap. A 2D game's page is about 400 KB; three.js adds about
|
||||
1 MB for 3D and Tone.js about 360 KB for raea/tone, and the rest is the game's own pictures and sounds. `--networks applovin,google,preview` makes fewer, `--title` and `--cta` set the host's own card, and
|
||||
`--orientation` sets what Google and TikTok are told.
|
||||
|
||||
Play the `preview` page yourself before handing it over: open it at a phone's size, drag, lose, and tap the card. In
|
||||
raea's own checkout, `bun sdk/playable/tools/check.ts PAGE.html OUT` plays it in WebKit, as an iPhone's ad view does,
|
||||
and fails on an error, a request, or a card that opens nothing.
|
||||
and fails on an error, a request, a card that opens nothing, or sound that doesn't play after the first touch.
|
||||
|
||||
## How it fails
|
||||
|
||||
@@ -86,4 +118,6 @@ and fails on an error, a request, or a card that opens nothing.
|
||||
| a tap does nothing | the press lasted less than a frame, or the step waits for the release | act on `down` |
|
||||
| the page is refused for a request | a URL or `staticFile` in the source, or a font from the web | import the file; take the URL out |
|
||||
| it's letterboxed on a phone | one orientation registered | register the other shape |
|
||||
| an `<Sfx>` never sounds | its `when` compares the step's frame to the frame shown | compare with `now - 1` |
|
||||
| the export says it plays raea/tone with tone, which this project doesn't have | no Tone.js in the project | `raea add tone@15.1.22` |
|
||||
| the video ad shows the end card early | the self-play loses too fast | tune the self-play so it nearly wins |
|
||||
@@ -9,6 +9,7 @@
|
||||
"react-dom": "file:../raea/node_modules/react-dom",
|
||||
"scheduler": "file:../raea/node_modules/scheduler",
|
||||
"three": "0.180.0",
|
||||
"tone": "15.1.22",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.3",
|
||||
@@ -19,6 +20,8 @@
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@babel/runtime": ["@babel/[email protected]", "", {}, "sha512-CvlZdpED5dsu21yK0DfpXksJWt1zeW09lY49hp7P9cA5Qedx/QkwEs1PfluSJjijH9i94oT9LmtgGWlPY8ISzw=="],
|
||||
|
||||
"@dimforge/rapier3d-compat": ["@dimforge/[email protected]", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="],
|
||||
|
||||
"@tweenjs/tween.js": ["@tweenjs/[email protected]", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="],
|
||||
@@ -39,6 +42,8 @@
|
||||
|
||||
"@webgpu/types": ["@webgpu/[email protected]", "", {}, "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA=="],
|
||||
|
||||
"automation-events": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.29.2", "tslib": "^2.8.1" } }, "sha512-cD+TLhJTI0q4AI3ktd353lrGZiVa9AchowSDzQzzGjSoYe22js4vlS32VUtWuaulghi1Yq0KYNWKk9wWuGymPA=="],
|
||||
|
||||
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
|
||||
|
||||
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
|
||||
@@ -55,8 +60,14 @@
|
||||
|
||||
"scheduler": ["scheduler@file:../raea/node_modules/scheduler", {}],
|
||||
|
||||
"standardized-audio-context": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.25.6", "automation-events": "^7.0.9", "tslib": "^2.7.0" } }, "sha512-Ki9zNz6pKcC5Pi+QPjPyVsD9GwJIJWgryji0XL9cAJXMGyn+dPOf6Qik1AHei0+UNVcc4BOCa0hWLBzlwqsW/A=="],
|
||||
|
||||
"three": ["[email protected]", "", {}, "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w=="],
|
||||
|
||||
"tone": ["[email protected]", "", { "dependencies": { "standardized-audio-context": "^25.3.70", "tslib": "^2.3.1" } }, "sha512-TCScAGD4sLsama5DjvTUXlLDXSqPealhL64nsdV1hhr6frPWve0DeSo63AKnSJwgfg55fhvxj0iPPRwPN5o0ag=="],
|
||||
|
||||
"tslib": ["[email protected]", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="],
|
||||
|
||||
"undici-types": ["[email protected]", "", {}, "sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA=="],
|
||||
|
||||
"@types/node/undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
# raea/ecs's world as wasm for a playable (docs/playables.feature PA12): runtime/ecs built for wasm32-unknown-unknown
|
||||
# as a cdylib, size-optimised (wasm-opt -Oz when it's here), into sdk/playable/src/host/ecs.wasm, with the hash of what
|
||||
# it was built from beside it (ecs.wasm.from). apps/playable's test fails when runtime/ecs changes and this isn't run.
|
||||
# usage: bash sdk/playable/ecs/build.sh [TARGET_DIR]
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "$0")/../../.." && pwd)
|
||||
target=${1:-$root/target}
|
||||
out=$root/sdk/playable/src/host
|
||||
cargo rustc --manifest-path "$root/Cargo.toml" -p raea-runtime-ecs --lib --crate-type cdylib --target wasm32-unknown-unknown \
|
||||
--profile release --target-dir "$target" \
|
||||
--config 'profile.release.opt-level="z"' --config 'profile.release.lto=true' --config 'profile.release.codegen-units=1' \
|
||||
--config 'profile.release.panic="abort"' --config 'profile.release.strip=true' --config 'profile.release.debug=false'
|
||||
wasm=$target/wasm32-unknown-unknown/release/raea_runtime_ecs.wasm
|
||||
if command -v wasm-opt > /dev/null; then wasm-opt -Oz --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext --enable-mutable-globals "$wasm" -o "$out/ecs.wasm"; else cp "$wasm" "$out/ecs.wasm"; fi
|
||||
bash "$root/sdk/playable/ecs/from.sh" > "$out/ecs.wasm.from"
|
||||
echo "ecs.wasm: $(wc -c < "$out/ecs.wasm" | tr -d ' ') bytes, $(gzip -9c "$out/ecs.wasm" | wc -c | tr -d ' ') gzipped"
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# what ecs.wasm is built from (build.sh): runtime/ecs's sources and manifest, and the Bevy it's on (Cargo.lock's line)
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "$0")/../../.." && pwd)
|
||||
{ cat "$root"/runtime/ecs/Cargo.toml "$root"/runtime/ecs/src/*.rs; grep -A1 '^name = "bevy_ecs"$' "$root/Cargo.lock"; } | shasum -a 256 | cut -c1-64
|
||||
@@ -15,7 +15,8 @@
|
||||
"react": "file:../raea/node_modules/react",
|
||||
"react-dom": "file:../raea/node_modules/react-dom",
|
||||
"scheduler": "file:../raea/node_modules/scheduler",
|
||||
"three": "0.180.0"
|
||||
"three": "0.180.0",
|
||||
"tone": "15.1.22"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.3",
|
||||
|
||||
@@ -1,22 +1,37 @@
|
||||
// `raea playable`'s lint, the part that renders (docs/playables.feature PA4): run by `raea run` on an entry that imports
|
||||
// the game first, so its compositions are registered. Each composition is rendered at 12 frames through its length,
|
||||
// and every 3D kind it draws is held to what the playable host draws (kinds.ts). Returns its shapes and the kinds.
|
||||
// and every 3D kind it draws is held to what the playable host draws (kinds.ts). Returns its shapes and the kinds, and
|
||||
// its sound (PA6): whether it plays a raea/tone graph or media, and every generated sound it describes, with what the
|
||||
// asset store makes it from (the native renderer's params: its seconds and the generator's settings, runtime/sound
|
||||
// generated_params), so the export makes each one and carries it in the page.
|
||||
import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { Clock, getCompositions } from "raea";
|
||||
import { describedAssets } from "@raea/asset/assets";
|
||||
import { PLAYABLE_KINDS } from "../host/kinds";
|
||||
|
||||
export default function walk() {
|
||||
const kinds: Record<string, number> = {};
|
||||
let tone = false;
|
||||
let media = false;
|
||||
const ToneOut = (globalThis as { __raeaToneOut?: () => unknown }).__raeaToneOut;
|
||||
const comps = getCompositions().map((c) => {
|
||||
const step = Math.max(1, Math.floor(c.durationInFrames / 12));
|
||||
for (let f = 0; f < c.durationInFrames; f += step) {
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(Clock, { frame: f, fps: c.fps, width: c.width, height: c.height, durationInFrames: c.durationInFrames }, createElement(c.component, c.defaultProps)),
|
||||
createElement(Clock, { frame: f, fps: c.fps, width: c.width, height: c.height, durationInFrames: c.durationInFrames }, createElement(c.component, c.defaultProps), ToneOut ? createElement(ToneOut as never) : null),
|
||||
);
|
||||
for (const m of html.matchAll(/data-3d="([A-Za-z0-9]+)"/g)) kinds[m[1]] = (kinds[m[1]] ?? 0) + 1;
|
||||
tone ||= html.includes("data-tone-");
|
||||
media ||= /<audio[^>]* src="/.test(html);
|
||||
}
|
||||
return { id: c.id, width: c.width, height: c.height, fps: c.fps, frames: c.durationInFrames };
|
||||
});
|
||||
return { comps, kinds: Object.keys(kinds), refused: Object.keys(kinds).filter((k) => !PLAYABLE_KINDS.has(k)) };
|
||||
const assets = [...describedAssets().values()].map((a) => {
|
||||
const params = { ...(a.options ?? {}), seconds: a.seconds };
|
||||
return { src: a.src, model: a.kind, prompt: a.prompt, seed: typeof a.options?.seed === "number" ? a.options.seed : 1, params };
|
||||
});
|
||||
// a raea/ecs World made (as the game's module loaded, or as it rendered): the page carries Bevy's world (PA12)
|
||||
const ecs = (globalThis as { __raeaEcsUsed?: boolean }).__raeaEcsUsed === true;
|
||||
return { comps, kinds: Object.keys(kinds), refused: Object.keys(kinds).filter((k) => !PLAYABLE_KINDS.has(k)), sound: { tone, media: media || assets.length > 0, assets }, ecs };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// What the host asks of whatever draws a playable's 3D (docs/playables.feature PA15): the export bundles a drawer
|
||||
// only when its lint found a 3D kind, so a 2D game's page carries no renderer at all.
|
||||
|
||||
/** One drawer on the stage's canvas, under the page */
|
||||
export interface Draw3d {
|
||||
/** The canvas sized to the composition, drawn at the screen's pixels (`scale` of the composition's) */
|
||||
fit(width: number, height: number, scale: number): void;
|
||||
/** The page's data-3d parts at this frame, read into the drawer's scene; true when there is any 3D to draw */
|
||||
sync(page: HTMLElement, seconds: number): boolean;
|
||||
/** Draws the scene synced last */
|
||||
draw(): void;
|
||||
}
|
||||
|
||||
/** Makes the drawer on the stage's canvas */
|
||||
export type MakeDraw3d = (canvas: HTMLCanvasElement) => Draw3d;
|
||||
@@ -0,0 +1,51 @@
|
||||
// raea/ecs's world in a playable (docs/playables.feature PA12): Bevy's own ECS (runtime/ecs, built to ecs.wasm by
|
||||
// sdk/playable/ecs/build.sh), which the export carries as __raeaEcsWasm for a game that makes a World. The entry
|
||||
// imports this before the game, so a World made as the game's module loads is already Bevy's. Calls go through
|
||||
// __raeaEcs as raea's V8 sends them through __raea_call (sdk/app native.ts ecsCall); a page where the module can't be
|
||||
// made keeps raea/ecs's TypeScript tables, which behave the same.
|
||||
|
||||
type Exports = {
|
||||
memory: WebAssembly.Memory;
|
||||
raea_alloc(len: number): number;
|
||||
raea_free(p: number, len: number): void;
|
||||
/** where the answer is: its address in the high 32 bits, its length in the low */
|
||||
raea_call(np: number, nl: number, ap: number, al: number): bigint;
|
||||
};
|
||||
|
||||
/** What ran, for tools/check.ts: the calls the world answered */
|
||||
export type EcsStats = { calls: number; bytes: number };
|
||||
|
||||
const g = globalThis as { __raeaEcsWasm?: string; __raeaEcs?: (name: string, json: string) => string; __raeaEcsStats?: EcsStats; __raea_call?: unknown };
|
||||
|
||||
if (g.__raeaEcsWasm && typeof g.__raea_call !== "function") {
|
||||
try {
|
||||
const s = atob(g.__raeaEcsWasm);
|
||||
const bin = new Uint8Array(s.length);
|
||||
for (let i = 0; i < s.length; i++) bin[i] = s.charCodeAt(i);
|
||||
// synchronous, as raea/ecs's calls are: WebKit compiles a module of any size on the page's thread
|
||||
const x = new WebAssembly.Instance(new WebAssembly.Module(bin), {}).exports as unknown as Exports;
|
||||
const enc = new TextEncoder();
|
||||
const dec = new TextDecoder();
|
||||
const stats: EcsStats = (g.__raeaEcsStats = { calls: 0, bytes: bin.length });
|
||||
const put = (text: string): [number, number] => {
|
||||
const b = enc.encode(text);
|
||||
const p = x.raea_alloc(b.length);
|
||||
new Uint8Array(x.memory.buffer, p, b.length).set(b);
|
||||
return [p, b.length];
|
||||
};
|
||||
g.__raeaEcs = (name, json) => {
|
||||
const [np, nl] = put(name);
|
||||
const [ap, al] = put(json);
|
||||
const at = x.raea_call(np, nl, ap, al);
|
||||
x.raea_free(np, nl);
|
||||
x.raea_free(ap, al);
|
||||
const out = dec.decode(new Uint8Array(x.memory.buffer, Number(at >> 32n), Number(at & 0xffffffffn)));
|
||||
stats.calls++;
|
||||
if (out[0] !== "o") throw new Error(`${name}: ${out.slice(1)}`);
|
||||
return out.slice(1);
|
||||
};
|
||||
} catch (e) {
|
||||
console.warn("raea playable: Bevy's world didn't load, so raea/ecs keeps its TypeScript tables", e);
|
||||
}
|
||||
}
|
||||
delete g.__raeaEcsWasm;
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
2e6fac7b3f0fba3852f43ff79bba2546e489eb6afabfb55c70dbe42828d4c72c
|
||||
@@ -1,5 +1,7 @@
|
||||
// A person's input as raea's FrameInput, in composition px: keys held, the primary pointer and every finger down.
|
||||
// The stage is the composition scaled uniformly into the screen, so each point is mapped back through its box.
|
||||
// A press is kept until a step has read it: the game steps at its fps (33 ms at 30), and a quick tap, or one on a phone
|
||||
// that drops frames, goes down and up between two steps, which a fold reading only what is held would never see.
|
||||
import type { FrameInput } from "raea";
|
||||
|
||||
/** window.addEventListener typed by the event's name (bun's globals type the bare addEventListener loosely) */
|
||||
@@ -11,6 +13,10 @@ export class Input {
|
||||
private keys = new Set<string>();
|
||||
private pointer?: { x: number; y: number; down: boolean };
|
||||
private touches = new Map<number, { x: number; y: number }>();
|
||||
/** pressed since the last step read the input: each finger where it last was, whether the pointer went down, keys */
|
||||
private unread = new Map<number, { x: number; y: number }>();
|
||||
private pressUnread = false;
|
||||
private keysUnread = new Set<string>();
|
||||
/** set on the first touch, click or key: networks keep sound off until then */
|
||||
touched = false;
|
||||
private firstTouch: (() => void)[] = [];
|
||||
@@ -31,11 +37,14 @@ export class Input {
|
||||
const p = at(e);
|
||||
this.pointer = { ...p, down: true };
|
||||
this.touches.set(e.pointerId, p);
|
||||
this.unread.set(e.pointerId, p);
|
||||
this.pressUnread = true;
|
||||
});
|
||||
on("pointermove", (e) => {
|
||||
const p = at(e);
|
||||
if (e.isPrimary) this.pointer = { ...p, down: this.pointer?.down ?? false };
|
||||
if (this.touches.has(e.pointerId)) this.touches.set(e.pointerId, p);
|
||||
if (this.unread.has(e.pointerId)) this.unread.set(e.pointerId, p);
|
||||
});
|
||||
const up = (e: PointerEvent) => {
|
||||
if (e.isPrimary && this.pointer) this.pointer = { ...this.pointer, down: false };
|
||||
@@ -46,6 +55,7 @@ export class Input {
|
||||
on("keydown", (e) => {
|
||||
first();
|
||||
this.keys.add(e.key);
|
||||
this.keysUnread.add(e.key);
|
||||
});
|
||||
on("keyup", (e) => this.keys.delete(e.key));
|
||||
on("blur", () => this.keys.clear());
|
||||
@@ -57,12 +67,19 @@ export class Input {
|
||||
else this.firstTouch.push(f);
|
||||
}
|
||||
|
||||
/** This frame's input, marked live (a person is playing: raea/games' fold reads it so) */
|
||||
/** This step's input, marked live (a person is playing: raea/games' fold reads it so). What went down since the last
|
||||
* step counts as held for this one, even if it is already up: the next step sees it let go. */
|
||||
now(): FrameInput & { live: true } {
|
||||
const keys = new Set([...this.keys, ...this.keysUnread]);
|
||||
const touches = new Map([...this.unread, ...this.touches]);
|
||||
const pointer = this.pointer && { ...this.pointer, down: this.pointer.down || this.pressUnread };
|
||||
this.unread.clear();
|
||||
this.pressUnread = false;
|
||||
this.keysUnread.clear();
|
||||
return {
|
||||
keys: [...this.keys],
|
||||
...(this.pointer ? { pointer: { ...this.pointer } } : {}),
|
||||
...(this.touches.size ? { touches: [...this.touches].map(([id, p]) => ({ id, ...p })) } : {}),
|
||||
keys: [...keys],
|
||||
...(pointer ? { pointer } : {}),
|
||||
...(touches.size ? { touches: [...touches].map(([id, p]) => ({ id, ...p })) } : {}),
|
||||
live: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
// The browser host a playable export runs a raea game in (docs/playables.feature PA1): the game's registered
|
||||
// composition (the one nearest the screen's shape, so a portrait and a landscape one can both ship) put on a stage
|
||||
// scaled uniformly into the screen, a Clock stepped 1/fps at a time off requestAnimationFrame with the person's input
|
||||
// recorded per frame, and its 3D drawn by three.js under the page. It starts when the network says the ad is
|
||||
// viewable, pauses while it isn't, and ends on the game's own EndCard or, at the composition's last frame, on one of
|
||||
// its own.
|
||||
// recorded per frame, and its 3D, if it has any, drawn under the page by the drawer the export bundled with it
|
||||
// (draw3d.ts; none for a 2D game, PA15), and its sound, if it has any, played after the first touch by the player the
|
||||
// export bundled (sound.ts, PA6). It starts when the network says the ad is viewable, pauses while it isn't,
|
||||
// and ends on the game's own EndCard or, at the composition's last frame, on one of its own.
|
||||
// The export's entry calls start(): `raea playable` (apps/playable) writes it after the game's import.
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import * as THREE from "three";
|
||||
import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea";
|
||||
import { EndCard } from "../cards";
|
||||
import { network, onAdEvent, whenReady } from "../network";
|
||||
import type { MakeDraw3d } from "./draw3d";
|
||||
import type { MakeSound } from "./sound";
|
||||
import { Input } from "./input";
|
||||
import { Scene3d } from "./scene";
|
||||
import { UNDER, backgroundUnder3d } from "@raea/r3f/three/page";
|
||||
import { Tonemap } from "./tonemap";
|
||||
|
||||
declare const __RAEA_PLAYABLE__: { title?: string; cta?: string } | undefined;
|
||||
const config = typeof __RAEA_PLAYABLE__ === "object" && __RAEA_PLAYABLE__ ? __RAEA_PLAYABLE__ : {};
|
||||
@@ -26,7 +27,7 @@ function pick(comps: RegisteredComposition[]): RegisteredComposition {
|
||||
|
||||
/** The 3D is drawn under the page, so the page elements holding it are cleared and the innermost solid background
|
||||
* among them becomes the 3D's clear colour, as the native engine shows the page's background behind the 3D. */
|
||||
function boot() {
|
||||
function boot(make3d?: MakeDraw3d, makeSound?: MakeSound) {
|
||||
const comps = getCompositions();
|
||||
if (!comps.length) throw new Error("raea playable: the game registered no composition (registerRoot)");
|
||||
// a still (tools/parity.ts): one composition at one frame, no one playing, as `raea render --frame` draws it
|
||||
@@ -43,12 +44,12 @@ function boot() {
|
||||
stage.append(canvas, page);
|
||||
document.body.append(stage);
|
||||
|
||||
// the 3D is tone-mapped by its own pass (antialiased in its target) and left transparent where nothing was drawn
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: true, premultipliedAlpha: true, powerPreference: "high-performance" });
|
||||
renderer.shadowMap.enabled = true;
|
||||
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
|
||||
const tonemap = new Tonemap(renderer);
|
||||
const scene = new Scene3d();
|
||||
const d3 = make3d?.(canvas);
|
||||
// a still is silent
|
||||
const sound = fixed ? undefined : makeSound?.();
|
||||
// raea/tone's graph and events, which the native entry renders beside the composition (runtime/bundle entry.rs)
|
||||
const ToneOut = (globalThis as { __raeaToneOut?: () => null }).__raeaToneOut;
|
||||
if (!d3) canvas.style.visibility = "hidden";
|
||||
|
||||
const layout = () => {
|
||||
if (comps.length > 1 && !fixed) comp = pick(comps);
|
||||
@@ -60,11 +61,7 @@ function boot() {
|
||||
top: `${(innerHeight - comp.height * s) / 2}px`,
|
||||
transform: `scale(${s})`,
|
||||
});
|
||||
// the canvas is drawn at the screen's pixels, not the composition's
|
||||
renderer.setPixelRatio(Math.min(2, devicePixelRatio || 1) * s);
|
||||
renderer.setSize(comp.width, comp.height, false);
|
||||
tonemap.resize();
|
||||
scene.fit(comp.width, comp.height);
|
||||
d3?.fit(comp.width, comp.height, s);
|
||||
};
|
||||
layout();
|
||||
addEventListener("resize", layout);
|
||||
@@ -89,28 +86,41 @@ function boot() {
|
||||
};
|
||||
onAdEvent((e) => {
|
||||
events.push(e.kind);
|
||||
if (e.kind === "end") over = true;
|
||||
if (e.kind === "end") {
|
||||
over = true;
|
||||
sound?.end();
|
||||
}
|
||||
tell(e.kind);
|
||||
});
|
||||
// the player took over from the game's own hand
|
||||
input.onFirstTouch(() => tell("touch"));
|
||||
input.onFirstTouch(() => {
|
||||
sound?.unlock();
|
||||
tell("touch");
|
||||
});
|
||||
|
||||
const draw = () => {
|
||||
// the page at this frame, and its sound
|
||||
const render = () => {
|
||||
const C = comp.component;
|
||||
flushSync(() =>
|
||||
root.render(
|
||||
<Clock frame={frame} fps={comp.fps} width={comp.width} height={comp.height} durationInFrames={comp.durationInFrames} input={timeline} defaultProps={comp.defaultProps}>
|
||||
<C {...comp.defaultProps} />
|
||||
{ToneOut ? <ToneOut /> : null}
|
||||
<EndCard show={timedOut} title={config.title} cta={config.cta} />
|
||||
</Clock>,
|
||||
),
|
||||
);
|
||||
scene.sync(page, frame / comp.fps);
|
||||
const clear = backgroundUnder3d(page);
|
||||
// the page's own background colour behind the 3D, untouched by the tone curve as natively
|
||||
stage.style.background = clear ?? "#000000";
|
||||
canvas.style.visibility = scene.any ? "visible" : "hidden";
|
||||
if (scene.any) tonemap.render(scene.scene, scene.camera);
|
||||
sound?.frame(page, frame / comp.fps);
|
||||
};
|
||||
const draw = () => {
|
||||
render();
|
||||
if (d3) {
|
||||
const any = d3.sync(page, frame / comp.fps);
|
||||
// the page's own background colour behind the 3D, untouched by the tone curve as natively
|
||||
stage.style.background = backgroundUnder3d(page) ?? "#000000";
|
||||
canvas.style.visibility = any ? "visible" : "hidden";
|
||||
if (any) d3.draw();
|
||||
}
|
||||
// a preview build says when its first frame was drawn (tools/check.ts reads it: startup on a slow phone)
|
||||
if (!firstDrawn && network === "preview") console.info(`raea playable: first frame at ${Math.round(performance.now())} ms`);
|
||||
firstDrawn = true;
|
||||
@@ -132,10 +142,14 @@ function boot() {
|
||||
timeline[frame] = input.now();
|
||||
if (frame + 1 >= comp.durationInFrames) {
|
||||
timedOut = true;
|
||||
sound?.end();
|
||||
break;
|
||||
}
|
||||
frame++;
|
||||
stepped = true;
|
||||
// a frame stepped past without being drawn (a slow phone): its page still renders when the game has sound, so an
|
||||
// <Sfx> that fires on it sounds
|
||||
if (sound && acc >= step && !over) render();
|
||||
}
|
||||
if (stepped || (timedOut && !shown)) {
|
||||
shown = timedOut;
|
||||
@@ -159,10 +173,15 @@ function boot() {
|
||||
(on) => {
|
||||
if (on !== visible) tell(on ? "viewable" : "hidden");
|
||||
visible = on;
|
||||
sound?.visible(on);
|
||||
},
|
||||
);
|
||||
requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") addEventListener("DOMContentLoaded", boot);
|
||||
else boot();
|
||||
/** Plays the registered game, its 3D drawn by `make3d` (none for a 2D game) and its sound by `makeSound` (none for a
|
||||
* silent one) */
|
||||
export function start(make3d?: MakeDraw3d, makeSound?: MakeSound) {
|
||||
if (document.readyState === "loading") addEventListener("DOMContentLoaded", () => boot(make3d, makeSound));
|
||||
else boot(make3d, makeSound);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
// A playable's sound (docs/playables.feature PA6): what the game's page holds each frame, played through Web Audio once
|
||||
// the person has touched the ad (networks keep sound off until then, and a browser won't start it before a gesture).
|
||||
// The page says it as the native renderer reads it: each <Audio> an <audio> element with its src, its source time,
|
||||
// volume, rate and loop (sdk/video media.tsx), and a raea/tone graph and the events due this frame as
|
||||
// <audio data-tone-graph> and <audio data-tone-evs> (sdk/audio tone/composition.tsx), which the export bundles a Tone.js
|
||||
// player for (tone.ts) only when the game has them. An imported file is in the page already (a data URL); a generated
|
||||
// one (asset:sao/..., asset:tokensynth/...) was made at export and is in __raeaSounds by its src.
|
||||
|
||||
/** One raea/tone event as the page writes it (sdk/audio tone/core.ts Ev) */
|
||||
export type ToneEv = { k: string; n: number; t: number; e: string; f?: number[]; d?: number; v?: number; o?: number; p?: string; val?: number; ramp?: number; curve?: string };
|
||||
|
||||
/** What plays a raea/tone graph (tone.ts): on its own context, which media share */
|
||||
export interface TonePlayer {
|
||||
context: AudioContext;
|
||||
/** The graph as the page writes it, again whenever it changes */
|
||||
graph(json: string): void;
|
||||
/** One event, at an AudioContext time */
|
||||
play(ev: ToneEv, when: number): void;
|
||||
/** Called in the first gesture: the context started */
|
||||
unlock(): void;
|
||||
}
|
||||
|
||||
export type MakeTone = (decode: (src: string) => Promise<AudioBuffer | null>) => TonePlayer;
|
||||
|
||||
export interface Sound {
|
||||
/** The page as just drawn, at the game's time in seconds */
|
||||
frame(page: HTMLElement, seconds: number): void;
|
||||
/** The first touch: sound may start */
|
||||
unlock(): void;
|
||||
/** The ad shown or hidden */
|
||||
visible(on: boolean): void;
|
||||
/** The game over: everything fades */
|
||||
end(): void;
|
||||
}
|
||||
|
||||
export type MakeSound = () => Sound;
|
||||
|
||||
/** What played, for tools/check.ts to read back: raea/tone events, clips started, files decoded and not */
|
||||
export type SoundStats = { events: number; clips: number; decoded: number; failed: number };
|
||||
|
||||
const sounds = (): Record<string, string> => (globalThis as { __raeaSounds?: Record<string, string> }).__raeaSounds ?? {};
|
||||
|
||||
/** A data URL's bytes */
|
||||
function bytes(url: string): ArrayBuffer | null {
|
||||
const at = url.indexOf(",");
|
||||
if (!url.startsWith("data:") || at < 0) return null;
|
||||
const body = url.slice(at + 1);
|
||||
if (!url.slice(0, at).endsWith(";base64")) return new TextEncoder().encode(decodeURIComponent(body)).buffer as ArrayBuffer;
|
||||
const s = atob(body);
|
||||
const out = new Uint8Array(s.length);
|
||||
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
|
||||
return out.buffer;
|
||||
}
|
||||
|
||||
/** One <Audio> playing: its source, its gain, and where it was asked to be */
|
||||
type Voice = { src: AudioBufferSourceNode | null; gain: GainNode; at: number; asked: number; started: boolean };
|
||||
|
||||
/** The page's sound, its raea/tone graph played by `makeTone` when the export bundled one */
|
||||
export function sound(makeTone?: MakeTone): MakeSound {
|
||||
return () => {
|
||||
// the page's <audio> elements describe sound for this player: the browser never loads them (an asset:... src isn't
|
||||
// a URL it can, and a data URL would be decoded twice)
|
||||
const make = document.createElement.bind(document);
|
||||
document.createElement = ((tag: string, o?: ElementCreationOptions) => {
|
||||
const el = make(tag, o);
|
||||
if (tag.toLowerCase() === "audio") (el as HTMLAudioElement).preload = "none";
|
||||
return el;
|
||||
}) as typeof document.createElement;
|
||||
const stats: SoundStats = ((globalThis as { __raeaSound?: SoundStats }).__raeaSound = { events: 0, clips: 0, decoded: 0, failed: 0 });
|
||||
const buffers = new Map<string, Promise<AudioBuffer | null>>();
|
||||
let ctx: AudioContext | null = null;
|
||||
const decode = (src: string): Promise<AudioBuffer | null> => {
|
||||
let b = buffers.get(src);
|
||||
if (!b) {
|
||||
const data = bytes(src.startsWith("data:") ? src : (sounds()[src] ?? ""));
|
||||
b =
|
||||
data && ctx
|
||||
? ctx.decodeAudioData(data).then(
|
||||
(d) => (stats.decoded++, d),
|
||||
(e) => (stats.failed++, console.warn(`raea playable: ${src.slice(0, 60)} doesn't decode`, e), null),
|
||||
)
|
||||
: Promise.resolve(null);
|
||||
if (!data) console.warn(`raea playable: no sound for ${src.slice(0, 60)} in the page`);
|
||||
buffers.set(src, b);
|
||||
}
|
||||
return b;
|
||||
};
|
||||
const tone = makeTone?.(decode);
|
||||
ctx = tone?.context ?? new AudioContext();
|
||||
const c = ctx;
|
||||
const voices = new Map<string, Voice>();
|
||||
const heard = new Set<string>();
|
||||
let unlocked = false;
|
||||
let shown = true;
|
||||
let over = false;
|
||||
let graph = "";
|
||||
|
||||
// a browser starts sound only inside a gesture, and WebKit counts the end of a touch, not its start: every gesture
|
||||
// tries until the context runs
|
||||
const resume = () => {
|
||||
if (unlocked && shown && c.state !== "running") void c.resume();
|
||||
};
|
||||
for (const e of ["pointerup", "touchend", "click", "keydown"]) addEventListener(e, resume, { passive: true });
|
||||
|
||||
const start = (key: string, v: Voice, el: HTMLElement) => {
|
||||
const src = el.getAttribute("src") ?? "";
|
||||
v.started = true;
|
||||
void decode(src).then((buf) => {
|
||||
if (!buf || voices.get(key) !== v || over) return;
|
||||
const s = c.createBufferSource();
|
||||
s.buffer = buf;
|
||||
s.loop = el.dataset.loop === "true";
|
||||
s.playbackRate.value = Number(el.dataset.playbackRate ?? 1) || 1;
|
||||
s.connect(v.gain);
|
||||
// where it is now: its source time when asked, plus what has played since
|
||||
const offset = v.at + (c.currentTime - v.asked) * s.playbackRate.value;
|
||||
s.start(0, s.loop ? offset % buf.duration : Math.min(offset, buf.duration));
|
||||
v.src = s;
|
||||
stats.clips++;
|
||||
});
|
||||
};
|
||||
const stop = (v: Voice) => {
|
||||
v.gain.gain.setTargetAtTime(0, c.currentTime, 0.005);
|
||||
v.src?.stop(c.currentTime + 0.05);
|
||||
};
|
||||
|
||||
return {
|
||||
frame(page, seconds) {
|
||||
if (over) return;
|
||||
const g = page.querySelector<HTMLElement>("audio[data-tone-graph]")?.dataset.toneGraph;
|
||||
if (tone && g && g !== graph) {
|
||||
graph = g;
|
||||
tone.graph(g);
|
||||
}
|
||||
if (!unlocked || c.state !== "running") return;
|
||||
// the raea/tone events due: the page shows each for a few frames, played once, as late as the frame allows
|
||||
if (tone)
|
||||
for (const el of page.querySelectorAll<HTMLElement>("audio[data-tone-evs]"))
|
||||
for (const ev of JSON.parse(el.dataset.toneEvs ?? "[]") as ToneEv[]) {
|
||||
if (heard.has(ev.k)) continue;
|
||||
heard.add(ev.k);
|
||||
stats.events++;
|
||||
tone.play(ev, c.currentTime + 0.01 + Math.max(0, ev.t - seconds));
|
||||
}
|
||||
if (heard.size > 4096) for (const k of [...heard].slice(0, 2048)) heard.delete(k);
|
||||
// each <Audio> on the page: one voice a clip (its src, the frame it starts on, its name)
|
||||
const here = new Set<string>();
|
||||
for (const el of page.querySelectorAll<HTMLElement>("audio[src]")) {
|
||||
const key = `${el.getAttribute("src")}|${el.dataset.from ?? ""}|${el.dataset.name ?? ""}`;
|
||||
here.add(key);
|
||||
const vol = el.dataset.ended === "true" ? 0 : Math.max(0, Number(el.dataset.volume ?? 1));
|
||||
let v = voices.get(key);
|
||||
if (!v) {
|
||||
const gain = c.createGain();
|
||||
gain.gain.value = vol;
|
||||
gain.connect(c.destination);
|
||||
v = { src: null, gain, at: 0, asked: 0, started: false };
|
||||
voices.set(key, v);
|
||||
}
|
||||
// until it plays (its file decoding), where the page last asked it to be
|
||||
if (!v.src) {
|
||||
v.at = Number(el.dataset.sourceTime ?? 0);
|
||||
v.asked = c.currentTime;
|
||||
}
|
||||
v.gain.gain.setTargetAtTime(vol, c.currentTime, 0.01);
|
||||
if (!v.started && el.dataset.ended !== "true") start(key, v, el);
|
||||
}
|
||||
for (const [key, v] of voices)
|
||||
if (!here.has(key)) {
|
||||
stop(v);
|
||||
voices.delete(key);
|
||||
}
|
||||
},
|
||||
unlock() {
|
||||
unlocked = true;
|
||||
tone?.unlock();
|
||||
resume();
|
||||
},
|
||||
visible(on) {
|
||||
shown = on;
|
||||
if (!on) void c.suspend();
|
||||
else resume();
|
||||
},
|
||||
end() {
|
||||
over = true;
|
||||
for (const v of voices.values()) {
|
||||
v.gain.gain.setTargetAtTime(0, c.currentTime, 0.15);
|
||||
v.src?.stop(c.currentTime + 1);
|
||||
}
|
||||
voices.clear();
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// A playable's 3D drawn by three.js (raea's three.js host, sdk/r3f/src/three, through scene.ts), tone-mapped by
|
||||
// Bevy's own curve (tonemap.ts). The export bundles it only for a game whose lint found a 3D kind (PA15).
|
||||
import * as THREE from "three";
|
||||
import type { Draw3d } from "./draw3d";
|
||||
import { Scene3d } from "./scene";
|
||||
import { Tonemap } from "./tonemap";
|
||||
|
||||
export function three3d(canvas: HTMLCanvasElement): Draw3d {
|
||||
// the 3D is tone-mapped by its own pass (antialiased in its target) and left transparent where nothing was drawn
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: true, premultipliedAlpha: true, powerPreference: "high-performance" });
|
||||
renderer.shadowMap.enabled = true;
|
||||
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
|
||||
const tonemap = new Tonemap(renderer);
|
||||
const scene = new Scene3d();
|
||||
return {
|
||||
fit(width, height, scale) {
|
||||
// the canvas is drawn at the screen's pixels, not the composition's
|
||||
renderer.setPixelRatio(Math.min(2, devicePixelRatio || 1) * scale);
|
||||
renderer.setSize(width, height, false);
|
||||
tonemap.resize();
|
||||
scene.fit(width, height);
|
||||
},
|
||||
sync(page, seconds) {
|
||||
scene.sync(page, seconds);
|
||||
return scene.any;
|
||||
},
|
||||
draw() {
|
||||
tonemap.render(scene.scene, scene.camera);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
// A playable's raea/tone graph played by Tone.js (docs/playables.feature PA6). raea/tone (sdk/audio tone/) is Tone's
|
||||
// API: each node in its graph is a Tone class by name with Tone's options, so the page's graph is built here from
|
||||
// Tone itself, and each event the page shows is the call that made it (an attack, a release, a param ramp, a player's
|
||||
// start). The export bundles this only for a game with a graph; Tone.js comes from the project's node_modules
|
||||
// (`raea add [email protected]`) as three.js does. A generated sample (TokenSynth's notes, SAO) was made at export: its
|
||||
// src is the one raea/asset gives the same description, and the page carries it (sound.ts).
|
||||
import * as Tone from "tone";
|
||||
import { lyria, sao, tokensynthNote } from "@raea/asset/assets";
|
||||
import type { MakeTone, ToneEv } from "./sound";
|
||||
|
||||
type Spec = { id: number; kind: string; options: Record<string, any>; name?: string };
|
||||
type Graph = { nodes: Spec[]; edges: [number, number, number][]; mods: [number, number, string][] };
|
||||
|
||||
/** A file as raea/tone wrote it (instruments.ts src): a path, or a generated sound's description */
|
||||
function srcOf(u: unknown): string | null {
|
||||
if (typeof u === "string") return u;
|
||||
if (!u || typeof u !== "object") return null;
|
||||
const g = u as { generate?: string; prompt?: string; seconds?: number; midi?: number; velocity?: number; seed?: number; precision?: any };
|
||||
if (!g.prompt) return null;
|
||||
if (g.generate === "tokensynth") return tokensynthNote(g.prompt, g.midi ?? 60, { seconds: g.seconds, velocity: g.velocity, seed: g.seed, precision: g.precision }).src;
|
||||
if (g.generate === "sao") return sao(g.prompt, { seconds: g.seconds }).src;
|
||||
if (g.generate === "lyria") return lyria(g.prompt, { seconds: g.seconds }).src;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The instruments Tone's PolySynth takes as its voice (its Monophonic ones, which Tone doesn't export as a class) */
|
||||
const VOICES = new Set(["Synth", "MonoSynth", "FMSynth", "AMSynth", "DuoSynth", "MembraneSynth", "MetalSynth"]);
|
||||
|
||||
/** raea's own option names, which Tone's constructors don't take */
|
||||
function toneOptions(o: Record<string, any>): Record<string, any> {
|
||||
const { poly: _p, maxPolyphony: _m, urls: _u, url: _l, baseUrl: _b, ...rest } = o;
|
||||
return rest;
|
||||
}
|
||||
|
||||
/** One node of the graph: what connects into it, what it connects from, and how an event plays on it */
|
||||
interface Node {
|
||||
input: Tone.ToneAudioNode | Tone.Param<any> | Tone.Signal<any>;
|
||||
output: Tone.ToneAudioNode;
|
||||
inst?: any;
|
||||
poly?: boolean;
|
||||
/** a Player's file, and the players started from it */
|
||||
buffer?: Tone.ToneAudioBuffer;
|
||||
players?: Tone.Player[];
|
||||
}
|
||||
|
||||
export const tone: MakeTone = (decode) => {
|
||||
const context = Tone.getContext().rawContext as unknown as AudioContext;
|
||||
let nodes = new Map<number, Node>();
|
||||
let built: Tone.ToneAudioNode[] = [];
|
||||
|
||||
const make = (s: Spec): Node => {
|
||||
const o = s.options ?? {};
|
||||
const T = (Tone as any)[s.kind];
|
||||
if (s.kind === "Player") {
|
||||
const out = new Tone.Volume(o.volume ?? 0);
|
||||
const n: Node = { input: out, output: out, players: [] };
|
||||
const src = srcOf(o.url);
|
||||
if (src) void decode(src).then((b) => b && (n.buffer = new Tone.ToneAudioBuffer(b)));
|
||||
return n;
|
||||
}
|
||||
if (s.kind === "Sampler") {
|
||||
// its samples are decoded first (a data URL fetched would be a request some networks block), then it's made
|
||||
const out = new Tone.Volume(o.volume ?? 0);
|
||||
const n: Node = { input: out, output: out, poly: true };
|
||||
const entries = Object.entries((o.urls ?? {}) as Record<string, unknown>);
|
||||
void Promise.all(entries.map(([, u]) => (srcOf(u) ? decode(srcOf(u)!) : Promise.resolve(null)))).then((bufs) => {
|
||||
const urls: Record<number, Tone.ToneAudioBuffer> = {};
|
||||
bufs.forEach((b, i) => b && (urls[Number(entries[i][0])] = new Tone.ToneAudioBuffer(b)));
|
||||
const s2 = new Tone.Sampler({ urls, attack: o.attack ?? 0, release: o.release ?? 0.1, curve: o.curve ?? "exponential" }).connect(out);
|
||||
built.push(s2);
|
||||
n.inst = s2;
|
||||
});
|
||||
return n;
|
||||
}
|
||||
if (typeof T !== "function") {
|
||||
console.warn(`raea playable: Tone has no ${s.kind}; it passes its input through`);
|
||||
const g = new Tone.Gain(1);
|
||||
return { input: g, output: g };
|
||||
}
|
||||
const opts = toneOptions(o);
|
||||
if (o.poly && VOICES.has(s.kind)) {
|
||||
const p = new Tone.PolySynth(T, opts);
|
||||
p.maxPolyphony = o.maxPolyphony ?? 32;
|
||||
return { input: p, output: p, inst: p, poly: true };
|
||||
}
|
||||
const n = new T(opts);
|
||||
const instrument = typeof n.triggerAttack === "function";
|
||||
// an LFO and Tone's moving effects (Chorus, Tremolo, AutoFilter, ...) run only once started
|
||||
if (!instrument && typeof n.start === "function") n.start();
|
||||
return { input: n, output: n, inst: instrument ? n : undefined };
|
||||
};
|
||||
|
||||
return {
|
||||
context,
|
||||
graph(json) {
|
||||
const g = JSON.parse(json) as Graph;
|
||||
for (const n of built) n.dispose();
|
||||
built = [];
|
||||
nodes = new Map();
|
||||
const dest = Tone.getDestination();
|
||||
for (const s of g.nodes) {
|
||||
if (s.id === 0) {
|
||||
dest.volume.value = s.options?.volume ?? 0;
|
||||
dest.mute = !!s.options?.mute;
|
||||
nodes.set(0, { input: dest, output: dest });
|
||||
continue;
|
||||
}
|
||||
const n = make(s);
|
||||
nodes.set(s.id, n);
|
||||
if (n.output !== dest) built.push(n.output);
|
||||
}
|
||||
for (const [a, b] of g.edges) {
|
||||
const from = nodes.get(a)?.output;
|
||||
const to = nodes.get(b)?.input;
|
||||
if (from && to) from.connect(to as Tone.InputNode);
|
||||
}
|
||||
// an LFO moving a parameter: [lfo, node, parameter]
|
||||
for (const [lfo, node, param] of g.mods) {
|
||||
const from = nodes.get(lfo)?.output;
|
||||
const target = (nodes.get(node)?.inst ?? nodes.get(node)?.output) as any;
|
||||
if (from && target?.[param]) from.connect(target[param]);
|
||||
}
|
||||
},
|
||||
play(ev: ToneEv, when: number) {
|
||||
const n = nodes.get(ev.n);
|
||||
if (!n) return;
|
||||
const at = Math.max(when, Tone.now());
|
||||
const f = ev.f ?? [];
|
||||
const noise = n.inst instanceof Tone.NoiseSynth;
|
||||
try {
|
||||
switch (ev.e) {
|
||||
case "a":
|
||||
if (noise) n.inst.triggerAttack(at, ev.v ?? 1);
|
||||
else n.inst?.triggerAttack(n.poly ? f : f[0], at, ev.v ?? 1);
|
||||
break;
|
||||
case "r":
|
||||
n.inst?.triggerRelease(n.poly ? f : at, n.poly ? at : undefined);
|
||||
break;
|
||||
case "ra":
|
||||
if (n.poly) n.inst?.releaseAll(at);
|
||||
else n.inst?.triggerRelease(at);
|
||||
break;
|
||||
case "ar":
|
||||
if (noise) n.inst.triggerAttackRelease(ev.d ?? 0.1, at, ev.v ?? 1);
|
||||
else n.inst?.triggerAttackRelease(n.poly ? f : f[0], ev.d ?? 0.1, at, ev.v ?? 1);
|
||||
break;
|
||||
case "start": {
|
||||
if (!n.buffer) break;
|
||||
const p = new Tone.Player(n.buffer).connect(n.output);
|
||||
n.players!.push(p);
|
||||
p.onstop = () => {
|
||||
n.players = n.players!.filter((x) => x !== p);
|
||||
p.dispose();
|
||||
};
|
||||
p.start(at, ev.o ?? 0, ev.d);
|
||||
break;
|
||||
}
|
||||
case "stop":
|
||||
for (const p of n.players ?? []) p.stop(at);
|
||||
break;
|
||||
case "param": {
|
||||
const target = (n.inst ?? n.output) as any;
|
||||
const p = ev.p ?? "";
|
||||
if (p === "mute") target.mute = (ev.val ?? 0) > 0;
|
||||
else if (target[p] && typeof target[p].setValueAtTime === "function") {
|
||||
const param = target[p] as Tone.Param<any>;
|
||||
if (ev.ramp && ev.ramp > 0) {
|
||||
if (ev.curve === "exp") param.exponentialRampTo(ev.val ?? 0, ev.ramp, at);
|
||||
else param.linearRampTo(ev.val ?? 0, ev.ramp, at);
|
||||
} else param.setValueAtTime(ev.val ?? 0, at);
|
||||
} else target.set?.({ [p]: ev.val });
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(`raea playable: a ${ev.e} on ${ev.n} didn't play`, e);
|
||||
}
|
||||
},
|
||||
unlock() {
|
||||
void Tone.start();
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -3,6 +3,10 @@
|
||||
// exceptions and any network request it tried read back, and screenshots saved.
|
||||
// `bun tools/check.ts PAGE.html OUT_DIR [WxH]`; exits 1 on a page error, a request, or a page that never drew.
|
||||
// PLAY_SECONDS=N plays on, then taps the end card (and the check fails if no install event came back).
|
||||
// TAP_MS=N holds each tap N ms (150 by default); TAP_MS=0 presses and lets go at once, as a quick finger and
|
||||
// Playwright's own tap() do, which a host that samples input once a frame must still see (PA20, raea #310).
|
||||
// A game with sound reports what played after the first touch (PA6), and fails if a sound didn't decode or, played
|
||||
// on with PLAY_SECONDS, nothing sounded.
|
||||
// WebKit, not Chrome: iOS ad WebViews are WebKit, and raea doesn't test in Chrome.
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
@@ -51,13 +55,19 @@ await press("up", W * 0.7, H * 0.75);
|
||||
await shot("1-played");
|
||||
await p.waitForTimeout(2500);
|
||||
await shot("2-later");
|
||||
// a tap in play, then the end card's, each held TAP_MS
|
||||
const hold = Number(process.env.TAP_MS ?? 150);
|
||||
const tap = async (x: number, y: number) => {
|
||||
await press("down", x, y);
|
||||
if (hold > 0) await p.waitForTimeout(hold);
|
||||
await press("up", x, y);
|
||||
};
|
||||
await tap(W / 2, H * 0.6);
|
||||
const more = Number(process.env.PLAY_SECONDS ?? 0);
|
||||
if (more > 0) {
|
||||
await p.waitForTimeout(more * 1000);
|
||||
await shot("3-end");
|
||||
await press("down", W / 2, H / 2);
|
||||
await p.waitForTimeout(150);
|
||||
await press("up", W / 2, H / 2);
|
||||
await tap(W / 2, H / 2);
|
||||
await p.waitForTimeout(300);
|
||||
}
|
||||
|
||||
@@ -66,10 +76,16 @@ const state = (await p.evaluate(() => ({
|
||||
parts: document.querySelectorAll("[data-3d]").length,
|
||||
page: document.querySelector("#raea-page")?.childElementCount ?? 0,
|
||||
events: (globalThis as { __raeaAdEvents?: unknown[] }).__raeaAdEvents ?? [],
|
||||
}))) as { canvas: boolean; parts: number; page: number; events: unknown[] };
|
||||
// a game with sound (PA6): what played after the first touch (host/sound.ts)
|
||||
sound: (globalThis as { __raeaSound?: { events: number; clips: number; decoded: number; failed: number } }).__raeaSound ?? null,
|
||||
// a game on raea/ecs: the calls Bevy's world (the page's wasm) answered (PA12)
|
||||
ecs: (globalThis as { __raeaEcsStats?: { calls: number; bytes: number } }).__raeaEcsStats ?? null,
|
||||
}))) as { canvas: boolean; parts: number; page: number; events: unknown[]; sound: { events: number; clips: number; decoded: number; failed: number } | null; ecs: { calls: number; bytes: number } | null };
|
||||
console.log(`page: ${JSON.stringify(state)}`);
|
||||
if (!state.page && !state.parts) problems.push("nothing drew: the game's page is empty");
|
||||
if (more > 0 && !JSON.stringify(state.events).includes("install")) problems.push("the end card was tapped but no install event came back");
|
||||
if (state.sound?.failed) problems.push(`${state.sound.failed} of the page's sounds didn't decode`);
|
||||
if (state.sound && more > 0 && !state.sound.events && !state.sound.clips) problems.push("the game has sound but nothing played after the first touch");
|
||||
for (const l of logs) console.log(l);
|
||||
for (const pr of problems) console.log(`PROBLEM: ${pr}`);
|
||||
await browser.close();
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// raea/ecs on a playable's Bevy world (docs/playables.feature PA12): the world the page carries as wasm (sdk/playable
|
||||
// host/ecs.ts, runtime/ecs built by sdk/playable/ecs/build.sh) answers a world's life as raea/ecs's TypeScript tables
|
||||
// do: spawns, queries, columns, parents, scene(), resources, events, copies stepped on their own and at(frame).
|
||||
// Each run is its own process, so the page's bridge never reaches another test.
|
||||
import { expect, test } from "bun:test";
|
||||
import { join } from "node:path";
|
||||
|
||||
const run = (wasm: boolean) => {
|
||||
const r = Bun.spawnSync([process.execPath, join(import.meta.dir, "ecs-wasm/run.ts")], { env: { ...process.env, WASM: wasm ? "1" : "0" }, stderr: "pipe" });
|
||||
expect(r.stderr.toString()).not.toMatch(/didn't load|Error/);
|
||||
expect(r.exitCode).toBe(0);
|
||||
return JSON.parse(r.stdout.toString()) as Record<string, unknown>;
|
||||
};
|
||||
|
||||
test("a playable's Bevy world (wasm) and raea/ecs's TypeScript tables live the same life", () => {
|
||||
const bevy = run(true);
|
||||
const ts = run(false);
|
||||
expect(bevy.native).toBe(true);
|
||||
expect(ts.native).toBe(false);
|
||||
const { native: _a, ...b } = bevy;
|
||||
const { native: _b, ...t } = ts;
|
||||
expect(b).toEqual(t);
|
||||
expect(b.after).toEqual({ score: 12, stars: 0, first: 12, caught: 12, basket: { id: expect.any(Number), kind: "basket", x: 0 } });
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
// One world's life, printed as JSON: on a playable's Bevy world (the page's ecs.wasm, loaded as its host loads it)
|
||||
// when run with WASM=1, else on raea/ecs's TypeScript tables. ecs-wasm.test.ts runs it both ways and compares.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
if (process.env.WASM === "1") {
|
||||
(globalThis as { __raeaEcsWasm?: string }).__raeaEcsWasm = readFileSync(join(import.meta.dir, "../../../playable/src/host/ecs.wasm")).toString("base64");
|
||||
await import("../../../playable/src/host/ecs.ts");
|
||||
}
|
||||
const { createWorld } = await import("raea/ecs");
|
||||
|
||||
const w = createWorld();
|
||||
const out: Record<string, unknown> = { native: w.native };
|
||||
for (let i = 0; i < 12; i++) w.spawn("star", { x: i - 6, y: 10 + (i % 3), side: i % 2 ? "odd" : "even" });
|
||||
const basket = w.spawn("basket", { x: 0 });
|
||||
w.resource("score", 0);
|
||||
w.system((world, f) => {
|
||||
for (const id of world.query("star")) {
|
||||
const y = (world.get(id).y as number) - 1;
|
||||
if (y < 0) {
|
||||
world.despawn(id);
|
||||
world.resource("score", (world.resource<number>("score") ?? 0) + 1);
|
||||
world.send("caught", { id, f });
|
||||
} else world.set(id, { y });
|
||||
}
|
||||
});
|
||||
out.query = w.query("star", [["side", "==", "odd"], ["x", ">", -3]]);
|
||||
out.column = w.column("star", "y");
|
||||
const parent = w.add({ Transform: { x: 1, y: 0, z: 0 }, Mesh: { shape: "box" } });
|
||||
const child = w.add({ Transform: { x: 0, y: 2, z: 0 }, Mesh: { shape: "ball" } }, { parent });
|
||||
out.children = w.children(parent).length === 1 && w.parent(child) === parent;
|
||||
out.find = w.find({ with: ["Mesh"], where: [["Transform.y", ">", 1]] }).length;
|
||||
out.scene = w.scene();
|
||||
// a game's next state: copied, stepped on its own, the first left as it was
|
||||
let s = w;
|
||||
const caught: unknown[] = [];
|
||||
for (let f = 0; f < 14; f++) {
|
||||
s = s.copy();
|
||||
s.step(f);
|
||||
caught.push(...s.events("caught"));
|
||||
}
|
||||
out.after = { score: s.resource("score"), stars: s.count("star"), first: w.count("star"), caught: caught.length, basket: s.get(basket) };
|
||||
out.at = w.at(11).resource("score");
|
||||
console.log(JSON.stringify(out));
|
||||
@@ -0,0 +1,317 @@
|
||||
// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.
|
||||
import type { Beat } from "./brief.gen";
|
||||
|
||||
export type Goal = { kind: GoalKind,
|
||||
/**
|
||||
* how the plan, the report and other goals' `after` name it ([a-z0-9_]); the kind when left out
|
||||
*/
|
||||
name?: string,
|
||||
/**
|
||||
* the workflow step it serves, by the workflow's name for it (`edit`, `deliver`)
|
||||
*/
|
||||
step?: string,
|
||||
/**
|
||||
* the goals that must be done before this one starts, by name
|
||||
*/
|
||||
after?: Array<string>,
|
||||
/**
|
||||
* what the goal is, in the person's words
|
||||
*/
|
||||
aim?: string,
|
||||
/**
|
||||
* what must hold before the agent may stop, beside the kind's packs: each checked in code or by a fresh critic
|
||||
*/
|
||||
rules?: Array<GoalRule>,
|
||||
/**
|
||||
* the pictures the job answers to (paths beside the brief): what is in it and where for a scene, the style for a kit
|
||||
*/
|
||||
references?: Array<string>,
|
||||
/**
|
||||
* one paragraph every reference prompt carries: era, palette, materials, wear, and one fictional maker
|
||||
*/
|
||||
style?: string,
|
||||
/**
|
||||
* by name, from the kind's set (DIALS); one left out is read from the references
|
||||
*/
|
||||
dials?: { [key in string]: GoalDial }, objects?: Array<GoalObject>, shots?: Array<GoalShot>,
|
||||
/**
|
||||
* the compositions the job's checks hold (relative to the brief): each needs a clean render or check newer than it
|
||||
*/
|
||||
compositions?: Array<string>,
|
||||
/**
|
||||
* what must exist when it's done, relative to the brief; replaces the kind's own list (`deliverables`)
|
||||
*/
|
||||
deliverables?: Array<string>,
|
||||
/**
|
||||
* the most critic rounds the job gets; at the cap it is delivered with what's still missing (8 by default)
|
||||
*/
|
||||
rounds?: number,
|
||||
/**
|
||||
* a cut job's contract: the brief as rules (cut.rs)
|
||||
*/
|
||||
cut?: CutGoal,
|
||||
/**
|
||||
* a playable job's game, networks and orientation (playable.rs)
|
||||
*/
|
||||
playable?: PlayableGoal,
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
previews?: Array<string>,
|
||||
/**
|
||||
* raea's packs switched by name over the kind's defaults (`{ surprise: true, place: false }`): which of
|
||||
* raea/goal's rules hold this goal (docs/goal.feature)
|
||||
*/
|
||||
packs?: { [key in string]: boolean },
|
||||
/**
|
||||
* the project's own checks (raea/check `check()`, imported into brief.ts), run by `raea goal check`; as data, only
|
||||
* their declarations (id, text, over, at) reach Rust
|
||||
*/
|
||||
checks?: Array<unknown>, };
|
||||
|
||||
export type GoalKind = "scene" | "kit" | "shot" | "cut" | "rules" | "playable";
|
||||
|
||||
export type GoalSource = "customer" | "reference";
|
||||
|
||||
export type GoalDialValue = number | string;
|
||||
|
||||
export type GoalDial = GoalDialValue | { value: GoalDialValue, source?: GoalSource,
|
||||
/**
|
||||
* what the value meant for this job, in one line
|
||||
*/
|
||||
means?: string, };
|
||||
|
||||
export type GoalRoute = "solid" | "rule" | "gen" | "library" | "picture";
|
||||
|
||||
export type GoalOrigin = "reference" | "invented";
|
||||
|
||||
export type GoalPick = {
|
||||
/**
|
||||
* "tripo-h31", "meshy", ...
|
||||
*/
|
||||
generator: string,
|
||||
/**
|
||||
* one line: why this one ("sharper dial numerals; Tripo fused the handset to the cradle")
|
||||
*/
|
||||
why: string, };
|
||||
|
||||
export type GoalObject = {
|
||||
/**
|
||||
* snake_case, unique in the job
|
||||
*/
|
||||
id: string, label: string,
|
||||
/**
|
||||
* real height in metres
|
||||
*/
|
||||
h?: number,
|
||||
/**
|
||||
* [width, depth, height] in metres, for boxy things (generators invent depth)
|
||||
*/
|
||||
dims?: [number, number, number],
|
||||
/**
|
||||
* largest extent in metres, for things that lie flat (tools, papers)
|
||||
*/
|
||||
max?: number, route?: GoalRoute,
|
||||
/**
|
||||
* one object, its condition and its materials; never a real brand
|
||||
*/
|
||||
prompt?: string, source?: GoalOrigin,
|
||||
/**
|
||||
* where it is in reference 0: [x0, y0, x1, y1] in 0..1
|
||||
*/
|
||||
crop?: [number, number, number, number],
|
||||
/**
|
||||
* where it stands in a scene: metres, the floor's front-left corner at the origin, rot 0 = facing the entrance
|
||||
*/
|
||||
at?: [number, number, number], rot?: number, hero?: boolean,
|
||||
/**
|
||||
* how large it is planned to be seen, which is how much of it gets built: 0 the hero (half the frame or more),
|
||||
* 1 featured (under 50%), 2 dressing (under 20%), 3 background (under 8%: a grey box reads), 4 far (under 2%: a
|
||||
* silhouette). A render that shows it finer than this says so (`lod-closer`; `raea scene lod` lists every part)
|
||||
*/
|
||||
lod?: number, pick?: GoalPick,
|
||||
/**
|
||||
* what was fixed by script ("glass made transmissive, label kept opaque")
|
||||
*/
|
||||
fixes?: Array<string>, };
|
||||
|
||||
export type GoalShot = {
|
||||
/**
|
||||
* [a-z0-9_]: the file it lands as (out/shots/<name>.png or .mp4)
|
||||
*/
|
||||
name: string,
|
||||
/**
|
||||
* in a crew's words: "slow push along the counter, rack focus to the register"
|
||||
*/
|
||||
description?: string,
|
||||
/**
|
||||
* static, dolly, truck, pedestal, crane, pan, tilt, orbit, dollyZoom, path
|
||||
*/
|
||||
move?: string, seconds?: number, lens?: number,
|
||||
/**
|
||||
* none, subtle, walk
|
||||
*/
|
||||
handheld?: string,
|
||||
/**
|
||||
* a still rather than a move
|
||||
*/
|
||||
still?: boolean,
|
||||
/**
|
||||
* the composition that renders it (relative to the brief): `raea make shots` draws its framing sheet and lens chart
|
||||
*/
|
||||
composition?: string,
|
||||
/**
|
||||
* its frame rate, for the frames `seconds` spans (30 when left out)
|
||||
*/
|
||||
fps?: number, };
|
||||
|
||||
export type Goals = Goal | Array<Goal>;
|
||||
|
||||
export type CutGoal = {
|
||||
/**
|
||||
* the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf media/brief.txt`): every `from` is found in it
|
||||
*/
|
||||
brief: string,
|
||||
/**
|
||||
* how many cuts the brief asks for; fewer planned is held open until an answered `open` item about "count" says why
|
||||
*/
|
||||
count?: Quoted<number>,
|
||||
/**
|
||||
* a cut's length when its own `seconds` says none: [least, most]
|
||||
*/
|
||||
seconds?: [number, number],
|
||||
/**
|
||||
* the formats every cut is delivered in when its own `formats` says none: "9:16", "16:9", "1:1", "4:5"
|
||||
*/
|
||||
formats?: Array<string>, cuts?: Array<CutPlan>,
|
||||
/**
|
||||
* what is said or shown: in every cut unless `every: false` (then in one or more)
|
||||
*/
|
||||
say?: Array<Phrase>,
|
||||
/**
|
||||
* what no cut says or shows: a banned claim, a word, a name
|
||||
*/
|
||||
never?: Array<Phrase>,
|
||||
/**
|
||||
* the line every cut ends on, heard or on screen in its last `within` seconds
|
||||
*/
|
||||
cta?: Cta,
|
||||
/**
|
||||
* the brief's open items ([TO CONFIRM]): each holds the job open until it has an answer
|
||||
*/
|
||||
open?: Array<CutOpen>,
|
||||
/**
|
||||
* every face whole and every text big enough, by the frames check of each file (true when left out)
|
||||
*/
|
||||
frames?: boolean, };
|
||||
|
||||
export type Quoted<T> = { value: T,
|
||||
/**
|
||||
* the brief's own words, as they are in its text
|
||||
*/
|
||||
from: string, };
|
||||
|
||||
export type CutPlan = {
|
||||
/**
|
||||
* [a-z0-9_], unique: each format lands as out/cuts/<id>_<W>x<H>.mp4 ("a1_s1_9x16.mp4")
|
||||
*/
|
||||
id: string, angle?: string,
|
||||
/**
|
||||
* solo or mashup
|
||||
*/
|
||||
kind?: string,
|
||||
/**
|
||||
* one of the brief's hook types ("Direct Problem", "Reaction")
|
||||
*/
|
||||
hook?: string,
|
||||
/**
|
||||
* captions, hook (a text hook) or none
|
||||
*/
|
||||
text?: string, formats?: Array<string>, seconds?: [number, number],
|
||||
/**
|
||||
* the cut's beats in order (docs/goal.feature MK48): what each must make the viewer feel and understand, decided
|
||||
* before the cut (Murch: emotion and story weigh most), and its pace
|
||||
*/
|
||||
beats?: Array<Beat>, };
|
||||
|
||||
export type Phrase = {
|
||||
/**
|
||||
* as it's said or shown; compared in lower case, by letters and digits ("24/7" and "24-7" are the same)
|
||||
*/
|
||||
text: string, from: string,
|
||||
/**
|
||||
* `say` only: false when one cut saying it is enough
|
||||
*/
|
||||
every?: boolean, };
|
||||
|
||||
export type Cta = { text: string, from: string,
|
||||
/**
|
||||
* the other lines a brief rotates (two host lines, a paid take's): any one lands it, each found in the brief
|
||||
*/
|
||||
also?: Array<string>,
|
||||
/**
|
||||
* how near the end it must land, in seconds (8 when left out)
|
||||
*/
|
||||
within?: number, };
|
||||
|
||||
export type CutOpen = { question: string, from: string,
|
||||
/**
|
||||
* what it decides: "count", "cta", "offer", a cut's id...
|
||||
*/
|
||||
about?: string,
|
||||
/**
|
||||
* the person's answer, as they gave it, and who gave it: until then the job can't be done
|
||||
*/
|
||||
answer?: string, by?: string, };
|
||||
|
||||
export type PlayableGoal = {
|
||||
/**
|
||||
* the game's TSX, relative to the brief: it renders as the video ad and exports as the playable
|
||||
*/
|
||||
game: string,
|
||||
/**
|
||||
* the files' name ([a-z0-9_], `NAME-NETWORK.html`); the game's file name when left out
|
||||
*/
|
||||
name?: 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
|
||||
*/
|
||||
networks?: Array<string>,
|
||||
/**
|
||||
* both unless the brief says one: Unity, AppLovin, Moloco and Mintegral want both
|
||||
*/
|
||||
orientation?: PlayableOrientation,
|
||||
/**
|
||||
* [least, most] seconds of play before the end card (15 to 60 by default)
|
||||
*/
|
||||
seconds?: [number, number],
|
||||
/**
|
||||
* the same game rendered as the video ad too, as out/cuts/NAME_9x16.mp4 (PA17)
|
||||
*/
|
||||
video?: boolean, };
|
||||
|
||||
export type PlayableOrientation = "both" | "portrait" | "landscape";
|
||||
|
||||
export type GoalRule = {
|
||||
/**
|
||||
* a short name: [a-z0-9_], how status, the critic and NOTES.md name it
|
||||
*/
|
||||
id: string,
|
||||
/**
|
||||
* a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`)
|
||||
*/
|
||||
run?: string,
|
||||
/**
|
||||
* the seconds `run` gets before it counts as failed (300 when left out)
|
||||
*/
|
||||
timeout?: number,
|
||||
/**
|
||||
* a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
|
||||
*/
|
||||
file?: string,
|
||||
/**
|
||||
* words that must be true of the work, judged by a fresh critic (`raea goal judge`), never by the agent that did it
|
||||
*/
|
||||
says?: string, };
|
||||
+2
-282
@@ -1,4 +1,6 @@
|
||||
// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.
|
||||
import type { Goals } from "./brief-goal.gen";
|
||||
export type * from "./brief-goal.gen";
|
||||
|
||||
export type Brief = { title: string, logline?: string,
|
||||
/**
|
||||
@@ -203,285 +205,3 @@ material?: string, style?: string,
|
||||
* what a near crop of it must show
|
||||
*/
|
||||
near?: string, };
|
||||
|
||||
export type Goal = { kind: GoalKind,
|
||||
/**
|
||||
* how the plan, the report and other goals' `after` name it ([a-z0-9_]); the kind when left out
|
||||
*/
|
||||
name?: string,
|
||||
/**
|
||||
* the workflow step it serves, by the workflow's name for it (`edit`, `deliver`)
|
||||
*/
|
||||
step?: string,
|
||||
/**
|
||||
* the goals that must be done before this one starts, by name
|
||||
*/
|
||||
after?: Array<string>,
|
||||
/**
|
||||
* what the goal is, in the person's words
|
||||
*/
|
||||
aim?: string,
|
||||
/**
|
||||
* what must hold before the agent may stop, beside the kind's packs: each checked in code or by a fresh critic
|
||||
*/
|
||||
rules?: Array<GoalRule>,
|
||||
/**
|
||||
* the pictures the job answers to (paths beside the brief): what is in it and where for a scene, the style for a kit
|
||||
*/
|
||||
references?: Array<string>,
|
||||
/**
|
||||
* one paragraph every reference prompt carries: era, palette, materials, wear, and one fictional maker
|
||||
*/
|
||||
style?: string,
|
||||
/**
|
||||
* by name, from the kind's set (DIALS); one left out is read from the references
|
||||
*/
|
||||
dials?: { [key in string]: GoalDial }, objects?: Array<GoalObject>, shots?: Array<GoalShot>,
|
||||
/**
|
||||
* the compositions the job's checks hold (relative to the brief): each needs a clean render or check newer than it
|
||||
*/
|
||||
compositions?: Array<string>,
|
||||
/**
|
||||
* what must exist when it's done, relative to the brief; replaces the kind's own list (`deliverables`)
|
||||
*/
|
||||
deliverables?: Array<string>,
|
||||
/**
|
||||
* the most critic rounds the job gets; at the cap it is delivered with what's still missing (8 by default)
|
||||
*/
|
||||
rounds?: number,
|
||||
/**
|
||||
* a cut job's contract: the brief as rules (cut.rs)
|
||||
*/
|
||||
cut?: CutGoal,
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
previews?: Array<string>,
|
||||
/**
|
||||
* raea's packs switched by name over the kind's defaults (`{ surprise: true, place: false }`): which of
|
||||
* raea/goal's rules hold this goal (docs/goal.feature)
|
||||
*/
|
||||
packs?: { [key in string]: boolean },
|
||||
/**
|
||||
* the project's own checks (raea/check `check()`, imported into brief.ts), run by `raea goal check`; as data, only
|
||||
* their declarations (id, text, over, at) reach Rust
|
||||
*/
|
||||
checks?: Array<unknown>, };
|
||||
|
||||
export type GoalKind = "scene" | "kit" | "shot" | "cut" | "rules";
|
||||
|
||||
export type GoalSource = "customer" | "reference";
|
||||
|
||||
export type GoalDialValue = number | string;
|
||||
|
||||
export type GoalDial = GoalDialValue | { value: GoalDialValue, source?: GoalSource,
|
||||
/**
|
||||
* what the value meant for this job, in one line
|
||||
*/
|
||||
means?: string, };
|
||||
|
||||
export type GoalRoute = "solid" | "rule" | "gen" | "library" | "picture";
|
||||
|
||||
export type GoalOrigin = "reference" | "invented";
|
||||
|
||||
export type GoalPick = {
|
||||
/**
|
||||
* "tripo-h31", "meshy", ...
|
||||
*/
|
||||
generator: string,
|
||||
/**
|
||||
* one line: why this one ("sharper dial numerals; Tripo fused the handset to the cradle")
|
||||
*/
|
||||
why: string, };
|
||||
|
||||
export type GoalObject = {
|
||||
/**
|
||||
* snake_case, unique in the job
|
||||
*/
|
||||
id: string, label: string,
|
||||
/**
|
||||
* real height in metres
|
||||
*/
|
||||
h?: number,
|
||||
/**
|
||||
* [width, depth, height] in metres, for boxy things (generators invent depth)
|
||||
*/
|
||||
dims?: [number, number, number],
|
||||
/**
|
||||
* largest extent in metres, for things that lie flat (tools, papers)
|
||||
*/
|
||||
max?: number, route?: GoalRoute,
|
||||
/**
|
||||
* one object, its condition and its materials; never a real brand
|
||||
*/
|
||||
prompt?: string, source?: GoalOrigin,
|
||||
/**
|
||||
* where it is in reference 0: [x0, y0, x1, y1] in 0..1
|
||||
*/
|
||||
crop?: [number, number, number, number],
|
||||
/**
|
||||
* where it stands in a scene: metres, the floor's front-left corner at the origin, rot 0 = facing the entrance
|
||||
*/
|
||||
at?: [number, number, number], rot?: number, hero?: boolean,
|
||||
/**
|
||||
* how large it is planned to be seen, which is how much of it gets built: 0 the hero (half the frame or more),
|
||||
* 1 featured (under 50%), 2 dressing (under 20%), 3 background (under 8%: a grey box reads), 4 far (under 2%: a
|
||||
* silhouette). A render that shows it finer than this says so (`lod-closer`; `raea scene lod` lists every part)
|
||||
*/
|
||||
lod?: number, pick?: GoalPick,
|
||||
/**
|
||||
* what was fixed by script ("glass made transmissive, label kept opaque")
|
||||
*/
|
||||
fixes?: Array<string>, };
|
||||
|
||||
export type GoalShot = {
|
||||
/**
|
||||
* [a-z0-9_]: the file it lands as (out/shots/<name>.png or .mp4)
|
||||
*/
|
||||
name: string,
|
||||
/**
|
||||
* in a crew's words: "slow push along the counter, rack focus to the register"
|
||||
*/
|
||||
description?: string,
|
||||
/**
|
||||
* static, dolly, truck, pedestal, crane, pan, tilt, orbit, dollyZoom, path
|
||||
*/
|
||||
move?: string, seconds?: number, lens?: number,
|
||||
/**
|
||||
* none, subtle, walk
|
||||
*/
|
||||
handheld?: string,
|
||||
/**
|
||||
* a still rather than a move
|
||||
*/
|
||||
still?: boolean,
|
||||
/**
|
||||
* the composition that renders it (relative to the brief): `raea make shots` draws its framing sheet and lens chart
|
||||
*/
|
||||
composition?: string,
|
||||
/**
|
||||
* its frame rate, for the frames `seconds` spans (30 when left out)
|
||||
*/
|
||||
fps?: number, };
|
||||
|
||||
export type Goals = Goal | Array<Goal>;
|
||||
|
||||
export type CutGoal = {
|
||||
/**
|
||||
* the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf media/brief.txt`): every `from` is found in it
|
||||
*/
|
||||
brief: string,
|
||||
/**
|
||||
* how many cuts the brief asks for; fewer planned is held open until an answered `open` item about "count" says why
|
||||
*/
|
||||
count?: Quoted<number>,
|
||||
/**
|
||||
* a cut's length when its own `seconds` says none: [least, most]
|
||||
*/
|
||||
seconds?: [number, number],
|
||||
/**
|
||||
* the formats every cut is delivered in when its own `formats` says none: "9:16", "16:9", "1:1", "4:5"
|
||||
*/
|
||||
formats?: Array<string>, cuts?: Array<CutPlan>,
|
||||
/**
|
||||
* what is said or shown: in every cut unless `every: false` (then in one or more)
|
||||
*/
|
||||
say?: Array<Phrase>,
|
||||
/**
|
||||
* what no cut says or shows: a banned claim, a word, a name
|
||||
*/
|
||||
never?: Array<Phrase>,
|
||||
/**
|
||||
* the line every cut ends on, heard or on screen in its last `within` seconds
|
||||
*/
|
||||
cta?: Cta,
|
||||
/**
|
||||
* the brief's open items ([TO CONFIRM]): each holds the job open until it has an answer
|
||||
*/
|
||||
open?: Array<CutOpen>,
|
||||
/**
|
||||
* every face whole and every text big enough, by the frames check of each file (true when left out)
|
||||
*/
|
||||
frames?: boolean, };
|
||||
|
||||
export type Quoted<T> = { value: T,
|
||||
/**
|
||||
* the brief's own words, as they are in its text
|
||||
*/
|
||||
from: string, };
|
||||
|
||||
export type CutPlan = {
|
||||
/**
|
||||
* [a-z0-9_], unique: each format lands as out/cuts/<id>_<W>x<H>.mp4 ("a1_s1_9x16.mp4")
|
||||
*/
|
||||
id: string, angle?: string,
|
||||
/**
|
||||
* solo or mashup
|
||||
*/
|
||||
kind?: string,
|
||||
/**
|
||||
* one of the brief's hook types ("Direct Problem", "Reaction")
|
||||
*/
|
||||
hook?: string,
|
||||
/**
|
||||
* captions, hook (a text hook) or none
|
||||
*/
|
||||
text?: string, formats?: Array<string>, seconds?: [number, number],
|
||||
/**
|
||||
* the cut's beats in order (docs/goal.feature MK48): what each must make the viewer feel and understand, decided
|
||||
* before the cut (Murch: emotion and story weigh most), and its pace
|
||||
*/
|
||||
beats?: Array<Beat>, };
|
||||
|
||||
export type Phrase = {
|
||||
/**
|
||||
* as it's said or shown; compared in lower case, by letters and digits ("24/7" and "24-7" are the same)
|
||||
*/
|
||||
text: string, from: string,
|
||||
/**
|
||||
* `say` only: false when one cut saying it is enough
|
||||
*/
|
||||
every?: boolean, };
|
||||
|
||||
export type Cta = { text: string, from: string,
|
||||
/**
|
||||
* the other lines a brief rotates (two host lines, a paid take's): any one lands it, each found in the brief
|
||||
*/
|
||||
also?: Array<string>,
|
||||
/**
|
||||
* how near the end it must land, in seconds (8 when left out)
|
||||
*/
|
||||
within?: number, };
|
||||
|
||||
export type CutOpen = { question: string, from: string,
|
||||
/**
|
||||
* what it decides: "count", "cta", "offer", a cut's id...
|
||||
*/
|
||||
about?: string,
|
||||
/**
|
||||
* the person's answer, as they gave it, and who gave it: until then the job can't be done
|
||||
*/
|
||||
answer?: string, by?: string, };
|
||||
|
||||
export type GoalRule = {
|
||||
/**
|
||||
* a short name: [a-z0-9_], how status, the critic and NOTES.md name it
|
||||
*/
|
||||
id: string,
|
||||
/**
|
||||
* a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`)
|
||||
*/
|
||||
run?: string,
|
||||
/**
|
||||
* the seconds `run` gets before it counts as failed (300 when left out)
|
||||
*/
|
||||
timeout?: number,
|
||||
/**
|
||||
* a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
|
||||
*/
|
||||
file?: string,
|
||||
/**
|
||||
* words that must be true of the work, judged by a fresh critic (`raea goal judge`), never by the agent that did it
|
||||
*/
|
||||
says?: string, };
|
||||
@@ -31,5 +31,5 @@ export const parts = (p: Parts): Parts => p;
|
||||
* them in order (a workflow; `workflow()` shares one), each with its kind's packs and its own `rules`; `raea goal
|
||||
* check` holds each goal at every save, render, hand-over and stop. They're raea/goal's, here too so a brief imports
|
||||
* one module; `plan` is raea/task's. */
|
||||
export { cut, goal, kit, rules, scene, shot, workflow } from "raea/goal";
|
||||
export { cut, goal, kit, playable, rules, scene, shot, workflow } from "raea/goal";
|
||||
export { plan } from "raea/task";
|
||||
@@ -0,0 +1,134 @@
|
||||
// Text in a box that hugs each line, as TikTok draws its text (12-03, Shane: "we need to ALLOW, albeit it's not
|
||||
// required, this kind of text box wrapping on multi-line text"): every line on its own fill as wide as its words, one
|
||||
// shape round them all, its outer corners rounded and, where a wider line meets a narrower one, the corner curved in.
|
||||
// For captions and hooks alike. Lines are given (a caption's lines are made by the words file: captionLines), so where
|
||||
// each breaks is the editor's. Each line is measured after layout (getBoundingClientRect), and the shape is drawn
|
||||
// behind them as one SVG path; until it's measured (or where nothing measures) each line has its own rounded fill.
|
||||
//
|
||||
// Emoji in it are drawn in colour on any machine (EmojiText, which captions can use too).
|
||||
//
|
||||
// <HugText lines={["This textbox has smooth", "rounded corners, like", "the textboxes on TikTok."]}
|
||||
// fill="#E8423F" color="#fff" className="font-brand text-[64px] font-bold" />
|
||||
import { type CSSProperties, type ReactNode, useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
/** the colour emoji faces, Apple's on a Mac and Noto's on Linux (the farm), named ahead of any text face: a text face
|
||||
* with its own outline of an emoji (DejaVu Sans has 😩) would otherwise draw it in one colour */
|
||||
export const EMOJI_FONTS = "'Apple Color Emoji', 'Noto Color Emoji', 'Segoe UI Emoji'";
|
||||
// an emoji with what joins it: modifiers, variation selectors, ZWJ sequences, keycaps and flags
|
||||
const EMOJI = /(?:\p{Regional_Indicator}{2}|[#*0-9]\uFE0F?\u20E3|\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})*(?:\u200D\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})*)*)+/gu;
|
||||
|
||||
/** text with each run of emoji in the colour emoji faces (EMOJI_FONTS), the rest in the text's own font */
|
||||
export function EmojiText({ text }: { text: string }): ReactNode {
|
||||
const out: ReactNode[] = [];
|
||||
let at = 0;
|
||||
for (const m of text.matchAll(EMOJI)) {
|
||||
if (m.index! > at) out.push(text.slice(at, m.index));
|
||||
out.push(<span key={m.index} style={{ fontFamily: EMOJI_FONTS }}>{m[0]}</span>);
|
||||
at = m.index! + m[0].length;
|
||||
}
|
||||
if (at < text.length) out.push(text.slice(at));
|
||||
return out.length === 1 && typeof out[0] === "string" ? out[0] : <>{out}</>;
|
||||
}
|
||||
|
||||
export type HugTextProps = {
|
||||
/** the lines, top to bottom */
|
||||
lines: string[];
|
||||
/** the box's colour */
|
||||
fill?: string;
|
||||
/** the text's colour */
|
||||
color?: string;
|
||||
/** how round the corners are, in px (clamped where two lines' widths differ by less) */
|
||||
radius?: number;
|
||||
/** room each side of a line's words, and above and below them, in px */
|
||||
padX?: number;
|
||||
padY?: number;
|
||||
/** where the lines sit against each other */
|
||||
align?: "center" | "left" | "right";
|
||||
/** classes for the text (its font, size, weight): the box is sized from them */
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
};
|
||||
|
||||
type Box = { x0: number; x1: number; y0: number; y1: number };
|
||||
|
||||
/** one outline round boxes stacked top to bottom: clockwise, its convex corners rounded by r and its concave ones
|
||||
* filleted by r, each corner's r no more than half the step it turns on or half a line's height */
|
||||
export function hugPath(boxes: Box[], r: number): string {
|
||||
if (!boxes.length) return "";
|
||||
// the boxes made to touch: each boundary halfway between one line's bottom and the next one's top
|
||||
const b = boxes.map((x) => ({ ...x }));
|
||||
for (let i = 0; i + 1 < b.length; i++) {
|
||||
const m = (b[i].y1 + b[i + 1].y0) / 2;
|
||||
b[i].y1 = m;
|
||||
b[i + 1].y0 = m;
|
||||
}
|
||||
const h = Math.min(...b.map((x) => x.y1 - x.y0));
|
||||
const R = Math.max(0, Math.min(r, h / 2));
|
||||
const f = (n: number) => +n.toFixed(2);
|
||||
const arc = (rr: number, x: number, y: number, convex: boolean) => `A${f(rr)} ${f(rr)} 0 0 ${convex ? 1 : 0} ${f(x)} ${f(y)}`;
|
||||
const top = b[0];
|
||||
const out: string[] = [`M${f(top.x0 + R)} ${f(top.y0)}`, `H${f(top.x1 - R)}`, arc(R, top.x1, top.y0 + R, true)];
|
||||
// down the right side
|
||||
for (let i = 0; i + 1 < b.length; i++) {
|
||||
const y = b[i].y1;
|
||||
const a = b[i].x1;
|
||||
const c = b[i + 1].x1;
|
||||
const d = Math.abs(c - a);
|
||||
if (d < 1) continue;
|
||||
const rr = Math.min(R, d / 2);
|
||||
out.push(`V${f(y - rr)}`);
|
||||
if (c > a) out.push(arc(rr, a + rr, y, false), `H${f(c - rr)}`, arc(rr, c, y + rr, true));
|
||||
else out.push(arc(rr, a - rr, y, true), `H${f(c + rr)}`, arc(rr, c, y + rr, false));
|
||||
}
|
||||
const last = b[b.length - 1];
|
||||
out.push(`V${f(last.y1 - R)}`, arc(R, last.x1 - R, last.y1, true), `H${f(last.x0 + R)}`, arc(R, last.x0, last.y1 - R, true));
|
||||
// up the left side
|
||||
for (let i = b.length - 2; i >= 0; i--) {
|
||||
const y = b[i].y1;
|
||||
const lo = b[i + 1].x0;
|
||||
const up = b[i].x0;
|
||||
const d = Math.abs(up - lo);
|
||||
if (d < 1) continue;
|
||||
const rr = Math.min(R, d / 2);
|
||||
out.push(`V${f(y + rr)}`);
|
||||
if (up < lo) out.push(arc(rr, lo - rr, y, false), `H${f(up + rr)}`, arc(rr, up, y - rr, true));
|
||||
else out.push(arc(rr, lo + rr, y, true), `H${f(up - rr)}`, arc(rr, up, y - rr, false));
|
||||
}
|
||||
out.push(`V${f(top.y0 + R)}`, arc(R, top.x0 + R, top.y0, true), "Z");
|
||||
return out.join(" ");
|
||||
}
|
||||
|
||||
export function HugText({ lines, fill = "#ffffff", color = "#111111", radius = 18, padX = 22, padY = 8, align = "center", className, style }: HugTextProps) {
|
||||
const wrap = useRef<HTMLDivElement>(null);
|
||||
const spans = useRef<(HTMLSpanElement | null)[]>([]);
|
||||
const [boxes, setBoxes] = useState<Box[] | null>(null);
|
||||
const key = lines.join("\n");
|
||||
useLayoutEffect(() => {
|
||||
const w = wrap.current?.getBoundingClientRect();
|
||||
if (!w) return;
|
||||
const got = spans.current.slice(0, lines.length).map((s) => s?.getBoundingClientRect());
|
||||
if (got.some((r) => !r || !r.width)) return;
|
||||
setBoxes(got.map((r) => ({ x0: r!.left - w.left, x1: r!.right - w.left, y0: r!.top - w.top, y1: r!.bottom - w.top })));
|
||||
}, [key]);
|
||||
const items = align === "center" ? "center" : align === "left" ? "flex-start" : "flex-end";
|
||||
return (
|
||||
<div ref={wrap} className={className} style={{ position: "relative", display: "inline-flex", flexDirection: "column", alignItems: items, color, ...style }}>
|
||||
{boxes && (
|
||||
<svg style={{ position: "absolute", left: 0, top: 0 }} width={Math.ceil(Math.max(...boxes.map((x) => x.x1)))} height={Math.ceil(Math.max(...boxes.map((x) => x.y1)))} viewBox={`0 0 ${Math.ceil(Math.max(...boxes.map((x) => x.x1)))} ${Math.ceil(Math.max(...boxes.map((x) => x.y1)))}`}>
|
||||
<path d={hugPath(boxes, radius)} fill={fill} />
|
||||
</svg>
|
||||
)}
|
||||
{lines.map((l, i) => (
|
||||
<span
|
||||
key={i}
|
||||
ref={(el) => {
|
||||
spans.current[i] = el;
|
||||
}}
|
||||
style={{ position: "relative", display: "inline-block", whiteSpace: "pre", padding: `${padY}px ${padX}px`, ...(boxes ? {} : { background: fill, borderRadius: radius }) }}
|
||||
>
|
||||
<EmojiText text={l} />
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -76,6 +76,7 @@ export { speedLength, speedPoints, speedSource, type SpeedPoint } from "@raea/vi
|
||||
export { Transition, type TransitionProps, type TransitionEdge, type TransitionKind } from "@raea/video/transition";
|
||||
export { Region, useRegion, proofBoxes, regionBand, type RegionName, type RegionBox, type RegionProps, type ProofInput, type ProofPart } from "@raea/video/region";
|
||||
export { InputRegion } from "@raea/video/input-region";
|
||||
export { HugText, hugPath, EmojiText, EMOJI_FONTS, type HugTextProps } from "./hug-text";
|
||||
export { lyria, sao, fish, isGeneratedAsset, type AssetKind, type GeneratedAsset } from "@raea/asset/assets";
|
||||
export { useInput, useGameState, useGameEvents, stepAll, keyEdges, type Playtest } from "@raea/app/games";
|
||||
export { actionsIn, applyActions, feedIn, ACTION_KEY, SPACE_KEY, FEED_KEY, type PanelAction, type PanelActions } from "@raea/video/panel";
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createRoot } from "react-dom/client";
|
||||
import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea";
|
||||
import { Input } from "@raea/playable/host/input";
|
||||
import { Collector, UNDER3D_CSS, clearUnder3d } from "./collect";
|
||||
import { patchShaderModules } from "./wgsl";
|
||||
|
||||
/** raea-web's engine, as wasm-bindgen exports it (engine/web: `import init, { Raea } from "./raea_web.js"`). */
|
||||
export interface RaeaEngine {
|
||||
@@ -31,6 +32,8 @@ const loaded = new WeakMap<() => Promise<RaeaWebModule>, Promise<RaeaWebModule>>
|
||||
export function loadRaea(load: () => Promise<RaeaWebModule>): Promise<RaeaWebModule> {
|
||||
let p = loaded.get(load);
|
||||
if (!p) {
|
||||
// Safari reads WGSL to the letter: Bevy's shaders are made to its rules first (wgsl.ts)
|
||||
patchShaderModules();
|
||||
p = load().then(async (m) => (await m.default(), m));
|
||||
loaded.set(load, p);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Safari's WGSL (WebKit) holds to the spec: a `let` can't hold a texture or a sampler (they aren't constructible
|
||||
// types), while Chrome's Tint lets it through. Bevy's PBR shaders do it (bevy_pbr pbr_fragment.wesl,
|
||||
// `let texture = pbr_bindings::base_color_texture;`), in every mesh with UVs, so raea-web drew nothing in Safari
|
||||
// ("Fragment module is invalid", 12-02). Each such `let` is inlined here before the module is made: its name is replaced
|
||||
// by what it held (a global binding, or an index into a binding array) through the rest of its block.
|
||||
|
||||
/** the global bindings of handle types (textures, samplers, arrays of either) a shader declares */
|
||||
function handles(code: string): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const m of code.matchAll(/\bvar\s+(\w+)\s*:\s*(?:texture_|sampler|binding_array\s*<\s*(?:texture_|sampler))/g)) out.add(m[1]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** where the block holding `at` closes (the index of its `}`), or the end */
|
||||
function blockEnd(code: string, at: number): number {
|
||||
let depth = 0;
|
||||
for (let i = at; i < code.length; i++) {
|
||||
const c = code[i];
|
||||
if (c === "{") depth++;
|
||||
else if (c === "}") {
|
||||
if (depth === 0) return i;
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return code.length;
|
||||
}
|
||||
|
||||
/** The shader with every `let` that holds a texture or sampler inlined; the same text when there's none. */
|
||||
export function inlineHandleLets(code: string): string {
|
||||
const globals = handles(code);
|
||||
if (!globals.size) return code;
|
||||
const decl = /\blet\s+(\w+)\s*(?::\s*[^=]+)?=\s*([^;]+);/g;
|
||||
for (let guard = 0; guard < 10_000; guard++) {
|
||||
decl.lastIndex = 0;
|
||||
let m: RegExpExecArray | null, found: RegExpExecArray | null = null;
|
||||
while ((m = decl.exec(code))) {
|
||||
const root = /^\s*(?:\w+::)*(\w+)/.exec(m[2])?.[1];
|
||||
if (root && globals.has(root)) { found = m; break; }
|
||||
}
|
||||
if (!found) return code;
|
||||
const [whole, name, held] = found;
|
||||
const from = found.index + whole.length;
|
||||
const end = blockEnd(code, from);
|
||||
const value = held.trim().replace(/\s+/g, " ");
|
||||
const rest = code.slice(from, end).replace(new RegExp(`\\b${name}\\b`, "g"), () => value);
|
||||
code = code.slice(0, found.index) + rest + code.slice(end);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
let patched = false;
|
||||
/** Makes every WebGPU shader module from its inlined text (once per page; nothing where there's no WebGPU). */
|
||||
export function patchShaderModules() {
|
||||
const G = (globalThis as { GPUDevice?: { prototype: { createShaderModule(d: { code: string }): unknown } } }).GPUDevice;
|
||||
if (patched || !G) return;
|
||||
patched = true;
|
||||
const make = G.prototype.createShaderModule;
|
||||
G.prototype.createShaderModule = function (d: { code: string }) {
|
||||
return make.call(this, typeof d?.code === "string" ? { ...d, code: inlineHandleLets(d.code) } : d);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// wgsl.ts: a `let` holding a texture or sampler is inlined for Safari; everything else is left as it was
|
||||
import { expect, test } from "bun:test";
|
||||
import { inlineHandleLets } from "../../src/wgsl";
|
||||
|
||||
const head = `@group(2) @binding(1) var base_color_texture: texture_2d<f32>;
|
||||
@group(2) @binding(2) var base_color_sampler: sampler;
|
||||
@group(2) @binding(3) var bindless_textures_2d: binding_array<texture_2d<f32>, 16>;
|
||||
`;
|
||||
|
||||
test("a texture and a sampler held by lets are used directly, in their block only", () => {
|
||||
const code = `${head}fn f(uv: vec2<f32>) -> vec4<f32> {
|
||||
var c = vec4(1.0);
|
||||
if (true) {
|
||||
let texture = base_color_texture;
|
||||
let sampler_ = base_color_sampler;
|
||||
let coords = uv;
|
||||
c *= textureSampleBias(texture, sampler_, coords, 0.0);
|
||||
}
|
||||
let texture_scale = 2.0;
|
||||
return c * texture_scale;
|
||||
}`;
|
||||
const out = inlineHandleLets(code);
|
||||
expect(out).not.toContain("let texture =");
|
||||
expect(out).not.toContain("let sampler_ =");
|
||||
expect(out).toContain("textureSampleBias(base_color_texture, base_color_sampler, coords, 0.0)");
|
||||
expect(out).toContain("let coords = uv;");
|
||||
expect(out).toContain("let texture_scale = 2.0;");
|
||||
expect(out).toContain("return c * texture_scale;");
|
||||
});
|
||||
|
||||
test("a binding array's element, over lines, and the same name again in the next block", () => {
|
||||
const code = `${head}fn g(i: u32, uv: vec2<f32>) -> f32 {
|
||||
var a = 0.0;
|
||||
{
|
||||
let texture = bindless_textures_2d[
|
||||
i
|
||||
];
|
||||
a += textureSample(texture, base_color_sampler, uv).r;
|
||||
}
|
||||
{
|
||||
let texture = base_color_texture;
|
||||
a += textureSample(texture, base_color_sampler, uv).g;
|
||||
}
|
||||
return a;
|
||||
}`;
|
||||
const out = inlineHandleLets(code);
|
||||
expect(out).toContain("textureSample(bindless_textures_2d[ i ], base_color_sampler, uv).r");
|
||||
expect(out).toContain("textureSample(base_color_texture, base_color_sampler, uv).g");
|
||||
expect(out).not.toMatch(/let texture\b/);
|
||||
});
|
||||
|
||||
test("a module path (naga_oil's pbr_bindings::) is a binding all the same; a shader with no handles is untouched", () => {
|
||||
expect(inlineHandleLets(`${head}fn h() { let t = pbr_bindings::base_color_texture; textureDimensions(t); }`)).toContain("textureDimensions(pbr_bindings::base_color_texture)");
|
||||
const plain = "fn k() -> f32 { let x = 1.0; return x; }";
|
||||
expect(inlineHandleLets(plain)).toBe(plain);
|
||||
});
|
||||
+1
-1
@@ -216,7 +216,7 @@ gen_files() {
|
||||
echo "A field marked ? may be left out."
|
||||
echo
|
||||
echo '```ts'
|
||||
grep -v '^// Generated' "$ROOT/sdk/raea/src/brief.gen.ts" | sed '/^$/d'
|
||||
cat "$ROOT/sdk/raea/src/brief.gen.ts" "$ROOT/sdk/raea/src/brief-goal.gen.ts" | grep -vE '^(// Generated|import type|export type \* from)' | sed '/^$/d'
|
||||
echo '```'
|
||||
}
|
||||
rm -rf "$tmp"
|
||||
|
||||
@@ -24,6 +24,8 @@ raea Transition its child coming in over its part's first frames and going
|
||||
raea Overlay children only in a render asked for that overlay
|
||||
raea Region a box at a named band, clear of the face perception found
|
||||
raea InputRegion a box that keeps a press until it's let go (a panel's page of its own)
|
||||
raea HugText text in a box hugging each line, its inside corners curved in, as TikTok draws text
|
||||
raea EmojiText text with its emoji drawn in the colour emoji faces on any machine
|
||||
raea Clock the tree at one frame of a composition (the frame's provider)
|
||||
raea Matchmove footage with solved 3D standing in it (its own Canvas3D)
|
||||
raea Plate footage behind the 3D, filling the camera's view
|
||||
|
||||
Reference in new issue
Block a user