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
LT4: a ray hit sees its instance's record, its averaged albedo and its emission (the first tier)
shinyobjectz2ab92392d4d4
diff --git a/docs/realism.feature b/docs/realism.featureindex dc016dfc..91c6ee0a 100644--- a/docs/realism.feature+++ b/docs/realism.feature@@ -324,6 +324,15 @@ Feature: raea Light: raea's own real-time realism renderer, measured against raethe scene's materialsAnd Berlin's snow bounces white, and a lit window throws warm light into the street at dusk; a hook that can'trun at a hit is named by D19's warning+ And so far (11-18, the first tier): systems/rt keeps each TLAS instance's record at its custom index+ (records.rs: its StandardMaterial's base colour times its texture's mean, less what is metal, and its emission+ as the radiance it sends, as the reference takes it), and the probes' and the cache's hits read it in place of+ LT2's stand-in. An instance with no StandardMaterial (a hook) keeps the stand-in. FLOOR3's lenses (4500 nits)+ now light its cells: gi mean 4.819 to 2.381 stops, bias -4.796 to -2.118, worst 7.029 to 6.012, flicker+ 0.101 to 0.415, live 16.1 ms. It stays dark and blotchy because one cosine ray an update rarely finds a lens+ that is 2 to 3% of the sky: emitters sampled by their power with a shadow ray (D7, LT6) are next. Glade gi+ mean 1.474 to 1.319, bias 1.241 to 1.074 (against LT3's unreliable reference). Taking emission over the+ exposure where Bevy draws it unexposed (emissive_exposure_weight 0, its default) made FLOOR3 3.2 stops brightScenario: LT5. raea's path tracer, the reference and the film tierThen a path tracer on systems/rt takes its first hit from the camera's G-buffer and runs full materials at everydiff --git a/systems/rt/src/gi.rs b/systems/rt/src/gi.rsindex c2f20902..2fe8607f 100644--- a/systems/rt/src/gi.rs+++ b/systems/rt/src/gi.rs@@ -27,7 +27,7 @@ use bevy::{extract_resource::{ExtractResource, ExtractResourcePlugin},render_asset::RenderAssets,render_resource::{- binding_types::{acceleration_structure, sampler, storage_buffer_sized, texture_cube, texture_storage_3d, uniform_buffer},+ binding_types::{acceleration_structure, sampler, storage_buffer_read_only_sized, storage_buffer_sized, texture_cube, texture_storage_3d, uniform_buffer},*,},renderer::{RenderDevice, RenderQueue},@@ -177,6 +177,8 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCacstorage_buffer_sized(false, None),texture_storage_3d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),storage_buffer_sized(false, None),+ // each instance's record (records.rs)+ storage_buffer_read_only_sized(false, None),),),);@@ -237,6 +239,7 @@ fn update(mut commands: Commands,grid: Option<Res<Grid>>,scene: Option<Res<crate::Scene>>,+ records: Option<Res<crate::Records>>,images: Res<RenderAssets<GpuImage>>,fallback: Res<FallbackImage>,p: Option<Res<Pipeline>>,@@ -245,7 +248,7 @@ fn update(queue: Res<RenderQueue>,mut state: ResMut<State>,) {- let (Some(grid), Some(scene), Some(p)) = (grid, scene, p) else { return };+ let (Some(grid), Some(scene), Some(records), Some(p)) = (grid, scene, records, p) else { return };let (Some(pipeline), Some(resolve)) = (cache.get_compute_pipeline(p.id), cache.get_compute_pipeline(p.resolve)) else { return };let Some(passes) = p.cache.0.iter().map(|id| cache.get_compute_pipeline(*id)).collect::<Option<Vec<_>>>() else { return };let Ok(passes) = <[&ComputePipeline; 6]>::try_from(passes) else { return };@@ -294,7 +297,7 @@ fn update(let group = device.create_bind_group("raea_gi",&cache.get_bind_group_layout(&p.layout),- &BindGroupEntries::sequential((uniform.binding().unwrap(), scene.0.as_binding(), sky, sky_diffuse, &p.sampler, cubes.as_entire_binding(), &voxels.texture_view, tags.as_entire_binding())),+ &BindGroupEntries::sequential((uniform.binding().unwrap(), scene.0.as_binding(), sky, sky_diffuse, &p.sampler, cubes.as_entire_binding(), &voxels.texture_view, tags.as_entire_binding(), records.0.as_entire_binding())),);// a steady frame is timed when the last one's times are inlet timed = !fresh && state.timer.as_ref().is_some_and(|t| t.pending.is_none());diff --git a/systems/rt/src/gi.wesl b/systems/rt/src/gi.weslindex ea23fcda..412f0403 100644--- a/systems/rt/src/gi.wesl+++ b/systems/rt/src/gi.wesl@@ -1,6 +1,6 @@// raea GI's probes (gi.rs; docs/realism.feature LT2, LT3): a grid of probes around the camera, each refreshed by 64-// rays through the scene's TLAS. A ray that misses sees the sky (the camera's environment); one that hits sees a flat-// stand-in surface (albedo 0.5, facing the ray) until hits know their surface (LT4), lit by what the world cache has+// rays through the scene's TLAS. A ray that misses sees the sky (the camera's environment); one that hits sees its+// instance's record (records.rs, LT4's first tier: averaged albedo and emission; the surface faces the ray), lit by what the world cache has// learned there (cache.wesl: the sun and every bounce, the sky shadowed by what's around), or, where its cell is new,// by the sun through one shadow ray and the sky's diffuse light, unshadowed. Each probe keeps a running mean of its// ambient cube (the light arriving along +-x, +-y, +-z) and writes it into Bevy's irradiance volume, which every@@ -35,10 +35,16 @@ struct Params {@group(0) @binding(6) var voxels: texture_storage_3d<rgba16float, write>;// which world probe each slot holds (xyz) and whether it holds one (w), so a slot taken over starts afresh@group(0) @binding(7) var<storage, read_write> tags: array<vec4<i32>>;+// each TLAS instance's record at its custom index (records.rs): its averaged albedo, and its emission (the radiance+// raster draws it with)+struct Record {+ albedo: vec4<f32>,+ emission: vec4<f32>,+}+@group(0) @binding(8) var<storage, read> records: array<Record>;const PI = 3.14159265;const RAYS = 64u;-const ALBEDO = 0.5;// the most frames a probe's mean is kept over: after that each frame's rays count a 32ndconst HISTORY = 32.0;const CASTS = 1u;@@ -94,16 +100,20 @@ fn fib(i: u32, n: u32) -> vec3<f32> {}// The queries live in functions of their own, a fresh one each call (traced_ao.wesl: Metal can't reassign one).-// the distance to the first surface along a ray, or -1 where it reaches the sky-fn first_hit(o: vec3<f32>, d: vec3<f32>) -> f32 {+// the first surface along a ray: how far (-1 where the ray reaches the sky), and its instance's record+struct Hit {+ t: f32,+ rec: u32,+}+fn first_hit(o: vec3<f32>, d: vec3<f32>) -> Hit {var rq: ray_query;rayQueryInitialize(&rq, tlas, RayDesc(0u, ALL, 0.01, 10000.0, o, d));rayQueryProceed(&rq);let h = rayQueryGetCommittedIntersection(&rq);if (h.kind == RAY_QUERY_INTERSECTION_NONE) {- return -1.0;+ return Hit(-1.0, 0u);}- return h.t;+ return Hit(h.t, h.instance_custom_data);}// whether a point sees the sun: only what casts shadows stops it (lib.rs's CASTS), as the shadow maps have itfn sees_sun(o: vec3<f32>, d: vec3<f32>) -> bool {@@ -189,13 +199,14 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) llet q = random_turn(hash(p.run.z * 7919u + round * 104729u + probe));let d = turn(q, fib(li, RAYS));var l = vec3(0.0);- let t = first_hit(at, d);- if (t < 0.0) {+ let h = first_hit(at, d);+ if (h.t < 0.0) {l = sky_radiance(d);} else {- let hit = at + d * t;+ let hit = at + d * h.t;var seed = hash(p.run.z * 7919u + round * 104729u + probe * RAYS + li);- l = ALBEDO / PI * irradiance_at(hit, -d, LIFE, &seed);+ let r = records[h.rec];+ l = r.albedo.rgb / PI * irradiance_at(hit, -d, LIFE, &seed) + r.emission.rgb;}light[li] = l;dirs[li] = d;@@ -266,13 +277,15 @@ fn learn(@builtin(global_invocation_id) id: vec3<u32>) {seen = 1.0;}let d = cosine(n, &seed);- let t = first_hit(o, d);- if (t < 0.0) {+ let h = first_hit(o, d);+ if (h.t < 0.0) {// a cosine sample's irradiance: pi times the radiance it seese += PI * sky_radiance(d);} else {- // the cell met lives as long as the one reading it- e += ALBEDO * irradiance_at(o + d * t, -d, atomicLoad(&life[cell]), &seed);+ // what the surface met sends back, its albedo of the light the cell met there has learned (that cell lives as+ // long as the one reading it), and its own light+ let r = records[h.rec];+ e += r.albedo.rgb * irradiance_at(o + d * h.t, -d, atomicLoad(&life[cell]), &seed) + PI * r.emission.rgb;}// the light (rgb) and whether the sun was seen (a)learned[id.x] = vec4(e, seen);diff --git a/systems/rt/src/lib.rs b/systems/rt/src/lib.rsindex 3f1b31f6..fa52b263 100644--- a/systems/rt/src/lib.rs+++ b/systems/rt/src/lib.rs@@ -11,6 +11,8 @@ pub mod gi;pub mod cache;// the sun's far shadow map, past the last cascade (RAEA_SUN_FAR, LT21)pub mod far;+// what a hit sees: each instance's averaged albedo and emission (LT4's first tier)+pub mod records;pub mod traced_ao;/// Every traced pass asked for: traced AO (RAEA_TRACED_AO), raea GI's probes (RAEA_GI), the sun's far shadow map@@ -43,7 +45,7 @@ use bevy::{/// Every visible opaque mesh instance (its mesh and world transform), from the main world each frame.#[derive(Resource, Default, Clone, ExtractResource)]#[extract_app(bevy::render::RenderApp)]-struct Instances(Vec<(AssetId<Mesh>, Mat4, u8)>);+struct Instances(Vec<(AssetId<Mesh>, Mat4, u8, records::Record)>);/// an instance's ray mask: every instance has ALL; CASTS where it casts shadows (no NotShadowCaster), which is all a/// sun ray tests, so a film's shadow-only stand-ins and its non-casting walls shade the sun as its shadow maps do@@ -71,6 +73,10 @@ fn spent(k: usize, since: std::time::Instant) {#[derive(Resource)]pub struct Scene(pub Tlas);+/// Each TLAS instance's record (records.rs), at its custom index: 32 bytes each, room for as many as the TLAS+#[derive(Resource)]+pub struct Records(pub Buffer);+/// How many times the TLAS was built and how many instances it last held, for raea GI's stats (gi.rs `report`)pub(crate) static TLAS_BUILT: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];@@ -82,6 +88,9 @@ struct Held {room: u32,/// Blases' batch count it was built againstbatches: u64,+ /// the records last written (Records), in the TLAS's order, and their buffer+ records: Vec<records::Record>,+ record_buf: Option<Buffer>,}pub fn install(app: &mut App) {@@ -112,20 +121,25 @@ fn see_through(m: &StandardMaterial) -> bool {m.base_color.alpha() < 0.99 || m.specular_transmission > 0.0 || m.diffuse_transmission > 0.0}+#[allow(clippy::too_many_arguments)]fn gather(meshes: Query<(&Mesh3d, &GlobalTransform, &InheritedVisibility, Option<&MeshMaterial3d<StandardMaterial>>, Has<bevy::light::NotShadowCaster>)>,lights: Query<(&DirectionalLight, &GlobalTransform)>,mats: Res<Assets<StandardMaterial>>,+ images: Res<Assets<Image>>,+ mut means: Local<HashMap<AssetId<Image>, Vec3>>,mut instances: ResMut<Instances>,mut sun: ResMut<Sun>,) {let t0 = std::time::Instant::now();instances.0.clear();for (mesh, t, vis, mat, no_shadow) in &meshes {- if !vis.get() || mat.and_then(|m| mats.get(&m.0)).is_some_and(see_through) {+ let mat = mat.and_then(|m| mats.get(&m.0));+ if !vis.get() || mat.is_some_and(see_through) {continue;}- instances.0.push((mesh.id(), t.to_matrix(), if no_shadow { ALL } else { ALL | CASTS }));+ let rec = mat.map_or(records::STAND_IN, |m| records::record(m, &images, &mut means));+ instances.0.push((mesh.id(), t.to_matrix(), if no_shadow { ALL } else { ALL | CASTS }, rec));}if let Some((_, t)) = lights.iter().find(|(l, _)| l.shadow_maps_enabled).or_else(|| lights.iter().next()) {sun.0 = t.back().as_vec3();@@ -163,7 +177,7 @@ fn build_blas(blases.0.remove(id);}let Some(instances) = instances else { return };- let mut wanted: Vec<AssetId<Mesh>> = instances.0.iter().map(|(id, _, _)| *id).filter(|id| !blases.0.contains_key(id)).collect();+ let mut wanted: Vec<AssetId<Mesh>> = instances.0.iter().map(|(id, ..)| *id).filter(|id| !blases.0.contains_key(id)).collect();wanted.sort_unstable();wanted.dedup();let mut made = Vec::new();@@ -237,12 +251,28 @@ fn build_tlas(mut commands: Commands, instances: Option<Res<Instances>>, blases:return;}let t0 = std::time::Instant::now();- let now: Vec<(AssetId<Mesh>, [f32; 12], u8)> = instances.0.iter().filter(|(id, ..)| blases.0.contains_key(id)).map(|(id, m, mask)| (*id, m.transpose().to_cols_array()[..12].try_into().unwrap(), *mask)).collect();+ let with: Vec<_> = instances.0.iter().filter(|(id, ..)| blases.0.contains_key(id)).collect();+ let now: Vec<(AssetId<Mesh>, [f32; 12], u8)> = with.iter().map(|(id, m, mask, _)| (*id, m.transpose().to_cols_array()[..12].try_into().unwrap(), *mask)).collect();+ let recs: Vec<records::Record> = with.iter().map(|(.., r)| *r).collect();if std::env::var_os("RAEA_RT_DEBUG").is_some() {- for (id, _, _) in instances.0.iter().filter(|(id, _, _)| !blases.0.contains_key(id)) {+ for (id, ..) in instances.0.iter().filter(|(id, ..)| !blases.0.contains_key(id)) {eprintln!("raea rt: no BLAS for {id:?}");}}+ // the records in the TLAS's order, written when they change: a material can change with no instance moving+ if held.records != recs || held.record_buf.is_none() {+ if held.record_buf.as_ref().is_none_or(|b| b.size() / 32 < recs.len() as u64) {+ let n = (recs.len() * 3 / 2).max(64) as u64;+ let b = device.create_buffer(&BufferDescriptor { label: Some("raea rt records"), size: n * 32, usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, mapped_at_creation: false });+ commands.insert_resource(Records(b.clone()));+ held.record_buf = Some(b);+ }+ let bytes: Vec<u8> = recs.iter().flatten().flat_map(|f| f.to_le_bytes()).collect();+ if let (false, Some(b)) = (bytes.is_empty(), held.record_buf.as_ref()) {+ queue.write_buffer(b, 0, &bytes);+ }+ held.records = recs;+ }if scene.is_some() && now == held.instances && held.batches == blases.1 {spent(1, t0);return;diff --git a/systems/rt/src/records.rs b/systems/rt/src/records.rsnew file mode 100644index 00000000..0be07291--- /dev/null+++ b/systems/rt/src/records.rs@@ -0,0 +1,74 @@+//! What a ray hit on an instance sees, D5's first tier (docs/realism.feature LT4): each instance's record, its averaged+//! albedo and its emission, in the TLAS's order (an instance's custom index is its place there, lib.rs build_tlas).+//! Read from its StandardMaterial: the base colour times its texture's mean, less what is metal, and the emissive+//! colour times its texture's mean as the radiance it sends (cd/m2, as the reference's tracer and Bevy's lights take+//! it: FLOOR3's lenses are 4500 nits). Not as raster draws the emitter itself: Bevy's emissive_exposure_weight of 0+//! (its default) draws it unexposed, a display value, and the light it gives would be that over the exposure, nine+//! times FLOOR3's reference (11-18, 3.2 stops bright). An instance with no StandardMaterial (a hooked or+//! custom one) keeps LT2's stand-in, albedo 0.5 and no emission, until the cache learns its surface from the screen+//! (D5's second tier).++use bevy::{+ asset::AssetId,+ image::Image,+ platform::collections::HashMap,+ prelude::*,+ render::render_resource::TextureFormat,+};++/// one instance's record, gi.wesl's Record: albedo (rgb), emission (rgb, the radiance raster's units give it)+pub type Record = [f32; 8];++/// LT2's stand-in: a flat 0.5, no emission+pub const STAND_IN: Record = [0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0];++/// The record of an instance drawn with `m`; `means` keeps each texture's mean colour.+pub fn record(m: &StandardMaterial, images: &Assets<Image>, means: &mut HashMap<AssetId<Image>, Vec3>) -> Record {+ let mut mean = |h: &Option<Handle<Image>>| h.as_ref().map_or(Vec3::ONE, |h| *means.entry(h.id()).or_insert_with(|| images.get(h).map_or(Vec3::ONE, texture_mean)));+ let base = Vec3::from_slice(&m.base_color.to_linear().to_f32_array()[..3]) * mean(&m.base_color_texture) * (1.0 - m.metallic);+ let emission = Vec3::new(m.emissive.red, m.emissive.green, m.emissive.blue) * mean(&m.emissive_texture);+ [base.x, base.y, base.z, 0.0, emission.x, emission.y, emission.z, 0.0]+}++/// An image's mean linear colour, from at most 4096 of its texels; white where its texels aren't on the CPU or aren't+/// 8-bit RGBA (a compressed texture keeps its material's colour).+fn texture_mean(image: &Image) -> Vec3 {+ let Some(data) = image.data.as_ref() else { return Vec3::ONE };+ let srgb = match image.texture_descriptor.format {+ TextureFormat::Rgba8UnormSrgb => true,+ TextureFormat::Rgba8Unorm => false,+ _ => return Vec3::ONE,+ };+ let texels = data.len() / 4;+ if texels == 0 {+ return Vec3::ONE;+ }+ let step = texels.div_ceil(4096).max(1);+ let lin = |v: u8| {+ let c = v as f32 / 255.0;+ if !srgb { c } else if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }+ };+ let (mut sum, mut n) = (Vec3::ZERO, 0.0);+ for t in (0..texels).step_by(step) {+ let p = &data[t * 4..t * 4 + 3];+ sum += Vec3::new(lin(p[0]), lin(p[1]), lin(p[2]));+ n += 1.0;+ }+ sum / n+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_record_is_raster_s_colour_and_light() {+ let (images, mut means) = (Assets::<Image>::default(), HashMap::default());+ let m = StandardMaterial { base_color: Color::linear_rgb(0.8, 0.4, 0.2), metallic: 0.5, emissive: LinearRgba::rgb(4500.0, 0.0, 0.0), ..default() };+ let r = record(&m, &images, &mut means);+ assert_eq!(&r[..3], &[0.4, 0.2, 0.1]);+ // the radiance it sends, whatever its exposure weight+ assert_eq!(r[4], 4500.0);+ assert_eq!(record(&StandardMaterial { emissive_exposure_weight: 1.0, ..m }, &images, &mut means)[4], 4500.0);+ }+}