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.

A compute's uniforms follow the frame, in a PNG render and an mp4

shinyobjectz1a516a8de19a
diff --git a/bench/compute-frames/check.sh b/bench/compute-frames/check.sh
new file mode 100755
index 00000000..1304a11a
--- /dev/null
+++ b/bench/compute-frames/check.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# An inline <Compute> whose uniform changes every frame (level.tsx: `level` f / 20, the grey it fills a render image
+# with). Each frame must show its own frame's grey, both in a PNG render (-o DIR) and in an mp4 (the fed render, whose
+# 3D is live): frame 10 is level 0.5, sRGB 188; frame 0 is black. Before, a compute's uniforms were its first frame's
+# (the spec is held from frame 0), and the mp4's live rows were read from the load's columns, so an mp4 of a compute
+# driven by its uniforms stayed black. Exits 1 on a failure.
+# bench/compute-frames/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
+cd "$(dirname "$0")/../.." || exit 2
+BIN=${RAEA_BIN:-$PWD/target/release/raea}
+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
+OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-compute-frames.XXXXXX")
+trap 'rm -rf "$OUT"' EXIT
+grey() { magick "$1" -format "%[fx:round(255*p{64,64}.r)]" info:; }
+status=0
+"$BIN" render bench/compute-frames/level.tsx -o "$OUT/dir" > "$OUT/dir.log" 2>&1 || { echo "FAIL: the PNG render failed"; grep -v WARN "$OUT/dir.log" | tail -3; exit 1; }
+for k in 0 10; do
+ want=$([ $k = 0 ] && echo 0 || echo 188)
+ got=$(grey "$OUT/dir/$(printf 'frame-%05d.png' $k)")
+ [ "$got" = "$want" ] || { echo "FAIL: PNG frame $k is grey $got, not $want"; status=1; }
+done
+"$BIN" render bench/compute-frames/level.tsx -o "$OUT/out.mp4" > "$OUT/mp4.log" 2>&1 || { echo "FAIL: the mp4 render failed"; grep -v WARN "$OUT/mp4.log" | tail -3; exit 1; }
+for k in 0 10; do
+ want=$([ $k = 0 ] && echo 0 || echo 188)
+ ffmpeg -v error -i "$OUT/out.mp4" -vf "select=eq(n\,$k)" -frames:v 1 -y "$OUT/mp4-$k.png" || { echo "FAIL: no mp4 frame $k"; status=1; continue; }
+ got=$(grey "$OUT/mp4-$k.png")
+ # the mp4's YUV round trip moves a grey by a few levels
+ [ $(( got > want ? got - want : want - got )) -le 4 ] || { echo "FAIL: mp4 frame $k is grey $got, not $want (within 4)"; status=1; }
+done
+[ $status = 0 ] && echo "PASS: a compute's per-frame uniform reaches frame 10 in a PNG render (188) and an mp4 (within 4)"
+exit $status
diff --git a/bench/compute-frames/level.tsx b/bench/compute-frames/level.tsx
new file mode 100644
index 00000000..ddcf8cec
--- /dev/null
+++ b/bench/compute-frames/level.tsx
@@ -0,0 +1,23 @@
+// bench/compute-frames: an inline <Compute> fills a 64 x 64 render image with the grey its uniform `level` gives,
+// f / 20 at frame f, and a Sprite shows it over the whole 128 x 128 frame (check.sh).
+import { Composition, registerRoot, useCurrentFrame } from "raea";
+import { Canvas3D, Compute, Sprite } from "raea/3d";
+
+const FILL = `
+@compute @workgroup_size(8, 8, 1)
+fn main(@builtin(global_invocation_id) id: vec3<u32>) {
+ let l = u_level();
+ textureStore(out, vec2<i32>(id.xy), vec4<f32>(l, l, l, 1.0));
+}`;
+
+function Shot() {
+ const f = useCurrentFrame();
+ return (
+ <Canvas3D layered clearColor="#000000">
+ <Compute wesl={FILL} workgroups={[8, 8, 1]} uniforms={{ level: f / 20 }} images={{ out: "render:level:64x64" }} />
+ <Sprite src="render:level:64x64" x={64} y={64} width={64} height={64} scale={2} />
+ </Canvas3D>
+ );
+}
+
+registerRoot(() => <Composition id="main" component={Shot} durationInFrames={12} fps={30} width={128} height={128} />);
diff --git a/sdk/render/src/3d/compute.tsx b/sdk/render/src/3d/compute.tsx
index 61f0ae63..18978031 100644
--- a/sdk/render/src/3d/compute.tsx
+++ b/sdk/render/src/3d/compute.tsx
@@ -64,7 +64,7 @@ function written(props: ComputeProps) {
if (entry !== null && (typeof entry !== "string" || !IDENT.test(entry))) throw new TypeError(`Compute: entry is an entry point's name or null, got ${JSON.stringify(entry)}`);
for (const [k, key] of Object.entries(bind)) if (typeof key !== "string" || !(key in images)) throw new TypeError(`Compute: bind ${k} is one of its images' keys (${Object.keys(images).join(", ")}), got ${JSON.stringify(key)}`);
const shader = { file: assetPath(file), workgroups, images, uniforms, buffers,...(defs !== undefined ? { defs: shaderDefs("Compute", defs) } : {}) };
- return node3d("Compute", { shader, entry: entry ?? "", bind: JSON.stringify(bind) });
+ return node3d("Compute", { shader, entry: entry ?? "", bind: JSON.stringify(bind), uniforms: JSON.stringify(uniforms) });
}
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -93,5 +93,6 @@ export function Compute(props: ComputeProps) {
if (typeof im !== "string" || !im.startsWith("render:")) throw new TypeError(`Compute: image ${k} is a "render:NAME", got ${JSON.stringify(im)}`);
}
const shader = { ...(wesl !== undefined ? { wesl } : { wgsl }), workgroups, uniforms, buffers, images, ...(defs !== undefined ? { defs: shaderDefs("Compute", defs) } : {}) };
- return node3d("Compute", { shader });
+ // its uniforms again as a keyed column, so a value that changes from frame to frame reaches it (the spec is its first frame's)
+ return node3d("Compute", { shader, uniforms: JSON.stringify(uniforms) });
}
diff --git a/systems/compute/src/lib.rs b/systems/compute/src/lib.rs
index c5bbcbcb..957527e4 100644
--- a/systems/compute/src/lib.rs
+++ b/systems/compute/src/lib.rs
@@ -45,6 +45,11 @@ pub struct Compute {
pub images: Vec<Handle<Image>>,
/// a compute as written (a <Compute file>): its own bindings, entry and images (written.rs)
pub written: Option<written::Written>,
+ /// its row's id, whose keyed `uniforms` column it follows frame by frame; its uniforms' names, in slot order; the
+ /// column last followed
+ pub id: String,
+ pub names: Vec<String>,
+ pub given: String,
}
/// The frame's computes, in order, and the frame's time.
@@ -80,7 +85,7 @@ pub fn build(world: &mut World, v: &Value, id: &str, mut image: impl FnMut(&mut
let workgroups = workgroups(o)?;
if o.contains_key("file") {
let (shader, w) = written::build(world, o, id, &mut image)?;
- return Ok(Compute { shader, workgroups, slots: [Vec4::ZERO; SLOTS], buffers: vec![], images: vec![], written: Some(w) });
+ return Ok(Compute { shader, workgroups, slots: [Vec4::ZERO; SLOTS], buffers: vec![], images: vec![], written: Some(w), id: id.to_string(), names: vec![], given: String::new() });
}
let ins = Inputs::read(world, o, "a compute", &mut image)?;
if !ins.textures.is_empty() || ins.array.is_some() {
@@ -131,7 +136,8 @@ pub fn build(world: &mut World, v: &Value, id: &str, mut image: impl FnMut(&mut
let (names, _) = ins.names();
let bnames: Vec<String> = buffers.iter().map(|b| b.0.clone()).collect();
let shader = register(world, module(&ins.src, &names, &bnames, &inames), &ins.defs, "raea compute", "raea_sys_compute");
- Ok(Compute { shader, workgroups, slots: ins.slots(), buffers, images, written: None })
+ let uniforms = names.iter().map(|(n, _)| n.clone()).collect();
+ Ok(Compute { shader, workgroups, slots: ins.slots(), buffers, images, written: None, id: id.to_string(), names: uniforms, given: String::new() })
}
/// A spec's workgroups, [x(, y(, z))], each 1 to 65535.
@@ -172,21 +178,42 @@ fn storage_slabs(w: &mut World) {
fn follow(frame: Option<Res<raea_sys_frame::FrameRows>>, mut c: ResMut<Computes>, parts: Query<(&Name, &Mesh3d)>) {
let Some(frame) = frame else { return };
let cols = &frame.cols;
- for w in c.list.iter_mut().filter_map(|c| c.written.as_mut()) {
+ for c in c.list.iter_mut() {
+ let Some(r) = cols.id.iter().position(|i| *i == c.id) else { continue };
+ let s = |k: &str| raea_sys_frame::keyed(|col| frame.at(r, col), k).unwrap_or_default();
+ let Some(w) = c.written.as_mut() else {
+ if let Err(e) = inline_uniforms(c, &s("uniforms")) {
+ error!("Compute {}: {e}", c.id);
+ }
+ continue;
+ };
for b in w.buffers.values_mut() {
if let written::Bound::Mesh { name, id, .. } = b {
*id = parts.iter().find(|(n, _)| n.as_str() == name).map(|(_, m)| m.id());
}
}
- let Some(r) = cols.id.iter().position(|i| *i == w.id) else { continue };
- let s = |k: &str| raea_sys_frame::keyed(|c| cols.get(r, c), k).unwrap_or_default();
- if let Err(e) = written::follow(w, &s("entry"), &s("bind")) {
+ if let Err(e) = written::follow(w, &s("entry"), &s("bind")).and_then(|_| written::follow_uniforms(w, &s("uniforms"))) {
error!("Compute {}: {e}", w.id);
w.entry = None;
}
}
}
+/// This frame's `uniforms` column (JSON, {NAME: value}) into an inline compute's slots, when it has changed; a name
+/// it wasn't built with is refused (its slots are fixed at build).
+fn inline_uniforms(c: &mut Compute, uniforms: &str) -> Result<(), String> {
+ if uniforms.is_empty() || c.given == uniforms {
+ return Ok(());
+ }
+ c.given = uniforms.to_string();
+ let given: serde_json::Map<String, Value> = serde_json::from_str(uniforms).map_err(|e| format!("uniforms: {e}"))?;
+ for (k, x) in &given {
+ let i = c.names.iter().position(|n| n == k).ok_or_else(|| format!("uniform {k} isn't one it was built with ({:?})", c.names))?;
+ c.slots[i] = raea_sys_material::shader_material::uniform(k, x)?.value;
+ }
+ Ok(())
+}
+
/// The frame's time onto the computes (so they're extracted each frame).
fn stamp(time: Res<Time>, mut c: ResMut<Computes>) {
if !c.list.is_empty() {
@@ -265,15 +292,15 @@ fn dispatch(c: Option<Res<Computes>>, mut s: ResMut<State>, cache: Res<PipelineC
};
bufs.insert(name.clone(), buf);
}
- let uniforms = match &w.ranged {
- Some(r) => match r.pack(&|b, end| ranges.get(b).map(|r| r[end as usize])) {
+ let uniforms = match w.ranged {
+ true => match w.packer.pack(&|b, end| ranges.get(b).map(|r| r[end as usize])) {
Ok((u, _)) => u,
Err(e) => {
error!("Compute {}: {e}", w.id);
continue;
}
},
- None => w.uniforms.clone(),
+ false => w.uniforms.clone(),
};
if let Some(group) = written::group(&device, &layout, w, &images, &bufs, &uniforms) {
groups.push((pipeline, group, k.workgroups));
diff --git a/systems/compute/src/slab.rs b/systems/compute/src/slab.rs
index f7cf712c..6ee37c2e 100644
--- a/systems/compute/src/slab.rs
+++ b/systems/compute/src/slab.rs
@@ -31,7 +31,7 @@ pub struct Ranged {
src: String,
defs: Vec<ShaderDefVal>,
declared: Vec<(String, String)>,
- given: Map<String, Value>,
+ pub given: Map<String, Value>,
}
impl Ranged {
diff --git a/systems/compute/src/written.rs b/systems/compute/src/written.rs
index 6a61f4e9..592a7717 100644
--- a/systems/compute/src/written.rs
+++ b/systems/compute/src/written.rs
@@ -45,7 +45,12 @@ pub struct Written {
pub entries: Vec<String>,
/// each storage buffer's binding, by its name
pub buffers: BTreeMap<String, Bound>,
- pub ranged: Option<Ranged>,
+ /// its uniforms' values, packed again when its row's keyed `uniforms` column changes (follow_uniforms), and each
+ /// frame when a field is a mesh's range in its slab (`ranged`)
+ pub packer: Ranged,
+ pub ranged: bool,
+ /// the `uniforms` column last followed
+ pub given: String,
}
fn format(f: &str) -> Option<TextureFormat> {
@@ -123,6 +128,19 @@ pub fn follow(w: &mut Written, entry: &str, bind: &str) -> Result<(), String> {
frame(w, &o)
}
+/// This frame's `uniforms` column (JSON, {NAME: value}) packed into its uniforms, when it has changed ("": as built).
+pub fn follow_uniforms(w: &mut Written, uniforms: &str) -> Result<(), String> {
+ if uniforms.is_empty() || w.given == uniforms {
+ return Ok(());
+ }
+ w.given = uniforms.to_string();
+ w.packer.given = serde_json::from_str(uniforms).map_err(|e| format!("uniforms: {e}"))?;
+ if !w.ranged {
+ w.uniforms = w.packer.pack(&|_, _| Some(0))?.0;
+ }
+ Ok(())
+}
+
/// Every entry and binding its row's columns take over the run (raea-sys-frame's keyed_all), checked at load; that a
/// frame's binding binds every storage texture its entry needs is checked frame by frame (follow).
pub fn check(w: &mut Written, entries: &[String], binds: &[String]) -> Result<(), String> {
@@ -184,10 +202,10 @@ pub fn build(world: &mut World, o: &serde_json::Map<String, Value>, id: &str, im
let ranged = Ranged::new(&src, &defs, declared, given);
// packed with each slab range 0, to check them; a run's own ranges are packed frame by frame (lib.rs dispatch)
let (uniforms, has_ranges) = ranged.pack(&|b, _| matches!(buffers.get(b), Some(Bound::Mesh { .. })).then_some(0)).map_err(|e| format!("{path}: {e}"))?;
- let ranged = has_ranges.then_some(ranged);
+ let (packer, ranged) = (ranged, has_ranges);
let entries = entries(&src);
let shader = raea_sys_shader::register(world, src, &defs, "raea compute as written", "raea_sys_compute");
- Ok((shader, Written { decls, images, uniforms, entry: None, bind: BTreeMap::new(), id: id.to_string(), seen: Default::default(), entries, buffers, ranged }))
+ Ok((shader, Written { decls, images, uniforms, entry: None, bind: BTreeMap::new(), id: id.to_string(), seen: Default::default(), entries, buffers, packer, ranged, given: String::new() }))
}
/// The bind group layout its declarations make, in the compute stage.
@@ -233,7 +251,7 @@ mod tests {
assert_eq!(d[2], Decl::Uniform { binding: 2, name: "config".into(), ty: "Cfg".into() });
assert_eq!(decls("@group(0) @binding(1) var<storage, read_write> b: array<f32>;").unwrap()[0], Decl::Buffer { binding: 1, name: "b".into(), ty: "array<f32>".into(), read_only: false });
assert!(decls("@group(0) @binding(0) var<workgroup> b: f32;").unwrap_err().contains("var<storage>"));
- let mut w = Written { decls: d, images: [("a".to_string(), Handle::default()), ("b".to_string(), Handle::default())].into(), uniforms: BTreeMap::new(), entry: None, bind: BTreeMap::new(), id: "compute0".into(), seen: Default::default(), entries: vec!["init".into(), "update".into()], buffers: BTreeMap::new(), ranged: None };
+ let mut w = Written { decls: d, images: [("a".to_string(), Handle::default()), ("b".to_string(), Handle::default())].into(), uniforms: BTreeMap::new(), entry: None, bind: BTreeMap::new(), id: "compute0".into(), seen: Default::default(), entries: vec!["init".into(), "update".into()], buffers: BTreeMap::new(), packer: super::Ranged::new("", &[], vec![], Default::default()), ranged: false, given: String::new() };
assert_eq!(entries("@compute @workgroup_size(8, 8, 1)\nfn init(@builtin(x) i: u32) {}\n@compute @workgroup_size(1)\nfn update_2() {}"), ["init", "update_2"]);
assert!(check(&mut w, &["init".into(), "".into()], &[r#"{"input": "a"}"#.into()]).is_ok());
assert!(check(&mut w, &["main".into()], &[]).unwrap_err().contains("entry main"));
diff --git a/systems/frame/src/lib.rs b/systems/frame/src/lib.rs
index 777a1aff..3cdf29c8 100644
--- a/systems/frame/src/lib.rs
+++ b/systems/frame/src/lib.rs
@@ -100,6 +100,15 @@ impl FrameRows {
}
}
+ /// A row's value this frame by its place (`cols.id`'s): a live row's as a live frame set it, else the timeline's at the
+ /// clock. A system following a row's keyed column reads it here: `cols` alone holds a live render's first frame.
+ pub fn at(&self, r: usize, c: &str) -> Option<V> {
+ match &self.live {
+ Some(rows) => rows.get(r)?.get(c).cloned(),
+ None => self.cols.get(r, c),
+ }
+ }
+
/// 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)?;
diff --git a/systems/framepass/src/lib.rs b/systems/framepass/src/lib.rs
index 0609199b..bc16bb6e 100644
--- a/systems/framepass/src/lib.rs
+++ b/systems/framepass/src/lib.rs
@@ -156,7 +156,7 @@ fn follow(frame: Option<Res<raea_sys_frame::FrameRows>>, mut cams: Query<&mut Fr
let mut changed = false;
for w in passes.bypass_change_detection().0.iter_mut().filter_map(|p| p.written.as_mut()) {
let Some(r) = cols.id.iter().position(|i| *i == w.id) else { continue };
- match w.follow(&raea_sys_frame::keyed(|c| cols.get(r, c), "uniforms").unwrap_or_default()) {
+ match w.follow(&raea_sys_frame::keyed(|c| frame.at(r, c), "uniforms").unwrap_or_default()) {
Ok(c) => changed |= c,
Err(e) => error!("FramePass {}: {e}", w.id),
}
diff --git a/tools/layers.toml b/tools/layers.toml
index 4a47d990..2afd2191 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -165,6 +165,7 @@ ui-parity = "tools"
ui-parity-compare = "tools"
conformance-fake = "tools"
rtools = "tools"
+skillcheck = "tools"
seetool = "tools"
# systems that hold only a facility another system may build on (docs/overhaul.md: the mixer graph, ONNX sessions,