Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

raea e2d2dd2c0

shinyobjectzad673617623f
diff --git a/apps/targets/src/config.rs b/apps/targets/src/config.rs
index 85c301ef..2a957702 100644
--- a/apps/targets/src/config.rs
+++ b/apps/targets/src/config.rs
@@ -65,7 +65,7 @@ pub fn parse(src: &str) -> Result<AppConfig, Error> {
if let Some(at) = other_export(&bare) {
return Err(Error::at(src, at, "`app` is exported, but not as `export const app = { ... }` (a literal the CLI can read)"));
}
- let Some(start) = find_export(&bare) else { return Ok(c) };
+ let Some(start) = find_export(&bare, "app") else { return Ok(c) };
c.declared = true;
let (value, _) = literal::value(src, &code, start)?;
let Value::Object(o) = value else { return Err(Error::at(src, start, "`app` must be an object literal")) };
@@ -99,8 +99,8 @@ fn pair(src: &str, at: usize, key: &str, v: &Value) -> Result<(f32, f32), Error>
Ok((w as f32, h as f32))
}
-/// Where `export const app` starts its value: past `=`, its type annotation skipped.
-fn find_export(code: &str) -> Option<usize> {
+/// Where `export const NAME` starts its value: past `=`, its type annotation skipped.
+fn find_export(code: &str, name: &str) -> Option<usize> {
let mut from = 0;
while let Some(i) = code[from..].find("export") {
let at = from + i;
@@ -108,7 +108,7 @@ fn find_export(code: &str) -> Option<usize> {
let t = rest.trim_start();
if let Some(r) = t.strip_prefix("const")
&& r.starts_with(char::is_whitespace)
- && let Some(r) = r.trim_start().strip_prefix("app")
+ && let Some(r) = r.trim_start().strip_prefix(name)
&& !r.starts_with(|ch: char| ch.is_alphanumeric() || ch == '_' || ch == '$')
{
let off = code.len() - r.len();
@@ -143,3 +143,15 @@ fn other_export(code: &str) -> Option<usize> {
}
None
}
+
+/// The steps an app file exports (`export const steps = [...]`, a literal as `app` is) as a check's script JSON, or
+/// None when it exports none: `raea app check` plays them when no `--script` is given, so an example's steps travel
+/// with it (docs/targets.feature T5a)
+pub fn steps(src: &str) -> Result<Option<String>, Error> {
+ let code = literal::blank_comments(src);
+ let Some(start) = find_export(&literal::blank_strings(&code), "steps") else { return Ok(None) };
+ match literal::value(src, &code, start)?.0 {
+ v @ Value::Array(_) => Ok(Some(v.to_string())),
+ _ => Err(Error::at(src, start, "`steps` must be an array literal of the check's steps")),
+ }
+}
diff --git a/apps/targets/src/portable.rs b/apps/targets/src/portable.rs
index 73af9ac6..2779f4fc 100644
--- a/apps/targets/src/portable.rs
+++ b/apps/targets/src/portable.rs
@@ -39,3 +39,20 @@ pub fn note(lines: &[String]) -> String {
}
format!("native wouldn't draw or answer {} thing{} (the web check still passes):\n {}", lines.len(), if lines.len() == 1 { "" } else { "s" }, lines.join("\n "))
}
+
+/// The Rune props a web app has that the web target ignores (T4b): @raea/rune names them on each element in
+/// `data-rune-web-ignored`, and the native host's run lists them by path in web-ignored.json.
+pub fn web_ignored(dir: &Path) -> Result<Vec<String>, String> {
+ let p = dir.join("web-ignored.json");
+ let text = std::fs::read_to_string(&p).map_err(|e| format!("{}: {e}", p.display()))?;
+ let v: Vec<Value> = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", p.display()))?;
+ Ok(v.iter().map(|w| format!("ignored on web: {} at {}", w["ignored"].as_str().unwrap_or(""), w["path"].as_str().unwrap_or(""))).collect())
+}
+
+/// A web app's Rune props the web ignores, said; empty when there are none.
+pub fn web_note(lines: &[String]) -> String {
+ if lines.is_empty() {
+ return String::new();
+ }
+ format!("Rune props the web target doesn't draw (@raea/rune has no CSS for them):\n {}", lines.join("\n "))
+}
diff --git a/apps/targets/src/verbs.rs b/apps/targets/src/verbs.rs
index b515836e..f624c75b 100644
--- a/apps/targets/src/verbs.rs
+++ b/apps/targets/src/verbs.rs
@@ -2,9 +2,10 @@
//! targets, the target read from the app's own `export const app` (T0a) unless `--target` says otherwise.
//!
//! run a window of its own: Blitz on Bevy for web (raea-page-host's window build), Rune for native
-//! check headless (R4b): the mount and each step of `--script` written as PNGs to `--png DIR`, with tree.json (each
-//! frame's elements by data-testid), and the portability report (portable.rs, T4a): on native it fails on any
-//! unmapped prop or unanswered call, naming each; on web it says what native wouldn't draw
+//! check headless (R4b): the mount and each step of `--script` (or the app's own `export const steps`, T5a) written as
+//! PNGs to `--png DIR`, with tree.json (each frame's elements by data-testid), and the portability report
+//! (portable.rs, T4a): on native it fails on any unmapped prop or unanswered call, naming each; on web it
+//! says what native wouldn't draw
//! bundle a Mac app, `-o App.app` (the file's name when left out)
//!
//! `raea rune ARGS` is `raea app ARGS --target native`, and its older spellings (`rune --headless APP`) still reach
@@ -106,10 +107,22 @@ pub fn parse(args: &[String], forced: Option<Target>) -> Result<Ask, String> {
if (identity.is_some() || notarize.is_some()) && verb != Verb::Bundle {
return Err("--identity and --notarize sign a Mac app: they're `raea app bundle`'s".into());
}
+ if verb == Verb::Check && script.is_none() {
+ script = exported_steps(&app)?;
+ }
let sign = crate::sign::Signing::new(identity, notarize);
Ok(Ask { verb, app, config, size, title, script, png, settle, out, rest, sign })
}
+/// The app's own `export const steps`, written out as the check's script, when it has them
+fn exported_steps(app: &Path) -> Result<Option<PathBuf>, String> {
+ let src = std::fs::read_to_string(app).map_err(|e| format!("{}: {e}", app.display()))?;
+ let Some(json) = crate::config::steps(&src).map_err(|e| format!("{}:{}: {}", app.display(), e.line, e.why))? else { return Ok(None) };
+ let file = std::env::temp_dir().join(format!("raea-app-steps-{}.json", std::process::id()));
+ std::fs::write(&file, json).map_err(|e| format!("{}: {e}", file.display()))?;
+ Ok(Some(file))
+}
+
pub fn wxh(v: &str) -> Result<(u32, u32), String> {
let bad = || format!("--size {v}: WxH");
let (w, h) = v.split_once('x').ok_or_else(bad)?;
diff --git a/apps/targets/src/web.rs b/apps/targets/src/web.rs
index 2633fcb1..2c2d21ca 100644
--- a/apps/targets/src/web.rs
+++ b/apps/targets/src/web.rs
@@ -54,13 +54,15 @@ pub fn run(a: &Ask) -> Result<String, String> {
}
}
-/// What the native target wouldn't draw (T4a): the app through raea-rune-host headless too, with the same steps, into
-/// `--png`'s native/. Said, never failed on: a web app is checked against web. A host that can't run says why.
+/// The Rune props the web ignores (T4b) and what the native target wouldn't draw (T4a): the app through
+/// raea-rune-host headless too, with the same steps, into `--png`'s native/. Said, never failed on: a web app is
+/// checked against web. A host that can't run says why.
fn native_note(a: &Ask) -> String {
let dir = a.png.join("native");
let native = Ask { png: dir.clone(), ..a.clone() };
- match crate::native::host(&crate::native::args(&native)).and_then(|_| crate::portable::report(&dir)) {
- Ok(lines) => crate::portable::note(&lines),
+ let read = |_| Ok::<_, String>((crate::portable::report(&dir)?, crate::portable::web_ignored(&dir)?));
+ match crate::native::host(&crate::native::args(&native)).and_then(read) {
+ Ok((lines, web)) => [crate::portable::web_note(&web), crate::portable::note(&lines)].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join("\n"),
Err(e) => format!("native: the Rune host couldn't run it headless ({e}), so what native wouldn't draw isn't known"),
}
}
diff --git a/apps/targets/tests/config.rs b/apps/targets/tests/config.rs
index 2a74ffaf..dc1bd284 100644
--- a/apps/targets/tests/config.rs
+++ b/apps/targets/tests/config.rs
@@ -68,3 +68,14 @@ fn the_command_line_overrides_the_file() {
assert!(e.starts_with(&format!("{}:2: ", f.display())), "{e}");
std::fs::remove_dir_all(&dir).unwrap();
}
+
+#[test]
+fn an_apps_own_steps_are_its_checks_script() {
+ use raea_app_targets::config::steps;
+ let src = "export default function A() { return <b /> }\n// export const steps = [{ press: 'no' }]\nexport const steps = [{ press: \"add\" }, { type: \"ada\", into: \"email\" }, { key: \"Tab\" }];";
+ let got: serde_json::Value = serde_json::from_str(&steps(src).unwrap().unwrap()).unwrap();
+ assert_eq!(got, serde_json::json!([{ "press": "add" }, { "type": "ada", "into": "email" }, { "key": "Tab" }]));
+ assert_eq!(steps("export default function A() {}").unwrap(), None);
+ let e = steps("const s = [];\nexport const steps = s;").unwrap_err();
+ assert_eq!(e.line, 2);
+}
diff --git a/apps/targets/tests/portable.rs b/apps/targets/tests/portable.rs
index 9fed1984..8e3858e1 100644
--- a/apps/targets/tests/portable.rs
+++ b/apps/targets/tests/portable.rs
@@ -38,3 +38,13 @@ fn a_run_with_no_report_is_an_error_not_a_pass() {
std::fs::create_dir_all(&d).unwrap();
assert!(report(&d).is_err());
}
+
+#[test]
+fn a_web_apps_rune_props_the_web_ignores_are_named_by_path() {
+ let d = dir("[]", "[] ");
+ std::fs::write(d.join("web-ignored.json"), r#"[{"path": "/div[0]/div[1]", "ignored": "lead"}]"#).unwrap();
+ let lines = raea_app_targets::portable::web_ignored(&d).unwrap();
+ assert_eq!(lines, ["ignored on web: lead at /div[0]/div[1]"]);
+ assert!(raea_app_targets::portable::web_note(&lines).contains("@raea/rune has no CSS for them"));
+ assert_eq!(raea_app_targets::portable::web_note(&[]), "");
+}
diff --git a/bench/bevy-parity/Cargo.toml b/bench/bevy-parity/Cargo.toml
index b42c14ba..27d6089e 100644
--- a/bench/bevy-parity/Cargo.toml
+++ b/bench/bevy-parity/Cargo.toml
@@ -7,9 +7,10 @@ publish = false
description = "Bevy's own examples, built against raea's Bevy with the parity probe in their App (docs/control.feature FC0a): one binary, RAEA_PARITY_EXAMPLE picks the example"
[dependencies]
-# the feature list engine/render's bevy has, so the examples build against the Bevy raea already compiled, and winit: the
-# examples open a window (raea's renders don't), and bevy_scene: Bevy 0.20's examples write their scenes in BSN
-bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "jpeg", "tonemapping_luts", "ktx2", "zstd_rust", "smaa_luts", "experimental_pbr_pcss", "area_light_luts", "bevy_gilrs", "bevy_winit", "bevy_scene"] }
+# the feature list engine/render's bevy has (its bevy-all: dfg_lut and bluenoise_texture too, which stock Bevy's defaults
+# leave out; without the DFG table rough surfaces at grazing angles take less ambient, many_cubes' box srgb 64 for 88), so the
+# examples build against the Bevy raea already compiled, and winit: the examples open a window (raea's renders don't), and bevy_scene: Bevy 0.20's examples write their scenes in BSN
+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "jpeg", "tonemapping_luts", "ktx2", "zstd_rust", "smaa_luts", "experimental_pbr_pcss", "area_light_luts", "dfg_lut", "bluenoise_texture", "bevy_gilrs", "bevy_winit", "bevy_scene"] }
raea-sys-parity = { path = "../../systems/parity" }
# Bevy's examples' own dependencies (bevy v0.20.0's dev-dependencies)
argh = "0.1.12"
diff --git a/bench/bevy-parity/build.rs b/bench/bevy-parity/build.rs
index 10655906..a233e97c 100644
--- a/bench/bevy-parity/build.rs
+++ b/bench/bevy-parity/build.rs
@@ -39,6 +39,16 @@ fn main() {
.replace("include_bytes!(\"", &format!("include_bytes!(\"{}/", file.parent().unwrap().display()))
.replace("App::new()", "crate::parity_app()")
.replace("\nfn main()", "\npub fn main()");
+ // an example drawing from an unseeded rng draws differently every run (two runs of many_lights: SSIM 0.58), so
+ // its draws are made a fixed sequence its port computes the same way: the n-th light's hue the golden angle
+ // times n. Each pattern must be found, so a changed example fails here instead of running unseeded
+ let mut code = code;
+ for (p, from, to) in SEEDED {
+ if path == *p {
+ assert!(code.contains(from), "{path}: no `{from}` to make fixed (bench/bevy-parity/build.rs SEEDED)");
+ code = code.replace(from, to);
+ }
+ }
let m = format!("ex_{}", path.replace('/', "__"));
std::fs::write(out.join(format!("{m}.rs")), code).unwrap();
writeln!(mods, "#[allow(dead_code, unused_imports, non_snake_case, clippy::all)]\npub mod {m} {{ include!(concat!(env!(\"OUT_DIR\"), \"/{m}.rs\")); }}").unwrap();
@@ -47,3 +57,6 @@ fn main() {
let reg = format!("{mods}\n/// Where the examples came from: empty when Bevy's source wasn't found at build time.\npub const BEVY_SRC: &str = {:?};\n/// Runs the example at `path`, false when the host doesn't build it.\npub fn run(path: &str) -> bool {{\n match path {{\n{arms} _ => return false,\n }}\n true\n}}\n", if have { src.display().to_string() } else { String::new() });
std::fs::write(out.join("registry.rs"), reg).unwrap();
}
+
+/// (example, its random draw, the fixed one put in its place): see main.
+const SEEDED: &[(&str, &str, &str)] = &[("stress_tests/many_lights", "rng.random_range(0.0..360.0)", "((i as f64 * 137.507_764_050_037_85) % 360.0) as f32")];
diff --git a/bench/bevy-parity/examples.list b/bench/bevy-parity/examples.list
index 110b6525..7f57930d 100644
--- a/bench/bevy-parity/examples.list
+++ b/bench/bevy-parity/examples.list
@@ -2,3 +2,5 @@
# A port beside each is sdk/raea/bench/bevy-parity/<path>.tsx.
stress_tests/many_cubes
3d/3d_scene
+stress_tests/many_lights
+stress_tests/many_foxes
diff --git a/bench/bevy-parity/runs.tsv b/bench/bevy-parity/runs.tsv
index b50b73f2..6141f6f2 100644
--- a/bench/bevy-parity/runs.tsv
+++ b/bench/bevy-parity/runs.tsv
@@ -1,3 +1,5 @@
# path example arguments (- for none) frames probed (docs/control.feature FC0a; tools/bevy-parity)
stress_tests/many_cubes --benchmark --instance-count 10000 30,60
3d/3d_scene - 5,10
+stress_tests/many_lights - 30,60
+stress_tests/many_foxes --sync 30,60
diff --git a/core/program/src/eval.rs b/core/program/src/eval.rs
index a3715ef0..e4a327bc 100644
--- a/core/program/src/eval.rs
+++ b/core/program/src/eval.rs
@@ -42,6 +42,15 @@ impl Col {
Col::Any(x) => x[r].is_some(),
}
}
+ /// Whether row r holds the same value here as in `other` (None: a column the row doesn't have), copying nothing.
+ pub fn same_at(&self, other: Option<&Col>, r: usize) -> bool {
+ match (self, other) {
+ (Col::Num { v, has }, Some(Col::Num { v: w, has: h })) => has[r] == h[r] && (!has[r] || v[r].to_bits() == w[r].to_bits()),
+ (Col::Any(x), Some(Col::Any(y))) => std::sync::Arc::ptr_eq(x, y) || x[r] == y[r],
+ (c, None) => !c.has(r),
+ (c, Some(o)) => c.get(r) == o.get(r),
+ }
+ }
pub fn num(&self, r: usize) -> Option<f64> {
match self {
Col::Num { v, has } => has[r].then_some(v[r]),
diff --git a/core/program/src/timeline.rs b/core/program/src/timeline.rs
index 2d72e585..5140bd04 100644
--- a/core/program/src/timeline.rs
+++ b/core/program/src/timeline.rs
@@ -12,6 +12,9 @@ pub struct Timeline {
pub base: Cols,
/// per frame: the columns whose values differ from the base (whole columns)
written: Vec<HashMap<String, Col>>,
+ /// per row: true when no frame changes any of its values from the base, so a system that applies a row's values
+ /// to the World each frame can apply a still row's once
+ still: Vec<bool>,
}
impl Timeline {
@@ -21,11 +24,21 @@ impl Timeline {
pub fn from_cols(prog: &Program, base: Cols) -> Result<Timeline, String> {
let frames = prog.frames.max(0);
- let written = parallel(frames as usize, |f| {
+ let per: Vec<(HashMap<String, Col>, Vec<usize>)> = parallel(frames as usize, |f| {
let raw = eval::frame_cols(prog, &base, f as i64);
- Ok(raw.cols.into_iter().filter(|(c, v)| base.cols.get(c) != Some(v)).collect())
+ let w: HashMap<String, Col> = raw.cols.into_iter().filter(|(c, v)| base.cols.get(c) != Some(v)).collect();
+ // the rows this frame moves: a written column's value differing from the base's at that row
+ let moved = (0..base.len()).filter(|r| w.iter().any(|(c, col)| !col.same_at(base.cols.get(c), *r))).collect();
+ Ok((w, moved))
})?;
- Ok(Timeline { frames, base, written })
+ let mut still = vec![true; base.len()];
+ let written = per.into_iter().map(|(w, moved)| {
+ for r in moved {
+ still[r] = false;
+ }
+ w
+ }).collect();
+ Ok(Timeline { frames, base, written, still })
}
/// Whether row r's value of any of `cols` differs from its base on some frame (it moves over the edit).
@@ -33,6 +46,11 @@ impl Timeline {
self.written.iter().any(|w| cols.iter().any(|c| w.get(*c).is_some_and(|col| col.get(r) != self.base.get(r, c))))
}
+ /// Whether row r's values are the same on every frame (out of range: false).
+ pub fn still(&self, r: usize) -> bool {
+ self.still.get(r).copied().unwrap_or(false)
+ }
+
/// One frame as columns.
pub fn cols(&self, f: i64) -> Cols {
let mut c = self.base.clone();
@@ -83,3 +101,25 @@ fn parallel_threads<T: Send>(n: usize, f: impl Fn(usize) -> Result<T, String> +
}
Ok(out)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn row(id: &str, x: f64) -> Tup {
+ Tup { kind: "mesh".into(), id: id.into(), vals: [("x".to_string(), V::N(x))].into_iter().collect() }
+ }
+
+ #[test]
+ fn a_row_no_frame_changes_is_still_and_a_keyed_one_is_not() {
+ let mut prog = Program { frames: 4, ..Default::default() };
+ prog.keys.insert(("moves".into(), "x".into()), vec![(0, 0.0, "linear".into()), (3, 3.0, "linear".into())]);
+ // a key that holds one value on every frame changes nothing
+ prog.keys.insert(("held".into(), "x".into()), vec![(0, 2.0, "linear".into()), (3, 2.0, "linear".into())]);
+ let t = Timeline::new(&prog, &[row("cube", 1.0), row("moves", 0.0), row("held", 2.0)]).unwrap();
+ assert!(t.still(0));
+ assert!(!t.still(1));
+ assert!(t.still(2));
+ assert!(!t.still(3), "a row past the end is never still");
+ }
+}
diff --git a/core/scene/src/props.rs b/core/scene/src/props.rs
index 0d066d43..001c0e60 100644
--- a/core/scene/src/props.rs
+++ b/core/scene/src/props.rs
@@ -114,3 +114,30 @@ pub fn fields_of(p: &Map<String, Value>) -> Option<String> {
}
(!o.is_empty()).then(|| Value::Object(o).to_string())
}
+
+/// A holder of the 3D made see-through, as every path that draws the 3D under the page does: its inline background
+/// goes (the nearest one's colour is the 3D's clear colour, returned here), and when it had one or has a class, an
+/// inline transparent background and no image override whatever a class gives it. Before, only an inline background
+/// went, so `className="bg-brand-bg"` (the brand's own utility) painted an opaque page over the 3D and every frame
+/// rendered as the background colour alone (2026-10-18, void's agent's perfume shot, black for 24 renders). Whether
+/// the props changed, and the clear colour.
+pub fn see_through(p: &mut Map<String, Value>) -> (bool, Option<String>) {
+ let classed = p.get("className").and_then(Value::as_str).is_some_and(|c| !c.trim().is_empty());
+ let style = p.entry("style").or_insert_with(|| Value::Object(Map::new()));
+ let Value::Object(st) = style else { return (false, None) };
+ let mut clear = None;
+ let mut had = false;
+ for k in ["background", "backgroundColor"] {
+ if let Some(v) = st.remove(k) {
+ had = true;
+ if clear.is_none() {
+ clear = v.as_str().map(str::to_string);
+ }
+ }
+ }
+ if had || classed {
+ st.insert("backgroundColor".into(), Value::String("transparent".into()));
+ st.insert("backgroundImage".into(), Value::String("none".into()));
+ }
+ (had || classed, clear)
+}
diff --git a/core/shape/src/build.rs b/core/shape/src/build.rs
index 390f52f8..09db2415 100644
--- a/core/shape/src/build.rs
+++ b/core/shape/src/build.rs
@@ -83,7 +83,17 @@ pub(crate) fn call(f: &str, a: Vec<Arg>) -> Result<Manifold, String> {
.collect();
Manifold::hull_manifolds(&corners)
}
- "sphere" => Manifold::sphere(nums(f, &a, 1)?[0], SEGMENTS),
+ // sphere(r), or sphere(r, n) for Bevy's icosphere of n subdivisions (drawn by Bevy's builder: engine spawn.rs),
+ // its segments about an icosphere's (4.5 x 2^n) up to 256 for CSG and contacts; uv_sphere(r, sectors, stacks)
+ "sphere" => {
+ let n = nums(f, &a, 1)?;
+ let seg = n.get(1).map_or(SEGMENTS, |s| (4.5 * 2f64.powf(s.clamp(0.0, 6.0))).round().clamp(8.0, 256.0) as i32);
+ Manifold::sphere(n[0], seg)
+ }
+ "uv_sphere" => {
+ let n = nums(f, &a, 3)?;
+ Manifold::sphere(n[0], (n[1].round() as i32).clamp(3, 512))
+ }
"cylinder" => {
let n = nums(f, &a, 2)?;
Manifold::cylinder_centered(n[1], n[0], n[0], SEGMENTS, true)
@@ -213,7 +223,7 @@ pub(crate) fn call(f: &str, a: Vec<Arg>) -> Result<Manifold, String> {
let (verts, tris) = if f == "obj" { read_obj(&path)? } else { read_glb(&path)? };
from_mesh(&verts, &tris)?
}
- o => return Err(format!("no shape {o}: box, rounded_box, sphere, cylinder, cone, torus, text3d, extrude, revolve, union, minus, intersect, hull, minkowski, minkowski_diff, move, rotate, scale, mirror, transform, trim, refine, smooth, simplify, refine_length, refine_tolerance, obj, glb; in a mask also frame, rect, disc, wipe, during, slide")),
+ o => return Err(format!("no shape {o}: box, rounded_box, sphere, uv_sphere, cylinder, cone, torus, text3d, extrude, revolve, union, minus, intersect, hull, minkowski, minkowski_diff, move, rotate, scale, mirror, transform, trim, refine, smooth, simplify, refine_length, refine_tolerance, obj, glb; in a mask also frame, rect, disc, wipe, during, slide")),
})
}
diff --git a/core/shape/src/lib.rs b/core/shape/src/lib.rs
index 2aa54680..99e1b25f 100644
--- a/core/shape/src/lib.rs
+++ b/core/shape/src/lib.rs
@@ -10,6 +10,7 @@
//! refine(a, n) refine_length(a, len) refine_tolerance(a, tol) smooth(a, angle°, smoothness, n) simplify(a, tol)
//! extrude("x y, ...; ...", h [, divisions, twist°, scale_x, scale_y]) revolve("x y, ...", [degrees, segments])
//! obj("path") / glb("path") a mesh file, closed into a solid
+//! sphere(r, n) / uv_sphere(r, sectors, stacks) Bevy's icosphere of n subdivisions, or its UV sphere
//!
//! `minus(rounded_box(2, 1, 0.2, 0.1), text3d("SALE", 0.45, 0.3))` is a sign with the word cut through it.
//!
@@ -27,6 +28,8 @@ mod build;
mod glyphs;
mod mesh;
mod parse;
+mod sphere;
+pub use sphere::{SphereOf, sphere_of};
pub use mesh::{export, from_mesh, read_glb, read_obj, to_mesh};
diff --git a/core/shape/src/sphere.rs b/core/shape/src/sphere.rs
new file mode 100644
index 00000000..998fb6e8
--- /dev/null
+++ b/core/shape/src/sphere.rs
@@ -0,0 +1,43 @@
+//! A shape expression that is a sphere alone, which a renderer draws as its own sphere mesh (raea-render: Bevy's
+//! Sphere::mesh(), as a Bevy Mesh3d's is) rather than as Manifold's.
+
+/// A sphere alone, as its expression asks for it
+#[derive(Debug, PartialEq)]
+pub enum SphereOf {
+ /// `sphere(r)` (5 subdivisions, Bevy's default) or `sphere(r, n)`
+ Ico { radius: f32, subdivisions: u32 },
+ /// `uv_sphere(r, sectors, stacks)`
+ Uv { radius: f32, sectors: u32, stacks: u32 },
+}
+
+/// The sphere `expr` is, when it is one alone; None for anything else (moved, cut, any other shape)
+pub fn sphere_of(expr: &str) -> Option<SphereOf> {
+ let e = expr.trim();
+ let (uv, inner) = match e.strip_prefix("uv_sphere(") {
+ Some(rest) => (true, rest),
+ None => (false, e.strip_prefix("sphere(")?),
+ };
+ let inner = inner.strip_suffix(')').filter(|i| !i.contains('('))?;
+ let n: Vec<f32> = inner.split(',').map(|s| s.trim().parse().ok()).collect::<Option<_>>()?;
+ match (uv, n.as_slice()) {
+ (false, &[radius]) => Some(SphereOf::Ico { radius, subdivisions: 5 }),
+ (false, &[radius, s]) => Some(SphereOf::Ico { radius, subdivisions: s as u32 }),
+ (true, &[radius, a, b]) => Some(SphereOf::Uv { radius, sectors: a as u32, stacks: b as u32 }),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_sphere_alone_is_read_and_anything_more_is_not() {
+ assert_eq!(sphere_of("sphere(2)"), Some(SphereOf::Ico { radius: 2.0, subdivisions: 5 }));
+ assert_eq!(sphere_of(" sphere(50, 9) "), Some(SphereOf::Ico { radius: 50.0, subdivisions: 9 }));
+ assert_eq!(sphere_of("uv_sphere(1, 32, 18)"), Some(SphereOf::Uv { radius: 1.0, sectors: 32, stacks: 18 }));
+ for e in ["move(sphere(1), 0, 1, 0)", "minus(sphere(1), box(1, 1, 1))", "box(1, 1, 1)", "uv_sphere(1, 32)", "sphere()"] {
+ assert_eq!(sphere_of(e), None, "{e}");
+ }
+ }
+}
diff --git a/docs/r3f.feature b/docs/r3f.feature
index 8b52255b..2bdcf6b5 100644
--- a/docs/r3f.feature
+++ b/docs/r3f.feature
@@ -48,13 +48,16 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
Scenario: R3F4. Scene3d, the three.js host, for any three.js app
Then sdk/r3f/src/three draws a raea page into a three.js scene without React Three Fiber (sdk/playable's host
is built on it): Scene3d.sync(page, seconds), fit(width, height), apply(renderer)
- And three/kinds.ts has a row for every kind raea's SDK renders (58): 26 drawn, 11 near, 4 settings, 9 effects
- and 8 that are Bevy's own (a WESL shader or frame pass, a compute pass, a Bevy component or resource, an ECS
- world read from the engine's tables, volumetric fog and fog volumes)
- And the 8 that are Bevy's own aren't three.js's to draw: WESL and WGSL run on Bevy's renderer, components,
- resources and ECS worlds are Bevy's data, and the fogs are raymarched through Bevy's shadow maps and depth. A
- page that needs them uses raea-web, raea's engine itself in the browser on WebGPU (docs/web-export.md, which
- says what stays native); Scene3d names each one it leaves out (a warning, and its row)
+ And three/kinds.ts has a row for every kind raea's SDK renders (58): 27 drawn, 11 near, 4 settings, 9 effects
+ and 7 that are Bevy's own (a WESL shader or frame pass, a compute pass, a Bevy component or resource,
+ volumetric fog and fog volumes)
+ And an ECS world (<Entities>) is drawn: its meshes and their transforms come from raea/ecs's own store in
+ JavaScript (sdk/app's scene(), the engine's composition of a child under its parent), each mesh's shape by
+ three's geometry or core/shape's wasm
+ And the 7 that are Bevy's own aren't three.js's to draw: WESL and WGSL run on Bevy's renderer, components and
+ resources are Bevy's data, and the fogs are raymarched through Bevy's shadow maps and depth. A page that needs
+ them uses raea-web, raea's engine itself in the browser on WebGPU (R3F10); Scene3d names each one it leaves out
+ (a warning, and its row)
And a Model with `at` is a copy of the model at each placement, as raea's engine draws it
And raea's default tone mapping, TonyMcMapface, is drawn with Bevy's own LUT (sdk/playable's tony.bin) in a
pass in place of three's output pass; ACES, AgX, Reinhard and none are three's own
@@ -65,6 +68,12 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
Then engine/shape-web compiles core/shape to wasm (tools/shape-wasm.sh, 2.6 MB) and loadShapes() brings it in:
the solid's own triangles, the same as raea's engine meshes
And until it loads, a solid waits (it isn't drawn as something else)
+ And each public release from 0.1.0-canary.3 carries the module, so an app needn't build Rust:
+ tools/release-web.sh attaches raea_shape_web.js and raea_shape_web_bg.wasm (and raea-web's raea_web.js and
+ raea_web_bg.wasm, with SHA256SUMS) to the GitHub release, at
+ https://github.com/shinyobjectz/raea/releases/download/vVERSION/raea_shape_web.js. GitHub serves them as
+ downloads (no CORS), so an app serves the two files itself and calls loadShapes("/raea_shape_web.js"), or
+ imports the glue and passes the module: loadShapes(await import("./raea_shape_web.js"))
@done
Scenario: R3F6. Frame effects
@@ -81,7 +90,8 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
three/kinds.ts, draws every kind three.js draws and fails on a warning, and fails on an effect row the
composer doesn't draw
And it walks three's exports and fails on an Object3D or Material class missing from input/kinds.ts
- And `bun test` in sdk/r3f runs these with the input, round-trip and source-export tests (26 tests)
+ And it fails on a kind three/kinds.ts calls "engine" that has no raea-web parity case (R3F10)
+ And `bun test` in sdk/r3f runs these with the input, round-trip and source-export tests (27 tests)
And a ShadowMaterial is raea's <Mesh shadow="catch">: a surface that shows only the shadows falling on it, in
its material's colour and opacity (systems/material shadow_catch.rs in the engine, three's ShadowMaterial in
Scene3d)
@@ -106,6 +116,7 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
| out-grade | <Grade> saturation, contrast, vignette | 0.9748 |
| out-lens | <LensDistortion k1={0.15}> | 0.9933 |
| out-catch | <Mesh shadow="catch">, three's ShadowMaterial | 0.9972 |
+ | out-entities| <Entities>: a raea/ecs world, a ship and its gun turned by a system | 0.9971 |
| src-basic | out-basic exported as R3F source, drawn by a plain <Canvas> | 0.9957 |
| src-tony | out-tony exported (Tony through raea-effects.ts) | 0.9960 |
| src-lights | out-lights exported as R3F source (Text3D as its triangles) | 0.9628 |
@@ -113,6 +124,7 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
| src-grade | out-grade exported | 0.9748 |
| src-lens | out-lens exported | 0.9933 |
| src-catch | out-catch exported | 0.9972 |
+ | src-entities| out-entities exported | 0.9971 |
And three's ACES scales its input by 1/0.6 where Bevy's doesn't: the host's exposure takes 0.6 under ACES, and
an R3F canvas's ACES reads as 0.74 stops more (measured: out-lights 0.927 to 0.963, in-lights 0.927 to 0.979)
@@ -133,3 +145,26 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
after each frame's updates; effects that only raea's engine draws (three/kinds.ts "engine") are named in the
header
And test/export.test.tsx checks what is written; the src-* cases (R3F8) draw it against raea's render
+
+ Rule: What three.js can't draw, raea-web does
+
+ @done
+ Scenario: R3F10. The engine's own kinds held to `raea render` in the browser
+ Given sdk/web/test/parity/cases.ts: a case for each kind three/kinds.ts calls "engine", and <Entities>
+ When sdk/web/tools/parity.sh renders each with `raea render` and with raea-web (sdk/web, raea's engine on WebGPU)
+ in headless Chrome (tools/shoot.ts), and compares the two by SSIM
+ Then every case is at least 0.92, and a blank web frame fails whatever its SSIM (measured 11-06)
+ | case | kinds | SSIM |
+ | surface-shader | SurfaceShader | 0.9998 |
+ | frame-pass | FramePass | 1.0000 |
+ | compute | Compute | 1.0000 |
+ | component | BevyComponent | 1.0000 |
+ | resource | BevyResource | 0.9999 |
+ | entities | Entities | 0.9760 |
+ | fog | VolumetricFog, FogVolume | 0.9993 |
+ And the first five are sdk/raea/bench/bevy-ts's cases (shader-scene, frame-pass, compute, reflect-on-camera,
+ reflect-keyed-resource-still, 64x64); entities and fog are 320x180
+ And a page's files (a glTF, a picture) are fetched from assets/ beside the page, Bevy's asset folder on the web
+ And measuring it fixed raea-web: a model's file is fetched rather than looked for on disk (runtime/scene3d
+ model.rs), a black page background is the 3D's clear rather than a cover over it (rgb(0, 0, 0) was read as
+ see-through, here and in Scene3d), and a layered <Canvas3D>'s empty slot isn't drawn
diff --git a/docs/web-export.md b/docs/web-export.md
index afc37a53..b1fdbfba 100644
--- a/docs/web-export.md
+++ b/docs/web-export.md
@@ -87,6 +87,15 @@ page draws what it draws natively; 0.903 at `pixel: 4`, where a cell is one draw
Still to measure: an iPad in Safari (30 fps) and the poster's first paint (1.5 s).
+## raea's own kinds in the browser
+
+The kinds three.js can't draw (sdk/r3f/src/three/kinds.ts "engine": SurfaceShader, FramePass, Compute, BevyComponent,
+BevyResource, VolumetricFog, FogVolume) and <Entities> are drawn here by raea's own engine. `sdk/web/tools/parity.sh`
+renders each case in sdk/web/test/parity with `raea render` and with raea-web in headless Chrome on WebGPU and compares
+them by SSIM: all seven at least 0.976, five at 0.9998 or more (docs/r3f.feature R3F10). A page's files (a glTF, a
+picture) are fetched from `assets/` beside the page, Bevy's asset folder on the web. Each GitHub release carries
+raea-web's module (`raea_web.js`, `raea_web_bg.wasm`), built by tools/release-web.sh.
+
## Sound
In a page raea/tone is Tone.js (the page's bundler maps `raea/tone` to `tone`), so an edit's sound is written once in
diff --git a/engine/render/src/engine/load.rs b/engine/render/src/engine/load.rs
index 542c6772..9a96ea23 100644
--- a/engine/render/src/engine/load.rs
+++ b/engine/render/src/engine/load.rs
@@ -126,7 +126,7 @@ impl Engine {
None => std::sync::Arc::new(raea_core_program::timeline::Timeline::from_cols(prog, base)?),
};
world.insert_resource(Edit { prog: prog.clone(), timeline, media });
- world.insert_resource(FrameRows { cols: eval::Cols::default(), ix, live: None, looks: HashMap::new() });
+ world.insert_resource(FrameRows { cols: eval::Cols::default(), ix, live: None, looks: HashMap::new(), timeline: None });
let Some(cam) = camera else { return Err("the edit needs a camera: INSERT INTO camera (id, ...) VALUES (...)".into()) };
let models = world.query::<&scene3d::Model3d>().iter(world).count();
let h = prog.height as f32;
diff --git a/engine/render/src/engine/spawn.rs b/engine/render/src/engine/spawn.rs
index d772a497..64916e17 100644
--- a/engine/render/src/engine/spawn.rs
+++ b/engine/render/src/engine/spawn.rs
@@ -29,6 +29,9 @@ pub(crate) fn relational(edit: Res<Edit>, clock: Res<Clock>, mut err: ResMut<Err
}
let t0 = bevy::platform::time::Instant::now();
frame.cols = edit.timeline.cols(clock.0);
+ if !frame.timeline.as_ref().is_some_and(|t| std::sync::Arc::ptr_eq(t, &edit.timeline)) {
+ frame.timeline = Some(edit.timeline.clone());
+ }
frame.parse_looks();
st.rules += t0.elapsed().as_nanos() as u64;
let _ = &mut err;
@@ -241,6 +244,17 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
let tangents = vals.get("normal_map").is_some_and(V::truthy);
// made once per shape and what it's given (share.rs): equal parts hold one Mesh, so Bevy batches them
let mesh = scene3d::shared_mesh(world, &format!("{expr}\0{uvs}\0{tangents}"), || {
+ // a sphere on its own is Bevy's Sphere::mesh() (its icosphere, or its UV sphere), as a Bevy Mesh3d's is
+ let ball = raea_core_shape::sphere_of(&expr).map(|s| match s {
+ raea_core_shape::SphereOf::Ico { radius, subdivisions } => Sphere::new(radius).mesh().ico(subdivisions).map_err(|e| format!("mesh {}: {e}", t.id)),
+ raea_core_shape::SphereOf::Uv { radius, sectors, stacks } => Ok(Sphere::new(radius).mesh().uv(sectors, stacks)),
+ });
+ if let Some(mut m) = ball.transpose()? {
+ if tangents {
+ m.generate_tangents().map_err(|e| format!("mesh {}: normalMap: its tangents: {e}", t.id))?;
+ }
+ return Ok(m);
+ }
// or its own vertex buffers (<BufferMesh>: "buffer:{positions, indices, normals, uvs}")
let (tris, own_uvs, own_colors) = match expr.strip_prefix("buffer:") {
Some(b) => {
@@ -375,4 +389,3 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
}
Ok(())
}
-
diff --git a/engine/rune/page/src/view.rs b/engine/rune/page/src/view.rs
index bd332135..e496b943 100644
--- a/engine/rune/page/src/view.rs
+++ b/engine/rune/page/src/view.rs
@@ -314,6 +314,9 @@ fn intern(s: &str) -> &'static str {
/// Props other than `style` that the host reads, and a report for the rest.
fn props(n: &Node, path: &str, report: &mut Report) {
+ if let Some(w) = n.props.get("data-rune-web-ignored").and_then(Value::as_str) {
+ report.web_ignored(path, w);
+ }
for k in n.props.keys() {
let known = k == "style" || k == "className" || k.starts_with("data-") || k.starts_with("aria-") || matches!(k.as_str(), "role" | "id" | "tabIndex" | "value" | "placeholder" | "disabled" | "type" | "name" | "src" | "alt" | "autoplay" | "autoPlay" | "loop" | "muted" | "playsInline" | "playsinline" | "__seek");
if !known {
diff --git a/engine/rune/src/main.rs b/engine/rune/src/main.rs
index 9d1a0e9b..6d0c9758 100644
--- a/engine/rune/src/main.rs
+++ b/engine/rune/src/main.rs
@@ -193,6 +193,10 @@ fn run() -> Result<(), String> {
}
let report = a.out.join("unmapped.json");
std::fs::write(&report, serde_json::to_string_pretty(&unmapped).unwrap()).map_err(|e| format!("{}: {e}", report.display()))?;
+ // the Rune props the web target ignores, as the SDK marked them: the web check lists them (T4b)
+ let web: Vec<_> = app.session.rt.state.report.borrow().web().map(|(path, w)| json!({"path": path, "ignored": w})).collect();
+ let report = a.out.join("web-ignored.json");
+ std::fs::write(&report, serde_json::to_string_pretty(&web).unwrap()).map_err(|e| format!("{}: {e}", report.display()))?;
// and every call the app made that this host didn't answer (T2c), the same way
let unanswered: Vec<_> = app.refused.borrow().iter().map(|(name, (why, n))| json!({"call": name, "why": why, "times": n})).collect();
for (name, (why, n)) in app.refused.borrow().iter() {
diff --git a/engine/rune/style/src/report.rs b/engine/rune/style/src/report.rs
index 6cb89a3a..36e50b47 100644
--- a/engine/rune/style/src/report.rs
+++ b/engine/rune/style/src/report.rs
@@ -18,6 +18,8 @@ pub struct Seen {
pub struct Report {
seen: BTreeMap<(String, &'static str), Seen>,
fresh: Vec<String>,
+ /// what the SDK marked as having no web form (`data-rune-web-ignored`, T4b), by element path
+ web: BTreeMap<String, String>,
}
impl Report {
@@ -46,6 +48,15 @@ impl Report {
self.seen.iter().map(|((p, _), s)| (p.as_str(), s))
}
+ /// Element `path`'s Rune props that the web target ignores, as @raea/rune named them (T4b).
+ pub fn web_ignored(&mut self, path: &str, what: &str) {
+ self.web.insert(path.to_string(), what.to_string());
+ }
+
+ pub fn web(&self) -> impl Iterator<Item = (&str, &str)> {
+ self.web.iter().map(|(p, w)| (p.as_str(), w.as_str()))
+ }
+
pub fn is_empty(&self) -> bool {
self.seen.is_empty()
}
diff --git a/runtime/bundle/src/styles.rs b/runtime/bundle/src/styles.rs
index 05604b9b..8467e2fc 100644
--- a/runtime/bundle/src/styles.rs
+++ b/runtime/bundle/src/styles.rs
@@ -2,7 +2,8 @@
//! (brand/brand.css beside the edit, its @imports dropped: Blitz loads no remote CSS), then Tailwind 4 for every class
//! any .ts or .tsx in the edit's folder uses, with raea's brand theme (engine/cli/template/theme.css: class names onto
//! --brand-* variables). render, play, bundle and export-game write it before they bundle, as the legacy app does
-//! (apps/legacy/shell/src/tailwind.rs: the same compile, which this follows byte for byte). Tailwind's compiler runs on raea's
+//! (apps/legacy/shell/src/tailwind.rs: the same compile, which this follows byte for byte, but for the classes inside a
+//! template's `${...}`, which it finds: docs/targets.feature T5a). Tailwind's compiler runs on raea's
//! JavaScriptCore (raea-native's js-exec), from the package raea ships (sdk/react/tw/node_modules/tailwindcss under
//! raea_io_home::home(): the checkout's, or an install's share/raea).
#[cfg(feature = "modules")]
@@ -149,47 +150,105 @@ fn candidates(code: &[PathBuf]) -> Vec<String> {
out
}
-/// The strings /(["'`])((?:(?!\1)[^\\]|\\.)*)\1/g matches: from a quote to the next unescaped same quote; a quote with
-/// no closing one is passed over
+/// The strings of `src` as JS reads them: from a quote to the next unescaped same quote, a quote with no closing one
+/// passed over. A template's text between its `${...}`s is a string each, and the code inside each `${...}` is read for
+/// strings of its own (`size-4 ${on ? "bg-blue-600" : "bg-white"}` gives `size-4 `, `bg-blue-600` and `bg-white`);
+/// read as one string, its words reached Tailwind with the quotes on them and matched nothing (docs/targets.feature T5a)
#[cfg_attr(not(feature = "modules"), allow(dead_code))]
fn quoted(src: &str) -> Vec<&str> {
- let b = src.as_bytes();
- let utf8_len = |lead: u8| match lead {
+ let mut out = Vec::new();
+ strings(src, 0, src.len(), false, &mut out);
+ out
+}
+
+fn utf8_len(lead: u8) -> usize {
+ match lead {
0xf0..=0xff => 4,
0xe0..=0xef => 3,
0xc0..=0xdf => 2,
_ => 1,
- };
- let mut out = Vec::new();
- let mut i = 0;
- while i < b.len() {
+ }
+}
+
+/// The strings in src[i..end], pushed in order; returns where it stopped: `end`, or in a `${` (`nested`) its closing `}`
+/// (an unmatched one at the top is passed over, so a stray brace in a comment or a regex can't end the file's read)
+fn strings<'a>(src: &'a str, mut i: usize, end: usize, nested: bool, out: &mut Vec<&'a str>) -> usize {
+ let b = src.as_bytes();
+ let mut depth = 0usize;
+ while i < end {
let q = b[i];
- if q == b'"' || q == b'\'' || q == b'`' {
- let mut j = i + 1;
- let mut closed = None;
- while j < b.len() {
- if b[j] == b'\\' {
- if j + 1 >= b.len() {
- break;
- }
- j += 1 + utf8_len(b[j + 1]);
+ match q {
+ b'"' | b'\'' => {
+ if let Some(close) = closing(b, i + 1, end, q) {
+ out.push(&src[i + 1..close]);
+ i = close + 1;
continue;
}
- if b[j] == q {
- closed = Some(j);
- break;
+ }
+ b'`' => {
+ if let Some(next) = template(src, i + 1, end, out) {
+ i = next;
+ continue;
}
- j += utf8_len(b[j]);
}
- if let Some(end) = closed {
- out.push(&src[i + 1..end]);
- i = end + 1;
- continue;
+ b'{' => depth += 1,
+ b'}' if depth == 0 => {
+ if nested {
+ return i;
+ }
}
+ b'}' => depth -= 1,
+ _ => {}
}
- i += utf8_len(b[i]).max(1);
+ i += utf8_len(q).max(1);
}
- out
+ end
+}
+
+/// The next unescaped `q` from `j`, before `end`
+fn closing(b: &[u8], mut j: usize, end: usize, q: u8) -> Option<usize> {
+ while j < end {
+ if b[j] == b'\\' {
+ if j + 1 >= end {
+ return None;
+ }
+ j += 1 + utf8_len(b[j + 1]);
+ continue;
+ }
+ if b[j] == q {
+ return Some(j);
+ }
+ j += utf8_len(b[j]);
+ }
+ None
+}
+
+/// A template from just after its backtick: its text pieces and the strings in its `${...}`s pushed in order, and where
+/// it ends (after the closing backtick), or None for one that never closes (its pushes taken back)
+fn template<'a>(src: &'a str, mut j: usize, end: usize, out: &mut Vec<&'a str>) -> Option<usize> {
+ let b = src.as_bytes();
+ let (mark, mut start) = (out.len(), j);
+ while j < end {
+ match b[j] {
+ b'\\' if j + 1 < end => j += 1 + utf8_len(b[j + 1]),
+ b'`' => {
+ out.push(&src[start..j]);
+ return Some(j + 1);
+ }
+ b'$' if b.get(j + 1) == Some(&b'{') => {
+ out.push(&src[start..j]);
+ let close = strings(src, j + 2, end, true, out);
+ if close >= end {
+ break;
+ }
+ j = close + 1;
+ start = j;
+ }
+ c => j += utf8_len(c),
+ }
+ }
+ out.truncate(mark);
+ None
}
#[cfg(test)]
@@ -198,6 +257,14 @@ mod tests {
#[test]
fn finds_quoted_words_as_project_ts() {
- assert_eq!(quoted(r#"a "b c" 'd' `e ${f}` "g\"h" 'unclosed"#), vec!["b c", "d", "e ${f}", "g\\\"h"]);
+ assert_eq!(quoted(r#"a "b c" 'd' `e ${f}` "g\"h" 'unclosed"#), vec!["b c", "d", "e ", "", "g\\\"h"]);
+ }
+
+ #[test]
+ fn reads_a_templates_code_for_strings_of_its_own() {
+ let src = r#"<div className={`size-4 ${on ? "bg-blue-600" : `ring ${n}`} rounded`} />"#;
+ assert_eq!(quoted(src), vec!["size-4 ", "bg-blue-600", "ring ", "", " rounded"]);
+ // a stray brace at the top doesn't end the read; a template that never closes is passed over
+ assert_eq!(quoted("} \"a\" { `b ${\"c\"} \"d\""), vec!["a", "c", "d"]);
}
}
diff --git a/runtime/export/src/program.rs b/runtime/export/src/program.rs
index 50837959..878cea1e 100644
--- a/runtime/export/src/program.rs
+++ b/runtime/export/src/program.rs
@@ -23,6 +23,18 @@ pub(crate) fn program(frames: &[(i64, Frame)], w: u32, h: u32, fps: f64) -> raea
eprintln!("raea: --alpha keeps 2D pages and <Video> clips transparent; the frames with 3D are drawn over the 3D and come out opaque");
}
let mut cam = row("cam", clear.map(|c| ("bg", V::S(c))).into_iter().collect());
+ // a holder's background that changes over the frames: the clear keyed frame by frame (bg_r, bg_g, bg_b, bg_a, sRGB),
+ // as the page over it changes. Before, the first frame's clear held for the whole render.
+ if has3d && !ALPHA.load(std::sync::atomic::Ordering::Relaxed) {
+ let mut last = None;
+ let each: Vec<Option<[f64; 4]>> = frames.iter().map(|(_, f)| f.clear.as_deref().and_then(hex_of).and_then(|c| rgba_of(&c))).collect();
+ if each.iter().flatten().any(|c| Some(c) != each[0].as_ref()) {
+ let cols: Vec<[f64; 4]> = each.iter().map(|c| *last.insert((*c).or(last).unwrap_or([0.0, 0.0, 0.0, 1.0]))).collect();
+ for (k, name) in ["bg_r", "bg_g", "bg_b", "bg_a"].iter().enumerate() {
+ raea_runtime_scene::column(&mut p, &mut cam, "cam", name, &cols.iter().map(|c| c[k]).collect::<Vec<_>>());
+ }
+ }
+ }
if has3d {
// where it is and looks, frame by frame; its lens, ambient light and post-processing (scene3d)
scene3d::camera(frames, &mut p, &mut cam);
@@ -155,3 +167,14 @@ pub(crate) fn sound_lint(p: &raea_core_program::ir::Program, fps: f64) {
}
}
}
+
+/// A `#rgb`, `#rrggbb` or `#rrggbbaa` colour as sRGB 0..1, alpha last
+pub(crate) fn rgba_of(c: &str) -> Option<[f64; 4]> {
+ let h = c.strip_prefix('#')?;
+ let h: String = if h.len() == 3 { h.chars().flat_map(|c| [c, c]).collect() } else { h.to_string() };
+ if h.len() != 6 && h.len() != 8 {
+ return None;
+ }
+ let at = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok().map(|v| v as f64 / 255.0);
+ Some([at(0)?, at(2)?, at(4)?, if h.len() == 8 { at(6)? } else { 1.0 }])
+}
diff --git a/runtime/look/src/camera.rs b/runtime/look/src/camera.rs
index bafcc3bc..7aca9bdc 100644
--- a/runtime/look/src/camera.rs
+++ b/runtime/look/src/camera.rs
@@ -56,9 +56,10 @@ pub fn camera(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>)
row.insert(name.into(), V::N(v));
}
}
- // ambient: every AmbientLight's intensity summed, per frame; its colour the first one's
+ // ambient: every AmbientLight's intensity summed, per frame; its colour the first one's. Any AmbientLight sends the
+ // column, so one of brightness 0 turns the ambient off as Bevy's does (with none, the camera keeps Bevy's default 80)
let amb: Vec<f64> = all.iter().map(|its| its.iter().filter(|i| i.kind == "ambient").map(|i| light_power("ambient", &i.props)).sum::<f64>()).collect();
- if amb.iter().any(|a| *a > 0.0) {
+ if all.iter().flatten().any(|i| i.kind == "ambient") {
column(p, row, id, "ambient", &amb);
if let Some(c) = all.iter().flatten().find(|i| i.kind == "ambient").and_then(|i| hex(i.props.get("color"))) {
if c != "#ffffff" {
diff --git a/runtime/react/src/animate.rs b/runtime/react/src/animate.rs
index 0f787f80..25eaf65e 100644
--- a/runtime/react/src/animate.rs
+++ b/runtime/react/src/animate.rs
@@ -37,7 +37,8 @@ pub(crate) struct Warned(std::collections::HashSet<String>);
pub(crate) fn sample_animations(
mut commands: Commands,
mut clock: ResMut<FrameClock>,
- mut q: Query<(Entity, &ReactNode, &mut ReactProps, Option<&Animated>)>,
+ // to sample, those whose props changed and the animated ones (not every element: 40% of 100 000 lights' step); the marker's
+ mut qs: ParamSet<(Query<(Entity, &ReactNode, &mut ReactProps, Option<&Animated>), Or<(Changed<ReactProps>, With<Animated>)>>, Query<(Entity, &ReactProps)>)>,
kids: Query<&Children>,
mut texts: Query<(&ReactNode, &ReactKind, &mut ReactText), Without<ReactProps>>,
mut marker: Local<MarkerCache>,
@@ -45,11 +46,12 @@ pub(crate) fn sample_animations(
) {
// the frame: the marker's, found once and kept
let has_marker = |p: &ReactProps| p.0.contains_key("data-raea-frame");
- if marker.entity.is_none_or(|e| q.get(e).map(|(_, _, p, _)| !has_marker(&p)).unwrap_or(true)) {
- marker.entity = q.iter().find(|(_, _, p, _)| has_marker(p)).map(|(e, ..)| e);
+ let all = qs.p1();
+ if marker.entity.is_none_or(|e| all.get(e).map(|(_, p)| !has_marker(p)).unwrap_or(true)) {
+ marker.entity = all.iter().find(|(_, p)| has_marker(p)).map(|(e, _)| e);
}
let Some(me) = marker.entity else { return };
- let Ok((_, _, mp, _)) = q.get(me) else { return };
+ let Ok((_, mp)) = all.get(me) else { return };
let Some(frame) = mp.0.get("data-raea-frame").and_then(Value::as_f64) else { return };
if frame < 0.0 {
return;
@@ -65,8 +67,7 @@ pub(crate) fn sample_animations(
*clock = next;
}
let f = clock.frame as f64;
-
- for (e, node, mut props, animated) in &mut q {
+ for (e, node, mut props, animated) in &mut qs.p0() {
let Some(src) = props.0.get("data-raea-anim").and_then(Value::as_str) else {
if animated.is_some() {
commands.entity(e).remove::<Animated>();
diff --git a/runtime/react/src/scene.rs b/runtime/react/src/scene.rs
index da9c956a..124505e6 100644
--- a/runtime/react/src/scene.rs
+++ b/runtime/react/src/scene.rs
@@ -9,7 +9,7 @@ use serde_json::{Map, Value};
use crate::{ReactKind, ReactOutbox, ReactProps};
pub use raea_runtime_bundle::*;
-pub use raea_core_scene::{Node3, hex_of, num};
+pub use raea_core_scene::{Node3, hex_of, num, see_through};
/// A composition bundled (raea_runtime_bundle), its folder first named as where its models' calls read from
pub fn bundle_composition(tsx: &Path, out_js: &Path, o: &CompOpts, portable: Option<&Path>) -> R<()> {
diff --git a/runtime/react/src/scene/holders.rs b/runtime/react/src/scene/holders.rs
index 3fd778f4..9473343f 100644
--- a/runtime/react/src/scene/holders.rs
+++ b/runtime/react/src/scene/holders.rs
@@ -22,94 +22,89 @@ pub fn scene_of(world: &mut World) -> Vec<Node3> {
world.resource_scope(|world, mut kept: Mut<Kept3d>| contrib3d(world, surf, &mut kept, &dirty).to_vec())
}
-/// The page elements holding the frame's 3D (each 3D root's ancestors up to the surface, nearest first) with their
-/// props: a render clears their backgrounds (the 3D is drawn under the page) and the nearest one's colour is the 3D's.
/// The elements holding the 3D (holders_of's), into `out` (ZeroHeap: live play's present asks each frame)
pub fn holder_entities(world: &mut World, out: &mut Vec<Entity>) {
out.clear();
- with_holder_query(world, |world, q| {
- let is3d = |w: &World, e: Entity| w.get::<ReactProps>(e).is_some_and(|p| p.0.contains_key("data-3d"));
- for (r, p, c) in q.0.iter(world) {
- if !p.0.contains_key("data-3d") || c.is_some_and(|c| is3d(world, c.parent())) {
- continue;
- }
- let mut at = world.get::<ChildOf>(r).map(|c| c.parent());
- while let Some(e) = at {
- if world.get::<ReactKind>(e).is_some_and(|k| k.0 == "surface") {
- break;
- }
- if !out.contains(&e) {
- out.push(e);
- }
- at = world.get::<ChildOf>(e).map(|c| c.parent());
- }
- }
- })
+ out.extend(fresh_holders(world).0);
}
-#[derive(Resource)]
-pub struct HolderQuery(QueryState<(Entity, &'static ReactProps, Option<&'static ChildOf>)>);
-
-pub fn with_holder_query<T>(world: &mut World, f: impl FnOnce(&mut World, &mut HolderQuery) -> T) -> T {
- if !world.contains_resource::<HolderQuery>() {
- let q = world.query();
- world.insert_resource(HolderQuery(q));
- }
- world.resource_scope(|world, mut q: Mut<HolderQuery>| f(world, &mut q))
-}
-
-pub fn holders_of(world: &mut World) -> Vec<(Entity, Map<String, Value>)> {
- let mut q = world.query::<(Entity, &ReactProps, Option<&ChildOf>)>();
- let is3d = |w: &World, e: Entity| w.get::<ReactProps>(e).is_some_and(|p| p.0.contains_key("data-3d"));
- let roots: Vec<Entity> = q.iter(world).filter(|(_, p, c)| p.0.contains_key("data-3d") && !c.is_some_and(|c| is3d(world, c.parent()))).map(|(e, _, _)| e).collect();
- let mut out: Vec<(Entity, Map<String, Value>)> = Vec::new();
- for r in roots {
- let mut at = world.get::<ChildOf>(r).map(|c| c.parent());
- while let Some(e) = at {
- if world.get::<ReactKind>(e).is_some_and(|k| k.0 == "surface") {
- break;
+/// Each 3D root's ancestors up to the surface, nearest first, in the page's order: a walk down from the surface that
+/// stops at each data-3d element (a 3D root), so the 3D's own parts are never visited. Before, every element's props
+/// were looked at each frame to find the roots (half of many_lights' React step, its 100 000 lights).
+fn holders_walk(world: &mut World, out: &mut Vec<Entity>) {
+ let Some(surf) = world.query::<(Entity, &ReactKind)>().iter(world).find(|(_, k)| k.0 == "surface").map(|(e, _)| e) else { return };
+ let world: &World = world;
+ let mut stack: Vec<(Entity, usize)> = vec![(surf, 0)];
+ let mut path: Vec<Entity> = Vec::new();
+ while let Some((e, depth)) = stack.pop() {
+ path.truncate(depth);
+ if e != surf
+ && let Some(p) = world.get::<ReactProps>(e)
+ && p.0.contains_key("data-3d")
+ {
+ for a in path.iter().rev().filter(|a| **a != surf) {
+ if !out.contains(a) {
+ out.push(*a);
+ }
}
- if !out.iter().any(|(x, _)| *x == e) {
- out.push((e, world.get::<ReactProps>(e).map(|p| p.0.clone()).unwrap_or_default()));
+ continue;
+ }
+ path.push(e);
+ if let Some(kids) = world.get::<Children>(e) {
+ for k in kids.iter().rev() {
+ stack.push((k, depth + 1));
}
- at = world.get::<ChildOf>(e).map(|c| c.parent());
}
}
- out
}
-/// A holder of the 3D made see-through, as every path that draws the 3D under the page does: its inline background
-/// goes (the nearest one's colour is the 3D's clear colour, returned here), and when it had one or has a class, an
-/// inline transparent background and no image override whatever a class gives it. Before, only an inline background
-/// went, so `className="bg-brand-bg"` (the brand's own utility) painted an opaque page over the 3D and every frame
-/// rendered as the background colour alone (2026-10-18, void's agent's perfume shot, black for 24 renders). Whether
-/// the props changed, and the clear colour.
-pub fn see_through(p: &mut Map<String, Value>) -> (bool, Option<String>) {
- let classed = p.get("className").and_then(Value::as_str).is_some_and(|c| !c.trim().is_empty());
- let style = p.entry("style").or_insert_with(|| Value::Object(Map::new()));
- let Value::Object(st) = style else { return (false, None) };
- let mut clear = None;
- let mut had = false;
- for k in ["background", "backgroundColor"] {
- if let Some(v) = st.remove(k) {
- had = true;
- if clear.is_none() {
- clear = v.as_str().map(str::to_string);
- }
- }
- }
- if had || classed {
- st.insert("backgroundColor".into(), Value::String("transparent".into()));
- st.insert("backgroundImage".into(), Value::String("none".into()));
- }
- (had || classed, clear)
+/// The page elements holding the frame's 3D (each 3D root's ancestors up to the surface, nearest first) with their
+/// props: a render clears their backgrounds (the 3D is drawn under the page) and the nearest one's colour is the 3D's.
+pub fn holders_of(world: &mut World) -> Vec<(Entity, Map<String, Value>)> {
+ fresh_holders(world).0.into_iter().map(|e| (e, world.get::<ReactProps>(e).map(|p| p.0.clone()).unwrap_or_default())).collect()
}
/// A layered Canvas3D's slot: the `<img data-raea-scene>` it renders, whose place in the page's paint order the 3D's
/// frame takes (as a texture), so page elements before it in the tree are under the 3D and those after it over it.
pub fn scene_slot(world: &mut World) -> Option<u64> {
- let mut q = world.query::<(&ReactProps, Option<&crate::ReactNode>)>();
- q.iter(world).find(|(p, _)| p.0.contains_key("data-raea-scene")).and_then(|(_, n)| n.map(|n| n.0))
+ fresh_holders(world).1.and_then(|s| world.get::<crate::ReactNode>(s)).map(|n| n.0)
+}
+
+/// The holders and the slot as the page last had them, worked out again only when the page changed: a child added,
+/// moved or taken away (or a commit's note that a parent lost one, `stale`), or new props on a holder, on the slot
+/// or on an element that becomes one (a page element's other props, a frame's mark, change nothing here). Each was a
+/// look at every element's props every frame (100 000 lights).
+#[derive(Resource)]
+pub(crate) struct HolderCache {
+ #[allow(clippy::type_complexity)]
+ watch: bevy::ecs::system::SystemState<(Query<'static, 'static, (), Or<(Changed<Children>, Changed<ChildOf>)>>, Query<'static, 'static, (Entity, &'static ReactProps), Changed<ReactProps>>)>,
+ holders: Vec<Entity>,
+ slot: Option<Entity>,
+ pub(crate) stale: bool,
+}
+
+fn fresh_holders(world: &mut World) -> (Vec<Entity>, Option<Entity>) {
+ if !world.contains_resource::<HolderCache>() {
+ let watch = bevy::ecs::system::SystemState::new(world);
+ world.insert_resource(HolderCache { watch, holders: Vec::new(), slot: None, stale: true });
+ }
+ let stale = world.resource_scope(|world, mut c: Mut<HolderCache>| {
+ let (holders, slot) = (c.holders.clone(), c.slot);
+ let Ok((moved, props)) = c.watch.get(world) else { return true };
+ let changed = moved.iter().next().is_some() || props.iter().any(|(e, p)| holders.contains(&e) || slot == Some(e) || p.0.contains_key("data-raea-scene"));
+ // what a commit changes directly on the World after this has a newer tick than this read (read.rs dirty3d)
+ world.increment_change_tick();
+ std::mem::take(&mut c.stale) || changed
+ });
+ if stale {
+ let mut holders = Vec::new();
+ holders_walk(world, &mut holders);
+ let slot = world.query::<(Entity, &ReactProps)>().iter(world).find(|(_, p)| p.0.contains_key("data-raea-scene")).map(|(e, _)| e);
+ let mut c = world.resource_mut::<HolderCache>();
+ (c.holders, c.slot) = (holders, slot);
+ }
+ let c = world.resource::<HolderCache>();
+ (c.holders.clone(), c.slot)
}
/// The 3D's clear colour for a render or play: transparent (#00000000) for a layered Canvas3D, whose background is the
diff --git a/runtime/react/src/scene/read.rs b/runtime/react/src/scene/read.rs
index e2fc4d35..3e5a966a 100644
--- a/runtime/react/src/scene/read.rs
+++ b/runtime/react/src/scene/read.rs
@@ -90,6 +90,10 @@ pub(crate) struct Watch3d(bevy::ecs::system::SystemState<Query<'static, 'static,
/// A commit's note that `e`'s parent loses it (a remove, or a move by append or insert)
pub(crate) fn touch_parent(world: &mut World, e: Entity) {
+ // the 3D's holders are worked out again too (holders.rs HolderCache)
+ if let Some(mut h) = world.get_resource_mut::<super::holders::HolderCache>() {
+ h.stale = true;
+ }
if let Some(p) = world.get::<ChildOf>(e).map(|c| c.parent())
&& let Some(mut k) = world.get_resource_mut::<Kept3d>()
{
diff --git a/runtime/scene/src/lib.rs b/runtime/scene/src/lib.rs
index 77c852d4..950223bd 100644
--- a/runtime/scene/src/lib.rs
+++ b/runtime/scene/src/lib.rs
@@ -12,7 +12,7 @@ use raea_core_program::ir::{Program, V};
use serde_json::{Map, Value};
use raea_core_scene::*;
-pub use raea_runtime_look::camera;
+pub use raea_runtime_look::{camera, column};
use raea_runtime_look::*;
mod parts;
diff --git a/runtime/scene/src/parts.rs b/runtime/scene/src/parts.rs
index 33456f83..316ff595 100644
--- a/runtime/scene/src/parts.rs
+++ b/runtime/scene/src/parts.rs
@@ -28,6 +28,9 @@ fn shader_row(id: String, it: &Item) -> BTreeMap<String, V> {
/// lights: directional (towards its target, the origin by default), point, spot
pub(crate) fn lights_rows(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {
let mut li = 0;
+ // a <Shadows>, found once: every light takes its cascades and biases (looking for it per light scanned every
+ // frame's items once a light, 100 000 lights by 100 000 items)
+ let shadows = all.iter().flatten().find(|i| i.kind == "shadows");
for (_, track) in &tr.lights {
let its = filled(&track);
let kind = its[0].kind;
@@ -82,7 +85,7 @@ pub(crate) fn lights_rows(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {
row.insert("soft".into(), V::N(r));
}
// a <Shadows>' cascades (the sun's) and biases (every light's)
- if let Some(sh) = all.iter().flatten().find(|i| i.kind == "shadows") {
+ if let Some(sh) = shadows {
for (prop, col) in [("distance", "shadow_dist"), ("firstCascade", "shadow_first"), ("cascades", "shadow_cascades"), ("overlap", "shadow_overlap"), ("bias", "shadow_bias"), ("normalBias", "shadow_nbias")] {
if let Some(x) = num(&sh.props, prop) {
row.insert(col.into(), V::N(x));
diff --git a/runtime/scene3d/src/model.rs b/runtime/scene3d/src/model.rs
index ba4d1722..b01b8e50 100644
--- a/runtime/scene3d/src/model.rs
+++ b/runtime/scene3d/src/model.rs
@@ -4,7 +4,8 @@ use super::*;
pub fn model(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup], dir: &Path) -> Result<(), String> {
let src = match t.vals.get("src") { Some(V::S(s)) => s.clone(), _ => return Err(format!("model {}: needs src (a .glb or .gltf file)", t.id)) };
let path = resolve_src(inserted, &src, dir)?;
- if !path.exists() {
+ // in the browser (raea-web) a file is fetched by the asset server, so there's nothing on disk to look for
+ if cfg!(not(target_arch = "wasm32")) && !path.exists() {
return Err(format!("model {}: {} doesn't exist", t.id, path.display()));
}
let gltf: Handle<Gltf> = world.resource::<AssetServer>().load(path.to_string_lossy().to_string());
diff --git a/runtime/scene3d/src/sync.rs b/runtime/scene3d/src/sync.rs
index b401477c..767edf40 100644
--- a/runtime/scene3d/src/sync.rs
+++ b/runtime/scene3d/src/sync.rs
@@ -40,6 +40,13 @@ pub fn sync_pictures(
}
}
+/// A still row's entity whose values sync_meshes or sync_lights has applied: it isn't read again (FrameRows::still).
+#[derive(Component)]
+pub struct StillSynced;
+
+/// The columns sync_meshes applies to a part's material.
+const MATERIAL_COLS: [&str; 6] = ["col_r", "opacity", "emissive_k", "rough", "metal", "sheet_frame"];
+
/// Meshes and models where the frame's rows put them: transform, whether they show, and the material values a row
/// animates. Only columns a row has are applied, so rows written before these columns draw as they did.
#[allow(clippy::type_complexity)]
@@ -60,11 +67,18 @@ pub fn sync_meshes(
Option<&super::decal::DecalStd>,
Option<&raea_sys_shader::Shaded>,
Has<super::SharedMaterial>,
+ Has<StillSynced>,
),
Or<(With<Mesh3d>, With<Model3d>, With<Instanced>)>,
>,
) {
- for (e, mut t, mut vis, mut mat, mut fogged, driven, mut painted, decal, shaded, shared) in &mut q {
+ for (e, mut t, mut vis, mut mat, mut fogged, driven, mut painted, decal, shaded, shared, synced) in &mut q {
+ // a row the same on every frame is applied once (10 000 still cubes made their values every frame); a live
+ // scene's rows are never still
+ let still = frame.still(e);
+ if still && synced {
+ continue;
+ }
let Some(v) = frame.vals(e) else { continue };
let v = &v;
// a mesh a Bevy plugin moves (a rigid body) keeps the plugin's transform (engine/plugins.rs)
@@ -81,7 +95,16 @@ pub fn sync_meshes(
// a painted mesh's standard material is kept aside for this (paint.rs), and a see-through mesh drawn with its froxel
// fog copy (froxel_glass.rs) follows its standard material
// (and a decal's, decal.rs, and a shaded one's, raea-sys-shader)
- let Some(h) = mat.as_ref().map(|m| m.0.clone()).or(painted.as_ref().map(|p| p.std.clone())).or(fogged.as_ref().map(|(f, _)| f.std.clone())).or(decal.map(|d| d.0.clone())).or(shaded.map(|s| s.std.clone())) else { continue };
+ let Some(h) = mat.as_ref().map(|m| m.0.clone()).or(painted.as_ref().map(|p| p.std.clone())).or(fogged.as_ref().map(|(f, _)| f.std.clone())).or(decal.map(|d| d.0.clone())).or(shaded.map(|s| s.std.clone())) else {
+ // no material yet: a still row with material columns waits for one (a painted or shaded copy comes later)
+ if still && !MATERIAL_COLS.iter().any(|k| v.contains_key(*k)) {
+ commands.entity(e).insert(StillSynced);
+ }
+ continue;
+ };
+ if still {
+ commands.entity(e).insert(StillSynced);
+ }
let h = &h;
// a sprite sheet's cell (an ImagePlane's `frame` of its `grid`)
if let Some(fr) = v.get("sheet_frame") {
@@ -164,8 +187,8 @@ pub fn sync_meshes(
/// once, and a row that moves (or moves back) writes every frame it changes. An entity with no entry always writes,
/// so a render seeking straight to frame N places its camera.
#[allow(clippy::type_complexity)]
-pub fn sync_camera(frame: Res<FrameRows>, edit: Option<Res<Edit>>, mut placed: Local<bevy::platform::collections::HashMap<Entity, (Vec3, Vec3)>>, mut q: Query<(Entity, &mut Transform, Option<&mut Projection>, Option<&mut AmbientLight>, Option<&mut bevy::post_process::dof::DepthOfField>, Option<&mut super::lens::Lens>, Option<&mut bevy::post_process::effect_stack::ChromaticAberration>), (With<Camera3d>, Without<super::BareEntity>)>) {
- for (e, mut t, proj, amb, dof, lens, ab) in &mut q {
+pub fn sync_camera(frame: Res<FrameRows>, edit: Option<Res<Edit>>, mut placed: Local<bevy::platform::collections::HashMap<Entity, (Vec3, Vec3)>>, mut q: Query<(Entity, &mut Transform, Option<&mut Projection>, Option<&mut AmbientLight>, Option<&mut bevy::post_process::dof::DepthOfField>, Option<&mut super::lens::Lens>, Option<&mut bevy::post_process::effect_stack::ChromaticAberration>, Option<&mut Camera>), (With<Camera3d>, Without<super::BareEntity>)>) {
+ for (e, mut t, proj, amb, dof, lens, ab, cam) in &mut q {
let Some(v) = frame.vals(e) else { continue };
let v = &v;
let pos = Vec3::new(num(v, "x", 0.0), num(v, "y", 2.0), num(v, "z", 9.0));
@@ -239,21 +262,37 @@ pub fn sync_camera(frame: Res<FrameRows>, edit: Option<Res<Edit>>, mut placed: L
a.brightness = b.num() as f32;
}
}
+ // a clear keyed frame by frame (bg_r..bg_a, sRGB: a holder's background that changes, runtime/export program.rs)
+ if let (Some(r), Some(mut c)) = (v.get("bg_r"), cam) {
+ let want = Color::srgba(r.num() as f32, num(v, "bg_g", 0.0), num(v, "bg_b", 0.0), num(v, "bg_a", 1.0));
+ if !matches!(c.clear_color, ClearColorConfig::Custom(have) if have == want) {
+ c.clear_color = ClearColorConfig::Custom(want);
+ }
+ }
}
}
/// Lights where the frame's rows put them, as bright as they say.
-pub fn sync_lights(frame: Res<FrameRows>, mut q: Query<(Entity, &mut Transform, Option<&mut DirectionalLight>, Option<&mut PointLight>, Option<&mut SpotLight>, Option<&CastsShadows>, Option<&mut bevy::light::RectLight>)>) {
+#[allow(clippy::type_complexity)]
+pub fn sync_lights(frame: Res<FrameRows>, mut commands: Commands, mut q: Query<(Entity, &mut Transform, Option<&mut DirectionalLight>, Option<&mut PointLight>, Option<&mut SpotLight>, Option<&CastsShadows>, Option<&mut bevy::light::RectLight>, Has<StillSynced>)>) {
// a dark light (a frame it isn't in: its power is 0) has its shadow maps off, so no shadow pass is drawn for it. Lit or dark,
// every light stays shown: hiding the dark ones (so Bevy doesn't extract them) put the lit volumetric spots' shafts
// out, as Bevy 0.19's prepare_lights indexes its spot lights past a count of point lights that the hidden ones
// threw off. Dark with its maps on, a film's every shadow-casting light drew them on every frame of every scene
// (the rome film: 20 lights, 4096-texel maps; 2026-10-20)
- for (e, mut t, d, p, s, casts, rect) in &mut q {
+ for (e, mut t, d, p, s, casts, rect, synced) in &mut q {
if d.is_none() && p.is_none() && s.is_none() && rect.is_none() {
continue;
}
+ // a light the same on every frame is applied once, as a still mesh is (100 000 lights made their values each frame)
+ let still = frame.still(e);
+ if still && synced {
+ continue;
+ }
let Some(v) = frame.vals(e) else { continue };
+ if still {
+ commands.entity(e).insert(StillSynced);
+ }
let v = &v;
let pos = Vec3::new(num(v, "x", 0.0), num(v, "y", 0.0), num(v, "z", 0.0));
let dir = Vec3::new(num(v, "dir_x", -0.5), num(v, "dir_y", -1.0), num(v, "dir_z", -0.4));
diff --git a/sdk/app/src/ecs.ts b/sdk/app/src/ecs.ts
index 76db6814..86a472ce 100644
--- a/sdk/app/src/ecs.ts
+++ b/sdk/app/src/ecs.ts
@@ -358,11 +358,21 @@ export class World {
events<T = unknown>(name: string): T[] {
return this.store.events(name) as T[];
}
- /** What draws, straight from the engine's world: Mesh + Transform entities (world space, parents composed) and
- * lights. Only with native tables (`<Entities world={w.at(frame)} />` hands this to the renderer). */
+ /** What draws: Mesh + Transform entities (world space, parents composed) and lights (`<Entities world={w.at(frame)} />`
+ * 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)) throw new Error("scene() needs the engine's tables");
- return native("ecs.scene", { world: this.store.world });
+ if (this.store instanceof NativeStore) return native("ecs.scene", { world: this.store.world });
+ const store = this.store;
+ const out: unknown[] = [];
+ for (const id of store.find({ with: ["Mesh"] })) {
+ const c = store.components(id);
+ let t = transformOf(c.Transform);
+ for (let p = store.parent(id); p !== null; p = store.parent(p)) t = compose(transformOf(store.components(p).Transform), t);
+ out.push({ id, kind: "Mesh", mesh: c.Mesh ?? null, position: [t[0], t[1], t[2]], rotation: [t[3], t[4], t[5]], scale: t[6] });
+ }
+ for (const id of store.find({ with: ["Light"] })) out.push({ id, kind: "Light", light: store.components(id).Light ?? null });
+ return out;
}
/** The engine's id of this world's tables (for the renderer), or null under plain bun. */
get handle(): number | null {
@@ -407,6 +417,24 @@ export class World {
}
/** A new world: native tables in the engine, TypeScript's under plain bun (or with `{ native: false }`). */
+/** [x, y, z, rx, ry, rz, scale] from a Transform component (all optional), as runtime/calls ecs.rs transform_of. */
+function transformOf(t: unknown): number[] {
+ const o = (t ?? {}) as Record<string, unknown>;
+ const g = (k: string, d: number) => (typeof o[k] === "number" ? (o[k] as number) : d);
+ return [g("x", 0), g("y", 0), g("z", 0), g("rx", 0), g("ry", 0), g("rz", 0), g("scale", 1)];
+}
+
+/** a child's transform in its parent's space made world space (rotation by z, then y, then x; uniform scale), as
+ * runtime/calls ecs.rs compose */
+function compose(p: number[], c: number[]): number[] {
+ const [sx, cx, sy, cy, sz, cz] = [Math.sin(p[3]), Math.cos(p[3]), Math.sin(p[4]), Math.cos(p[4]), Math.sin(p[5]), Math.cos(p[5])];
+ let [x, y, z] = [c[0] * p[6], c[1] * p[6], c[2] * p[6]];
+ [x, y] = [x * cz - y * sz, x * sz + y * cz];
+ [x, z] = [x * cy + z * sy, -x * sy + z * cy];
+ [y, z] = [y * cx - z * sx, y * sx + z * cx];
+ return [p[0] + x, p[1] + y, p[2] + z, p[3] + c[3], p[4] + c[4], p[5] + c[5], p[6] * c[6]];
+}
+
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");
diff --git a/sdk/guides/craft/motion/apps.md b/sdk/guides/craft/motion/apps.md
index b0ced301..ed3ee1ae 100644
--- a/sdk/guides/craft/motion/apps.md
+++ b/sdk/guides/craft/motion/apps.md
@@ -3,6 +3,10 @@
What works today. The "not yet" list is the gaps: when one is built, delete its line here.
+This page covers an app inside a composition. An app that is its own program, a window on the web target (Blitz) or
+the native one (Rune) chosen by `export const app = { target }`, is `raea app run|check|bundle`: see the raea skill's
+"Apps: web or native", and `sdk/rune/examples/` for two that pass the check on both targets.
+
- Packages: `raea add @assistant-ui/react` writes `package.json` and `raea.lock` and lays out `node_modules`. raea's own package
manager does it; no Node, npm or bun is needed, and install scripts never run.
- A React library that needs a real DOM (assistant-ui, Radix, shadcn) runs as an app: a module whose default export is
diff --git a/sdk/r3f/README.md b/sdk/r3f/README.md
index 4f20b9fc..241b236d 100644
--- a/sdk/r3f/README.md
+++ b/sdk/r3f/README.md
@@ -24,13 +24,21 @@ In a project, three and @react-three/fiber are its own: `raea add [email protected]
import { Canvas } from "@react-three/fiber";
import { Raea, loadShapes } from "@raea/r3f";
-loadShapes(await import("./raea_shape_web.js")); // solids, Text3D: tools/shape-wasm.sh builds it
+loadShapes(await import("./raea_shape_web.js")); // solids, Text3D: from the release, or tools/shape-wasm.sh
<Canvas shadows><Raea component={Edit} fps={30} /></Canvas>
```
Its camera, tone mapping (raea's default, TonyMcMapface, drawn with Bevy's own table), fog, environment and effects
become the canvas's. Without React, `Scene3d` (`@raea/r3f/three`) draws a raea page into any three.js scene.
+The shape module, `raea_shape_web.js` and `raea_shape_web_bg.wasm`, is attached to each GitHub release from 0.1.0-canary.3
+(`https://github.com/shinyobjectz/raea/releases/download/vVERSION/raea_shape_web.js`). Serve the two files with
+your app: GitHub sends them as downloads, so a page can't import them from there.
+
+What only raea's engine draws (WESL and WGSL shaders, Bevy components and resources, volumetric fog) isn't three.js's
+to draw: `Scene3d` names each one it leaves out. A page that needs them plays the composition with `@raea/web`, raea's
+engine in the browser on WebGPU (`sdk/web/tools/parity.sh` holds each to `raea render`).
+
**raea as R3F source.** Write a composition out as a plain R3F module, with no raea needed to run it:
```sh
diff --git a/sdk/r3f/src/three/kinds.ts b/sdk/r3f/src/three/kinds.ts
index 5219a58d..9fe6372d 100644
--- a/sdk/r3f/src/three/kinds.ts
+++ b/sdk/r3f/src/three/kinds.ts
@@ -69,7 +69,7 @@ export const KINDS: Record<string, { status: Status; three: string; note?: strin
Compute: { status: "engine", three: "a WGSL compute pass runs in Bevy" },
BevyComponent: { status: "engine", three: "a Bevy component (a gizmo's is drawn as lines)" },
BevyResource: { status: "engine", three: "a Bevy resource" },
- Entities: { status: "engine", three: "an ECS world's entities, read from the engine's tables (World.scene() needs them); <Scene world> draws a world's rows as parts the host draws" },
+ Entities: { status: "drawn", three: "a mesh per Mesh entity of World.scene() (its shape, a standard surface of its colour, roughness and metalness, world space), as the engine reads it" },
};
/** the geometry kinds, each a primitive three.js has too */
diff --git a/sdk/r3f/src/three/page.ts b/sdk/r3f/src/three/page.ts
index d8b1b563..10ac178d 100644
--- a/sdk/r3f/src/three/page.ts
+++ b/sdk/r3f/src/three/page.ts
@@ -12,7 +12,8 @@ export function backgroundUnder3d(page: Element): string | undefined {
if (!el.hasAttribute(UNDER)) {
const style = (el as HTMLElement).style;
const bg = el.isConnected && typeof getComputedStyle === "function" ? getComputedStyle(el).backgroundColor : style?.backgroundColor || style?.background;
- if (bg && bg !== "transparent" && !bg.endsWith(", 0)")) el.setAttribute(UNDER, bg);
+ // see-through is rgba(..., 0); rgb(0, 0, 0), black, also ends in ", 0)" and is solid
+ if (bg && bg !== "transparent" && !/^rgba\(.*,\s*0\)$/.test(bg)) el.setAttribute(UNDER, bg);
else continue;
}
clear ??= el.getAttribute(UNDER)!;
diff --git a/sdk/r3f/src/three/scene.ts b/sdk/r3f/src/three/scene.ts
index ece4a02d..74528c2f 100644
--- a/sdk/r3f/src/three/scene.ts
+++ b/sdk/r3f/src/three/scene.ts
@@ -27,6 +27,8 @@ interface Kept {
copies?: ModelPart[];
/** a solid waiting for the shape module */
waiting?: boolean;
+ /** <Entities>: a mesh per entity id, and the shape it was made from */
+ entities?: Map<number, { mesh: THREE.Mesh; shape: string }>;
}
/** what raea's settings make of the renderer: apply() sets them */
@@ -154,6 +156,40 @@ export class Scene3d {
this.hang(k, el, g);
return k;
}
+ case "Entities": {
+ // a world's entities (World.scene(): world space, parents composed): each Mesh entity a mesh of its shape with
+ // a standard surface, as the engine reads them (runtime/react scene/read.rs); its lights aren't drawn there either
+ const g = (k.obj as THREE.Group | undefined) ?? new THREE.Group();
+ this.hang(k, el, g);
+ const kept = (k.entities ??= new Map());
+ const seen = new Set<number>();
+ k.waiting = false;
+ for (const n of (p.scene as { id: number; kind: string; mesh?: Props; position?: number[]; rotation?: number[]; scale?: number }[] | undefined) ?? []) {
+ if (n.kind !== "Mesh") continue;
+ seen.add(n.id);
+ const shape = typeof n.mesh?.shape === "string" ? n.mesh.shape : "";
+ let e = kept.get(n.id);
+ if (!e || e.shape !== shape) {
+ const geometry = geometryOfShape(shape);
+ if (!geometry) {
+ k.waiting = true;
+ this.warnOnce("Entities shape", "is a solid: load raea's shape module (loadShapes) to draw it");
+ continue;
+ }
+ e?.mesh.removeFromParent();
+ const mesh = new THREE.Mesh(geometry, e?.mesh.material ?? new THREE.MeshStandardMaterial());
+ mesh.castShadow = mesh.receiveShadow = true;
+ g.add(mesh);
+ e = { mesh, shape };
+ kept.set(n.id, e);
+ }
+ place(e.mesh, { position: n.position, rotation: n.rotation, scale: n.scale });
+ const { color, roughness, metalness } = n.mesh ?? {};
+ paint(e.mesh.material as THREE.Material, { color, roughness, metalness }, true);
+ }
+ for (const [id, e] of kept) if (!seen.has(id)) (e.mesh.removeFromParent(), kept.delete(id));
+ return k;
+ }
case "Mesh": {
// its shape: a primitive child (three's own), else its data-shape (a buffer, or a solid for the shape module)
const shape = el.getAttribute("data-shape");
diff --git a/sdk/r3f/test/coverage.test.tsx b/sdk/r3f/test/coverage.test.tsx
index b76b4e71..30f4555f 100644
--- a/sdk/r3f/test/coverage.test.tsx
+++ b/sdk/r3f/test/coverage.test.tsx
@@ -70,6 +70,14 @@ describe("raea → three.js coverage", () => {
}
});
+ test("every kind only raea's engine draws has a raea-web parity case (sdk/web/test/parity/cases.ts)", async () => {
+ const { CASES } = await import("../../web/test/parity/cases");
+ const measured = new Set(CASES.flatMap((c: { kinds: string[] }) => c.kinds));
+ const engine = Object.entries(KINDS).filter(([, r]) => r.status === "engine").map(([k]) => k);
+ expect(engine.length).toBeGreaterThan(0);
+ expect(engine.filter((k) => !measured.has(k))).toEqual([]);
+ });
+
test("effects are listed for the app's composer, engine kinds named", () => {
const host = new Scene3d();
host.sync(parse(`<div data-3d="Bloom" data-props="${esc(JSON.stringify({ intensity: 0.3 }))}"></div><div data-3d="Fisheye" data-props="{}"></div>`) as unknown as Element);
diff --git a/sdk/r3f/test/parity/fixtures.tsx b/sdk/r3f/test/parity/fixtures.tsx
index 4bee6702..8c40d4cd 100644
--- a/sdk/r3f/test/parity/fixtures.tsx
+++ b/sdk/r3f/test/parity/fixtures.tsx
@@ -6,8 +6,9 @@ import { useRef, type ReactNode } from "react";
import * as THREE from "three";
import { useCurrentFrame } from "raea";
import {
- Bloom, Cuboid, Grade, LensDistortion, Fog, Sphere, Text3D, ToneMapping, Torus,
+ Bloom, Cuboid, Entities, Grade, LensDistortion, Fog, Sphere, Text3D, ToneMapping, Torus,
} from "raea/3d";
+import { createWorld } from "raea/ecs";
import {
AmbientLight, DirectionalLight, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial,
PerspectiveCamera, PointLight, RectAreaLight, SpotLight,
@@ -249,6 +250,29 @@ function OutCatch() {
);
}
+// an ECS world drawn with no React element per entity (<Entities>): a ship and its gun, turned by a system
+const fleet = createWorld();
+const ship = fleet.add({ Mesh: { shape: "rounded_box(2, 0.6, 1, 0.1)", color: "#2563eb", roughness: 0.5, metalness: 0 }, Transform: { x: 0, y: 0.5, z: 0, ry: 0 } });
+fleet.add({ Mesh: { shape: "cylinder(0.15, 1.2)", color: "#f59e0b", roughness: 0.4, metalness: 0 }, Transform: { x: 0, y: 0.6, z: 0, rx: 0.4 } }, { parent: ship });
+fleet.system((w, f) => w.insert(ship, { Transform: { x: 0, y: 0.5, z: 0, ry: f * 0.05 } }));
+
+function OutEntities() {
+ const f = useCurrentFrame();
+ return (
+ <AbsoluteFill style={{ background: "#0b1020" }}>
+ <PerspectiveCamera position={[0, 2, 6]} lookAt={[0, 0.5, 0]} fov={45} />
+ <ToneMapping mode="aces" />
+ <AmbientLight intensity={0.4} />
+ <DirectionalLight position={[2, 4, 3]} target={[0, 0, 0]} intensity={2} />
+ <Mesh name="ground" rotation={[-Math.PI / 2, 0, 0]}>
+ <Cuboid args={[12, 12, 0.001]} />
+ <MeshStandardMaterial color="#8090a0" roughness={0.9} />
+ </Mesh>
+ <Entities world={fleet.at(f)} />
+ </AbsoluteFill>
+ );
+}
+
export const OUTPUTS: Record<string, { component: () => ReactNode; frame: number }> = {
basic: { component: () => <OutBasic />, frame: 24 },
// raea's default tone mapping, TonyMcMapface
@@ -260,4 +284,6 @@ export const OUTPUTS: Record<string, { component: () => ReactNode; frame: number
lens: { component: () => <OutEffects fx="lens" />, frame: 0 },
// shadow="catch" (three's ShadowMaterial): only the shadow on the floor
catch: { component: OutCatch, frame: 0 },
+ // an ECS world's entities (<Entities>), frame 10 of its system
+ entities: { component: OutEntities, frame: 10 },
};
diff --git a/sdk/r3f/tools/chrome.ts b/sdk/r3f/tools/chrome.ts
index 98e6e6ad..72901f59 100644
--- a/sdk/r3f/tools/chrome.ts
+++ b/sdk/r3f/tools/chrome.ts
@@ -17,12 +17,13 @@ export interface Chrome {
close(): void;
}
-/** Chrome opened on `page` (a file or an http URL) at width x height, `scale` device pixels per CSS px */
-export async function openChrome(page: string, width: number, height: number, opts: { scale?: number; mobile?: boolean; throttle?: number } = {}): Promise<Chrome> {
+/** Chrome opened on `page` (a file or an http URL) at width x height, `scale` device pixels per CSS px; `webgpu` turns on
+ * WebGPU in headless Chrome (sdk/web's raea-web parity) */
+export async function openChrome(page: string, width: number, height: number, opts: { scale?: number; mobile?: boolean; throttle?: number; webgpu?: boolean } = {}): Promise<Chrome> {
const chrome = process.env.CHROME ?? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
const profile = mkdtempSync(resolve(tmpdir(), "raea-playable-chrome-"));
const port = 9300 + Math.floor(Math.random() * 500);
- const proc = Bun.spawn([chrome, "--headless=new", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, "--enable-unsafe-swiftshader", "--no-first-run", "about:blank"], { stdout: "ignore", stderr: "ignore" });
+ const proc = Bun.spawn([chrome, "--headless=new", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, "--enable-unsafe-swiftshader", ...(opts.webgpu ? ["--enable-unsafe-webgpu"] : []), "--no-first-run", "about:blank"], { stdout: "ignore", stderr: "ignore" });
let target: { webSocketDebuggerUrl: string } | undefined;
for (let i = 0; i < 100 && !target; i++) {
diff --git a/sdk/r3f/tools/parity.sh b/sdk/r3f/tools/parity.sh
index 61fdb749..55cff2ad 100755
--- a/sdk/r3f/tools/parity.sh
+++ b/sdk/r3f/tools/parity.sh
@@ -9,7 +9,7 @@ OUT=${1:-$(mktemp -d)}
URL=${R3F_PARITY_URL:-serve}
[ -f wasm/raea_shape_web.js ] || tools/shape-wasm.sh
MIN=${MIN:-0.92}
-CASES=(in-basic:24 in-lights:0 in-things:0 in-catch:0 out-basic:24 out-tony:24 out-lights:0 out-bloom:0 out-grade:0 out-lens:0 out-catch:0 src-basic:24 src-tony:24 src-lights:0 src-bloom:0 src-grade:0 src-lens:0 src-catch:0)
+CASES=(in-basic:24 in-lights:0 in-things:0 in-catch:0 out-basic:24 out-tony:24 out-lights:0 out-bloom:0 out-grade:0 out-lens:0 out-catch:0 out-entities:10 src-basic:24 src-tony:24 src-lights:0 src-bloom:0 src-grade:0 src-lens:0 src-catch:0 src-entities:10)
mkdir -p "$OUT"
for c in "${CASES[@]}"; do
# a src-* case is its out-* composition, drawn from the R3F source the source export wrote for it
diff --git a/sdk/r3f/tools/shoot.ts b/sdk/r3f/tools/shoot.ts
index 2bc6127b..a8924dd1 100644
--- a/sdk/r3f/tools/shoot.ts
+++ b/sdk/r3f/tools/shoot.ts
@@ -8,7 +8,7 @@ const [baseArg, out, ...only] = process.argv.slice(2);
if (!baseArg || !out) throw new Error("usage: bun tools/shoot.ts BASE_URL|serve OUT_DIR [in-basic ...]");
const served = baseArg === "serve" ? await serve() : undefined;
const base = served?.url ?? baseArg;
-const cases = only.length ? only : ["in-basic", "in-lights", "in-things", "in-catch", "out-basic", "out-tony", "out-lights", "out-bloom", "out-grade", "out-lens", "out-catch", "src-basic", "src-tony", "src-lights", "src-bloom", "src-grade", "src-lens", "src-catch"];
+const cases = only.length ? only : ["in-basic", "in-lights", "in-things", "in-catch", "out-basic", "out-tony", "out-lights", "out-bloom", "out-grade", "out-lens", "out-catch", "out-entities", "src-basic", "src-tony", "src-lights", "src-bloom", "src-grade", "src-lens", "src-catch", "src-entities"];
let failed = 0;
for (const c of cases) {
const [dir, name] = c.split("-");
diff --git a/sdk/raea/bench/bevy-parity/.gitignore b/sdk/raea/bench/bevy-parity/.gitignore
new file mode 100644
index 00000000..cf4b6263
--- /dev/null
+++ b/sdk/raea/bench/bevy-parity/.gitignore
@@ -0,0 +1,2 @@
+# Bevy's assets, linked by tools/bevy-parity
+*/assets
diff --git a/sdk/raea/bench/bevy-parity/stress_tests/many_cubes.tsx b/sdk/raea/bench/bevy-parity/stress_tests/many_cubes.tsx
index 35e210fd..b63303dd 100644
--- a/sdk/raea/bench/bevy-parity/stress_tests/many_cubes.tsx
+++ b/sdk/raea/bench/bevy-parity/stress_tests/many_cubes.tsx
@@ -24,23 +24,35 @@ const places: [number, number, number][] = Array.from({ length: N }, (_, i) => {
return [Math.cos(theta) * Math.sin(phi) * RADIUS, Math.sin(theta) * Math.sin(phi) * RADIUS, Math.cos(phi) * RADIUS];
});
-function Shot() {
+// the example's move_camera system: only the camera reads the clock, as only that system touches it each update
+function Rig() {
const f = useCurrentFrame();
- // rotate_z then rotate_x each update, about the world's axes: q = (Rx(d) * Rz(d))^(f + 1)
+ // rotate_z then rotate_x each update, about the world's axes: q = (Rx(d) * Rz(d))^(f + 1) (--benchmark turns a fixed 1/60 s each update, the first too)
const d = 0.15 / 60;
const step = Quat.mul(Quat.fromRotationX(d), Quat.fromRotationZ(d));
let q = Quat.IDENTITY;
for (let k = 0; k <= f; k++) q = Quat.mul(step, q);
+ return <Camera3d transform={{ translation: [0, 0, 0], rotation: q }} />;
+}
+
+// the example's setup: spawned once, never touched again
+const Cubes = () => (
+ <>
+ {places.map((p, i) => (
+ <Mesh3d key={i} transform={Transform.fromXyz(p[0], p[1], p[2]).lookingAt([0, 0, 0])}>
+ <Cuboid half_size={[H, H, H]} />
+ <StandardMaterial base_color="#ffffff" />
+ </Mesh3d>
+ ))}
+ </>
+);
+
+function Shot() {
return (
<>
- <Camera3d transform={{ translation: [0, 0, 0], rotation: q }} />
+ <Rig />
<DirectionalLight transform={Transform.fromXyz(0, 0, 0).lookingAt([0, -1, -1])} />
- {places.map((p, i) => (
- <Mesh3d key={i} transform={Transform.fromXyz(p[0], p[1], p[2]).lookingAt([0, 0, 0])}>
- <Cuboid half_size={[H, H, H]} />
- <StandardMaterial base_color="#ffffff" />
- </Mesh3d>
- ))}
+ <Cubes />
<Mesh3d transform={{ translation: [0, 0, 0], scale: [-1, -1, -1] }}>
<Cuboid half_size={[RADIUS * 1.1, RADIUS * 1.1, RADIUS * 1.1]} />
<StandardMaterial base_color="#ffffff" />
diff --git a/sdk/raea/bench/bevy-parity/stress_tests/many_foxes.tsx b/sdk/raea/bench/bevy-parity/stress_tests/many_foxes.tsx
new file mode 100644
index 00000000..01fb2b29
--- /dev/null
+++ b/sdk/raea/bench/bevy-parity/stress_tests/many_foxes.tsx
@@ -0,0 +1,69 @@
+// Bevy v0.20.0 examples/stress_tests/many_foxes.rs in raea's TSX (docs/control.feature FC1a), run --sync (every fox
+// starts its clip at 0; without it each starts at its entity's index / 10, which is Bevy's allocator's): 1000 animated
+// foxes (models/animated/Fox.glb, its Run clip, Animation(2)) in rings 2 m apart, each ring turning at 2 m/s the other
+// way to the last, on a 5000 m green plane under a shadow-casting sun, in a 1920 x 1080 window.
+import { Composition, registerRoot, staticFile, useCurrentFrame } from "raea";
+import { Entity, Model } from "raea/3d";
+import { Quat, Transform } from "raea/transform";
+import { Camera3d } from "raea/camera";
+import { Mesh3d, Plane3d } from "raea/mesh";
+import { StandardMaterial } from "raea/pbr";
+import { DirectionalLight, Shadows } from "raea/light";
+
+const COUNT = 1000;
+const RING_SPACING = 2;
+const FOX_SPACING = 2;
+const SPEED = 2;
+const FOX = staticFile("models/animated/Fox.glb");
+
+type Fox = { x: number; z: number; rotation: [number, number, number, number] };
+type Ring = { radius: number; sign: number; foxes: Fox[] };
+
+// the example's setup: rings out from 2 m, as many foxes as fit 2 m apart, until 1000 are placed
+const rings: Ring[] = [];
+let radius = RING_SPACING;
+for (let left = COUNT, i = 0; left > 0; i++) {
+ const base = i % 2 === 0 ? Quat.fromRotationY(Math.PI) : Quat.IDENTITY;
+ const circumference = Math.PI * 2 * radius;
+ const n = Math.min(Math.floor(Math.fround(circumference / FOX_SPACING)), left);
+ const step = circumference / (n * radius);
+ const foxes = Array.from({ length: n }, (_, k) => {
+ const a = k * step;
+ return { x: radius * Math.cos(a), z: radius * Math.sin(a), rotation: Quat.mul(base, Quat.fromRotationY(-a)) };
+ });
+ rings.push({ radius, sign: i % 2 === 0 ? 1 : -1, foxes });
+ left -= n;
+ radius += RING_SPACING;
+}
+const zoom = 0.8;
+const eye: [number, number, number] = [radius * 1.25 * zoom, radius * 0.5 * zoom, radius * 1.5 * zoom];
+
+function Shot() {
+ const f = useCurrentFrame();
+ // update_fox_rings turns each ring by the update's delta_secs (none on the first), and each fox's AnimationPlayer
+ // advances its clip by the same, from the first update (offsets of -1 to 8 frames scored 0.95-0.974 against 0.990)
+ const t = f / 60;
+ return (
+ <>
+ <Camera3d transform={Transform.fromTranslation(eye).lookingAt([0.2 * eye[0], 0, 0.2 * eye[2]])} />
+ {rings.map((r, i) => (
+ <Entity key={i} transform={{ rotation: Quat.fromRotationY(r.sign * (SPEED / r.radius) * t) }}>
+ {r.foxes.map((x, k) => (
+ <Entity key={k} transform={{ translation: [x.x, 0, x.z], rotation: x.rotation, scale: [0.01, 0.01, 0.01] }}>
+ <Model src={FOX} animation={2} time={t} />
+ </Entity>
+ ))}
+ </Entity>
+ ))}
+ <Mesh3d transform={Transform.IDENTITY}>
+ <Plane3d half_size={[2500, 2500]} />
+ <StandardMaterial base_color="rgb(76.5, 127.5, 76.5)" />
+ </Mesh3d>
+ {/* Bevy's default 2048-texel maps; its CascadeShadowConfigBuilder's 4 cascades, 0.2 overlap */}
+ <Shadows mapSize={2048} firstCascade={0.9 * radius} distance={2.8 * radius} cascades={4} overlap={0.2} />
+ <DirectionalLight shadow_maps_enabled transform={{ translation: [0, 0, 0], rotation: Quat.fromEuler("ZYX", 0, 1, -Math.PI / 4), scale: [1, 1, 1] }} />
+ </>
+ );
+}
+
+registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1920} height={1080} />);
diff --git a/sdk/raea/bench/bevy-parity/stress_tests/many_lights.tsx b/sdk/raea/bench/bevy-parity/stress_tests/many_lights.tsx
new file mode 100644
index 00000000..ee67863b
--- /dev/null
+++ b/sdk/raea/bench/bevy-parity/stress_tests/many_lights.tsx
@@ -0,0 +1,74 @@
+// Bevy v0.20.0 examples/stress_tests/many_lights.rs, written in raea's TSX the way an author would (docs/control.feature
+// FC0a), run by tools/bevy-parity beside the Rust example: an inside-out white icosphere (9 subdivisions) of radius 50, 100 000 point lights
+// on it (range 0.3, 1000 lumens) along a Fibonacci spiral, a deep pink cube five metres across at its top, and the
+// camera at the centre turning 0.15 rad a frame-second about Z then X. The example draws each light's hue at random
+// from an unseeded rng; bench/bevy-parity's build.rs makes the n-th the golden angle times n, as here (SEEDED).
+// Frame n here is the example's update n.
+import { Composition, registerRoot, useCurrentFrame } from "raea";
+
+import { Transform, Quat } from "raea/transform";
+import { Camera3d } from "raea/camera";
+import { Cuboid, Mesh3d, Sphere } from "raea/mesh";
+import { StandardMaterial } from "raea/pbr";
+import { PointLight } from "raea/light";
+
+const LIGHT_RADIUS = 0.3;
+const LIGHT_INTENSITY = 1000;
+const RADIUS = 50;
+const N_LIGHTS = 100_000;
+const GOLDEN = 0.5 * (1 + Math.sqrt(5));
+const EPSILON = 0.36;
+
+/** hsl(h, 1, 0.5) as hex, as Bevy's Color::hsl makes it (sRGB) */
+function hsl(h: number): string {
+ const f = (n: number) => {
+ const k = (n + h / 30) % 12;
+ return 0.5 - 0.5 * Math.max(-1, Math.min(k - 3, 9 - k, 1));
+ };
+ return "#" + [f(0), f(8), f(4)].map((c) => Math.round(c * 255).toString(16).padStart(2, "0")).join("");
+}
+
+const lights = Array.from({ length: N_LIGHTS }, (_, i) => {
+ const theta = Math.PI * 2 * (i / GOLDEN);
+ // the example takes acos in f32
+ const phi = Math.acos(Math.fround(1 - (2 * (i + EPSILON)) / (N_LIGHTS - 1 + 2 * EPSILON)));
+ const p: [number, number, number] = [Math.cos(theta) * Math.sin(phi) * RADIUS, Math.sin(theta) * Math.sin(phi) * RADIUS, Math.cos(phi) * RADIUS];
+ return { p, color: hsl((i * 137.50776405003785) % 360) };
+});
+
+// the example's move_camera system: only the camera reads the clock
+function Rig() {
+ const f = useCurrentFrame();
+ // rotate_z then rotate_x each update, about the world's axes: q = (Rx(d) * Rz(d))^f (it turns by the update's delta_secs, none on the first: f turns at frame f; the f + 1 form matched one frame early, SSIM 0.99996)
+ const d = 0.15 / 60;
+ const step = Quat.mul(Quat.fromRotationX(d), Quat.fromRotationZ(d));
+ let q = Quat.IDENTITY;
+ for (let k = 0; k < f; k++) q = Quat.mul(step, q);
+ return <Camera3d transform={{ translation: [0, 0, 0], rotation: q }} />;
+}
+
+// the example's setup: spawned once, never touched again
+const Scene = () => (
+ <>
+ <Mesh3d transform={{ translation: [0, 0, 0], scale: [-1, -1, -1] }}>
+ <Sphere radius={RADIUS} ico={9} />
+ <StandardMaterial base_color="#ffffff" />
+ </Mesh3d>
+ {lights.map((l, i) => (
+ <PointLight key={i} transform={Transform.fromXyz(l.p[0], l.p[1], l.p[2])} range={LIGHT_RADIUS} intensity={LIGHT_INTENSITY} color={l.color} />
+ ))}
+ <Mesh3d transform={{ translation: [0, RADIUS, 0], scale: [5, 5, 5] }}>
+ <Cuboid half_size={[0.5, 0.5, 0.5]} />
+ <StandardMaterial base_color="#ff1493" />
+ </Mesh3d>
+ </>
+);
+
+const Shot = () => (
+ <>
+ <Rig />
+ <Scene />
+ </>
+);
+
+registerRoot(() => <Composition id="main" component={Shot} durationInFrames={121} fps={60} width={1920} height={1080} />);
diff --git a/sdk/raea/conformance/ambient-zero.test.tsx b/sdk/raea/conformance/ambient-zero.test.tsx
new file mode 100644
index 00000000..ada1b923
--- /dev/null
+++ b/sdk/raea/conformance/ambient-zero.test.tsx
@@ -0,0 +1,29 @@
+// An AmbientLight of brightness 0 turns the ambient off, as Bevy's does: it is not dropped for the camera's default 80
+// (runtime/look/src/camera.rs). Runs where the release binary and ffmpeg are built and on PATH.
+import { expect, test } from "bun:test";
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const BIN = process.env.RAEA_BIN ?? join(import.meta.dir, "../../../target/release/raea");
+const ffmpeg = Bun.which("ffmpeg");
+
+/** the frame's centre pixel, RGB */
+function centre(id: string, dir: string): number[] {
+ const png = join(dir, `${id}.png`);
+ const r = Bun.spawnSync([BIN, "render", join(import.meta.dir, "ambient-zero/scene.tsx"), "--composition", id, "--frame", "0", "-o", png], { stderr: "pipe" });
+ expect(r.exitCode).toBe(0);
+ const px = new Uint8Array(Bun.spawnSync([ffmpeg!, "-v", "error", "-i", png, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]).stdout);
+ const i = (45 * 160 + 80) * 3;
+ return [...px.subarray(i, i + 3)];
+}
+
+test.skipIf(!existsSync(BIN) || !ffmpeg)("AmbientLight brightness 0 leaves an unlit box black; 80 lights it", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ambient-zero-"));
+ try {
+ expect(Math.max(...centre("dark", dir))).toBeLessThan(8);
+ expect(Math.min(...centre("lit", dir))).toBeGreaterThan(40);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}, 120_000);
diff --git a/sdk/raea/conformance/ambient-zero/scene.tsx b/sdk/raea/conformance/ambient-zero/scene.tsx
new file mode 100644
index 00000000..e1b3994e
--- /dev/null
+++ b/sdk/raea/conformance/ambient-zero/scene.tsx
@@ -0,0 +1,26 @@
+// A white box filling the view, lit only by an AmbientLight: brightness 0 in "dark", Bevy's 80 in "lit"
+// (ambient-zero.test.tsx).
+import { Composition, registerRoot } from "raea";
+import { Camera3d } from "raea/camera";
+import { AmbientLight } from "raea/light";
+import { Cuboid, Mesh3d } from "raea/mesh";
+import { StandardMaterial } from "raea/pbr";
+import { Transform } from "raea/transform";
+
+const Shot = ({ brightness }: { brightness: number }) => (
+ <>
+ <Camera3d transform={Transform.IDENTITY} />
+ <AmbientLight brightness={brightness} />
+ <Mesh3d transform={Transform.fromXyz(0, 0, -5)}>
+ <Cuboid half_size={[3, 3, 3]} />
+ <StandardMaterial base_color="#ffffff" />
+ </Mesh3d>
+ </>
+);
+
+registerRoot(() => (
+ <>
+ <Composition id="dark" component={() => <Shot brightness={0} />} durationInFrames={1} fps={30} width={160} height={90} />
+ <Composition id="lit" component={() => <Shot brightness={80} />} durationInFrames={1} fps={30} width={160} height={90} />
+ </>
+));
diff --git a/sdk/raea/conformance/animate-held.test.tsx b/sdk/raea/conformance/animate-held.test.tsx
new file mode 100644
index 00000000..9a48393d
--- /dev/null
+++ b/sdk/raea/conformance/animate-held.test.tsx
@@ -0,0 +1,23 @@
+// An <Animate> that React renders once is still sampled on every frame by the engine (runtime/react animate.rs, which
+// visits only the elements whose props changed and the animated ones). Runs where the release binary and ffmpeg are
+// built and on PATH.
+import { expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const BIN = process.env.RAEA_BIN ?? join(import.meta.dir, "../../../target/release/raea");
+const ffmpeg = Bun.which("ffmpeg");
+
+test.skipIf(!existsSync(BIN) || !ffmpeg)("a box fading in over frames 0-6 is black at frame 0 and white at frame 12", () => {
+ const dir = mkdtempSync(join(tmpdir(), "animate-held-"));
+ try {
+ const r = Bun.spawnSync([BIN, "render", join(import.meta.dir, "animate-held/fade.tsx"), "--composition", "main", "--at", "0,12", "-o", dir], { stderr: "pipe" });
+ expect(r.exitCode).toBe(0);
+ const grey = readdirSync(dir).filter((f) => f.endsWith(".png")).sort().map((f) => new Uint8Array(Bun.spawnSync([ffmpeg!, "-v", "error", "-i", join(dir, f), "-f", "rawvideo", "-pix_fmt", "gray", "-"]).stdout)[0]);
+ expect(grey[0]).toBeLessThan(20);
+ expect(grey[1]).toBeGreaterThan(235);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}, 120_000);
diff --git a/sdk/raea/conformance/animate-held/fade.tsx b/sdk/raea/conformance/animate-held/fade.tsx
new file mode 100644
index 00000000..8782c24a
--- /dev/null
+++ b/sdk/raea/conformance/animate-held/fade.tsx
@@ -0,0 +1,11 @@
+// A white box that fades in over frames 0-6 with <Animate enter="fade"> (animate-held.test.tsx): React renders it once
+// and never again, so the engine samples it each frame (runtime/react animate.rs) though its props don't change.
+import { Animate, Composition, registerRoot } from "raea";
+
+const Shot = () => (
+ <div style={{ position: "absolute", inset: 0, background: "#000000" }}>
+ <Animate enter="fade" style={{ position: "absolute", inset: 0, background: "#ffffff" }} />
+ </div>
+);
+
+registerRoot(() => <Composition id="main" component={Shot} durationInFrames={20} fps={30} width={160} height={90} />);
diff --git a/sdk/raea/conformance/holder-clear.test.tsx b/sdk/raea/conformance/holder-clear.test.tsx
new file mode 100644
index 00000000..321f3fad
--- /dev/null
+++ b/sdk/raea/conformance/holder-clear.test.tsx
@@ -0,0 +1,45 @@
+// The 3D clears to its nearest holder's background, and a holder's new background is seen on the frame it changes:
+// the holders are kept across frames and worked out again when a holder's props change (runtime/react holders.rs
+// HolderCache). Runs where the release binary and ffmpeg are built and on PATH.
+import { expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const BIN = process.env.RAEA_BIN ?? join(import.meta.dir, "../../../target/release/raea");
+const ffmpeg = Bun.which("ffmpeg");
+
+/** a PNG's top-left pixel, RGB */
+function corner(png: string): number[] {
+ const px = new Uint8Array(Bun.spawnSync([ffmpeg!, "-v", "error", "-i", png, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]).stdout);
+ return [...px.subarray(0, 3)];
+}
+
+/** frames 2 and 8 of one of holder-clear's scenes, each as its top-left pixel */
+function corners(scene: string): number[][] {
+ const dir = mkdtempSync(join(tmpdir(), "holder-clear-"));
+ try {
+ const r = Bun.spawnSync([BIN, "render", join(import.meta.dir, "holder-clear", scene), "--composition", "main", "--at", "2,8", "-o", dir], { stderr: "pipe" });
+ expect(r.exitCode).toBe(0);
+ return readdirSync(dir).filter((f) => f.endsWith(".png")).sort().map((f) => corner(join(dir, f)));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+function redThenBlue([before, after]: number[][]) {
+ expect(before[0]).toBeGreaterThan(200);
+ expect(before[2]).toBeLessThan(40);
+ expect(after[2]).toBeGreaterThan(200);
+ expect(after[0]).toBeLessThan(40);
+}
+
+test.skipIf(!existsSync(BIN) || !ffmpeg)("a holder's background turning blue at frame 5 clears the 3D blue from frame 5", () => {
+ redThenBlue(corners("scene.tsx"));
+}, 120_000);
+
+// the holders kept across frames: a 3D that moves to another holder clears to the new one (before, a commit's move
+// carried the tick the watch had just read at, so it was never seen and frame 8 cleared red)
+test.skipIf(!existsSync(BIN) || !ffmpeg)("a 3D moved at frame 5 from a red holder to a blue one clears blue from frame 5", () => {
+ redThenBlue(corners("moved.tsx"));
+}, 120_000);
diff --git a/sdk/raea/conformance/holder-clear/moved.tsx b/sdk/raea/conformance/holder-clear/moved.tsx
new file mode 100644
index 00000000..c1ef8202
--- /dev/null
+++ b/sdk/raea/conformance/holder-clear/moved.tsx
@@ -0,0 +1,29 @@
+// The 3D moved at frame 5 from under a red page element to under a blue one (holder-clear.test.tsx): the holders are
+// worked out again when the page's elements move, so the 3D clears to its new holder's background.
+import { Composition, registerRoot, useCurrentFrame } from "raea";
+import { Camera3d } from "raea/camera";
+import { Cuboid, Mesh3d } from "raea/mesh";
+import { StandardMaterial } from "raea/pbr";
+import { Transform } from "raea/transform";
+
+const Cube = () => (
+ <>
+ <Camera3d transform={Transform.IDENTITY} />
+ <Mesh3d transform={Transform.fromXyz(0, 0, -5)}>
+ <Cuboid half_size={[0.5, 0.5, 0.5]} />
+ <StandardMaterial base_color="#ffffff" />
+ </Mesh3d>
+ </>
+);
+
+const Shot = () => {
+ const f = useCurrentFrame();
+ return (
+ <>
+ <div key="red" style={{ position: "absolute", left: 0, top: 0, width: 0, height: 0, background: "#ff0000" }}>{f < 5 ? <Cube /> : null}</div>
+ <div key="blue" style={{ position: "absolute", left: 0, top: 0, width: 0, height: 0, background: "#0000ff" }}>{f < 5 ? null : <Cube />}</div>
+ </>
+ );
+};
+
+registerRoot(() => <Composition id="main" component={Shot} durationInFrames={10} fps={30} width={160} height={90} />);
diff --git a/sdk/raea/conformance/holder-clear/scene.tsx b/sdk/raea/conformance/holder-clear/scene.tsx
new file mode 100644
index 00000000..a7e61ee0
--- /dev/null
+++ b/sdk/raea/conformance/holder-clear/scene.tsx
@@ -0,0 +1,22 @@
+// A 3D shot under a page element whose background turns from red to blue at frame 5 (holder-clear.test.tsx): the
+// 3D clears to its holder's background, frame by frame.
+import { Composition, registerRoot, useCurrentFrame } from "raea";
+import { Camera3d } from "raea/camera";
+import { Cuboid, Mesh3d } from "raea/mesh";
+import { StandardMaterial } from "raea/pbr";
+import { Transform } from "raea/transform";
+
+const Shot = () => {
+ const f = useCurrentFrame();
+ return (
+ <div style={{ position: "absolute", inset: 0, background: f < 5 ? "#ff0000" : "#0000ff" }}>
+ <Camera3d transform={Transform.IDENTITY} />
+ <Mesh3d transform={Transform.fromXyz(0, 0, -5)}>
+ <Cuboid half_size={[0.5, 0.5, 0.5]} />
+ <StandardMaterial base_color="#ffffff" />
+ </Mesh3d>
+ </div>
+ );
+};
+
+registerRoot(() => <Composition id="main" component={Shot} durationInFrames={10} fps={30} width={160} height={90} />);
diff --git a/sdk/render/src/3d/shapes.tsx b/sdk/render/src/3d/shapes.tsx
index 914fc63b..646b298a 100644
--- a/sdk/render/src/3d/shapes.tsx
+++ b/sdk/render/src/3d/shapes.tsx
@@ -33,8 +33,9 @@ export interface BoxProps { args?: [number, number, number] }
/** Bevy's Cuboid: half its size along each axis ([0.5, 0.5, 0.5], a 1 m cube, as Bevy's default). */
export interface CuboidProps { half_size?: [number, number, number] }
-/** `args`, or Bevy's Sphere field: radius (0.5 by Bevy's default). */
-export interface SphereProps { args?: [number]; radius?: number }
+/** `args`, or Bevy's Sphere field: radius (0.5 by Bevy's default). Its mesh is Bevy's Sphere::mesh(): an icosphere of 5
+ * subdivisions, or `ico` of them (Bevy's `.ico(n)`, 0 to 80), or a UV sphere of `uv` = [sectors, stacks] (`.uv(s, t)`). */
+export interface SphereProps { args?: [number]; radius?: number; ico?: number; uv?: [number, number] }
export interface PlaneProps { args?: [number, number] }
@@ -73,16 +74,16 @@ interface BevyShape<P> {
args: (p: P) => number[];
}
-function geometry<P extends { args?: number[] }>(name: string, defaults: number[], shape: (a: number[]) => string, bevy?: BevyShape<P>, display = name) {
+function geometry<P extends { args?: number[] }>(name: string, defaults: number[], shape: (a: number[], props: P) => string, bevy?: BevyShape<P>, display = name) {
const own = (props: P) => bevy !== undefined && bevy.keys.some((k) => (props as Record<string, unknown>)[k] !== undefined);
const argsOf = (props: P) => {
if (own(props) && props.args !== undefined) throw new TypeError(`${display}: args or Bevy's fields (${bevy!.keys.join(", ")}), not both`);
return checkArgs(display, own(props) ? bevy!.args(props) : (props.args ?? defaults), defaults.length);
};
- const toShape = (props: Record<string, unknown>) => shape(argsOf(props as P));
+ const toShape = (props: Record<string, unknown>) => shape(argsOf(props as P), props as P);
const Component = (props: P) => {
const args = argsOf(props);
- shape(args);
+ shape(args, props);
const rest = own(props) ? Object.fromEntries(Object.entries(props).filter(([k]) => !bevy!.keys.includes(k))) : props;
return node3d(name, { ...rest, args });
};
@@ -106,7 +107,22 @@ function fromSize(size: [number, number, number]): Required<CuboidProps> {
export const Cuboid = /* @__PURE__ */ Object.assign(CuboidShape, { fromSize });
-export const Sphere = /* @__PURE__ */ geometry<SphereProps>("Sphere", [1], (a) => `sphere(${list(a)})`, { keys: ["radius"], args: (p) => [p.radius ?? 0.5] });
+/** A sphere's expression: sphere(r), sphere(r, ico n) as sphere(r, n), or uv_sphere(r, sectors, stacks). */
+function sphereOf(r: number, p: SphereProps): string {
+ if (p.ico !== undefined && p.uv !== undefined) throw new TypeError("Sphere: ico or uv, not both");
+ if (p.ico !== undefined) {
+ if (!Number.isInteger(p.ico) || p.ico < 0 || p.ico > 80) throw new TypeError(`Sphere: ico is a whole number of subdivisions from 0 to 80, not ${p.ico}`);
+ return `sphere(${r}, ${p.ico})`;
+ }
+ if (p.uv !== undefined) {
+ const [s, t] = p.uv;
+ if (!Number.isInteger(s) || !Number.isInteger(t) || s < 3 || t < 2) throw new TypeError(`Sphere: uv is [sectors, stacks], whole numbers, at least [3, 2], not [${p.uv}]`);
+ return `uv_sphere(${r}, ${s}, ${t})`;
+ }
+ return `sphere(${r})`;
+}
+
+export const Sphere = /* @__PURE__ */ geometry<SphereProps>("Sphere", [1], (a, p) => `${sphereOf(a[0], p)}`, { keys: ["radius", "ico", "uv"], args: (p) => [p.radius ?? 0.5] });
/** @deprecated <Plane3d>, raea/mesh */
export const Plane = /* @__PURE__ */ geometry<PlaneProps>("Plane", [1, 1], (a) => `box(${list(a)}, 0)`);
diff --git a/sdk/rune/examples/signin.tsx b/sdk/rune/examples/signin.tsx
new file mode 100644
index 00000000..757fb386
--- /dev/null
+++ b/sdk/rune/examples/signin.tsx
@@ -0,0 +1,67 @@
+// A sign-in card styled only by Tailwind classes, for both targets (docs/targets.feature T5a): fields that ring on
+// focus, a checkbox that shows a focus-visible ring when Tab reaches it, a submit that stays disabled until the form is
+// ready, md: putting the two fields side by side, and dark: for the system's appearance. The submit springs on "snap"
+// in Rune; on the web that is a CSS transition (@raea/rune's web.css).
+import { useState } from "react";
+import { rune } from "../src/index.ts";
+
+const field =
+ "h-9 w-full rounded-md border border-zinc-300 bg-white px-3 text-sm text-zinc-900 outline-none hover:border-zinc-400 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-50";
+
+function Field({ id, name, value, set }: { id: string; name: string; value: string; set: (v: string) => void }) {
+ return (
+ <div data-testid={`${id}-row`} className="flex flex-1 flex-col gap-1.5">
+ <span className="text-sm font-medium text-zinc-700 dark:text-zinc-300">{name}</span>
+ <input data-testid={id} value={value} onChange={(e) => set((e.target as HTMLInputElement).value)} className={field} />
+ </div>
+ );
+}
+
+export default function SignIn() {
+ const [email, setEmail] = useState("");
+ const [code, setCode] = useState("");
+ const [remember, setRemember] = useState(false);
+ const [signedIn, setSignedIn] = useState(false);
+ const ready = email.includes("@") && code.length === 6;
+ return (
+ <div data-testid="page" className="flex min-h-screen flex-col items-center bg-zinc-50 p-6 dark:bg-zinc-950">
+ <div data-testid="card" className="flex w-full max-w-lg flex-col gap-5 rounded-xl border border-zinc-200 bg-white p-6 shadow-sm dark:border-zinc-800 dark:bg-zinc-900">
+ <span data-testid="title" className="text-lg font-semibold text-zinc-900 dark:text-zinc-50">
+ {signedIn ? `Signed in as ${email}` : "Sign in"}
+ </span>
+ <div data-testid="fields" className="flex flex-col gap-4 md:flex-row">
+ <Field id="email" name="Email" value={email} set={setEmail} />
+ <Field id="code" name="Six-digit code" value={code} set={setCode} />
+ </div>
+ <div
+ data-testid="remember"
+ role="checkbox"
+ aria-checked={remember}
+ tabIndex={0}
+ onClick={() => setRemember(!remember)}
+ className="flex flex-row items-center gap-2 rounded-md p-1 hover:bg-zinc-100 focus-visible:ring-2 focus-visible:ring-blue-500 dark:hover:bg-zinc-800"
+ >
+ <div data-testid="box" className={`size-4 rounded border ${remember ? "border-blue-600 bg-blue-600" : "border-zinc-400 bg-white dark:border-zinc-600"}`} />
+ <span className="text-sm text-zinc-700 dark:text-zinc-300">Remember this device</span>
+ </div>
+ <button
+ data-testid="submit"
+ disabled={!ready}
+ onClick={ready ? () => setSignedIn(true) : undefined}
+ className="h-9 rounded-md bg-zinc-900 px-4 text-sm font-medium text-white hover:bg-zinc-700 disabled:opacity-50 dark:bg-zinc-50 dark:text-zinc-900"
+ {...rune({ motion: "snap" })}
+ >
+ Sign in
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export const steps = [
+ { type: "[email protected]", into: "email" },
+ { type: "123456", into: "code" },
+ { key: "Tab" },
+ { press: "remember" },
+ { press: "submit" },
+];
diff --git a/sdk/rune/gen-css.ts b/sdk/rune/gen-css.ts
new file mode 100644
index 00000000..97f2f9b9
--- /dev/null
+++ b/sdk/rune/gen-css.ts
@@ -0,0 +1,52 @@
+// Writes src/web.css: the CSS fallbacks for Rune's props on the web target (src/web.ts, docs/targets.feature T4b).
+// bun sdk/rune/gen-css.ts (src/web.css is committed; a test checks it's what this writes)
+import { ENTERS, MAX_BLUR, PRESETS } from "./src/web.ts";
+
+/** A spring as a cubic-bezier: a critically damped one eases out; a bouncy one overshoots by its bounce. */
+const ease = (bounce: number) => (bounce > 0 ? `cubic-bezier(0.34, ${(1 + bounce * 3).toFixed(2)}, 0.64, 1)` : "cubic-bezier(0.2, 0, 0, 1)");
+
+const ms = (s: number) => `${Math.round(s * 1000)}ms`;
+
+/** Each entrance's first frame, as Rune's preset transitions start (rune-motion transition.rs). */
+const FROM: Record<(typeof ENTERS)[number], string> = {
+ none: "",
+ opacity: "opacity: 0;",
+ slide: "transform: translateX(-100%);",
+ blurReplace: "opacity: 0; transform: scale(0.96); filter: blur(1.5px);",
+ "move-top": "transform: translateY(-100%);",
+ "move-bottom": "transform: translateY(100%);",
+ "move-leading": "transform: translateX(-100%);",
+ "move-trailing": "transform: translateX(100%);",
+ "push-top": "opacity: 0; transform: translateY(-100%);",
+ "push-bottom": "opacity: 0; transform: translateY(100%);",
+ "push-leading": "opacity: 0; transform: translateX(-100%);",
+ "push-trailing": "opacity: 0; transform: translateX(100%);",
+};
+
+export function css(): string {
+ const out = ["/* @raea/rune on the web target (docs/targets.feature T4b): written by gen-css.ts, don't edit. */"];
+ const props = "opacity, transform, translate, scale, rotate, width, height, background-color, color, border-color, box-shadow, filter";
+ for (const [name, p] of Object.entries(PRESETS)) {
+ out.push(`[data-rune-motion="${name}"] { transition-property: ${props}; transition-duration: ${ms(p.duration)}; transition-timing-function: ${ease(p.bounce)}; }`);
+ }
+ for (const e of ENTERS) {
+ if (e === "none") {
+ out.push(`[data-rune-enter="none"] { animation: none; }`);
+ continue;
+ }
+ out.push(`@keyframes rune-enter-${e} { from { ${FROM[e]} } }`);
+ out.push(`[data-rune-enter="${e}"] { animation-name: rune-enter-${e}; animation-duration: ${ms(PRESETS.settle.duration)}; animation-timing-function: ${ease(0)}; animation-fill-mode: backwards; }`);
+ }
+ // an enter's own spring, after the effects so it wins
+ for (const [name, p] of Object.entries(PRESETS)) {
+ out.push(`[data-rune-enter-motion="${name}"] { animation-duration: ${ms(p.duration)}; animation-timing-function: ${ease(p.bounce)}; }`);
+ }
+ out.push(`[data-rune-instant], [data-rune-instant] * { transition: none !important; animation: none !important; }`);
+ for (let s = 0; s <= MAX_BLUR; s++) out.push(`[data-rune-blur="${s}"] { filter: blur(${s}px); }`);
+ for (let s = 0; s <= MAX_BLUR; s++) out.push(`[data-rune-backdrop-blur="${s}"] { backdrop-filter: blur(${s}px); }`);
+ // the system's glass is a blur where there's no system material (the SDK's own words for it)
+ out.push(`[data-rune-glass] { backdrop-filter: blur(24px); }`);
+ return out.join("\n") + "\n";
+}
+
+if (import.meta.main) await Bun.write(new URL("./src/web.css", import.meta.url), css());
diff --git a/sdk/rune/src/css.d.ts b/sdk/rune/src/css.d.ts
new file mode 100644
index 00000000..c52eab3c
--- /dev/null
+++ b/sdk/rune/src/css.d.ts
@@ -0,0 +1,2 @@
+// The stylesheet web.css is imported for its side effect: the bundler carries it to the page (T4b).
+declare module "*.css";
diff --git a/sdk/rune/src/index.ts b/sdk/rune/src/index.ts
index 6bf85778..2f8035ff 100644
--- a/sdk/rune/src/index.ts
+++ b/sdk/rune/src/index.ts
@@ -1,13 +1,18 @@
// @raea/rune: what Rune can do that CSS can't, as typed props on any element (docs/rune.feature R6a). They travel as
// one `data-rune` attribute, so React DOM, Blitz and a browser ignore them and the same TSX renders there unchanged;
-// raea-rune-host reads it (engine/rune/style/src/runeprops.rs) and maps each field to Rune's builder.
+// raea-rune-host reads it (engine/rune/style/src/runeprops.rs) and maps each field to Rune's builder. On the web, the
+// data-rune-* attributes beside it and web.css draw what CSS can (T4b, web.ts).
//
// <div {...rune({ motion: "pop", transition: { effect: "slide" } })}>...</div>
//
// Everything not marked with motion lands at once in the Rune host, as the DOM does; an element that asks for motion,
// a transition or lead and trail animates as Rune does.
+import "./web.css";
+import { web } from "./web.ts";
+
export * from "./kit.tsx";
+export { web } from "./web.ts";
/** A spring as Rune has it: how long it takes to settle, in seconds, and how much it overshoots (0 none, 1 a lot). */
export type Spring = { duration: number; bounce?: number };
@@ -79,7 +84,8 @@ export type RuneProps = {
glass?: boolean;
};
-/** The prop that carries `p`: spread it onto any element. */
-export function rune(p: RuneProps): { "data-rune": string } {
- return { "data-rune": JSON.stringify(p) };
+/** The props that carry `p`: spread them onto any element. `data-rune` is the native host's; the `data-rune-*` ones are
+ * the web's CSS fallbacks (web.ts, web.css), and `data-rune-web-ignored` names what the web can't draw (T4b). */
+export function rune(p: RuneProps): { "data-rune": string } & Record<string, string> {
+ return { "data-rune": JSON.stringify(p), ...web(p).attrs };
}
diff --git a/sdk/rune/src/web.css b/sdk/rune/src/web.css
new file mode 100644
index 00000000..40f201cb
--- /dev/null
+++ b/sdk/rune/src/web.css
@@ -0,0 +1,172 @@
+/* @raea/rune on the web target (docs/targets.feature T4b): written by gen-css.ts, don't edit. */
+[data-rune-motion="instant"] { transition-property: opacity, transform, translate, scale, rotate, width, height, background-color, color, border-color, box-shadow, filter; transition-duration: 100ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-motion="snap"] { transition-property: opacity, transform, translate, scale, rotate, width, height, background-color, color, border-color, box-shadow, filter; transition-duration: 250ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-motion="settle"] { transition-property: opacity, transform, translate, scale, rotate, width, height, background-color, color, border-color, box-shadow, filter; transition-duration: 300ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-motion="reflow"] { transition-property: opacity, transform, translate, scale, rotate, width, height, background-color, color, border-color, box-shadow, filter; transition-duration: 400ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-motion="glide"] { transition-property: opacity, transform, translate, scale, rotate, width, height, background-color, color, border-color, box-shadow, filter; transition-duration: 320ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-motion="morph"] { transition-property: opacity, transform, translate, scale, rotate, width, height, background-color, color, border-color, box-shadow, filter; transition-duration: 300ms; transition-timing-function: cubic-bezier(0.34, 1.48, 0.64, 1); }
+[data-rune-motion="pop"] { transition-property: opacity, transform, translate, scale, rotate, width, height, background-color, color, border-color, box-shadow, filter; transition-duration: 250ms; transition-timing-function: cubic-bezier(0.34, 1.45, 0.64, 1); }
+[data-rune-motion="drift"] { transition-property: opacity, transform, translate, scale, rotate, width, height, background-color, color, border-color, box-shadow, filter; transition-duration: 850ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-enter="none"] { animation: none; }
+@keyframes rune-enter-opacity { from { opacity: 0; } }
+[data-rune-enter="opacity"] { animation-name: rune-enter-opacity; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+@keyframes rune-enter-slide { from { transform: translateX(-100%); } }
+[data-rune-enter="slide"] { animation-name: rune-enter-slide; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+@keyframes rune-enter-blurReplace { from { opacity: 0; transform: scale(0.96); filter: blur(1.5px); } }
+[data-rune-enter="blurReplace"] { animation-name: rune-enter-blurReplace; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+@keyframes rune-enter-move-top { from { transform: translateY(-100%); } }
+[data-rune-enter="move-top"] { animation-name: rune-enter-move-top; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+@keyframes rune-enter-move-bottom { from { transform: translateY(100%); } }
+[data-rune-enter="move-bottom"] { animation-name: rune-enter-move-bottom; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+@keyframes rune-enter-move-leading { from { transform: translateX(-100%); } }
+[data-rune-enter="move-leading"] { animation-name: rune-enter-move-leading; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+@keyframes rune-enter-move-trailing { from { transform: translateX(100%); } }
+[data-rune-enter="move-trailing"] { animation-name: rune-enter-move-trailing; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+@keyframes rune-enter-push-top { from { opacity: 0; transform: translateY(-100%); } }
+[data-rune-enter="push-top"] { animation-name: rune-enter-push-top; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+@keyframes rune-enter-push-bottom { from { opacity: 0; transform: translateY(100%); } }
+[data-rune-enter="push-bottom"] { animation-name: rune-enter-push-bottom; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+@keyframes rune-enter-push-leading { from { opacity: 0; transform: translateX(-100%); } }
+[data-rune-enter="push-leading"] { animation-name: rune-enter-push-leading; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+@keyframes rune-enter-push-trailing { from { opacity: 0; transform: translateX(100%); } }
+[data-rune-enter="push-trailing"] { animation-name: rune-enter-push-trailing; animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); animation-fill-mode: backwards; }
+[data-rune-enter-motion="instant"] { animation-duration: 100ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-enter-motion="snap"] { animation-duration: 250ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-enter-motion="settle"] { animation-duration: 300ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-enter-motion="reflow"] { animation-duration: 400ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-enter-motion="glide"] { animation-duration: 320ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-enter-motion="morph"] { animation-duration: 300ms; animation-timing-function: cubic-bezier(0.34, 1.48, 0.64, 1); }
+[data-rune-enter-motion="pop"] { animation-duration: 250ms; animation-timing-function: cubic-bezier(0.34, 1.45, 0.64, 1); }
+[data-rune-enter-motion="drift"] { animation-duration: 850ms; animation-timing-function: cubic-bezier(0.2, 0, 0, 1); }
+[data-rune-instant], [data-rune-instant] * { transition: none !important; animation: none !important; }
+[data-rune-blur="0"] { filter: blur(0px); }
+[data-rune-blur="1"] { filter: blur(1px); }
+[data-rune-blur="2"] { filter: blur(2px); }
+[data-rune-blur="3"] { filter: blur(3px); }
+[data-rune-blur="4"] { filter: blur(4px); }
+[data-rune-blur="5"] { filter: blur(5px); }
+[data-rune-blur="6"] { filter: blur(6px); }
+[data-rune-blur="7"] { filter: blur(7px); }
+[data-rune-blur="8"] { filter: blur(8px); }
+[data-rune-blur="9"] { filter: blur(9px); }
+[data-rune-blur="10"] { filter: blur(10px); }
+[data-rune-blur="11"] { filter: blur(11px); }
+[data-rune-blur="12"] { filter: blur(12px); }
+[data-rune-blur="13"] { filter: blur(13px); }
+[data-rune-blur="14"] { filter: blur(14px); }
+[data-rune-blur="15"] { filter: blur(15px); }
+[data-rune-blur="16"] { filter: blur(16px); }
+[data-rune-blur="17"] { filter: blur(17px); }
+[data-rune-blur="18"] { filter: blur(18px); }
+[data-rune-blur="19"] { filter: blur(19px); }
+[data-rune-blur="20"] { filter: blur(20px); }
+[data-rune-blur="21"] { filter: blur(21px); }
+[data-rune-blur="22"] { filter: blur(22px); }
+[data-rune-blur="23"] { filter: blur(23px); }
+[data-rune-blur="24"] { filter: blur(24px); }
+[data-rune-blur="25"] { filter: blur(25px); }
+[data-rune-blur="26"] { filter: blur(26px); }
+[data-rune-blur="27"] { filter: blur(27px); }
+[data-rune-blur="28"] { filter: blur(28px); }
+[data-rune-blur="29"] { filter: blur(29px); }
+[data-rune-blur="30"] { filter: blur(30px); }
+[data-rune-blur="31"] { filter: blur(31px); }
+[data-rune-blur="32"] { filter: blur(32px); }
+[data-rune-blur="33"] { filter: blur(33px); }
+[data-rune-blur="34"] { filter: blur(34px); }
+[data-rune-blur="35"] { filter: blur(35px); }
+[data-rune-blur="36"] { filter: blur(36px); }
+[data-rune-blur="37"] { filter: blur(37px); }
+[data-rune-blur="38"] { filter: blur(38px); }
+[data-rune-blur="39"] { filter: blur(39px); }
+[data-rune-blur="40"] { filter: blur(40px); }
+[data-rune-blur="41"] { filter: blur(41px); }
+[data-rune-blur="42"] { filter: blur(42px); }
+[data-rune-blur="43"] { filter: blur(43px); }
+[data-rune-blur="44"] { filter: blur(44px); }
+[data-rune-blur="45"] { filter: blur(45px); }
+[data-rune-blur="46"] { filter: blur(46px); }
+[data-rune-blur="47"] { filter: blur(47px); }
+[data-rune-blur="48"] { filter: blur(48px); }
+[data-rune-blur="49"] { filter: blur(49px); }
+[data-rune-blur="50"] { filter: blur(50px); }
+[data-rune-blur="51"] { filter: blur(51px); }
+[data-rune-blur="52"] { filter: blur(52px); }
+[data-rune-blur="53"] { filter: blur(53px); }
+[data-rune-blur="54"] { filter: blur(54px); }
+[data-rune-blur="55"] { filter: blur(55px); }
+[data-rune-blur="56"] { filter: blur(56px); }
+[data-rune-blur="57"] { filter: blur(57px); }
+[data-rune-blur="58"] { filter: blur(58px); }
+[data-rune-blur="59"] { filter: blur(59px); }
+[data-rune-blur="60"] { filter: blur(60px); }
+[data-rune-blur="61"] { filter: blur(61px); }
+[data-rune-blur="62"] { filter: blur(62px); }
+[data-rune-blur="63"] { filter: blur(63px); }
+[data-rune-blur="64"] { filter: blur(64px); }
+[data-rune-backdrop-blur="0"] { backdrop-filter: blur(0px); }
+[data-rune-backdrop-blur="1"] { backdrop-filter: blur(1px); }
+[data-rune-backdrop-blur="2"] { backdrop-filter: blur(2px); }
+[data-rune-backdrop-blur="3"] { backdrop-filter: blur(3px); }
+[data-rune-backdrop-blur="4"] { backdrop-filter: blur(4px); }
+[data-rune-backdrop-blur="5"] { backdrop-filter: blur(5px); }
+[data-rune-backdrop-blur="6"] { backdrop-filter: blur(6px); }
+[data-rune-backdrop-blur="7"] { backdrop-filter: blur(7px); }
+[data-rune-backdrop-blur="8"] { backdrop-filter: blur(8px); }
+[data-rune-backdrop-blur="9"] { backdrop-filter: blur(9px); }
+[data-rune-backdrop-blur="10"] { backdrop-filter: blur(10px); }
+[data-rune-backdrop-blur="11"] { backdrop-filter: blur(11px); }
+[data-rune-backdrop-blur="12"] { backdrop-filter: blur(12px); }
+[data-rune-backdrop-blur="13"] { backdrop-filter: blur(13px); }
+[data-rune-backdrop-blur="14"] { backdrop-filter: blur(14px); }
+[data-rune-backdrop-blur="15"] { backdrop-filter: blur(15px); }
+[data-rune-backdrop-blur="16"] { backdrop-filter: blur(16px); }
+[data-rune-backdrop-blur="17"] { backdrop-filter: blur(17px); }
+[data-rune-backdrop-blur="18"] { backdrop-filter: blur(18px); }
+[data-rune-backdrop-blur="19"] { backdrop-filter: blur(19px); }
+[data-rune-backdrop-blur="20"] { backdrop-filter: blur(20px); }
+[data-rune-backdrop-blur="21"] { backdrop-filter: blur(21px); }
+[data-rune-backdrop-blur="22"] { backdrop-filter: blur(22px); }
+[data-rune-backdrop-blur="23"] { backdrop-filter: blur(23px); }
+[data-rune-backdrop-blur="24"] { backdrop-filter: blur(24px); }
+[data-rune-backdrop-blur="25"] { backdrop-filter: blur(25px); }
+[data-rune-backdrop-blur="26"] { backdrop-filter: blur(26px); }
+[data-rune-backdrop-blur="27"] { backdrop-filter: blur(27px); }
+[data-rune-backdrop-blur="28"] { backdrop-filter: blur(28px); }
+[data-rune-backdrop-blur="29"] { backdrop-filter: blur(29px); }
+[data-rune-backdrop-blur="30"] { backdrop-filter: blur(30px); }
+[data-rune-backdrop-blur="31"] { backdrop-filter: blur(31px); }
+[data-rune-backdrop-blur="32"] { backdrop-filter: blur(32px); }
+[data-rune-backdrop-blur="33"] { backdrop-filter: blur(33px); }
+[data-rune-backdrop-blur="34"] { backdrop-filter: blur(34px); }
+[data-rune-backdrop-blur="35"] { backdrop-filter: blur(35px); }
+[data-rune-backdrop-blur="36"] { backdrop-filter: blur(36px); }
+[data-rune-backdrop-blur="37"] { backdrop-filter: blur(37px); }
+[data-rune-backdrop-blur="38"] { backdrop-filter: blur(38px); }
+[data-rune-backdrop-blur="39"] { backdrop-filter: blur(39px); }
+[data-rune-backdrop-blur="40"] { backdrop-filter: blur(40px); }
+[data-rune-backdrop-blur="41"] { backdrop-filter: blur(41px); }
+[data-rune-backdrop-blur="42"] { backdrop-filter: blur(42px); }
+[data-rune-backdrop-blur="43"] { backdrop-filter: blur(43px); }
+[data-rune-backdrop-blur="44"] { backdrop-filter: blur(44px); }
+[data-rune-backdrop-blur="45"] { backdrop-filter: blur(45px); }
+[data-rune-backdrop-blur="46"] { backdrop-filter: blur(46px); }
+[data-rune-backdrop-blur="47"] { backdrop-filter: blur(47px); }
+[data-rune-backdrop-blur="48"] { backdrop-filter: blur(48px); }
+[data-rune-backdrop-blur="49"] { backdrop-filter: blur(49px); }
+[data-rune-backdrop-blur="50"] { backdrop-filter: blur(50px); }
+[data-rune-backdrop-blur="51"] { backdrop-filter: blur(51px); }
+[data-rune-backdrop-blur="52"] { backdrop-filter: blur(52px); }
+[data-rune-backdrop-blur="53"] { backdrop-filter: blur(53px); }
+[data-rune-backdrop-blur="54"] { backdrop-filter: blur(54px); }
+[data-rune-backdrop-blur="55"] { backdrop-filter: blur(55px); }
+[data-rune-backdrop-blur="56"] { backdrop-filter: blur(56px); }
+[data-rune-backdrop-blur="57"] { backdrop-filter: blur(57px); }
+[data-rune-backdrop-blur="58"] { backdrop-filter: blur(58px); }
+[data-rune-backdrop-blur="59"] { backdrop-filter: blur(59px); }
+[data-rune-backdrop-blur="60"] { backdrop-filter: blur(60px); }
+[data-rune-backdrop-blur="61"] { backdrop-filter: blur(61px); }
+[data-rune-backdrop-blur="62"] { backdrop-filter: blur(62px); }
+[data-rune-backdrop-blur="63"] { backdrop-filter: blur(63px); }
+[data-rune-backdrop-blur="64"] { backdrop-filter: blur(64px); }
+[data-rune-glass] { backdrop-filter: blur(24px); }
diff --git a/sdk/rune/src/web.ts b/sdk/rune/src/web.ts
new file mode 100644
index 00000000..07d4027c
--- /dev/null
+++ b/sdk/rune/src/web.ts
@@ -0,0 +1,72 @@
+// What Rune's props are on the web target (docs/targets.feature T4b). Blitz, like a browser, ignores `data-rune`, so
+// `rune()` also writes a `data-rune-*` attribute for each prop that has a CSS fallback, and web.css (gen-css.ts writes
+// it) draws them: a motion preset as a CSS transition of its duration, an enter transition as a keyframe animation,
+// blur and backdropBlur (whole points, 0 to 64) and glass as filters, instant as no transitions or animations inside.
+// Blitz draws all of these (filter, backdrop-filter, transitions and @keyframes; checked 11-06; it doesn't do
+// @starting-style). What has no CSS form is named in `data-rune-web-ignored`, which `raea app check` lists on a web app:
+// an exit (React removes the element at once), lead and trail, a spring of your own, an effect with numbers of its own,
+// a blur that isn't a whole number of points from 0 to 64.
+
+import type { Effect, Motion, RuneProps, SpringPreset } from "./index.ts";
+
+/** Rune's motion tokens (rune-motion tokens.rs): each preset's settle time in seconds and its bounce. */
+export const PRESETS: Record<SpringPreset, { duration: number; bounce: number }> = {
+ instant: { duration: 0.1, bounce: 0 },
+ snap: { duration: 0.25, bounce: 0 },
+ settle: { duration: 0.3, bounce: 0 },
+ reflow: { duration: 0.4, bounce: 0 },
+ glide: { duration: 0.32, bounce: 0 },
+ morph: { duration: 0.3, bounce: 0.16 },
+ pop: { duration: 0.25, bounce: 0.15 },
+ drift: { duration: 0.85, bounce: 0 },
+};
+
+/** The entrances web.css has keyframes for, by the attribute value. */
+export const ENTERS = ["none", "opacity", "slide", "blurReplace", "move-top", "move-bottom", "move-leading", "move-trailing", "push-top", "push-bottom", "push-leading", "push-trailing"] as const;
+
+/** The largest blur sigma web.css has a rule for. */
+export const MAX_BLUR = 64;
+
+const preset = (m: Motion | undefined): SpringPreset | null => (typeof m === "string" ? m : null);
+
+/** An effect's attribute value, or null when it has numbers of its own. */
+function enter(e: Effect): string | null {
+ if (typeof e === "string") return e;
+ if ("move" in e) return `move-${e.move}`;
+ if ("push" in e) return `push-${e.push}`;
+ return null;
+}
+
+/** The web's attributes for `p`, and the names of the props it has no CSS for. */
+export function web(p: RuneProps): { attrs: Record<string, string>; ignored: string[] } {
+ const attrs: Record<string, string> = {};
+ const ignored: string[] = [];
+ if (p.motion !== undefined) {
+ const m = preset(p.motion);
+ if (m) attrs["data-rune-motion"] = m;
+ else ignored.push("motion (a spring of its own)");
+ }
+ if (p.transition !== undefined) {
+ const t = typeof p.transition === "object" && "effect" in p.transition ? p.transition : { effect: p.transition as Effect };
+ const e = enter(t.effect);
+ if (e) attrs["data-rune-enter"] = e;
+ else ignored.push("transition (an effect with numbers of its own)");
+ if (t.enter !== undefined) {
+ const m = preset(t.enter);
+ if (m) attrs["data-rune-enter-motion"] = m;
+ else ignored.push("transition's enter (a spring of its own)");
+ }
+ if (e !== "none") ignored.push("transition's exit (React removes the element at once)");
+ }
+ if (p.lead !== undefined) ignored.push("lead");
+ if (p.instant) attrs["data-rune-instant"] = "";
+ for (const [k, attr] of [["blur", "data-rune-blur"], ["backdropBlur", "data-rune-backdrop-blur"]] as const) {
+ const v = p[k];
+ if (v === undefined) continue;
+ if (Number.isInteger(v) && v >= 0 && v <= MAX_BLUR) attrs[attr] = String(v);
+ else ignored.push(`${k} (${v}: whole points from 0 to ${MAX_BLUR} only)`);
+ }
+ if (p.glass) attrs["data-rune-glass"] = "";
+ if (ignored.length) attrs["data-rune-web-ignored"] = ignored.join("; ");
+ return { attrs, ignored };
+}
diff --git a/sdk/rune/web.test.ts b/sdk/rune/web.test.ts
new file mode 100644
index 00000000..761088f4
--- /dev/null
+++ b/sdk/rune/web.test.ts
@@ -0,0 +1,49 @@
+// T4b: Rune's props on the web target: a CSS fallback for each that has one, the rest named as ignored.
+import { expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { css } from "./gen-css.ts";
+import { web } from "./src/web.ts";
+
+// rune(p) is { "data-rune": JSON.stringify(p), ...web(p).attrs } (index.ts, which needs React to load)
+const rune = (p: Parameters<typeof web>[0]) => ({ "data-rune": JSON.stringify(p), ...web(p).attrs });
+const Spring = (duration: number, bounce = 0) => ({ duration, bounce });
+
+test("presets, effects, blurs, glass and instant get the web's attributes", () => {
+ const a = rune({ motion: "pop", transition: { effect: { push: "top" }, enter: "snap" }, blur: 8, backdropBlur: 0, glass: true, instant: true });
+ expect(a["data-rune-motion"]).toBe("pop");
+ expect(a["data-rune-enter"]).toBe("push-top");
+ expect(a["data-rune-enter-motion"]).toBe("snap");
+ expect(a["data-rune-blur"]).toBe("8");
+ expect(a["data-rune-backdrop-blur"]).toBe("0");
+ expect(a["data-rune-glass"]).toBe("");
+ expect(a["data-rune-instant"]).toBe("");
+ // the exit is the one thing here the web can't do
+ expect(a["data-rune-web-ignored"]).toBe("transition's exit (React removes the element at once)");
+ // the native host's prop is as it was
+ expect(JSON.parse(a["data-rune"]).motion).toBe("pop");
+});
+
+test("what has no CSS is named, never dropped", () => {
+ const a = rune({ motion: Spring(0.4, 0.2), transition: { effect: { scale: 0.8 } }, lead: { lead: "snap", trail: "settle" }, blur: 2.5 });
+ expect(a["data-rune-motion"]).toBeUndefined();
+ expect(a["data-rune-web-ignored"].split("; ")).toEqual([
+ "motion (a spring of its own)",
+ "transition (an effect with numbers of its own)",
+ "transition's exit (React removes the element at once)",
+ "lead",
+ "blur (2.5: whole points from 0 to 64 only)",
+ ]);
+ // no transition at all is nothing to ignore
+ expect(rune({ transition: "none" })["data-rune-web-ignored"]).toBeUndefined();
+});
+
+test("every attribute value rune() writes has a rule in web.css, which is what gen-css.ts writes", () => {
+ const sheet = readFileSync(new URL("./src/web.css", import.meta.url), "utf8");
+ expect(sheet).toBe(css());
+ for (const v of ["instant", "snap", "settle", "reflow", "glide", "morph", "pop", "drift"]) {
+ expect(sheet).toContain(`[data-rune-motion="${v}"]`);
+ expect(sheet).toContain(`[data-rune-enter-motion="${v}"]`);
+ }
+ for (const e of ["opacity", "slide", "blurReplace", "move-leading", "push-bottom"]) expect(sheet).toContain(`@keyframes rune-enter-${e} `);
+ expect(sheet).toContain(`[data-rune-blur="64"] { filter: blur(64px); }`);
+});
diff --git a/sdk/skills/raea/SKILL.md b/sdk/skills/raea/SKILL.md
index cc8468e5..0cb3d731 100644
--- a/sdk/skills/raea/SKILL.md
+++ b/sdk/skills/raea/SKILL.md
@@ -148,31 +148,48 @@ raea check out/piece.mp4 --manifest out/render.json --taste ~/.raea/taste/taste.
`ffmpeg -i film.mp4 -c:v libx264 -preset slow -crf 23 -maxrate 2600k -bufsize 5200k -pix_fmt yuv420p -c:a aac -b:a 128k -movflags +faststart film-share.mp4`.
- Deliver to the controllers' specs (sizes, platforms, loudness) when the workspace sets them.
-## Native apps with Rune — HEADLESS (a checkout with projects/rune)
-<!-- sources: docs/rune.feature engine/cli/src/cli.rs -->
-
-The same TSX that renders on Bevy can be drawn by Rune, a native GPU UI framework, through `raea rune`. Target it for
-three things: a desktop app (a window of its own, packaged as a signed Mac app), UI rendered to video (product-UI ads:
-springs and presence on the virtual clock), and a Rune layer inside a Bevy scene (a HUD). A composition or a game
-stays on Bevy; reach for Rune when the thing is an application's interface.
-
-- Write it as a React app: a default export, DOM elements, inline `style` or Tailwind `className`. Rune draws the
- subset in projects/rune/README.md's table (size, min/max, padding, margin, gap, flex, absolute insets, scroll,
- colours and gradients, border, radius, shadow, opacity, font size, weight and family). Anything else is reported in
- `unmapped.json`, never dropped: an empty one means the page maps whole.
-- Rune-only behaviour is typed props from `@raea/rune` (sdk/rune), ignored by every other host:
+## Apps: web or native — HEADLESS
+<!-- sources: docs/targets.feature apps/targets/src sdk/ui/src/app.ts sdk/rune/src -->
+
+An app is a React file with a default export: DOM elements, inline `style` or Tailwind `className`, on @raea/ui. One
+setting picks the host that draws it. **web** (the default) is Blitz on Bevy, with Chrome's CSS and npm packages.
+**native** is Rune: a native window, native text, keyboard and accessibility, and springs on every change. The SDK
+is the same; only the setting differs. A composition or a game stays a composition; an app is an application's
+interface.
+
+- Say the target in the app's own file, as a literal (anything else is refused at its line):
+ `export const app = { target: "native", title: "Notes", size: [480, 640], minSize: [360, 480] };`. With no
+ `app` export, or no `target` in it, the target is `"web"`. `--target web|native` on the command line overrides it.
+- The verbs, the same on both targets: `raea app run app.tsx` opens it in a window; `raea app check app.tsx` runs it
+ headless; `raea app bundle app.tsx -o Notes.app` makes a Mac app. `raea app bundle` signs ad hoc unless you give
+ `--identity "Developer ID Application: ..."` (or RAEA_SIGN_IDENTITY) and `--notarize PROFILE` (a notarytool
+ keychain profile): it always signs with your own identity, never raea's.
+- Check before you show it. Give the app its input as `export const steps = [{ press: "add" }, { type: "Ada", into: "name" }, { key: "Tab" }, { wheel: "list", dy: 120 }, { frames: 30 }];`
+ (elements by `data-testid`), or as `--script steps.json`. `raea app check app.tsx --png out/` writes a PNG after
+ the mount and after each step (00-mount.png, 01-press-add.png, ...) and tree.json (each element's role, label,
+ text and box). Read the PNGs. Check on both targets when the app should run on both: `--target web` and
+ `--target native`.
+- What the check holds each target to. **native** fails on any prop Rune doesn't map or call its host doesn't
+ answer, naming each with its element's path (unmapped.json, unanswered.json). Change the prop, or keep the app on
+ web. **web** passes when it draws, and says what native wouldn't draw and which Rune props it ignores.
+- Native draws flex layout (no grid), sizes, padding, margin, gap, absolute insets, scroll, colours and gradients,
+ borders, radius, shadows and rings, outlines, opacity, transforms and transitions, text, images and video, fonts
+ from the app's folder, and Tailwind's classes with hover:, focus:, focus-visible:, active:, disabled:, dark: and
+ sm: to 2xl:. Anything else is reported, never dropped. An empty unmapped.json means the page maps whole.
+- What only Rune does is typed props from `@raea/rune`:
`<div {...rune({ motion: "pop", transition: { effect: { push: "top" }, enter: "pop" } })}>`, plus `lead`,
- `instant`, `blur`, `backdropBlur` and `glass`, and rune-kit's `Badge`, `Spinner`, `Progress`, `RollingText` and
- `Switch`. Without them an element lands at once, as it does in a browser.
-- Check your work headless before you show it: write the input as steps.json (`[{"press": "inc"}, {"type": "Ada", "into": "name"}, {"key": "Enter"}]`,
- elements by `data-testid`) and run `raea rune --headless app.tsx --script steps.json --png out/`. It writes a PNG after the
- mount and after each step (00-mount.png, 01-press-inc.png, ...), tree.json (each element's role, label, text and
- box) and unmapped.json, the same bytes every run. Read the PNGs and the tree; fix what's unmapped.
-- Film it: add `--video out/app.mp4 [--audio music.wav]` to the headless run. Every frame on the virtual clock at 60 fps,
- a cursor gliding to each element it presses, through `raea media encode` (signed like every export). The same app
- and script give the same frames (out/video.json has their hashes).
-- Open it: `raea rune run app.tsx`. Package it: `raea rune bundle app.tsx -o App.app --notarize` (signed with raea's
- Developer ID, notarized, accepted by Gatekeeper).
+ `instant`, `blur`, `backdropBlur` and `glass`, and its `Badge`, `Spinner`, `Progress`, `RollingText` and
+ `Switch`. On web, a preset motion becomes a CSS transition and an entrance a keyframe, blur and glass become filters,
+ and the rest is ignored and listed by the check. Without these props an element lands at once, as in a browser.
+- Host calls (`call` and `callSync` from `@raea/ui/wire`), answered on both targets: `net.fetch`, `net.ws.*`,
+ `net.storage.*`, `net.clipboard.*`, `os.open` (http, https, mailto), `fs.pick`, `fs.save`, `fs.read`, `fs.write`
+ and `dialog.message`. Headless, a step answers a dialog: `{ pick: ["a.txt"] }`, `{ save: "out.txt" }`,
+ `{ dialog: 0 }`. `world.*` (BRP on the 3D world) is web's only: native refuses it with "no world on the native
+ target".
+- Examples ship with raea and pass the check on both targets: `sdk/rune/examples/signin.tsx` (Tailwind only) and
+ `sdk/rune/examples/motion.tsx` (Rune's props). On a native app, `raea app check --video out/app.mp4 [--audio
+ music.wav]` films it on the virtual clock at 60 fps, with a cursor gliding to each element it presses. The same app
+ and steps give the same frames.
## Go further
diff --git a/sdk/web/.gitignore b/sdk/web/.gitignore
new file mode 100644
index 00000000..19d621a2
--- /dev/null
+++ b/sdk/web/.gitignore
@@ -0,0 +1,2 @@
+wasm/
+test/parity/gen/
diff --git a/sdk/web/bun.lock b/sdk/web/bun.lock
new file mode 100644
index 00000000..266a2fa7
--- /dev/null
+++ b/sdk/web/bun.lock
@@ -0,0 +1,43 @@
+{
+ "lockfileVersion": 2,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "@raea/web",
+ "dependencies": {
+ "react": "file:../raea/node_modules/react",
+ "react-dom": "file:../raea/node_modules/react-dom",
+ "scheduler": "file:../raea/node_modules/scheduler",
+ },
+ "devDependencies": {
+ "@types/bun": "1.4.3",
+ "@types/react-dom": "19.2.0",
+ },
+ },
+ },
+ "packages": {
+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="],
+
+ "@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="],
+
+ "@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-brtBs0MnE9SMx7px208g39lRmC5uHZs96caOJfTjFcYSLHNamvaSMfJNagChVNkup2SdtOxKX1FDBkRSJe1ZAg=="],
+
+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
+
+ "csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
+
+ "react": ["react@file:../raea/node_modules/react", {}],
+
+ "react-dom": ["react-dom@file:../raea/node_modules/react-dom", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.0" } }],
+
+ "scheduler": ["scheduler@file:../raea/node_modules/scheduler", {}],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-GNCQH3MbVGB8OAVAoTiLH8pu4wx5Ni3DWKpnBzGj3WDsi8EwmK0aOVBooNEt+g5YL1eHPxcS9XUTouwFU6j1kQ=="],
+
+ "@types/node/undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
+
+ "react-dom/scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
+ }
+}
diff --git a/sdk/web/package.json b/sdk/web/package.json
index d5d31488..68223bb7 100644
--- a/sdk/web/package.json
+++ b/sdk/web/package.json
@@ -15,5 +15,9 @@
"react": "file:../raea/node_modules/react",
"react-dom": "file:../raea/node_modules/react-dom",
"scheduler": "file:../raea/node_modules/scheduler"
+ },
+ "devDependencies": {
+ "@types/bun": "1.4.3",
+ "@types/react-dom": "19.2.0"
}
}
diff --git a/sdk/web/src/collect.ts b/sdk/web/src/collect.ts
index b9598179..1dcaeafa 100644
--- a/sdk/web/src/collect.ts
+++ b/sdk/web/src/collect.ts
@@ -79,7 +79,8 @@ export function clearUnder3d(page: HTMLElement): string | undefined {
for (let el = first.parentElement; el && el !== page; el = el.parentElement) {
if (!el.hasAttribute(UNDER)) {
const bg = getComputedStyle(el).backgroundColor;
- if (bg && bg !== "transparent" && !bg.endsWith(", 0)")) el.setAttribute(UNDER, hex(bg));
+ // see-through is rgba(..., 0); rgb(0, 0, 0), black, also ends in ", 0)" and is solid
+ if (bg && bg !== "transparent" && !/^rgba\(.*,\s*0\)$/.test(bg)) el.setAttribute(UNDER, hex(bg));
else continue;
}
clear ??= el.getAttribute(UNDER)!;
@@ -93,4 +94,5 @@ function hex(css: string): string {
return m ? "#" + [m[1], m[2], m[3]].map((n) => Number(n).toString(16).padStart(2, "0")).join("") : css;
}
-export const UNDER3D_CSS = `[${UNDER}]{background:transparent!important}`;
+// a layered <Canvas3D>'s slot (an <img> the native renderer paints the 3D into) is hidden: the 3D is drawn under the page here
+export const UNDER3D_CSS = `[${UNDER}]{background:transparent!important}img[data-raea-scene]{visibility:hidden}`;
diff --git a/sdk/web/test/parity/.tsx b/sdk/web/test/parity/.tsx
new file mode 100644
index 00000000..e69de29b
diff --git a/sdk/web/test/parity/cases.ts b/sdk/web/test/parity/cases.ts
new file mode 100644
index 00000000..ab9c2bbc
--- /dev/null
+++ b/sdk/web/test/parity/cases.ts
@@ -0,0 +1,21 @@
+// raea-web parity: the kinds raea's own engine draws that three.js can't (sdk/r3f/src/three/kinds.ts "engine"), each
+// drawn by `raea render` and by raea-web in headless Chrome on WebGPU, compared by SSIM (tools/parity.sh). The first five
+// are sdk/raea/bench/bevy-ts's cases (64x64); entities and fog are beside this file (320x180).
+const BENCH = "../../../raea/bench/bevy-ts/cases";
+export interface Case {
+ name: string;
+ /** the kinds it measures */
+ kinds: string[];
+ /** the edit, relative to this directory; its composition "main" */
+ edit: string;
+ frame: number;
+}
+export const CASES: Case[] = [
+ { name: "surface-shader", kinds: ["SurfaceShader"], edit: `${BENCH}/shader-scene.tsx`, frame: 0 },
+ { name: "frame-pass", kinds: ["FramePass"], edit: `${BENCH}/frame-pass.tsx`, frame: 0 },
+ { name: "compute", kinds: ["Compute"], edit: `${BENCH}/compute.tsx`, frame: 1 },
+ { name: "component", kinds: ["BevyComponent"], edit: `${BENCH}/reflect-on-camera.tsx`, frame: 0 },
+ { name: "resource", kinds: ["BevyResource"], edit: `${BENCH}/reflect-keyed-resource-still.tsx`, frame: 15 },
+ { name: "entities", kinds: ["Entities"], edit: "./entities.tsx", frame: 10 },
+ { name: "fog", kinds: ["VolumetricFog", "FogVolume"], edit: "./fog.tsx", frame: 0 },
+];
diff --git a/sdk/web/test/parity/entities.tsx b/sdk/web/test/parity/entities.tsx
new file mode 100644
index 00000000..41f32044
--- /dev/null
+++ b/sdk/web/test/parity/entities.tsx
@@ -0,0 +1,27 @@
+// raea-web parity: an ECS world drawn by the engine with no React element per entity (<Entities>), as conformance
+// golden 06: a ship (rounded box) and its gun (a cylinder, its child), turned by a system each frame.
+import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";
+import { Canvas3D, Entities } from "raea/3d";
+import { Camera3d } from "raea/camera";
+import { DirectionalLight } from "raea/light";
+import { Transform } from "raea/transform";
+import { createWorld } from "raea/ecs";
+
+const game = createWorld();
+const ship = game.add({ Mesh: { shape: "rounded_box(2, 0.6, 1, 0.1)", color: "#2563eb", roughness: 0.5, metalness: 0 }, Transform: { x: 0, y: 0, z: 0, ry: 0 } });
+game.add({ Mesh: { shape: "cylinder(0.15, 1.2)", color: "#f59e0b", roughness: 0.4, metalness: 0 }, Transform: { x: 0, y: 0.6, z: 0 } }, { parent: ship });
+game.system((w, f) => w.insert(ship, { Transform: { x: 0, y: 0, z: 0, ry: f * 0.05 } }));
+
+function Ships() {
+ const frame = useCurrentFrame();
+ return (
+ <AbsoluteFill style={{ background: "#0b1020" }}>
+ <Canvas3D>
+ <Camera3d transform={Transform.fromXyz(0, 1.5, 6).lookingAt([0, 0, 0])} />
+ <DirectionalLight illuminance={8000} transform={Transform.fromXyz(2, 3, 4).lookingAt([0, 0, 0])} />
+ <Entities world={game.at(frame)} />
+ </Canvas3D>
+ </AbsoluteFill>
+ );
+}
+registerRoot(() => <Composition id="main" component={Ships} durationInFrames={30} fps={30} width={320} height={180} />);
diff --git a/sdk/web/test/parity/fog.tsx b/sdk/web/test/parity/fog.tsx
new file mode 100644
index 00000000..c0b134ac
--- /dev/null
+++ b/sdk/web/test/parity/fog.tsx
@@ -0,0 +1,31 @@
+// raea-web parity (docs/web-export.md, "raea's own kinds"): volumetric fog, a fog volume lit by a volumetric sun, a
+// box's shadow cut through its shafts. Bevy raymarches it through its shadow maps; three.js has nothing for it.
+import { AbsoluteFill, Composition, registerRoot } from "raea";
+import { Canvas3D, FogVolume, VolumetricFog } from "raea/3d";
+import { Camera3d } from "raea/camera";
+import { DirectionalLight } from "raea/light";
+import { Cuboid, Mesh3d } from "raea/mesh";
+import { StandardMaterial } from "raea/pbr";
+import { Transform } from "raea/transform";
+
+function Fog() {
+ return (
+ <AbsoluteFill style={{ background: "#05070c" }}>
+ <Canvas3D>
+ <Camera3d transform={Transform.fromXyz(0, 1.5, 7).lookingAt([0, 1, 0])} />
+ <DirectionalLight volumetric illuminance={8000} shadow_maps_enabled transform={Transform.fromXyz(2, 6, -3).lookingAt([0, 0, 0])} />
+ <VolumetricFog />
+ <FogVolume name="air" position={[0, 2, 0]} scale={[10, 4, 10]} density={0.06} scattering={0.5} absorption={0.1} />
+ <Mesh3d name="floor" transform={Transform.fromXyz(0, -0.05, 0)}>
+ <Cuboid half_size={[6, 0.05, 6]} />
+ <StandardMaterial base_color="#808890" perceptual_roughness={0.9} />
+ </Mesh3d>
+ <Mesh3d name="box" transform={Transform.fromXyz(0, 2.5, -1)}>
+ <Cuboid half_size={[0.8, 0.8, 0.8]} />
+ <StandardMaterial base_color="#c04030" />
+ </Mesh3d>
+ </Canvas3D>
+ </AbsoluteFill>
+ );
+}
+registerRoot(() => <Composition id="main" component={Fog} durationInFrames={1} fps={30} width={320} height={180} />);
diff --git a/sdk/web/tools/parity.sh b/sdk/web/tools/parity.sh
new file mode 100755
index 00000000..55419e5c
--- /dev/null
+++ b/sdk/web/tools/parity.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+# raea-web parity (docs/web-export.md, "raea's own kinds"): each case in test/parity/cases.ts, the kinds three.js can't
+# draw (sdk/r3f/src/three/kinds.ts "engine"), rendered by `raea render` and by raea-web in headless Chrome on WebGPU
+# (tools/shoot.ts), compared by SSIM. Fails under $MIN (0.92). Needs raea, Chrome, ImageMagick and sdk/web/wasm
+# (tools/wasm.sh builds it).
+# tools/parity.sh [OUT_DIR]
+set -euo pipefail
+cd "$(dirname "$0")/.."
+OUT=${1:-$(mktemp -d)}
+MIN=${MIN:-0.92}
+[ -f wasm/raea_web_bg.wasm ] || tools/wasm.sh
+mkdir -p "$OUT"
+export RAEA_SIGN=0 RAEA_MARK=0
+CASES=$(bun -e 'const { CASES } = await import("./test/parity/cases.ts"); for (const c of CASES) console.log(`${c.name} ${c.edit} ${c.frame}`)')
+while read -r name edit frame; do
+ (cd test/parity && raea render "$edit" --composition main --frame "$frame" -o "$OUT/$name-native.png" >/dev/null)
+done <<< "$CASES"
+bun tools/shoot.ts "$OUT"
+fail=0
+while read -r name _ _; do
+ # ImageMagick 7.1.2 reports SSIM's distance (1 - SSIM)
+ d=$(magick compare -metric SSIM "$OUT/$name-native.png" "$OUT/$name-web.png" null: 2>&1 | sed -E 's/.*\(([0-9.e-]+)\).*/\1/' || true)
+ s=$(echo "1 - $d" | bc -l)
+ # a blank web frame fails whatever its SSIM (a mostly dark native frame would otherwise pass)
+ [ "$(magick "$OUT/$name-web.png" -format "%[fx:maxima]" info:)" = 0 ] && s=0
+ ok=$(echo "$s >= $MIN" | bc -l)
+ printf '%-15s SSIM %.4f %s\n' "$name" "$s" "$([ "$ok" = 1 ] && echo ok || echo LOW)"
+ [ "$ok" = 1 ] || fail=1
+done <<< "$CASES"
+exit $fail
diff --git a/sdk/web/tools/shoot.ts b/sdk/web/tools/shoot.ts
new file mode 100644
index 00000000..c8785f94
--- /dev/null
+++ b/sdk/web/tools/shoot.ts
@@ -0,0 +1,93 @@
+// raea-web parity, the browser side (tools/parity.sh): each case in test/parity/cases.ts built into a page that plays
+// its composition with @raea/web, held at the case's frame, drawn by raea-web on WebGPU in headless Chrome
+// (sdk/r3f/tools/chrome.ts, never the person's own), and screenshotted at the composition's size.
+// bun tools/shoot.ts OUT_DIR [case ...]
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { openChrome } from "../../r3f/tools/chrome";
+import { CASES } from "../test/parity/cases";
+
+const here = resolve(import.meta.dir, "..");
+const [out, ...only] = process.argv.slice(2);
+if (!out) throw new Error("usage: bun tools/shoot.ts OUT_DIR [case ...]");
+const cases = CASES.filter((c) => !only.length || only.includes(c.name));
+
+/** the page for one case: its edit (registering "main") played and held, `window.__raea` saying how it went */
+function entry(edit: string, frame: number): string {
+ return `import ${JSON.stringify(join("..", edit))};
+import { loadRaea, play } from "@raea/web";
+const w = window as unknown as { __raea: string };
+w.__raea = "loading";
+const load = () => import("/wasm/raea_web.js" as string);
+(async () => {
+ if (!("gpu" in navigator)) return void (w.__raea = "error: no WebGPU");
+ const m = await loadRaea(load as never);
+ let shown = 0;
+ play({ stage: document.getElementById("stage")!, Raea: m.Raea, composition: "main", hold: ${frame}, onFirstFrame: () => void (shown = performance.now()), onError: (e) => void (w.__raea = "error: " + String(e)) });
+ // the held frame drawn a few times over (a compute pass's or a resource's frame settles), then shown
+ const wait = () => (shown && performance.now() - shown > ${Number(process.env.SHOOT_SETTLE ?? 1500)} ? void (w.__raea = w.__raea.startsWith("error") ? w.__raea : "ready") : requestAnimationFrame(wait));
+ wait();
+})().catch((e) => void (w.__raea = "error: " + String(e)));
+`;
+}
+
+// the entries sit in the package (test/parity/gen, not in git) so the SDK's paths resolve them; the bundles go to a temp dir
+const gen = resolve(here, "test/parity/gen");
+mkdirSync(gen, { recursive: true });
+const dir = mkdtempSync(join(tmpdir(), "raea-web-parity-"));
+try {
+ for (const c of cases) {
+ const src = join(gen, `${c.name}.tsx`);
+ writeFileSync(src, entry(c.edit, c.frame));
+ const built = await Bun.build({
+ entrypoints: [src], outdir: join(dir, c.name), target: "browser", external: ["/wasm/*"],
+ define: { "process.env.NODE_ENV": '"production"' },
+ plugins: [{ name: "one-copy", setup(b) { b.onResolve({ filter: /^(react|react-dom|scheduler)(\/.*)?$/ }, (a) => ({ path: Bun.resolveSync(a.path, resolve(here, "../raea")) })); } }],
+ });
+ if (!built.success) throw new AggregateError(built.logs, `shoot: ${c.name} didn't build`);
+ }
+ const server = Bun.serve({
+ port: 0,
+ fetch(req) {
+ const p = new URL(req.url).pathname;
+ const name = p.split("/")[1];
+ if (p.startsWith("/wasm/")) return new Response(Bun.file(resolve(here, "wasm", p.slice(6))), { headers: { "content-type": p.endsWith(".wasm") ? "application/wasm" : "text/javascript" } });
+ if (p === `/${name}/`) return new Response(`<!doctype html><meta charset="utf-8"><body style="margin:0;background:#000"><div id="stage" style="position:absolute;inset:0"></div><script type="module" src="/${name}/${name}.js"></script>`, { headers: { "content-type": "text/html" } });
+ if (p === "/favicon.ico") return new Response(null, { status: 204 });
+ // a bundle's file, else one of the case's own files beside its edit (a glTF, a picture), as raea render finds them;
+ // raea-web asks for them under assets/ (Bevy's asset folder on the web, beside the page)
+ const built = Bun.file(join(dir, p.slice(1)));
+ const c = CASES.find((x) => x.name === name);
+ const own = c ? Bun.file(resolve(here, "test/parity", c.edit, "..", p.slice(name.length + 2).replace(/^assets\//, ""))) : built;
+ return built.size ? new Response(built, { headers: { "content-type": p.endsWith(".js") ? "text/javascript" : "application/octet-stream" } }) : new Response(own);
+ },
+ });
+ let failed = 0;
+ for (const c of cases) {
+ const { width, height } = await dims(c.edit);
+ const chrome = await openChrome(`http://127.0.0.1:${server.port}/${c.name}/`, width, height, { scale: 1, mobile: false, webgpu: true });
+ let state = "";
+ for (let i = 0; i < 600; i++) {
+ state = String(await chrome.value("window.__raea"));
+ if (state === "ready" || state.startsWith("error")) break;
+ await Bun.sleep(100);
+ }
+ if (state === "ready") await chrome.shot(join(out, `${c.name}-web.png`));
+ else failed++;
+ console.log(`${c.name}: ${state}${state === "ready" && !process.env.SHOOT_LOGS ? "" : `\n ${[...chrome.logs, ...chrome.problems].slice(process.env.SHOOT_LOGS ? -40 : -8).join("\n ")}`}`);
+ chrome.close();
+ }
+ server.stop(true);
+ if (failed) process.exit(1);
+} finally {
+ rmSync(dir, { recursive: true, force: true });
+}
+
+/** a case's composition size, read from its source (width={N} height={N} on its Composition) */
+async function dims(edit: string): Promise<{ width: number; height: number }> {
+ const s = await Bun.file(resolve(here, "test/parity", edit)).text();
+ const w = /width=\{(\d+)\}/.exec(s), h = /height=\{(\d+)\}/.exec(s);
+ if (!w || !h) throw new Error(`shoot: ${edit} names no width and height`);
+ return { width: Number(w[1]), height: Number(h[1]) };
+}
diff --git a/sdk/web/tools/wasm.sh b/sdk/web/tools/wasm.sh
new file mode 100755
index 00000000..8a8a96d9
--- /dev/null
+++ b/sdk/web/tools/wasm.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+# raea-web's wasm (engine/web) built with the web profile and bound for the browser into sdk/web/wasm (not in git):
+# raea_web.js and raea_web_bg.wasm, which @raea/web's loadRaea instantiates. Needs the wasm32 target and wasm-bindgen.
+set -euo pipefail
+cd "$(dirname "$0")/../../.."
+CARGO_TARGET_DIR=$PWD/target/web lane build -- cargo build -p raea-web --target wasm32-unknown-unknown --profile web -j 6 --message-format short
+wasm-bindgen --target web --out-dir sdk/web/wasm --no-typescript target/web/wasm32-unknown-unknown/web/raea_web.wasm
+ls -la sdk/web/wasm
diff --git a/sdk/web/tsconfig.json b/sdk/web/tsconfig.json
new file mode 100644
index 00000000..1d958edb
--- /dev/null
+++ b/sdk/web/tsconfig.json
@@ -0,0 +1 @@
+{ "extends": "../tsconfig.base.json", "compilerOptions": { "types": ["bun"], "skipLibCheck": true }, "include": ["src", "test", "tools"] }
diff --git a/systems/frame/src/lib.rs b/systems/frame/src/lib.rs
index 22d4cb25..21f29654 100644
--- a/systems/frame/src/lib.rs
+++ b/systems/frame/src/lib.rs
@@ -45,9 +45,29 @@ pub struct FrameRows {
pub live: Option<Vec<BTreeMap<String, V>>>,
/// rows whose frame look changes (the camera's `frame_looks`): that list as written, and each look's columns
pub looks: HashMap<usize, (String, Vec<BTreeMap<String, V>>)>,
+ /// the edit's timeline the columns came from (which rows never change: `still`)
+ pub timeline: Option<std::sync::Arc<raea_core_program::timeline::Timeline>>,
}
impl FrameRows {
+ /// Whether a row's values are the same on every frame of the edit, so a system applying them to its entity each
+ /// frame can apply them once (a live scene's rows: never, since a play changes any of them).
+ pub fn still(&self, e: Entity) -> bool {
+ self.live.is_none() && self.timeline.as_ref().zip(self.ix.get(&e)).is_some_and(|(t, r)| t.still(*r))
+ }
+
+ /// One of a row's values this frame, copying only it (with its frame look laid on, as `vals` has it).
+ pub fn get(&self, e: Entity, c: &str) -> Option<V> {
+ let r = *self.ix.get(&e)?;
+ if self.looks.contains_key(&r) {
+ return self.vals(e)?.get(c).cloned();
+ }
+ match &self.live {
+ Some(rows) => rows.get(r)?.get(c).cloned(),
+ None => self.cols.get(r, c),
+ }
+ }
+
/// A row's values this frame.
pub fn vals(&self, e: Entity) -> Option<std::borrow::Cow<'_, BTreeMap<String, V>>> {
let r = *self.ix.get(&e)?;
diff --git a/systems/meshseq/src/lib.rs b/systems/meshseq/src/lib.rs
index cabda487..509531c8 100644
--- a/systems/meshseq/src/lib.rs
+++ b/systems/meshseq/src/lib.rs
@@ -301,10 +301,11 @@ fn sync_glitches(
joints: Query<&GlobalTransform, Without<Mesh3d>>,
) {
for (e, root_gt) in &rows {
- let Some(v) = frame.vals(e) else { continue };
- if !GLITCH_COLS.iter().any(|k| v.contains_key(*k)) {
+ // a row with no glitch column is passed over without making its values (10 000 cubes made them every frame)
+ if !GLITCH_COLS.iter().any(|k| frame.get(e, k).is_some()) {
continue;
}
+ let Some(v) = frame.vals(e) else { continue };
let p = params(&v);
let active = p[..7].iter().any(|x| *x != 0.0);
let mut fresh = None;
diff --git a/systems/parity/src/lib.rs b/systems/parity/src/lib.rs
index 1947fa53..771e84a2 100644
--- a/systems/parity/src/lib.rs
+++ b/systems/parity/src/lib.rs
@@ -47,13 +47,17 @@ struct Probe {
/// Adds the probe when RAEA_PARITY is set: the example host's entry and RaeaPlugins' (raea_plugins.rs).
pub fn install(app: &mut App) {
let Ok(out) = std::env::var("RAEA_PARITY") else { return };
- let frames = match std::env::var("RAEA_PARITY_FRAMES").ok().as_deref() {
+ let frames: Option<BTreeSet<u64>> = match std::env::var("RAEA_PARITY_FRAMES").ok().as_deref() {
None | Some("all") | Some("") => None,
Some(s) => Some(s.split(',').filter_map(|f| f.trim().parse().ok()).collect()),
};
let png = std::env::var("RAEA_PARITY_PNG").ok().map(PathBuf::from);
if let Some(d) = &png {
let _ = std::fs::create_dir_all(d);
+ // an earlier run's pictures would end RAEA_PARITY_EXIT's wait for this run's
+ for k in frames.iter().flatten() {
+ let _ = std::fs::remove_file(d.join(format!("{k}.png")));
+ }
}
let exit = std::env::var("RAEA_PARITY_EXIT").is_ok_and(|v| v == "1");
let types: Vec<String> = std::env::var("RAEA_PARITY_TYPES")
@@ -86,8 +90,13 @@ fn probe(
p.frame += 1;
p.ticks += 1;
let last = p.frames.as_ref().and_then(|s| s.last().copied());
+ // a screenshot's readback lands some frames after it's asked for (save_to_disk writes it on the main thread), so
+ // the run ends once every probed frame's picture is on disk, or 600 frames on without it
if p.exit && last.is_some_and(|l| f >= l + 4) {
- exit.write(AppExit::Success);
+ let saved = |d: &PathBuf| p.frames.iter().flatten().all(|k| d.join(format!("{k}.png")).exists());
+ if p.png.as_ref().is_none_or(saved) || last.is_some_and(|l| f >= l + 600) {
+ exit.write(AppExit::Success);
+ }
return;
}
if p.frames.as_ref().is_some_and(|s| !s.contains(&f)) {
diff --git a/tools/release.sh b/tools/release.sh
index c4776254..ad391750 100755
--- a/tools/release.sh
+++ b/tools/release.sh
@@ -46,7 +46,20 @@ mkdir -p "$stage/bin" "$stage/share/raea" "$out"
# the skills gate (docs/skills.feature SK9): the committed tree at REF against this release's raea, so a stale reference,
# a retired word, a flag no verb takes or a dead link refuses the release
gate=$(mktemp -d)
-git archive "$ref" | tar -x -C "$gate"
+# Windows makes no symlinks: tar fails on each of the tree's (sdk/*/node_modules, old content links), which the skills
+# check never reads. There, those failures alone are left out and counted; any other is the release's (T1f, 11-07)
+untar() {
+ local err rc=0
+ err=$(tar -x -C "$1" 2>&1 >/dev/null) || rc=$?
+ [ $rc -eq 0 ] && return 0
+ if [ "$platform" = windows-x86_64 ] && ! grep -v -e "Cannot create symlink" -e "Exiting with failure status" <<< "$err" | grep -q .; then
+ echo "release.sh: note: the skills gate left out $(grep -c "Cannot create symlink" <<< "$err") symlinks (Windows makes none)"
+ return 0
+ fi
+ printf '%s\n' "$err" >&2
+ return $rc
+}
+git archive "$ref" | untar "$gate" || { echo "release.sh: the skills gate couldn't unpack $ref" >&2; exit 1; }
git -C "$gate" init -q && git -C "$gate" add -A && git -C "$gate" -c user.name=release -c [email protected] commit -qm "$ref" --no-verify
raea_bin=$bin/raea; [ -f "$raea_bin.exe" ] && raea_bin=$raea_bin.exe
if ! (cd "$gate" && SKILLS_STRICT=1 SKILLS_CHANGED= RAEA_BIN="$raea_bin" RAEA_APP="$root/apps/app" RAEA_APP_REV="$(git -C "$root" rev-parse "$ref:apps/app")" bash tools/skills.sh check); then