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
Path tracer: it walks the fog volumes, so the hall's haze and steam have a ground truth
shinyobjectz5a4060df5e31
diff --git a/systems/fog/src/froxel.rs b/systems/fog/src/froxel.rsindex 81b9cd12..addcdf92 100644--- a/systems/fog/src/froxel.rs+++ b/systems/fog/src/froxel.rs@@ -52,6 +52,7 @@ use bevy::{Extract, ExtractSchedule, Render, RenderApp, RenderStartup, RenderSystems,},shader::ShaderDefVal,+ solari::pathtracer::PathtracerMedia,};mod views;@@ -159,7 +160,7 @@ fn extract_volumes(mut volumes: ResMut<Volumes>, q: Extract<Query<(&FogVolume, &volumes.corners = found.iter().map(|f| f.2).collect();}-fn prepare_volumes(mut volumes: ResMut<Volumes>, device: Res<RenderDevice>, queue: Res<RenderQueue>) {+fn prepare_volumes(mut volumes: ResMut<Volumes>, device: Res<RenderDevice>, queue: Res<RenderQueue>, media: Option<ResMut<PathtracerMedia>>) {// never empty: a storage buffer needs a sizelet mut list = volumes.list.clone();if list.is_empty() {@@ -167,6 +168,13 @@ fn prepare_volumes(mut volumes: ResMut<Volumes>, device: Res<RenderDevice>, queu}*volumes.buffer.get_mut() = list;volumes.buffer.write_buffer(&device, &queue);+ // the reference path tracer walks the same volumes (bevy_solari pathtracer/media.wesl); RAEA_PT_MEDIA=0 leaves+ // them out of it, for a frame without its air+ if let Some(mut media) = media {+ static OFF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ let off = *OFF.get_or_init(|| std::env::var("RAEA_PT_MEDIA").is_ok_and(|v| v == "0"));+ media.0 = if off { None } else { volumes.buffer.buffer().cloned() };+ }}/// A fire as the grid's light pass reads it (froxel_light.wesl's `GridFire`): it lights the fog around it, as itsdiff --git a/systems/fog/src/froxel_hero.wesl b/systems/fog/src/froxel_hero.weslindex b986ca00..9be40273 100644--- a/systems/fog/src/froxel_hero.wesl+++ b/systems/fog/src/froxel_hero.wesl@@ -39,7 +39,7 @@ import bevy_pbr::render::mesh_view_types::POINT_LIGHT_FLAGS_SPOT_LIGHT_Y_NEGATIVimport bevy_pbr::render::view_transformations::frag_coord_to_ndc;import bevy_pbr::render::view_transformations::position_ndc_to_view;import bevy_render::maths::orthonormalize;-import raea_sys_fog::froxel_volume::volume_weight;+import raea_sys_fog::froxel_volume::{Volume, volume_weight, henyey_greenstein};struct Params {view_from_clip: mat4x4<f32>,@@ -58,13 +58,6 @@ struct Params {hero_along: vec4<u32>,}-struct Volume {- local_from_world: mat4x4<f32>,- scatter: vec4<f32>,- ambient: vec4<f32>,- shape: vec4<f32>,-}-@group(1) @binding(0) var<uniform> params: Params;@group(1) @binding(1) var<storage, read> volumes: array<Volume>;@group(1) @binding(2) var grid: texture_3d<f32>;@@ -81,7 +74,6 @@ struct Volume {@group(1) @binding(8) var blocks256: texture_2d_array<f32>;@group(1) @binding(9) var nearest: sampler;-const FRAC_4_PI: f32 = 0.07957747154594767;const NONE: u32 = 0xffffffffu;// fog volumes whose sides cut the ray (more are still lit, their sides just aren't cut at)const CUT_VOLUMES: u32 = 16u;@@ -208,11 +200,6 @@ fn transmittance(ray: Ray, depth: f32) -> f32 {// ---- the integrand -----fn henyey_greenstein(g: f32, c: f32) -> f32 {- let denom = 1.0 + g * g - 2.0 * g * c;- return FRAC_4_PI * (1.0 - g * g) / (denom * sqrt(denom));-}-// the light scattered toward the eye per metre at a point (per unit of the light's colour, before the light's own// falloff), summed over the volumes holding itfn medium(hero: Hero, p: vec3<f32>) -> vec3<f32> {diff --git a/systems/fog/src/froxel_light.wesl b/systems/fog/src/froxel_light.weslindex 7f83d681..2e9c96b2 100644--- a/systems/fog/src/froxel_light.wesl+++ b/systems/fog/src/froxel_light.wesl@@ -23,7 +23,7 @@ import bevy_pbr::render::view_transformations::position_ndc_to_view;import bevy_render::maths::orthonormalize;import bevy_pbr::render::clustered_forward as clustering;import bevy_pbr::render::pbr_lighting::getDistanceAttenuation;-import raea_sys_fog::froxel_volume::volume_weight;+import raea_sys_fog::froxel_volume::{Volume, volume_weight, henyey_greenstein};struct Params {view_from_clip: mat4x4<f32>,@@ -35,13 +35,6 @@ struct Params {heroes: vec4<u32>,}-struct Volume {- local_from_world: mat4x4<f32>,- scatter: vec4<f32>,- ambient: vec4<f32>,- shape: vec4<f32>,-}-struct GridFire {center_time: vec4<f32>,size_intensity: vec4<f32>,@@ -59,15 +52,10 @@ struct GridFire {@group(1) @binding(3) var depth_texture: texture_depth_2d;}-const FRAC_4_PI: f32 = 0.07957747154594767;// the volumes a point can be in at once that directional lights are phased forconst HELD: u32 = 8u;const DIRECTIONAL: u32 = 4u;-fn henyey_greenstein(g: f32, neg_LdotV: f32) -> f32 {- let denom = 1.0 + g * g - 2.0 * g * neg_LdotV;- return FRAC_4_PI * (1.0 - g * g) / (denom * sqrt(denom));-}// the medium at a point of the view (every volume holding it, summed) and the light it scatters toward the eye per// metre: rgb scattered, a extinction. `pixel` is the frame's pixel the point is seen through (its light cluster)diff --git a/systems/fog/src/froxel_solari.wesl b/systems/fog/src/froxel_solari.weslindex 5b2f8e6d..b99e5e87 100644--- a/systems/fog/src/froxel_solari.wesl+++ b/systems/fog/src/froxel_solari.wesl@@ -21,7 +21,7 @@ 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};-import raea_sys_fog::froxel_volume::volume_weight;+import raea_sys_fog::froxel_volume::{Volume, volume_weight, henyey_greenstein, sample_phase};enable wgpu_ray_query;@@ -36,13 +36,6 @@ struct Params {heroes: vec4<u32>,}-struct Volume {- local_from_world: mat4x4<f32>,- scatter: vec4<f32>,- ambient: vec4<f32>,- shape: vec4<f32>,-}-// froxel/solari.rs SolariFogParamsstruct SolariFog {// the last frame's view (unjittered) and its grid's slab, for the history@@ -68,7 +61,6 @@ struct SolariFog {@group(1) @binding(6) var guides_was: texture_2d<f32>;@group(1) @binding(7) var guides: texture_storage_2d<rgba32float, write>;-const FRAC_4_PI: f32 = 0.07957747154594767;const LUMA = vec3(0.2126, 0.7152, 0.0722);// how much of a guide is kept from one frame to the next, so it follows a camera, an opening closed or the sun movedconst GUIDE_KEEP: f32 = 0.9;@@ -76,23 +68,6 @@ const GUIDE_KEEP: f32 = 0.9;const COS_WIDEST: f32 = 0.5;const COS_NARROWEST: f32 = 0.99939;-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>, u: vec2<f32>) -> vec3<f32> {- 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 phasefn toward_eye(s: ResolvedLightSample, P: vec3<f32>, V: vec3<f32>, g: f32) -> vec3<f32> {diff --git a/systems/fog/src/froxel_volume.wesl b/systems/fog/src/froxel_volume.weslindex 997ebd9b..add758a8 100644--- a/systems/fog/src/froxel_volume.wesl+++ b/systems/fog/src/froxel_volume.wesl@@ -1,7 +1,41 @@// A fog volume's shape as the froxel passes read it (froxel_light, froxel_hero, froxel_solari): how much of its density// a point in its box has. froxel.rs packs `shape`: x the thinning per metre going up (`falloff`), y the box's height in// metres, z the feathered share of the box's half-size at every face (`soft`), w how much narrower its floor is than-// its top (`taper`).+// its top (`taper`). The reference path tracer walks the same volumes (bevy_solari pathtracer/media.wesl).++import bevy_render::maths::{PI_2, orthonormalize};++// froxel.rs GpuVolume+struct Volume {+ local_from_world: mat4x4<f32>,+ // rgb: the light it scatters toward the eye per metre from Bevy's lights; a: extinction per metre+ scatter: vec4<f32>,+ // rgb: the scattering coefficient per metre (fog colour x scattering x density); a: anisotropy+ ambient: vec4<f32>,+ shape: vec4<f32>,+}++const FRAC_4_PI: f32 = 0.07957747154594767;++// the Henyey-Greenstein phase, per steradian, for the cosine between the direction light travels on and the one it+// came in on reversed: with V the eye ray's direction and L toward the light, cos_theta = dot(L, V), and g > 0 puts+// the glow round a light ahead of the eye+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>, u: vec2<f32>) -> vec3<f32> {+ 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);+}// The density at `local` (the box's own coordinates, -0.5 to 0.5) over the volume's density: 0 outside its shape.// Thinning is exp(-falloff x metres above the floor). Taper narrows the box's width and depth linearly toward the floor,diff --git a/vendor/bevy_solari/src/pathtracer/media.wesl b/vendor/bevy_solari/src/pathtracer/media.weslnew file mode 100644index 00000000..48087493--- /dev/null+++ b/vendor/bevy_solari/src/pathtracer/media.wesl@@ -0,0 +1,112 @@+// raea: the participating media the reference path tracer walks: the scene's fog volumes, as raea_sys_fog's froxel+// grid reads them (froxel_volume.wesl: each a box with a density shaped by its falloff, soft faces and taper), so the+// tracer is the truth the froxel passes are measured against. Extinction is grey (the volume's density x (absorption ++// scattering)), scattering coloured (fog colour x scattering x density), the phase Henyey-Greenstein.+//+// A path's segment finds its next collision by delta tracking against a majorant, the sum of the extinctions of the+// volumes the segment crosses (a volume's shape only thins it); a collision scatters the path, a null one passes.+// A shadow ray's transmittance is ratio tracked against the same majorant. Both are unbiased.+//+// This imports raea_sys_fog's shader library, which raea always installs beside Solari.++import bevy_pbr::render::utils::rand_f;+import package::scene::bindings::RAY_T_MAX;+import raea_sys_fog::froxel_volume::{Volume, volume_weight};++// pathtracer/node.rs: PathtracerMedia's buffer (a single empty volume when the scene has none)+@group(1) @binding(3) var<storage, read> volumes: array<Volume>;++// enough null collisions for a ray through the densest box the hall's steam makes, many times over+const MAX_STEPS: u32 = 512u;++struct MediaSpan {+ t0: f32,+ t1: f32,+ majorant: f32,+}++struct MediumCollision {+ // where along the ray, or -1 when it reaches t_max+ t: f32,+ // the scattering albedo (scattering over extinction, per channel)+ albedo: vec3<f32>,+ // the scattering volume's anisotropy+ g: f32,+}++// the part of [t_min, t_max] inside any volume, and the sum of the extinctions of the volumes it crosses+fn media_span(origin: vec3<f32>, direction: vec3<f32>, t_min: f32, t_max: f32) -> MediaSpan {+ var span = MediaSpan(t_max, t_min, 0.0);+ for (var v = 0u; v < arrayLength(&volumes); v++) {+ let extinction = volumes[v].scatter.a;+ if extinction <= 0.0 { continue; }+ let m = volumes[v].local_from_world;+ let o = (m * vec4(origin, 1.0)).xyz;+ let d = (m * vec4(direction, 0.0)).xyz;+ // the box -0.5..0.5, by slabs (an axis the ray runs along gives +-inf, which min and max handle)+ let inv = 1.0 / d;+ let a = (vec3(-0.5) - o) * inv;+ let b = (vec3(0.5) - o) * inv;+ let near = max(max(min(a.x, b.x), min(a.y, b.y)), max(min(a.z, b.z), t_min));+ let far = min(min(max(a.x, b.x), max(a.y, b.y)), min(max(a.z, b.z), t_max));+ if near < far {+ span.t0 = min(span.t0, near);+ span.t1 = max(span.t1, far);+ span.majorant += extinction;+ }+ }+ return span;+}++// the extinction at p summed over the volumes, and the volume that `pick` (0 to that sum) falls in: x its index+// (or none), y the sum+fn extinction_at(p: vec3<f32>, pick: f32) -> vec2<f32> {+ var sum = 0.0;+ var picked = -1.0;+ for (var v = 0u; v < arrayLength(&volumes); v++) {+ let extinction = volumes[v].scatter.a;+ if extinction <= 0.0 { continue; }+ let local = (volumes[v].local_from_world * vec4(p, 1.0)).xyz;+ sum += extinction * volume_weight(volumes[v].shape, local);+ if picked < 0.0 && pick < sum { picked = f32(v); }+ }+ return vec2(picked, sum);+}++// the ray's first real collision with the media between t_min and t_max, by delta tracking+fn media_collision(origin: vec3<f32>, direction: vec3<f32>, t_min: f32, t_max: f32, rng: ptr<function, u32>) -> MediumCollision {+ let missed = MediumCollision(-1.0, vec3(1.0), 0.0);+ let span = media_span(origin, direction, t_min, t_max);+ if span.majorant <= 0.0 || span.t0 >= span.t1 { return missed; }+ var t = span.t0;+ for (var i = 0u; i < MAX_STEPS; i++) {+ t -= log(1.0 - rand_f(rng)) / span.majorant;+ if t >= span.t1 { return missed; }+ let hit = extinction_at(origin + direction * t, rand_f(rng) * span.majorant);+ if hit.x >= 0.0 {+ let vol = volumes[u32(hit.x)];+ return MediumCollision(t, vol.ambient.rgb / vol.scatter.a, vol.ambient.a);+ }+ }+ return missed;+}++// how much of the light gets through the media between t_min and t_max, by ratio tracking (a light at infinity:+// t_max RAY_T_MAX, which the volumes' boxes cut short)+fn media_transmittance(origin: vec3<f32>, direction: vec3<f32>, t_min: f32, t_max: f32, rng: ptr<function, u32>) -> f32 {+ let span = media_span(origin, direction, t_min, min(t_max, RAY_T_MAX));+ if span.majorant <= 0.0 || span.t0 >= span.t1 { return 1.0; }+ var t = span.t0;+ var through = 1.0;+ for (var i = 0u; i < MAX_STEPS; i++) {+ t -= log(1.0 - rand_f(rng)) / span.majorant;+ if t >= span.t1 { break; }+ through *= 1.0 - extinction_at(origin + direction * t, 0.0).y / span.majorant;+ // nearly none left: roulette it out, keeping the estimate unbiased+ if through < 0.05 {+ if rand_f(rng) >= through * 10.0 { return 0.0; }+ through = 0.1;+ }+ }+ return through;+}diff --git a/vendor/bevy_solari/src/pathtracer/mod.rs b/vendor/bevy_solari/src/pathtracer/mod.rsindex 74021359..92d9538f 100644--- a/vendor/bevy_solari/src/pathtracer/mod.rs+++ b/vendor/bevy_solari/src/pathtracer/mod.rs@@ -30,6 +30,7 @@ pub struct PathtracingPlugin;impl Plugin for PathtracingPlugin {fn build(&self, app: &mut App) {embedded_asset!(app, "pathtracer.wesl");+ bevy_shader::load_shader_library!(app, "media.wesl");}fn finish(&self, app: &mut App) {@@ -46,6 +47,7 @@ impl Plugin for PathtracingPlugin {}render_app+ .init_resource::<PathtracerMedia>().add_systems(RenderStartup,init_pathtracer_pipelines.after(init_gpu_resource::<RaytracingSceneBindings>),@@ -64,6 +66,11 @@ impl Plugin for PathtracingPlugin {}}+/// raea: the participating media the path tracer walks (media.wesl): raea_sys_fog's froxel.rs puts its fog volumes'+/// buffer here each frame (froxel_volume.wesl's `Volume`). None: the tracer walks a single empty volume.+#[derive(bevy_ecs::resource::Resource, Default)]+pub struct PathtracerMedia(pub Option<bevy_render::render_resource::Buffer>);+#[derive(Component, Reflect, Default, Clone)]#[reflect(Component, Default, Clone)]#[require(Hdr)]diff --git a/vendor/bevy_solari/src/pathtracer/node.rs b/vendor/bevy_solari/src/pathtracer/node.rsindex be638b0f..c730af7c 100644--- a/vendor/bevy_solari/src/pathtracer/node.rs+++ b/vendor/bevy_solari/src/pathtracer/node.rs@@ -1,11 +1,12 @@-use super::{prepare::PathtracerAccumulationTexture, Pathtracer};+use super::{prepare::PathtracerAccumulationTexture, Pathtracer, PathtracerMedia};use crate::scene::RaytracingSceneBindings;use bevy_asset::{load_embedded_asset, AssetServer};use bevy_ecs::{prelude::*, resource::Resource, system::Commands};use bevy_render::{camera::ExtractedCamera,render_resource::{- binding_types::{texture_storage_2d, uniform_buffer},+ binding_types::{storage_buffer_read_only_sized, texture_storage_2d, uniform_buffer},+ BindingResource, Buffer, BufferInitDescriptor, BufferUsages,BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries,CachedComputePipelineId, ComputePassDescriptor, ComputePipelineDescriptor,ImageSubresourceRange, PipelineCache, ShaderStages, StorageTextureAccess, TextureFormat,@@ -20,6 +21,8 @@ use bevy_utils::default;pub struct PathtracerPipelines {bind_group_layout: BindGroupLayoutDescriptor,pipeline: CachedComputePipelineId,+ // raea: the media when the scene has none: one volume of no extinction (froxel_volume.wesl's Volume, 112 bytes)+ no_media: Buffer,}/// Initializes the pathtracer pipelines at render startup.@@ -28,6 +31,7 @@ pub fn init_pathtracer_pipelines(pipeline_cache: Res<PipelineCache>,scene_bindings: Res<RaytracingSceneBindings>,asset_server: Res<AssetServer>,+ render_device: Res<RenderDevice>,) {let bind_group_layout = BindGroupLayoutDescriptor::new("pathtracer_bind_group_layout",@@ -37,6 +41,7 @@ pub fn init_pathtracer_pipelines(texture_storage_2d(TextureFormat::Rgba32Float, StorageTextureAccess::ReadWrite),texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),uniform_buffer::<ViewUniform>(true),+ storage_buffer_read_only_sized(false, None),),),);@@ -51,9 +56,15 @@ pub fn init_pathtracer_pipelines(..default()});+ let no_media = render_device.create_buffer_with_data(&BufferInitDescriptor {+ label: Some("pathtracer_no_media"),+ contents: &[0u8; 112],+ usage: BufferUsages::STORAGE,+ });commands.insert_resource(PathtracerPipelines {bind_group_layout,pipeline,+ no_media,});}@@ -70,6 +81,7 @@ pub fn pathtracer(scene_bindings: Res<RaytracingSceneBindings>,view_uniforms: Res<ViewUniforms>,render_device: Res<RenderDevice>,+ media: Res<PathtracerMedia>,mut ctx: RenderContext,) {let (pathtracer_settings, accumulation_texture, camera, view_target, view_uniform_offset) =@@ -95,6 +107,7 @@ pub fn pathtracer(&accumulation_texture.0.default_view,view_target.get_unsampled_color_attachment().view,view_uniforms_binding,+ BindingResource::Buffer(media.0.as_ref().unwrap_or(&pathtracer_pipelines.no_media).as_entire_buffer_binding()),)),);diff --git a/vendor/bevy_solari/src/pathtracer/pathtracer.wesl b/vendor/bevy_solari/src/pathtracer/pathtracer.weslindex 9913812d..3baca26b 100644--- a/vendor/bevy_solari/src/pathtracer/pathtracer.wesl+++ b/vendor/bevy_solari/src/pathtracer/pathtracer.wesl@@ -2,7 +2,9 @@ import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;import bevy_pbr::render::utils::{rand_f, rand_vec2f};import bevy_render::view::View;import package::scene::brdf::{evaluate_brdf, evaluate_and_sample_brdf, brdf_pdf, F_AB};-import package::scene::sampling::{sample_random_light, random_emissive_light_pdf, power_heuristic, sample_environment_map_light_and_sun};+import package::scene::sampling::{generate_random_light_sample, calculate_resolved_light_contribution, trace_visibility, LightContribution, random_emissive_light_pdf, power_heuristic, sample_environment_map_light_and_sun};+import package::pathtracer::media::{media_collision, media_transmittance};+import raea_sys_fog::froxel_volume::{henyey_greenstein, sample_phase};import package::scene::bindings::{trace_ray, resolve_ray_hit_full, RAY_T_MIN, RAY_T_MAX, MIRROR_ROUGHNESS_THRESHOLD, materials, material_ids, material_alpha, coat_albedo, facing_normal, ALPHA_PREMULTIPLIED};enable wgpu_ray_query;@@ -11,6 +13,20 @@ enable wgpu_ray_query;@group(1) @binding(1) var view_output: texture_storage_2d<rgba16float, write>;@group(1) @binding(2) var<uniform> view: View;+// raea: a light sample's contribution at p (sample_random_light's), dimmed by the media on its way to p+fn sample_light_through_media(p: vec3<f32>, normal: vec3<f32>, rng: ptr<function, u32>) -> LightContribution {+ let sample = generate_random_light_sample(rng);+ let light = sample.resolved_light_sample.world_position;+ var contribution = calculate_resolved_light_contribution(sample.resolved_light_sample, p, normal);+ if trace_visibility(p, light) == 0.0 {+ contribution.radiance = vec3(0.0);+ return contribution;+ }+ let reach = select(RAY_T_MAX, distance(light.xyz, p), light.w == 1.0);+ contribution.radiance *= media_transmittance(p, contribution.wi, 0.0, reach, rng);+ return contribution;+}+@compute @workgroup_size(8, 8, 1)fn pathtrace(@builtin(global_invocation_id) global_id: vec3<u32>) {if any(global_id.xy >= vec2u(view.viewport.zw)) {@@ -42,6 +58,32 @@ fn pathtrace(@builtin(global_invocation_id) global_id: vec3<u32>) {var sees_sun = true;loop {let ray = trace_ray(ray_origin, ray_direction, ray_t_min, RAY_T_MAX, RAY_FLAG_NONE);+ // raea: the media (fog volumes, media.wesl) before the surface: a collision scatters the path there. Light is+ // sampled at it by the phase (weighted against the phase's own rays reaching an emissive surface), and the+ // path goes on along a direction drawn from the phase, which the phase's pdf cancels+ let t_hit = select(RAY_T_MAX, ray.t, ray.kind != RAY_QUERY_INTERSECTION_NONE);+ let collision = media_collision(ray_origin, ray_direction, ray_t_min, t_hit, &rng);+ if collision.t >= 0.0 {+ let p = ray_origin + ray_direction * collision.t;+ throughput *= collision.albedo;+ let light = sample_light_through_media(p, ray_direction, &rng);+ let phase = henyey_greenstein(collision.g, dot(light.wi, ray_direction));+ var weight = 1.0;+ if light.brdf_rays_can_hit {+ weight = power_heuristic(1.0 / light.inverse_solid_angle_pdf, phase);+ }+ radiance += weight * throughput * light.radiance * light.inverse_pdf * phase;+ let next = sample_phase(collision.g, ray_direction, rand_vec2f(&rng));+ p_bounce = henyey_greenstein(collision.g, dot(next, ray_direction));+ ray_origin = p;+ ray_direction = next;+ ray_t_min = 0.0;+ sees_sun = false;+ let rr = saturate(luminance(throughput));+ if rand_f(&rng) >= rr { break; }+ throughput /= rr;+ continue;+ }if ray.kind != RAY_QUERY_INTERSECTION_NONE {var ray_hit = resolve_ray_hit_full(ray);// raea: a premultiplied surface the ray stopped at: shaded in full for its alpha's share of the stops, else as@@ -74,7 +116,7 @@ fn pathtrace(@builtin(global_invocation_id) global_id: vec3<u32>) {// Sample direct lighting, but only if the surface is not mirror-likelet is_perfectly_specular = ray_hit.material.roughness <= MIRROR_ROUGHNESS_THRESHOLD && ray_hit.material.metallic > 0.9999;if !is_perfectly_specular {- let direct_lighting = sample_random_light(ray_hit.world_position, ray_hit.world_normal, &rng);+ let direct_lighting = sample_light_through_media(ray_hit.world_position, ray_hit.world_normal, &rng);mis_weight = 1.0;if direct_lighting.brdf_rays_can_hit {