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
Fog: Solari's emissive lights and sky light the froxel grid
shinyobjectz9ae63e33c2e9
diff --git a/systems/fog/Cargo.toml b/systems/fog/Cargo.tomlindex fb8b8dfd..2769b8bc 100644--- a/systems/fog/Cargo.toml+++ b/systems/fog/Cargo.toml@@ -10,5 +10,5 @@ description = "Froxel fog (one medium in a grid along the view), glass seen throraea-sys-frame = { path = "../frame" }raea-sys-volume = { path = "../volume" }raea-core-program = { path = "../../core/program" }-bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "bevy_solari"] }bytemuck = "1"diff --git a/systems/fog/src/froxel.rs b/systems/fog/src/froxel.rsindex d505984b..1b5c6641 100644--- a/systems/fog/src/froxel.rs+++ b/systems/fog/src/froxel.rs@@ -58,6 +58,7 @@ mod views;pub use views::*;mod pipelines;pub use pipelines::*;+mod solari;/// The camera's fog as a grid: the ambient light the fog scatters (linear, times its intensity), and the grid's/// slices along the view, its tile in pixels and the points lit a cell.@@ -85,6 +86,7 @@ pub fn install(app: &mut App) {bevy::asset::embedded_asset!(app, "froxel_grid.wesl");bevy::asset::embedded_asset!(app, "froxel_hero.wesl");bevy::asset::embedded_asset!(app, "froxel_minmax.wgsl");+ bevy::asset::embedded_asset!(app, "froxel_solari.wesl");app.add_plugins(ExtractComponentPlugin::<FroxelFog>::default());let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return };render_app@@ -92,7 +94,7 @@ pub fn install(app: &mut App) {.init_resource::<GridFires>().add_systems(RenderStartup, init_pipelines.after(bevy::pbr::MeshPipelineSystems)).add_systems(ExtractSchedule, (extract_volumes, super::fire::extract_grid_fires))- .add_systems(Render, ((prepare_pipelines, prepare_volumes, prepare_fires, prepare_views).in_set(RenderSystems::Prepare), prepare_textures.in_set(RenderSystems::PrepareResources)))+ .add_systems(Render, ((prepare_pipelines, prepare_volumes, prepare_fires, prepare_views).in_set(RenderSystems::Prepare), (prepare_textures, solari::prepare).in_set(RenderSystems::PrepareResources))).add_systems(Core3d, draw.after(bevy::core_pipeline::core_3d::main_opaque_pass_3d).before(bevy::core_pipeline::core_3d::main_transparent_pass_3d));}@@ -191,15 +193,27 @@ fn prepare_fires(mut fires: ResMut<GridFires>, device: Res<RenderDevice>, queue:#[allow(clippy::too_many_arguments)]fn draw(- view: ViewQuery<(&ViewTarget, &ViewDepthStencilTexture, &ViewPipelines, &ViewGrid, &GridTextures, &MeshViewBindGroup, &Msaa, Option<&ViewShadowBindings>)>,+ view: ViewQuery<(+ &ViewTarget,+ &ViewDepthStencilTexture,+ &ViewPipelines,+ &ViewGrid,+ &GridTextures,+ &MeshViewBindGroup,+ &Msaa,+ Option<&ViewShadowBindings>,+ Option<&solari::SolariFog>,+ Option<&bevy::render::view::ViewUniformOffset>,+ )>,cache: Res<PipelineCache>,pipelines: Option<Res<Pipelines>>,volumes: Res<Volumes>,fires: Res<GridFires>,+ (solari_pipelines, scene, view_uniforms): (Option<Res<solari::SolariFogPipelines>>, Option<Res<bevy::solari::scene::RaytracingSceneBindings>>, Res<bevy::render::view::ViewUniforms>),mut ctx: RenderContext,) {let Some(p) = pipelines else { return };- let (target, depth, ids, grid, tex, view_group, msaa, shadows) = view.into_inner();+ let (target, depth, ids, grid, tex, view_group, msaa, shadows, solari_fog, view_offset) = view.into_inner();if volumes.list.is_empty() {return;}@@ -237,8 +251,18 @@ fn draw(}}+ // 1b. under Solari, what its emissive meshes and the sky scatter at each cell (froxel/solari.rs), which the+ // integrate pass then adds to the atlas's light+ let with_solari = if skip.contains("solari") {+ None+ } else {+ solari::draw(&mut ctx, &cache, solari_pipelines.as_deref(), scene.as_deref(), &view_uniforms, solari_fog, view_offset, params.clone(), vols.clone(), &tex.atlas.default_view, &tex.grid)+ };+// 2. each column front to back- let group = device.create_bind_group("froxel_integrate", &cache.get_bind_group_layout(&p.integrate_layout), &BindGroupEntries::sequential((params.clone(), &tex.atlas.default_view, &tex.grid)));+ let (integrate, group) = with_solari.unwrap_or_else(|| {+ (integrate, device.create_bind_group("froxel_integrate", &cache.get_bind_group_layout(&p.integrate_layout), &BindGroupEntries::sequential((params.clone(), &tex.atlas.default_view, &tex.grid))))+ });{let mut pass = ctx.command_encoder().begin_compute_pass(&ComputePassDescriptor { label: Some("froxel_integrate"), timestamp_writes: None });pass.set_pipeline(integrate);diff --git a/systems/fog/src/froxel/solari.rs b/systems/fog/src/froxel/solari.rsnew file mode 100644index 00000000..0404cb30--- /dev/null+++ b/systems/fog/src/froxel/solari.rs@@ -0,0 +1,226 @@+//! Solari's lights in the froxel grid (docs/raytracing.feature RT19, froxel_solari.wesl). Under Solari the grid's+//! light pass sees only Bevy's lights, so a lamp Solari lights a room with (an emissive mesh) and the sky through a+//! skylight lit no air: photo 5's hall needed a point light beside each lamp for its glow. For a view with+//! SolariLighting and Solari's scene bound, a compute pass after the light pass writes what Solari's emissive meshes+//! and the sky scatter at each cell (resampled from Solari's light list, a shadow ray each through its scene, averaged+//! over the cell's last frames) into a texture of the atlas's layout, and the integrate pass adds it to the atlas's+//! light. A second pass blurs that light over each cell's neighbours before the medium scatters it.+//! RAEA_FOG_SOLARI=0 leaves it all out (the A/B); RAEA_FOG_SOLARI_CANDIDATES (8) lights drawn a cell,+//! RAEA_FOG_SOLARI_SKY (1) sky rays a cell, RAEA_FOG_SOLARI_FRAMES (16) frames its history averages,+//! RAEA_FOG_SOLARI_PARTS (lamps,sky) which of them light it, RAEA_FOG_SOLARI_FILTER=0 no blur.++use super::*;+use bevy::render::render_resource::binding_types::texture_storage_2d;+use bevy::render::view::{ViewUniform, ViewUniformOffset, ViewUniforms};+use bevy::solari::{realtime::SolariLighting, scene::RaytracingSceneBindings};++/// What the pass reads besides the grid (froxel_solari.wesl's `SolariFog`).+#[derive(ShaderType, Clone, Copy, Default)]+pub struct SolariFogParams {+ /// the last frame's view (unjittered) and its grid's slab, for the history+ pub prev_clip_from_world: Mat4,+ pub prev_slab: Vec4,+ /// x: the frame's number; y: 1 to start the history again; z: candidates a cell; w: frames the history averages+ pub frame: UVec4,+ /// x: what lights it (1 the emissive meshes, 2 the sky); y: sky rays a cell; z: 1 to blur+ pub more: UVec4,+}++/// A view's Solari light for the grid: three textures of the atlas's size, this frame's light and the last's (its+/// history, the two swapped each frame), and what the integrate pass adds.+#[derive(Component)]+pub struct SolariFog {+ textures: [(Texture, TextureView); 2],+ filtered: (Texture, TextureView),+ size: UVec2,+ frame: u32,+ prev: (Mat4, Vec4),+ buffer: UniformBuffer<SolariFogParams>,+}++impl SolariFog {+ fn now(&self) -> &TextureView {+ &self.textures[(self.frame & 1) as usize].1+ }+ fn was(&self) -> &TextureView {+ &self.textures[((self.frame + 1) & 1) as usize].1+ }+}++/// The pass's pipeline and the integrate pass's that adds its light, made once Solari's scene layout exists.+#[derive(Resource)]+pub struct SolariFogPipelines {+ layout: BindGroupLayoutDescriptor,+ integrate_layout: BindGroupLayoutDescriptor,+ solari: CachedComputePipelineId,+ filter: CachedComputePipelineId,+ integrate: CachedComputePipelineId,+}++fn on() -> bool {+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *ON.get_or_init(|| std::env::var("RAEA_FOG_SOLARI").as_deref() != Ok("0"))+}++fn setting(name: &str, default: u32) -> u32 {+ std::env::var(name).ok().and_then(|v| v.parse().ok()).filter(|v: &u32| *v > 0).unwrap_or(default)+}++fn make_pipelines(cache: &PipelineCache, assets: &AssetServer, scene: &RaytracingSceneBindings) -> SolariFogPipelines {+ let layout = BindGroupLayoutDescriptor::new(+ "froxel_solari_layout",+ &BindGroupLayoutEntries::sequential(+ ShaderStages::COMPUTE,+ (+ uniform_buffer::<Params>(false),+ storage_buffer_read_only::<GpuVolume>(false),+ uniform_buffer::<ViewUniform>(true),+ uniform_buffer::<SolariFogParams>(false),+ texture_2d(TextureSampleType::Float { filterable: false }),+ texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),+ ),+ ),+ );+ let integrate_layout = BindGroupLayoutDescriptor::new(+ "froxel_integrate_solari_layout",+ &BindGroupLayoutEntries::with_indices(+ ShaderStages::COMPUTE,+ (+ (0, uniform_buffer::<Params>(false)),+ (1, texture_2d(TextureSampleType::Float { filterable: false })),+ (2, texture_storage_3d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly)),+ (6, texture_2d(TextureSampleType::Float { filterable: false })),+ ),+ ),+ );+ let shader: Handle<Shader> = assets.load("embedded://raea_sys_fog/froxel_solari.wesl");+ let [solari, filter] = ["solari", "filter_light"].map(|entry| {+ cache.queue_compute_pipeline(ComputePipelineDescriptor {+ label: Some(format!("froxel_{entry}").into()),+ layout: vec![scene.bind_group_layout.clone(), layout.clone()],+ shader: shader.clone(),+ entry_point: Some(entry.into()),+ ..default()+ })+ });+ let integrate = cache.queue_compute_pipeline(ComputePipelineDescriptor {+ label: Some("froxel_integrate_solari".into()),+ layout: vec![integrate_layout.clone()],+ shader: assets.load("embedded://raea_sys_fog/froxel_grid.wesl"),+ shader_defs: vec!["SOLARI".into()],+ entry_point: Some("integrate".into()),+ ..default()+ });+ SolariFogPipelines { layout, integrate_layout, solari, filter, integrate }+}++fn texture(device: &RenderDevice, size: UVec2, i: usize) -> (Texture, TextureView) {+ let t = device.create_texture(&TextureDescriptor {+ label: Some(["froxel_solari_a", "froxel_solari_b", "froxel_solari_filtered"][i]),+ size: Extent3d { width: size.x, height: size.y, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: TextureDimension::D2,+ format: TextureFormat::Rgba16Float,+ usage: TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING,+ view_formats: &[],+ });+ let v = t.create_view(&TextureViewDescriptor::default());+ (t, v)+}++/// Each Solari view's textures and parameters for this frame (the pipelines first, once Solari's scene exists).+#[allow(clippy::type_complexity)]+pub fn prepare(+ mut commands: Commands,+ device: Res<RenderDevice>,+ queue: Res<RenderQueue>,+ cache: Res<PipelineCache>,+ assets: Res<AssetServer>,+ pipelines: Option<Res<SolariFogPipelines>>,+ scene: Option<Res<RaytracingSceneBindings>>,+ mut views: Query<(Entity, &ViewGrid, &ExtractedView, &SolariLighting, Option<&mut SolariFog>)>,+) {+ if !on() {+ return;+ }+ let Some(scene) = scene else { return };+ if pipelines.is_none() {+ commands.insert_resource(make_pipelines(&cache, &assets, &scene));+ return;+ }+ let (candidates, frames, sky) = (setting("RAEA_FOG_SOLARI_CANDIDATES", 8), setting("RAEA_FOG_SOLARI_FRAMES", 16), setting("RAEA_FOG_SOLARI_SKY", 1));+ let parts = std::env::var("RAEA_FOG_SOLARI_PARTS").unwrap_or_else(|_| "lamps,sky".into());+ let parts = parts.contains("lamps") as u32 | (parts.contains("sky") as u32) << 1;+ let filter = (std::env::var("RAEA_FOG_SOLARI_FILTER").as_deref() != Ok("0")) as u32;+ for (e, grid, view, solari, fog) in &mut views {+ let g = grid.params.grid;+ let size = UVec2::new(g.x * g.w, g.y * g.z.div_ceil(g.w));+ let now = (view.clip_from_view * view.world_from_view.to_matrix().inverse(), grid.params.slab);+ let mut fresh = None;+ let fog = match fog {+ Some(f) if f.size == size => f.into_inner(),+ _ => fresh.insert(SolariFog { textures: [texture(&device, size, 0), texture(&device, size, 1)], filtered: texture(&device, size, 2), size, frame: 0, prev: now, buffer: default() }),+ };+ let reset = fog.frame == 0 || solari.reset;+ if fog.frame > 0 {+ fog.frame += 1;+ } else {+ // the first frame writes texture 1, so the next reads it as its history+ fog.frame = 1;+ }+ *fog.buffer.get_mut() = SolariFogParams { prev_clip_from_world: fog.prev.0, prev_slab: fog.prev.1, frame: UVec4::new(fog.frame, reset as u32, candidates, frames), more: UVec4::new(parts, sky, filter, 0) };+ fog.buffer.write_buffer(&device, &queue);+ fog.prev = now;+ if let Some(f) = fresh {+ commands.entity(e).insert(f);+ }+ }+}++/// After the light pass: Solari's light into the view's texture, and the integrate pass's pipeline and bind group that+/// add it, or None (no Solari here, or not ready) to integrate as before.+#[allow(clippy::too_many_arguments)]+pub fn draw<'a>(+ ctx: &mut RenderContext,+ cache: &'a PipelineCache,+ pipelines: Option<&SolariFogPipelines>,+ scene: Option<&RaytracingSceneBindings>,+ view_uniforms: &ViewUniforms,+ fog: Option<&SolariFog>,+ offset: Option<&ViewUniformOffset>,+ params: BindingResource,+ volumes: BindingResource,+ atlas: &TextureView,+ grid: &TextureView,+) -> Option<(&'a ComputePipeline, BindGroup)> {+ let (p, fog, offset) = (pipelines?, fog?, offset?);+ let (Some(scene_group), Some(pass), Some(filter), Some(integrate), Some(view)) = (+ scene.and_then(|s| s.bind_group.as_ref()),+ cache.get_compute_pipeline(p.solari),+ cache.get_compute_pipeline(p.filter),+ cache.get_compute_pipeline(p.integrate),+ view_uniforms.uniforms.binding(),+ ) else {+ return None;+ };+ let device = ctx.render_device().clone();+ let layout = cache.get_bind_group_layout(&p.layout);+ let fog_params = fog.buffer.binding()?;+ // the light found this frame into its history, then the history blurred and scattered+ let steps = [("froxel_solari", pass, fog.was(), fog.now()), ("froxel_solari_filter", filter, fog.now(), &fog.filtered.1)];+ for (label, pipeline, input, output) in steps {+ let group = device.create_bind_group(label, &layout, &BindGroupEntries::sequential((params.clone(), volumes.clone(), view.clone(), fog_params.clone(), input, output)));+ let mut c = ctx.command_encoder().begin_compute_pass(&ComputePassDescriptor { label: Some(label), timestamp_writes: None });+ c.set_pipeline(pipeline);+ c.set_bind_group(0, scene_group, &[]);+ c.set_bind_group(1, &group, &[offset.offset]);+ c.dispatch_workgroups(fog.size.x.div_ceil(8), fog.size.y.div_ceil(8), 1);+ }+ let group = device.create_bind_group(+ "froxel_integrate_solari",+ &cache.get_bind_group_layout(&p.integrate_layout),+ &BindGroupEntries::with_indices(((0, params), (1, atlas), (2, grid), (6, &fog.filtered.1))),+ );+ Some((integrate, group))+}diff --git a/systems/fog/src/froxel_grid.wesl b/systems/fog/src/froxel_grid.weslindex 700a2f06..c412b5c5 100644--- a/systems/fog/src/froxel_grid.wesl+++ b/systems/fog/src/froxel_grid.wesl@@ -25,6 +25,9 @@ struct Params {} @else {@group(0) @binding(5) var depth_texture: texture_depth_2d;}+// the light Solari's lights scatter at each cell (froxel_solari.wesl), added to the light pass's+@if(SOLARI)+@group(0) @binding(6) var solari_light: texture_2d<f32>;// the far side of slice s (the last's is the grid's far depth)fn boundary(s: f32) -> f32 {@@ -51,7 +54,10 @@ fn integrate(@builtin(global_invocation_id) id: vec3<u32>) {let back = boundary(f32(s));let len = (back - front) * stretch;front = back;- let cell = textureLoad(atlas, vec2(id.x + (s % g.w) * g.x, id.y + (s / g.w) * g.y), 0);+ let at = vec2(id.x + (s % g.w) * g.x, id.y + (s / g.w) * g.y);+ var cell = textureLoad(atlas, at, 0);+ @if(SOLARI)+ cell = vec4(cell.rgb + textureLoad(solari_light, at, 0).rgb, cell.a);let sigma_t = cell.a;let through = exp(-sigma_t * len);// Hillaire's step: the light scattered along the cell, dimmed by what of the cell lies in front of itdiff --git a/systems/fog/src/froxel_solari.wesl b/systems/fog/src/froxel_solari.weslnew file mode 100644index 00000000..362b0041--- /dev/null+++ b/systems/fog/src/froxel_solari.wesl@@ -0,0 +1,261 @@+// The froxel grid's light from Solari (docs/raytracing.feature RT19, froxel/solari.rs): at each cell of the atlas, the+// light Solari's own lights scatter toward the eye, found as Solari finds a surface's: its emissive meshes (CANDIDATES+// drawn, one kept by its share of the cell's light, resampled importance sampling, and one shadow ray to it through+// Solari's scene), and the sky through whatever opens onto it (SKY rays in directions drawn from the medium's phase,+// so the phase cancels). Bevy's lights (the sun's shafts through its shadow maps, the point and spot lights) stay the+// light pass's; Solari's directional lights are left out here, as they'd count the sun twice.+// `solari`: each frame's estimate of the light arriving (phase-weighted, before the medium's scattering) goes into the+// cell's history, found where the cell's centre was in the last frame's view, an average of its last `frames` frames.+// `filter`: the history blurred over the cell's 3 x 3 x 3 neighbours (a tent), then scattered by the medium at the+// cell's centre, which is what the integrate pass adds. The light is blurred, not the light the medium scatters, so a+// dense edge (the steam's) stays sharp while its light settles.++import bevy_render::view::View;+import bevy_render::maths::{PI_2, orthonormalize};+import bevy_pbr::render::utils::{rand_f, rand_vec2f};+import bevy_solari::scene::bindings::{trace_ray, light_sources, RAY_T_MIN, RAY_T_MAX};+import bevy_solari::scene::sampling::{generate_random_light_sample, trace_visibility, sample_environment_map_light, ResolvedLightSample};++enable wgpu_ray_query;++// the grid's (views.rs Params: what this pass reads of it, a prefix of the uniform)+struct Params {+ view_from_clip: mat4x4<f32>,+ grid: vec4<u32>,+ slab: vec4<f32>,+ viewport: vec4<f32>,+ ambient: vec4<f32>,+ counts: vec4<u32>,+ heroes: vec4<u32>,+}++struct Volume {+ local_from_world: mat4x4<f32>,+ scatter: vec4<f32>,+ ambient: vec4<f32>,+ shape: vec4<f32>,+}++// froxel/solari.rs SolariFogParams+struct SolariFog {+ // the last frame's view (unjittered) and its grid's slab, for the history+ prev_clip_from_world: mat4x4<f32>,+ prev_slab: vec4<f32>,+ // x: the frame's number; y: 1 to start the history again; z: candidates a cell; w: frames the history averages+ frame: vec4<u32>,+ // x: what lights it (1 the emissive meshes, 2 the sky); y: sky rays a cell; z: 1 to filter+ more: vec4<u32>,+}++@group(1) @binding(0) var<uniform> params: Params;+@group(1) @binding(1) var<storage, read> volumes: array<Volume>;+@group(1) @binding(2) var<uniform> view: View;+@group(1) @binding(3) var<uniform> fog: SolariFog;+// solari: the last frame's history; filter: this frame's+@group(1) @binding(4) var history: texture_2d<f32>;+// solari: this frame's history; filter: what the integrate pass adds+@group(1) @binding(5) var out: texture_storage_2d<rgba16float, write>;++const FRAC_4_PI: f32 = 0.07957747154594767;+const LUMA = vec3(0.2126, 0.7152, 0.0722);++fn henyey_greenstein(g: f32, cos_theta: f32) -> f32 {+ let denom = 1.0 + g * g - 2.0 * g * cos_theta;+ return FRAC_4_PI * (1.0 - g * g) / (denom * sqrt(denom));+}++// a direction toward the light drawn from the phase about the view's direction V (pdf: the phase itself)+fn sample_phase(g: f32, V: vec3<f32>, rng: ptr<function, u32>) -> vec3<f32> {+ let u = rand_vec2f(rng);+ var cos_theta = 1.0 - 2.0 * u.x;+ if (abs(g) > 1e-3) {+ let s = (1.0 - g * g) / (1.0 - g + 2.0 * g * u.x);+ cos_theta = clamp((1.0 + g * g - s * s) / (2.0 * g), -1.0, 1.0);+ }+ let sin_theta = sqrt(max(0.0, 1.0 - cos_theta * cos_theta));+ let phi = u.y * PI_2;+ return orthonormalize(V) * vec3(cos(phi) * sin_theta, sin(phi) * sin_theta, cos_theta);+}++// what a light sample sends to point P toward the eye, before its pdf: emitted radiance x its cosine / distance^2 x+// the phase+fn toward_eye(s: ResolvedLightSample, P: vec3<f32>, V: vec3<f32>, g: f32) -> vec3<f32> {+ let ray = s.world_position.xyz - P;+ let d2 = max(dot(ray, ray), 1e-6);+ let wi = ray * inverseSqrt(d2);+ let cos_light = saturate(dot(-wi, s.world_normal));+ return s.radiance * (cos_light / d2) * henyey_greenstein(g, dot(wi, V));+}++// a point at view depth `depth` through a frame pixel+fn view_point(pixel: vec2<f32>, depth: f32) -> vec3<f32> {+ let ndc = vec2((pixel.x - params.viewport.x) / params.viewport.z * 2.0 - 1.0, 1.0 - (pixel.y - params.viewport.y) / params.viewport.w * 2.0);+ let q4 = params.view_from_clip * vec4(ndc, 1.0, 1.0);+ let q = q4.xyz / q4.w;+ return q * (depth / -q.z);+}++// the world point at a place in the cell (0-1 each way: across, down, deep)+fn cell_point(cell: vec2<u32>, slice: u32, at: vec3<f32>) -> vec3<f32> {+ let tile = params.slab.x;+ let last = params.viewport.xy + params.viewport.zw - 0.5;+ let pixel = min(params.viewport.xy + (vec2<f32>(cell) + at.xy) * tile, last);+ let depth = params.slab.y * exp(params.slab.w * (f32(slice) + at.z) / f32(params.grid.z));+ return (view.world_from_view * vec4(view_point(pixel, depth), 1.0)).xyz;+}++// the medium at P: its scattering per metre (each volume's colour x scattering x density, thinned going up) in rgb,+// and its anisotropy weighted by each volume's share in a+fn medium(P: vec3<f32>) -> vec4<f32> {+ var sigma_s = vec3(0.0);+ var g = 0.0;+ var share = 0.0;+ for (var v = 0u; v < params.counts.x; v += 1u) {+ let vol = &volumes[v];+ let local = ((*vol).local_from_world * vec4(P, 1.0)).xyz;+ if (any(abs(local) > vec3(0.5))) {+ continue;+ }+ let s = (*vol).ambient.rgb * exp(-(*vol).shape.x * (local.y + 0.5) * (*vol).shape.y);+ sigma_s += s;+ g += (*vol).ambient.a * dot(s, LUMA);+ share += dot(s, LUMA);+ }+ return vec4(sigma_s, select(0.0, g / share, share > 0.0));+}++// an atlas texel's cell and slice, or slice >= the grid's depth where the texel holds none+fn texel_cell(t: vec2<u32>) -> vec3<u32> {+ let slice = (t.y / params.grid.y) * params.grid.w + t.x / params.grid.x;+ return vec3(t.x % params.grid.x, t.y % params.grid.y, slice);+}++fn cell_texel(cell: vec2<u32>, slice: u32) -> vec2<u32> {+ let cols = params.grid.w;+ return vec2(cell.x + (slice % cols) * params.grid.x, cell.y + (slice / cols) * params.grid.y);+}++@compute @workgroup_size(8, 8, 1)+fn solari(@builtin(global_invocation_id) id: vec3<u32>) {+ let size = textureDimensions(out);+ if (id.x >= size.x || id.y >= size.y) {+ return;+ }+ let c = texel_cell(id.xy);+ if (c.z >= params.grid.z) {+ textureStore(out, id.xy, vec4(0.0));+ return;+ }+ var rng = (id.x * 1973u + id.y * 9277u + fog.frame.x * 26699u) | 1u;++ // this frame's point: anywhere in the cell, so the history averages the whole cell+ let P = cell_point(c.xy, c.z, vec3(rand_vec2f(&rng), rand_f(&rng)));+ let V = normalize(P - view.world_position);+ let m = medium(P);+ let held = any(m.rgb > vec3(0.0));+ let g = m.a;++ var light = vec3(0.0);+ if (held) {+ // the emissive meshes: CANDIDATES drawn, one kept by its share of the light here, one shadow ray to it+ let count = select(0u, fog.frame.z, (fog.more.x & 1u) != 0u && arrayLength(&light_sources) > 0u);+ var kept: ResolvedLightSample;+ var kept_weight = 0.0;+ var w_sum = 0.0;+ for (var i = 0u; i < count; i += 1u) {+ let s = generate_random_light_sample(&rng).resolved_light_sample;+ // a directional light (w 0) is the light pass's+ if (s.world_position.w == 0.0) {+ continue;+ }+ let p_hat = dot(toward_eye(s, P, V, g), LUMA);+ let w = p_hat * s.inverse_pdf;+ w_sum += w;+ if (w > 0.0 && rand_f(&rng) * w_sum < w) {+ kept = s;+ kept_weight = p_hat;+ }+ }+ if (kept_weight > 0.0) {+ light += toward_eye(kept, P, V, g) * (w_sum / (f32(count) * kept_weight)) * trace_visibility(P, kept.world_position);+ }+ // the sky, through what opens onto it: directions drawn from the phase, so the phase cancels+ let rays = select(0u, fog.more.y, (fog.more.x & 2u) != 0u);+ var sky = vec3(0.0);+ for (var i = 0u; i < rays; i += 1u) {+ let L = sample_phase(g, V, &rng);+ let hit = trace_ray(P, L, RAY_T_MIN, RAY_T_MAX, RAY_FLAG_TERMINATE_ON_FIRST_HIT);+ if (hit.kind == RAY_QUERY_INTERSECTION_NONE) {+ sky += sample_environment_map_light(L);+ }+ }+ light += sky / f32(max(rays, 1u));+ }+ let now = light * view.exposure;++ // the history: where the cell's centre was in the last frame's view+ var n = 1.0;+ var result = now;+ if (fog.frame.y == 0u) {+ let C = cell_point(c.xy, c.z, vec3(0.5));+ let was = fog.prev_clip_from_world * vec4(C, 1.0);+ if (was.w > 0.0) {+ let ndc = was.xy / was.w;+ let px = vec2((ndc.x + 1.0) * 0.5 * params.viewport.z, (1.0 - ndc.y) * 0.5 * params.viewport.w);+ let pc = vec2<i32>(floor(px / params.slab.x));+ let ps = i32(floor(f32(params.grid.z) * log(was.w / fog.prev_slab.y) / fog.prev_slab.w));+ if (all(pc >= vec2(0)) && pc.x < i32(params.grid.x) && pc.y < i32(params.grid.y) && ps >= 0 && ps < i32(params.grid.z)) {+ let h = textureLoad(history, cell_texel(vec2<u32>(pc), u32(ps)), 0);+ n = min(h.a + 1.0, f32(fog.frame.w));+ result = mix(h.rgb, now, 1.0 / n);+ }+ }+ }+ // a cell outside every volume keeps no history (and the filter leaves it out)+ textureStore(out, id.xy, select(vec4(0.0), vec4(result, n), held));+}++@compute @workgroup_size(8, 8, 1)+fn filter_light(@builtin(global_invocation_id) id: vec3<u32>) {+ let size = textureDimensions(out);+ if (id.x >= size.x || id.y >= size.y) {+ return;+ }+ let c = texel_cell(id.xy);+ if (c.z >= params.grid.z) {+ textureStore(out, id.xy, vec4(0.0));+ return;+ }+ let sigma_s = medium(cell_point(c.xy, c.z, vec3(0.5))).rgb;+ if (all(sigma_s <= vec3(0.0))) {+ textureStore(out, id.xy, vec4(0.0));+ return;+ }+ var sum = vec3(0.0);+ var weight = 0.0;+ let reach = select(0, 1, fog.more.z != 0u);+ for (var dz = -reach; dz <= reach; dz += 1) {+ let s = i32(c.z) + dz;+ if (s < 0 || s >= i32(params.grid.z)) {+ continue;+ }+ for (var dy = -reach; dy <= reach; dy += 1) {+ let y = i32(c.y) + dy;+ if (y < 0 || y >= i32(params.grid.y)) {+ continue;+ }+ for (var dx = -reach; dx <= reach; dx += 1) {+ let x = i32(c.x) + dx;+ if (x < 0 || x >= i32(params.grid.x)) {+ continue;+ }+ let h = textureLoad(history, cell_texel(vec2(u32(x), u32(y)), u32(s)), 0);+ // a tent (1 2 1 each way), and only cells with light found (a > 0)+ let w = f32((2 - abs(dx)) * (2 - abs(dy)) * (2 - abs(dz))) * select(0.0, 1.0, h.a > 0.0);+ sum += h.rgb * w;+ weight += w;+ }+ }+ }+ textureStore(out, id.xy, vec4(sigma_s * sum / max(weight, 1e-6), 1.0));+}