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
LT3: the world cache's light reaches the screen, each pixel reading it at its own surface (raea-sys-gi, RAEA_GI=1)
shinyobjectz2ca930d81e3a
diff --git a/Cargo.lock b/Cargo.lockindex d76d194d..2add7c8c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14926,6 +14926,7 @@ dependencies = ["raea-sys-fog-half","raea-sys-frame","raea-sys-framepass",+ "raea-sys-gi","raea-sys-grass","raea-sys-grid","raea-sys-hold",@@ -15977,6 +15978,15 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-sys-gi"+version = "0.1.0"+dependencies = [+ "bevy",+ "raea-sys-compose",+ "raea-sys-rt",+]+[[package]]name = "raea-sys-glb"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex c31468df..870ce515 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -126,6 +126,7 @@ members = ["systems/sprite","systems/stage","systems/rt",+ "systems/gi","systems/text3d","runtime/gpuframe","runtime/scene3d",diff --git a/docs/realism.feature b/docs/realism.featureindex 7cb2ad09..dc016dfc 100644--- a/docs/realism.feature+++ b/docs/realism.feature@@ -300,6 +300,19 @@ Feature: raea Light: raea's own real-time realism renderer, measured against raemeasure. LT2's probes cost 0.253 ms at 131072 rays. Open: the cache lights nothing on screen yet (as LT2'sgrid: Metal's sampler limit), so its light is unchecked; the persistent TLAS, compaction and the screen's8x8-tile paths are still to build+ And the cache's light reaches the screen (11-18, raea-sys-gi, behind RAEA_GI=1), a measuring step as LT2's grid+ was meant to be: each pixel reads the cache at its own surface, from the depth and normal prepasses, with the+ sun's share taken out by each cell's mean of seeing it (cache.wesl `sunlit`, 4 MiB more), since raster draws+ the sun with its shadows. It's written a texel a pixel and drawn by the main pass in place of the irradiance+ volume, the environment map's diffuse and the ambient (raea's bevy_pbr RaeaGiScreen, binding 41, read by+ textureLoad: no sampler, so a hooked material at Metal's 16 still builds). A cell is read by hundreds of+ pixels, so the cache's reads load before they write. With raea's temporal filter on both, raster against+ gi: the glade's mean 1.750/1.474 stops, bias 1.532/1.241, worst 2.953/2.948, flicker 0.788/0.780, its+ undergrowth darker where cells see less sky. But the glade's reference (Solari's path tracer) is near black,+ unconverged and without its fog, so its numbers measure the reference more than the GI (LT5). FLOOR3 goes black+ but for its ceiling panels, 4.8 stops under its reference: it is lit by their emission alone, which no cell+ knows yet (LT4's first tier, a hit's record's albedo and emission); live 14.5/16.3 ms, the cache and its+ probes 0.92 ms of GPUScenario: LT4. What a ray hit seesGiven every MaterialExtension writes the deferred G-buffer with its own surface code (D4; procmat's is first,diff --git a/engine/render/Cargo.toml b/engine/render/Cargo.tomlindex 5bb4deee..041b50f0 100644--- a/engine/render/Cargo.toml+++ b/engine/render/Cargo.toml@@ -16,6 +16,7 @@ raea-sys-hold = { path = "../../systems/hold" }raea-sys-splat = { path = "../../systems/splat" }raea-sys-sprite = { path = "../../systems/sprite" }raea-sys-rt = { path = "../../systems/rt" }+raea-sys-gi = { path = "../../systems/gi" }# soft shadows (experimental_pbr_pcss) are under the native feature with raea-runtime-scene3d/pcss: WebGPU refuses their samplingbevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "tonemapping_luts", "ktx2", "zstd_rust"] }image = { version = "0.25", default-features = false, features = ["png", "jpeg", "hdr"] }diff --git a/engine/render/src/engine/raea_plugins.rs b/engine/render/src/engine/raea_plugins.rsindex b3a0dbbb..21c524bb 100644--- a/engine/render/src/engine/raea_plugins.rs+++ b/engine/render/src/engine/raea_plugins.rs@@ -60,6 +60,7 @@ raea_plugin! {PaintPlugin: super::paint::install, "The paint and cartoon looks' surfaces (paint.rs).";PassesPlugin: super::passes::install, "Render passes per view (passes.rs).";TracedAoPlugin: raea_sys_rt::passes, "Traced passes: ambient occlusion, raea GI's world probes and the sun's far shadow map (raea-sys-rt).";+ GiScreenPlugin: raea_sys_gi::install, "raea GI's light on screen: each pixel's indirect diffuse from the world cache, read by the main pass (raea-sys-gi, RAEA_GI=1).";VolumePlugin: super::volume::install, "Simulated smoke, clouds and contrails, raymarched (volume.rs).";GrassPlugin: raea_sys_grass::install, "Fields of grass, made in tiles as detailed as the camera's distance asks (systems/grass).";DetailPlugin: raea_sys_lod::install, "Where each part is drawn: levels by distance or size on screen, cross-faded, draw distance and shadows left to a coarser level (raea-sys-lod, docs/realism.feature LT21).";diff --git a/systems/gi/Cargo.toml b/systems/gi/Cargo.tomlnew file mode 100644index 00000000..29020e3a--- /dev/null+++ b/systems/gi/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "raea-sys-gi"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "raea GI's screen side: each pixel's indirect diffuse light from the world cache, read by the main pass"++[dependencies]+raea-sys-rt = { path = "../rt" }+raea-sys-compose = { path = "../compose" }+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }diff --git a/systems/gi/src/lib.rs b/systems/gi/src/lib.rsnew file mode 100644index 00000000..f2bc00f2--- /dev/null+++ b/systems/gi/src/lib.rs@@ -0,0 +1,167 @@+//! raea GI's screen side (docs/realism.feature LT8, D6): the indirect diffuse light each pixel gets, drawn by the main+//! pass in place of the irradiance volume, the environment map's diffuse and the ambient light (raea's bevy_pbr+//! RaeaGiScreen, the mesh view group's binding 41, read texel for pixel: no sampler, so a hooked material at Metal's 16+//! keeps building, where Bevy's irradiance volume took a 17th).+//!+//! Its first form is a measuring step, as LT2's irradiance volume was meant to be: each pixel reads the world cache+//! (raea-sys-rt cache.wesl) at its own surface, from the depth and normal prepasses, and takes out the sun's share,+//! which raster draws with its shadows. What the cache learned from the sky and from a bounce more reaches the screen,+//! so its light can be measured against the reference (LT1). A pixel whose cell is new this frame draws Bevy's own+//! light until the cell has learned. Screen probes come after (LT8): a probe every 16 pixels tracing the screen, then+//! the TLAS, ending in the cache.+//!+//! On with RAEA_GI=1, on every 3D camera, which gets its depth and normal prepasses, with MSAA off.++use bevy::{+ core_pipeline::{+ prepass::{DepthPrepass, NormalPrepass, ViewPrepassTextures},+ schedule::Core3d,+ Core3dSystems,+ },+ diagnostic::FrameCount,+ pbr::RaeaGiScreen,+ prelude::*,+ render::{+ camera::ExtractedCamera,+ extract_component::{ExtractComponent, ExtractComponentPlugin},+ render_resource::{+ binding_types::{texture_2d, texture_depth_2d, texture_storage_2d, uniform_buffer, uniform_buffer_sized},+ *,+ },+ renderer::{RenderContext, RenderDevice, ViewQuery},+ texture::{CachedTexture, TextureCache},+ view::{ViewUniform, ViewUniformOffset, ViewUniforms},+ Render, RenderApp, RenderStartup, RenderSystems,+ },+};+use raea_sys_rt::gi::WorldCache;++/// A camera whose pixels take raea GI's light (RAEA_GI=1). Brings the prepasses it reads.+#[derive(Component, Clone, Copy, Default, ExtractComponent)]+#[extract_app(bevy::render::RenderApp)]+#[require(DepthPrepass, NormalPrepass)]+pub struct GiScreen;++/// the screen's format: the light arriving (rgb), and 1 where a cell had any (a)+const FORMAT: TextureFormat = TextureFormat::Rgba16Float;++pub fn install(app: &mut App) {+ if std::env::var("RAEA_GI").as_deref() != Ok("1") {+ return;+ }+ bevy::asset::embedded_asset!(app, "screen.wesl");+ app.add_plugins(ExtractComponentPlugin::<GiScreen>::default()).add_systems(PostUpdate, cameras);+ let Some(render) = app.get_sub_app_mut(RenderApp) else { return };+ render+ .add_systems(RenderStartup, init)+ .add_systems(Render, textures.in_set(RenderSystems::PrepareResources))+ .add_systems(Core3d, draw.after(Core3dSystems::Prepass).before(Core3dSystems::MainPass));+}++/// Every 3D camera takes the screen's light, single-sampled: PrepassRead keeps MSAA off and the prepasses on whatever+/// the camera's row says (raea-sys-post's msaa_for_3d and sync).+fn cameras(mut commands: Commands, q: Query<Entity, (With<Camera3d>, Without<GiScreen>)>) {+ for e in &q {+ commands.entity(e).insert((GiScreen, raea_sys_compose::passes::PrepassRead, Msaa::Off));+ }+}++/// a view's screen and this frame's parameters+#[derive(Component)]+struct GiFrame {+ screen: CachedTexture,+ params: Buffer,+}++/// screen.wesl's Params, three vec4s: toward the sun, the sun's light (lux), the frame's salt+const PARAMS_BYTES: u64 = 48;++/// Each view's screen, at its target's size, and the lighting's binding to it. None until the world cache has run (its+/// first frame), so the main pass draws Bevy's own light until then.+fn textures(+ mut commands: Commands,+ mut cache: ResMut<TextureCache>,+ device: Res<RenderDevice>,+ frame: Res<FrameCount>,+ world: Option<Res<WorldCache>>,+ views: Query<(Entity, &ExtractedCamera), With<GiScreen>>,+) {+ let Some(world) = world else { return };+ let (d, l) = (world.sun_dir, world.sun_light);+ let words: [u32; 12] = [d.x.to_bits(), d.y.to_bits(), d.z.to_bits(), 0, l.x.to_bits(), l.y.to_bits(), l.z.to_bits(), 0, frame.0.wrapping_mul(0x9e37_79b9), 0, 0, 0];+ let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();+ for (e, camera) in &views {+ let Some(size) = camera.physical_target_size else { continue };+ let screen = cache.get(+ &device,+ TextureDescriptor {+ label: Some("raea_gi_screen"),+ size: Extent3d { width: size.x, height: size.y, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: TextureDimension::D2,+ format: FORMAT,+ usage: TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING,+ view_formats: &[],+ },+ );+ let params = device.create_buffer_with_data(&BufferInitDescriptor { label: Some("raea_gi_screen_params"), contents: &bytes, usage: BufferUsages::UNIFORM });+ commands.entity(e).insert((RaeaGiScreen(screen.default_view.clone()), GiFrame { screen, params }));+ }+}++#[derive(Resource)]+struct GiPipeline {+ layout: BindGroupLayoutDescriptor,+ id: CachedComputePipelineId,+}++fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCache>) {+ let layout = BindGroupLayoutDescriptor::new(+ "raea_gi_screen_layout",+ &BindGroupLayoutEntries::sequential(+ ShaderStages::COMPUTE,+ (+ uniform_buffer::<ViewUniform>(true),+ texture_depth_2d(),+ texture_2d(TextureSampleType::Float { filterable: false }),+ texture_storage_2d(FORMAT, StorageTextureAccess::WriteOnly),+ uniform_buffer_sized(false, core::num::NonZero::new(PARAMS_BYTES)),+ ),+ ),+ );+ // group 1 is the world cache's own (raea-sys-rt cache.rs), bound as raea-sys-rt bound it this frame+ let id = cache.queue_compute_pipeline(ComputePipelineDescriptor {+ label: Some("raea_gi_screen".into()),+ layout: vec![layout.clone(), raea_sys_rt::cache::layout()],+ shader: assets.load("embedded://raea_sys_gi/screen.wesl"),+ entry_point: Some("main".into()),+ ..default()+ });+ commands.insert_resource(GiPipeline { layout, id });+}++/// Each view's screen from its prepasses and this frame's world cache, before the main pass reads it.+fn draw(+ view: ViewQuery<(&ViewPrepassTextures, &ViewUniformOffset, &GiFrame)>,+ pipeline: Option<Res<GiPipeline>>,+ world: Option<Res<WorldCache>>,+ uniforms: Res<ViewUniforms>,+ cache: Res<PipelineCache>,+ mut ctx: RenderContext,+) {+ let (Some(p), Some(world), Some(view_binding)) = (pipeline, world, uniforms.uniforms.binding()) else { return };+ let (prepass, offset, f) = view.into_inner();+ let (Some(rp), Some(depth), Some(normal)) = (cache.get_compute_pipeline(p.id), prepass.depth_only_view(), prepass.normal_view()) else { return };+ let group = ctx.render_device().create_bind_group(+ "raea_gi_screen",+ &cache.get_bind_group_layout(&p.layout),+ &BindGroupEntries::sequential((view_binding, depth, normal, &f.screen.default_view, f.params.as_entire_binding())),+ );+ let size = f.screen.texture.size();+ let mut pass = ctx.command_encoder().begin_compute_pass(&ComputePassDescriptor { label: Some("raea_gi_screen"), timestamp_writes: None });+ pass.set_pipeline(rp);+ pass.set_bind_group(0, &group, &[offset.offset]);+ pass.set_bind_group(1, &world.group, &[]);+ pass.dispatch_workgroups(size.width.div_ceil(8), size.height.div_ceil(8), 1);+}diff --git a/systems/gi/src/screen.wesl b/systems/gi/src/screen.weslnew file mode 100644index 00000000..56760e08--- /dev/null+++ b/systems/gi/src/screen.wesl@@ -0,0 +1,57 @@+// raea GI's screen pass (lib.rs; docs/realism.feature LT8): each pixel's indirect diffuse light, read from the world+// cache (raea-sys-rt cache.wesl) at the pixel's own surface, with the sun's share taken out (raster draws the sun, its+// shadows with it). Written as the irradiance volume's light is (irradiance over pi), and 1 in alpha where a cell had+// any; 0 where the pixel is sky, outside the view, or its cell is new, so the main pass draws Bevy's own light there.+import bevy_render::view::View;+import raea_sys_rt::cache::{find, hash, radiance, cells, sunlit, LIFE, NONE};++@group(0) @binding(0) var<uniform> view: View;+@group(0) @binding(1) var depth_tex: texture_depth_2d;+@group(0) @binding(2) var normal_tex: texture_2d<f32>;+@group(0) @binding(3) var out_tex: texture_storage_2d<rgba16float, write>;++struct Params {+ /// toward the sun (xyz)+ sun_dir: vec4<f32>,+ /// the sun's light (rgb, lux), as the cache's cells were lit by it+ sun: vec4<f32>,+ /// the frame's salt+ run: vec4<u32>,+}+@group(0) @binding(4) var<uniform> p: Params;++const PI: f32 = 3.14159265;++@compute @workgroup_size(8, 8, 1)+fn main(@builtin(global_invocation_id) id: vec3<u32>) {+ let size = textureDimensions(out_tex);+ if (any(id.xy >= size)) {+ return;+ }+ let px = vec2<i32>(id.xy);+ let at_px = vec2<f32>(id.xy) + 0.5;+ let uv = (at_px - view.viewport.xy) / view.viewport.zw;+ let d = textureLoad(depth_tex, px, 0);+ // sky (reverse z: 0 is infinitely far), or outside the view+ if (d <= 0.0 || any(uv < vec2(0.0)) || any(uv > vec2(1.0))) {+ textureStore(out_tex, px, vec4(0.0));+ return;+ }+ let w = view.world_from_clip * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d, 1.0);+ let at = w.xyz / w.w;+ let n = normalize(textureLoad(normal_tex, px, 0).xyz * 2.0 - 1.0);+ var seed = hash(id.x * 1973u + id.y * 9277u + p.run.x);+ let k = find(at + n * 0.02, n, LIFE, &seed);+ if (k == NONE) {+ textureStore(out_tex, px, vec4(0.0));+ return;+ }+ let r = radiance[k];+ if (r.a < 1.0) {+ textureStore(out_tex, px, vec4(0.0));+ return;+ }+ // the sun as the cell saw it: on its own side, the share of its learning the sun was in view+ let sun = p.sun.xyz * max(dot(cells[k].n.xyz, p.sun_dir.xyz), 0.0) * sunlit[k];+ textureStore(out_tex, px, vec4(max(r.rgb - sun, vec3(0.0)) / PI, 1.0));+}diff --git a/systems/rt/src/cache.rs b/systems/rt/src/cache.rsindex 3c25b795..397d6ce4 100644--- a/systems/rt/src/cache.rs+++ b/systems/rt/src/cache.rs@@ -1,5 +1,5 @@//! raea GI's world cache, its buffers and passes (docs/realism.feature LT3; cache.wesl, compact.wesl, and gi.wesl's-//! `learn` and `blend`): 2^20 cells of 84 bytes (84 MiB) on the surfaces rays hit. Each frame, before the probes, every+//! `learn` and `blend`): 2^20 cells of 88 bytes (88 MiB) on the surfaces rays hit. Each frame, before the probes, every//! cell ages and the live ones are listed (compact.wesl); about RAEA_GI_UPDATES of them (40000) learn one bounce more//! and take it into their means. The probes then read it where their rays hit (gi.wesl). The list's length becomes the//! update's dispatch on the GPU: wgpu won't take a buffer as a dispatch's arguments while that dispatch binds it for@@ -23,9 +23,10 @@ use bevy::{/// cells in all: 1024 blocks of 1024 (cache.wesl's CELLS; compact.wesl lists them in two levels)pub(crate) const CELLS: u64 = 1 << 20;-/// the cache's buffers in binding order, each `(label, bytes)`: a cell's 84 bytes are a checksum, a life, its light,-/// where it is and its side, its light's change, its place in the list's block sum, its place in the list, its new light-const BUFFERS: [(&str, u64); 11] = [+/// the cache's buffers in binding order, each `(label, bytes)`: a cell's 88 bytes are a checksum, a life, its light,+/// where it is and its side, its light's change, its place in the list's block sum, its place in the list, its new+/// light, and how much of the time it sees the sun (so a pixel can take the sun out: raea-sys-gi, whose raster has it)+const BUFFERS: [(&str, u64); 12] = [("raea gi cache checksums", 4 * CELLS),("raea gi cache life", 4 * CELLS),("raea gi cache radiance", 16 * CELLS),@@ -37,6 +38,7 @@ const BUFFERS: [(&str, u64); 11] = [("raea gi cache count", 4),("raea gi cache dispatch", 16),("raea gi cache learned", 16 * CELLS),+ ("raea gi cache sunlit", 4 * CELLS),];/// where the list's length and its dispatch are among BUFFERSpub(crate) const COUNT: usize = 8;@@ -63,10 +65,10 @@ impl Upkeep {}}-/// the cache's bindings: group 1 of every pass that reads or keeps it-pub(crate) fn layout() -> BindGroupLayoutDescriptor {+/// the cache's bindings: group 1 of every pass that reads or keeps it (raea-sys-gi's screen pass among them)+pub fn layout() -> BindGroupLayoutDescriptor {let s = || storage_buffer_sized(false, None);- BindGroupLayoutDescriptor::new("raea_gi_cache_layout", &BindGroupLayoutEntries::sequential(ShaderStages::COMPUTE, (s(), s(), s(), s(), s(), s(), s(), s(), s(), s(), s(), uniform_buffer::<Upkeep>(false))))+ BindGroupLayoutDescriptor::new("raea_gi_cache_layout", &BindGroupLayoutEntries::sequential(ShaderStages::COMPUTE, (s(), s(), s(), s(), s(), s(), s(), s(), s(), s(), s(), s(), uniform_buffer::<Upkeep>(false))))}/// the cache's six passes, in the order they rundiff --git a/systems/rt/src/cache.wesl b/systems/rt/src/cache.weslindex 49e2d555..a7f31249 100644--- a/systems/rt/src/cache.wesl+++ b/systems/rt/src/cache.wesl@@ -39,7 +39,10 @@ struct Upkeep {@group(1) @binding(9) var<storage, read_write> dispatch: vec3<u32>;// each listed cell's new light this frame, before the blend@group(1) @binding(10) var<storage, read_write> learned: array<vec4<f32>>;-@group(1) @binding(11) var<uniform> upkeep: Upkeep;+// how much of the time the cell sees the sun, a mean as its light's: the sun's share of its light, which a pixel+// whose raster draws the sun itself takes out (raea-sys-gi)+@group(1) @binding(11) var<storage, read_write> sunlit: array<f32>;+@group(1) @binding(12) var<uniform> upkeep: Upkeep;/// cells in all (cache.rs CELLS): 1024 blocks of 1024const CELLS: u32 = 1048576u;@@ -48,6 +51,8 @@ const LIFE: u32 = 10u;/// the most cells tried after a collisionconst SEARCH: u32 = 3u;const EMPTY: u32 = 0u;+/// no cell: one claimed new this frame, or none to be had+const NONE: u32 = 0xffffffffu;fn hash(v: u32) -> u32 {let s = v * 747796405u + 2891336453u;@@ -93,9 +98,19 @@ fn key_of(at: vec3<f32>, n: vec3<f32>, size: f32) -> vec2<u32> {}/// The light a cell holds at a place and side (rgb) and over how many frames (a: 0 for a cell new this frame, or-/// none to be had), keeping it alive `keep` frames. The place is jittered across the surface by up to half a cell,-/// so the cache reads as a blur rather than a grid. A cell not found is claimed, empty: some update learns it.-fn read(at_in: vec3<f32>, n: vec3<f32>, keep: u32, seed: ptr<function, u32>) -> vec4<f32> {+/// none to be had), keeping it alive `keep` frames (see `find`).+fn read(at: vec3<f32>, n: vec3<f32>, keep: u32, seed: ptr<function, u32>) -> vec4<f32> {+ let k = find(at, n, keep, seed);+ if (k == NONE) {+ return vec4(0.0);+ }+ return radiance[k];+}++/// The cell at a place and side, kept alive `keep` frames: NONE for one claimed new this frame, or none to be had.+/// The place is jittered across the surface by up to half a cell, so the cache reads as a blur rather than a grid. A+/// cell not found is claimed, empty: some update learns it.+fn find(at_in: vec3<f32>, n: vec3<f32>, keep: u32, seed: ptr<function, u32>) -> u32 {var at = at_in;var size = cell_size(at, seed);let t = normalize(cross(n, select(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), abs(n.x) > 0.9)));@@ -105,18 +120,31 @@ fn read(at_in: vec3<f32>, n: vec3<f32>, keep: u32, seed: ptr<function, u32>) ->let kc = key_of(at, n, size);var key = kc.x;for (var i = 0u; i < SEARCH; i++) {- let cas = atomicCompareExchangeWeak(&checksums[key], EMPTY, kc.y);- if (cas.old_value == kc.y || cas.old_value == EMPTY) {- atomicMax(&life[key], keep);- }- if (cas.old_value == kc.y) {- return radiance[key];+ // a plain load first: a screen's pixels read the same cell by the hundred, and a write each would queue them+ let now = atomicLoad(&checksums[key]);+ if (now == kc.y) {+ if (atomicLoad(&life[key]) < keep) {+ atomicMax(&life[key], keep);+ }+ return key;}- if (cas.old_value == EMPTY && cas.exchanged) {- cells[key] = Cell(vec4(at, 0.0), vec4(n, 0.0));- return vec4(0.0);+ if (now == EMPTY) {+ let cas = atomicCompareExchangeWeak(&checksums[key], EMPTY, kc.y);+ if (cas.exchanged) {+ atomicMax(&life[key], keep);+ cells[key] = Cell(vec4(at, 0.0), vec4(n, 0.0));+ return NONE;+ }+ if (cas.old_value == kc.y) {+ atomicMax(&life[key], keep);+ return key;+ }+ if (cas.old_value == EMPTY) {+ // the weak exchange failed with nothing there: tried again next frame+ return NONE;+ }}key = (key + 1u) & (CELLS - 1u);}- return vec4(0.0);+ return NONE;}diff --git a/systems/rt/src/gi.rs b/systems/rt/src/gi.rsindex c1e75886..c2f20902 100644--- a/systems/rt/src/gi.rs+++ b/systems/rt/src/gi.rs@@ -223,8 +223,18 @@ fn key(g: &Grid) -> [u32; 9] {[f(g.sun.x), f(g.sun.y), f(g.sun.z), f(g.sun_light.x), f(g.sun_light.y), f(g.sun_light.z), h, f(i), g.res.x ^ (g.res.y << 10) ^ (g.res.z << 20)]}+/// This frame's world cache for passes outside raea-sys-rt (raea-sys-gi's screen pass, after this frame's update): its+/// group 1 (cache::layout), and the sun its cells were lit by, toward it and its light (lux)+#[derive(Resource, Clone)]+pub struct WorldCache {+ pub group: BindGroup,+ pub sun_dir: Vec3,+ pub sun_light: Vec3,+}+#[allow(clippy::too_many_arguments)]fn update(+ mut commands: Commands,grid: Option<Res<Grid>>,scene: Option<Res<crate::Scene>>,images: Res<RenderAssets<GpuImage>>,@@ -276,6 +286,7 @@ fn update(upkeep.write_buffer(&device, &queue);let cells = state.cache.get_or_insert_with(|| crate::cache::buffers(&device));let cache_group = crate::cache::bind(&device, &cache.get_bind_group_layout(&p.cache_layout), cells, upkeep.binding().unwrap());+ commands.insert_resource(WorldCache { group: cache_group.clone(), sun_dir: grid.sun.truncate(), sun_light: grid.sun_light });if state.timer.is_none() && device.features().contains(WgpuFeatures::TIMESTAMP_QUERY) {state.timer = Some(timer(&device, &queue));}diff --git a/systems/rt/src/gi.wesl b/systems/rt/src/gi.weslindex 28b571bb..ea23fcda 100644--- a/systems/rt/src/gi.wesl+++ b/systems/rt/src/gi.wesl@@ -5,7 +5,7 @@// 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// standard material samples in place of its environment's diffuse light. `learn` and `blend` are the cache's update.-import raea_sys_rt::cache::{read, rand, hash, radiance, cells, deltas, life, live, count, learned, upkeep, LIFE};+import raea_sys_rt::cache::{read, rand, hash, radiance, cells, deltas, life, live, count, learned, sunlit, upkeep, LIFE};enable wgpu_ray_query;@@ -259,9 +259,11 @@ fn learn(@builtin(global_invocation_id) id: vec3<u32>) {let n = c.n.xyz;let o = c.at.xyz + n * 0.02;var e = vec3(0.0);+ var seen = 0.0;let ndl = dot(n, p.sun_dir.xyz);if (ndl > 0.0 && sees_sun(o, p.sun_dir.xyz)) {e = p.sun.xyz * ndl;+ seen = 1.0;}let d = cosine(n, &seed);let t = first_hit(o, d);@@ -272,7 +274,8 @@ fn learn(@builtin(global_invocation_id) id: vec3<u32>) {// the cell met lives as long as the one reading ite += ALBEDO * irradiance_at(o + d * t, -d, atomicLoad(&life[cell]), &seed);}- learned[id.x] = vec4(e, 1.0);+ // the light (rgb) and whether the sun was seen (a)+ learned[id.x] = vec4(e, seen);}// Each cell that learned this frame takes its new light into its mean: up to upkeep.size.z frames, fewer while its@@ -297,4 +300,5 @@ fn blend(@builtin(global_invocation_id) id: vec3<u32>) {let mixed = mix(old.rgb, now, w);deltas[cell] = select(mix(delta, luma(mixed) - luma(old.rgb), 1.0 / 8.0), 0.0, reset);radiance[cell] = vec4(mixed, n);+ sunlit[cell] = mix(sunlit[cell], learned[id.x].a, w);}diff --git a/systems/rt/src/lib.rs b/systems/rt/src/lib.rsindex b8cbea3f..3f1b31f6 100644--- a/systems/rt/src/lib.rs+++ b/systems/rt/src/lib.rs@@ -7,8 +7,8 @@// traced ambient occlusion, the TLAS's first reader; raea GI's world probes (RAEA_GI=1, docs/realism.feature LT2)pub mod gi;-// raea GI's world cache: a hash grid of the light on the surfaces rays hit (LT3)-pub(crate) mod cache;+// raea GI's world cache: a hash grid of the light on the surfaces rays hit (LT3); its layout read by raea-sys-gi+pub mod cache;// the sun's far shadow map, past the last cascade (RAEA_SUN_FAR, LT21)pub mod far;pub mod traced_ao;diff --git a/vendor/bevy_pbr/src/prepass/mod.rs b/vendor/bevy_pbr/src/prepass/mod.rsindex 3aaa7772..c4379e72 100644--- a/vendor/bevy_pbr/src/prepass/mod.rs+++ b/vendor/bevy_pbr/src/prepass/mod.rs@@ -926,7 +926,7 @@ pub fn check_prepass_views_need_specialization(Option<&DepthPrepass>,Option<&NormalPrepass>,Option<&MotionVectorPrepass>,- bevy_ecs::query::Has<TemporalJitter>,+ Has<TemporalJitter>,)>,) {for (view, msaa, depth_prepass, normal_prepass, motion_vector_prepass, jitter) in views.iter_mut() {diff --git a/vendor/bevy_pbr/src/render/mesh_view_bindings.rs b/vendor/bevy_pbr/src/render/mesh_view_bindings.rsindex 4cb997a5..b03c0988 100644--- a/vendor/bevy_pbr/src/render/mesh_view_bindings.rs+++ b/vendor/bevy_pbr/src/render/mesh_view_bindings.rs@@ -497,6 +497,8 @@ fn layout_entries((39, texture_2d(TextureSampleType::Float { filterable: false })),(40, uniform_buffer_sized(false, NonZero::new(RAEA_FAR_SUN_BYTES))),));+ // raea: the view's indirect light from raea GI (RaeaGiScreen)+ entries = entries.extend_with_indices(((41, texture_2d(TextureSampleType::Float { filterable: false })),));let mut binding_array_entries = DynamicBindGroupLayoutEntries::new(ShaderStages::FRAGMENT);if layout_key.contains(MeshPipelineViewLayoutKey::ENVIRONMENT_MAP) {@@ -554,6 +556,13 @@ pub struct RaeaFarSun {/// raea: the uniform's size (six vec4s: mesh_view_bindings.wesl's RaeaFarSun)pub const RAEA_FAR_SUN_BYTES: u64 = 96;+/// raea: a view's indirect diffuse light from raea GI (raea's raea-sys-gi, docs/realism.feature LT3 and LT8), a texel a+/// pixel, read where the pixel is: the light arriving (rgb, as the irradiance volume's, which a diffuse colour turns+/// into the light sent back) and 1 where it holds any (a). In place of the irradiance volume, the environment map's+/// diffuse and the ambient light where it does. Bound at 41 of every mesh view group; where a view has none, zeros.+#[derive(Component, Clone)]+pub struct RaeaGiScreen(pub TextureView);+#[derive(Resource, Clone)]pub struct MeshPipelineViewLayouts {params: Arc<MeshPipelineViewLayoutParams>,@@ -688,6 +697,7 @@ pub fn prepare_mesh_view_bind_groups(Option<&ViewContactShadowsUniformOffset>,Option<&OrderIndependentTransparencySettingsOffset>,Has<ScreenSpaceTransmission>,+ Option<&RaeaGiScreen>,),)>,(images, fallback_image, fallback_image_zero): (@@ -767,6 +777,7 @@ pub fn prepare_mesh_view_bind_groups(view_contact_shadows_offset,view_oit_settings_offset,has_transmission,+ raea_gi,),) in &views{@@ -947,6 +958,8 @@ pub fn prepare_mesh_view_bind_groups(None => (&fallback_image.d2.texture_view, raea_far_sun_none),};entries = entries.extend_with_indices(((39, far_map), (40, far_params.as_entire_binding())));+ // raea: the view's raea GI (RaeaGiScreen), or zeros: none+ entries = entries.extend_with_indices(((41, raea_gi.map_or(&fallback_image_zero.texture_view, |g| &g.0)),));let environment_map_bind_group_entries =render_view_environment_maps.map(|render_view_environment_maps| {diff --git a/vendor/bevy_pbr/src/render/mesh_view_bindings.wesl b/vendor/bevy_pbr/src/render/mesh_view_bindings.weslindex fa6016a7..a4649ae8 100644--- a/vendor/bevy_pbr/src/render/mesh_view_bindings.wesl+++ b/vendor/bevy_pbr/src/render/mesh_view_bindings.wesl@@ -133,6 +133,10 @@ struct RaeaFarSun {@group(0) @binding(39) var raea_far_sun_map: texture_2d<f32>;@group(0) @binding(40) var<uniform> raea_far_sun: RaeaFarSun;+// raea: the view's indirect diffuse light from raea GI (mesh_view_bindings.rs RaeaGiScreen; raea's raea-sys-gi), a texel+// a pixel: the light arriving (rgb, as the irradiance volume's) and 1 where it holds any (a)+@group(0) @binding(41) var raea_gi: texture_2d<f32>;+@if(ENVIRONMENT_MAP && MULTIPLE_LIGHT_PROBES_IN_ARRAY) {@group(1) @binding(0) var diffuse_environment_maps: binding_array<texture_cube<f32>, 8u>;@group(1) @binding(1) var specular_environment_maps: binding_array<texture_cube<f32>, 8u>;diff --git a/vendor/bevy_pbr/src/render/pbr_functions.wesl b/vendor/bevy_pbr/src/render/pbr_functions.weslindex eda2b98b..3ef0d256 100644--- a/vendor/bevy_pbr/src/render/pbr_functions.wesl+++ b/vendor/bevy_pbr/src/render/pbr_functions.wesl@@ -707,6 +707,19 @@ fn apply_pbr_lighting(found_diffuse_indirect = true;}+ // raea: raea GI's indirect diffuse at this pixel (mesh_view_bindings.rs RaeaGiScreen), where it holds any: in place+ // of the irradiance volume, the environment map's diffuse and the ambient light (raea's docs/realism.feature LT8)+ var raea_gi_found = false;+ if (!found_diffuse_indirect) {+ let gi_size = vec2<i32>(textureDimensions(view_bindings::raea_gi));+ let gi = textureLoad(view_bindings::raea_gi, min(vec2<i32>(in.frag_coord.xy), gi_size - 1), 0);+ if (gi.a > 0.0) {+ indirect_light += gi.rgb * diffuse_color * diffuse_occlusion;+ found_diffuse_indirect = true;+ raea_gi_found = true;+ }+ }+@if(IRRADIANCE_VOLUME)// Irradiance volume light (indirect)if (!found_diffuse_indirect) {@@ -759,7 +772,7 @@ fn apply_pbr_lighting(let enable_ambient = (view_bindings::lights.ambient_light_flags & mesh_view_types::AMBIENT_LIGHT_FLAGS_AFFECTS_LIGHTMAPPED_MESHES_BIT) != 0u;@else // LIGHTMAPlet enable_ambient = true;- if (enable_ambient) {+ if (enable_ambient && !raea_gi_found) {indirect_light += ambient::ambient_light(in.world_position, in.N, in.V, NdotV, diffuse_color, F0, perceptual_roughness, diffuse_occlusion);}