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
core/scene, systems/sampler's arrays, systems/procmat, and a pbr.md line
shinyobjectz3a62efa343ba
diff --git a/core/scene/src/lib.rs b/core/scene/src/lib.rsindex bb663a5c..4eee724d 100644--- a/core/scene/src/lib.rs+++ b/core/scene/src/lib.rs@@ -58,6 +58,36 @@ pub fn base_ident(it: &Item) -> &str {}}+/// A mesh's surface as part of what it is across frames: its material's kind and its shader's source, hashed (not the+/// uniforms, which animate). A mesh row takes its surface from its track's first frame, so a later shot's mesh of the+/// same shape on an earlier shot's track drew the earlier shot's shader (a set's street in its own colours, the+/// ShaderExtension that reads them lost: gambit previz v4, act 3); two shaders are now two parts.+fn surface_ident(it: &Item) -> String {+ use std::hash::{Hash, Hasher};+ let Some(m) = it.material.as_ref().filter(|_| it.kind == "mesh") else { return String::new() };+ let mut h = std::collections::hash_map::DefaultHasher::new();+ let mut any = false;+ if let Some(sh) = m.props.get("shader").and_then(Value::as_object) {+ for k in ["wgsl", "wesl", "fragment"] {+ if let Some(s) = sh.get(k).and_then(Value::as_str) {+ (k, s).hash(&mut h);+ any = true;+ }+ }+ }+ for k in ["vertexShader", "fragmentShader"] {+ if let Some(s) = m.props.get(k).and_then(Value::as_str) {+ (k, s).hash(&mut h);+ any = true;+ }+ }+ match (&*m.kind, any) {+ ("MeshStandardMaterial", false) => String::new(),+ (kind, false) => format!("|{kind}"),+ (kind, true) => format!("|{kind}:{:016x}", h.finish()),+ }+}+/// `tracks` over items already walked: only the parts of these kinds are copiedpub fn tracks_of(all: &[Vec<Item>], kinds: &[&str]) -> Vec<(String, Vec<Option<Item>>)> {let mut order: Vec<String> = Vec::new();@@ -66,7 +96,7 @@ pub fn tracks_of(all: &[Vec<Item>], kinds: &[&str]) -> Vec<(String, Vec<Option<Ifor (i, its) in all.iter().enumerate() {let mut seen: BTreeMap<String, usize> = BTreeMap::new();for it in its.iter().filter(|it| kinds.contains(&it.kind)).cloned() {- let base = format!("{}|{}", it.kind, base_ident(&it));+ let base = format!("{}|{}{}", it.kind, base_ident(&it), surface_ident(&it));let k = seen.entry(base.clone()).or_insert(0);let id = format!("{base}#{k}");*k += 1;@@ -108,3 +138,42 @@ pub fn entities_nodes(props: &Map<String, Value>) -> Vec<Node3> {}).collect()}++#[cfg(test)]+mod surface_tracks {+ use super::*;++ fn mesh(shape: &str, material: &str, shader: Option<(&str, f64)>) -> Item {+ let mut props = Map::new();+ if let Some((src, k)) = shader {+ props.insert("shader".into(), serde_json::json!({ "wgsl": src, "uniforms": { "k": k } }));+ }+ let material = Node3 { kind: material.into(), props: std::sync::Arc::new(props), shape: None, at: None, kids: Vec::new().into() };+ Item { kind: "mesh", props: std::sync::Arc::new(Map::new()), shape: Some(shape.into()), at: None, material: Some(material), world: Mat4::IDENTITY }+ }++ #[test]+ fn one_shape_under_two_shaders_is_two_parts() {+ // a shot's box under shader A, then the next shot's box of the same shape under shader B+ let a = mesh("box", "MeshStandardMaterial", Some(("fn surface(in: VertexOutput, pbr: ptr<function, PbrInput>) { }", 1.0)));+ let b = mesh("box", "MeshStandardMaterial", Some(("fn surface(in: VertexOutput, pbr: ptr<function, PbrInput>) { (*pbr).material.base_color = in.color; }", 1.0)));+ let t = tracks_of(&[vec![a], vec![b]], &["mesh"]);+ assert_eq!(t.len(), 2, "{:?}", t.iter().map(|x| &x.0).collect::<Vec<_>>());+ }++ #[test]+ fn a_shader_whose_uniforms_move_stays_one_part() {+ let src = "fn surface(in: VertexOutput, pbr: ptr<function, PbrInput>) { }";+ let t = tracks_of(&[vec![mesh("box", "MeshStandardMaterial", Some((src, 0.0)))], vec![mesh("box", "MeshStandardMaterial", Some((src, 1.0)))]], &["mesh"]);+ assert_eq!(t.len(), 1);+ assert!(t[0].1.iter().all(Option::is_some));+ }++ #[test]+ fn plain_standard_meshes_keep_their_old_identity() {+ // no shader: the key is what it was before, so a scene without shaders matches its parts as it did+ let t = tracks_of(&[vec![mesh("box", "MeshStandardMaterial", None)], vec![mesh("box", "MeshStandardMaterial", None)]], &["mesh"]);+ assert_eq!(t.len(), 1);+ assert_eq!(t[0].0, "mesh|box#0");+ }+}diff --git a/docs/manual/reference/sdk/pbr.md b/docs/manual/reference/sdk/pbr.mdindex e3d84e78..cc810dde 100644--- a/docs/manual/reference/sdk/pbr.md+++ b/docs/manual/reference/sdk/pbr.md@@ -140,6 +140,7 @@ Used in: [3d/lightmaps](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/| `scale` | `number` | the noise's size in metres (1) || `color` | `string` | the colour patches take || `amount` | `number` | how far toward `color` the patches go (0.6) |+| `world` | `number` | under a <Look cuts>: the world this mesh is in. 0 (the default): outside every cut. 1 to 4: inside that cut and no later one. -1: everywhere. Given alone it leaves the breakup off |### `ProceduralExtension`diff --git a/systems/procmat/src/lib.rs b/systems/procmat/src/lib.rsindex bd86c9ef..a4f86a51 100644--- a/systems/procmat/src/lib.rs+++ b/systems/procmat/src/lib.rs@@ -53,6 +53,12 @@ impl MaterialExtension for Procedural {fn fragment_shader() -> ShaderRef {"embedded://raea_sys_procmat/procmat.wesl".into()}+ /// The same shader in the deferred pass (its PREPASS_PIPELINE branch writes the G-buffer): without it a deferred+ /// material drew StandardMaterial's own, the base colour flat. Solari makes every opaque material deferred, so under+ /// <SolariLighting> a procedural surface (an oilcloth's checks, a plastered wall) lost its pattern (FP-LAB, 11-17).+ fn deferred_fragment_shader() -> ShaderRef {+ "embedded://raea_sys_procmat/procmat.wesl".into()+ }}const NUMS: [(&str, &str); 9] = [("scale", "proc_scale"), ("bump", "proc_bump"), ("seed", "proc_seed"), ("gap", "proc_gap"), ("dust", "proc_dust"), ("dirt", "proc_dirt"), ("edges", "proc_edges"), ("roughA", "proc_rough_a"), ("roughB", "proc_rough_b")];diff --git a/systems/sampler/src/arrays.rs b/systems/sampler/src/arrays.rsindex 3819345d..5d6187a8 100644--- a/systems/sampler/src/arrays.rs+++ b/systems/sampler/src/arrays.rs@@ -15,6 +15,15 @@ pub struct PendingArrays {pending: Vec<(Handle<Image>, Vec<Handle<Image>>, u32, String)>,}+/// Arrays already made or reserved, by their spec (the `{src, layers}` or `{layers: [...]}` JSON, sampler included), so+/// every material naming the same array shares one image. Without it each material made its own copy: a city whose+/// every tile's window material names one 40-layer room atlas (768 x 30720, 94 MB) went past memguard's 24 GB cap on+/// a single frame; with it the same frame peaked at 3.8 GB (gambit's trailer previz, act 1, frame 100).+#[derive(Resource, Default)]+pub struct ArrayCache {+ by_spec: std::collections::HashMap<String, Handle<Image>>,+}+/// A texture spec that's an array: it has `layers`.pub fn is_array(v: &Value) -> bool {v.as_object().is_some_and(|o| o.contains_key("layers"))@@ -22,6 +31,10 @@ pub fn is_array(v: &Value) -> bool {/// An array texture's handle, made once its layers load; `{sampler}` is set on the array as on any texture.pub fn array(world: &mut World, v: &Value, who: &str, image: &mut impl FnMut(&mut World, &Value) -> Result<Handle<Image>, String>) -> Result<Handle<Image>, String> {+ let key = v.to_string();+ if let Some(h) = world.get_resource::<ArrayCache>().and_then(|c| c.by_spec.get(&key)) {+ return Ok(h.clone());+ }let o = v.as_object().ok_or_else(|| format!("{who}: an array is {{layers: [picture, ...]}} or {{src, layers: N}}"))?;let (layers, n) = match (o.get("layers"), o.get("src")) {(Some(Value::Array(a)), None) if a.len() >= 2 => (a.iter().map(|x| image(world, x)).collect::<Result<Vec<_>, _>>()?, a.len() as u32),@@ -32,6 +45,7 @@ pub fn array(world: &mut World, v: &Value, who: &str, image: &mut impl FnMut(&mu_ => return Err(format!("{who}: an array is {{layers: [picture, ...]}} (2 or more) or {{src, layers: N}} (a picture of N layers stacked top to bottom), got {v}")),};let h = world.resource::<Assets<Image>>().reserve_handle();+ world.get_resource_or_insert_with(ArrayCache::default).by_spec.insert(key, h.clone());world.get_resource_or_insert_with(PendingArrays::default).pending.push((h.clone(), layers, n, who.to_string()));if let Some(s) = o.get("sampler") {PendingSamplers::give(world, h.clone(), Sampling::of(s)?, who.to_string());@@ -53,8 +67,18 @@ pub fn sync_arrays(p: Option<ResMut<PendingArrays>>, mut images: ResMut<Assets<Icontinue;}match stack(&layers.iter().map(|l| images.get(l).unwrap()).collect::<Vec<_>>(), n) {- Ok(img) => {+ Ok(mut img) => {+ // the array lives on the GPU only (its pixels aren't kept on the CPU after the upload), and its layers'+ // pictures never go to the GPU at all: a stack is one tall picture, and past 32768 pixels (43 layers+ // of 768) it is taller than a GPU's 2D texture may be, which stopped the whole render. Changed in the+ // frame they load, before the render world takes them.+ img.asset_usage = RenderAssetUsages::RENDER_WORLD;let _ = images.insert(&h, img);+ for l in &layers {+ if let Some(mut src) = images.get_mut(l) {+ src.asset_usage = RenderAssetUsages::MAIN_WORLD;+ }+ }}Err(e) => eprintln!("raea: {who}: {e}"),}@@ -88,6 +112,7 @@ fn stack(layers: &[&Image], n: u32) -> Result<Image, String> {#[cfg(test)]mod tests {use super::*;+ use bevy::ecs::system::RunSystemOnce;use bevy::render::render_resource::TextureFormat;fn pic(px: [u8; 4]) -> Image {@@ -106,4 +131,36 @@ mod tests {let big = Image::new_fill(Extent3d { width: 4, height: 2, depth_or_array_layers: 1 }, TextureDimension::D2, &[0, 0, 0, 255], TextureFormat::Rgba8UnormSrgb, RenderAssetUsages::all());assert!(stack(&[&a, &big], 2).is_err());}++ #[test]+ fn the_same_array_named_twice_is_one_image() {+ let mut world = World::new();+ world.init_resource::<Assets<Image>>();+ let mut loads = 0;+ let mut image = |w: &mut World, _: &Value| -> Result<Handle<Image>, String> {+ loads += 1;+ Ok(w.resource::<Assets<Image>>().reserve_handle())+ };+ let spec = serde_json::json!({ "src": "rooms.png", "layers": 40 });+ let (a, b) = (array(&mut world, &spec, "t1", &mut image).unwrap(), array(&mut world, &spec, "t2", &mut image).unwrap());+ assert_eq!(a.id(), b.id());+ let other = array(&mut world, &serde_json::json!({ "src": "rooms.png", "layers": 20 }), "t3", &mut image).unwrap();+ assert_ne!(a.id(), other.id());+ assert_eq!(loads, 2);+ }++ #[test]+ fn an_array_is_gpu_only_and_its_stack_never_goes_to_the_gpu() {+ let mut world = World::new();+ world.init_resource::<Assets<Image>>();+ let tall = Image::new_fill(Extent3d { width: 2, height: 6, depth_or_array_layers: 1 }, TextureDimension::D2, &[9, 9, 9, 255], TextureFormat::Rgba8UnormSrgb, RenderAssetUsages::all());+ let src = world.resource_mut::<Assets<Image>>().add(tall);+ let s2 = src.clone();+ let h = array(&mut world, &serde_json::json!({ "src": "stack.png", "layers": 3 }), "t", &mut |_: &mut World, _: &Value| Ok(s2.clone())).unwrap();+ world.run_system_once(sync_arrays).unwrap();+ let images = world.resource::<Assets<Image>>();+ assert_eq!(images.get(&h).unwrap().texture_descriptor.size.depth_or_array_layers, 3);+ assert_eq!(images.get(&h).unwrap().asset_usage, RenderAssetUsages::RENDER_WORLD);+ assert_eq!(images.get(&src).unwrap().asset_usage, RenderAssetUsages::MAIN_WORLD);+ }}