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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
Layer pass, the 3D's half (docs/review.feature R2b, R2e; work in progress, parked with the source stamps): each Engine::draw records its frame's meshes with --layers (systems/frame layer.rs record: every shown Mesh3d from the lowest-order active Camera3d drawn on the CPU straight at mask size, nearest first, as the layer of the nearest part up with a LayerKey; skinned meshes posed by their joints; no morph targets), and the file's mask is the page's where it painted and the 3D's elsewhere (raster.rs, Recorder::frame_3d). Names: a use's outermost element is named after its component (Badge), an unnamed part after its tag (Mesh3d), else aria-label, class, tag. RAEA_LAYERS=1 turns it on too, until --layers is in the help with its manual entry. bench/layers: a third mesh in front of the moving cube, written before it; mutants.sh breaks the pass four ways (keys swapped, the 3D 2 px right, the farthest triangle winning, the page under the 3D): each fails compare.sh while the pass passes all 15 layers at IoU >= 0.969.
shinyobjectze02938531993
diff --git a/bench/layers/conformance.tsx b/bench/layers/conformance.tsxindex cf4717f0..b369854c 100644--- a/bench/layers/conformance.tsx+++ b/bench/layers/conformance.tsx@@ -16,6 +16,12 @@ const Shot = () => {<AbsoluteFill style={{ background: "#16202e" }}><Camera3d transform={Transform.fromXyz(0, 0, 6).lookingAt([0, 0, 0])} /><DirectionalLight illuminance={9000} transform={Transform.fromXyz(2, 4, 6).lookingAt([0, 0, 0])} />+ {/* in front of the moving cube's lower right, and written before it: a pass that draws in order, not by depth,+ puts the cube over it */}+ <Mesh3d transform={Transform.fromXyz(-0.1, -0.2, 1.4)}>+ <Cuboid half_size={[0.35, 0.35, 0.35]} />+ <StandardMaterial base_color="#3fa7ff" />+ </Mesh3d><Mesh3d transform={Transform.fromXyz(-0.6 + f * 0.01, 0.3, 0).withRotation(Quat.fromEuler("XYZ", 0.4, f * 0.02, 0))}><Cuboid half_size={[0.7, 0.7, 0.7]} /><StandardMaterial base_color="#2fbf71" />diff --git a/bench/layers/mutants.sh b/bench/layers/mutants.shnew file mode 100755index 00000000..84c96bfc--- /dev/null+++ b/bench/layers/mutants.sh@@ -0,0 +1,24 @@+#!/bin/bash+# The layer pass's mutants (docs/review.feature R2e): the pass broken four ways on purpose (RAEA_LAYERS_MUTANT, in+# raea-sys-layers): two layers' keys swapped, the 3D 2 px to the right, the 3D's occlusion ignored, the page drawn+# under the 3D. Each must fail compare.sh against the oracle; the unbroken pass must pass. Exits 1 when one doesn't.+# bench/layers/mutants.sh ORACLE OUT (ORACLE: oracle.sh's folder; RAEA_BIN: the raea to run)+cd "$(dirname "$0")/../.." || exit 2+ORACLE=${1:?ORACLE: oracle.sh OUT folder}+OUT=${2:?OUT folder}+BIN=${RAEA_BIN:-$PWD/target/release/raea}+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0 RAEA_SOURCE_STAMPS=1 RAEA_AUDIO_MUTE=1 RAEA_LAYERS=1+mkdir -p "$OUT/src"+cp bench/layers/conformance.tsx bench/layers/badge.tsx "$ORACLE/src/pic.png" "$OUT/src/"+status=0+for m in none swap shift occlusion under; do+ rm -rf "${OUT:?}/$m"+ RAEA_LAYERS_MUTANT=$m "$BIN" render "$OUT/src/conformance.tsx" --at 10,45,80 -o "$OUT/$m" > "$OUT/$m.log" 2>&1 || { echo "FAIL the render ($m) failed"; tail -3 "$OUT/$m.log"; exit 1; }+ bench/layers/compare.sh "$ORACLE" "$OUT/$m/conformance.layers" > "$OUT/$m.compare" 2>&1+ got=$?+ if [ "$m" = none ]; then+ if (( got == 0 )); then echo "ok the pass itself passes"; else echo "FAIL the pass itself fails:"; grep FAIL "$OUT/$m.compare" | sed 's/^/ /'; status=1; fi+ elif (( got == 1 )); then echo "ok mutant $m fails: $(grep -c FAIL "$OUT/$m.compare") layers"+ else echo "FAIL mutant $m passes the oracle"; status=1; fi+done+exit $statusdiff --git a/bench/layers/oracle.sh b/bench/layers/oracle.shindex 3a5b7c1e..18349a02 100755--- a/bench/layers/oracle.sh+++ b/bench/layers/oracle.sh@@ -23,7 +23,7 @@ B1=$(at conformance.tsx Badge 1); B2=$(at conformance.tsx Badge 2); LI=$(at conf# not the AbsoluteFill: its background over 3D is the 3D's clear (raea-runtime-export program.rs), behind every layer# and none of them, so hiding it changes nothing and the layer pass gives no layer thereKEYS=(- "$(at conformance.tsx Mesh3d 1)" "$(at conformance.tsx Mesh3d 2)"+ "$(at conformance.tsx Mesh3d 1)" "$(at conformance.tsx Mesh3d 2)" "$(at conformance.tsx Mesh3d 3)""$(at badge.tsx div 1)|$B1" "$(at badge.tsx span 1)|$B1" "$(at badge.tsx div 1)|$B2" "$(at badge.tsx span 1)|$B2""$(at conformance.tsx div 1)" "$(at conformance.tsx h1 1)" "$(at conformance.tsx Img 1)" "$(at conformance.tsx div 2)""$(at conformance.tsx ul 1)" "$LI#one" "$LI#two" "$LI#three"diff --git a/engine/render/src/engine.rs b/engine/render/src/engine.rsindex 6024b9d4..542fa5c4 100644--- a/engine/render/src/engine.rs+++ b/engine/render/src/engine.rs@@ -231,6 +231,7 @@ impl Engine {self.pipe.flush(&mut self.app);self.app.update();self.capture_aov(f);+ raea_sys_frame::layer::record(self.app.world_mut(), f);}/// With MotionBlur, the frame before the clock's drawn first (its readback ignored): Bevy takes each mesh's,diff --git a/runtime/export/src/render.rs b/runtime/export/src/render.rsindex 22f70ac7..cbb14607 100644--- a/runtime/export/src/render.rs+++ b/runtime/export/src/render.rs@@ -54,7 +54,7 @@ pub fn render(args: &[String]) -> R<String> {(_, Some(at)) => Some(at.split(',').map(|f| f.trim().parse::<i64>().map_err(|_| "--at takes frame numbers".to_string())).collect::<R<_>>()?),_ => None,};- let layers = raea_sys_layers::start(args.iter().any(|a| a == "--layers"), &out, &tsx);+ let layers = raea_sys_layers::start(args.iter().any(|a| a == "--layers") || std::env::var_os("RAEA_LAYERS").is_some_and(|v| v == "1"), &out, &tsx);*MANIFEST.lock().unwrap() = flag(args, "--manifest").map(PathBuf::from).or(layers);TEN_BIT.store(args.iter().any(|a| a == "--10bit"), std::sync::atomic::Ordering::Relaxed);AOV.store(args.iter().any(|a| a == "--aov"), std::sync::atomic::Ordering::Relaxed);diff --git a/systems/frame/src/layer.rs b/systems/frame/src/layer.rsindex 94e5e09e..f953d0b4 100644--- a/systems/frame/src/layer.rs+++ b/systems/frame/src/layer.rs@@ -12,3 +12,68 @@ pub struct LayerKey(pub String);/// The key a stamped element or part's props give it (raea-sys-layers owns it: the page's half reads it too).pub use raea_sys_layers::key_of;++/// With `raea render --layers`, frame `f`'s 3D recorded as layer indices (raea-sys-layers, docs/review.feature R2b):+/// every shown mesh drawn on the CPU from the frame's camera, nearest first, as the layer of the nearest part up from+/// it with a LayerKey (none: it still hides what's behind it). Skinned meshes are posed as their joints are; morph+/// targets and anything not a mesh (sprites, splats, particles) are not drawn.+pub fn record(world: &mut World, f: i64) {+ if !raea_sys_layers::on() {+ return;+ }+ let mut cams = world.query_filtered::<(&Camera, &GlobalTransform), With<Camera3d>>();+ let Some((cam, at)) = cams.iter(world).filter(|(c, _)| c.is_active).min_by_key(|(c, _)| c.order) else { return };+ let Some(size) = cam.physical_target_size() else { return };+ let clip_from_world = cam.clip_from_view() * Mat4::from(at.affine().inverse());+ let mut layers: Vec<raea_sys_layers::Layer> = Vec::new();+ let mut tris: Vec<raea_sys_layers::Tri> = Vec::new();+ let mut parts = world.query::<(Entity, &Mesh3d, &GlobalTransform, Option<&InheritedVisibility>, Option<&bevy::mesh::skinning::SkinnedMesh>)>();+ let (meshes, binds) = (world.resource::<Assets<Mesh>>(), world.resource::<Assets<bevy::mesh::skinning::SkinnedMeshInverseBindposes>>());+ for (e, m, place, shown, skin) in parts.iter(world) {+ if shown.is_some_and(|s| !s.get()) {+ continue;+ }+ let Some(mesh) = meshes.get(&m.0).filter(|m| m.primitive_topology() == bevy::mesh::PrimitiveTopology::TriangleList) else { continue };+ let Ok(Some(bevy::mesh::VertexAttributeValues::Float32x3(pos))) = mesh.try_attribute_option(Mesh::ATTRIBUTE_POSITION) else { continue };+ let joints = skin.and_then(|s| Some((s, binds.get(&s.inverse_bindposes)?))).map(|(s, b)| s.joints.iter().zip(b.iter()).map(|(j, ib)| world.get::<GlobalTransform>(*j).map_or(Mat4::IDENTITY, |g| Mat4::from(g.affine()) * *ib)).collect::<Vec<_>>());+ let posed = posed(mesh, pos, joints.as_deref(), Mat4::from(place.affine()));+ let clip: Vec<[f32; 4]> = posed.iter().map(|p| (clip_from_world * p.extend(1.0)).to_array()).collect();+ let v = keyed(world, e).map_or(0, |(key, name)| match layers.iter().position(|l| l.key == key) {+ Some(i) => i as u16 + 1,+ None => {+ layers.push(raea_sys_layers::Layer::of(key, "mesh", name, None, None));+ layers.len() as u16+ }+ });+ let corners: Vec<usize> = match mesh.try_indices_option() {+ Ok(Some(ix)) => ix.iter().collect(),+ _ => (0..clip.len()).collect(),+ };+ tris.extend(corners.chunks_exact(3).filter_map(|t| Some(([*clip.get(t[0])?, *clip.get(t[1])?, *clip.get(t[2])?], v))));+ }+ let mask = raea_sys_layers::raster((size.x, size.y), tris);+ raea_sys_layers::with(|r| r.frame_3d(f, size.x, &mask, &layers));+}++/// A mesh's vertices in the world: posed by its joints' matrices (a skin's, in place of its transform) or `place`.+fn posed(mesh: &Mesh, pos: &[[f32; 3]], joints: Option<&[Mat4]>, place: Mat4) -> Vec<Vec3> {+ use bevy::mesh::VertexAttributeValues as A;+ let skin = joints.zip(mesh.try_attribute_option(Mesh::ATTRIBUTE_JOINT_INDEX).ok().flatten()).zip(mesh.try_attribute_option(Mesh::ATTRIBUTE_JOINT_WEIGHT).ok().flatten());+ match skin {+ Some(((joints, A::Uint16x4(ix)), A::Float32x4(wt))) => pos.iter().zip(ix).zip(wt).map(|((p, i), w)| {+ let m = (0..4).fold(Mat4::ZERO, |m, k| m + joints.get(i[k] as usize).copied().unwrap_or(Mat4::IDENTITY) * w[k]);+ m.transform_point3(Vec3::from(*p))+ }).collect(),+ _ => pos.iter().map(|p| place.transform_point3(Vec3::from(*p))).collect(),+ }+}++/// The key and name of the nearest entity up from `e` (itself first) with a LayerKey.+fn keyed(world: &World, mut e: Entity) -> Option<(String, String)> {+ loop {+ if let Some(k) = world.get::<LayerKey>(e) {+ return Some((k.0.clone(), world.get::<Name>(e).map_or("mesh".into(), |n| n.as_str().to_string())));+ }+ e = world.get::<ChildOf>(e)?.parent();+ }+}diff --git a/systems/layers/src/file.rs b/systems/layers/src/file.rsindex 0cfde3dd..2f7e0d00 100644--- a/systems/layers/src/file.rs+++ b/systems/layers/src/file.rs@@ -12,6 +12,8 @@ use serde_json::json;use crate::Layer;pub const SCALE: u32 = 4;+/// a page sample where the page painted nothing (the 3D's shows there)+pub const NONE: u16 = u16::MAX;pub struct Recorder {path: PathBuf,@@ -23,34 +25,62 @@ pub struct Recorder {/// each layer's first and last frameseen: Vec<[i64; 2]>,by_key: HashMap<String, u16>,- /// each recorded frame's mask, as runs+ /// each recorded frame's page mask, as runs (NONE where the page painted nothing)masks: BTreeMap<i64, Vec<(u16, u16)>>,+ /// each 3D frame's mask (its width, its runs): what shows where the page painted nothing+ three: BTreeMap<i64, (usize, Vec<(u16, u16)>)>,+ /// the composition's folder, where the keys' files are: a use's root is named after its component from there+ src: Option<PathBuf>,}impl Recorder {pub fn new(path: PathBuf, video: String) -> Recorder {- Recorder { path, video, size: (0, 0), layers: Vec::new(), seen: Vec::new(), by_key: HashMap::new(), masks: BTreeMap::new() }+ Recorder { path, video, size: (0, 0), layers: Vec::new(), seen: Vec::new(), by_key: HashMap::new(), masks: BTreeMap::new(), three: BTreeMap::new(), src: None }}- /// Frame `f`'s layers: `px` (`w` x `h`, row-major) each pixel's index into `layers` plus one (0: none). A frame- /// recorded again replaces what it had (a page drawn twice in a frame).+ /// Layers at the root of a use of the edit's components named after the component (`Badge` for the element+ /// `<Badge />` drew outermost), from the sources in `dir`.+ pub fn named_from(mut self, dir: PathBuf) -> Recorder {+ self.src = Some(dir);+ self+ }++ /// The layer as the table lists it: an element or mesh that is the outermost of a use (its parent drawn outside+ /// that use) is named after the component used.+ fn named(&self, l: &Layer) -> Layer {+ let mut l = l.clone();+ let parent_uses = l.parent.as_ref().and_then(|p| self.by_key.get(p)).map(|i| &self.layers[*i as usize - 1].uses);+ let root = l.uses.first().filter(|_| matches!(l.kind, "element" | "mesh") && parent_uses != Some(&l.uses));+ if let Some(name) = root.zip(self.src.as_ref()).and_then(|(u, dir)| crate::names::component_at(dir, u)) {+ l.name = name;+ } else if let Some(name) = self.src.as_ref().filter(|_| l.kind == "mesh" && l.name == "mesh").and_then(|dir| crate::names::component_at(dir, &l.loc)) {+ // an unnamed part: the part it is ("Mesh3d", "Model")+ l.name = name;+ }+ l+ }++ /// Frame `f`'s page: `px` (`w` x `h`, row-major) each pixel's index into `layers` plus one (0: in no layer, NONE:+ /// nothing painted). A frame recorded again replaces what it had (a page drawn twice in a frame). The frames the+ /// page is recorded at are the file's.pub fn frame(&mut self, f: i64, w: u32, h: u32, px: &[u16], layers: &[Layer]) {self.size = (w, h);let global: Vec<u16> = std::iter::once(0).chain(layers.iter().map(|l| self.index(l, f))).collect();let (mw, mh) = (w.div_ceil(SCALE), h.div_ceil(SCALE));- let mut runs: Vec<(u16, u16)> = Vec::new();- for y in 0..mh {- let fy = (y * SCALE + SCALE / 2).min(h - 1);- for x in 0..mw {- let fx = (x * SCALE + SCALE / 2).min(w - 1);- let v = px.get((fy * w + fx) as usize).and_then(|v| global.get(*v as usize)).copied().unwrap_or(0);- match runs.last_mut() {- Some((lv, n)) if *lv == v && *n < u16::MAX => *n += 1,- _ => runs.push((v, 1)),- }- }- }- self.masks.insert(f, runs);+ let at = (0..mh).flat_map(|y| (0..mw).map(move |x| ((y * SCALE + SCALE / 2).min(h - 1), (x * SCALE + SCALE / 2).min(w - 1))));+ let mask = at.map(|(fy, fx)| match px.get((fy * w + fx) as usize) {+ Some(&NONE) | None => NONE,+ Some(v) => global.get(*v as usize).copied().unwrap_or(0),+ });+ self.masks.insert(f, runs(mask));+ }++ /// Frame `f`'s 3D, drawn to a target `w` px wide (the frame its top left): `mask` (its quarter, row-major, as+ /// `raster` gives it) each sample's index into `layers` plus one, 0 for none. It shows where the page painted+ /// nothing.+ pub fn frame_3d(&mut self, f: i64, w: u32, mask: &[u16], layers: &[Layer]) {+ let global: Vec<u16> = std::iter::once(0).chain(layers.iter().map(|l| self.index(l, f))).collect();+ self.three.insert(f, (w.div_ceil(SCALE) as usize, runs(mask.iter().map(|v| global.get(*v as usize).copied().unwrap_or(0)))));}/// A layer's value in the file (its place in the table plus one), added at its first frame.@@ -58,6 +88,7 @@ impl Recorder {let i = match self.by_key.get(&l.key) {Some(i) => *i,None => {+ let l = self.named(l);self.layers.push(l.clone());self.seen.push([f, f]);let i = self.layers.len() as u16;@@ -70,11 +101,23 @@ impl Recorder {i}+ /// Frame `f`'s mask as the file has it: the page's, the 3D's where the page painted nothing.+ fn composite(&self, f: i64) -> Vec<(u16, u16)> {+ let page = expand(&self.masks[&f]);+ let (tw, three) = self.three.get(&f).map(|(tw, r)| (*tw, expand(r))).unwrap_or_default();+ let mw = self.size.0.div_ceil(SCALE) as usize;+ let under = |i: usize| Some((i % mw, i / mw)).filter(|(x, _)| *x < tw).and_then(|(x, y)| three.get(y * tw + x)).copied().unwrap_or(0);+ let over = crate::mutant("under");+ runs(page.iter().enumerate().map(|(i, v)| if *v == NONE || (over && under(i) != 0) { under(i) } else { *v }))+ }+/// The header, as NAME.layers gives it.pub fn header(&self, fps: f64) -> serde_json::Value {let (w, h) = self.size;- let layers: Vec<_> = self.layers.iter().zip(&self.seen).map(|(l, s)| {- let mut v = json!({"key": l.key, "kind": l.kind, "name": l.name, "parent": l.parent, "loc": l.loc, "use": l.uses, "index": l.index, "frames": s});+ let keys: Vec<&str> = self.layers.iter().map(|l| l.key.as_str()).collect();+ let key = |i: usize| if crate::mutant("swap") && i < 2 && keys.len() > 1 { keys[1 - i] } else { keys[i] };+ let layers: Vec<_> = self.layers.iter().zip(&self.seen).enumerate().map(|(i, (l, s))| {+ let mut v = json!({"key": key(i), "kind": l.kind, "name": l.name, "parent": l.parent, "loc": l.loc, "use": l.uses, "index": l.index, "frames": s});if let Some(src) = &l.src {v["src"] = json!(src);}@@ -96,14 +139,15 @@ impl Recorder {let mut out = b"RAEALAYR".to_vec();out.extend((head.len() as u32).to_le_bytes());out.extend(head.as_bytes());- let mut before: Option<&Vec<(u16, u16)>> = None;- for runs in self.masks.values() {- if before == Some(runs) {+ let mut before: Option<Vec<(u16, u16)>> = None;+ for f in self.masks.keys() {+ let runs = self.composite(*f);+ if before.as_ref() == Some(&runs) {out.extend(0u32.to_le_bytes());continue;}out.extend((runs.len() as u32).to_le_bytes());- for (v, n) in runs {+ for (v, n) in &runs {out.extend(v.to_le_bytes());out.extend(n.to_le_bytes());}@@ -122,3 +166,19 @@ impl Recorder {Ok(self.path.file_name().map(|n| n.to_string_lossy().into_owned()))}}++/// Values as runs of one value, none past 65535 long.+fn runs(vals: impl Iterator<Item = u16>) -> Vec<(u16, u16)> {+ let mut out: Vec<(u16, u16)> = Vec::new();+ for v in vals {+ match out.last_mut() {+ Some((lv, n)) if *lv == v && *n < u16::MAX => *n += 1,+ _ => out.push((v, 1)),+ }+ }+ out+}++fn expand(runs: &[(u16, u16)]) -> Vec<u16> {+ runs.iter().flat_map(|(v, n)| std::iter::repeat_n(*v, *n as usize)).collect()+}diff --git a/systems/layers/src/lib.rs b/systems/layers/src/lib.rsindex f003d4d7..ba757cfb 100644--- a/systems/layers/src/lib.rs+++ b/systems/layers/src/lib.rs@@ -5,12 +5,15 @@//! 4y+2)); `Recorder` keeps them with the table of layers and writes NAME.layers (file.rs).mod file;+mod names;+mod raster;#[cfg(feature = "page")]mod page;#[cfg(feature = "page")]mod scene;pub use file::Recorder;+pub use raster::{Tri, raster};#[cfg(feature = "page")]pub use page::page_ids;@@ -51,6 +54,16 @@ pub struct Layer {pub src: Option<String>,}+impl Layer {+ /// A layer from its key (key_of's "loc[#index][|use|use…]"), split back into its stamp, place and uses.+ pub fn of(key: String, kind: &'static str, name: String, parent: Option<String>, src: Option<String>) -> Layer {+ let (loc, rest) = key.split_once('|').map_or((key.as_str(), None), |(l, r)| (l, Some(r)));+ let (loc, index) = loc.split_once('#').map_or((loc, None), |(l, i)| (l, Some(i.to_string())));+ let (loc, uses) = (loc.to_string(), rest.map(|r| r.split('|').map(str::to_string).collect()).unwrap_or_default());+ Layer { key, kind, name, parent, loc, uses, index, src }+ }+}+thread_local! {/// `raea render --layers`: the render's recorder (one render per thread)static ON: RefCell<Option<Recorder>> = const { RefCell::new(None) };@@ -62,7 +75,8 @@ pub fn start(on: bool, out: &std::path::Path, tsx: &std::path::Path) -> Option<Plet path = on.then(|| path_for(out, tsx));// a folder of frames is no video: its name stands for itlet video = out.file_name().unwrap_or_default().to_string_lossy().into_owned();- ON.with(|r| *r.borrow_mut() = path.clone().map(|p| Recorder::new(p, video)));+ let src = tsx.parent().map(PathBuf::from).unwrap_or_default();+ ON.with(|r| *r.borrow_mut() = path.clone().map(|p| Recorder::new(p, video).named_from(src)));path.map(|p| p.with_extension("render.json"))}@@ -100,3 +114,10 @@ pub fn path_for(out: &std::path::Path, tsx: &std::path::Path) -> PathBuf {#[cfg(test)]mod tests;++/// RAEA_LAYERS_MUTANT (bench/layers/mutants.sh): the pass broken on purpose, so the oracle is seen to catch it.+/// `swap` the first two layers' keys, `shift` the 3D 2 px right, `occlusion` the 3D's farthest triangle wins over its+/// nearest, `under` the 3D drawn over the page.+pub(crate) fn mutant(name: &str) -> bool {+ std::env::var("RAEA_LAYERS_MUTANT").is_ok_and(|m| m == name)+}diff --git a/systems/layers/src/names.rs b/systems/layers/src/names.rsnew file mode 100644index 00000000..76a23a96--- /dev/null+++ b/systems/layers/src/names.rs@@ -0,0 +1,22 @@+//! A layer's name: the component whose JSX drew it, read from the source at its use's loc.++/// The component a use's loc ("file:line:col", the col UTF-16 and 1-based, at its "<") names: `Badge` for+/// `<Badge x={1} />`, read from the source in `dir`. None when it can't be read.+pub fn component_at(dir: &std::path::Path, loc: &str) -> Option<String> {+ let mut it = loc.rsplitn(3, ':');+ let (col, line, file) = (it.next()?.parse::<usize>().ok()?, it.next()?.parse::<usize>().ok()?, it.next()?);+ let text = std::fs::read_to_string(dir.join(file)).ok()?;+ let row = text.lines().nth(line.checked_sub(1)?)?;+ // the UTF-16 column as a char offset+ let (mut units, mut start) = (0, None);+ for (i, c) in row.char_indices() {+ if units + 1 >= col {+ start = Some(i);+ break;+ }+ units += c.len_utf16();+ }+ let rest = row[start?..].strip_prefix('<')?;+ let name: String = rest.chars().take_while(|c| c.is_alphanumeric() || matches!(c, '_' | '$' | '.')).collect();+ (!name.is_empty()).then_some(name)+}diff --git a/systems/layers/src/page.rs b/systems/layers/src/page.rsindex b4908cbf..6664f6a7 100644--- a/systems/layers/src/page.rs+++ b/systems/layers/src/page.rs@@ -7,8 +7,9 @@ use blitz_dom::{BaseDocument, LocalName, NodeId};use crate::{Layer, key_of};-/// The page as layer keys: each pixel's (row-major, `w` x `h`; None where no layer shows) by its index in `layers`,-/// and the layers shown or laid out this frame, in document order. `scale`: page px to frame px.+/// The page as layer keys: each pixel's (row-major, `w` x `h`) index in `layers` plus one (0 where something in no+/// layer is drawn, file::NONE where nothing is), and the layers shown or laid out this frame, in document order.+/// `scale`: page px to frame px.pub fn page_ids(doc: &mut BaseDocument, scale: f64, w: u32, h: u32) -> (Vec<u16>, Vec<Layer>) {let mut ids: HashMap<NodeId, u16> = HashMap::new();let mut layers: Vec<Layer> = Vec::new();@@ -32,20 +33,12 @@ pub fn page_ids(doc: &mut BaseDocument, scale: f64, w: u32, h: u32) -> (Vec<u16>};let name = match kind {"text" => node.text_content().trim().chars().take(40).collect(),- _ => tag,+ // what a person would call it: its label, its first class, its tag (a use's root is named after its+ // component by the recorder)+ _ => attr("aria-label").or_else(|| attr("class").and_then(|c| c.split_whitespace().next())).map_or(tag, str::to_string),};- let (loc, rest) = key.split_once('|').map_or((key.as_str(), None), |(l, r)| (l, Some(r)));- let (loc, index) = loc.split_once('#').map_or((loc, None), |(l, i)| (l, Some(i.to_string())));- layers.push(Layer {- kind,- name,- parent: at.checked_sub(1).map(|p| layers[p as usize].key.clone()),- loc: loc.to_string(),- uses: rest.map(|r| r.split('|').map(str::to_string).collect()).unwrap_or_default(),- index,- src,- key,- });+ let parent = at.checked_sub(1).map(|p| layers[p as usize].key.clone());+ layers.push(Layer::of(key, kind, name, parent, src));at = layers.len() as u16;}if at > 0 {diff --git a/systems/layers/src/raster.rs b/systems/layers/src/raster.rsnew file mode 100644index 00000000..57c88b3a--- /dev/null+++ b/systems/layers/src/raster.rs@@ -0,0 +1,76 @@+//! The 3D's half of the layer pass: triangles in clip space drawn straight into the mask (one sample a mask pixel, at+//! frame px (4x + 2, 4y + 2) as the mask's own), nearest first, each triangle's value where it is in front. A+//! triangle crossing the camera's near side is cut there. Exact: no antialiasing, no colours to read back.++use crate::file::SCALE;++/// A triangle's corners in clip space (x, y, z, w) and the value it draws (0: in no layer, though it still hides+/// what's behind it).+pub type Tri = ([[f32; 4]; 3], u16);++/// The mask (`frame` is the frame's size in px, the mask its quarter, row-major) of `tris`: each sample the value of+/// the nearest triangle over it, 0 where none is.+pub fn raster(frame: (u32, u32), tris: impl IntoIterator<Item = Tri>) -> Vec<u16> {+ let (w, h) = frame;+ let (mw, mh) = (w.div_ceil(SCALE) as usize, h.div_ceil(SCALE) as usize);+ let mut ids = vec![0u16; mw * mh];+ // 1/w at each sample: nearer is bigger+ let mut near = vec![0f32; mw * mh];+ const EPS: f32 = 1e-5;+ let (shift, farthest) = (if crate::mutant("shift") { 2.0 } else { 0.0 }, crate::mutant("occlusion"));+ for (corners, v) in tris {+ for tri in cut(corners, EPS) {+ // frame px (pixel centers at +0.5), then mask px: frame px 4x + 2.5 is mask px x + 0.5+ let p: Vec<[f32; 3]> = tri.iter().map(|c| {+ let (fx, fy) = ((c[0] / c[3] + 1.0) * 0.5 * w as f32 + shift, (1.0 - c[1] / c[3]) * 0.5 * h as f32);+ [(fx - 2.5) / SCALE as f32 + 0.5, (fy - 2.5) / SCALE as f32 + 0.5, 1.0 / c[3]]+ }).collect();+ let area = (p[1][0] - p[0][0]) * (p[2][1] - p[0][1]) - (p[2][0] - p[0][0]) * (p[1][1] - p[0][1]);+ if area.abs() < 1e-12 {+ continue;+ }+ let x0 = p.iter().map(|q| q[0]).fold(f32::MAX, f32::min).floor().max(0.0) as usize;+ let x1 = (p.iter().map(|q| q[0]).fold(f32::MIN, f32::max).ceil().max(0.0) as usize).min(mw);+ let y0 = p.iter().map(|q| q[1]).fold(f32::MAX, f32::min).floor().max(0.0) as usize;+ let y1 = (p.iter().map(|q| q[1]).fold(f32::MIN, f32::max).ceil().max(0.0) as usize).min(mh);+ for y in y0..y1 {+ for x in x0..x1 {+ let (sx, sy) = (x as f32 + 0.5, y as f32 + 0.5);+ let e = |a: &[f32; 3], b: &[f32; 3]| ((b[0] - a[0]) * (sy - a[1]) - (sx - a[0]) * (b[1] - a[1])) / area;+ let (b0, b1, b2) = (e(&p[1], &p[2]), e(&p[2], &p[0]), e(&p[0], &p[1]));+ // inside, its edges' samples to one side only (a sample on an edge two triangles share is one's)+ let inside = |b: f32, a: &[f32; 3], c: &[f32; 3]| b > 0.0 || (b == 0.0 && ((c[1] - a[1]) * area.signum() < 0.0 || (c[1] == a[1] && (c[0] - a[0]) * area.signum() > 0.0)));+ if !(inside(b0, &p[1], &p[2]) && inside(b1, &p[2], &p[0]) && inside(b2, &p[0], &p[1])) {+ continue;+ }+ let inv_w = b0 * p[0][2] + b1 * p[1][2] + b2 * p[2][2];+ let i = y * mw + x;+ if (inv_w > near[i]) != (farthest && near[i] > 0.0) {+ near[i] = inv_w;+ ids[i] = v;+ }+ }+ }+ }+ }+ ids+}++/// The triangle's part in front of the camera (w > eps): none, one or two triangles.+fn cut(t: [[f32; 4]; 3], eps: f32) -> Vec<[[f32; 4]; 3]> {+ if t.iter().all(|c| c[3] > eps) {+ return vec![t];+ }+ let mut poly: Vec<[f32; 4]> = Vec::new();+ for i in 0..3 {+ let (a, b) = (t[i], t[(i + 1) % 3]);+ if a[3] > eps {+ poly.push(a);+ }+ if (a[3] > eps) != (b[3] > eps) {+ let s = (eps - a[3]) / (b[3] - a[3]);+ poly.push(std::array::from_fn(|k| a[k] + (b[k] - a[k]) * s));+ }+ }+ (1..poly.len().saturating_sub(1)).map(|i| [poly[0], poly[i], poly[i + 1]]).collect()+}diff --git a/systems/layers/src/scene.rs b/systems/layers/src/scene.rsindex f76f876c..27bf01a3 100644--- a/systems/layers/src/scene.rs+++ b/systems/layers/src/scene.rs@@ -31,12 +31,12 @@ impl<'a> IdScene<'a> {IdScene { ctx, resources: Resources::new(), ids }}- /// Each pixel's layer index, row-major.+ /// Each pixel's layer index, row-major (NONE where nothing was drawn).pub(crate) fn finish(mut self) -> Vec<u16> {self.ctx.flush();let mut px = Pixmap::new(self.ctx.width(), self.ctx.height());self.ctx.render(&mut px, &mut self.resources);- px.data().iter().map(|p| if p.a == 0 { 0 } else { p.r as u16 | (p.g as u16) << 8 }).collect()+ px.data().iter().map(|p| if p.a == 0 { crate::file::NONE } else { p.r as u16 | (p.g as u16) << 8 }).collect()}/// Ready to draw for the node being painted, at `transform`: false when its brush draws nothing.diff --git a/systems/layers/src/tests.rs b/systems/layers/src/tests.rsindex 80898a0a..52f85daa 100644--- a/systems/layers/src/tests.rs+++ b/systems/layers/src/tests.rs@@ -39,3 +39,51 @@ fn a_folder_of_frames_gets_the_compositions_name() {assert_eq!(path_for(std::path::Path::new("o/film.mp4"), std::path::Path::new("src/promo.tsx")), PathBuf::from("o/film.layers"));assert_eq!(path_for(std::path::Path::new("o/frames"), std::path::Path::new("src/promo.tsx")), PathBuf::from("o/frames/promo.layers"));}++#[test]+fn the_page_covers_the_3d_only_where_it_painted() {+ let mut r = Recorder::new("x.layers".into(), "x.mp4".into());+ // 8x4 frame, 2x1 mask: the page painted the left sample (layer p), nothing on the right+ let px: Vec<u16> = (0..32).map(|i| if i % 8 < 4 { 1 } else { file::NONE }).collect();+ r.frame(0, 8, 4, &px, &[layer("p", "element")]);+ // the 3D has mesh m under both samples+ r.frame_3d(0, 8, &[1, 1], &[layer("m", "mesh")]);+ let b = r.bytes(30.0);+ let n = u32::from_le_bytes(b[8..12].try_into().unwrap()) as usize;+ let words: Vec<u16> = b[12 + n..].chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();+ // p is 1, m is 2: left p, right m+ assert_eq!(words, vec![2, 0, 1, 1, 2, 1]);+}++#[test]+fn the_nearest_triangle_wins_and_one_behind_the_camera_is_cut() {+ // a 16x8 frame is a 4x2 mask; a big triangle at w = 2 (value 1) and a nearer one at w = 1 (value 2) over the+ // left half only+ let far = ([[-3.0 * 2.0, -3.0 * 2.0, 0.0, 2.0], [3.0 * 2.0, -3.0 * 2.0, 0.0, 2.0], [0.0, 3.0 * 2.0, 0.0, 2.0]], 1);+ let near = ([[-1.0, -1.0, 0.0, 1.0], [0.2, -1.0, 0.0, 1.0], [-1.0, 1.4, 0.0, 1.0]], 2);+ let m = raster((16, 8), [far, near]);+ assert_eq!(m.len(), 8);+ assert_eq!(m[0], 2, "the near one over the top left: {m:?}");+ assert_eq!(m[3], 1, "the far one over the top right: {m:?}");+ // all behind the camera: nothing+ let behind = ([[0.0, 0.0, 0.0, -1.0], [1.0, 0.0, 0.0, -1.0], [0.0, 1.0, 0.0, -1.0]], 3);+ assert!(raster((16, 8), [behind]).iter().all(|v| *v == 0));+}++#[test]+fn a_uses_root_is_named_after_its_component() {+ let dir = std::env::temp_dir().join(format!("raea-layers-names-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("comp.tsx"), "const a = 1;\n <Card x={1} />\n <motion.Div />\n").unwrap();+ assert_eq!(names::component_at(&dir, "comp.tsx:2:3").as_deref(), Some("Card"));+ assert_eq!(names::component_at(&dir, "comp.tsx:3:3").as_deref(), Some("motion.Div"));+ assert_eq!(names::component_at(&dir, "comp.tsx:1:1"), None);+ let mut r = Recorder::new("x.layers".into(), "x.mp4".into()).named_from(dir.clone());+ let root = Layer::of("card.tsx:1:1|comp.tsx:2:3".into(), "element", "div".into(), Some("top.tsx:1:1".into()), None);+ let inner = Layer::of("card.tsx:2:1|comp.tsx:2:3".into(), "element", "span".into(), Some(root.key.clone()), None);+ r.frame(0, 4, 4, &[1; 16], &[layer("top.tsx:1:1", "element"), root, inner]);+ let head = r.header(30.0);+ assert_eq!(head["layers"][1]["name"], "Card");+ assert_eq!(head["layers"][2]["name"], "span", "inside the use, not its root");+ let _ = std::fs::remove_dir_all(dir);+}