mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
917d41b12a | ||
|
|
80562f9ef7 | ||
|
|
5f407a1cc2 | ||
|
|
b0437d2d08 | ||
|
|
230f817543 | ||
|
|
8dfd71eb92 | ||
|
|
2cbfa8c608 | ||
|
|
c3765a13bb | ||
|
|
5301beb62f | ||
|
|
5c2a524369 | ||
|
|
4044e442c2 |
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
+13
@@ -13801,6 +13801,7 @@ name = "raea-app-engines"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-app-forma",
|
||||
"raea-app-interchange",
|
||||
"raea-app-tools",
|
||||
"raea-io-home",
|
||||
@@ -13829,6 +13830,14 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-forma"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-game"
|
||||
version = "0.1.0"
|
||||
@@ -13978,7 +13987,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",
|
||||
@@ -14061,6 +14073,7 @@ name = "raea-app-tools"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-app-forma",
|
||||
"raea-app-motion",
|
||||
"raea-io-assets",
|
||||
"raea-io-gen",
|
||||
|
||||
@@ -237,6 +237,7 @@ members = [
|
||||
"apps/tools",
|
||||
"apps/motion",
|
||||
"apps/engines",
|
||||
"apps/forma",
|
||||
"apps/interchange",
|
||||
"apps/judge",
|
||||
"apps/make",
|
||||
|
||||
@@ -213,7 +213,8 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
|
||||
continue;
|
||||
}
|
||||
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
|
||||
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
|
||||
let color = r.middle_color();
|
||||
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, color) };
|
||||
let Some(ratio) = ratio else { continue };
|
||||
measured += 1;
|
||||
if ratio < 3.0 {
|
||||
|
||||
@@ -67,8 +67,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
|
||||
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
|
||||
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
|
||||
]);
|
||||
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
|
||||
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
|
||||
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 };
|
||||
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 };
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
|
||||
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
|
||||
@@ -267,7 +267,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
|
||||
|
||||
#[test]
|
||||
fn a_caption_is_timed_from_the_first_word_it_shows() {
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
|
||||
let words: Vec<Word> = [("half", 12.2), ("of", 12.66), ("the", 12.8), ("spend", 12.96)].iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect();
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
// on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later
|
||||
@@ -335,7 +335,7 @@ fn safe_area_tests_the_letters_not_the_box() {
|
||||
|
||||
#[test]
|
||||
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
|
||||
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
|
||||
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
@@ -425,10 +425,11 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
|
||||
#[test]
|
||||
fn a_moving_text_is_read_where_it_is() {
|
||||
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
|
||||
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), color: String::new(), size: 40.0 };
|
||||
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], color: String::new(), size: 40.0 };
|
||||
let (t, b) = run.middle(30.0);
|
||||
assert_eq!(t, 4.0);
|
||||
assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}");
|
||||
let still = Run { boxes: vec![ink(0); 240], box_: [40.0, 1000.0, 60.0, 40.0], ..run };
|
||||
assert_eq!(still.middle(30.0), (4.0, [40.0, 1000.0, 60.0, 40.0]));
|
||||
}
|
||||
|
||||
@@ -43,6 +43,10 @@ pub struct Run {
|
||||
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
|
||||
/// through the frame's edges and zones, which only counts against it when no frame shows it clear
|
||||
pub boxes: Vec<[f64; 4]>,
|
||||
/// its colour on each of those frames, beside `boxes`: a text can change colour while it reads the same (a step
|
||||
/// chip lighting up, grey on dark to dark on yellow), and its contrast is its colour on the frame it's measured at
|
||||
pub colors: Vec<String>,
|
||||
/// its colour on its last frame
|
||||
pub color: String,
|
||||
pub size: f64,
|
||||
}
|
||||
@@ -57,6 +61,15 @@ impl Run {
|
||||
let (at, [x, y, w, h]) = (self.boxes[n / 2], self.box_);
|
||||
(self.to - (n - n / 2) as f64 / fps, [x + at[0] - last[0], y + at[1] - last[1], w, h])
|
||||
}
|
||||
|
||||
/// Its colour on the frame `middle` measures: the one it had there, not the one it ended with.
|
||||
pub fn middle_color(&self) -> &str {
|
||||
let n = self.boxes.len();
|
||||
match self.colors.get(n / 2) {
|
||||
Some(c) if n > 1 && self.colors.len() == n => c,
|
||||
_ => &self.color,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
|
||||
@@ -114,18 +127,21 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
});
|
||||
let mut r = match found {
|
||||
Some(i) => open.remove(i),
|
||||
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), color: String::new(), size: 0.0 },
|
||||
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), color: String::new(), size: 0.0 },
|
||||
};
|
||||
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
|
||||
if text.len() > r.text.len() {
|
||||
r.boxes.clear();
|
||||
r.colors.clear();
|
||||
}
|
||||
if text.len() >= r.text.len() {
|
||||
r.text = text;
|
||||
r.box_ = b;
|
||||
r.boxes.push(ink.unwrap_or(b));
|
||||
r.colors.push(color.clone());
|
||||
}
|
||||
r.to = t + 1.0 / fps;
|
||||
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
|
||||
r.color = color;
|
||||
r.size = x["size"].as_f64().unwrap_or(0.0);
|
||||
next.push(r);
|
||||
}
|
||||
@@ -294,3 +310,21 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
|
||||
passed.push(format!("cues: {checked} texts land on their words"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn a_text_that_lights_up_is_measured_in_its_colour_at_the_middle() {
|
||||
// a step chip: grey on dark for six frames, then dark on yellow for four (the same words)
|
||||
let m = json!({"fps": 10.0, "frames": (0..10).map(|f| json!({"frame": f, "text": [
|
||||
{"text": "03 MAP", "box": [500, 120, 130, 52], "size": 23, "color": if f < 6 { "rgb(169, 169, 174)" } else { "rgb(10, 10, 11)" }}
|
||||
]})).collect::<Vec<_>>()});
|
||||
let runs = text_runs(&m);
|
||||
assert_eq!(runs.len(), 1);
|
||||
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour");
|
||||
assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ description = "The `raea` verbs that script other engines from TypeScript: Blend
|
||||
[dependencies]
|
||||
# Blender found or downloaded, its scripts in Python, and the helpers Godot's setup shares (apps/tools/src/blender.rs)
|
||||
raea-app-tools = { path = "../tools" }
|
||||
# forma, a headless modeller (GPL-3.0-or-later), downloaded and run as its own program, its .glb fixed after (apps/forma)
|
||||
raea-app-forma = { path = "../forma" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# a TypeScript script bundled and run on raea's engine, posting raea/blender's batches to the bridge (blender.post)
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
|
||||
+10
-2
@@ -1,6 +1,8 @@
|
||||
//! The verbs that script other engines from TypeScript: Blender (`raea setup blender`, `raea blender run SCRIPT.py|.ts`;
|
||||
//! finding and setting Blender up is apps/tools/src/blender.rs) and Godot with GodotJS (`raea setup godot`,
|
||||
//! `raea godot run|types|open`; sdk/blender and sdk/godot are their TypeScript sides).
|
||||
//! `raea godot run|types|open`; sdk/blender and sdk/godot are their TypeScript sides). forma, a headless modeller for
|
||||
//! hard-surface parts, runs the same way: downloaded, run as its own program, never linked (`raea setup forma`,
|
||||
//! `raea forma`; apps/forma).
|
||||
|
||||
/// the Blender a TypeScript script drives (`raea blender run SCRIPT.ts`, sdk/blender)
|
||||
pub mod blender_bridge;
|
||||
@@ -16,11 +18,16 @@ pub mod shot;
|
||||
pub mod round;
|
||||
|
||||
use raea_app_tools::blender;
|
||||
/// `raea setup forma` and `raea forma`: forma (GPL-3.0-or-later) downloaded and run as its own program (apps/forma)
|
||||
pub use raea_app_forma as forma;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// The CLI's verbs here, or None for any other: `setup blender|godot`, `blender ...` and `godot ...`.
|
||||
/// The CLI's verbs here, or None for any other: `setup blender|godot|forma`, `blender ...`, `godot ...` and `forma ...`.
|
||||
pub fn cli(args: &[String]) -> Option<R<String>> {
|
||||
if let Some(done) = forma::cli(args) {
|
||||
return Some(done);
|
||||
}
|
||||
let second = args.get(1).map(String::as_str);
|
||||
Some(match (args.first()?.as_str(), second) {
|
||||
("setup", Some("blender")) => blender::setup(&args[2..]),
|
||||
@@ -54,5 +61,6 @@ mod tests {
|
||||
assert!(cli(&args("render edit.tsx")).is_none());
|
||||
assert!(cli(&[]).is_none());
|
||||
assert!(cli(&args("godot")).unwrap().unwrap_err().contains(godot::USAGE));
|
||||
assert!(cli(&args("forma")).is_some());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "raea-app-forma"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea setup forma` and `raea forma`: forma (GPL-3.0-or-later) downloaded and run as its own program, its .glb fixed after"
|
||||
|
||||
[dependencies]
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# the .glb forma writes, read and written back with its colours linear and its normals smoothed (glb.rs)
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,340 @@
|
||||
//! The .glb forma writes, fixed for a renderer that reads glTF as the spec says (docs/forma.feature FM3, FM4). forma
|
||||
//! 0.4.4 writes a material's colour as it was typed (sRGB, as a person picks one) into baseColorFactor, which glTF reads
|
||||
//! as linear, so every colour comes out pale; and it writes one normal per face, so a cylinder shows its facets. The fix
|
||||
//! converts the colours, and gives each corner the mean of the faces around it that meet its own at under `smooth`
|
||||
//! degrees, so a box keeps its edges and a cylinder's side turns round. Only the JSON's colours and the normals' bytes
|
||||
//! change: positions, indices, UVs and the file's layout stay as forma wrote them. A fixed file is marked in
|
||||
//! asset.extras and left alone after, so fixing twice never darkens it twice.
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// The mark a fixed file carries in asset.extras.
|
||||
pub const MARK: &str = "raea_forma";
|
||||
|
||||
const JSON: u32 = 0x4E4F_534A;
|
||||
const BIN: u32 = 0x004E_4942;
|
||||
const FLOAT: u64 = 5126;
|
||||
|
||||
/// What a fix changed.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct Fixed {
|
||||
/// materials whose colour was made linear
|
||||
pub colours: usize,
|
||||
/// mesh primitives whose normals were smoothed
|
||||
pub primitives: usize,
|
||||
/// the file was fixed before and is unchanged
|
||||
pub already: bool,
|
||||
}
|
||||
|
||||
/// Fixes a .glb in place (written beside it, then renamed over it).
|
||||
pub fn fix_file(path: &Path, smooth: Option<f32>) -> R<Fixed> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let (out, fixed) = fix(&bytes, smooth).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
if !fixed.already {
|
||||
let tmp = path.with_extension("raea-tmp");
|
||||
std::fs::write(&tmp, out).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
}
|
||||
Ok(fixed)
|
||||
}
|
||||
|
||||
/// The fixed file's bytes. `smooth`: the largest angle in degrees between two faces whose shared corners are smoothed;
|
||||
/// None keeps forma's normals.
|
||||
pub fn fix(glb: &[u8], smooth: Option<f32>) -> R<(Vec<u8>, Fixed)> {
|
||||
let (mut doc, mut bin) = read(glb)?;
|
||||
if doc["asset"]["extras"][MARK].is_object() {
|
||||
return Ok((glb.to_vec(), Fixed { colours: 0, primitives: 0, already: true }));
|
||||
}
|
||||
let colours = linear_colours(&mut doc);
|
||||
let primitives = match smooth {
|
||||
Some(deg) => smooth_normals(&doc, &mut bin, deg)?,
|
||||
None => 0,
|
||||
};
|
||||
let asset = doc.as_object_mut().ok_or("the glTF JSON isn't an object")?.entry("asset").or_insert_with(|| json!({"version": "2.0"}));
|
||||
let extras = asset.as_object_mut().ok_or("asset isn't an object")?.entry("extras").or_insert_with(|| json!({}));
|
||||
if let Some(e) = extras.as_object_mut() {
|
||||
e.insert(MARK.into(), json!({"colours": "linear", "smooth": smooth}));
|
||||
}
|
||||
Ok((write(&doc, &bin), Fixed { colours, primitives, already: false }))
|
||||
}
|
||||
|
||||
/// The JSON chunk and the BIN chunk (empty when there is none).
|
||||
pub fn read(glb: &[u8]) -> R<(Value, Vec<u8>)> {
|
||||
let u32_at = |at: usize| glb.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
if glb.get(..4) != Some(b"glTF") || u32_at(4) != Some(2) {
|
||||
return Err("not a glTF 2.0 binary (.glb)".into());
|
||||
}
|
||||
let (len, kind) = (u32_at(12).ok_or("no JSON chunk")? as usize, u32_at(16).ok_or("no JSON chunk")?);
|
||||
let text = glb.get(20..20 + len).filter(|_| kind == JSON).ok_or("the first chunk isn't JSON")?;
|
||||
let doc: Value = serde_json::from_slice(text).map_err(|e| format!("the glTF JSON: {e}"))?;
|
||||
let at = 20 + len;
|
||||
let bin = match (u32_at(at), u32_at(at + 4)) {
|
||||
(Some(n), Some(BIN)) => glb.get(at + 8..at + 8 + n as usize).ok_or("the BIN chunk runs past the file")?.to_vec(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
Ok((doc, bin))
|
||||
}
|
||||
|
||||
/// A .glb of a JSON document and a BIN chunk, each padded to four bytes as glTF asks (the JSON with spaces).
|
||||
pub fn write(doc: &Value, bin: &[u8]) -> Vec<u8> {
|
||||
let mut text = serde_json::to_vec(doc).unwrap_or_default();
|
||||
while !text.len().is_multiple_of(4) {
|
||||
text.push(b' ');
|
||||
}
|
||||
let mut data = bin.to_vec();
|
||||
while !data.len().is_multiple_of(4) {
|
||||
data.push(0);
|
||||
}
|
||||
let total = 12 + 8 + text.len() + if data.is_empty() { 0 } else { 8 + data.len() };
|
||||
let mut out = Vec::with_capacity(total);
|
||||
out.extend_from_slice(b"glTF");
|
||||
out.extend_from_slice(&2u32.to_le_bytes());
|
||||
out.extend_from_slice(&(total as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(text.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&JSON.to_le_bytes());
|
||||
out.extend_from_slice(&text);
|
||||
if !data.is_empty() {
|
||||
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&BIN.to_le_bytes());
|
||||
out.extend_from_slice(&data);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// sRGB's transfer undone: the linear value glTF's baseColorFactor holds.
|
||||
pub fn srgb_to_linear(c: f64) -> f64 {
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
|
||||
/// Every material's baseColorFactor made linear (alpha kept); how many there were.
|
||||
fn linear_colours(doc: &mut Value) -> usize {
|
||||
let Some(mats) = doc.get_mut("materials").and_then(Value::as_array_mut) else { return 0 };
|
||||
let mut n = 0;
|
||||
for m in mats {
|
||||
if let Some(c) = m.pointer_mut("/pbrMetallicRoughness/baseColorFactor").and_then(Value::as_array_mut) {
|
||||
for v in c.iter_mut().take(3) {
|
||||
if let Some(x) = v.as_f64() {
|
||||
*v = json!(srgb_to_linear(x));
|
||||
}
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Where an accessor's elements are in the BIN chunk: the first's byte, the step between them, how many, the component
|
||||
/// type, the components in each. None for one this fix doesn't read (sparse, another buffer, or past the chunk).
|
||||
fn layout(doc: &Value, acc: u64, bin: &[u8]) -> Option<(usize, usize, usize, u64, usize)> {
|
||||
let a = doc["accessors"].get(acc as usize)?;
|
||||
if a.get("sparse").is_some() {
|
||||
return None;
|
||||
}
|
||||
let v = doc["bufferViews"].get(a["bufferView"].as_u64()? as usize)?;
|
||||
if v["buffer"].as_u64().unwrap_or(0) != 0 {
|
||||
return None;
|
||||
}
|
||||
let comp = a["componentType"].as_u64()?;
|
||||
let size = match comp {
|
||||
5120 | 5121 => 1,
|
||||
5122 | 5123 => 2,
|
||||
5125 | 5126 => 4,
|
||||
_ => return None,
|
||||
};
|
||||
let n = match a["type"].as_str()? {
|
||||
"SCALAR" => 1,
|
||||
"VEC2" => 2,
|
||||
"VEC3" => 3,
|
||||
"VEC4" => 4,
|
||||
_ => return None,
|
||||
};
|
||||
let start = v["byteOffset"].as_u64().unwrap_or(0) as usize + a["byteOffset"].as_u64().unwrap_or(0) as usize;
|
||||
let stride = v["byteStride"].as_u64().map_or(size * n, |s| s as usize);
|
||||
let count = a["count"].as_u64()? as usize;
|
||||
(count == 0 || start + stride * (count - 1) + size * n <= bin.len()).then_some((start, stride, count, comp, n))
|
||||
}
|
||||
|
||||
fn f32_at(bin: &[u8], at: usize) -> f32 {
|
||||
f32::from_le_bytes([bin[at], bin[at + 1], bin[at + 2], bin[at + 3]])
|
||||
}
|
||||
|
||||
fn vec3s(doc: &Value, acc: u64, bin: &[u8]) -> Option<Vec<[f32; 3]>> {
|
||||
let (start, stride, count, comp, n) = layout(doc, acc, bin)?;
|
||||
(comp == FLOAT && n == 3).then(|| (0..count).map(|i| std::array::from_fn(|k| f32_at(bin, start + i * stride + 4 * k))).collect())
|
||||
}
|
||||
|
||||
fn indices(doc: &Value, prim: &Value, bin: &[u8], verts: usize) -> Option<Vec<usize>> {
|
||||
let Some(acc) = prim.get("indices").and_then(Value::as_u64) else { return Some((0..verts).collect()) };
|
||||
let (start, stride, count, comp, n) = layout(doc, acc, bin)?;
|
||||
if n != 1 {
|
||||
return None;
|
||||
}
|
||||
let at = |i: usize| start + i * stride;
|
||||
let idx: Vec<usize> = match comp {
|
||||
5121 => (0..count).map(|i| bin[at(i)] as usize).collect(),
|
||||
5123 => (0..count).map(|i| u16::from_le_bytes([bin[at(i)], bin[at(i) + 1]]) as usize).collect(),
|
||||
5125 => (0..count).map(|i| u32::from_le_bytes([bin[at(i)], bin[at(i) + 1], bin[at(i) + 2], bin[at(i) + 3]]) as usize).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
idx.iter().all(|&i| i < verts).then_some(idx)
|
||||
}
|
||||
|
||||
fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
|
||||
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
||||
}
|
||||
fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
|
||||
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
}
|
||||
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
|
||||
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
}
|
||||
fn unit(a: [f32; 3]) -> Option<[f32; 3]> {
|
||||
let l = dot(a, a).sqrt();
|
||||
(l > 1e-20).then(|| [a[0] / l, a[1] / l, a[2] / l])
|
||||
}
|
||||
|
||||
/// New normals for one primitive: each corner takes the area-weighted mean of the triangles at its position (corners
|
||||
/// forma split per face are joined by position) whose facing is within `deg` of the corner's own normal.
|
||||
pub fn smoothed(pos: &[[f32; 3]], normals: &[[f32; 3]], idx: &[usize], deg: f32) -> Vec<[f32; 3]> {
|
||||
let lo = pos.iter().fold([f32::MAX; 3], |m, p| std::array::from_fn(|k| m[k].min(p[k])));
|
||||
let hi = pos.iter().fold([f32::MIN; 3], |m, p| std::array::from_fn(|k| m[k].max(p[k])));
|
||||
let eps = (dot(sub(hi, lo), sub(hi, lo)).sqrt() * 1e-6).max(1e-9);
|
||||
let key = |p: [f32; 3]| p.map(|c| (c / eps).round() as i64);
|
||||
let mut group: HashMap<[i64; 3], usize> = HashMap::new();
|
||||
let gid: Vec<usize> = pos.iter().map(|&p| { let n = group.len(); *group.entry(key(p)).or_insert(n) }).collect();
|
||||
let mut around: Vec<Vec<[f32; 3]>> = vec![Vec::new(); group.len()];
|
||||
for t in idx.as_chunks::<3>().0 {
|
||||
let f = cross(sub(pos[t[1]], pos[t[0]]), sub(pos[t[2]], pos[t[0]]));
|
||||
if unit(f).is_none() {
|
||||
continue;
|
||||
}
|
||||
let mut seen = [usize::MAX; 3];
|
||||
for (k, &v) in t.iter().enumerate() {
|
||||
if !seen.contains(&gid[v]) {
|
||||
around[gid[v]].push(f);
|
||||
seen[k] = gid[v];
|
||||
}
|
||||
}
|
||||
}
|
||||
let cos = deg.to_radians().cos();
|
||||
(0..pos.len())
|
||||
.map(|v| {
|
||||
let Some(own) = unit(normals[v]) else { return normals[v] };
|
||||
let sum = around[gid[v]].iter().filter(|f| unit(**f).is_some_and(|u| dot(u, own) >= cos)).fold([0.0; 3], |s, f| [s[0] + f[0], s[1] + f[1], s[2] + f[2]]);
|
||||
unit(sum).unwrap_or(own)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every triangle primitive's normals smoothed in the BIN chunk; how many primitives changed. A primitive with tangents
|
||||
/// is left alone (smoothing would leave them stale), as is one whose data this fix doesn't read.
|
||||
fn smooth_normals(doc: &Value, bin: &mut [u8], deg: f32) -> R<usize> {
|
||||
let mut done: HashSet<u64> = HashSet::new();
|
||||
let mut n = 0;
|
||||
for mesh in doc["meshes"].as_array().into_iter().flatten() {
|
||||
for prim in mesh["primitives"].as_array().into_iter().flatten() {
|
||||
let attrs = &prim["attributes"];
|
||||
let (Some(p), Some(nm)) = (attrs["POSITION"].as_u64(), attrs["NORMAL"].as_u64()) else { continue };
|
||||
if prim["mode"].as_u64().unwrap_or(4) != 4 || attrs.get("TANGENT").is_some() || !done.insert(nm) {
|
||||
continue;
|
||||
}
|
||||
let (Some(pos), Some(normals)) = (vec3s(doc, p, bin), vec3s(doc, nm, bin)) else { continue };
|
||||
let Some(idx) = indices(doc, prim, bin, pos.len()).filter(|_| pos.len() == normals.len()) else { continue };
|
||||
let new = smoothed(&pos, &normals, &idx, deg);
|
||||
let (start, stride, ..) = layout(doc, nm, bin).ok_or("the normals moved")?;
|
||||
for (i, v) in new.iter().enumerate() {
|
||||
for (k, c) in v.iter().enumerate() {
|
||||
let at = start + i * stride + 4 * k;
|
||||
bin[at..at + 4].copy_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Two triangles forma-style (corners split per face, flat normals) meeting along x at `fold` degrees, with
|
||||
/// a red material typed as sRGB.
|
||||
fn hinge(fold: f32) -> Vec<u8> {
|
||||
let (s, c) = fold.to_radians().sin_cos();
|
||||
let pos: [[f32; 3]; 6] = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, -c, s], [1.0, 0.0, 0.0]];
|
||||
let b = unit(cross(sub(pos[4], pos[3]), sub(pos[5], pos[3]))).unwrap();
|
||||
let nrm: [[f32; 3]; 6] = [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], b, b, b];
|
||||
let mut bin = Vec::new();
|
||||
for v in pos.iter().chain(nrm.iter()) {
|
||||
for c in v {
|
||||
bin.extend_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
}
|
||||
for i in 0u16..6 {
|
||||
bin.extend_from_slice(&i.to_le_bytes());
|
||||
}
|
||||
let doc = json!({
|
||||
"asset": {"version": "2.0", "generator": "forma"},
|
||||
"materials": [{"pbrMetallicRoughness": {"baseColorFactor": [0.72, 0.36, 0.0, 0.5]}}],
|
||||
"meshes": [{"primitives": [{"attributes": {"POSITION": 0, "NORMAL": 1}, "indices": 2, "material": 0}]}],
|
||||
"accessors": [
|
||||
{"bufferView": 0, "componentType": 5126, "count": 6, "type": "VEC3"},
|
||||
{"bufferView": 0, "byteOffset": 72, "componentType": 5126, "count": 6, "type": "VEC3"},
|
||||
{"bufferView": 1, "componentType": 5123, "count": 6, "type": "SCALAR"}
|
||||
],
|
||||
"bufferViews": [{"buffer": 0, "byteLength": 144}, {"buffer": 0, "byteOffset": 144, "byteLength": 12}],
|
||||
"buffers": [{"byteLength": 156}]
|
||||
});
|
||||
write(&doc, &bin)
|
||||
}
|
||||
|
||||
fn normals_of(glb: &[u8]) -> Vec<[f32; 3]> {
|
||||
let (doc, bin) = read(glb).unwrap();
|
||||
vec3s(&doc, 1, &bin).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours_become_linear_once() {
|
||||
let (out, f) = fix(&hinge(10.0), None).unwrap();
|
||||
assert_eq!(f, Fixed { colours: 1, primitives: 0, already: false });
|
||||
let (doc, _) = read(&out).unwrap();
|
||||
let c: Vec<f64> = doc["materials"][0]["pbrMetallicRoughness"]["baseColorFactor"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
assert!((c[0] - 0.4770).abs() < 1e-3 && (c[1] - 0.1065).abs() < 1e-3 && c[2] == 0.0 && c[3] == 0.5, "{c:?}");
|
||||
assert_eq!(doc["asset"]["generator"], "forma");
|
||||
let (again, f2) = fix(&out, Some(40.0)).unwrap();
|
||||
assert!(f2.already && again == out);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shallow_fold_turns_round_and_a_sharp_one_stays() {
|
||||
let (out, f) = fix(&hinge(10.0), Some(40.0)).unwrap();
|
||||
assert_eq!(f.primitives, 1);
|
||||
let n = normals_of(&out);
|
||||
// the corners on the shared edge lean halfway; the corners on one face alone keep its facing
|
||||
let tilt = |v: [f32; 3]| dot(v, [0.0, 0.0, 1.0]).acos().to_degrees();
|
||||
assert!((tilt(n[0]) - 5.0).abs() < 0.01 && (tilt(n[1]) - 5.0).abs() < 0.01 && (tilt(n[3]) - 5.0).abs() < 0.01, "{n:?}");
|
||||
assert!(tilt(n[2]) < 1e-3 && (tilt(n[4]) - 10.0).abs() < 0.01, "{n:?}");
|
||||
for v in &n {
|
||||
assert!((dot(*v, *v) - 1.0).abs() < 1e-5);
|
||||
}
|
||||
let (sharp, _) = fix(&hinge(60.0), Some(40.0)).unwrap();
|
||||
assert_eq!(normals_of(&sharp), normals_of(&hinge(60.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_keeps_its_layout() {
|
||||
let src = hinge(10.0);
|
||||
let (out, _) = fix(&src, Some(40.0)).unwrap();
|
||||
assert_eq!(out.len() % 4, 0);
|
||||
assert_eq!(u32::from_le_bytes([out[8], out[9], out[10], out[11]]) as usize, out.len());
|
||||
let ((_, a), (_, b)) = (read(&src).unwrap(), read(&out).unwrap());
|
||||
assert_eq!(a.len(), b.len());
|
||||
assert_eq!(a[..72], b[..72], "positions untouched");
|
||||
assert_eq!(a[144..], b[144..], "indices untouched");
|
||||
assert!(fix(b"not a glb", None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
//! `raea setup forma` and `raea forma` (docs/forma.feature). forma (github.com/wrong-nebula/forma) is a headless
|
||||
//! modeller for hard-surface parts: a few lines of its pipe language make a watertight mesh with exact sizes in
|
||||
//! milliseconds (gears, brackets, threads, enclosures, a lathed vase, a table). forma is GPL-3.0-or-later and raea is
|
||||
//! FSL, so raea never links forma or ships it: setup downloads forma's own release into ~/.raea/tools/forma, as
|
||||
//! `raea setup blender` does Blender, and `raea forma` runs it as a program of its own, then fixes the .glb it wrote
|
||||
//! (glb.rs). What forma makes belongs to whoever made it; the GPL covers forma alone.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// the .glb forma writes, its colours made linear and its normals smoothed
|
||||
pub mod glb;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// The forma raea downloads and is tested with.
|
||||
pub const VERSION: &str = "0.4.4";
|
||||
/// Linux: forma's static musl binary from its GitHub release, which needs no Node; each archive's sha256, pinned.
|
||||
const LINUX: [(&str, &str); 2] = [
|
||||
("x86_64", "52ffc3d60787a9aab9989064624729115e6b1b8d29e53540fde0188443af9470"),
|
||||
("aarch64", "c4788352ce97c432a818d4c8e6f16d60e74e193909ac56ea5b1a066cf967bb5d"),
|
||||
];
|
||||
/// Elsewhere: the npm package forma-3d (forma built for WebAssembly, with its CLI and MCP server), run by Node 18+ or
|
||||
/// Bun; the tarball's sha512, pinned (npm's own integrity for it, in hex).
|
||||
const NPM_SHA512: &str = "676e7990b32dbc3a035079509c5ac9baa86bd24423a53e57e9b586f4b7ff45b07bda75842f58e795c7a128b8a35bc94bc1eafc8e2f94126bcc5f1c3200626a95";
|
||||
/// The angle under which `raea forma` smooths a .glb's normals unless --smooth says.
|
||||
pub const SMOOTH: f32 = 40.0;
|
||||
|
||||
pub const USAGE: &str = "raea setup forma [--check] [--download] (find forma or download it into ~/.raea/tools/forma: forma 0.4.4, a headless modeller for hard-surface parts (GPL-3.0-or-later, so raea runs it as its own program and never ships it), its static binary on Linux, else its npm package run by Node 18+ or Bun, each checked against its pinned hash)\n raea forma SCRIPT.forma -o OUT.glb|.stl|.obj|.3mf|.step [--unit m|cm|mm|um|in|ft] [--render PREVIEW.png] [--draw BLUEPRINT.svg] [--size PX] [--smooth DEG] [--flat] [--no-strict] (a forma script made into OUT, each named part its own node; a mesh that isn't watertight is refused with forma's reason unless --no-strict; a .glb's colours are made linear, as glTF reads them, and its normals smoothed where faces meet under DEG degrees (40 unless given; --flat keeps forma's faceted ones); --render's preview draws the last part, raea render draws them all)\n raea forma fix FILE.glb... [--smooth DEG] [--flat] (the same fix on a .glb forma wrote by itself (its MCP server's export, its own CLI): colours linear, normals smoothed; a file fixed before is left alone)\n raea forma spec [--topic deform|curves|uv|remesh|scene] [--gbnf] (forma's language reference, about 500 tokens: its primitives, operations and selectors)";
|
||||
|
||||
/// How forma is run: its own binary, or its npm package's CLI by a JavaScript runtime.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Forma {
|
||||
Native(PathBuf),
|
||||
Js { runtime: PathBuf, cli: PathBuf },
|
||||
}
|
||||
|
||||
impl Forma {
|
||||
pub fn command(&self) -> Command {
|
||||
match self {
|
||||
Forma::Native(bin) => Command::new(bin),
|
||||
Forma::Js { runtime, cli } => {
|
||||
let mut c = Command::new(runtime);
|
||||
c.arg(cli);
|
||||
c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
match self {
|
||||
Forma::Native(p) | Forma::Js { cli: p, .. } => p,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where raea keeps its download of forma.
|
||||
pub fn own_dir() -> R<PathBuf> {
|
||||
Ok(raea_io_home::user_home().ok_or("no home folder (HOME)")?.join(".raea/tools/forma"))
|
||||
}
|
||||
|
||||
fn on_path(name: &str) -> Option<PathBuf> {
|
||||
let exe = if cfg!(windows) { format!("{name}.exe") } else { name.to_string() };
|
||||
std::env::split_paths(&std::env::var_os("PATH")?).map(|d| d.join(&exe)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Node, else Bun: what runs forma's npm package.
|
||||
fn js_runtime() -> R<PathBuf> {
|
||||
on_path("node").or_else(|| on_path("bun")).ok_or_else(|| "forma runs here on Node.js 18 or later, or Bun, and neither is on PATH: install one (https://nodejs.org), then raea setup forma again".into())
|
||||
}
|
||||
|
||||
/// A forma at a path: a .mjs or .js is forma's npm CLI, anything else its binary.
|
||||
fn at(p: PathBuf) -> R<Forma> {
|
||||
Ok(if p.extension().is_some_and(|x| x == "mjs" || x == "js") { Forma::Js { runtime: js_runtime()?, cli: p } } else { Forma::Native(p) })
|
||||
}
|
||||
|
||||
fn run(cmd: &mut Command, what: &str) -> R<String> {
|
||||
let o = cmd.output().map_err(|e| format!("{what}: {e}"))?;
|
||||
if !o.status.success() {
|
||||
return Err(format!("{what} failed: {}{}", String::from_utf8_lossy(&o.stderr).trim(), String::from_utf8_lossy(&o.stdout).trim()));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&o.stdout).into_owned())
|
||||
}
|
||||
|
||||
/// The forma to use and where it came from: `git config --global raea.forma` (a binary or forma's bin/forma.mjs),
|
||||
/// raea's download, then a `forma` on PATH that says it is forma.
|
||||
pub fn find() -> R<Option<(Forma, &'static str)>> {
|
||||
let configured = run(Command::new("git").args(["config", "--global", "raea.forma"]), "git config").ok().map(|o| PathBuf::from(o.trim()));
|
||||
if let Some(p) = configured.filter(|p| p.is_file()) {
|
||||
return Ok(Some((at(p)?, "raea.forma in git config")));
|
||||
}
|
||||
let dir = own_dir()?;
|
||||
for p in [dir.join(if cfg!(windows) { "forma.exe" } else { "forma" }), dir.join("package/bin/forma.mjs")] {
|
||||
if p.is_file() {
|
||||
return Ok(Some((at(p)?, "raea's download")));
|
||||
}
|
||||
}
|
||||
Ok(on_path("forma").map(Forma::Native).filter(|f| version(f).is_ok()).map(|f| (f, "PATH")))
|
||||
}
|
||||
|
||||
/// `forma --version`'s first line ("forma 0.4.4 (WASM)"); an error when the program isn't forma.
|
||||
pub fn version(f: &Forma) -> R<String> {
|
||||
let out = run(f.command().arg("--version"), "forma --version")?;
|
||||
out.lines().map(str::trim).find(|l| l.starts_with("forma")).map(str::to_string).ok_or_else(|| format!("{} --version didn't say forma", f.path().display()))
|
||||
}
|
||||
|
||||
/// A file's sha256 or sha512 in hex, by the platform's own tool (as blender.rs and godot.rs check their downloads).
|
||||
pub fn digest(file: &Path, bits: u32) -> R<String> {
|
||||
let out = if cfg!(windows) {
|
||||
run(Command::new("certutil").arg("-hashfile").arg(file).arg(format!("SHA{bits}")), "certutil")?.lines().nth(1).unwrap_or_default().replace(' ', "")
|
||||
} else if on_path("shasum").is_some() {
|
||||
run(Command::new("shasum").args(["-a", &bits.to_string()]).arg(file), "shasum")?.split_whitespace().next().unwrap_or_default().to_string()
|
||||
} else {
|
||||
run(Command::new(format!("sha{bits}sum")).arg(file), "sha sum")?.split_whitespace().next().unwrap_or_default().to_string()
|
||||
};
|
||||
Ok(out.to_lowercase())
|
||||
}
|
||||
|
||||
/// Downloads forma into ~/.raea/tools/forma, checked against its pinned hash: Linux's binary, else the npm package.
|
||||
fn download() -> R<(Forma, String)> {
|
||||
let linux = LINUX.iter().find(|(arch, _)| cfg!(target_os = "linux") && *arch == std::env::consts::ARCH);
|
||||
let (url, bits, want, file) = match linux {
|
||||
Some((arch, sum)) => (format!("https://github.com/wrong-nebula/forma/releases/download/v{VERSION}/forma-linux-{arch}-musl.tar.gz"), 256, *sum, "forma.tar.gz"),
|
||||
None => {
|
||||
js_runtime()?; // before downloading what nothing here could run
|
||||
(format!("https://registry.npmjs.org/forma-3d/-/forma-3d-{VERSION}.tgz"), 512, NPM_SHA512, "forma-3d.tgz")
|
||||
}
|
||||
};
|
||||
let dir = own_dir()?;
|
||||
let tmp = dir.with_file_name("forma.download");
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
let unpacked = tmp.join("unpacked");
|
||||
std::fs::create_dir_all(&unpacked).map_err(|e| format!("{}: {e}", unpacked.display()))?;
|
||||
let got = tmp.join(file);
|
||||
run(Command::new("curl").args(["-fL", "--retry", "3", "-o"]).arg(&got).arg(&url), "downloading forma")?;
|
||||
if digest(&got, bits)? != want {
|
||||
return Err(format!("{url} doesn't match its pinned sha{bits}; nothing installed (it's in {})", tmp.display()));
|
||||
}
|
||||
run(Command::new("tar").arg("-xzf").arg(&got).arg("-C").arg(&unpacked), "unpacking forma")?;
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::rename(&unpacked, &dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
let what = if linux.is_some() { "its Linux binary from github.com/wrong-nebula/forma" } else { "its npm package forma-3d" };
|
||||
let f = find()?.filter(|(_, from)| *from == "raea's download").ok_or_else(|| format!("{url} held no forma"))?.0;
|
||||
Ok((f, format!("downloaded forma {VERSION}, {what}")))
|
||||
}
|
||||
|
||||
/// `raea setup forma [--check] [--download]`.
|
||||
pub fn setup(args: &[String]) -> R<String> {
|
||||
let check = args.iter().any(|a| a == "--check");
|
||||
let fresh = args.iter().any(|a| a == "--download");
|
||||
let (f, from) = match find()?.filter(|_| !fresh) {
|
||||
Some((f, from)) => (f, from.to_string()),
|
||||
None if check => return Ok(format!("CHECKED no forma found (raea.forma, {}, PATH): raea setup forma downloads forma {VERSION}", own_dir()?.display())),
|
||||
None => download()?,
|
||||
};
|
||||
let v = version(&f)?;
|
||||
let pinned = if v.contains(VERSION) { String::new() } else { format!(" (raea is tested with {VERSION}: raea setup forma --download fetches it)") };
|
||||
let head = if check { "CHECKED " } else { "APPLIED " };
|
||||
Ok(format!("{head} {v} ({from}){pinned}\n {}\n make: raea forma SCRIPT.forma -o OUT.glb; its language: raea forma spec; agents: the `forma` MCP server (raea skills install adds it)\n forma is GPL-3.0-or-later and runs as its own program; what it makes is yours", f.path().display()))
|
||||
}
|
||||
|
||||
/// `raea forma`'s arguments, read.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Make {
|
||||
pub script: String,
|
||||
pub out: String,
|
||||
pub unit: Option<String>,
|
||||
pub render: Option<String>,
|
||||
pub draw: Option<String>,
|
||||
pub size: Option<String>,
|
||||
pub smooth: Option<f32>,
|
||||
pub strict: bool,
|
||||
}
|
||||
|
||||
/// Reads `raea forma SCRIPT -o OUT ...` (args without the verb).
|
||||
pub fn parse(args: &[String]) -> R<Make> {
|
||||
let mut m = Make { smooth: Some(SMOOTH), strict: true, ..Default::default() };
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
let mut val = |flag: &str| it.next().cloned().ok_or_else(|| format!("{flag} takes a value: {USAGE}"));
|
||||
match a.as_str() {
|
||||
"-o" | "--out" => m.out = val(a)?,
|
||||
"--unit" => m.unit = Some(val(a)?),
|
||||
"--render" => m.render = Some(val(a)?),
|
||||
"--draw" => m.draw = Some(val(a)?),
|
||||
"--size" => m.size = Some(val(a)?),
|
||||
"--smooth" => m.smooth = Some(val(a)?.parse().map_err(|_| "--smooth takes degrees, 40 say".to_string())?),
|
||||
"--flat" => m.smooth = None,
|
||||
"--no-strict" => m.strict = false,
|
||||
f if f.starts_with('-') && f != "-" => return Err(format!("raea forma has no {f}: {USAGE}")),
|
||||
s if m.script.is_empty() => m.script = s.to_string(),
|
||||
s => return Err(format!("one script at a time ({} and {s})", m.script)),
|
||||
}
|
||||
}
|
||||
if m.script.is_empty() || m.out.is_empty() {
|
||||
return Err(format!("usage: {USAGE}"));
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// forma's own arguments for a make: always one node per named part in a .glb.
|
||||
pub fn forma_args(m: &Make) -> Vec<String> {
|
||||
let mut a: Vec<String> = vec!["eval".into(), if m.strict { "--strict" } else { "--no-strict" }.into()];
|
||||
if m.out.to_lowercase().ends_with(".glb") {
|
||||
a.push("--scene".into());
|
||||
}
|
||||
a.extend(["--out".into(), m.out.clone()]);
|
||||
for (flag, v) in [("--unit", &m.unit), ("--render", &m.render), ("--size", &m.size), ("--draw", &m.draw)] {
|
||||
if let Some(v) = v {
|
||||
a.extend([flag.to_string(), v.clone()]);
|
||||
}
|
||||
}
|
||||
a.push(m.script.clone());
|
||||
a
|
||||
}
|
||||
|
||||
/// `raea forma fix FILE.glb... [--smooth DEG] [--flat]` (args after `fix`): needs no forma, only its files.
|
||||
pub fn fix(args: &[String]) -> R<String> {
|
||||
let mut smooth = Some(SMOOTH);
|
||||
let mut files = Vec::new();
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--smooth" => smooth = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--smooth takes degrees, 40 say")?),
|
||||
"--flat" => smooth = None,
|
||||
f if f.starts_with('-') => return Err(format!("raea forma fix has no {f}: {USAGE}")),
|
||||
f if f.to_lowercase().ends_with(".glb") => files.push(f),
|
||||
f => return Err(format!("{f} isn't a .glb: forma's .stl, .obj, .3mf and .step carry no colours to fix")),
|
||||
}
|
||||
}
|
||||
if files.is_empty() {
|
||||
return Err(format!("which .glb: {USAGE}"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for f in files {
|
||||
let fixed = glb::fix_file(Path::new(f), smooth)?;
|
||||
out.push(if fixed.already { format!("CHECKED {f}: fixed before, left alone") } else { format!("APPLIED {f}: {} colours made linear, {} meshes' normals smoothed", fixed.colours, fixed.primitives) });
|
||||
}
|
||||
Ok(out.join("\n"))
|
||||
}
|
||||
|
||||
/// `raea forma ...` (args with the verb): `spec` passes through to forma; a make runs forma, then fixes the .glb.
|
||||
pub fn forma(args: &[String]) -> R<String> {
|
||||
if args.get(1).map(String::as_str) == Some("fix") {
|
||||
return fix(&args[2..]);
|
||||
}
|
||||
let (f, _) = find()?.ok_or("no forma: raea setup forma finds or downloads it")?;
|
||||
if args.get(1).map(String::as_str) == Some("spec") {
|
||||
return run(f.command().arg("spec").args(&args[2..]), "forma spec");
|
||||
}
|
||||
let m = parse(&args[1..])?;
|
||||
if m.script != "-" && !Path::new(&m.script).is_file() {
|
||||
return Err(format!("no script {}", m.script));
|
||||
}
|
||||
let o = f.command().args(forma_args(&m)).stdin(Stdio::inherit()).output().map_err(|e| format!("{}: {e}", f.path().display()))?;
|
||||
let (out, err) = (String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
|
||||
if !o.status.success() {
|
||||
let why = if o.status.code() == Some(3) { " (not watertight: --no-strict writes it anyway)" } else { "" };
|
||||
return Err(format!("forma refused {}{why}: {}{}", m.script, err.trim(), if out.trim().is_empty() { String::new() } else { format!("\n{}", out.trim()) }));
|
||||
}
|
||||
let mut report = out.trim_end().to_string();
|
||||
if m.out.to_lowercase().ends_with(".glb") {
|
||||
let fixed = glb::fix_file(Path::new(&m.out), m.smooth)?;
|
||||
let normals = match m.smooth {
|
||||
Some(d) => format!("{} meshes' normals smoothed under {d}°", fixed.primitives),
|
||||
None => "normals flat as forma wrote them".into(),
|
||||
};
|
||||
report += &format!("\nAPPLIED {}: {} colours made linear, {normals}", m.out, fixed.colours);
|
||||
} else {
|
||||
report += &format!("\nAPPLIED {}", m.out);
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// The verbs here, or None for any other: `setup forma` and `forma ...`.
|
||||
pub fn cli(args: &[String]) -> Option<R<String>> {
|
||||
match (args.first()?.as_str(), args.get(1).map(String::as_str)) {
|
||||
("setup", Some("forma")) => Some(setup(&args[2..])),
|
||||
("forma", _) => Some(forma(args)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(s: &str) -> Vec<String> {
|
||||
s.split_whitespace().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_make_reads_its_flags_and_passes_forma_its_own() {
|
||||
let m = parse(&args("bolt.forma -o bolt.glb --unit mm --render b.png --smooth 30")).unwrap();
|
||||
assert_eq!((m.smooth, m.strict, m.unit.as_deref()), (Some(30.0), true, Some("mm")));
|
||||
assert_eq!(forma_args(&m).join(" "), "eval --strict --scene --out bolt.glb --unit mm --render b.png bolt.forma");
|
||||
let flat = parse(&args("p.forma -o p.stl --flat --no-strict")).unwrap();
|
||||
assert_eq!((flat.smooth, flat.strict), (None, false));
|
||||
assert_eq!(forma_args(&flat).join(" "), "eval --no-strict --out p.stl p.forma");
|
||||
assert_eq!(parse(&args("p.forma -o p.glb")).unwrap().smooth, Some(SMOOTH));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_make_refuses_what_it_cant_read() {
|
||||
assert!(parse(&args("p.forma")).unwrap_err().starts_with("usage:"));
|
||||
assert!(parse(&args("p.forma -o p.glb --bogus")).unwrap_err().contains("no --bogus"));
|
||||
assert!(parse(&args("a.forma b.forma -o p.glb")).unwrap_err().contains("one script"));
|
||||
assert!(parse(&args("p.forma -o p.glb --smooth soft")).is_err());
|
||||
assert!(parse(&args("p.forma -o")).unwrap_err().contains("takes a value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_flag_is_in_the_usage() {
|
||||
for f in ["--check", "--download", "--unit", "--render", "--draw", "--size", "--smooth", "--flat", "--no-strict", "--topic", "--gbnf"] {
|
||||
assert!(USAGE.contains(&format!("[{f}")), "{f}");
|
||||
}
|
||||
assert!(cli(&args("setup blender")).is_none() && cli(&args("render x.tsx")).is_none() && cli(&[]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digests_of_a_known_file() {
|
||||
let f = std::env::temp_dir().join(format!("raea-forma-digest-{}", std::process::id()));
|
||||
std::fs::write(&f, b"abc").unwrap();
|
||||
let (a, b) = (digest(&f, 256), digest(&f, 512));
|
||||
let _ = std::fs::remove_file(&f);
|
||||
assert_eq!(a.unwrap(), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
|
||||
assert!(b.unwrap().starts_with("ddaf35a193617aba"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fix_takes_only_glb_files() {
|
||||
assert!(fix(&args("part.stl")).unwrap_err().contains("isn't a .glb"));
|
||||
assert!(fix(&args("--flat")).unwrap_err().starts_with("which .glb"));
|
||||
assert!(fix(&args("a.glb --soft")).unwrap_err().contains("no --soft"));
|
||||
let d = std::env::temp_dir().join(format!("raea-forma-fix-{}.glb", std::process::id()));
|
||||
std::fs::write(&d, glb::write(&serde_json::json!({"asset": {"version": "2.0"}, "materials": [{"pbrMetallicRoughness": {"baseColorFactor": [0.5, 0.5, 0.5, 1.0]}}]}), &[])).unwrap();
|
||||
let p = d.to_string_lossy().to_string();
|
||||
let (first, again) = (fix(std::slice::from_ref(&p)), fix(&[p]));
|
||||
let _ = std::fs::remove_file(&d);
|
||||
assert!(first.unwrap().contains("1 colours made linear") && again.unwrap().contains("fixed before"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_names_its_kind() {
|
||||
assert_eq!(at(PathBuf::from("/x/forma")).unwrap(), Forma::Native(PathBuf::from("/x/forma")));
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
+170
-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 {
|
||||
/// a 3D drawer (Bevy's programs, its scene read by three.js), for a game with a 3D kind (PA11, PA15)
|
||||
with_3d: bool,
|
||||
sounds: Sounds,
|
||||
/// Bevy's world as wasm, for a game that makes a raea/ecs World (PA12)
|
||||
ecs: bool,
|
||||
}
|
||||
|
||||
/// The bundle's entry: Bevy's world first for a game on raea/ecs (PA12: a World made as the game's module loads is
|
||||
/// already Bevy's), the game, then the host started with Bevy's PBR programs as its 3D drawer (PA11) only for a game
|
||||
/// with 3D (PA15: a 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
|
||||
/// raea/tone graph (PA6)
|
||||
fn entry(game: &Path, host: &Path, carry: Carry) -> String {
|
||||
let Carry { with_3d, sounds, ecs } = carry;
|
||||
let first = if ecs { format!("import {:?};\n", spec(&host.join("ecs.ts"))) } else { String::new() };
|
||||
let mut e = format!("{first}import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
|
||||
if with_3d {
|
||||
e.push_str(&format!("import {{ bevy3d }} from {:?};\n", spec(&host.join("bevy.ts"))));
|
||||
}
|
||||
if sounds != Sounds::None {
|
||||
e.push_str(&format!("import {{ sound }} from {:?};\n", spec(&host.join("sound.ts"))));
|
||||
}
|
||||
if sounds == Sounds::Tone {
|
||||
e.push_str(&format!("import {{ tone }} from {:?};\n", spec(&host.join("tone.ts"))));
|
||||
}
|
||||
let d3 = if with_3d { "bevy3d" } else { "undefined" };
|
||||
e.push_str(&match sounds {
|
||||
Sounds::None if with_3d => "start(bevy3d);\n".into(),
|
||||
Sounds::None => "start();\n".into(),
|
||||
Sounds::Media => format!("start({d3}, sound());\n"),
|
||||
Sounds::Tone => format!("start({d3}, sound(tone));\n"),
|
||||
});
|
||||
e
|
||||
}
|
||||
|
||||
/// The game and the host in one minified script that carries its files
|
||||
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,57 @@ 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("bevy3d } from \"/h/host/bevy.ts\"") && e.contains("start(bevy3d);"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_game_with_sound_starts_with_its_player_and_tone_only_for_a_graph() {
|
||||
let media = e(false, Sounds::Media, false);
|
||||
assert!(media.contains("start(undefined, sound());") && !media.contains("tone"), "{media}");
|
||||
let tone = e(true, Sounds::Tone, false);
|
||||
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(bevy3d, sound(tone));"), "{tone}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_game_on_raea_ecs_loads_bevys_world_before_the_game() {
|
||||
let e = e(false, Sounds::None, true);
|
||||
assert!(e.starts_with("import \"/h/host/ecs.ts\";\nimport \"/g/game.tsx\";"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_carried_ecs_wasm_is_built_from_runtime_ecs_as_it_is() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/ecs/from.sh")).output().expect("bash");
|
||||
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/ecs.wasm.from")).unwrap_or_default();
|
||||
assert_eq!(built.trim(), now, "runtime/ecs changed since ecs.wasm was built: bash sdk/playable/ecs/build.sh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_carried_bevy_programs_are_made_from_bevys_shaders_as_they_are() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/bevy/from.sh")).output().expect("bash");
|
||||
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/bevy/programs.from")).unwrap_or_default();
|
||||
assert_eq!(built.trim(), now, "Bevy's shaders or tools/bevy-glsl changed since programs.ts was made: bash sdk/playable/bevy/build.sh");
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ raea-io-assets = { path = "../../io/assets" }
|
||||
# generation flows: made.app, fal, Replicate, OpenRouter, Modal, ComfyUI (`raea gen`)
|
||||
raea-io-gen = { path = "../../io/gen" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# the forma version the `forma` MCP server is pinned to (agent_mcp.rs; forma itself is fetched by npx, never linked)
|
||||
raea-app-forma = { path = "../forma" }
|
||||
raea-io-media = { path = "../../io/media", default-features = false }
|
||||
serde_json = "1"
|
||||
# the verbs' flags read as a render reads its own
|
||||
|
||||
+56
-29
@@ -1,14 +1,26 @@
|
||||
//! The MCP servers `raea skills install` offers an agent (docs/skills.feature SK11): today `blender`, which drives a
|
||||
//! running Blender through the MCP for Blender add-on (`raea setup blender` installs it). Each agent keeps MCP servers
|
||||
//! in its own place; a server already registered under the name is left as the person set it.
|
||||
//! The MCP servers `raea skills install` offers an agent (docs/skills.feature SK11): `blender`, which drives a running
|
||||
//! Blender through the MCP for Blender add-on (`raea setup blender` installs it), and `forma`, forma's own server for
|
||||
//! modelling hard-surface parts in a few lines (docs/forma.feature FM6). Each agent keeps MCP servers in its own place;
|
||||
//! a server already registered under the name is left as the person set it.
|
||||
use serde_json::{json, Value};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// The blender MCP server: uv runs it, so nothing is installed until an agent starts it.
|
||||
const NAME: &str = "blender";
|
||||
const CMD: &str = "uvx";
|
||||
const ARGS: [&str; 1] = ["mcp-for-blender"];
|
||||
/// An MCP server raea offers: its name, the program, its arguments.
|
||||
pub struct Server {
|
||||
pub name: &'static str,
|
||||
pub cmd: &'static str,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
/// The servers raea offers. Each is fetched by its runner when an agent first starts it, so nothing is installed here:
|
||||
/// blender by uv's uvx, forma (GPL-3.0-or-later, its own program) by npm's npx at the version raea is tested with.
|
||||
/// Windows starts npx through cmd, as npx there is a .cmd script.
|
||||
pub fn servers() -> Vec<Server> {
|
||||
let forma = ["-y".to_string(), "-p".into(), format!("forma-3d@{}", raea_app_forma::VERSION), "forma-3d-mcp".into()];
|
||||
let (cmd, args) = if cfg!(windows) { ("cmd", ["/c".to_string(), "npx".into()].into_iter().chain(forma).collect()) } else { ("npx", forma.to_vec()) };
|
||||
vec![Server { name: "blender", cmd: "uvx", args: vec!["mcp-for-blender".into()] }, Server { name: "forma", cmd, args }]
|
||||
}
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
@@ -28,18 +40,18 @@ fn json_file(agent: &str) -> R<Option<PathBuf>> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds `blender` to a JSON config's `mcpServers` unless one is there; true when it added.
|
||||
pub fn add_json(path: &Path) -> R<bool> {
|
||||
/// Adds a server to a JSON config's `mcpServers` unless one of its name is there; true when it added.
|
||||
pub fn add_json(path: &Path, sv: &Server) -> R<bool> {
|
||||
let mut doc: Value = match std::fs::read_to_string(path) {
|
||||
Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", path.display()))?,
|
||||
_ => json!({}),
|
||||
};
|
||||
let servers = doc.as_object_mut().ok_or_else(|| format!("{} isn't a JSON object", path.display()))?.entry("mcpServers").or_insert_with(|| json!({}));
|
||||
let servers = servers.as_object_mut().ok_or_else(|| format!("{}: mcpServers isn't an object", path.display()))?;
|
||||
if servers.contains_key(NAME) {
|
||||
if servers.contains_key(sv.name) {
|
||||
return Ok(false);
|
||||
}
|
||||
servers.insert(NAME.into(), json!({"command": CMD, "args": ARGS}));
|
||||
servers.insert(sv.name.into(), json!({"command": sv.cmd, "args": sv.args}));
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
@@ -49,45 +61,52 @@ pub fn add_json(path: &Path) -> R<bool> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Adds a `[mcp_servers.blender]` table to Codex's config.toml unless one is there; true when it added.
|
||||
pub fn add_toml(path: &Path) -> R<bool> {
|
||||
/// Adds a `[mcp_servers.NAME]` table to Codex's config.toml unless one is there; true when it added.
|
||||
pub fn add_toml(path: &Path, sv: &Server) -> R<bool> {
|
||||
let text = std::fs::read_to_string(path).unwrap_or_default();
|
||||
if text.lines().any(|l| l.trim() == format!("[mcp_servers.{NAME}]")) {
|
||||
let (name, cmd) = (sv.name, sv.cmd);
|
||||
if text.lines().any(|l| l.trim() == format!("[mcp_servers.{name}]")) {
|
||||
return Ok(false);
|
||||
}
|
||||
let args = ARGS.iter().map(|a| format!("{a:?}")).collect::<Vec<_>>().join(", ");
|
||||
let args = sv.args.iter().map(|a| format!("{a:?}")).collect::<Vec<_>>().join(", ");
|
||||
let sep = if text.is_empty() || text.ends_with("\n\n") { "" } else if text.ends_with('\n') { "\n" } else { "\n\n" };
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
std::fs::write(path, format!("{text}{sep}[mcp_servers.{NAME}]\ncommand = {CMD:?}\nargs = [{args}]\n")).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
std::fs::write(path, format!("{text}{sep}[mcp_servers.{name}]\ncommand = {cmd:?}\nargs = [{args}]\n")).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Registers the blender MCP server for an agent; the line says what happened. Claude Code rewrites ~/.claude.json while
|
||||
/// it runs, so its own `claude mcp add` is used when `claude` is on PATH.
|
||||
/// Registers every server raea offers for an agent, a line each saying what happened.
|
||||
pub fn offer(agent: &str) -> R<String> {
|
||||
let line = |added: bool, at: &Path| if added { format!("{}: MCP server {NAME} added", at.display()) } else { format!("{}: MCP server {NAME} already there", at.display()) };
|
||||
servers().iter().map(|sv| offer_one(agent, sv)).collect::<R<Vec<_>>>().map(|l| l.join("\n"))
|
||||
}
|
||||
|
||||
/// Registers one MCP server for an agent; the line says what happened. Claude Code rewrites ~/.claude.json while it
|
||||
/// runs, so its own `claude mcp add` is used when `claude` is on PATH.
|
||||
fn offer_one(agent: &str, sv: &Server) -> R<String> {
|
||||
let name = sv.name;
|
||||
let line = |added: bool, at: &Path| if added { format!("{}: MCP server {name} added", at.display()) } else { format!("{}: MCP server {name} already there", at.display()) };
|
||||
if agent == "codex" {
|
||||
let p = user_home()?.join(".codex/config.toml");
|
||||
return Ok(line(add_toml(&p)?, &p));
|
||||
return Ok(line(add_toml(&p, sv)?, &p));
|
||||
}
|
||||
let p = json_file(agent)?.ok_or_else(|| format!("no agent {agent:?}"))?;
|
||||
if agent == "claude" {
|
||||
let listed = Command::new("claude").args(["mcp", "get", NAME]).output();
|
||||
let listed = Command::new("claude").args(["mcp", "get", name]).output();
|
||||
match listed {
|
||||
Ok(o) if o.status.success() => return Ok(line(false, &p)),
|
||||
Ok(_) => {
|
||||
let o = Command::new("claude").args(["mcp", "add", "--scope", "user", NAME, "--", CMD]).args(ARGS).output().map_err(|e| e.to_string())?;
|
||||
let o = Command::new("claude").args(["mcp", "add", "--scope", "user", name, "--", sv.cmd]).args(&sv.args).output().map_err(|e| e.to_string())?;
|
||||
if !o.status.success() {
|
||||
return Err(format!("claude mcp add {NAME}: {}", String::from_utf8_lossy(&o.stderr).trim()));
|
||||
return Err(format!("claude mcp add {name}: {}", String::from_utf8_lossy(&o.stderr).trim()));
|
||||
}
|
||||
return Ok(line(true, &p));
|
||||
}
|
||||
Err(_) => {} // no claude on PATH: write its file
|
||||
}
|
||||
}
|
||||
Ok(line(add_json(&p)?, &p))
|
||||
Ok(line(add_json(&p, sv)?, &p))
|
||||
}
|
||||
|
||||
/// A move's guide as a skill of its own, named for the move: its description from the guide's first paragraph.
|
||||
@@ -115,18 +134,26 @@ mod tests {
|
||||
let d = std::env::temp_dir().join(format!("raea-agent-mcp-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
let j = d.join("kimi/mcp.json");
|
||||
assert!(add_json(&j).unwrap());
|
||||
assert!(!add_json(&j).unwrap());
|
||||
let all = servers();
|
||||
let (blender, forma) = (&all[0], &all[1]);
|
||||
assert!(add_json(&j, blender).unwrap());
|
||||
assert!(!add_json(&j, blender).unwrap());
|
||||
std::fs::write(&j, r#"{"theme":"dark","mcpServers":{"blender":{"command":"mine"}}}"#).unwrap();
|
||||
assert!(!add_json(&j).unwrap());
|
||||
assert!(!add_json(&j, blender).unwrap());
|
||||
assert!(add_json(&j, forma).unwrap());
|
||||
let kept: Value = serde_json::from_str(&std::fs::read_to_string(&j).unwrap()).unwrap();
|
||||
assert_eq!(kept["mcpServers"]["blender"]["command"], "mine");
|
||||
assert_eq!(kept["theme"], "dark");
|
||||
let pinned = format!("forma-3d@{}", raea_app_forma::VERSION);
|
||||
assert!(kept["mcpServers"]["forma"]["args"].as_array().unwrap().iter().any(|a| a == pinned.as_str()), "{kept}");
|
||||
let t = d.join("codex/config.toml");
|
||||
std::fs::create_dir_all(t.parent().unwrap()).unwrap();
|
||||
std::fs::write(&t, "model = \"x\"\n").unwrap();
|
||||
assert!(add_toml(&t).unwrap());
|
||||
assert!(!add_toml(&t).unwrap());
|
||||
assert!(add_toml(&t, blender).unwrap());
|
||||
assert!(!add_toml(&t, blender).unwrap());
|
||||
assert_eq!(std::fs::read_to_string(&t).unwrap(), "model = \"x\"\n\n[mcp_servers.blender]\ncommand = \"uvx\"\nargs = [\"mcp-for-blender\"]\n");
|
||||
assert!(add_toml(&t, forma).unwrap());
|
||||
assert!(std::fs::read_to_string(&t).unwrap().contains(&format!("[mcp_servers.forma]\ncommand = {:?}\n", forma.cmd)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ pub mod song;
|
||||
pub mod sound;
|
||||
pub mod splat;
|
||||
|
||||
/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender)
|
||||
/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender; forma, for hard-surface parts)
|
||||
pub mod agent_mcp;
|
||||
pub mod agent_hooks;
|
||||
/// Grok Bot as a `raea skills install` target: its copy staged on this Mac, and the links that finish it in Grok Bot
|
||||
|
||||
@@ -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`"))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
@spec
|
||||
Feature: forma, a headless modeller for hard-surface parts, run as its own program
|
||||
Shane, 2026-12-03, on github.com/wrong-nebula/forma: "can we make this an external package and integration we can
|
||||
use or allow agents to download... its a gpl license so idk what that means for us". forma is a ~1 MB pure-Rust
|
||||
modeller built for agents: a few lines of its pipe language (`box(4, 2, 0.4) | bevel(vertical, 0.25) | cut(cyl(0.5,
|
||||
1))`) make a watertight mesh with exact sizes in milliseconds, with semantic edge and face selectors instead of vertex
|
||||
indices. On 12-03 ten parts (gears, a flange, a threaded bolt, a mug, an enclosure, a lathed pawn, a lofted bottle,
|
||||
a table, a desk lamp, a lettered plate) each built in about 0.2 s through its npm CLI, and loaded straight into raea
|
||||
with <Model>. Two faults showed under raea's light: every colour pale (forma writes the sRGB value it was given into
|
||||
baseColorFactor, which glTF reads as linear) and every curve faceted (one normal per face). Its text is a blocky
|
||||
capitals-only face, and it can't make anything organic.
|
||||
|
||||
The licence: forma is GPL-3.0-or-later, raea is FSL-1.1, and the two can't be combined into one program. So raea
|
||||
never links forma's crates or bundles its WebAssembly into the SDK, the CLI or the apps. raea downloads forma's own
|
||||
release and runs it as a separate program, as it already does Blender (apps/tools/src/blender.rs), and works only
|
||||
on the files forma writes. The GPL covers forma, not what it makes, and running it on raea cloud isn't distributing
|
||||
it (GPLv3, not the AGPL).
|
||||
|
||||
Where it sits beside raea's own modelling (docs/blender.feature's framing): TSX is the scene; solids, sdf and grow
|
||||
make what numbers or rules define inside raea; forma is a faster way to make a hard-surface part an agent can check
|
||||
by its numbers (watertight, volume, box) before anyone looks; Blender stays the workshop for assets that are already
|
||||
good; raea gen and CC0 libraries make what looks define.
|
||||
|
||||
Background:
|
||||
Given raea pins one forma version (apps/forma VERSION, 0.4.4) with a hash for each download it makes
|
||||
And forma lives in ~/.raea/tools/forma, or wherever `git config --global raea.forma` points
|
||||
|
||||
Rule: Getting forma
|
||||
|
||||
@done
|
||||
Scenario: FM1. raea setup forma finds forma or downloads the pinned version
|
||||
Given `raea setup forma [--check] [--download]`
|
||||
When no forma is found (raea.forma, raea's download, a `forma` on PATH that says it is forma)
|
||||
Then on Linux (x86_64, aarch64) forma's static musl binary is downloaded from its GitHub release and checked
|
||||
against its pinned sha256: it needs no Node
|
||||
And elsewhere forma's npm package (forma-3d) is downloaded from the npm registry and checked against its pinned
|
||||
sha512, to be run by Node 18+ or Bun; with neither on PATH it says so before downloading anything
|
||||
And a download that doesn't match its hash installs nothing and says where it left the file
|
||||
And --check only says what would be used; --download replaces what is there
|
||||
And the report names forma's version, where it came from, and that forma is GPL and runs as its own program
|
||||
|
||||
Rule: Making parts
|
||||
|
||||
@done
|
||||
Scenario: FM2. raea forma makes a script's parts, strict by default
|
||||
Given `raea forma SCRIPT.forma -o OUT.glb|.stl|.obj|.3mf|.step [--unit U] [--render P.png] [--draw B.svg]`
|
||||
Then forma evaluates the script with --strict, and a .glb gets one node per named part (--scene)
|
||||
And forma's report (each part's vertices, watertight, volume, box) is printed as it wrote it
|
||||
And a part that isn't watertight is refused with forma's reason and nothing is written, unless --no-strict
|
||||
And a flag raea forma doesn't know is refused with the usage
|
||||
And `raea forma spec [--topic T] [--gbnf]` prints forma's own language reference
|
||||
|
||||
@done
|
||||
Scenario: FM3. A .glb's colours are made linear, as glTF reads them
|
||||
Given a .glb forma wrote, its baseColorFactor typed as sRGB
|
||||
Then each material's colour is converted sRGB to linear (alpha kept), so terracotta reads terracotta under raea's
|
||||
light and not pink
|
||||
And the file is marked in asset.extras.raea_forma, and a marked file is never converted twice
|
||||
And `raea forma fix FILE.glb... [--smooth DEG] [--flat]` does FM3 and FM4 to a .glb forma wrote by itself (its
|
||||
MCP server's export), with no forma needed
|
||||
|
||||
@done
|
||||
Scenario: FM4. A .glb's normals are smoothed where faces meet at under 40 degrees
|
||||
Given forma's one normal per face
|
||||
Then each corner takes the area-weighted mean of the faces at its position whose facing is within DEG of its own
|
||||
(--smooth DEG, 40 unless given), so a box keeps its edges and a cylinder's side turns round
|
||||
And positions, indices, UVs and the file's layout are kept byte for byte; only the normals' bytes change
|
||||
And --flat keeps forma's normals; a primitive with tangents, or one in a layout the fix doesn't read, is left alone
|
||||
|
||||
Scenario: FM5. The fixed parts under raea's light match what the script asked for
|
||||
Given the 12-03 table (scratchpad forma-try): ten parts made by `raea forma`, loaded with <Model>, one still
|
||||
Then each part's lit colour is within a JND of its typed colour lit the same way in a raea <Cuboid>
|
||||
And no curved part shows facets in a 4x crop
|
||||
|
||||
Rule: Agents
|
||||
|
||||
@done
|
||||
Scenario: FM6. raea skills install adds forma's MCP server
|
||||
Given `raea skills install --agent claude|codex|kimi|gemini`
|
||||
Then beside `blender`, a `forma` MCP server is registered: `npx -y -p forma-3d@VERSION forma-3d-mcp` (through
|
||||
`cmd /c` on Windows), fetched by npx when the agent first starts it
|
||||
And a server the person already registered under the name is left as they set it; --no-mcp adds neither
|
||||
|
||||
Scenario: FM7. The raea skill says when forma is the tool and when it isn't
|
||||
Given the raea skill (raea-skills, skills/raea/3d.md)
|
||||
Then it names forma for hard-surface parts numbers define (mechanical parts, props with exact sizes, a blockout's
|
||||
furniture) and `raea forma` over forma's own CLI, so the .glb comes out fixed
|
||||
And it names what forma is wrong for: anything organic (people, animals, cloth, plants), textures, lettering
|
||||
that has to look good, and the scene itself, which stays TSX
|
||||
And it says the MCP server's exports aren't fixed: a part meant for a render goes through `raea forma`, or
|
||||
`raea forma fix FILE.glb` after the server exported it
|
||||
@@ -13,9 +13,12 @@ every project to import as `@shared/components/NAME`. `raea part` is the old nam
|
||||
Beside raea's own sets is the library: several hundred open-source components (text reveals, counters, charts,
|
||||
transitions, product-screen demos, game HUDs and more), sorted by what they're for rather than who made them.
|
||||
`raea make component list` ends with its categories; `list WORDS` searches it by a category (`text`), a category and
|
||||
type (`text/reveal`), or words in a name or description (`"count up"`). `add NAME` copies the component into
|
||||
`components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's first line names
|
||||
the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
|
||||
type (`text/reveal`), a name or the name it had upstream, the phrases people ask for it with (`"chat input"`,
|
||||
`composer`, `"lower third"`, `template`), or words in what it does (`"count up"`). `show NAME` tells one in full: what
|
||||
it draws and how it moves, when to use it and when not, the size and length it was designed at, and each prop with its
|
||||
type, default and what it does; `--json` gives the same as JSON, for every hit of a `list`. `add NAME` copies the
|
||||
component into `components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's
|
||||
first line names the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
|
||||
|
||||
```sh
|
||||
raea make component list
|
||||
@@ -23,6 +26,8 @@ raea make component add captions end-card
|
||||
raea make component add reel --shared
|
||||
raea make component list text/reveal
|
||||
raea make component list count up
|
||||
raea make component list chat input
|
||||
raea make component show prompt-send
|
||||
raea make component add soft-blur-in
|
||||
```
|
||||
|
||||
@@ -31,7 +36,7 @@ raea make component add soft-blur-in
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, "count up")
|
||||
raea make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, "count up", "chat input", template; show tells one in full: what it draws, when to use it and when not, its props)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -41,6 +46,7 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--force` | – | Replace a component's files that are already there. Without it, an existing component is left alone and the command stops. |
|
||||
| `--json` | – | The library's items as JSON (`list`: every hit, best first; `show`: the one), each with its props, when to use it and when not, and the phrases it's asked for with. |
|
||||
| `--shared` | – | Copy into the workspace's `shared/components/` instead, where every project in the workspace imports it as `/components/NAME`. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -0,0 +1,62 @@
|
||||
---
|
||||
title: "raea forma"
|
||||
summary: "Make hard-surface parts from a few lines of forma's language: watertight meshes with exact sizes, written as a .glb raea renders."
|
||||
order: 117
|
||||
sources: ["apps/forma/src/lib.rs", "apps/forma/src/glb.rs", "apps/tools/src/agent_mcp.rs"]
|
||||
---
|
||||
|
||||
`raea forma` runs [forma](https://github.com/wrong-nebula/forma), a headless modeller for hard-surface parts, on a
|
||||
script in its pipe language, and writes the parts it makes: gears, brackets, threaded bolts, enclosures, a lathed vase,
|
||||
a table and its legs. Each named part is its own node in the .glb, every mesh is checked watertight, and a script
|
||||
evaluates in milliseconds, so an agent can write a part, read forma's report (sizes, volume, whether it is watertight)
|
||||
and change it in the same turn. Load the .glb with `<Model>` and light it in raea.
|
||||
|
||||
forma writes a material's colour as it was typed into the .glb, where glTF reads linear colour, so every part would
|
||||
render pale; and it writes one normal per face, so a curved side shows its facets. `raea forma` fixes both in the file
|
||||
after forma writes it: colours made linear, and corners smoothed where faces meet at under 40 degrees (a box keeps its
|
||||
edges, a cylinder's side turns round). The file is marked as fixed and never fixed twice. `raea forma fix` does the
|
||||
same to a .glb forma wrote by itself, through its MCP server or its own CLI.
|
||||
|
||||
forma is GPL-3.0-or-later, so raea never links it or ships it. [`raea setup forma`](setup.md) downloads forma's own
|
||||
release into `~/.raea/tools/forma` and `raea forma` runs it as a program of its own. What forma makes is yours.
|
||||
|
||||
```sh
|
||||
raea setup forma
|
||||
raea forma spec # the language, about 500 tokens
|
||||
raea forma bracket.forma -o assets/bracket.glb # strict: refused with forma's reason unless watertight
|
||||
raea forma gears.forma --unit mm -o assets/gears.glb --draw gears.svg
|
||||
raea forma fix assets/vase.glb # one the MCP server exported
|
||||
```
|
||||
|
||||
Use it for parts that numbers define: mechanical parts, props with exact sizes, a blockout's furniture. It is the wrong
|
||||
tool for anything organic (people, animals, cloth, plants), for textures, and for the scene itself, which stays TSX.
|
||||
`raea skills install` adds forma's own MCP server to an agent as `forma`, for modelling a part over several turns.
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea forma SCRIPT.forma -o OUT.glb|.stl|.obj|.3mf|.step [--unit m|cm|mm|um|in|ft] [--render PREVIEW.png] [--draw BLUEPRINT.svg] [--size PX] [--smooth DEG] [--flat] [--no-strict] (a forma script made into OUT, each named part its own node; a mesh that isn't watertight is refused with forma's reason unless --no-strict; a .glb's colours are made linear, as glTF reads them, and its normals smoothed where faces meet under DEG degrees (40 unless given; --flat keeps forma's faceted ones); --render's preview draws the last part, raea render draws them all)
|
||||
raea forma fix FILE.glb... [--smooth DEG] [--flat] (the same fix on a .glb forma wrote by itself (its MCP server's export, its own CLI): colours linear, normals smoothed; a file fixed before is left alone)
|
||||
raea forma spec [--topic deform|curves|uv|remesh|scene] [--gbnf] (forma's language reference, about 500 tokens: its primitives, operations and selectors)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--draw` | `BLUEPRINT.svg` | Also write a dimensioned SVG drawing of the parts. |
|
||||
| `--flat` | – | Keep forma's normals, one per face, faceted. |
|
||||
| `--gbnf` | – | With `spec`: print forma's GBNF grammar, for constrained decoding. |
|
||||
| `--no-strict` | – | Write the mesh even when it isn't watertight. |
|
||||
| `--render` | `PREVIEW.png` | Also write forma's own PNG preview (four views of the last part). |
|
||||
| `--size` | `PX` | The preview's size in pixels (512 unless given). |
|
||||
| `--smooth` | `DEG` | Smooth normals where faces meet at under DEG degrees (40 unless given). |
|
||||
| `--topic` | `deform\|curves\|uv\|remesh\|scene` | With `spec`: one topic's reference. |
|
||||
| `--unit` | `m\|cm\|mm\|um\|in\|ft` | The unit the script is written in (metres unless given); a .glb is always in metres. |
|
||||
| `-o` | `OUT.glb\|.stl\|.obj\|.3mf\|.step` | Where to write the parts; a .glb gets its colours and normals fixed. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -101,7 +101,7 @@ Music read, voices, and the audio setup.
|
||||
|
||||
## raea make: the asset tools
|
||||
|
||||
What a project is made from, each a `raea make TOOL`: components, solids, clothes and motion for SOMA's body, splats, physics, light and weathering bakes, foley and instruments; and generated media, Blender and Godot.
|
||||
What a project is made from, each a `raea make TOOL`: components, solids, clothes and motion for SOMA's body, splats, physics, light and weathering bakes, foley and instruments; and generated media, Blender, Godot and forma.
|
||||
|
||||
| Verb | What it does |
|
||||
| --- | --- |
|
||||
@@ -120,6 +120,7 @@ What a project is made from, each a `raea make TOOL`: components, solids, clothe
|
||||
| [`raea gen`](gen.md) | Generate images, video, music, sound, speech, 3D models and text through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI. |
|
||||
| [`raea blender`](blender.md) | Run a Blender Python script headless, with raea's library of mesh scripts: convert, decimate, repair, split, bake, rig, cloth. |
|
||||
| [`raea godot`](godot.md) | Run a TypeScript script against Godot's whole API in a headless Godot with GodotJS, record what it draws as frames, or open the editor on the project. |
|
||||
| [`raea forma`](forma.md) | Make hard-surface parts from a few lines of forma's language: watertight meshes with exact sizes, written as a .glb raea renders. |
|
||||
|
||||
## Agents and setup
|
||||
|
||||
@@ -133,8 +134,8 @@ What an agent reads and shows the person, and the tools raea installs.
|
||||
| [`raea notes`](notes.md) | A person's notes as files the work is held to: each taken word for word, then restated as asks before anything changes. |
|
||||
| [`raea show`](show.md) | Show the person something in the raea app, as an item they can use and answer: stills, a video, a sound, a script, an interactive .tsx or a question. |
|
||||
| [`raea skill`](skill.md) | Print the agent skill this raea ships, matched to its version, or one of its references. |
|
||||
| [`raea skills`](skills.md) | Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP server and hook. |
|
||||
| [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on. |
|
||||
| [`raea skills`](skills.md) | Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP servers and hook. |
|
||||
| [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on; or download forma, Godot and the motion models. |
|
||||
| [`raea bug`](bug.md) | Report a bug in raea itself to raea's server: a line saying what's wrong and what happened, with raea's version and the OS added, no account needed. |
|
||||
| [`raea ask`](ask.md) | Ask about a piece's picture and sound: clef-omni answers in words and a probability, paid from your raea plan, and every answer is kept so a question can be calibrated. |
|
||||
|
||||
|
||||
@@ -20,15 +20,16 @@ import the file instead), URLs and network calls, modules that need the native e
|
||||
kinds the playable's renderer doesn't draw. It notes a game with only one orientation, and one that never imports
|
||||
`raea/playable` (`<EndCard>`, `<InstallButton>`, `install()`) to open the store itself.
|
||||
|
||||
The 3D is drawn by three.js on raea's scene contract, with Bevy's light units and tone mapping. It comes from the
|
||||
project (`raea add [email protected]`).
|
||||
The 3D is drawn by Bevy's own PBR shaders, translated to WebGL2 when raea is built, with Bevy's light units,
|
||||
shadows, fog and TonyMcMapface tone mapping. three.js reads the page's 3D parts into a scene for them, so it comes from
|
||||
the project (`raea add [email protected]`). A game with no 3D ships without either.
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
---
|
||||
title: "raea setup"
|
||||
summary: "Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on."
|
||||
summary: "Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on; or download forma, Godot and the motion models."
|
||||
order: 129
|
||||
sources: ["apps/tools/src/blender.rs"]
|
||||
sources: ["apps/tools/src/blender.rs", "apps/forma/src/lib.rs"]
|
||||
---
|
||||
|
||||
`raea setup blender` finds the Blender on this machine (from `git config raea.blender`, raea's own copy, /Applications or the `PATH`), or downloads the current LTS from blender.org into `~/.raea/tools/blender`. It then installs the add-on that
|
||||
lets an agent drive Blender over MCP. [`raea blender run`](blender.md) uses the Blender it found.
|
||||
|
||||
`raea setup forma` finds forma (from `git config raea.forma`, raea's own copy or the `PATH`), or downloads forma
|
||||
itself into `~/.raea/tools/forma`: its static binary on Linux, else its npm package, run by Node 18+ or Bun. Each is
|
||||
checked against the hash raea pins. forma is GPL-3.0-or-later, so it is fetched from forma's own release and never
|
||||
shipped with raea; [`raea forma`](forma.md) runs it as a program of its own.
|
||||
|
||||
```sh
|
||||
raea setup blender --check
|
||||
raea setup blender
|
||||
raea setup forma
|
||||
```
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
@@ -19,6 +25,7 @@ raea setup blender
|
||||
|
||||
```sh
|
||||
raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install raea's add-on and the MCP add-on)
|
||||
raea setup forma [--check] [--download] (find forma or download it into ~/.raea/tools/forma: forma 0.4.4, a headless modeller for hard-surface parts (GPL-3.0-or-later, so raea runs it as its own program and never ships it), its static binary on Linux, else its npm package run by Node 18+ or Bun, each checked against its pinned hash)
|
||||
raea setup motion [--check] (what raea make motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU)
|
||||
raea setup godot [--check] (download Godot 4.6.1 with GodotJS, its TypeScript bindings (MIT), into ~/.raea/tools/godot: JavaScriptCore on the Mac, QuickJS on Windows and Linux; raea's own build (the Mac's notarized), else GodotJS's, each checked against its pinned sha256)
|
||||
```
|
||||
@@ -29,7 +36,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--check` | – | Say which Blender would be used, without downloading or installing anything. |
|
||||
| `--download` | – | Download the LTS even when a Blender is already on this machine. |
|
||||
| `--check` | – | Say which Blender (or forma) would be used, without downloading or installing anything. |
|
||||
| `--download` | – | Download the LTS (or forma's pinned version) even when one is already on this machine. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -38,6 +38,7 @@ comment read as asks is a note: it closes when the person retires it, and the ap
|
||||
raea show out/look-1.png out/look-2.png out/look-3.png --ask "Which of these three?"
|
||||
raea show out/cut.mp4 --replaces i-show-2f9c
|
||||
raea show --question "Warmer or cooler grade?" --choice Warmer --choice Cooler
|
||||
raea show --choose "Warm grade" out/warm-1.png out/warm-2.png --choose "Cool grade" out/cool-1.png --recommend 2
|
||||
raea show --question "Which opening?" --choice Slam --preview out/slam.mp4 --choice Drift --preview out/drift.mp4 \
|
||||
--question "Narrator speed?" --preview voice/take.mp3 --choice "As is" --choice Faster
|
||||
raea show --on i-show-2f9c --working c-3 --sub "grade pass"
|
||||
@@ -51,7 +52,7 @@ raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Wa
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
|
||||
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --choose LABEL FILE... --choose LABEL FILE... [--recommend N] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --choose LABEL FILE... once per option (2 to 6) for the person to pick one, --recommend N the one you would (nothing is picked for them), their pick back as {"kind":"answer","choice":LABEL}; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
|
||||
```
|
||||
|
||||
Needs the raea app's host running on this machine; then waits for a person's click in the raea app (to answer). Takes any number of arguments besides its flags.
|
||||
@@ -63,6 +64,7 @@ Needs the raea app's host running on this machine; then waits for a person's cli
|
||||
| `--as` | `NAME` | Who's showing it, as the feed names them (your harness's name when left out: Claude Code, Codex, Gemini). |
|
||||
| `--ask` | `LINE` | What you want from the person, shown with the item. With `--on` and `--working`: one ask you read the comment as (give it once per ask), shown on the comment for the person to correct. |
|
||||
| `--choice` | `A` | With `--question`: one answer to pick; give it once per answer. Stills given instead are the choices. |
|
||||
| `--choose` | `LABEL FILE...` | One option for the person to pick, named, its files after it; give it once per option, 2 to 6. Their pick comes back as `{"kind":"answer","choice":LABEL}`. |
|
||||
| `--clip` | `FILE` | With `--sign`: the clip the person is to sign, cut from the render (`raea notes check` cuts it). |
|
||||
| `--despite` | `CHECK WHY` | A check the render still fails, and why it goes to the person anyway; give it once per check. `raea show` refuses a render whose record still holds an error, naming each, and the why is shown on the item. |
|
||||
| `--detail` | `PARAGRAPH` | The paragraph the viewer opens from the `--label` before it. |
|
||||
@@ -76,6 +78,7 @@ Needs the raea app's host running on this machine; then waits for a person's cli
|
||||
| `--preview` | `FILE` | A still, video, sound, script or `.md` the person can play or read while answering. After a `--choice` it is that choice's preview, otherwise the question's. |
|
||||
| `--project` | `P` | The project to post to: its id, title or `Workspace/project`. The project this folder is in when left out. |
|
||||
| `--question` | `Q` | Ask the person this, with `--choice` answers or stills to pick from. |
|
||||
| `--recommend` | `N` | With `--choose`: the option you'd pick, from 1, marked on it. Nothing is picked for the person. |
|
||||
| `--render` | `HASH` | With `--sign`: the sha256 of the render the clip was cut from, which the person's sign names. |
|
||||
| `--replaces` | `ITEM` | The item this is the next version of, so the feed shows it as that item's new version. |
|
||||
| `--role` | `ROLE` | With `--as`: the role shown beside the name. |
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
title: "raea skills"
|
||||
summary: "Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP server and hook."
|
||||
summary: "Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP servers and hook."
|
||||
order: 128
|
||||
sources: ["engine/cli/src/skill.rs"]
|
||||
---
|
||||
|
||||
`raea skills install` copies the skill this raea ships into the folder an agent reads skills from, stamped with this
|
||||
version: `~/.claude/skills` for Claude Code, `~/.agents/skills` for Codex, Kimi Code's skills folder, and
|
||||
`~/.gemini/skills` for Gemini. It also adds the Blender MCP server to the agent, and raea's hooks to every agent
|
||||
`~/.gemini/skills` for Gemini. It also adds the Blender and forma MCP servers to the agent, and raea's hooks to every agent
|
||||
([`raea hook`](hook.md)): media opened in the Mac's viewer goes to `raea show`, and the quick check runs after each
|
||||
saved composition. A skill folder that's a link (a checkout of raea-skills) is left as it is.
|
||||
|
||||
@@ -26,7 +26,7 @@ raea skills install --agent claude --pin quieter --pin bolder # /quieter and
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
|
||||
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender and forma MCP servers unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
@@ -37,7 +37,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
|
||||
| --- | --- | --- |
|
||||
| `--agent` | `claude\|codex\|kimi\|gemini\|grokbot` | Which agent to install for. |
|
||||
| `--no-hooks` | – | Leave Claude Code's settings alone: don't add the quick-check hook. |
|
||||
| `--no-mcp` | – | Don't add the Blender MCP server to the agent. |
|
||||
| `--no-mcp` | – | Don't add the Blender and forma MCP servers to the agent. |
|
||||
| `--pin` | `MOVE` | Install a note's guide as a skill of its own, so `/MOVE` loads just it (`quieter`, `bolder`, `layout`, `adapt` and the rest). Repeatable. |
|
||||
| `--reference` | `cli\|feed\|files\|sdk` | Used by `raea skill`; see [`raea skill`](skill.md). |
|
||||
|
||||
|
||||
+96
-1
@@ -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
|
||||
@@ -164,7 +185,7 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
curves on the converted units scored Reinhard 14.5, Neutral 21.2, AgX 23.3, none 30.4, ACES 37.9; what is left is
|
||||
the shading itself (the bricks' side faces a touch darker), PA11's job
|
||||
|
||||
@needs:PA9
|
||||
@done @needs:PA9
|
||||
Scenario: PA11. Bevy's own shading in the light renderer
|
||||
Then Bevy's PBR shaders, composed for the pipelines a playable uses, are translated to GLSL ES 3.00 with naga at
|
||||
export time, and the light renderer draws with them instead of three.js's own materials
|
||||
@@ -183,11 +204,51 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
View (784 B), Lights (2,176 B), the cluster offsets, index lists and clustered lights (16 KB each, so the host
|
||||
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
|
||||
# Status 12-03: built. tools/bevy-glsl composes the three programs with Bevy's own ShaderCache (raea's vendored
|
||||
# bevy_pbr, bevy_render and bevy_core_pipeline 0.20.0, WebGL2's defs, 10 directional lights, Gaussian shadow
|
||||
# filtering, MSAA, distance fog, the projection's kind read from the view) and naga 30 translates them;
|
||||
# sdk/playable/bevy/build.sh writes them into host/bevy/programs.ts (105 KB, 21 KB gzipped) with each block's field offsets and which of Bevy's bindings each
|
||||
# block and sampler is, and apps/playable's test fails when Bevy's shaders or the translator change and it isn't
|
||||
# rebuilt. host/bevy.ts replaces three.js's renderer (three.ts and tonemap.ts are gone): it reads raea's three.js
|
||||
# scene graph (scene.ts) for the parts, geometry and transforms, and fills Bevy's blocks as Bevy's render world
|
||||
# does (bevy/fill.ts: prepare_view_uniforms, prepare_lights, MeshUniform::new, StandardMaterial's uniform; the
|
||||
# lights back in Bevy's units through units.ts): reverse Z, one 1x1x1 light cluster packed as Bevy packs it for
|
||||
# WebGL2, one directional shadow cascade (as Bevy on WebGL2 has) fitted to what the camera sees of the scene,
|
||||
# point and spot lights, distance fog (Bevy's GpuFog from the scene's Fog: linear from near to far, or
|
||||
# exponential for a density, as the native engine makes it), a forward pass into half float with 4x MSAA, then
|
||||
# TonyMcMapface through Bevy's table. A Plane3d is drawn as its one face (Bevy's PlaneMeshBuilder), not as the
|
||||
# flat Box three.js was given, whose top face three points down. Not drawn yet, each warned once in the
|
||||
# console: an environment's light, a camera's own <Fog> (Bevy's DistanceFog component), normal maps, transmission, vertex colours, point and
|
||||
# spot shadows, rect lights, a shadow catcher, a paint look
|
||||
# Measured on brick-rush against `raea render --frame` (mean difference over the drawn pixels / 255, both pages
|
||||
# against the same native frames; landscape frame 300 rendered with --despite type-over-part): portrait frame 90
|
||||
# three.js 6.1 -> Bevy 4.3 (PA10 recorded 5.4), landscape frame 300 9.8 -> 7.7, what is left in landscape mostly
|
||||
# the page's pulsing hint text. star-catch portrait frame 150: 17.0 -> 15.6 over the frame, 6.7 -> 5.0 over the
|
||||
# 3D above the hint text. A scene of a floor, six boxes, a ball, a sun with shadows, a point light and a spot
|
||||
# light (frame 10): perspective portrait 1.3, orthographic landscape 0.8, with linear fog 0.7, with exponential
|
||||
# fog 0.7. The page: brick-rush 1,889 -> 1,794 KB (three's renderer out, the programs in).
|
||||
# First frame in a fresh WebKit (served from localhost, to the GPU finishing it, 25 interleaved runs): three.js
|
||||
# median 131 ms, mean 129.8; Bevy median 131 ms, mean 131.8. The GL work is about 5 ms on both pages; the rest
|
||||
# is script and the page. Chrome's 4x CPU throttle isn't used (raea doesn't test in Chrome); with every WebKit
|
||||
# process clamped to the efficiency cores at background priority (taskpolicy -b), 142 and 145 ms over 11 runs.
|
||||
# brick-rush and star-catch play to their end cards and store taps in WebKit (tools/check.ts) in portrait and
|
||||
# landscape, with instant and 150 ms taps
|
||||
|
||||
@done
|
||||
Scenario: PA12. Bevy systems in a playable
|
||||
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 +270,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); a drawer (three.ts then,
|
||||
# Bevy's programs in bevy.ts since PA11) draws it, and the export's entry passes it to start() only when the lint
|
||||
# found a 3D kind, so a 2D game's bundle never imports three.js. Measured (preview page, before -> after, the after with PA8's ~95 KB of Inter):
|
||||
# tiles 1,345 -> 378 KB, gates 1,347 -> 380 KB, three 2D brand playables 2,752 -> 1,782, 3,409 -> 2,440 and
|
||||
# 2,693 -> 1,724 KB; brick-rush (3D, keeps three.js) 1,384 -> 1,478 KB. Each of the six played to its end card
|
||||
# and its store tap in WebKit (tools/check.ts), with instant taps (TAP_MS=0) and 150 ms taps.
|
||||
|
||||
Scenario: PA16. Playables in the review (raea cloud and the desktop)
|
||||
Given the review's own player (raea-platform board-simple review.js PLAYER_DRAWS) is the one view of a shown file
|
||||
@@ -241,4 +309,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.
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// The component library (sdk/raea/library/components, catalog.ts): every listed file is there, every relative import
|
||||
// in it lands on a file of the library, nothing imports another video framework, and the search finds by use.
|
||||
// in it lands on a file of the library, nothing imports another video framework, the search finds by use and by the
|
||||
// words people ask with, and each item carries what an agent picks by (tools/library-meta.sh writes it).
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, join, normalize } from "node:path";
|
||||
import { listed, type Item } from "../src/catalog";
|
||||
import { listed, searched, shown, terms, type Item } from "../src/catalog";
|
||||
|
||||
const lib = join(import.meta.dir, "../../../sdk/raea/library/components");
|
||||
const cat = JSON.parse(readFileSync(join(lib, "catalog.json"), "utf8")) as { sources: Record<string, { licence: string }>; items: Item[] };
|
||||
@@ -45,4 +46,37 @@ describe("the component library", () => {
|
||||
expect(listed(cat.items, ["count", "up"]).split("\n")[0]).toContain("count");
|
||||
expect(listed(cat.items, ["zzqx"])).toContain("no component in the library");
|
||||
});
|
||||
|
||||
test("each item says what it draws, when to use it and not, how it's asked for, and its props", () => {
|
||||
const thin = cat.items.filter((i) => !i.what || !i.use_when?.length || !i.avoid_when?.length || !i.asked_as?.length || !Array.isArray(i.props) || !i.aspect);
|
||||
expect(thin.map((i) => i.name)).toEqual([]);
|
||||
// its props are the ones its file declares
|
||||
const flash = cat.items.find((i) => i.name === "flash-count")!;
|
||||
expect(flash.props!.find((p) => p.name === "value")).toMatchObject({ type: "number", default: "3600" });
|
||||
});
|
||||
|
||||
test("its words name no other library or its tooling: the components are raea's", () => {
|
||||
const named = cat.items.flatMap((i) => [i.what ?? "", ...(i.use_when ?? []), ...(i.avoid_when ?? [])].filter((s) => /\b(remotion|remocn|snapcn|snap-cn|shadcn)\b/i.test(s)).map((s) => `${i.name}: ${s}`));
|
||||
expect(named).toEqual([]);
|
||||
});
|
||||
|
||||
test("search by the words people use: a product's UI, a composer, a chat input, a template, an AI prompt", () => {
|
||||
const top = (q: string, n = 3) => searched(cat.items, terms([q])).slice(0, n).map((i) => `${i.category}/${i.name}`);
|
||||
expect(top("claude code").every((n) => /terminal|agent/.test(n))).toBe(true);
|
||||
expect(top("composer")).toEqual(expect.arrayContaining(["ui/prompt-send"]));
|
||||
expect(top("chat input", 5)).toEqual(expect.arrayContaining(["ui/input", "ui/prompt-send"]));
|
||||
expect(top("AI prompt").every((n) => n.startsWith("ui/prompt-"))).toBe(true);
|
||||
expect(top("composer animations with claude")).toEqual(expect.arrayContaining(["ui/prompt-send"]));
|
||||
// the upstream name is a search alias: snapcn's terminal-simulator is ui/terminal-session here
|
||||
expect(top("terminal simulator", 2).sort()).toEqual(["ui/terminal-session", "ui/terminal-simulator"]);
|
||||
// "template" alone: the items that are one, and how to narrow it
|
||||
expect(listed(cat.items, ["template"])).toContain("say what it shows to narrow it");
|
||||
expect(listed(cat.items, ["cli"])).not.toContain("click-type");
|
||||
});
|
||||
|
||||
test("show: one item in full, with its props and when to use it", () => {
|
||||
const i = cat.items.find((i) => i.name === "prompt-send")!;
|
||||
const s = shown(i);
|
||||
for (const want of ["ui/prompt-send", "use it when:", "not when:", "props:", "text?: string", "raea make component add prompt-send", 'import { PromptSend } from "./components/ui/prompt-send"']) expect(s).toContain(want);
|
||||
});
|
||||
});
|
||||
+88
-24
@@ -6,7 +6,15 @@
|
||||
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
export type Item = { name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string };
|
||||
/** One of a component's props, read from its Props type: its type as written, its default, a line on what it does */
|
||||
export type Prop = { name: string; type: string; default?: string; says?: string; required?: boolean };
|
||||
/** An item; the fields after `from` are tools/library-meta.sh's: the upstream component it was matched to by content
|
||||
* (a search alias, never its name here), what it draws and how it moves, when to use it and when not, the phrases
|
||||
* people ask for it with, its props, and the length, frame rate, size, aspect and feel it was designed at */
|
||||
export type Item = {
|
||||
name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string;
|
||||
upstream?: string; what?: string; use_when?: string[]; avoid_when?: string[]; asked_as?: string[]; props?: Prop[]; length?: number; fps?: number; size?: string; aspect?: string; vibe?: string;
|
||||
};
|
||||
type Catalog = { sources: Record<string, { url: string; licence: string }>; items: Item[] };
|
||||
export type Got = { item: Item; licence: string; files: Record<string, string> };
|
||||
|
||||
@@ -17,6 +25,9 @@ function home(raea: string, env: Record<string, string | undefined>): string | u
|
||||
return [env.RAEA_HOME && join(env.RAEA_HOME, rel), join(bin, "../share/raea", rel), join(bin, "../..", rel)].find((p) => p && existsSync(join(p, "catalog.json")));
|
||||
}
|
||||
|
||||
/** An item by its name, category/name or category/type/name */
|
||||
export const found = (items: Item[], want: string) => items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
|
||||
|
||||
/** Host op "components": {op: "list"} is every item, {op: "get", name} one item with its files' text (by its path in
|
||||
* the library, which is its path under components/). No library beside this raea: an empty list, and no item. */
|
||||
export function componentsHost(raea: string, env: Record<string, string | undefined>, a: Record<string, unknown>): Item[] | Got | null {
|
||||
@@ -25,46 +36,99 @@ export function componentsHost(raea: string, env: Record<string, string | undefi
|
||||
const cat = JSON.parse(readFileSync(join(dir, "catalog.json"), "utf8")) as Catalog;
|
||||
if (a.op !== "get") return cat.items;
|
||||
const want = String(a.name).replace(/^\/+|\/+$/g, "");
|
||||
const item = cat.items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
|
||||
const item = found(cat.items, want);
|
||||
if (!item) return null;
|
||||
const files = Object.fromEntries([...item.files, ...item.needs].map((f) => [f, readFileSync(join(dir, f), "utf8")]));
|
||||
return { item, licence: cat.sources[item.from]?.licence ?? "", files };
|
||||
}
|
||||
|
||||
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${i.says.split(". ")[0].slice(0, 110)}`;
|
||||
// what a row says: the item's own line, or what it draws when that line is a few words
|
||||
const line = (i: Item) => (i.says.length >= 40 || !i.what ? i.says : i.what).split(". ")[0];
|
||||
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${line(i).slice(0, 110)}`;
|
||||
|
||||
// words that say nothing about which one ("a", "animation", "component") are skipped; "template", "effect" and
|
||||
// "preset" narrow to the items that are one when they're all a search says, and only rank otherwise
|
||||
const FILLER = new Set(["a", "an", "the", "with", "for", "of", "and", "in", "on", "to", "my", "our", "some", "please", "use", "using", "raea", "component", "components", "animation", "animations", "animated", "thing", "something", "from", "like", "one"]);
|
||||
const SOFT = new Set(["template", "templates", "effect", "effects", "preset", "presets"]);
|
||||
const esc = (w: string) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
// a word at a word's start ("count" finds "counter"); a short one only whole ("cli" isn't "click", "ai" isn't "aim")
|
||||
const finds = (w: string) => (w.length <= 3 ? new RegExp(`(^|[^a-z0-9])${esc(w)}(s|es)?($|[^a-z0-9])`, "i") : new RegExp(`(^|[^a-z0-9])${esc(w.replace(/s$/, ""))}`, "i"));
|
||||
|
||||
/** How well an item answers the words: 0 when a word that matters isn't anywhere in it. The name, the upstream name
|
||||
* and the phrases people ask for it with count most; what it does and when to use it count once */
|
||||
export function scored(i: Item, ws: string[]): number {
|
||||
const asked = (i.asked_as ?? []).join(" | ");
|
||||
const told = [i.says, i.what ?? "", ...(i.use_when ?? [])].join(" ");
|
||||
const named = (n: string | undefined, w: string) => (!n ? 0 : n.split("-").includes(w) ? 3 : w.length > 3 && n.includes(w) ? 2 : 0);
|
||||
const key = ws.filter((w) => !SOFT.has(w));
|
||||
let s = 0;
|
||||
// the words together, as written: a phrase people ask with, a name, or a sentence of what it does
|
||||
const phrase = key.join(" ");
|
||||
if (key.length > 1) s += (i.asked_as ?? []).some((a) => a.toLowerCase().includes(phrase)) ? 6 : [i.name, i.upstream ?? ""].includes(key.join("-")) ? 6 : told.toLowerCase().includes(phrase) ? 3 : 0;
|
||||
for (const w of ws) {
|
||||
const [c, t] = w.split("/");
|
||||
const re = finds(w);
|
||||
let got = 0;
|
||||
if (w.includes("/")) got = i.category === c && (!t || i.type === t) ? 4 : 0;
|
||||
else if (i.category === w || i.type === w) got = 4;
|
||||
// its name (or upstream's), the phrases it's asked for with, and its own words each add
|
||||
else got = Math.max(named(i.name, w), named(i.upstream, w)) + (re.test(asked) ? 3 : 0) + (re.test(told) || i.from === w ? 1 : 0);
|
||||
if (!got && !SOFT.has(w)) return 0;
|
||||
s += got;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** `raea make component list`'s lines for the library: with no words, each category and its types; with words, the
|
||||
* items they name. A word is a category ("text"), a category/type ("text/reveal"), or anything in a name or in what
|
||||
* an item does; every word must be found, and a name's own words count first. */
|
||||
* items they name. A word is a category ("text"), a category/type ("text/reveal"), a name or upstream name, or
|
||||
* anything in the phrases people ask with, what it does or when to use it; every word that matters must be found */
|
||||
export function listed(items: Item[], words: string[]): string {
|
||||
if (!items.length) return "";
|
||||
if (!words.length) {
|
||||
const ws = terms(words);
|
||||
if (!ws.length) {
|
||||
const cats = [...new Set(items.map((i) => i.category))].sort();
|
||||
const line = (c: string) => {
|
||||
const of = items.filter((i) => i.category === c);
|
||||
const types = [...new Set(of.map((i) => i.type))].sort().map((t) => `${t} ${of.filter((i) => i.type === t).length}`);
|
||||
return `${c.padEnd(14)} ${String(of.length).padStart(3)} ${types.join(", ")}`;
|
||||
};
|
||||
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "count up"; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
|
||||
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "chat input", list "count up"; show NAME tells one in full; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
|
||||
}
|
||||
const ws = words.join(" ").toLowerCase().split(/\s+/).filter(Boolean);
|
||||
const phrase = ws.join(" ");
|
||||
const score = (i: Item) => {
|
||||
// the words together, as written, in what it does: ahead of the same words scattered
|
||||
let s = ws.length > 1 && i.says.toLowerCase().includes(phrase) ? 3 : 0;
|
||||
for (const w of ws) {
|
||||
const [c, t] = w.split("/");
|
||||
if (w.includes("/") ? i.category === c && (!t || i.type === t) : i.category === w || i.type === w) s += 4;
|
||||
else if (i.name.split("-").includes(w)) s += 3;
|
||||
else if (i.name.includes(w)) s += 2;
|
||||
else if (i.says.toLowerCase().includes(w)) s += 1;
|
||||
else return 0;
|
||||
}
|
||||
return s;
|
||||
};
|
||||
const found = items.map((i) => [score(i), i] as const).filter(([s]) => s > 0).sort((a, b) => b[0] - a[0] || a[1].name.localeCompare(b[1].name));
|
||||
const found = searched(items, ws);
|
||||
if (!found.length) return `no component in the library for "${words.join(" ")}" (raea make component list shows the categories)\n`;
|
||||
return found.map(([, i]) => row(i)).join("\n") + "\n";
|
||||
// "template" or "effect" alone: the items that are one, a page of them, and how to narrow it
|
||||
if (ws.every((w) => SOFT.has(w))) {
|
||||
const top = found.slice(0, 30);
|
||||
return `${found.length} components are a ${ws[0].replace(/s$/, "")}; say what it shows to narrow it (list ${ws[0]} chat, list ${ws[0]} logo, list "${ws[0]} product demo"):\n${top.map(row).join("\n")}\n${found.length > top.length ? `... and ${found.length - top.length} more\n` : ""}`;
|
||||
}
|
||||
return found.map(row).join("\n") + "\n";
|
||||
}
|
||||
|
||||
/** A search's words that matter, in lower case */
|
||||
export const terms = (words: string[]) => words.join(" ").toLowerCase().split(/\s+/).filter((w) => w && !FILLER.has(w));
|
||||
|
||||
/** The items the words find, best first */
|
||||
export function searched(items: Item[], ws: string[]): Item[] {
|
||||
// equal scores: the one more of whose asked-for phrases the words are in is more about them
|
||||
const res = ws.filter((w) => !w.includes("/")).map(finds);
|
||||
const fit = (i: Item) => (i.asked_as ?? []).filter((a) => res.some((re) => re.test(a))).length;
|
||||
return items
|
||||
.map((i) => [scored(i, ws), fit(i), i] as const)
|
||||
.filter(([s]) => s > 0)
|
||||
.sort((a, b) => b[0] - a[0] || b[1] - a[1] || a[2].name.localeCompare(b[2].name))
|
||||
.map(([, , i]) => i);
|
||||
}
|
||||
|
||||
/** `raea make component show NAME`: everything an agent picks by, without opening the file */
|
||||
export function shown(i: Item, from = "./components"): string {
|
||||
const list = (head: string, xs?: string[]) => (xs?.length ? `${head}\n${xs.map((x) => ` - ${x}`).join("\n")}\n` : "");
|
||||
const made = [i.size && `${i.size} (${i.aspect})`, !i.size && i.aspect, i.length && `${i.length} frames at ${i.fps ?? 30} fps`, i.vibe && `feels ${i.vibe}`].filter(Boolean).join(", ");
|
||||
const props = (i.props ?? []).map((p) => ` ${p.name}${p.required ? "" : "?"}: ${p.type}${p.default !== undefined ? ` = ${p.default}` : ""}${p.says ? `\n ${p.says}` : ""}`);
|
||||
return `${i.category}/${i.name} (${i.type}; from ${i.from}${i.upstream ? `, ${i.upstream} there` : ""})
|
||||
${i.what ?? i.says}
|
||||
${list("use it when:", i.use_when)}${list("not when:", i.avoid_when)}${i.asked_as?.length ? `asked for as: ${i.asked_as.join("; ")}\n` : ""}${made ? `designed at: ${made}\n` : ""}${props.length ? `props:\n${props.join("\n")}\n` : "props: none (its words and colours are written in the file)\n"}add it: raea make component add ${i.name}
|
||||
import ${i.default ? i.component : `{ ${i.component} }`} from "${from}/${i.category}/${i.name}";
|
||||
`;
|
||||
}
|
||||
|
||||
/** What `add` says of a copied item: where it is, how to import it, the fonts it loads, whose it was */
|
||||
|
||||
@@ -136,7 +136,7 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
IN_HELP.set(was);
|
||||
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage
|
||||
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
|
||||
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
|
||||
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --choose LABEL FILE... --choose LABEL FILE... [--recommend N] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --choose LABEL FILE... once per option (2 to 6) for the person to pick one, --recommend N the one you would (nothing is picked for them), their pick back as {{\"kind\":\"answer\",\"choice\":LABEL}}; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
|
||||
// clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts
|
||||
let usage = format!("{usage}\n raea make clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder, and the first use of any step makes the Python environment the clothes run in there (by uv); no step needs Blender)");
|
||||
// body motion made by Kimodo, on MLX on a Mac and on PyTorch elsewhere (docs/character.feature CH15c):
|
||||
@@ -146,10 +146,10 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
let usage = format!("{usage}\n raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run] (a bug in raea itself, not in your own composition, sent to raea's server with raea's version and the OS, no account needed: words only, paths, emails and keys taken out before it goes; five a day from a machine, the same bug again counted on the first report; --dry-run prints what would go and sends nothing)");
|
||||
let usage = format!("{usage}\n {} ({})\n {} ({})", raea_sys_fixes::USAGE, raea_sys_fixes::ABOUT, raea_app_voice::USAGE, raea_app_voice::ABOUT); // a problem looked up before it's guessed at (systems/fixes); speech to speech (apps/voice)
|
||||
// a workspace's files and specs (docs/projects.feature), listed under render's usage like library
|
||||
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
|
||||
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::forma::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
|
||||
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
|
||||
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, format!("{GOAL_USAGE}\n {}", raea_app_make::USAGE), raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
|
||||
return Ok(usage::under_make(&format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, \"count up\")\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
|
||||
return Ok(usage::under_make(&format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, \"count up\", \"chat input\", template; show tells one in full: what it draws, when to use it and when not, its props)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
|
||||
}
|
||||
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
|
||||
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
|
||||
@@ -196,7 +196,8 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
if args[0] == "setup" && args.get(1).map(String::as_str) == Some("motion") {
|
||||
return tools::motion::setup(&args[2..]);
|
||||
}
|
||||
// `setup blender|godot`, `blender ...` and `godot ...`: Blender and Godot scripted (SK11, apps/engines)
|
||||
// `setup blender|godot|forma`, `blender ...`, `godot ...` and `forma ...`: Blender and Godot scripted, forma run (SK11,
|
||||
// apps/engines, apps/forma)
|
||||
if let Some(done) = raea_app_engines::cli(args) {
|
||||
return done;
|
||||
}
|
||||
|
||||
+13
-3
@@ -28,7 +28,7 @@ import { absolute, fromCwd, labelsIn, showVerb } from "./show";
|
||||
// `raea make clothes` (clothes.ts): garments for SOMA's body from words
|
||||
import { clothesVerb } from "./clothes";
|
||||
// the component library (catalog.ts): open components sorted by use, listed and copied by `raea make component`
|
||||
import { added, listed, type Got, type Item } from "./catalog";
|
||||
import { added, found, listed, searched, shown as inFull, terms, type Got, type Item } from "./catalog";
|
||||
// `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server
|
||||
import { bugVerb } from "./bug";
|
||||
|
||||
@@ -199,8 +199,18 @@ export function raeaHandler(host?: Host, engine?: Engine) {
|
||||
// the library beside this raea (none in a shell with no host: raea's own sets are all it lists)
|
||||
const shelf = (): Item[] => (host ? (host("components", { op: "list" }) as Item[]) : []);
|
||||
if (args[1] === undefined) return out(parts() + listed(shelf(), []), 0, was);
|
||||
if (args[1] === "list") return out(clean(args.slice(2)).length ? listed(shelf(), clean(args.slice(2))) : parts() + listed(shelf(), []), 0, was);
|
||||
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force]\n`);
|
||||
const ws = clean(args.slice(2));
|
||||
// --json: the items found (each with its props, when to use it and when not) for an agent to pick from
|
||||
if (args[1] === "list" && args.includes("--json")) return out(`${JSON.stringify(ws.length ? searched(shelf(), terms(ws)) : shelf(), null, 1)}\n`, 0, was);
|
||||
if (args[1] === "list") return out(ws.length ? listed(shelf(), ws) : parts() + listed(shelf(), []), 0, was);
|
||||
// show: one item in full, so it can be picked without opening its file
|
||||
if (args[1] === "show") {
|
||||
const item = ws[0] ? found(shelf(), ws[0]) : undefined;
|
||||
if (!item) return out("", 1, `${was}raea make component show: no "${ws[0] ?? ""}" in the library (raea make component list WORDS finds one)\n`);
|
||||
const at = (await c.fs.exists(p("compositions"))) ? "../components" : "./components";
|
||||
return out(args.includes("--json") ? `${JSON.stringify(item, null, 1)}\n` : inFull(item, at), 0, was);
|
||||
}
|
||||
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] [--json] | show NAME [--json] | add NAME ... [--shared] [--force]\n`);
|
||||
const names = clean(args.slice(2));
|
||||
if (!names.length) return out("", 2, `${was}raea make component add NAME ... (raea make component list shows them)\n`);
|
||||
const force = args.includes("--force");
|
||||
|
||||
+29
-4
@@ -32,6 +32,9 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
|
||||
raea show FILE... --fyi
|
||||
Only for the person to look at, nothing to approve: they say Got it (you hear {"kind":"seen"}), and anything they
|
||||
want to say back comes through the chat. Without it a show is a version for them to approve or send notes on.
|
||||
raea show --choose "Warm grade" A.png B.png --choose "Cool grade" C.png [--recommend 2] [--title T] [--ask TEXT]
|
||||
The person picks one: 2 to 6 options, each named, its files after it. --recommend N marks the one you'd pick (from
|
||||
1); nothing is picked for them. Their pick comes back as {"kind":"answer","choice":"Cool grade"}.
|
||||
raea show --group "Day: sun through the doors" A.png B.png --group "Night: practicals only" C.png [--title T]
|
||||
Lay the files out in groups the person sees side by side, each titled before the colon and said after it in a plain
|
||||
line (never shorthand); the files after a --group are its own. Keep it short: enough to know what each group is.
|
||||
@@ -58,7 +61,7 @@ raea show FILE... --replaces ITEM --done ID...
|
||||
closes when the person retires it, never with --done. raea notes post sends all of these from the notes.
|
||||
`;
|
||||
|
||||
const WITH_VALUE = new Set(["--group", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
|
||||
const WITH_VALUE = new Set(["--group", "--choose", "--recommend", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
|
||||
const FLAGS = new Set(["--open", "--fyi", "--playable"]);
|
||||
|
||||
/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
|
||||
@@ -118,6 +121,26 @@ export function parseShow(args: string[], cwd: string) {
|
||||
});
|
||||
const empty = groups.find((g) => !g.files.length);
|
||||
if (empty) throw new Error(`the group "${empty.title}" has no files: put its files after its --group\n${SHOW_USAGE}`);
|
||||
// the options to choose from (raea-platform home.feature HM5): each --choose "Label" holds the files after it
|
||||
const options: { label: string; files: string[]; recommended?: true }[] = [];
|
||||
args.forEach((a, i) => {
|
||||
if (a === "--choose" && args[i + 1] !== undefined) options.push({ label: args[i + 1].trim(), files: [] });
|
||||
else if (a === "--group" && options.length) throw new Error(`--choose and --group don't mix: each option is its own group\n${SHOW_USAGE}`);
|
||||
else if (options.length && isFile(a, i)) options.at(-1)!.files.push(abs(a));
|
||||
});
|
||||
if (options.length) {
|
||||
if (options.length < 2 || options.length > 6) throw new Error(`--choose gives 2 to 6 options, each with its files\n${SHOW_USAGE}`);
|
||||
const bare = options.find((o) => !o.label || !o.files.length);
|
||||
if (bare) throw new Error(`the option "${bare.label}" ${bare.label ? "has no files: put its files after its --choose" : "needs a name"}\n${SHOW_USAGE}`);
|
||||
if (files.length !== options.flatMap((o) => o.files).length) throw new Error(`with --choose, every file goes after the option it's in\n${SHOW_USAGE}`);
|
||||
if (args.includes("--question") || args.includes("--fyi")) throw new Error(`--choose is its own question: no --question or --fyi with it\n${SHOW_USAGE}`);
|
||||
}
|
||||
const recommend = one("--recommend");
|
||||
if (recommend !== undefined) {
|
||||
const n = Number(recommend);
|
||||
if (!options.length || !Number.isInteger(n) || n < 1 || n > options.length) throw new Error(`--recommend N names one of the --choose options, from 1${options.length ? ` to ${options.length}` : ""}\n${SHOW_USAGE}`);
|
||||
options[n - 1].recommended = true;
|
||||
}
|
||||
const despite = args.flatMap((a, i) => {
|
||||
if (a !== "--despite") return [];
|
||||
const [check, why] = [args[i + 1], args[i + 2]];
|
||||
@@ -157,7 +180,7 @@ export function parseShow(args: string[], cwd: string) {
|
||||
if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`);
|
||||
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
|
||||
if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`);
|
||||
return { groups, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
|
||||
return { groups, options, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
|
||||
}
|
||||
|
||||
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
|
||||
@@ -218,7 +241,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
|
||||
a.files = [(ask("playable", { file: a.files[0], cwd }) as { page: string }).page];
|
||||
a.title ??= a.files[0].replace(/^.*[\\/]/, "").replace(/-preview\.html$/, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
|
||||
}
|
||||
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
|
||||
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : a.options.length ? { intent: "choose", options: a.options } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
|
||||
| { opened: string[] }
|
||||
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean };
|
||||
if ("opened" in r) return `The raea app isn't on this Mac, so ${r.opened.length === 1 ? "it opened" : `${r.opened.length} files opened`} in the Mac's own viewer: nothing was posted and nothing comes back. Install raea (raea.io) to show work as items the person can answer.\n`;
|
||||
@@ -242,7 +265,9 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
|
||||
? `Shown in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}); the window is on it.`
|
||||
: `Posted in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}), with a notice; the window stayed where the person is.`,
|
||||
...settled,
|
||||
a.fyi
|
||||
a.options.length
|
||||
? `They pick one of ${a.options.length}: {"kind":"answer","choice":"<the option's name>"} comes to ${inbox}. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and carry on with their pick.`
|
||||
: a.fyi
|
||||
? `Only to look at: when they've seen it, {"kind":"seen"} comes to ${inbox}; nothing to wait for.`
|
||||
: `What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
|
||||
"",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! `raea --version` the agent reads `raea skill` instead.
|
||||
use super::*;
|
||||
|
||||
pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)";
|
||||
pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender and forma MCP servers unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)";
|
||||
|
||||
/// `raea doctor [--fix] [DIR]` (SK10): what doesn't match this raea, an agent's skill reinstalled by --fix.
|
||||
pub fn doctor(args: &[String]) -> R<String> {
|
||||
@@ -117,7 +117,7 @@ pub fn install(args: &[String]) -> R<String> {
|
||||
if agent == "grokbot" { return tools::agent_grokbot::stage(&to, out); }
|
||||
// every agent's hooks (A5d, SK10), in its own config: --no-hooks leaves it alone
|
||||
if !args.iter().any(|a| a == "--no-hooks") { out += &tools::agent_hooks::install(agent)?; }
|
||||
// the MCP servers raea offers (SK11): blender, for a running Blender; --no-mcp leaves the agent's servers alone
|
||||
// the MCP servers raea offers (SK11): blender, for a running Blender, and forma (FM6); --no-mcp leaves the agent's servers alone
|
||||
if !args.iter().any(|a| a == "--no-mcp") {
|
||||
out += &tools::agent_mcp::offer(agent)?;
|
||||
out += "\n";
|
||||
|
||||
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
|
||||
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
|
||||
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
|
||||
assert!(missing.is_empty(), "not in raea help: {missing:?}");
|
||||
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_playable::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
|
||||
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_playable::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_engines::forma::USAGE, raea_app_lightbake::USAGE] {
|
||||
assert!(help.contains(usage), "{usage}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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"
|
||||
@@ -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 []
|
||||
}
|
||||
|
||||
@@ -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] })
|
||||
})
|
||||
@@ -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")
|
||||
})
|
||||
@@ -12,8 +12,9 @@ docs/components.md in the raea repository.
|
||||
every thing the piece needs as a component: `Kitchen`, `Kettle`, `Steam`, `BrushedSteel`, `MorningLook`,
|
||||
`PriceCard`. One component is one concern: one object, one surface, one effect, one card.
|
||||
2. **Look before making.** `raea make component list` shows raea's own and the library's categories; `raea make
|
||||
component list WORDS` searches the library by what a piece is for (`text/reveal`, `numbers/counter`, `transitions`,
|
||||
`"count up"`): several hundred open-source text reveals, counters, charts, logo stings, HUDs and screen demos. A
|
||||
component list WORDS` searches the library by what a piece is for and how people ask for it (`text/reveal`,
|
||||
`numbers/counter`, `"count up"`, `"chat input"`, `template`): several hundred open-source text reveals, counters,
|
||||
charts, logo stings, HUDs and screen demos, and `raea make component show NAME` says when to use one and its props. A
|
||||
project's `components/` and the workspace's `shared/components/` hold what this person already has; `raea library
|
||||
search "WORDS"` finds their assets. Interface pieces (forms, tables, dashboards) come from shadcn, never rebuilt:
|
||||
see "shadcn" below. A library piece arrives with its source's sample words, colours and fonts: pass the brief's.
|
||||
@@ -28,6 +29,26 @@ docs/components.md in the raea repository.
|
||||
A piece written as one long file of meshes and numbers can't be reused, checked part by part, tuned by a person or
|
||||
fixed by a note that names a thing. Write components even for a one-off: the next note will name one of them.
|
||||
|
||||
## A template, an effect, a branded screen: the library first
|
||||
|
||||
When the person asks for a template, an effect, a preset, "something from remocn" (or snapcn), or a known kind of app
|
||||
screen moving (a chat box or composer, an AI prompt, a terminal, an agent at work, a phone or laptop showing an app),
|
||||
the library has it more often than not, already made and timed. Look there before drawing anything:
|
||||
|
||||
1. `raea make component list WORDS`, with the person's own words: `list composer`, `list "chat input"`, `list "AI
|
||||
prompt"`, `list "claude code"`, `list terminal`, `list template product`, `list "lower third"`. It searches each
|
||||
component's name, the name it had upstream, the phrases people ask for it with, and what it does; `list template`
|
||||
or `list effect` alone lists the ones that are and says how to narrow it.
|
||||
2. `raea make component show NAME` for the best hits: what it draws and how it moves, when to use it and when not
|
||||
(naming the better pick for the other case), the size, length and frame rate it was designed at, and every prop
|
||||
with its type, default and what it does. `list WORDS --json` gives the same for every hit. Pick from these;
|
||||
there's no need to open the files, and never fetch the upstream sources by hand.
|
||||
3. `raea make component add NAME`, then pass the brief's words, colours, fonts and logo through its props. A
|
||||
component with no props (some templates) has them written in its file: change them there.
|
||||
|
||||
Only when nothing fits is it written new, as a component (step 4). A brand's own product UI that isn't in the library
|
||||
(a particular app's chat window, say) is built from the nearest one: `add` it and restyle it.
|
||||
|
||||
## What a component is
|
||||
|
||||
A component is a React function component that draws one thing from its props and the frame:
|
||||
|
||||
@@ -52,30 +52,68 @@ 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.
|
||||
|
||||
The host draws that 3D with Bevy's own PBR shaders, so a frame of the playable matches `raea render --frame` closely.
|
||||
It has the sun's shadow, point and spot lights, fog from `<Fog>` and Bevy's tone mapping. Some things are left out,
|
||||
and the page's console names each one once: normal maps, transmission, vertex colours, point and spot shadows, rect
|
||||
lights, an environment's light, a camera's own `<Fog>` child, a shadow catcher and a paint look. Check how the 3D looks
|
||||
in the `preview` page, not only 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 with 3D: it reads the scene for the playable
|
||||
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; 3D adds about
|
||||
1 MB (three.js's scene graph and Bevy's shaders) 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 +124,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 |
|
||||
+12
-2
@@ -9,5 +9,15 @@ src/host/tony.bin is the tone-mapping table Tony McMapface, resampled by tools/t
|
||||
https://github.com/bevyengine/bevy
|
||||
Licensed under MIT OR Apache-2.0.
|
||||
|
||||
host/tonemap.ts samples it as Bevy's tonemapping shader does. The rest of raea/playable is raea's own, under the
|
||||
repository's licence.
|
||||
host/bevy.ts samples it as Bevy's tonemapping shader does.
|
||||
|
||||
src/host/bevy/programs.ts holds Bevy's PBR shaders (bevy_pbr's mesh, pbr and prepass programs, with bevy_render's
|
||||
and bevy_core_pipeline's shader imports), composed by Bevy's shader cache and translated to GLSL ES by naga
|
||||
(tools/bevy-glsl).
|
||||
|
||||
Bevy
|
||||
By the Bevy contributors
|
||||
https://github.com/bevyengine/bevy
|
||||
Licensed under MIT OR Apache-2.0.
|
||||
|
||||
The rest of raea/playable is raea's own, under the repository's licence.
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# Bevy's PBR programs for a playable (docs/playables.feature PA11): tools/bevy-glsl composes Bevy's mesh, pbr and
|
||||
# prepass shaders with WebGL2's defs and translates them to GLSL ES 3.00, into sdk/playable/src/host/bevy/programs.ts,
|
||||
# with the hash of what they were made from beside it (programs.from). apps/playable's test fails when Bevy's shaders
|
||||
# or the translator change and this isn't run.
|
||||
# usage: bash sdk/playable/bevy/build.sh [TARGET_DIR]
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "$0")/../../.." && pwd)
|
||||
target=${1:-$root/target/bevy-glsl}
|
||||
out=$root/sdk/playable/src/host/bevy
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -r "$work"' EXIT
|
||||
cargo run -q --release --manifest-path "$root/tools/bevy-glsl/Cargo.toml" --target-dir "$target" -- "$root" "$work"
|
||||
cp "$work/programs.ts" "$out/programs.ts"
|
||||
bash "$root/sdk/playable/bevy/from.sh" > "$out/programs.from"
|
||||
echo "programs.ts: $(wc -c < "$out/programs.ts" | tr -d ' ') bytes, $(gzip -9c "$out/programs.ts" | wc -c | tr -d ' ') gzipped"
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# what programs.ts is made from (build.sh): the translator, raea's vendored bevy_pbr shaders, and the Bevy and naga it
|
||||
# composes them with (Cargo.lock's lines)
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "$0")/../../.." && pwd)
|
||||
{
|
||||
cat "$root"/tools/bevy-glsl/Cargo.toml "$root"/tools/bevy-glsl/src/*.rs
|
||||
find "$root/vendor/bevy_pbr/src" \( -name '*.wesl' -o -name '*.wgsl' \) | LC_ALL=C sort | xargs cat
|
||||
grep -A1 -E '^name = "(bevy_render|bevy_core_pipeline|bevy_shader)"$' "$root/Cargo.lock"
|
||||
} | shasum -a 256 | cut -c1-64
|
||||
@@ -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,415 @@
|
||||
// A playable's 3D drawn by Bevy's own PBR programs (docs/playables.feature PA11): Bevy's mesh, pbr and prepass shaders
|
||||
// as Bevy composes them for a WebGL2 device, translated to GLSL ES by naga (tools/bevy-glsl, bevy/programs.ts), fed the
|
||||
// uniform blocks Bevy's render world fills (bevy/fill.ts). The page's parts are read by raea's three.js host into a
|
||||
// scene graph (scene.ts), which this reads back without three's renderer: each mesh's geometry and world transform,
|
||||
// each material's values, each light in Bevy's units. As Bevy on WebGL2 draws: one directional shadow cascade, a
|
||||
// forward pass into half float with 4x MSAA and reverse Z, the point and spot lights in one cluster, distance fog; then
|
||||
// Bevy's TonyMcMapface through its own table, as the native engine's frame pass does. 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 tony from "./tony.bin";
|
||||
import { Block } from "./bevy/block";
|
||||
import { Meshes, POINTS, Program, Textures, UNITS, programs } from "./bevy/gl";
|
||||
import { PBR_FRAG, PBR_VERT, SHADOW_VERT } from "./bevy/programs";
|
||||
import { ambientOf, cascade, fillFog, fillLights, fillMaterial, fillMesh, fillView, toLight, type Cascade, type Lights, type Surface } from "./bevy/fill";
|
||||
|
||||
const BATCH = 93; // PER_OBJECT_BUFFER_BATCH_SIZE: the meshes one uniform block holds
|
||||
const N = Math.round(Math.cbrt(tony.length / 3));
|
||||
|
||||
const EMPTY_FS = "#version 300 es\nprecision highp float;\nvoid main() {}\n";
|
||||
const TONE_VS = `#version 300 es
|
||||
out vec2 uv;
|
||||
void main() { vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); uv = p; gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); }`;
|
||||
// the HDR target is drawn upside down (naga's coordinate flip): its first row is the picture's top
|
||||
const TONE_FS = `#version 300 es
|
||||
precision highp float;
|
||||
precision highp sampler3D;
|
||||
uniform sampler2D scene;
|
||||
uniform sampler3D lut;
|
||||
uniform float exposure;
|
||||
in vec2 uv;
|
||||
out vec4 color;
|
||||
void main() {
|
||||
vec4 c = texture(scene, vec2(uv.x, 1.0 - uv.y));
|
||||
vec3 x = max(c.rgb / max(c.a, 1e-5), vec3(0.0)) * exposure;
|
||||
vec3 t = (x / (x + 1.0)) * (${N - 1}.0 / ${N}.0) + 0.5 / ${N}.0;
|
||||
color = vec4(texture(lut, clamp(t, 0.0, 1.0)).rgb * c.a, c.a);
|
||||
}`;
|
||||
|
||||
/** One draw: a mesh (or one of an instanced mesh's copies), its geometry's range and its material's slot */
|
||||
type Draw = {
|
||||
geometry: THREE.BufferGeometry;
|
||||
world: THREE.Matrix4;
|
||||
material: number;
|
||||
surface: Surface;
|
||||
start: number;
|
||||
count: number;
|
||||
casts: boolean;
|
||||
receives: boolean;
|
||||
depth: number;
|
||||
};
|
||||
|
||||
const ALIGN = (n: number, a: number) => Math.ceil(n / a) * a;
|
||||
|
||||
export function bevy3d(canvas: HTMLCanvasElement): Draw3d {
|
||||
const gl = canvas.getContext("webgl2", { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, powerPreference: "high-performance" });
|
||||
if (!gl) throw new Error("raea playable: this browser has no WebGL2");
|
||||
const hdr = !!gl.getExtension("EXT_color_buffer_float") || !!gl.getExtension("EXT_color_buffer_half_float");
|
||||
const warned = new Set<string>();
|
||||
const warn = (why: string) => {
|
||||
if (warned.has(why)) return;
|
||||
warned.add(why);
|
||||
console.warn(`raea playable: ${why}`);
|
||||
};
|
||||
if (!hdr) warn("this browser can't draw into half float: the 3D's highlights clip before the tone curve");
|
||||
|
||||
// linked while the page's first frame is built; bound at the first draw
|
||||
const [pbr, shadowProgram, tone] = programs(gl, [[PBR_VERT, PBR_FRAG], [SHADOW_VERT, EMPTY_FS], [TONE_VS, TONE_FS]]) as [Program, Program, Program];
|
||||
let exposureAt: WebGLUniformLocation | null = null;
|
||||
|
||||
const align = gl.getParameter(gl.UNIFORM_BUFFER_OFFSET_ALIGNMENT) as number;
|
||||
const blocks = {
|
||||
view: new Block("view"),
|
||||
lightView: new Block("view"),
|
||||
lights: new Block("lights"),
|
||||
clustered: new Block("clustered_lights"),
|
||||
offsets: new Block("cluster_offsets_and_counts"),
|
||||
lists: new Block("clusterable_object_index_lists"),
|
||||
globals: new Block("globals"),
|
||||
fog: new Block("fog"),
|
||||
metadata: new Block("metadata"),
|
||||
mesh: new Block("mesh", 1, ALIGN(new Block("mesh").size, align)),
|
||||
material: new Block("material", 1, ALIGN(new Block("material").size, align)),
|
||||
};
|
||||
const buffers = new Map<Block, { b: WebGLBuffer; bytes: number }>();
|
||||
const upload = (block: Block) => {
|
||||
let k = buffers.get(block);
|
||||
if (!k) buffers.set(block, (k = { b: gl.createBuffer()!, bytes: 0 }));
|
||||
gl.bindBuffer(gl.UNIFORM_BUFFER, k.b);
|
||||
if (k.bytes !== block.bytes.byteLength) {
|
||||
gl.bufferData(gl.UNIFORM_BUFFER, block.bytes, gl.DYNAMIC_DRAW);
|
||||
k.bytes = block.bytes.byteLength;
|
||||
} else gl.bufferSubData(gl.UNIFORM_BUFFER, 0, block.bytes);
|
||||
return k.b;
|
||||
};
|
||||
const bind = (name: string, block: Block, copy = 0) => {
|
||||
const k = buffers.get(block)!;
|
||||
gl.bindBufferRange(gl.UNIFORM_BUFFER, POINTS[name], k.b, copy * block.stride, block.size);
|
||||
};
|
||||
|
||||
const textures = new Textures(gl);
|
||||
const meshes = new Meshes(gl);
|
||||
|
||||
// Bevy's table for TonyMcMapface (tools/tony.ts), sRGB bytes already
|
||||
const lut = gl.createTexture()!;
|
||||
gl.bindTexture(gl.TEXTURE_3D, lut);
|
||||
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
|
||||
gl.texImage3D(gl.TEXTURE_3D, 0, gl.RGB8, N, N, N, 0, gl.RGB, gl.UNSIGNED_BYTE, tony);
|
||||
for (const [k, v] of [[gl.TEXTURE_MIN_FILTER, gl.LINEAR], [gl.TEXTURE_MAG_FILTER, gl.LINEAR], [gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE], [gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE], [gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE]]) gl.texParameteri(gl.TEXTURE_3D, k, v);
|
||||
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
|
||||
|
||||
// a depth texture sampled with comparison, as Bevy's shadow samplers are (reverse Z: greater-or-equal is lit)
|
||||
const depthTexture = (target: number, size: number) => {
|
||||
const t = gl.createTexture()!;
|
||||
gl.bindTexture(target, t);
|
||||
if (target === gl.TEXTURE_CUBE_MAP) for (let f = 0; f < 6; f++) gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, 0, gl.DEPTH_COMPONENT32F, size, size, 0, gl.DEPTH_COMPONENT, gl.FLOAT, null);
|
||||
else gl.texImage2D(target, 0, gl.DEPTH_COMPONENT32F, size, size, 0, gl.DEPTH_COMPONENT, gl.FLOAT, null);
|
||||
gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
|
||||
gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, gl.GEQUAL);
|
||||
gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
return t;
|
||||
};
|
||||
// point lights' shadows aren't drawn: their cube is one texel, never sampled
|
||||
const pointShadows = depthTexture(gl.TEXTURE_CUBE_MAP, 1);
|
||||
let shadowSize = 0;
|
||||
let shadowMap: WebGLTexture | null = null;
|
||||
const shadowFbo = gl.createFramebuffer()!;
|
||||
const shadowTarget = (size: number) => {
|
||||
if (size === shadowSize && shadowMap) return;
|
||||
if (shadowMap) gl.deleteTexture(shadowMap);
|
||||
shadowSize = size;
|
||||
shadowMap = depthTexture(gl.TEXTURE_2D, size);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFbo);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, shadowMap, 0);
|
||||
gl.drawBuffers([gl.NONE]);
|
||||
gl.readBuffer(gl.NONE);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||
};
|
||||
shadowTarget(2048);
|
||||
|
||||
// the forward pass's targets: multisampled colour and depth, resolved into a texture the tone pass reads
|
||||
const samples = Math.min(4, gl.getParameter(gl.MAX_SAMPLES) as number);
|
||||
const msaaFbo = gl.createFramebuffer()!;
|
||||
const resolveFbo = gl.createFramebuffer()!;
|
||||
let color: WebGLRenderbuffer | null = null;
|
||||
let depth: WebGLRenderbuffer | null = null;
|
||||
let resolved: WebGLTexture | null = null;
|
||||
let width = 1;
|
||||
let height = 1;
|
||||
const targets = () => {
|
||||
if (color) gl.deleteRenderbuffer(color);
|
||||
if (depth) gl.deleteRenderbuffer(depth);
|
||||
if (resolved) gl.deleteTexture(resolved);
|
||||
const format = hdr ? gl.RGBA16F : gl.RGBA8;
|
||||
color = gl.createRenderbuffer()!;
|
||||
gl.bindRenderbuffer(gl.RENDERBUFFER, color);
|
||||
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, format, width, height);
|
||||
depth = gl.createRenderbuffer()!;
|
||||
gl.bindRenderbuffer(gl.RENDERBUFFER, depth);
|
||||
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT32F, width, height);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, msaaFbo);
|
||||
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, color);
|
||||
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depth);
|
||||
resolved = gl.createTexture()!;
|
||||
gl.bindTexture(gl.TEXTURE_2D, resolved);
|
||||
gl.texStorage2D(gl.TEXTURE_2D, 1, format, width, height);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, resolveFbo);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, resolved, 0);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||
};
|
||||
|
||||
const scene = new Scene3d();
|
||||
let frame = 0;
|
||||
let seconds = 0;
|
||||
|
||||
/** The scene's meshes and lights, as Bevy's extraction would find them */
|
||||
const gather = () => {
|
||||
const draws: Draw[] = [];
|
||||
const lights: Lights = { ambient: null, directional: [], points: [], spots: [] };
|
||||
const materials = new Map<string, { slot: number; surface: Surface }>();
|
||||
const ids = new WeakMap<THREE.Material, number>();
|
||||
let nextId = 0;
|
||||
const order: { m: THREE.Material; tint: THREE.Color | null; surface: Surface }[] = [];
|
||||
const slotOf = (m: THREE.Material, tint: THREE.Color | null) => {
|
||||
let id = ids.get(m);
|
||||
if (id === undefined) ids.set(m, (id = nextId++));
|
||||
const key = tint ? `${id}:${tint.getHexString()}` : `${id}`;
|
||||
let k = materials.get(key);
|
||||
if (!k) {
|
||||
k = { slot: order.length, surface: { blend: false, doubleSided: false } };
|
||||
materials.set(key, k);
|
||||
order.push({ m, tint, surface: k.surface });
|
||||
}
|
||||
return k;
|
||||
};
|
||||
const camInv = scene.camera.matrixWorldInverse;
|
||||
const p = new THREE.Vector3();
|
||||
const add = (mesh: THREE.Mesh, world: THREE.Matrix4, tint: THREE.Color | null) => {
|
||||
const g = mesh.geometry;
|
||||
const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
|
||||
const groups = Array.isArray(mesh.material) && g.groups.length ? g.groups : [{ start: 0, count: Infinity, materialIndex: 0 }];
|
||||
for (const gr of groups) {
|
||||
const m = mats[gr.materialIndex ?? 0];
|
||||
if (!m || !m.visible) continue;
|
||||
if (m instanceof THREE.ShadowMaterial) {
|
||||
warn("a shadow catcher isn't drawn in a playable yet");
|
||||
continue;
|
||||
}
|
||||
const k = slotOf(m, tint);
|
||||
p.setFromMatrixPosition(world).applyMatrix4(camInv);
|
||||
draws.push({ geometry: g, world, material: k.slot, surface: k.surface, start: gr.start, count: gr.count, casts: mesh.castShadow, receives: mesh.receiveShadow, depth: p.z });
|
||||
}
|
||||
};
|
||||
scene.scene.updateMatrixWorld();
|
||||
scene.scene.traverseVisible((o) => {
|
||||
if (o instanceof THREE.InstancedMesh) {
|
||||
const one = new THREE.Matrix4();
|
||||
for (let i = 0; i < o.count; i++) {
|
||||
o.getMatrixAt(i, one);
|
||||
const tint = o.instanceColor ? new THREE.Color().fromArray(o.instanceColor.array, i * 3) : null;
|
||||
add(o, o.matrixWorld.clone().multiply(one), tint);
|
||||
}
|
||||
} else if (o instanceof THREE.Mesh) add(o, o.matrixWorld, null);
|
||||
else if (o instanceof THREE.AmbientLight || o instanceof THREE.HemisphereLight) lights.ambient = ambientOf(o, lights.ambient);
|
||||
else if (o instanceof THREE.DirectionalLight) lights.directional.push(o);
|
||||
else if (o instanceof THREE.SpotLight) {
|
||||
lights.spots.push(o);
|
||||
if (o.castShadow) warn("a spot light's shadow isn't drawn in a playable yet");
|
||||
} else if (o instanceof THREE.PointLight) {
|
||||
lights.points.push(o);
|
||||
if (o.castShadow) warn("a point light's shadow isn't drawn in a playable yet");
|
||||
} else if (o instanceof THREE.RectAreaLight) warn("a rect light isn't drawn in a playable yet");
|
||||
else if (o instanceof THREE.Points || o instanceof THREE.Line || o instanceof THREE.Sprite) warn(`a ${o.type} isn't drawn in a playable yet`);
|
||||
});
|
||||
if (scene.scene.userData.raeaEnvironment) warn("an environment's light isn't drawn in a playable yet");
|
||||
if (scene.effects.some((e) => e.kind === "Look")) warn("a paint look isn't drawn in a playable yet");
|
||||
blocks.material.resize(order.length);
|
||||
order.forEach(({ m, tint, surface }, slot) => Object.assign(surface, fillMaterial(blocks.material, slot, m, tint, warn)));
|
||||
return { draws, lights, materials: order.length };
|
||||
};
|
||||
|
||||
const drawAll = (list: Draw[], program: Program, main: boolean) => {
|
||||
let batch = -1;
|
||||
let cull: boolean | null = null;
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const d = list[i];
|
||||
const m = meshes.get(d.geometry);
|
||||
if (!m) continue;
|
||||
const at = (d as Draw & { at: number }).at;
|
||||
const b = Math.floor(at / BATCH);
|
||||
if (b !== batch) {
|
||||
bind("mesh", blocks.mesh, b);
|
||||
batch = b;
|
||||
}
|
||||
gl.uniform1ui(program.first, at % BATCH);
|
||||
const two = d.surface.doubleSided;
|
||||
if (cull !== !two) {
|
||||
if (two) gl.disable(gl.CULL_FACE);
|
||||
else gl.enable(gl.CULL_FACE);
|
||||
cull = !two;
|
||||
}
|
||||
if (main) {
|
||||
bind("material", blocks.material, d.material);
|
||||
const s = d.surface;
|
||||
const tex = (unit: number, t: THREE.Texture | null | undefined) => {
|
||||
gl.activeTexture(gl.TEXTURE0 + unit);
|
||||
gl.bindTexture(gl.TEXTURE_2D, textures.get(t) ?? textures.white);
|
||||
};
|
||||
tex(UNITS.base_color_texture, s.map);
|
||||
tex(UNITS.emissive_texture, s.emissiveMap);
|
||||
tex(UNITS.metallic_roughness_texture, s.mrMap);
|
||||
tex(UNITS.occlusion_texture, s.aoMap);
|
||||
}
|
||||
gl.bindVertexArray(m.vao);
|
||||
const start = d.start;
|
||||
const count = Math.min(d.count, m.count - start);
|
||||
if (m.index) gl.drawElements(gl.TRIANGLES, count, m.index, start * (m.index === gl.UNSIGNED_INT ? 4 : 2));
|
||||
else gl.drawArrays(gl.TRIANGLES, start, count);
|
||||
}
|
||||
gl.bindVertexArray(null);
|
||||
};
|
||||
|
||||
return {
|
||||
fit(w, h, scale) {
|
||||
// the canvas is drawn at the screen's pixels, not the composition's
|
||||
const ratio = Math.min(2, devicePixelRatio || 1) * scale;
|
||||
const cw = Math.max(1, Math.floor(w * ratio));
|
||||
const ch = Math.max(1, Math.floor(h * ratio));
|
||||
if (cw !== width || ch !== height || !color) {
|
||||
width = canvas.width = cw;
|
||||
height = canvas.height = ch;
|
||||
targets();
|
||||
}
|
||||
scene.fit(w, h);
|
||||
},
|
||||
sync(page, s) {
|
||||
seconds = s;
|
||||
scene.sync(page, s);
|
||||
return scene.any;
|
||||
},
|
||||
draw() {
|
||||
frame++;
|
||||
const { draws, lights } = gather();
|
||||
draws.forEach((d, i) => ((d as Draw & { at: number }).at = i));
|
||||
blocks.mesh.resize(Math.ceil(draws.length / BATCH));
|
||||
draws.forEach((d, i) => fillMesh(blocks.mesh, Math.floor(i / BATCH), i % BATCH, d.world, d.receives));
|
||||
|
||||
// the shadow: the first directional light that casts one, its cascade over what casts and catches
|
||||
const sun = scene.settings.shadows ? lights.directional.find((l) => l.castShadow) : undefined;
|
||||
let shadow: { light: THREE.DirectionalLight; cascade: Cascade } | null = null;
|
||||
if (sun) {
|
||||
shadowTarget(Math.min(scene.settings.shadowMap || 2048, gl.getParameter(gl.MAX_TEXTURE_SIZE) as number));
|
||||
const bounds = new THREE.Box3();
|
||||
const box = new THREE.Box3();
|
||||
for (const d of draws) {
|
||||
if (!d.geometry.boundingBox) d.geometry.computeBoundingBox();
|
||||
bounds.union(box.copy(d.geometry.boundingBox!).applyMatrix4(d.world));
|
||||
}
|
||||
const c = cascade(toLight(sun), bounds, scene.camera, shadowSize);
|
||||
if (c) shadow = { light: sun, cascade: c };
|
||||
}
|
||||
|
||||
for (const b of [blocks.view, blocks.lightView, blocks.lights, blocks.clustered, blocks.offsets, blocks.lists, blocks.globals, blocks.fog]) b.resize(1);
|
||||
fillFog(blocks.fog, scene.scene.fog as THREE.Fog | THREE.FogExp2 | null);
|
||||
fillView(blocks.view, scene.camera, width, height, frame);
|
||||
fillLights(blocks.lights, blocks.clustered, blocks.offsets, blocks.lists, lights, shadow, width, height);
|
||||
blocks.globals.f("time", seconds);
|
||||
blocks.globals.u("frame_count", frame);
|
||||
for (const b of Object.values(blocks)) upload(b);
|
||||
for (const [name, b] of [["lights", blocks.lights], ["clustered_lights", blocks.clustered], ["cluster_offsets_and_counts", blocks.offsets], ["clusterable_object_index_lists", blocks.lists], ["globals", blocks.globals], ["metadata", blocks.metadata], ["fog", blocks.fog]] as [string, Block][]) bind(name, b);
|
||||
|
||||
// Bevy's clip space flipped in y by naga: front faces wind clockwise in GL's
|
||||
gl.frontFace(gl.CW);
|
||||
gl.cullFace(gl.BACK);
|
||||
gl.enable(gl.DEPTH_TEST);
|
||||
gl.depthFunc(gl.GEQUAL);
|
||||
gl.clearDepth(0);
|
||||
|
||||
// the shadow pass, from the light, as Bevy's prepass draws it
|
||||
if (shadow) {
|
||||
fillView(blocks.lightView, scene.camera, shadowSize, shadowSize, frame, undefined);
|
||||
blocks.lightView.f("clip_from_world", shadow.cascade.clipFromWorld.elements);
|
||||
upload(blocks.lightView);
|
||||
bind("view", blocks.lightView);
|
||||
// not sampled while it's drawn into
|
||||
gl.activeTexture(gl.TEXTURE0 + UNITS.directional_shadow_textures);
|
||||
gl.bindTexture(gl.TEXTURE_2D, null);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFbo);
|
||||
gl.viewport(0, 0, shadowSize, shadowSize);
|
||||
gl.depthMask(true);
|
||||
gl.disable(gl.BLEND);
|
||||
gl.clear(gl.DEPTH_BUFFER_BIT);
|
||||
shadowProgram.use();
|
||||
drawAll(draws.filter((d) => d.casts && !d.surface.blend), shadowProgram, false);
|
||||
}
|
||||
|
||||
// the forward pass: opaque, then blended back to front without writing depth
|
||||
bind("view", blocks.view);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, msaaFbo);
|
||||
gl.viewport(0, 0, width, height);
|
||||
gl.clearColor(0, 0, 0, 0);
|
||||
gl.depthMask(true);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
||||
pbr.use();
|
||||
gl.activeTexture(gl.TEXTURE0 + UNITS.directional_shadow_textures);
|
||||
gl.bindTexture(gl.TEXTURE_2D, shadowMap);
|
||||
gl.activeTexture(gl.TEXTURE0 + UNITS.point_shadow_textures);
|
||||
gl.bindTexture(gl.TEXTURE_CUBE_MAP, pointShadows);
|
||||
gl.activeTexture(gl.TEXTURE0 + UNITS.raea_gi);
|
||||
gl.bindTexture(gl.TEXTURE_2D, textures.none);
|
||||
gl.disable(gl.BLEND);
|
||||
drawAll(draws.filter((d) => !d.surface.blend), pbr, true);
|
||||
const blended = draws.filter((d) => d.surface.blend).sort((a, b) => a.depth - b.depth);
|
||||
if (blended.length) {
|
||||
gl.enable(gl.BLEND);
|
||||
// BlendState::ALPHA_BLENDING
|
||||
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
|
||||
gl.depthMask(false);
|
||||
drawAll(blended, pbr, true);
|
||||
gl.depthMask(true);
|
||||
gl.disable(gl.BLEND);
|
||||
}
|
||||
|
||||
// resolved, then tone-mapped onto the canvas
|
||||
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, msaaFbo);
|
||||
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, resolveFbo);
|
||||
gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||
gl.viewport(0, 0, width, height);
|
||||
gl.disable(gl.DEPTH_TEST);
|
||||
gl.disable(gl.CULL_FACE);
|
||||
if (!exposureAt) {
|
||||
tone.use();
|
||||
gl.uniform1i(gl.getUniformLocation(tone.p, "scene"), 0);
|
||||
gl.uniform1i(gl.getUniformLocation(tone.p, "lut"), 1);
|
||||
exposureAt = gl.getUniformLocation(tone.p, "exposure");
|
||||
}
|
||||
tone.use();
|
||||
gl.uniform1f(exposureAt, scene.settings.exposure * scene.settings.grade);
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, resolved);
|
||||
gl.activeTexture(gl.TEXTURE1);
|
||||
gl.bindTexture(gl.TEXTURE_3D, lut);
|
||||
gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
textures.done();
|
||||
meshes.done();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// One of Bevy's uniform blocks as bytes (docs/playables.feature PA11): its fields written by their names in Bevy's
|
||||
// shader structs, at the offsets naga laid them out (programs.ts LAYOUT), so the host fills a block as Bevy's render
|
||||
// world fills its buffer. A path names nested fields with dots; each array on the way takes the next index.
|
||||
import { LAYOUT } from "./programs";
|
||||
|
||||
type Plan = { at: number; strides: number[] };
|
||||
|
||||
export class Block {
|
||||
readonly size: number;
|
||||
bytes: ArrayBuffer;
|
||||
f32: Float32Array;
|
||||
u32: Uint32Array;
|
||||
i32: Int32Array;
|
||||
private readonly layout: Record<string, number>;
|
||||
private readonly plans = new Map<string, Plan>();
|
||||
|
||||
/** `name` is the binding's name in Bevy's files (view, lights, mesh, material ...); `count` copies of it, each
|
||||
* `stride` bytes apart (a buffer of many materials, or of batches of meshes) */
|
||||
constructor(readonly name: string, count = 1, readonly stride = 0) {
|
||||
const layout = LAYOUT[name];
|
||||
if (!layout) throw new Error(`raea playable: Bevy's programs have no ${name} block`);
|
||||
this.layout = layout;
|
||||
this.size = layout.$size;
|
||||
this.bytes = new ArrayBuffer(0);
|
||||
this.f32 = new Float32Array(0);
|
||||
this.u32 = new Uint32Array(0);
|
||||
this.i32 = new Int32Array(0);
|
||||
this.resize(count);
|
||||
}
|
||||
|
||||
/** Room for `count` copies, cleared */
|
||||
resize(count: number) {
|
||||
const bytes = Math.max(1, count) * Math.max(this.stride, this.size);
|
||||
if (bytes !== this.bytes.byteLength) {
|
||||
this.bytes = new ArrayBuffer(bytes);
|
||||
this.f32 = new Float32Array(this.bytes);
|
||||
this.u32 = new Uint32Array(this.bytes);
|
||||
this.i32 = new Int32Array(this.bytes);
|
||||
} else new Uint8Array(this.bytes).fill(0);
|
||||
}
|
||||
|
||||
private plan(path: string): Plan {
|
||||
let p = this.plans.get(path);
|
||||
if (p) return p;
|
||||
p = { at: 0, strides: [] };
|
||||
const top = this.layout["[]"];
|
||||
if (top !== undefined) p.strides.push(top);
|
||||
let pre = "";
|
||||
for (const seg of path.split(".")) {
|
||||
pre = pre ? `${pre}.${seg}` : seg;
|
||||
const at = this.layout[pre];
|
||||
if (at === undefined) throw new Error(`raea playable: Bevy's ${this.name} has no ${pre}`);
|
||||
p.at += at;
|
||||
const s = this.layout[`${pre}[]`];
|
||||
if (s !== undefined) p.strides.push(s);
|
||||
}
|
||||
this.plans.set(path, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** A field's byte offset in copy `copy`, each array on its path at the index given in turn */
|
||||
at(path: string, copy = 0, ...index: number[]): number {
|
||||
const p = this.plan(path);
|
||||
let at = copy * this.stride + p.at;
|
||||
for (let k = 0; k < p.strides.length; k++) at += (index[k] ?? 0) * p.strides[k];
|
||||
return at;
|
||||
}
|
||||
|
||||
f(path: string, v: number | ArrayLike<number>, copy = 0, ...index: number[]) {
|
||||
const at = this.at(path, copy, ...index) >> 2;
|
||||
if (typeof v === "number") this.f32[at] = v;
|
||||
else this.f32.set(v, at);
|
||||
}
|
||||
|
||||
u(path: string, v: number, copy = 0, ...index: number[]) {
|
||||
this.u32[this.at(path, copy, ...index) >> 2] = v >>> 0;
|
||||
}
|
||||
|
||||
i(path: string, v: number, copy = 0, ...index: number[]) {
|
||||
this.i32[this.at(path, copy, ...index) >> 2] = v | 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
// Bevy's uniform blocks filled from the scene (docs/playables.feature PA11), as Bevy's render world fills them:
|
||||
// bevy_render's prepare_view_uniforms (the view), bevy_pbr's prepare_lights (lights, clustered lights, the light
|
||||
// cluster's lists), MeshUniform::new (each mesh) and StandardMaterial's as_bind_group_shader_type (each material).
|
||||
// The scene is raea's three.js scene graph (scene.ts); its lights are back in Bevy's units through units.ts, and its
|
||||
// colours are linear already (three's working space is linear sRGB, Bevy's LinearRgba).
|
||||
import * as THREE from "three";
|
||||
import { AMBIENT, LUMENS, LUX, toRaea } from "@raea/r3f/units";
|
||||
import type { Block } from "./block";
|
||||
|
||||
/** Bevy's default camera exposure, EV100 9.7 (Exposure::default) */
|
||||
export const EXPOSURE = 1 / (1.2 * 2 ** 9.7);
|
||||
|
||||
const MAX_DIRECTIONAL = 10; // the programs' MAX_DIRECTIONAL_LIGHTS
|
||||
const MAX_CLUSTERED = 204; // the clustered lights' array in a uniform block
|
||||
const SQRT_2 = Math.SQRT2;
|
||||
|
||||
/** Bevy's matrices for a three.js camera: clip_from_view as Bevy makes it (reverse Z; a perspective one with no far
|
||||
* plane), from three's projection's own terms so its zoom and view offset carry */
|
||||
export function clipFromView(cam: THREE.Camera): THREE.Matrix4 {
|
||||
const p = cam.projectionMatrix.elements;
|
||||
const m = new THREE.Matrix4();
|
||||
if (cam instanceof THREE.OrthographicCamera) {
|
||||
const r = 1 / (cam.far - cam.near);
|
||||
// glam's orthographic_rh(left, right, bottom, top, far, near): Bevy swaps near and far for reverse Z
|
||||
m.set(p[0], 0, 0, p[12], 0, p[5], 0, p[13], 0, 0, r, cam.far * r, 0, 0, 0, 1);
|
||||
} else {
|
||||
const near = (cam as THREE.PerspectiveCamera).near ?? 0.1;
|
||||
// perspective_infinite_reverse_rh, with three's x and y terms
|
||||
m.set(p[0], 0, p[8], 0, 0, p[5], p[9], 0, 0, 0, 0, near, 0, 0, -1, 0);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
/** The View block for a camera on a viewport of `width` x `height` pixels */
|
||||
export function fillView(b: Block, cam: THREE.Camera, width: number, height: number, frame: number, clip?: THREE.Matrix4) {
|
||||
const clipFromViewM = clip ?? clipFromView(cam);
|
||||
const worldFromView = cam.matrixWorld.clone();
|
||||
const viewFromWorld = worldFromView.clone().invert();
|
||||
const viewFromClip = clipFromViewM.clone().invert();
|
||||
const clipFromWorld = clipFromViewM.clone().multiply(viewFromWorld);
|
||||
b.f("clip_from_world", clipFromWorld.elements);
|
||||
b.f("unjittered_clip_from_world", clipFromWorld.elements);
|
||||
b.f("world_from_clip", worldFromView.clone().multiply(viewFromClip).elements);
|
||||
b.f("world_from_view", worldFromView.elements);
|
||||
b.f("view_from_world", viewFromWorld.elements);
|
||||
b.f("clip_from_view", clipFromViewM.elements);
|
||||
b.f("view_from_clip", viewFromClip.elements);
|
||||
const at = new THREE.Vector3().setFromMatrixPosition(worldFromView);
|
||||
b.f("world_position", [at.x, at.y, at.z]);
|
||||
b.f("lod_view_world_position", [at.x, at.y, at.z]);
|
||||
b.f("exposure", EXPOSURE);
|
||||
b.f("viewport", [0, 0, width, height]);
|
||||
b.f("main_pass_viewport", [0, 0, width, height]);
|
||||
// ColorGrading::default (it acts only where the tone curve is in this pass; the tone curve is the frame pass's)
|
||||
b.f("color_grading.balance", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]);
|
||||
for (const k of ["saturation", "contrast", "gamma", "gain"]) b.f(`color_grading.${k}`, [1, 1, 1]);
|
||||
b.f("color_grading.midtone_range", [0.2, 0.7]);
|
||||
b.f("color_grading.post_saturation", 1);
|
||||
b.u("frame_count", frame);
|
||||
}
|
||||
|
||||
/** A three.js light's colour in Bevy's LinearRgba */
|
||||
const rgb = (c: THREE.Color, k: number) => [c.r * k, c.g * k, c.b * k, 1];
|
||||
|
||||
/** The scene's lights, found by walking it */
|
||||
export type Lights = {
|
||||
ambient: THREE.Color | null;
|
||||
directional: THREE.DirectionalLight[];
|
||||
points: THREE.PointLight[];
|
||||
spots: THREE.SpotLight[];
|
||||
};
|
||||
|
||||
/** The one shadow cascade (WebGL2 has room for one, as Bevy on WebGL2 does) */
|
||||
export type Cascade = { clipFromWorld: THREE.Matrix4; texel: number };
|
||||
|
||||
/** The light's world rotation as Bevy's looking_to gives it: -Z along the light, +Z back toward it */
|
||||
function worldFromLight(toLight: THREE.Vector3): THREE.Matrix4 {
|
||||
const z = toLight.clone().normalize();
|
||||
const up = Math.abs(z.y) > 0.9999 ? new THREE.Vector3(0, 0, 1) : new THREE.Vector3(0, 1, 0);
|
||||
const x = new THREE.Vector3().crossVectors(up, z).normalize();
|
||||
const y = new THREE.Vector3().crossVectors(z, x);
|
||||
return new THREE.Matrix4().makeBasis(x, y, z);
|
||||
}
|
||||
|
||||
/** Where a directional light shines from: its position less its target's */
|
||||
export function toLight(l: THREE.DirectionalLight | THREE.SpotLight): THREE.Vector3 {
|
||||
const from = new THREE.Vector3().setFromMatrixPosition(l.matrixWorld);
|
||||
const to = new THREE.Vector3().setFromMatrixPosition(l.target.matrixWorld);
|
||||
const d = from.sub(to);
|
||||
return d.lengthSq() > 0 ? d.normalize() : new THREE.Vector3(0, 1, 0);
|
||||
}
|
||||
|
||||
/** One cascade as bevy_light's calculate_cascade makes it, fitted to what casts and catches shadow: the scene's
|
||||
* bounds, narrowed (across the light) to what the camera sees of them, as Bevy's cascades cover the view */
|
||||
export function cascade(toward: THREE.Vector3, bounds: THREE.Box3, cam: THREE.Camera, size: number): Cascade | null {
|
||||
if (bounds.isEmpty()) return null;
|
||||
const wfl = worldFromLight(toward);
|
||||
const lfw = wfl.clone().transpose();
|
||||
const box = new THREE.Box3();
|
||||
const p = new THREE.Vector3();
|
||||
for (let i = 0; i < 8; i++) {
|
||||
p.set(i & 1 ? bounds.max.x : bounds.min.x, i & 2 ? bounds.max.y : bounds.min.y, i & 4 ? bounds.max.z : bounds.min.z);
|
||||
box.expandByPoint(p.applyMatrix4(lfw));
|
||||
}
|
||||
// what the camera sees, as far as the scene reaches from it: its frustum's corners in the light's space
|
||||
const eye = new THREE.Vector3().setFromMatrixPosition(cam.matrixWorld);
|
||||
const reach = Math.max(1, Math.sqrt(Math.max(bounds.distanceToPoint(eye) ** 2, ...[0, 1, 2, 3, 4, 5, 6, 7].map((i) => eye.distanceToSquared(new THREE.Vector3(i & 1 ? bounds.max.x : bounds.min.x, i & 2 ? bounds.max.y : bounds.min.y, i & 4 ? bounds.max.z : bounds.min.z))))));
|
||||
const seen = new THREE.Box3();
|
||||
const lfc = lfw.clone().multiply(cam.matrixWorld);
|
||||
const inv = cam.projectionMatrixInverse;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
// three's NDC corner, at the near plane or at `reach` along the view
|
||||
p.set(i & 1 ? 1 : -1, i & 2 ? 1 : -1, -1).applyMatrix4(inv);
|
||||
if (i & 4) {
|
||||
if (cam instanceof THREE.OrthographicCamera) p.z = -reach;
|
||||
else p.multiplyScalar(reach / Math.max(1e-6, -p.z));
|
||||
}
|
||||
seen.expandByPoint(p.applyMatrix4(lfc));
|
||||
}
|
||||
const min = new THREE.Vector2(Math.max(box.min.x, seen.min.x), Math.max(box.min.y, seen.min.y));
|
||||
const max = new THREE.Vector2(Math.min(box.max.x, seen.max.x), Math.min(box.max.y, seen.max.y));
|
||||
if (min.x >= max.x || min.y >= max.y) return null;
|
||||
const margin = 0.02 * Math.max(max.x - min.x, max.y - min.y) + 0.05;
|
||||
const diameter = Math.max(max.x - min.x, max.y - min.y) + 2 * margin;
|
||||
const texel = diameter / size;
|
||||
const near = new THREE.Vector3(
|
||||
Math.floor((0.5 * (min.x + max.x)) / texel) * texel,
|
||||
Math.floor((0.5 * (min.y + max.y)) / texel) * texel,
|
||||
box.max.z + margin,
|
||||
);
|
||||
const cascadeFromWorld = lfw.clone().setPosition(-near.x, -near.y, -near.z);
|
||||
const r = 1 / (near.z - (box.min.z - margin));
|
||||
const clipFromCascade = new THREE.Matrix4().set(2 / diameter, 0, 0, 0, 0, 2 / diameter, 0, 0, 0, 0, r, 1, 0, 0, 0, 1);
|
||||
return { clipFromWorld: clipFromCascade.multiply(cascadeFromWorld), texel };
|
||||
}
|
||||
|
||||
/** The Lights block, the clustered lights and the one cluster's lists, as prepare_lights fills them for a 1x1x1
|
||||
* cluster grid: every point and spot light in the one cluster */
|
||||
export function fillLights(lights: Block, clustered: Block, offsets: Block, lists: Block, l: Lights, shadow: { light: THREE.DirectionalLight; cascade: Cascade } | null, width: number, height: number) {
|
||||
const ambient = l.ambient ?? new THREE.Color(1, 1, 1).multiplyScalar(80);
|
||||
lights.f("ambient_color", [ambient.r, ambient.g, ambient.b, 1]);
|
||||
const dirs = l.directional.slice(0, MAX_DIRECTIONAL);
|
||||
dirs.forEach((d, i) => {
|
||||
const lux = toRaea("DirectionalLight", d.intensity) * LUX;
|
||||
lights.f("directional_lights.color", rgb(d.color, lux), 0, i);
|
||||
const t = toLight(d);
|
||||
lights.f("directional_lights.direction_to_light", [t.x, t.y, t.z], 0, i);
|
||||
const casts = shadow?.light === d;
|
||||
lights.u("directional_lights.flags", casts ? 1 : 0, 0, i); // SHADOW_MAPS_ENABLED
|
||||
lights.f("directional_lights.shadow_depth_bias", 0.02, 0, i);
|
||||
lights.f("directional_lights.shadow_normal_bias", 1.8 * SQRT_2, 0, i);
|
||||
lights.u("directional_lights.num_cascades", casts ? 1 : 0, 0, i);
|
||||
lights.f("directional_lights.cascades_overlap_proportion", 0.3, 0, i);
|
||||
lights.u("directional_lights.depth_texture_base_index", 0, 0, i);
|
||||
lights.u("directional_lights.decal_index", 0xffffffff, 0, i);
|
||||
lights.f("directional_lights.sun_disk_angular_size", 0.00930842, 0, i);
|
||||
lights.f("directional_lights.sun_disk_intensity", 1, 0, i);
|
||||
if (casts && shadow) {
|
||||
lights.f("directional_lights.cascades.clip_from_world", shadow.cascade.clipFromWorld.elements, 0, i, 0);
|
||||
lights.f("directional_lights.cascades.texel_size", shadow.cascade.texel, 0, i, 0);
|
||||
lights.f("directional_lights.cascades.far_bound", 1e9, 0, i, 0);
|
||||
}
|
||||
});
|
||||
const points = l.points.slice(0, MAX_CLUSTERED);
|
||||
const spots = l.spots.slice(0, MAX_CLUSTERED - points.length);
|
||||
const p = new THREE.Vector3();
|
||||
const put = (k: number, light: THREE.PointLight | THREE.SpotLight, lumens: number) => {
|
||||
const range = light.distance > 0 ? light.distance : 1000;
|
||||
const c = rgb(light.color, lumens / (4 * Math.PI));
|
||||
clustered.f("data.color_inverse_square_range", [c[0], c[1], c[2], 1 / (range * range)], 0, k);
|
||||
p.setFromMatrixPosition(light.matrixWorld);
|
||||
clustered.f("data.position_radius", [p.x, p.y, p.z, 0], 0, k);
|
||||
clustered.f("data.shadow_depth_bias", 0.08, 0, k);
|
||||
clustered.f("data.shadow_normal_bias", 0.6, 0, k);
|
||||
clustered.f("data.shadow_map_near_z", 0.1, 0, k);
|
||||
clustered.u("data.decal_index", 0xffffffff, 0, k);
|
||||
clustered.f("data.range", range, 0, k);
|
||||
};
|
||||
points.forEach((pl, k) => put(k, pl, toRaea("PointLight", pl.intensity) * LUMENS));
|
||||
spots.forEach((s, j) => {
|
||||
const k = points.length + j;
|
||||
put(k, s, toRaea("SpotLight", s.intensity) * LUMENS);
|
||||
const dir = toLight(s).negate();
|
||||
const outer = s.angle;
|
||||
const inner = outer * (1 - s.penumbra);
|
||||
const scale = 1 / Math.max(Math.cos(inner) - Math.cos(outer), 1e-4);
|
||||
clustered.f("data.light_custom_data", [dir.x, dir.z, scale, -Math.cos(outer) * scale], 0, k);
|
||||
clustered.u("data.flags", (1 << 5) | (dir.y < 0 ? 1 << 1 : 0), 0, k); // SPOT_LIGHT, SPOT_LIGHT_Y_NEGATIVE
|
||||
clustered.f("data.spot_light_tan_angle", Math.tan(outer), 0, k);
|
||||
});
|
||||
// the one cluster: its lights from offset 0, its point lights then its spot lights (9 bits a count), and their
|
||||
// indices four to a u32 (clustered_forward.wesl's WebGL2 unpacking)
|
||||
offsets.u32[offsets.at("data") >> 2] = (points.length << 9) | spots.length;
|
||||
for (let k = 0; k < points.length + spots.length; k++) lists.u32[(lists.at("data", 0, k >> 4) >> 2) + ((k >> 2) & 3)] |= k << (8 * (k & 3));
|
||||
lights.u("cluster_dimensions", 1);
|
||||
lights.u32[(lights.at("cluster_dimensions") >> 2) + 1] = 1;
|
||||
lights.u32[(lights.at("cluster_dimensions") >> 2) + 2] = 1;
|
||||
lights.u32[(lights.at("cluster_dimensions") >> 2) + 3] = 1;
|
||||
lights.f("cluster_factors", [1 / width, 1 / height, 0, 0]);
|
||||
lights.u("n_directional_lights", dirs.length);
|
||||
lights.i("spot_light_shadowmap_offset", (shadow ? 1 : 0) - points.length);
|
||||
lights.u("ambient_light_flags", 1); // AFFECTS_LIGHTMAPPED_MESHES
|
||||
lights.u("n_rect_lights", 0);
|
||||
}
|
||||
|
||||
/** One mesh's MeshUniform in its batch's slot */
|
||||
export function fillMesh(b: Block, copy: number, slot: number, world: THREE.Matrix4, receives: boolean) {
|
||||
const e = world.elements;
|
||||
// world_from_local as Affine3::to_transpose: the affine's three rows, its translation in each w
|
||||
const rows = [e[0], e[4], e[8], e[12], e[1], e[5], e[9], e[13], e[2], e[6], e[10], e[14]];
|
||||
b.f("world_from_local", rows, copy, slot);
|
||||
b.f("previous_world_from_local", rows, copy, slot);
|
||||
// inverse_transpose_3x3, packed into a mat2x4 and an f32
|
||||
const n = new THREE.Matrix3().getNormalMatrix(world).elements;
|
||||
b.f("local_from_world_transpose_a", [n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7]], copy, slot);
|
||||
b.f("local_from_world_transpose_b", n[8], copy, slot);
|
||||
// no LOD (u16::MAX), SHADOW_RECEIVER, SIGN_DETERMINANT_MODEL_3X3
|
||||
b.u("flags", 0xffff | (receives ? 1 << 29 : 0) | (world.determinant() > 0 ? 1 << 31 : 0), copy, slot);
|
||||
b.u("current_skin_index", 0xffffffff, copy, slot);
|
||||
b.u("material_and_lightmap_bind_group_slot", 0xffff << 16, copy, slot);
|
||||
b.u("morph_descriptor_index", 0xffffffff, copy, slot);
|
||||
}
|
||||
|
||||
/** What a material draws with: its block's flags say which pictures it samples */
|
||||
export type Surface = {
|
||||
map?: THREE.Texture | null;
|
||||
emissiveMap?: THREE.Texture | null;
|
||||
mrMap?: THREE.Texture | null;
|
||||
aoMap?: THREE.Texture | null;
|
||||
blend: boolean;
|
||||
doubleSided: boolean;
|
||||
};
|
||||
|
||||
type AnyMaterial = THREE.Material & Partial<THREE.MeshPhysicalMaterial> & { color?: THREE.Color; map?: THREE.Texture | null };
|
||||
|
||||
/** One material's StandardMaterialUniform, from a three.js material raea's host made (materials.ts), times an
|
||||
* instance's colour */
|
||||
export function fillMaterial(b: Block, copy: number, material: THREE.Material, tint: THREE.Color | null, warn: (why: string) => void): Surface {
|
||||
const m = material as AnyMaterial;
|
||||
const c = m.color ?? new THREE.Color(1, 1, 1);
|
||||
const t = tint ?? { r: 1, g: 1, b: 1 };
|
||||
b.f("base_color", [c.r * t.r, c.g * t.g, c.b * t.b, m.opacity], copy);
|
||||
const unlit = m instanceof THREE.MeshBasicMaterial;
|
||||
const e = m.emissive;
|
||||
const k = m.emissiveIntensity ?? 1;
|
||||
// a StandardMaterial's emissive in nits, its exposure weight 0 (it skips the camera's exposure, as natively)
|
||||
if (e) b.f("emissive", [e.r * k, e.g * k, e.b * k, 0], copy);
|
||||
b.f("attenuation_color", [1, 1, 1, 1], copy);
|
||||
const map = m.map ?? null;
|
||||
const uv = map ? (map.matrixAutoUpdate && map.updateMatrix(), map.matrix.elements) : [1, 0, 0, 0, 1, 0, 0, 0, 1];
|
||||
b.f("uv_transform", [uv[0], uv[1], uv[2], 0, uv[3], uv[4], uv[5], 0, uv[6], uv[7], uv[8], 0], copy);
|
||||
// Bevy's reflectance 0.5 is three's specularIntensity 1 (materials.ts), tinted by the specular colour
|
||||
const r = 0.5 * (m.specularIntensity ?? 1);
|
||||
const st = m.specularColor ?? { r: 1, g: 1, b: 1 };
|
||||
b.f("reflectance", [st.r * r, st.g * r, st.b * r], copy);
|
||||
b.f("perceptual_roughness", m.roughness ?? 0.5, copy);
|
||||
b.f("metallic", m.metalness ?? 0, copy);
|
||||
b.f("ior", m.ior ?? 1.5, copy);
|
||||
b.f("attenuation_distance", Infinity, copy);
|
||||
b.f("clearcoat", m.clearcoat ?? 0, copy);
|
||||
b.f("clearcoat_perceptual_roughness", m.clearcoatRoughness ?? 0.5, copy);
|
||||
b.f("anisotropy_rotation", [1, 0], copy);
|
||||
b.f("parallax_depth_scale", 0.1, copy);
|
||||
b.f("max_parallax_layer_count", 16, copy);
|
||||
b.f("lightmap_exposure", 1, copy);
|
||||
b.u("max_relief_mapping_search_steps", 5, copy);
|
||||
b.u("deferred_lighting_pass_id", 1, copy);
|
||||
if ((m.transmission ?? 0) > 0) warn("transmission isn't drawn in a playable yet");
|
||||
if (m.normalMap) warn("a normal map isn't drawn in a playable yet");
|
||||
if ((m as { vertexColors?: boolean }).vertexColors) warn("vertex colours aren't drawn in a playable yet");
|
||||
const s: Surface = { map, emissiveMap: m.emissiveMap, aoMap: m.aoMap, blend: false, doubleSided: m.side === THREE.DoubleSide };
|
||||
if (m.roughnessMap || m.metalnessMap) {
|
||||
if (!m.roughnessMap || m.roughnessMap === m.metalnessMap) s.mrMap = m.roughnessMap ?? m.metalnessMap;
|
||||
else warn("separate roughness and metalness maps aren't drawn in a playable yet (one metallic-roughness map is)");
|
||||
}
|
||||
let flags = 1 << 8; // FOG_ENABLED
|
||||
if (s.map) flags |= 1 << 0;
|
||||
if (s.emissiveMap) flags |= 1 << 1;
|
||||
if (s.mrMap) flags |= 1 << 2;
|
||||
if (s.aoMap) flags |= 1 << 3;
|
||||
if (s.doubleSided) flags |= 1 << 4;
|
||||
if (unlit) flags |= 1 << 5;
|
||||
let cutoff = 0.5;
|
||||
if (m.alphaTest > 0) {
|
||||
flags |= 1 << 29; // ALPHA_MODE_MASK
|
||||
cutoff = m.alphaTest;
|
||||
} else if (m.transparent && (m.opacity < 1 || !!map)) {
|
||||
flags |= 2 << 29; // ALPHA_MODE_BLEND
|
||||
s.blend = true;
|
||||
}
|
||||
b.u("flags", flags, copy);
|
||||
b.f("alpha_cutoff", cutoff, copy);
|
||||
return s;
|
||||
}
|
||||
|
||||
/** The ambient light's colour times its brightness in cd/m² (a hemisphere light is drawn as the ambient between its
|
||||
* two colours) */
|
||||
export function ambientOf(l: THREE.AmbientLight | THREE.HemisphereLight, had: THREE.Color | null): THREE.Color {
|
||||
const nits = toRaea("AmbientLight", l.intensity) * AMBIENT;
|
||||
const c = l instanceof THREE.HemisphereLight ? l.color.clone().lerp(l.groundColor, 0.5) : l.color.clone();
|
||||
return (had ?? new THREE.Color(0, 0, 0)).add(c.multiplyScalar(nits));
|
||||
}
|
||||
|
||||
/** Bevy's distance fog (prepare_fog's GpuFog) from the scene's, as the native engine makes it from a Fog part: a
|
||||
* density makes it exponential, else linear from near to far; none is mode 0, which the shader passes over */
|
||||
export function fillFog(b: Block, fog: THREE.Fog | THREE.FogExp2 | null) {
|
||||
if (!fog) return;
|
||||
const c = fog.color;
|
||||
b.f("base_color", [c.r, c.g, c.b, 1]);
|
||||
b.f("directional_light_color", [0, 0, 0, 0]);
|
||||
b.f("directional_light_exponent", 8);
|
||||
if (fog instanceof THREE.FogExp2) {
|
||||
b.f("be", [fog.density, 0, 0]);
|
||||
b.u("mode", 2);
|
||||
} else {
|
||||
b.f("be", [fog.near, fog.far, 0]);
|
||||
b.u("mode", 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// WebGL2 plumbing for Bevy's programs in a playable (docs/playables.feature PA11): programs linked with each uniform
|
||||
// block on its binding's point and each sampler on its unit, by the names Bevy's files give them (programs.ts), and
|
||||
// the scene's geometry and pictures as GL buffers and textures, kept while the scene holds them.
|
||||
import * as THREE from "three";
|
||||
import { BLOCKS, SAMPLERS } from "./programs";
|
||||
|
||||
/** Each of Bevy's uniform bindings on its own binding point */
|
||||
export const POINTS: Record<string, number> = {
|
||||
view: 0, lights: 1, cluster_offsets_and_counts: 2, clusterable_object_index_lists: 3, clustered_lights: 4,
|
||||
globals: 5, mesh: 6, material: 7, metadata: 8, fog: 9,
|
||||
};
|
||||
|
||||
/** Each of Bevy's textures on its own unit */
|
||||
export const UNITS: Record<string, number> = {
|
||||
base_color_texture: 0, emissive_texture: 1, metallic_roughness_texture: 2, occlusion_texture: 3,
|
||||
directional_shadow_textures: 4, point_shadow_textures: 5, raea_gi: 6,
|
||||
};
|
||||
|
||||
/** A program linking: compiled and linked as soon as it's asked for, its blocks and samplers bound (which waits for
|
||||
* the link) only when it's first drawn with, so the driver compiles it while the page's first frame is being built */
|
||||
export class Program {
|
||||
private done = false;
|
||||
first: WebGLUniformLocation | null = null;
|
||||
constructor(private gl: WebGL2RenderingContext, readonly p: WebGLProgram, private shaders: WebGLShader[]) {}
|
||||
|
||||
/** Linked and bound; throws when it didn't link */
|
||||
use() {
|
||||
const gl = this.gl;
|
||||
gl.useProgram(this.p);
|
||||
if (this.done) return;
|
||||
this.done = true;
|
||||
const p = this.p;
|
||||
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
|
||||
const why = this.shaders.map((s) => gl.getShaderInfoLog(s)).find(Boolean) || gl.getProgramInfoLog(p);
|
||||
throw new Error(`raea playable: Bevy's programs didn't link: ${why}`);
|
||||
}
|
||||
for (const s of this.shaders) gl.deleteShader(s);
|
||||
const blocks = gl.getProgramParameter(p, gl.ACTIVE_UNIFORM_BLOCKS) as number;
|
||||
for (let i = 0; i < blocks; i++) {
|
||||
const name = gl.getActiveUniformBlockName(p, i) ?? "";
|
||||
const point = POINTS[BLOCKS[name] ?? ""];
|
||||
if (point === undefined) throw new Error(`raea playable: Bevy's uniform block ${name} has no binding`);
|
||||
gl.uniformBlockBinding(p, i, point);
|
||||
}
|
||||
for (const [name, texture] of Object.entries(SAMPLERS)) {
|
||||
const at = gl.getUniformLocation(p, name);
|
||||
if (at) gl.uniform1i(at, UNITS[texture]);
|
||||
}
|
||||
this.first = gl.getUniformLocation(p, "naga_vs_first_instance");
|
||||
}
|
||||
}
|
||||
|
||||
function shader(gl: WebGL2RenderingContext, type: number, src: string): WebGLShader {
|
||||
const s = gl.createShader(type)!;
|
||||
gl.shaderSource(s, src);
|
||||
gl.compileShader(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Programs compiled and linked, without waiting for either */
|
||||
export function programs(gl: WebGL2RenderingContext, pairs: [string, string][]): Program[] {
|
||||
return pairs.map(([vs, fs]) => {
|
||||
const p = gl.createProgram()!;
|
||||
const v = shader(gl, gl.VERTEX_SHADER, vs);
|
||||
const f = shader(gl, gl.FRAGMENT_SHADER, fs);
|
||||
gl.attachShader(p, v);
|
||||
gl.attachShader(p, f);
|
||||
gl.linkProgram(p);
|
||||
return new Program(gl, p, [v, f]);
|
||||
});
|
||||
}
|
||||
|
||||
/** One picture's texture, made again when three.js marks it changed */
|
||||
type Kept = { tex: WebGLTexture; version: number; seen: number };
|
||||
|
||||
const WRAP: Record<number, number> = { [THREE.RepeatWrapping]: 0x2901, [THREE.ClampToEdgeWrapping]: 0x812f, [THREE.MirroredRepeatWrapping]: 0x8370 };
|
||||
|
||||
/** The scene's pictures as textures: a colour picture in sRGB (sampled as linear, as Bevy's Rgba8UnormSrgb is) */
|
||||
export class Textures {
|
||||
private kept = new Map<THREE.Texture, Kept>();
|
||||
private frame = 0;
|
||||
/** Bevy's fallback for a texture a material doesn't have: white */
|
||||
readonly white: WebGLTexture;
|
||||
/** raea GI's screen with nothing in it: every pixel's light comes from the ambient light, as natively without GI */
|
||||
readonly none: WebGLTexture;
|
||||
|
||||
constructor(private gl: WebGL2RenderingContext) {
|
||||
this.white = this.pixel([255, 255, 255, 255]);
|
||||
this.none = this.pixel([0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
private pixel(rgba: number[]): WebGLTexture {
|
||||
const gl = this.gl;
|
||||
const t = gl.createTexture()!;
|
||||
gl.bindTexture(gl.TEXTURE_2D, t);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(rgba));
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
return t;
|
||||
}
|
||||
|
||||
/** A three.js texture's GL texture, or undefined until its picture has loaded */
|
||||
get(t: THREE.Texture | null | undefined): WebGLTexture | undefined {
|
||||
if (!t) return undefined;
|
||||
const img = t.image as (TexImageSource & { width?: number; height?: number; complete?: boolean; data?: ArrayBufferView }) | undefined;
|
||||
if (!img || img.complete === false || !(img.width ?? 0)) return undefined;
|
||||
const gl = this.gl;
|
||||
let k = this.kept.get(t);
|
||||
if (k && k.version === t.version) {
|
||||
k.seen = this.frame;
|
||||
return k.tex;
|
||||
}
|
||||
const tex = k?.tex ?? gl.createTexture()!;
|
||||
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, t.flipY);
|
||||
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, t.premultiplyAlpha);
|
||||
gl.pixelStorei(gl.UNPACK_ALIGNMENT, t.unpackAlignment);
|
||||
const srgb = t.colorSpace === THREE.SRGBColorSpace;
|
||||
const internal = srgb ? gl.SRGB8_ALPHA8 : gl.RGBA8;
|
||||
if (img.data) gl.texImage2D(gl.TEXTURE_2D, 0, internal, img.width!, img.height!, 0, gl.RGBA, gl.UNSIGNED_BYTE, img.data);
|
||||
else gl.texImage2D(gl.TEXTURE_2D, 0, internal, gl.RGBA, gl.UNSIGNED_BYTE, img);
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
|
||||
gl.generateMipmap(gl.TEXTURE_2D);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, WRAP[t.wrapS] ?? gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, WRAP[t.wrapT] ?? gl.CLAMP_TO_EDGE);
|
||||
this.kept.set(t, { tex, version: t.version, seen: this.frame });
|
||||
return tex;
|
||||
}
|
||||
|
||||
/** The end of a frame: a texture the scene no longer draws is let go */
|
||||
done() {
|
||||
for (const [t, k] of this.kept)
|
||||
if (k.seen < this.frame - 1) {
|
||||
this.gl.deleteTexture(k.tex);
|
||||
this.kept.delete(t);
|
||||
}
|
||||
this.frame++;
|
||||
}
|
||||
}
|
||||
|
||||
/** One geometry's vertex array: positions, normals and UVs at Bevy's locations 0, 1 and 2, and its indices */
|
||||
export type Mesh = { vao: WebGLVertexArrayObject; count: number; index: number; buffers: WebGLBuffer[]; version: string; seen: number };
|
||||
|
||||
export class Meshes {
|
||||
private kept = new Map<THREE.BufferGeometry, Mesh>();
|
||||
private frame = 0;
|
||||
|
||||
constructor(private gl: WebGL2RenderingContext) {}
|
||||
|
||||
get(g: THREE.BufferGeometry): Mesh | undefined {
|
||||
const pos = g.attributes.position as THREE.BufferAttribute | undefined;
|
||||
if (!pos) return undefined;
|
||||
const nor = g.attributes.normal as THREE.BufferAttribute | undefined;
|
||||
const uv = g.attributes.uv as THREE.BufferAttribute | undefined;
|
||||
const version = `${pos.version}.${nor?.version ?? -1}.${uv?.version ?? -1}.${g.index?.version ?? -1}`;
|
||||
let m = this.kept.get(g);
|
||||
if (m && m.version === version) {
|
||||
m.seen = this.frame;
|
||||
return m;
|
||||
}
|
||||
const gl = this.gl;
|
||||
if (m) this.free(m);
|
||||
const vao = gl.createVertexArray()!;
|
||||
gl.bindVertexArray(vao);
|
||||
const buffers: WebGLBuffer[] = [];
|
||||
const attr = (loc: number, a: THREE.BufferAttribute | undefined, size: number) => {
|
||||
if (!a) {
|
||||
gl.disableVertexAttribArray(loc);
|
||||
gl.vertexAttrib4f(loc, 0, 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
const b = gl.createBuffer()!;
|
||||
buffers.push(b);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, b);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, a.array as Float32Array, gl.STATIC_DRAW);
|
||||
gl.enableVertexAttribArray(loc);
|
||||
gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
|
||||
};
|
||||
attr(0, pos, 3);
|
||||
attr(1, nor, 3);
|
||||
attr(2, uv, 2);
|
||||
let index = 0;
|
||||
if (g.index) {
|
||||
const b = gl.createBuffer()!;
|
||||
buffers.push(b);
|
||||
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b);
|
||||
const arr = g.index.array;
|
||||
const wide = arr instanceof Uint32Array || (!(arr instanceof Uint16Array) && pos.count > 65535);
|
||||
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, wide ? Uint32Array.from(arr) : Uint16Array.from(arr), gl.STATIC_DRAW);
|
||||
index = wide ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT;
|
||||
}
|
||||
gl.bindVertexArray(null);
|
||||
m = { vao, count: g.index ? g.index.count : pos.count, index, buffers, version, seen: this.frame };
|
||||
this.kept.set(g, m);
|
||||
return m;
|
||||
}
|
||||
|
||||
private free(m: Mesh) {
|
||||
this.gl.deleteVertexArray(m.vao);
|
||||
for (const b of m.buffers) this.gl.deleteBuffer(b);
|
||||
}
|
||||
|
||||
done() {
|
||||
for (const [g, m] of this.kept)
|
||||
if (m.seen < this.frame - 1) {
|
||||
this.free(m);
|
||||
this.kept.delete(g);
|
||||
}
|
||||
this.frame++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
e79d0a380e1b6a00a0c7a9f21f1d6aa19fa1ec3673f1aea423c4ba4f087b9a65
|
||||
@@ -0,0 +1,10 @@
|
||||
// Bevy's PBR programs for a playable, as tools/bevy-glsl makes them (docs/playables.feature PA11): generated by
|
||||
// sdk/playable/bevy/build.sh, not edited. Each program's GLSL ES 3.00; which of Bevy's bindings each uniform block
|
||||
// and sampler is; each binding's fields at their byte offsets (nested fields from their struct's start, an array's
|
||||
// stride under `name[]`).
|
||||
export const PBR_VERT = "#version 300 es\nprecision highp float;\nprecision highp int;\nuniform uint naga_vs_first_instance;\nstruct _1bevy_pbr_render_1forward_io_Vertex {\nuint instance_index;\nvec3 position;\nvec3 normal;\nvec2 uv;\n};\nstruct _1bevy_pbr_render_1forward_io_VertexOutput {\nvec4 position;\nvec4 world_position;\nvec3 world_normal;\nvec2 uv;\nuint instance_index;\n};\nstruct _1bevy_pbr_render_1forward_io_UncompressedVertex {\nuint instance_index;\nvec3 position;\nvec3 normal;\nvec2 uv;\n};\nstruct _1bevy_render_mesh_1metadata_types_MeshMetadata {\nvec3 aabb_center;\nuint pad_a;\nvec3 aabb_half_extents;\nuint pad_b;\nvec4 uv_channels_min_and_extents[2];\n};\nstruct _1bevy_pbr_render_1mesh_types_Mesh {\nmat3x4 world_from_local;\nmat3x4 previous_world_from_local;\nmat2x4 local_from_world_transpose_a;\nfloat local_from_world_transpose_b;\nuint flags;\nuvec2 lightmap_uv_rect;\nuint first_vertex_index;\nuint current_skin_index;\nuint material_and_lightmap_bind_group_slot;\nuint tag;\nuint morph_descriptor_index;\nuint metadata_index;\n};\nstruct _1bevy_render_view_ColorGrading {\nmat3x3 balance;\nvec3 saturation;\nvec3 contrast;\nvec3 gamma;\nvec3 gain;\nvec3 lift;\nvec2 midtone_range;\nfloat exposure;\nfloat hue;\nfloat post_saturation;\n};\nstruct _1bevy_render_view_View {\nmat4x4 clip_from_world;\nmat4x4 unjittered_clip_from_world;\nmat4x4 world_from_clip;\nmat4x4 world_from_view;\nmat4x4 view_from_world;\nmat4x4 clip_from_view;\nmat4x4 view_from_clip;\nvec3 world_position;\nfloat exposure;\nvec4 viewport;\nvec4 main_pass_viewport;\nvec4 frustum[6];\nvec3 lod_view_world_position;\n_1bevy_render_view_ColorGrading color_grading;\nfloat mip_bias;\nuint frame_count;\n};\nlayout(std140) uniform _1bevy_render_mesh_1metadata_types_MeshMetadata_block_0Vertex { _1bevy_render_mesh_1metadata_types_MeshMetadata _group_2_binding_9_vs; };\nlayout(std140) uniform type_10_block_1Vertex { _1bevy_pbr_render_1mesh_types_Mesh _group_2_binding_0_vs[93]; };\nlayout(std140) uniform _1bevy_render_view_View_block_2Vertex { _1bevy_render_view_View _group_0_binding_0_vs; };\nlayout(location = 0) in vec3 _p2vs_location0;\nlayout(location = 1) in vec3 _p2vs_location1;\nlayout(location = 2) in vec2 _p2vs_location2;\nsmooth out vec4 _vs2fs_location0;\nsmooth out vec3 _vs2fs_location1;\nsmooth out vec2 _vs2fs_location2;\nflat out uint _vs2fs_location6;\n_1bevy_render_mesh_1metadata_types_MeshMetadata _1bevy_pbr_render_1mesh_functions_1get_metadata(uint instance_index) {\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _group_2_binding_9_vs;\nreturn _e2;\n}\n_1bevy_pbr_render_1forward_io_UncompressedVertex _1bevy_pbr_render_1forward_io_1decompress_vertex(_1bevy_pbr_render_1forward_io_Vertex vertex_in, uint instance_index_1) {\n_1bevy_pbr_render_1forward_io_UncompressedVertex uncompressed_vertex = _1bevy_pbr_render_1forward_io_UncompressedVertex(0u, vec3(0.0), vec3(0.0), vec2(0.0));\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _1bevy_pbr_render_1mesh_functions_1get_metadata(instance_index_1);\nuncompressed_vertex.instance_index = instance_index_1;\nuncompressed_vertex.position = vertex_in.position;\nuncompressed_vertex.normal = vertex_in.normal;\nuncompressed_vertex.uv = vertex_in.uv;\n_1bevy_pbr_render_1forward_io_UncompressedVertex _e11 = uncompressed_vertex;\nreturn _e11;\n}\nmat4x4 _1bevy_render_maths_2affine3_to_square(mat3x4 affine) {\nreturn transpose(mat4x4(affine[0], affine[1], affine[2], vec4(0.0, 0.0, 0.0, 1.0)));\n}\nmat4x4 _1bevy_pbr_render_1mesh_functions_3get_world_from_local(uint instance_index_2) {\nmat3x4 _e4 = _group_2_binding_0_vs[instance_index_2].world_from_local;\nmat4x4 _e5 = _1bevy_render_maths_2affine3_to_square(_e4);\nreturn _e5;\n}\nmat3x3 _1bevy_render_maths_4mat2x4_f32_to_mat3x3_unpack(mat2x4 a, float b) {\nreturn mat3x3(a[0].xyz, vec3(a[0].w, a[1].xy), vec3(a[1].zw, b));\n}\nvec3 _1bevy_pbr_render_1mesh_functions_4mesh_normal_local_to_world(vec3 vertex_normal, uint instance_index_3) {\nif (any(notEqual(vertex_normal, vec3(0.0)))) {\nmat2x4 _e9 = _group_2_binding_0_vs[instance_index_3].local_from_world_transpose_a;\nfloat _e13 = _group_2_binding_0_vs[instance_index_3].local_from_world_transpose_b;\nmat3x3 _e14 = _1bevy_render_maths_4mat2x4_f32_to_mat3x3_unpack(_e9, _e13);\nreturn normalize((_e14 * vertex_normal));\n} else {\nreturn vertex_normal;\n}\n}\nvec4 _1bevy_pbr_render_1mesh_functions_4mesh_position_local_to_world(mat4x4 world_from_local_1, vec4 vertex_position) {\nreturn (world_from_local_1 * vertex_position);\n}\nvec4 _1bevy_pbr_render_1view_transformations_3position_world_to_clip(vec3 world_pos) {\nmat4x4 _e3 = _group_0_binding_0_vs.clip_from_world;\nvec4 clip_pos = (_e3 * vec4(world_pos, 1.0));\nreturn clip_pos;\n}\nvoid main() {\n_1bevy_pbr_render_1forward_io_Vertex vertex_no_morph = _1bevy_pbr_render_1forward_io_Vertex((uint(gl_InstanceID) + naga_vs_first_instance), _p2vs_location0, _p2vs_location1, _p2vs_location2);\n_1bevy_pbr_render_1forward_io_VertexOutput out_ = _1Line truncated
|
||||
export const PBR_FRAG = "#version 300 es\nprecision highp float;\nprecision highp int;\nstruct _1bevy_pbr_render_1forward_io_VertexOutput {\nvec4 position;\nvec4 world_position;\nvec3 world_normal;\nvec2 uv;\nuint instance_index;\n};\nstruct _1bevy_pbr_render_1forward_io_FragmentOutput {\nvec4 color;\n};\nstruct _1bevy_pbr_render_1pbr_types_StandardMaterial {\nvec4 base_color;\nvec4 emissive;\nvec4 attenuation_color;\nmat3x3 uv_transform;\nvec3 reflectance;\nfloat perceptual_roughness;\nfloat metallic;\nfloat diffuse_transmission;\nfloat specular_transmission;\nfloat thickness;\nfloat ior;\nfloat attenuation_distance;\nfloat clearcoat;\nfloat clearcoat_perceptual_roughness;\nfloat anisotropy_strength;\nvec2 anisotropy_rotation;\nuint flags;\nfloat alpha_cutoff;\nfloat parallax_depth_scale;\nfloat max_parallax_layer_count;\nfloat lightmap_exposure;\nuint max_relief_mapping_search_steps;\nuint deferred_lighting_pass_id;\n};\nstruct _1bevy_pbr_render_1pbr_types_PbrInput {\n_1bevy_pbr_render_1pbr_types_StandardMaterial material;\nvec3 diffuse_occlusion;\nfloat specular_occlusion;\nvec4 frag_coord;\nvec4 world_position;\nvec3 world_normal;\nvec3 N;\nvec3 V;\nvec3 lightmap_light;\nvec3 clearcoat_N;\nfloat anisotropy_strength;\nvec3 anisotropy_T;\nvec3 anisotropy_B;\nbool is_orthographic;\nuint flags;\nfloat directional_shadow_factor;\n};\nstruct _1bevy_pbr_render_1mesh_types_Mesh {\nmat3x4 world_from_local;\nmat3x4 previous_world_from_local;\nmat2x4 local_from_world_transpose_a;\nfloat local_from_world_transpose_b;\nuint flags;\nuvec2 lightmap_uv_rect;\nuint first_vertex_index;\nuint current_skin_index;\nuint material_and_lightmap_bind_group_slot;\nuint tag;\nuint morph_descriptor_index;\nuint metadata_index;\n};\nstruct _1bevy_render_view_ColorGrading {\nmat3x3 balance;\nvec3 saturation;\nvec3 contrast;\nvec3 gamma;\nvec3 gain;\nvec3 lift;\nvec2 midtone_range;\nfloat exposure;\nfloat hue;\nfloat post_saturation;\n};\nstruct _1bevy_render_view_View {\nmat4x4 clip_from_world;\nmat4x4 unjittered_clip_from_world;\nmat4x4 world_from_clip;\nmat4x4 world_from_view;\nmat4x4 view_from_world;\nmat4x4 clip_from_view;\nmat4x4 view_from_clip;\nvec3 world_position;\nfloat exposure;\nvec4 viewport;\nvec4 main_pass_viewport;\nvec4 frustum[6];\nvec3 lod_view_world_position;\n_1bevy_render_view_ColorGrading color_grading;\nfloat mip_bias;\nuint frame_count;\n};\nstruct _1bevy_pbr_render_1pbr_functions_SampleBias {\nfloat mip_bias;\n};\nstruct _1bevy_pbr_render_1pbr_lighting_LayerLightingInput {\nvec3 N;\nvec3 R;\nfloat NdotV;\nfloat perceptual_roughness;\nfloat roughness;\n};\nstruct _1bevy_pbr_render_1pbr_lighting_LightingInput {\n_1bevy_pbr_render_1pbr_lighting_LayerLightingInput layers[1];\nvec3 P;\nvec3 V;\nvec3 diffuse_color;\nfloat metallic;\nvec3 F0_dielectric;\nvec3 F0_metallic;\nvec2 F_ab;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_DirectionalCascade {\nmat4x4 clip_from_world;\nfloat texel_size;\nfloat far_bound;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_DirectionalLight {\n_1bevy_pbr_render_2mesh_view_types_DirectionalCascade cascades[1];\nvec4 color;\nvec3 direction_to_light;\nuint flags;\nfloat soft_shadow_size;\nfloat shadow_depth_bias;\nfloat shadow_normal_bias;\nuint num_cascades;\nfloat cascades_overlap_proportion;\nuint depth_texture_base_index;\nuint decal_index;\nfloat sun_disk_angular_size;\nfloat sun_disk_intensity;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_RectLight {\nvec4 color;\nvec3 position;\nfloat width;\nvec3 right;\nfloat height;\nvec3 up;\nfloat range;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_Lights {\n_1bevy_pbr_render_2mesh_view_types_DirectionalLight directional_lights[10];\nvec4 ambient_color;\nuvec4 cluster_dimensions;\nvec4 cluster_factors;\nuint n_directional_lights;\nint spot_light_shadowmap_offset;\nuint ambient_light_flags;\nuint n_rect_lights;\n_1bevy_pbr_render_2mesh_view_types_RectLight rect_lights[8];\n};\nstruct _1bevy_pbr_render_1clustered_forward_ClusterableObjectIndexRanges {\nuint first_point_light_index_offset;\nuint first_spot_light_index_offset;\nuint first_rect_light_index_offset;\nuint first_reflection_probe_index_offset;\nuint first_irradiance_volume_index_offset;\nuint first_decal_offset;\nuint last_clusterable_object_index_offset;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusterOffsetsAndCounts {\nuvec4 data[1024];\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusterableObjectIndexLists {\nuvec4 data[1024];\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusteredLight {\nvec4 light_custom_data;\nvec4 color_inverse_square_range;\nvec4 position_radius;\nuint flags;\nfloat shadow_depth_bias;\nfloat shadow_normal_bias;\nfloat spot_light_tan_angle;\nfloat soft_shadow_size;\nfloat shadow_map_near_z;\nuint decal_index;\nfloat range;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusteredLights {\n_1bevy_pbr_render_2mesh_view_types_ClusteredLight data[204];\n};\nstruct _1bevy_render_globals_Globals {\nfloat time;\nfloat delta_time;\nuint frame_count;\Line truncated
|
||||
export const SHADOW_VERT = "#version 300 es\nprecision highp float;\nprecision highp int;\nuniform uint naga_vs_first_instance;\nstruct _1bevy_pbr_prepass_io_Vertex {\nuint instance_index;\nvec3 position;\n};\nstruct _1bevy_pbr_prepass_io_VertexOutput {\nvec4 position;\nvec4 world_position;\nfloat unclipped_depth;\nuint instance_index;\n};\nstruct _1bevy_pbr_prepass_io_UncompressedVertex {\nuint instance_index;\nvec3 position;\n};\nstruct _1bevy_render_mesh_1metadata_types_MeshMetadata {\nvec3 aabb_center;\nuint pad_a;\nvec3 aabb_half_extents;\nuint pad_b;\nvec4 uv_channels_min_and_extents[2];\n};\nstruct _1bevy_pbr_render_1mesh_types_Mesh {\nmat3x4 world_from_local;\nmat3x4 previous_world_from_local;\nmat2x4 local_from_world_transpose_a;\nfloat local_from_world_transpose_b;\nuint flags;\nuvec2 lightmap_uv_rect;\nuint first_vertex_index;\nuint current_skin_index;\nuint material_and_lightmap_bind_group_slot;\nuint tag;\nuint morph_descriptor_index;\nuint metadata_index;\n};\nstruct _1bevy_render_view_ColorGrading {\nmat3x3 balance;\nvec3 saturation;\nvec3 contrast;\nvec3 gamma;\nvec3 gain;\nvec3 lift;\nvec2 midtone_range;\nfloat exposure;\nfloat hue;\nfloat post_saturation;\n};\nstruct _1bevy_render_view_View {\nmat4x4 clip_from_world;\nmat4x4 unjittered_clip_from_world;\nmat4x4 world_from_clip;\nmat4x4 world_from_view;\nmat4x4 view_from_world;\nmat4x4 clip_from_view;\nmat4x4 view_from_clip;\nvec3 world_position;\nfloat exposure;\nvec4 viewport;\nvec4 main_pass_viewport;\nvec4 frustum[6];\nvec3 lod_view_world_position;\n_1bevy_render_view_ColorGrading color_grading;\nfloat mip_bias;\nuint frame_count;\n};\nlayout(std140) uniform _1bevy_render_mesh_1metadata_types_MeshMetadata_block_0Vertex { _1bevy_render_mesh_1metadata_types_MeshMetadata _group_2_binding_9_vs; };\nlayout(std140) uniform type_9_block_1Vertex { _1bevy_pbr_render_1mesh_types_Mesh _group_2_binding_0_vs[93]; };\nlayout(std140) uniform _1bevy_render_view_View_block_2Vertex { _1bevy_render_view_View _group_0_binding_0_vs; };\nlayout(location = 0) in vec3 _p2vs_location0;\nsmooth out vec4 _vs2fs_location4;\nsmooth out float _vs2fs_location6;\nflat out uint _vs2fs_location7;\n_1bevy_render_mesh_1metadata_types_MeshMetadata _1bevy_pbr_render_1mesh_functions_1get_metadata(uint instance_index) {\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _group_2_binding_9_vs;\nreturn _e2;\n}\n_1bevy_pbr_prepass_io_UncompressedVertex _1bevy_pbr_prepass_io_1decompress_vertex(_1bevy_pbr_prepass_io_Vertex vertex_in, uint instance_index_1) {\n_1bevy_pbr_prepass_io_UncompressedVertex uncompressed_vertex = _1bevy_pbr_prepass_io_UncompressedVertex(0u, vec3(0.0));\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _1bevy_pbr_render_1mesh_functions_1get_metadata(instance_index_1);\nuncompressed_vertex.instance_index = instance_index_1;\nuncompressed_vertex.position = vertex_in.position;\n_1bevy_pbr_prepass_io_UncompressedVertex _e7 = uncompressed_vertex;\nreturn _e7;\n}\nmat4x4 _1bevy_render_maths_2affine3_to_square(mat3x4 affine) {\nreturn transpose(mat4x4(affine[0], affine[1], affine[2], vec4(0.0, 0.0, 0.0, 1.0)));\n}\nmat4x4 _1bevy_pbr_render_1mesh_functions_3get_world_from_local(uint instance_index_2) {\nmat3x4 _e4 = _group_2_binding_0_vs[instance_index_2].world_from_local;\nmat4x4 _e5 = _1bevy_render_maths_2affine3_to_square(_e4);\nreturn _e5;\n}\nvec4 _1bevy_pbr_render_1mesh_functions_4mesh_position_local_to_world(mat4x4 world_from_local_1, vec4 vertex_position) {\nreturn (world_from_local_1 * vertex_position);\n}\nvec4 _1bevy_pbr_render_1view_transformations_3position_world_to_clip(vec3 world_pos) {\nmat4x4 _e3 = _group_0_binding_0_vs.clip_from_world;\nvec4 clip_pos = (_e3 * vec4(world_pos, 1.0));\nreturn clip_pos;\n}\nvoid main() {\n_1bevy_pbr_prepass_io_Vertex vertex_no_morph = _1bevy_pbr_prepass_io_Vertex((uint(gl_InstanceID) + naga_vs_first_instance), _p2vs_location0);\n_1bevy_pbr_prepass_io_VertexOutput out_ = _1bevy_pbr_prepass_io_VertexOutput(vec4(0.0), vec4(0.0), 0.0, 0u);\n_1bevy_pbr_prepass_io_UncompressedVertex vertex_1 = _1bevy_pbr_prepass_io_UncompressedVertex(0u, vec3(0.0));\nmat4x4 world_from_local = mat4x4(0.0);\n_1bevy_pbr_prepass_io_UncompressedVertex _e3 = _1bevy_pbr_prepass_io_1decompress_vertex(vertex_no_morph, vertex_no_morph.instance_index);\nvertex_1 = _e3;\nmat4x4 _e6 = _1bevy_pbr_render_1mesh_functions_3get_world_from_local(vertex_no_morph.instance_index);\nworld_from_local = _e6;\nmat4x4 _e9 = world_from_local;\nvec3 _e11 = vertex_1.position;\nvec4 _e14 = _1bevy_pbr_render_1mesh_functions_4mesh_position_local_to_world(_e9, vec4(_e11, 1.0));\nout_.world_position = _e14;\nvec4 _e17 = out_.world_position;\nvec4 _e19 = _1bevy_pbr_render_1view_transformations_3position_world_to_clip(_e17.xyz);\nout_.position = _e19;\nfloat _e23 = out_.position.z;\nout_.unclipped_depth = _e23;\nfloat _e28 = out_.position.z;\nout_.position.z = min(_e28, 1.0);\nout_.instance_index = vertex_no_morph.instance_index;\n_1bevy_pbr_prepass_io_VertexOutput _eLine truncated
|
||||
export const BLOCKS: Record<string, string> = {"_1bevy_pbr_render_1pbr_types_StandardMaterial_block_1Fragment":"material","_1bevy_pbr_render_2mesh_view_types_ClusterOffsetsAndCounts_block_4Fragment":"cluster_offsets_and_counts","_1bevy_pbr_render_2mesh_view_types_ClusterableObjectIndexLists_block_5Fragment":"clusterable_object_index_lists","_1bevy_pbr_render_2mesh_view_types_ClusteredLights_block_6Fragment":"clustered_lights","_1bevy_pbr_render_2mesh_view_types_Fog_block_8Fragment":"fog","_1bevy_pbr_render_2mesh_view_types_Lights_block_3Fragment":"lights","_1bevy_render_globals_Globals_block_7Fragment":"globals","_1bevy_render_mesh_1metadata_types_MeshMetadata_block_0Vertex":"metadata","_1bevy_render_view_View_block_2Fragment":"view","_1bevy_render_view_View_block_2Vertex":"view","type_10_block_0Fragment":"mesh","type_10_block_1Vertex":"mesh","type_9_block_1Vertex":"mesh"};
|
||||
export const SAMPLERS: Record<string, string> = {"_group_0_binding_2_fs":"point_shadow_textures","_group_0_binding_41_fs":"raea_gi","_group_0_binding_5_fs":"directional_shadow_textures","_group_3_binding_1_fs":"base_color_texture","_group_3_binding_3_fs":"emissive_texture","_group_3_binding_5_fs":"metallic_roughness_texture","_group_3_binding_7_fs":"occlusion_texture"};
|
||||
export const LAYOUT: Record<string, Record<string, number>> = {"cluster_offsets_and_counts":{"$size":16384,"data":0,"data[]":16},"clusterable_object_index_lists":{"$size":16384,"data":0,"data[]":16},"clustered_lights":{"$size":16320,"data":0,"data.color_inverse_square_range":16,"data.decal_index":72,"data.flags":48,"data.light_custom_data":0,"data.position_radius":32,"data.range":76,"data.shadow_depth_bias":52,"data.shadow_map_near_z":68,"data.shadow_normal_bias":56,"data.soft_shadow_size":64,"data.spot_light_tan_angle":60,"data[]":80},"fog":{"$size":64,"base_color":0,"be":32,"bi":48,"directional_light_color":16,"directional_light_exponent":44,"mode":60},"globals":{"$size":16,"_webgl2_padding":12,"delta_time":4,"frame_count":8,"time":0},"lights":{"$size":2176,"ambient_color":1600,"ambient_light_flags":1656,"cluster_dimensions":1616,"cluster_factors":1632,"directional_lights":0,"directional_lights.cascades":0,"directional_lights.cascades.clip_from_world":0,"directional_lights.cascades.far_bound":68,"directional_lights.cascades.texel_size":64,"directional_lights.cascades[]":80,"directional_lights.cascades_overlap_proportion":128,"directional_lights.color":80,"directional_lights.decal_index":136,"directional_lights.depth_texture_base_index":132,"directional_lights.direction_to_light":96,"directional_lights.flags":108,"directional_lights.num_cascades":124,"directional_lights.shadow_depth_bias":116,"directional_lights.shadow_normal_bias":120,"directional_lights.soft_shadow_size":112,"directional_lights.sun_disk_angular_size":140,"directional_lights.sun_disk_intensity":144,"directional_lights[]":160,"n_directional_lights":1648,"n_rect_lights":1660,"rect_lights":1664,"rect_lights.color":0,"rect_lights.height":44,"rect_lights.position":16,"rect_lights.range":60,"rect_lights.right":32,"rect_lights.up":48,"rect_lights.width":28,"rect_lights[]":64,"spot_light_shadowmap_offset":1652},"material":{"$size":192,"alpha_cutoff":164,"anisotropy_rotation":152,"anisotropy_strength":144,"attenuation_color":32,"attenuation_distance":132,"base_color":0,"clearcoat":136,"clearcoat_perceptual_roughness":140,"deferred_lighting_pass_id":184,"diffuse_transmission":116,"emissive":16,"flags":160,"ior":128,"lightmap_exposure":176,"max_parallax_layer_count":172,"max_relief_mapping_search_steps":180,"metallic":112,"parallax_depth_scale":168,"perceptual_roughness":108,"reflectance":96,"specular_transmission":120,"thickness":124,"uv_transform":48},"mesh":{"$size":16368,"[]":176,"current_skin_index":148,"first_vertex_index":144,"flags":132,"lightmap_uv_rect":136,"local_from_world_transpose_a":96,"local_from_world_transpose_b":128,"material_and_lightmap_bind_group_slot":152,"metadata_index":164,"morph_descriptor_index":160,"previous_world_from_local":48,"tag":156,"world_from_local":0},"metadata":{"$size":64,"aabb_center":0,"aabb_half_extents":16,"pad_a":12,"pad_b":28,"uv_channels_min_and_extents":32,"uv_channels_min_and_extents[]":16},"view":{"$size":784,"clip_from_view":320,"clip_from_world":0,"color_grading":608,"color_grading.balance":0,"color_grading.contrast":64,"color_grading.exposure":136,"color_grading.gain":96,"color_grading.gamma":80,"color_grading.hue":140,"color_grading.lift":112,"color_grading.midtone_range":128,"color_grading.post_saturation":144,"color_grading.saturation":48,"exposure":460,"frame_count":772,"frustum":496,"frustum[]":16,"lod_view_world_position":592,"main_pass_viewport":480,"mip_bias":768,"unjittered_clip_from_world":64,"view_from_clip":384,"view_from_world":256,"viewport":464,"world_from_clip":128,"world_from_view":192,"world_position":448}};
|
||||
@@ -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,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();
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -1,65 +0,0 @@
|
||||
// Bevy's tone mapping in the playable (docs/playables.feature PA10): the 3D drawn into a half-float target with no
|
||||
// tone curve, then one full-screen pass maps it through TonyMcMapface (Bevy's default, tools/tony.ts's table) and
|
||||
// encodes sRGB, as bevy_core_pipeline's tonemapping.wesl does. Where nothing was drawn it stays transparent, so the
|
||||
// page's background shows through as it does under the native engine's 3D.
|
||||
import * as THREE from "three";
|
||||
import tony from "./tony.bin";
|
||||
|
||||
const N = Math.round(Math.cbrt(tony.length / 3));
|
||||
|
||||
const FRAG = /* glsl */ `
|
||||
precision highp float;
|
||||
precision highp sampler3D;
|
||||
uniform sampler2D scene;
|
||||
uniform sampler3D lut;
|
||||
in vec2 vUv;
|
||||
out vec4 color;
|
||||
void main() {
|
||||
vec4 c = texture(scene, vUv);
|
||||
vec3 x = max(c.rgb / max(c.a, 1e-5), vec3(0.0));
|
||||
vec3 uv = (x / (x + 1.0)) * (${N - 1}.0 / ${N}.0) + 0.5 / ${N}.0;
|
||||
// the table holds sRGB-encoded bytes, already the screen's values
|
||||
color = vec4(texture(lut, clamp(uv, 0.0, 1.0)).rgb * c.a, c.a);
|
||||
}`;
|
||||
|
||||
const VERT = /* glsl */ `
|
||||
in vec3 position;
|
||||
in vec2 uv;
|
||||
out vec2 vUv;
|
||||
void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
|
||||
|
||||
export class Tonemap {
|
||||
private target: THREE.WebGLRenderTarget;
|
||||
private quad: THREE.Mesh;
|
||||
private camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
|
||||
|
||||
constructor(private renderer: THREE.WebGLRenderer) {
|
||||
renderer.toneMapping = THREE.NoToneMapping;
|
||||
renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
|
||||
this.target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4, colorSpace: THREE.LinearSRGBColorSpace });
|
||||
const rgba = new Uint8Array(N * N * N * 4);
|
||||
for (let i = 0; i < N * N * N; i++) rgba.set([tony[i * 3], tony[i * 3 + 1], tony[i * 3 + 2], 255], i * 4);
|
||||
const lut = new THREE.Data3DTexture(rgba, N, N, N);
|
||||
lut.minFilter = lut.magFilter = THREE.LinearFilter;
|
||||
lut.unpackAlignment = 1;
|
||||
lut.needsUpdate = true;
|
||||
const material = new THREE.RawShaderMaterial({ glslVersion: THREE.GLSL3, vertexShader: VERT, fragmentShader: FRAG, uniforms: { scene: { value: this.target.texture }, lut: { value: lut } }, transparent: true, premultipliedAlpha: true, blending: THREE.NoBlending, depthTest: false, depthWrite: false });
|
||||
this.quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material);
|
||||
}
|
||||
|
||||
/** The target sized to the canvas's drawing buffer */
|
||||
resize() {
|
||||
const s = this.renderer.getDrawingBufferSize(new THREE.Vector2());
|
||||
this.target.setSize(s.x, s.y);
|
||||
}
|
||||
|
||||
render(scene: THREE.Scene, camera: THREE.Camera) {
|
||||
const r = this.renderer;
|
||||
r.setRenderTarget(this.target);
|
||||
r.setClearColor(0x000000, 0);
|
||||
r.clear();
|
||||
r.render(scene, camera);
|
||||
r.setRenderTarget(null);
|
||||
r.render(this.quad, this.camera);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Bevy's TonyMcMapface tone-mapping table for the playable host (docs/playables.feature PA10): bevy_core_pipeline's
|
||||
// tony_mc_mapface.ktx2 (48³, E5B9G9R9 floats, zstd; MIT, Tomasz Stachowiak) resampled to N³ and stored as sRGB-encoded
|
||||
// RGB bytes, which host/tonemap.ts samples as Bevy's tonemapping.wesl does.
|
||||
// RGB bytes, which host/bevy.ts's tone pass samples as Bevy's tonemapping.wesl does.
|
||||
// `bun tools/tony.ts N OUT.bin` (N = 48 keeps Bevy's own size).
|
||||
import { readdirSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
|
||||
@@ -16,6 +16,18 @@ export const GEOMETRY: Record<string, (a: number[]) => THREE.BufferGeometry> = {
|
||||
Ring: (a) => new THREE.RingGeometry(a[0] ?? 0.5, a[1] ?? 1, 48),
|
||||
};
|
||||
|
||||
/** A Plane3d's one face (its Mesh's data-shape "plane(nx, ny, nz, w, h)"), as Bevy's PlaneMeshBuilder makes it: the +Y
|
||||
* plane, w along x and h along -z, turned to its normal by the shortest arc. Its Box child (a box with no depth, for
|
||||
* three's sake) would face both ways, and three's BoxGeometry points a flat side's normal down */
|
||||
export function planeOf(kind: string, el: Element): THREE.BufferGeometry | undefined {
|
||||
const m = kind === "Box" ? /^plane\(([^)]*)\)$/.exec(el.parentElement?.getAttribute("data-shape") ?? "") : null;
|
||||
if (!m) return undefined;
|
||||
const [nx, ny, nz, w, h] = m[1].split(",").map(Number);
|
||||
const g = new THREE.PlaneGeometry(w, h).rotateX(-Math.PI / 2);
|
||||
const n = new THREE.Vector3(nx, ny, nz).normalize();
|
||||
return g.applyQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), n));
|
||||
}
|
||||
|
||||
interface BufferSpec {
|
||||
positions: number[];
|
||||
indices?: number[];
|
||||
|
||||
@@ -8,7 +8,7 @@ import { HDRLoader } from "three/examples/jsm/loaders/HDRLoader.js";
|
||||
import type { Sky } from "three/examples/jsm/objects/Sky.js";
|
||||
import { paintLook, paintTone } from "./paint";
|
||||
import { fire, flat, grass, placeFlat, plateTexture, richText, screenCard, sky, splatPoints } from "./extras";
|
||||
import { GEOMETRY, geometryOfShape, shapesReady } from "./geometry";
|
||||
import { GEOMETRY, geometryOfShape, planeOf, shapesReady } from "./geometry";
|
||||
import { KINDS, PRIMITIVES } from "./kinds";
|
||||
import { TONE, fitCamera, makeLight, setCamera, setLight, vec } from "./lights";
|
||||
import { MATERIAL, paint, texture, vertexColoured } from "./materials";
|
||||
@@ -390,7 +390,7 @@ export class Scene3d {
|
||||
const mesh = owner?.obj instanceof THREE.Mesh ? owner.obj : undefined;
|
||||
if (mesh) {
|
||||
k.geometry?.dispose();
|
||||
k.geometry = GEOMETRY[kind](Array.isArray(p.args) ? (p.args as number[]) : []);
|
||||
k.geometry = planeOf(kind, el) ?? GEOMETRY[kind](Array.isArray(p.args) ? (p.args as number[]) : []);
|
||||
mesh.geometry = k.geometry;
|
||||
}
|
||||
return k;
|
||||
|
||||
@@ -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));
|
||||
+26794
-614
File diff suppressed because it is too large.
Load diff
@@ -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";
|
||||
+1
-1
Submodule skills updated: a2481c23ef...fb72c5e256.
Generated
+2221
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "bevy-glsl"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "Bevy's PBR programs for a playable (docs/playables.feature PA11): composed by Bevy's own ShaderCache with WebGL2's defs, translated to GLSL ES 3.00 by naga, with each uniform block's layout"
|
||||
|
||||
# its own workspace: run on demand (sdk/playable/bevy/build.sh), not part of raea's build
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
bevy_shader = "=0.20.0"
|
||||
bevy_asset = "=0.20.0"
|
||||
naga = { version = "=30.0.1", features = ["wgsl-in", "glsl-out"] }
|
||||
serde_json = "1"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
@@ -0,0 +1,283 @@
|
||||
//! Bevy's PBR programs for a playable (docs/playables.feature PA11). Bevy's own ShaderCache composes them, from Bevy's
|
||||
//! shader files (raea's vendored bevy_pbr, and bevy_render and bevy_core_pipeline at the version raea builds), with the
|
||||
//! defs Bevy's mesh and prepass pipelines give a WebGL2 device; naga translates each entry point to GLSL ES 3.00 for
|
||||
//! WebGL. Beside the sources, bevy.json says for each program which uniform block and sampler is which binding and
|
||||
//! lays out each block's struct (offsets, sizes, strides), so the host fills them as Bevy's render world does.
|
||||
//!
|
||||
//! cargo run --release --manifest-path tools/bevy-glsl/Cargo.toml -- RAEA_ROOT OUT_DIR
|
||||
|
||||
use bevy_asset::AssetId;
|
||||
use bevy_shader::{Shader, ShaderCache, ShaderCacheError, ShaderCacheSource, ShaderDefVal, ValidateShader};
|
||||
use naga::back::glsl;
|
||||
use naga::proc::{BoundsCheckPolicies, Layouter};
|
||||
use naga::{AddressSpace, ShaderStage, TypeInner};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn keep(_: &(), source: ShaderCacheSource, _: &ValidateShader) -> Result<String, ShaderCacheError> {
|
||||
match source {
|
||||
ShaderCacheSource::Wgsl(s) => Ok(s),
|
||||
ShaderCacheSource::SpirV(_) => panic!("a SPIR-V shader in the pbr program"),
|
||||
}
|
||||
}
|
||||
|
||||
fn def(name: &str) -> ShaderDefVal {
|
||||
ShaderDefVal::Bool(name.to_string().into(), true)
|
||||
}
|
||||
fn uint(name: &str, v: u32) -> ShaderDefVal {
|
||||
ShaderDefVal::UInt(name.to_string().into(), v)
|
||||
}
|
||||
|
||||
/// WebGL2's limits as Bevy reads them (render/light.rs under `webgl`, gpu_array_buffer.rs's batch size: a 16 KB
|
||||
/// uniform binding over the 176-byte MeshUniform)
|
||||
fn per_file_defs(path: &str) -> Vec<ShaderDefVal> {
|
||||
match path {
|
||||
"bevy_pbr/render/mesh_view_types.wesl" => vec![uint("MAX_DIRECTIONAL_LIGHTS", 10), uint("MAX_CASCADES_PER_LIGHT", 1), uint("MAX_RECT_LIGHTS", 8)],
|
||||
"bevy_pbr/render/mesh_bindings.wesl" => vec![uint("PER_OBJECT_BUFFER_BATCH_SIZE", 93)],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// What every program on a WebGL2 device gets (mesh.rs specialize, view and device parts)
|
||||
fn webgl_defs() -> Vec<ShaderDefVal> {
|
||||
vec![
|
||||
def("WEBGL2"),
|
||||
def("NO_ARRAY_TEXTURES_SUPPORT"),
|
||||
def("NO_CUBE_ARRAY_TEXTURES_SUPPORT"),
|
||||
def("SIXTEEN_BYTE_ALIGNMENT"),
|
||||
uint("AVAILABLE_STORAGE_BUFFER_BINDINGS", 0),
|
||||
uint("MAX_DIRECTIONAL_LIGHTS", 10),
|
||||
uint("MAX_CASCADES_PER_LIGHT", 1),
|
||||
uint("PER_OBJECT_BUFFER_BATCH_SIZE", 93),
|
||||
def("MESH_PIPELINE"),
|
||||
def("VERTEX_OUTPUT_INSTANCE_INDEX"),
|
||||
def("VERTEX_POSITIONS"),
|
||||
def("VERTEX_NORMALS"),
|
||||
def("VERTEX_UVS"),
|
||||
def("VERTEX_UVS_A"),
|
||||
def("METADATA_USE_UNIFORM_BUFFERS"),
|
||||
// no VIEW_PROJECTION_PERSPECTIVE: the shader reads the projection's kind from the view, so an orthographic
|
||||
// camera shades as it does natively
|
||||
// material.rs: the material's bind group
|
||||
uint("MATERIAL_BIND_GROUP", 3),
|
||||
]
|
||||
}
|
||||
|
||||
/// The forward pass of a lit StandardMaterial mesh into an HDR target: Bevy tone-maps after it (the host's tone pass,
|
||||
/// with Bevy's TonyMcMapface table), as it does natively with an HDR camera. Distance fog is in, off (its mode 0) where
|
||||
/// the scene has none
|
||||
fn forward_defs() -> Vec<ShaderDefVal> {
|
||||
let mut d = webgl_defs();
|
||||
d.extend([
|
||||
def("MULTISAMPLED"),
|
||||
def("SHADOW_FILTER_METHOD_GAUSSIAN"),
|
||||
def("DISTANCE_FOG"),
|
||||
ShaderDefVal::Int("SCREEN_SPACE_SPECULAR_TRANSMISSION_BLUR_TAPS".into(), 4),
|
||||
uint("RENDER_PHASE_TYPE", 1),
|
||||
]);
|
||||
d
|
||||
}
|
||||
|
||||
/// A directional light's shadow pass (prepass/mod.rs for a shadow view: depth only, positions, and on WebGL2 the
|
||||
/// orthographic depth clamp emulated, as it has no unclipped depth)
|
||||
fn shadow_defs() -> Vec<ShaderDefVal> {
|
||||
let mut d = webgl_defs();
|
||||
d.retain(|v| !matches!(v, ShaderDefVal::Bool(n, _) if n == "VERTEX_NORMALS" || n == "VERTEX_UVS" || n == "VERTEX_UVS_A" || n == "VIEW_PROJECTION_PERSPECTIVE"));
|
||||
d.extend([def("PREPASS_PIPELINE"), def("DEPTH_PREPASS"), def("UNCLIPPED_DEPTH_ORTHO_EMULATION"), def("VIEW_PROJECTION_ORTHOGRAPHIC")]);
|
||||
d
|
||||
}
|
||||
|
||||
fn files(root: &Path, under: &Path, out: &mut Vec<(String, PathBuf)>) {
|
||||
let Ok(rd) = std::fs::read_dir(under) else { return };
|
||||
for e in rd.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
files(root, &p, out);
|
||||
} else if p.extension().is_some_and(|x| x == "wesl" || x == "wgsl") {
|
||||
out.push((p.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"), p));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A type's layout in a uniform block, as naga lays it out (WGSL's uniform rules, std140's)
|
||||
fn layout(m: &naga::Module, l: &Layouter, ty: naga::Handle<naga::Type>) -> Value {
|
||||
let t = &m.types[ty];
|
||||
let size = l[ty].size;
|
||||
let scalar = |s: naga::Scalar| match s.kind {
|
||||
naga::ScalarKind::Float => "f32",
|
||||
naga::ScalarKind::Uint => "u32",
|
||||
naga::ScalarKind::Sint => "i32",
|
||||
naga::ScalarKind::Bool => "bool",
|
||||
_ => "?",
|
||||
};
|
||||
match &t.inner {
|
||||
TypeInner::Scalar(s) => json!({ "k": scalar(*s), "size": size }),
|
||||
TypeInner::Atomic(s) => json!({ "k": scalar(*s), "size": size }),
|
||||
TypeInner::Vector { size: n, scalar: s } => json!({ "k": "vec", "n": *n as u32, "s": scalar(*s), "size": size }),
|
||||
TypeInner::Matrix { columns, rows, .. } => {
|
||||
let col = if *rows as u32 == 2 { 8 } else { 16 };
|
||||
json!({ "k": "mat", "c": *columns as u32, "r": *rows as u32, "stride": col, "size": size })
|
||||
}
|
||||
TypeInner::Array { base, size: n, stride } => {
|
||||
let count = match n {
|
||||
naga::ArraySize::Constant(c) => c.get(),
|
||||
_ => 0,
|
||||
};
|
||||
json!({ "k": "array", "of": layout(m, l, *base), "count": count, "stride": stride, "size": size })
|
||||
}
|
||||
TypeInner::Struct { members, span } => {
|
||||
let fields: Vec<Value> = members
|
||||
.iter()
|
||||
.map(|f| json!({ "name": f.name.clone().unwrap_or_default(), "offset": f.offset, "type": layout(m, l, f.ty) }))
|
||||
.collect();
|
||||
json!({ "k": "struct", "name": t.name.clone().unwrap_or_default(), "fields": fields, "size": span })
|
||||
}
|
||||
other => json!({ "k": format!("{other:?}").split([' ', '{', '(']).next().unwrap_or("?"), "size": size }),
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry point in GLSL ES 3.00 for WebGL, and what its names bind to
|
||||
fn translate(wgsl: &str, stage: ShaderStage, entry: &str) -> Result<(String, Value), String> {
|
||||
let module = naga::front::wgsl::parse_str(wgsl).map_err(|e| e.emit_to_string(wgsl))?;
|
||||
let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all())
|
||||
.validate(&module)
|
||||
.map_err(|e| e.emit_to_string(wgsl))?;
|
||||
let options = glsl::Options {
|
||||
version: glsl::Version::Embedded { version: 300, is_webgl: true },
|
||||
writer_flags: glsl::WriterFlags::ADJUST_COORDINATE_SPACE | glsl::WriterFlags::FORCE_POINT_SIZE,
|
||||
binding_map: Default::default(),
|
||||
zero_initialize_workgroup_memory: false,
|
||||
};
|
||||
let pipeline = glsl::PipelineOptions { shader_stage: stage, entry_point: entry.to_string(), multiview: None };
|
||||
let mut out = String::new();
|
||||
let mut w = glsl::Writer::new(&mut out, &module, &info, &options, &pipeline, BoundsCheckPolicies::default()).map_err(|e| format!("{e:?}"))?;
|
||||
let reflection = w.write().map_err(|e| format!("{e:?}"))?;
|
||||
let mut lay = Layouter::default();
|
||||
lay.update(module.to_ctx()).map_err(|e| format!("{e:?}"))?;
|
||||
let mut uniforms = Map::new();
|
||||
for (h, name) in &reflection.uniforms {
|
||||
let g = &module.global_variables[*h];
|
||||
let b = g.binding.as_ref().map(|b| json!({ "group": b.group, "binding": b.binding })).unwrap_or(Value::Null);
|
||||
let kind = match g.space {
|
||||
AddressSpace::Uniform => "uniform",
|
||||
AddressSpace::Storage { .. } => "storage",
|
||||
_ => "other",
|
||||
};
|
||||
uniforms.insert(name.clone(), json!({ "var": g.name, "space": kind, "at": b, "type": layout(&module, &lay, g.ty) }));
|
||||
}
|
||||
let mut textures = Map::new();
|
||||
for (name, m) in &reflection.texture_mapping {
|
||||
let t = &module.global_variables[m.texture];
|
||||
let s = m.sampler.map(|s| &module.global_variables[s]);
|
||||
let at = |g: &naga::GlobalVariable| g.binding.as_ref().map(|b| json!({ "group": b.group, "binding": b.binding }));
|
||||
textures.insert(name.clone(), json!({ "texture": t.name, "at": at(t), "sampler": s.map(|s| s.name.clone()), "sampler_at": s.and_then(at), "kind": format!("{:?}", module.types[t.ty].inner).split([' ', '{', '(']).next().unwrap_or("?").to_string(), "dim": dim(&module.types[t.ty].inner) }));
|
||||
}
|
||||
let varyings: Vec<String> = reflection.varying.keys().cloned().collect();
|
||||
Ok((out, json!({ "uniforms": uniforms, "textures": textures, "varyings": varyings })))
|
||||
}
|
||||
|
||||
/// A binding's name as Bevy's files give it (`..._bindings__1clustered_lights` -> clustered_lights)
|
||||
fn short(var: &str) -> String {
|
||||
var.rsplit("bindings_").next().unwrap_or(var).trim_start_matches('_').trim_start_matches(|c: char| c.is_ascii_digit()).to_string()
|
||||
}
|
||||
|
||||
/// A block's fields at their offsets by dotted path, each from its own struct's start; an array's stride as `path[]`
|
||||
fn flatten(t: &Value, prefix: &str, out: &mut Map<String, Value>) {
|
||||
match t["k"].as_str() {
|
||||
Some("struct") => {
|
||||
for f in t["fields"].as_array().into_iter().flatten() {
|
||||
let name = f["name"].as_str().unwrap_or_default();
|
||||
let path = if prefix.is_empty() { name.to_string() } else { format!("{prefix}.{name}") };
|
||||
out.insert(path.clone(), f["offset"].clone());
|
||||
flatten(&f["type"], &path, out);
|
||||
}
|
||||
}
|
||||
Some("array") => {
|
||||
out.insert(format!("{prefix}[]"), t["stride"].clone());
|
||||
flatten(&t["of"], prefix, out);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn dim(t: &TypeInner) -> Value {
|
||||
match t {
|
||||
TypeInner::Image { dim, arrayed, class } => json!({ "dim": format!("{dim:?}"), "arrayed": arrayed, "class": format!("{class:?}") }),
|
||||
_ => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<(), String> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let (Some(root), Some(out)) = (args.get(1), args.get(2)) else {
|
||||
return Err("usage: bevy-glsl RAEA_ROOT OUT_DIR".into());
|
||||
};
|
||||
let root = PathBuf::from(root);
|
||||
let reg = std::env::var("CARGO_HOME").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".cargo"));
|
||||
let registry = std::fs::read_dir(reg.join("registry/src"))
|
||||
.map_err(|e| format!("cargo's registry: {e}"))?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.find(|p| p.join("bevy_render-0.20.0").is_dir())
|
||||
.ok_or("bevy_render 0.20.0 isn't in cargo's registry: build raea first")?;
|
||||
let crates: Vec<(&str, PathBuf)> = vec![
|
||||
("bevy_pbr", root.join("vendor/bevy_pbr/src")),
|
||||
("bevy_render", registry.join("bevy_render-0.20.0/src")),
|
||||
("bevy_core_pipeline", registry.join("bevy_core_pipeline-0.20.0/src")),
|
||||
];
|
||||
let mut cache: ShaderCache<String, ()> = ShaderCache::new((), keep);
|
||||
let mut ids: BTreeMap<String, AssetId<Shader>> = BTreeMap::new();
|
||||
for (name, src) in &crates {
|
||||
let mut fs = Vec::new();
|
||||
files(src, src, &mut fs);
|
||||
for (rel, p) in fs {
|
||||
let path = format!("{name}/{rel}");
|
||||
let text = std::fs::read_to_string(&p).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
let mut shader = if rel.ends_with(".wesl") { Shader::from_wesl(text, format!("embedded://{path}")) } else { Shader::from_wgsl(text, format!("embedded://{path}")) };
|
||||
shader.shader_defs = per_file_defs(&path);
|
||||
let id = AssetId::Uuid { uuid: uuid::Uuid::new_v4() };
|
||||
cache.set_shader(id, shader);
|
||||
ids.insert(path, id);
|
||||
}
|
||||
}
|
||||
let id = |p: &str| ids.get(p).copied().ok_or(format!("{p} isn't among Bevy's shaders"));
|
||||
let out = PathBuf::from(out);
|
||||
std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
|
||||
let programs: [(&str, &str, ShaderStage, &str, Vec<ShaderDefVal>); 3] = [
|
||||
("pbr.vert", "bevy_pbr/render/mesh.wesl", ShaderStage::Vertex, "vertex", forward_defs()),
|
||||
("pbr.frag", "bevy_pbr/render/pbr.wesl", ShaderStage::Fragment, "fragment", forward_defs()),
|
||||
("shadow.vert", "bevy_pbr/prepass/prepass.wesl", ShaderStage::Vertex, "vertex", shadow_defs()),
|
||||
];
|
||||
let mut meta = Map::new();
|
||||
let mut ts = String::from("// Bevy's PBR programs for a playable, as tools/bevy-glsl makes them (docs/playables.feature PA11): generated by\n// sdk/playable/bevy/build.sh, not edited. Each program's GLSL ES 3.00; which of Bevy's bindings each uniform block\n// and sampler is; each binding's fields at their byte offsets (nested fields from their struct's start, an array's\n// stride under `name[]`).\n");
|
||||
let (mut blocks, mut samplers, mut layouts) = (Map::new(), Map::new(), Map::new());
|
||||
for (name, file, stage, entry, defs) in programs {
|
||||
let wgsl = cache.get(0, id(file)?, &defs).map_err(|e| format!("{file}: {e}"))?;
|
||||
std::fs::write(out.join(format!("{name}.wgsl")), wgsl.as_str()).map_err(|e| e.to_string())?;
|
||||
let (glsl, info) = translate(&wgsl, stage, entry).map_err(|e| format!("{file} ({name}): {e}"))?;
|
||||
std::fs::write(out.join(format!("{name}.glsl")), &glsl).map_err(|e| e.to_string())?;
|
||||
eprintln!("{name}: {} lines, {} bytes", glsl.lines().count(), glsl.len());
|
||||
// leading spaces and blank lines carry nothing in GLSL
|
||||
let tight: String = glsl.lines().map(str::trim_start).filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n");
|
||||
ts.push_str(&format!("export const {} = {};\n", name.replace('.', "_").to_uppercase(), Value::from(tight)));
|
||||
for (block, u) in info["uniforms"].as_object().into_iter().flatten() {
|
||||
let short = short(u["var"].as_str().unwrap_or_default());
|
||||
blocks.insert(block.clone(), Value::from(short.clone()));
|
||||
let mut flat = Map::new();
|
||||
flat.insert("$size".into(), u["type"]["size"].clone());
|
||||
flatten(&u["type"], "", &mut flat);
|
||||
layouts.insert(short, Value::Object(flat));
|
||||
}
|
||||
for (sampler, t) in info["textures"].as_object().into_iter().flatten() {
|
||||
samplers.insert(sampler.clone(), Value::from(short(t["texture"].as_str().unwrap_or_default())));
|
||||
}
|
||||
meta.insert(name.into(), info);
|
||||
}
|
||||
ts.push_str(&format!("export const BLOCKS: Record<string, string> = {};\n", Value::Object(blocks)));
|
||||
ts.push_str(&format!("export const SAMPLERS: Record<string, string> = {};\n", Value::Object(samplers)));
|
||||
ts.push_str(&format!("export const LAYOUT: Record<string, Record<string, number>> = {};\n", Value::Object(layouts)));
|
||||
std::fs::write(out.join("programs.ts"), ts).map_err(|e| e.to_string())?;
|
||||
std::fs::write(out.join("bevy.json"), serde_json::to_string_pretty(&Value::Object(meta)).unwrap()).map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -274,6 +274,7 @@ rtools = "tools"
|
||||
skillcheck = "tools"
|
||||
seetool = "tools"
|
||||
raea-hands-audit = "tools"
|
||||
bevy-glsl = "tools" # Bevy's PBR shaders as WebGL2 GLSL for a playable's light host (docs/playables.feature PA11)
|
||||
|
||||
# systems that hold only a facility another system may build on (docs/overhaul.md: the mixer graph, ONNX sessions,
|
||||
# Vision requests, K kernels on the GPU)
|
||||
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
# The component library's catalog, given what an agent picks a component by (tools/library-meta/enrich.ts): each item
|
||||
# matched by content to the upstream component it came from, with what it draws, when to use it and when not, the
|
||||
# phrases people ask for it with, its props, and the length and size it was designed at. `raea make component list
|
||||
# WORDS` searches these and `raea make component show NAME` prints them.
|
||||
# tools/library-meta.sh [UPSTREAM] UPSTREAM holds a checkout of each source catalog.json names, in a folder named as
|
||||
# the catalog names it (remocn, snapcn, rve-templates); with none given they're
|
||||
# cloned (shallow) from the catalog's urls into a scratch folder, removed after
|
||||
# REPORT=1 tools/library-meta.sh also lists the upstream components the library didn't take
|
||||
# Run it after adding to the library or after upstream's docs change, then read the diff: hand.json beside enrich.ts
|
||||
# holds the words written by hand (snapcn's and React Video Editor's components have no when-to-use docs upstream).
|
||||
set -euo pipefail
|
||||
ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
||||
cat=$ROOT/sdk/raea/library/components/catalog.json
|
||||
up=${1:-}
|
||||
if [ -z "$up" ]; then
|
||||
up=$(mktemp -d "${TMPDIR:-/tmp}/library-meta.XXXXXX")
|
||||
trap 'rm -rf "$up"' EXIT
|
||||
jq -r '.sources | to_entries[] | "\(.key) \(.value.url)"' "$cat" | while read -r key url; do
|
||||
GIT_LFS_SKIP_SMUDGE=1 git clone -q --depth 1 "$url.git" "$up/$key"
|
||||
done
|
||||
fi
|
||||
for d in $(jq -r '.sources | keys[]' "$cat"); do [ -d "$up/$d" ] || { echo "library-meta: no $up/$d" >&2; exit 2; }; done
|
||||
bun "$ROOT/tools/library-meta/enrich.ts" "$up" ${REPORT:+--report}
|
||||
@@ -0,0 +1,129 @@
|
||||
// The component library's catalog (sdk/raea/library/components/catalog.json), given what an agent picks a component
|
||||
// by: each item matched by content to the upstream component it was taken from (its name there kept as `upstream`, a
|
||||
// search alias, never its name here), then what it draws and how it moves, when to use it and when not, the phrases
|
||||
// people ask for it with, its props (name, type, default, one line) read from its own source, and the length, frame
|
||||
// rate, size and feel it was designed at. Hand-written words in hand.json beside this win over upstream's.
|
||||
//
|
||||
// bun tools/library-meta/enrich.ts UPSTREAM [--report] UPSTREAM holds checkouts of remocn, snapcn, rve-templates
|
||||
// (tools/library-meta.sh clones them and runs this). Run again after the library changes: it only rewrites these fields.
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { type Prop, readProps } from "./props";
|
||||
import { documented, similarity, tokens, type Up, upstream } from "./upstream";
|
||||
import { phrases, relink, veil } from "./words";
|
||||
|
||||
type Hand = { what?: string; use_when?: string[]; avoid_when?: string[]; asked_as?: string[]; vibe?: string };
|
||||
type Item = Record<string, unknown> & { name: string; category: string; type: string; says: string; component: string; files: string[]; from: string };
|
||||
|
||||
const [up, ...flags] = process.argv.slice(2);
|
||||
if (!up) throw new Error("usage: bun tools/library-meta/enrich.ts UPSTREAM [--report]");
|
||||
const lib = join(import.meta.dir, "../../sdk/raea/library/components");
|
||||
const catPath = join(lib, "catalog.json");
|
||||
const cat = JSON.parse(readFileSync(catPath, "utf8")) as { sources: unknown; items: Item[] };
|
||||
const hand = JSON.parse(readFileSync(join(import.meta.dir, "hand.json"), "utf8")) as Record<string, Hand>;
|
||||
const ups = upstream(up);
|
||||
|
||||
// each item's upstream original: the same source's component whose identifiers and strings it shares most
|
||||
const match = new Map<string, { u: Up; score: number }>();
|
||||
for (const i of cat.items) {
|
||||
const t = tokens(i.files.map((f) => readFileSync(join(lib, f), "utf8")).join("\n"));
|
||||
let best: { u: Up; score: number } | undefined;
|
||||
for (const u of ups) if (u.source === i.from) {
|
||||
const score = similarity(t, u.tokens);
|
||||
if (!best || score > best.score) best = { u, score };
|
||||
}
|
||||
if (best && best.score >= 0.3) match.set(i.name, best);
|
||||
}
|
||||
const ours = new Map([...cat.items].flatMap((i) => (match.has(i.name) ? [[match.get(i.name)!.u.name, `${i.category}/${i.name}`] as const] : [])));
|
||||
const known = new Set([...ups.map((u) => u.name), ...documented(up).map((d) => d.name)]);
|
||||
|
||||
const sentences = (s: string) => s.split(/(?<=[.!?])\s+(?=[A-Z`"'(])/).filter(Boolean);
|
||||
// upstream's words in ours: names out, pointers at our names, markdown's emphasis and links as plain words
|
||||
const said = (s: string) => relink(veil(s.replace(/\*\*([^*]+)\*\*/g, "$1").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")), ours, known);
|
||||
const stop = (s: string) => (s && !/[.!?:]$/.test(s) ? `${s}.` : s);
|
||||
/** what it draws and how it moves: the first sentences that describe, not the ones that list props or themes */
|
||||
function what(i: Item, u?: Up): string {
|
||||
const pick = (s?: string) =>
|
||||
sentences(said(s ?? ""))
|
||||
.filter((x) => !/^(Pass|It ships|Ships|Install|Standalone|Use it|Import|Wrap|Set |Every |All )/.test(x) && !/`raea make component add`/.test(x))
|
||||
.slice(0, 2)
|
||||
.join(" ");
|
||||
if (i.from === "rve-templates") return [i.says.split(". ")[0].replace(/\.?$/, "."), u?.description && `(${u.description}.)`].filter(Boolean).join(" ") + " No props: its words and colours are written in the file.";
|
||||
// snapcn's description says what it draws and its Usage how it's built; remocn's Usage says how it moves
|
||||
const d = stop(pick(u?.description));
|
||||
let w = i.from === "snapcn" ? d : pick(u?.usage);
|
||||
if (!w || w.length < 100) w = [d, stop(pick(i.from === "snapcn" ? u?.usage : ""))].filter((x, k, a) => x && a.indexOf(x) === k).join(" ");
|
||||
if (!w) w = i.says;
|
||||
return w.length > 420 ? `${sentences(w)[0]}` : w;
|
||||
}
|
||||
|
||||
function props(i: Item, u?: Up): Prop[] {
|
||||
const file = i.files.find((f) => f.endsWith("/index.tsx")) ?? i.files.find((f) => f.endsWith(".tsx")) ?? i.files[0];
|
||||
const rows = new Map((u?.rows ?? []).map((r) => [r.name, r]));
|
||||
return readProps(readFileSync(join(lib, file), "utf8"), i.component).map((p) => {
|
||||
const r = rows.get(p.name);
|
||||
const says = p.says ?? (r?.description ? said(r.description) : undefined);
|
||||
const dflt = p.default ?? r?.default;
|
||||
return { name: p.name, type: p.type, ...(dflt !== undefined ? { default: dflt } : {}), ...(says ? { says: veil(says) } : {}), ...(p.required ? { required: true } : {}) };
|
||||
});
|
||||
}
|
||||
|
||||
const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a);
|
||||
const uniq = (xs: string[]) => {
|
||||
const seen = new Set<string>();
|
||||
return xs.filter((x) => x && !seen.has(x.toLowerCase()) && seen.add(x.toLowerCase()));
|
||||
};
|
||||
|
||||
const missing: string[] = [];
|
||||
cat.items = cat.items.map((i) => {
|
||||
const m = match.get(i.name);
|
||||
const u = m?.u;
|
||||
const h = hand[i.name] ?? {};
|
||||
const base: Item = { ...i };
|
||||
for (const k of ["upstream", "what", "use_when", "avoid_when", "asked_as", "props", "length", "fps", "size", "aspect", "vibe"]) delete base[k];
|
||||
const use = h.use_when ?? (u?.useWhen ?? []).map(said);
|
||||
const avoid = h.avoid_when ?? (u?.avoidWhen ?? []).map(said);
|
||||
if (!use.length) missing.push(`${i.category}/${i.name}`);
|
||||
const g = u?.width && u.height ? gcd(u.width, u.height) : 0;
|
||||
return {
|
||||
...base,
|
||||
...(u ? { upstream: u.name } : {}),
|
||||
what: h.what ?? what(i, u),
|
||||
use_when: use,
|
||||
avoid_when: avoid,
|
||||
asked_as: uniq([...(h.asked_as ?? []), ...(u?.askedAs ?? []).map(veil), ...phrases({ ...i, section: u?.section, upstream: u?.name })]),
|
||||
props: props(i, u),
|
||||
...(u?.frames ? { length: u.frames, fps: u.fps ?? 30 } : {}),
|
||||
...(g ? { size: `${u!.width}x${u!.height}`, aspect: `${u!.width! / g}:${u!.height! / g}` } : { aspect: "any: it fills the frame it's given" }),
|
||||
...((h.vibe ?? u?.vibe) ? { vibe: h.vibe ?? u?.vibe } : {}),
|
||||
};
|
||||
});
|
||||
// hand.json's names, and the components (or category/type) its words point at, must be the library's
|
||||
const names = new Set(cat.items.flatMap((i) => [`${i.category}/${i.name}`, `${i.category}/${i.type}`]));
|
||||
const bad = Object.entries(hand).flatMap(([n, h]) => [
|
||||
...(cat.items.some((i) => i.name === n) ? [] : [`hand.json: no item ${n}`]),
|
||||
...[...JSON.stringify(h).matchAll(/`([a-z]+\/[a-z0-9-]+)`/g)].filter(([, r]) => !names.has(r)).map(([, r]) => `hand.json ${n}: no item ${r}`),
|
||||
]);
|
||||
if (bad.length) throw new Error(bad.join("\n"));
|
||||
// one prop to a line, so the file reads (and diffs) by item
|
||||
const lines: string[] = [];
|
||||
const text = JSON.stringify(cat, (k, v) => (k === "props" && Array.isArray(v) ? v.map((p) => `\u0001${lines.push(JSON.stringify(p)) - 1}`) : v), 1);
|
||||
writeFileSync(catPath, `${text.replace(/"\\u0001(\d+)"/g, (_, n) => lines[Number(n)])}\n`);
|
||||
|
||||
const mapped = cat.items.filter((i) => i.upstream).length;
|
||||
console.log(`${cat.items.length} items enriched, ${mapped} matched to an upstream component (${cat.items.filter((i) => i.upstream && i.upstream !== i.name).length} under another name there)`);
|
||||
const unmatched = cat.items.filter((i) => !i.upstream).map((i) => `${i.category}/${i.name}`);
|
||||
if (unmatched.length) console.log(`no upstream match (check by hand): ${unmatched.join(", ")}`);
|
||||
if (missing.length) console.log(`no use_when (add it to hand.json): ${missing.length}: ${missing.join(", ")}`);
|
||||
if (flags.includes("--report")) {
|
||||
// upstream components the library didn't take, by docs section
|
||||
const took = new Set(cat.items.filter((i) => i.upstream).map((i) => `${i.from}/${i.upstream}`));
|
||||
const left = new Map<string, string[]>();
|
||||
const regs = new Set(ups.map((u) => `${u.source}/${u.name}`));
|
||||
for (const d of documented(up))
|
||||
if (regs.has(`${d.source}/${d.name}`) && !took.has(`${d.source}/${d.name}`)) left.set(`${d.source} ${d.section}`, [...(left.get(`${d.source} ${d.section}`) ?? []), d.name]);
|
||||
for (const u of ups) if (u.source !== "rve-templates" && !u.section && !took.has(`${u.source}/${u.name}`)) left.set(`${u.source} (no docs page)`, [...(left.get(`${u.source} (no docs page)`) ?? []), u.name]);
|
||||
for (const u of ups) if (u.source === "rve-templates" && !took.has(`${u.source}/${u.name}`)) left.set("rve-templates", [...(left.get("rve-templates") ?? []), u.name]);
|
||||
console.log("\nnot vendored:");
|
||||
for (const [k, v] of [...left].sort()) console.log(`${k} (${v.length}): ${v.sort().join(", ")}`);
|
||||
}
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user