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
SG1: a ShaderExtension's uniforms follow the frame
shinyobjectzabead7eae410
diff --git a/docs/stage-guards.feature b/docs/stage-guards.featureindex 0c86e940..2d9a3e40 100644--- a/docs/stage-guards.feature+++ b/docs/stage-guards.feature@@ -100,6 +100,12 @@ Feature: Stage guards: a 3D render an agent can't break# runtime/live/tests/stage_guards.rs passes (5 tests; live_emissive and live_sheet still pass). Left: SG0's# renders of the repros, and a shader's `three` and `shader` columns, whose uniforms change every frame# (frozen uniforms keep their own fix rather than a part spawned each frame).+ # Status 11-21 (stage-guards-15): the `shader` column's uniforms follow the frame. A ShaderExtension whose uniform+ # was the frame over 89 (blue to red) drew frame 0's blue all video long on main, and SG9 failed it ("frame 89+ # card: 30136 pixels differ from the frame rendered alone"); now it goes blue, purple, red and SG9 passes. Its+ # uniforms go as `own:uniforms` rows, as a <Material>'s do (runtime/look own_uniforms, `ext` for a 3D mesh), and+ # raea-sys-shader own_live.rs packs them into the shaded material's slots when they change (ShaderExt slots_for).+ # `three` sends its uniforms each frame as `three:uniforms` rows (R3F11).Scenario: SG2. A part never inherits another part's rowThe cause was live.rs: a text block kept the id its frame gave it (`text0` is the frame's first block), where adiff --git a/runtime/look/src/parts.rs b/runtime/look/src/parts.rsindex 10a0af5b..47bf2af5 100644--- a/runtime/look/src/parts.rs+++ b/runtime/look/src/parts.rs@@ -56,10 +56,11 @@ pub fn keyed_vec(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its:/// `own:uniforms` component rows from each frame they change, which raea-sys-shader's own_live.rs packs into the/// part's Material; none when they never change over a render's frames (the spec the part is made with holds them),/// but one for a single frame (live play's, whose next frame may change them). `spec` finds an item's Material spec: a-/// mesh's material's `shader`, a 2D part's own. Called after the part's row is pushed.-pub fn own_uniforms(p: &mut Program, id: &str, its: &[Item], spec: impl Fn(&Item) -> Option<&Value>) {+/// mesh's material's `shader`, a 2D part's own. With `ext`, a ShaderExtension's spec (no `own`) is sent too: its+/// uniforms froze at the part's first frame without (docs/stage-guards.feature SG1). Called after the part's row is pushed.+pub fn own_uniforms(p: &mut Program, id: &str, its: &[Item], ext: bool, spec: impl Fn(&Item) -> Option<&Value>) {let each: Vec<(usize, Value)> = its.iter().enumerate().filter_map(|(f, it)| {- let s = spec(it).filter(|s| s.get("own").is_some())?;+ let s = spec(it).filter(|s| ext || s.get("own").is_some())?;let v = serde_json::json!({ "uniforms": s.get("uniforms").cloned().unwrap_or(Value::Null), "buffers": s.get("buffers").cloned().unwrap_or(Value::Null) });Some((f, serde_json::json!({ "type": "own:uniforms", "value": v })))}).collect();diff --git a/runtime/scene/src/parts.rs b/runtime/scene/src/parts.rsindex 7ee0bde0..733658a1 100644--- a/runtime/scene/src/parts.rs+++ b/runtime/scene/src/parts.rs@@ -278,7 +278,7 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {components(p, &id, &its);material_fields(p, &id, &its);three_uniforms(p, &id, &its);- own_uniforms(p, &id, &its, |it| it.material.as_ref()?.props.get("shader"));+ own_uniforms(p, &id, &its, true, |it| it.material.as_ref()?.props.get("shader"));}}diff --git a/runtime/scene2d/src/lib.rs b/runtime/scene2d/src/lib.rsindex 49c92b93..2c28a46f 100644--- a/runtime/scene2d/src/lib.rs+++ b/runtime/scene2d/src/lib.rs@@ -66,7 +66,7 @@ pub fn sprites(tracks: &[Track], p: &mut Program) {place2d(p, &mut row, &id, &its, "#ffffff");visible(p, &mut row, &id, track);p.spawns.push(("sprite".into(), vec![row]));- own_uniforms(p, &id, &its, |it| it.props.get("shader"));+ own_uniforms(p, &id, &its, false, |it| it.props.get("shader"));}}@@ -99,7 +99,7 @@ pub fn shapes(tracks: &[Track], p: &mut Program) {place2d(p, &mut row, &id, &its, "#ffffff");visible(p, &mut row, &id, track);p.spawns.push(("shape2d".into(), vec![row]));- own_uniforms(p, &id, &its, |it| it.props.get("shader"));+ own_uniforms(p, &id, &its, false, |it| it.props.get("shader"));}}diff --git a/systems/shader/src/lib.rs b/systems/shader/src/lib.rsindex b9a77482..c426d1d2 100644--- a/systems/shader/src/lib.rs+++ b/systems/shader/src/lib.rs@@ -68,7 +68,7 @@ pub fn install(app: &mut App) {#[bind_group_data(ExtKey)]pub struct ShaderExt {#[uniform(100)]- slots: [Vec4; SLOTS],+ pub(crate) slots: [Vec4; SLOTS],// one sampler for all four (the first texture's): the standard material and the view already bind 13 of the// fragment stage's 16 samplers, so four more failed the pipeline ("Too many bindings of type Samplers", 17)#[texture(101)]@@ -84,6 +84,35 @@ pub struct ShaderExt {#[texture(109, dimension = "2d_array")]arr: Option<Handle<Image>>,shader: u128,+ /// how a frame's uniforms repack `slots` (own_live.rs: a ShaderExtension's uniforms that change over the frames)+ #[reflect(ignore)]+ repack: Option<std::sync::Arc<Repack>>,+}++/// What a ShaderExt's slots are packed from: its uniforms' names in slot order with their first values, and its own+/// @binding(100) struct's fields when the source declares one (layout.rs)+#[derive(Debug)]+pub struct Repack {+ names: Vec<String>,+ first: Vec<Vec4>,+ fields: Option<Vec<(String, String)>>,+}++impl ShaderExt {+ /// The slots a frame's uniforms ({name: value}) pack into, None when they're the ones it holds; a uniform the+ /// frame doesn't give takes its first value+ pub fn slots_for(&self, given: &serde_json::Map<String, Value>) -> Result<Option<[Vec4; SLOTS]>, String> {+ let Some(r) = &self.repack else { return Ok(None) };+ let mut vals = Vec::with_capacity(r.names.len());+ for (n, f) in r.names.iter().zip(&r.first) {+ vals.push((n.clone(), given.get(n).map(|x| uniform(n, x).map(|u| u.value)).transpose()?.unwrap_or(*f)));+ }+ let slots = match &r.fields {+ Some(fields) => layout::pack(fields, &vals)?,+ None => std::array::from_fn(|i| vals.get(i).map_or(Vec4::ZERO, |v| v.1)),+ };+ Ok((slots != self.slots).then_some(slots))+ }}/// What picks a ShaderExt's pipeline: its shader's uuid.@@ -326,16 +355,18 @@ pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Vatrue => ext_bind::fit(&ins.src, &ins.textures)?,false => (ins.src.clone(), ins.textures.iter().map(|x| Some(x.1.clone())).collect()),};- let (src, slots) = match layout::own_struct(&own, &ins.defs).or_else(|| file.then(|| Ok(vec![]))) {+ let (src, slots, fields) = match layout::own_struct(&own, &ins.defs).or_else(|| file.then(|| Ok(vec![]))) {Some(fields) => {- let vals: Vec<(String, Vec4)> = ins.uniforms.iter().map(|u| (u.name.clone(), u.value)).collect();- (own, layout::pack(&fields?, &vals)?)+ let (fields, vals) = (fields?, ins.uniforms.iter().map(|u| (u.name.clone(), u.value)).collect::<Vec<_>>());+ (own, layout::pack(&fields, &vals)?, Some(fields))}- None => (module(&ins.src, &names, &tnames, ins.array.as_ref().map(|a| a.0.as_str())), ins.slots()),+ None => (module(&ins.src, &names, &tnames, ins.array.as_ref().map(|a| a.0.as_str())), ins.slots(), None),};+ let (names, first) = ins.uniforms.iter().map(|u| (u.name.clone(), u.value)).unzip();+ let repack = (!ins.uniforms.is_empty()).then(|| std::sync::Arc::new(Repack { names, first, fields }));let id = register(world, src, &ins.defs, "raea surface shader", "raea_sys_shader");let mut t = tex.into_iter();- Ok(ShaderExt { slots, tex0: t.next().flatten(), tex1: t.next().flatten(), tex2: t.next().flatten(), tex3: t.next().flatten(), arr: ins.array.map(|a| a.1), shader: id })+ Ok(ShaderExt { slots, tex0: t.next().flatten(), tex1: t.next().flatten(), tex2: t.next().flatten(), tex3: t.next().flatten(), arr: ins.array.map(|a| a.1), shader: id, repack })}/// A mesh row's shader put on its part: a <Material>'s own (own.rs) or a ShaderExtension over its standard material.@@ -347,7 +378,8 @@ pub fn put(world: &mut World, e: Entity, v: &Value, mut image: impl FnMut(&mut W}let ext = build(world, v, image)?;shade(world, e, &ext, made);- Ok(())+ // the frame's uniforms a row gave before it was on (own_live.rs)+ own_live::settle(world, e)}/// A shaded part: the standard material the rows animate (sync_meshes writes it), copied onto the shaded one's base@@ -396,6 +428,19 @@ pub fn sync_shaded(stds: Res<Assets<StandardMaterial>>, mut shaded: ResMut<Asset#[cfg(test)]mod tests {+ #[test]+ fn a_frame_s_uniforms_repack_the_slots_they_change() {+ use bevy::math::Vec4;+ let repack = super::Repack { names: vec!["glow".into(), "tint".into()], first: vec![Vec4::ZERO, Vec4::new(1.0, 0.5, 0.0, 0.0)], fields: None };+ let mut ext = super::ShaderExt { slots: [Vec4::ZERO; super::SLOTS], tex0: None, tex1: None, tex2: None, tex3: None, arr: None, shader: 0, repack: Some(std::sync::Arc::new(repack)) };+ ext.slots[1] = Vec4::new(1.0, 0.5, 0.0, 0.0);+ // frame 0's values are the ones it holds: nothing to write+ assert_eq!(ext.slots_for(serde_json::json!({ "glow": 0.0 }).as_object().unwrap()).unwrap(), None);+ // a later frame's glow goes in its slot, the tint it didn't give keeps its first value+ let s = ext.slots_for(serde_json::json!({ "glow": 0.75 }).as_object().unwrap()).unwrap().expect("glow changed");+ assert_eq!((s[0].x, s[1]), (0.75, Vec4::new(1.0, 0.5, 0.0, 0.0)));+ }+#[test]fn hooks_are_found_by_name() {assert!(super::defines("fn surface(in: VertexOutput, pbr: ptr<function, PbrInput>) {}", "surface"));diff --git a/systems/shader/src/own_live.rs b/systems/shader/src/own_live.rsindex d885e773..203748b2 100644--- a/systems/shader/src/own_live.rs+++ b/systems/shader/src/own_live.rs@@ -2,7 +2,8 @@//! frame gives them. The rows send a part's <Material> uniforms and buffers as keyed `own:uniforms` component rows//! from each frame they change (raea-runtime-look own_uniforms), and `patch` packs them into the part's OwnMaterial//! and its ShaderBuffers, as Bevy's examples change a material's fields and buffers in their update systems-//! (shader/storage_buffer's colours, sprite_material's dissolve).+//! (shader/storage_buffer's colours, sprite_material's dissolve); a ShaderExtension's uniforms go into its shaded+//! material's slots (`shaded`).use bevy::prelude::*;use bevy::render::storage::ShaderBuffer;@@ -61,6 +62,7 @@ pub fn patch(world: &mut World, e: Entity, v: &Value) -> Result<(), String> {let got = match (&h, &arr) {(Some(h), _) => world.resource::<Assets<OwnMaterial>>().get(h).map(packed),(None, Some(a)) => world.resource::<Assets<OwnArrayMaterial>>().get(a).map(|m| packed(&m.own)),+ (None, None) if world.get::<MeshMaterial3d<crate::ShadedMaterial>>(e).is_some() => return shaded(world, e, v),// a row applied before the part's Material is put on (shade_rows runs after the rows): kept for `put`(None, None) => {world.entity_mut(e).insert(Pending(v.clone()));@@ -87,6 +89,19 @@ pub fn patch(world: &mut World, e: Entity, v: &Value) -> Result<(), String> {Ok(())}+/// A ShaderExtension's uniforms this frame, packed into its shaded material's slots (lib.rs slots_for), written only+/// when they change (SG1: they were read from the part's first frame alone, so a uniform driven by the frame froze)+fn shaded(world: &mut World, e: Entity, v: &Value) -> Result<(), String> {+ let (Some(h), Some(given)) = (world.get::<MeshMaterial3d<crate::ShadedMaterial>>(e).map(|m| m.0.clone()), v.get("uniforms").and_then(Value::as_object)) else { return Ok(()) };+ let Some(m) = world.resource::<Assets<crate::ShadedMaterial>>().get(&h) else { return Err("own:uniforms: its shaded material isn't made".into()) };+ if let Some(slots) = m.extension.slots_for(given)? {+ if let Some(mut m) = world.resource_mut::<Assets<crate::ShadedMaterial>>().get_mut(&h) {+ m.extension.slots = slots;+ }+ }+ Ok(())+}+#[cfg(test)]mod tests {#[test]