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: light is dimmed by what the fog absorbs on its way to each point of it
shinyobjectzd0eb2424a61b
diff --git a/systems/fog/src/froxel.rs b/systems/fog/src/froxel.rsindex addcdf92..fad8e5d6 100644--- a/systems/fog/src/froxel.rs+++ b/systems/fog/src/froxel.rs@@ -113,6 +113,41 @@ struct GpuVolume {/// x: falloff per metre up from the box's floor; y: the box's height in metres; z: the feathered share of the/// half-size at each face (`soft`); w: how much narrower the floor is than the top (`taper`); froxel_volume.weslshape: Vec4,+ /// x: the extinction per metre that dims light on its way through the volume to a point of the fog+ /// (froxel_volume.wesl volume_depth), by [`ShadowRule`]+ shadow: Vec4,+}++/// How the fog dims light on its way to a point of it (RAEA_FOG_SHADOW). The froxel passes scatter light once, so+/// dimming it by the whole extinction loses the light the medium scatters on toward the point (white fog under a+/// uniform sky: 0.75 of the truth's); not dimming it keeps light that a grey or thick medium absorbs (grey fog: 0.60+/// against 0.40). The path tracer is the truth they're measured against (bevy_solari pathtracer/media.wesl):+/// absorption alone matched it (grey 0.411 against 0.398, white 1.000; the hall's air 0.955 of the truth's, Bevy's+/// 0.939), so it's the default.+#[derive(Clone, Copy, PartialEq, Debug)]+enum ShadowRule {+ /// Bevy's: a constant exp(-extinction x the box's half-diagonal) on every point of it, nothing else+ Bevy,+ /// not dimmed+ Off,+ /// by what the medium absorbs (density x absorption): the default+ Absorb,+ /// by absorption and the share of scattering that turns light aside (density x (absorption + scattering x (1 - g)))+ Delta,+ /// by the whole extinction (single scattering)+ Full,+}++fn shadow_rule() -> ShadowRule {+ static RULE: std::sync::OnceLock<ShadowRule> = std::sync::OnceLock::new();+ *RULE.get_or_init(|| match std::env::var("RAEA_FOG_SHADOW").as_deref() {+ Ok("off") => ShadowRule::Off,+ Ok("absorb") => ShadowRule::Absorb,+ Ok("delta") => ShadowRule::Delta,+ Ok("full") => ShadowRule::Full,+ Ok("bevy") => ShadowRule::Bevy,+ _ => ShadowRule::Absorb,+ })}/// The frame's fog volumes, in rank order (their row ids), so the medium sums them in one order every frame.@@ -138,7 +173,16 @@ fn extract_volumes(mut volumes: ResMut<Volumes>, q: Extract<Query<(&FogVolume, &let extinction = fv.density_factor * (fv.absorption + fv.scattering);let colour = fv.fog_color.to_linear().to_vec3();let tint = fv.light_tint.to_linear().to_vec3();- let light = colour * tint * fv.light_intensity * fv.scattering * fv.density_factor * (-extinction * radius).exp();+ let rule = shadow_rule();+ let bevy = if rule == ShadowRule::Bevy { (-extinction * radius).exp() } else { 1.0 };+ let light = colour * tint * fv.light_intensity * fv.scattering * fv.density_factor * bevy;+ let shadow = fv.density_factor+ * match rule {+ ShadowRule::Bevy | ShadowRule::Off => 0.0,+ ShadowRule::Absorb => fv.absorption,+ ShadowRule::Delta => fv.absorption + fv.scattering * (1.0 - fv.scattering_asymmetry.clamp(0.0, 1.0)),+ ShadowRule::Full => fv.absorption + fv.scattering,+ };let height = affine.transform_vector3a(Vec3A::Y).length();let corners = std::array::from_fn(|k| {let c = Vec3A::new(if k & 1 == 0 { -0.5 } else { 0.5 }, if k & 2 == 0 { -0.5 } else { 0.5 }, if k & 4 == 0 { -0.5 } else { 0.5 });@@ -151,6 +195,7 @@ fn extract_volumes(mut volumes: ResMut<Volumes>, q: Extract<Query<(&FogVolume, &scatter: light.extend(extinction),ambient: (colour * fv.scattering * fv.density_factor).extend(fv.scattering_asymmetry),shape: shape.map_or(Vec4::new(0.0, height, 0.0, 0.0), |s| Vec4::new(s.falloff, height, s.soft, s.taper)),+ shadow: Vec4::new(shadow, 0.0, 0.0, 0.0),},corners,));diff --git a/systems/fog/src/froxel_hero.wesl b/systems/fog/src/froxel_hero.weslindex 9be40273..3d06c56f 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, volume_weight, henyey_greenstein};+import raea_sys_fog::froxel_volume::{Volume, volume_weight, henyey_greenstein, volume_depth};struct Params {view_from_clip: mat4x4<f32>,@@ -201,9 +201,16 @@ fn transmittance(ray: Ray, depth: f32) -> f32 {// ---- the integrand ----// 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 it+// falloff), summed over the volumes holding it, and dimmed by the fog on the light's way there (volume_depth)fn medium(hero: Hero, p: vec3<f32>) -> vec3<f32> {var k = vec3(0.0);+ var depth = 0.0;+ var dir = hero.axis;+ var reach = 3.4e38;+ if (hero.kind == 0u) {+ reach = length(hero.position - p);+ dir = (hero.position - p) / max(reach, 1e-6);+ }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;@@ -217,7 +224,12 @@ fn medium(hero: Hero, p: vec3<f32>) -> vec3<f32> {}k += (*vol).scatter.rgb * w * phase;}- return k;+ if (any(k > vec3(0.0))) {+ for (var v = 0u; v < params.counts.x; v += 1u) {+ depth += volume_depth(volumes[v], p, dir, reach);+ }+ }+ return k * exp(-depth);}// a spot's cone at a point (Bevy's: the cosine off its axis, scaled and offset, squared)diff --git a/systems/fog/src/froxel_light.wesl b/systems/fog/src/froxel_light.weslindex 2e9c96b2..8e5b2d2a 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, volume_weight, henyey_greenstein};+import raea_sys_fog::froxel_volume::{Volume, volume_weight, volume_depth, henyey_greenstein};struct Params {view_from_clip: mat4x4<f32>,@@ -56,6 +56,15 @@ struct GridFire {const HELD: u32 = 8u;const DIRECTIONAL: u32 = 4u;+// what of a light's light gets through the fog from p along dir (unit) for up to t_max metres (froxel_volume.wesl)+fn light_through(p: vec3<f32>, dir: vec3<f32>, t_max: f32) -> f32 {+ var depth = 0.0;+ for (var v = 0u; v < params.counts.x; v += 1u) {+ depth += volume_depth(volumes[v], p, dir, t_max);+ }+ return exp(-depth);+}+// 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)@@ -115,6 +124,7 @@ fn medium_light(P_view: vec3<f32>, pixel: vec2<f32>) -> vec4<f32> {let array_index = i32((*light).depth_texture_base_index + cascade_index);lit = sample_shadow_map_hardware(light_local.xy, light_local.z, array_index);}+ lit *= light_through(P_world, normalize(L), 3.4e38);if (lit == 0.0) {continue;}@@ -155,6 +165,10 @@ fn medium_light(P_view: vec3<f32>, pixel: vec2<f32>) -> vec4<f32> {atten *= fetch_spot_shadow_without_normal(light_id, vec4(P_world, 1.0), pixel);}}+ if (atten > 0.0) {+ let d = sqrt(distance_square);+ atten *= light_through(P_world, light_to_frag / max(d, 1e-6), d);+ }ps += (*light).color_inverse_square_range.rgb * atten;}s += k * ps * exposure;diff --git a/systems/fog/src/froxel_solari.wesl b/systems/fog/src/froxel_solari.weslindex 2f0b97d8..bb1001f0 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, volume_weight, henyey_greenstein, sample_phase};+import raea_sys_fog::froxel_volume::{Volume, volume_weight, volume_depth, henyey_greenstein, sample_phase};enable wgpu_ray_query;@@ -68,6 +68,15 @@ const GUIDE_KEEP: f32 = 0.9;const COS_WIDEST: f32 = 0.5;const COS_NARROWEST: f32 = 0.99939;+// what of a light's light gets through the fog from p along dir (unit) for up to t_max metres (froxel_volume.wesl)+fn light_through(p: vec3<f32>, dir: vec3<f32>, t_max: f32) -> f32 {+ var depth = 0.0;+ for (var v = 0u; v < params.counts.x; v += 1u) {+ depth += volume_depth(volumes[v], p, dir, t_max);+ }+ return exp(-depth);+}+// 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> {@@ -214,7 +223,7 @@ fn sky_guided(P: vec3<f32>, C: vec3<f32>, V: vec3<f32>, g: f32, rays: u32, t: velet pdf = (1.0 - share) * phase + share * select(0.0, cone_pdf, dot(L, axis) >= cos_max);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 && pdf > 0.0) {- let arrives = sample_environment_map_light(L) * (phase / pdf);+ let arrives = sample_environment_map_light(L) * (phase / pdf) * light_through(P, L, RAY_T_MAX);sky += arrives;// weighted by what it brought: a cone's own rays, crowded in it, would otherwise narrow it frame by framefound += vec4(L, 1.0) * dot(arrives, LUMA);@@ -272,7 +281,9 @@ fn solari(@builtin(global_invocation_id) id: vec3<u32>) {}}if (kept_weight > 0.0) {- light += toward_eye(kept, P, V, g) * (w_sum / (f32(count) * kept_weight)) * trace_visibility(P, kept.world_position);+ let to = kept.world_position.xyz - P;+ let d = length(to);+ light += toward_eye(kept, P, V, g) * (w_sum / (f32(count) * kept_weight)) * trace_visibility(P, kept.world_position) * light_through(P, to / max(d, 1e-6), d);}// the sky, through what opens onto it: guided, or directions drawn from the phase (so the phase cancels)let rays = select(0u, fog.more.y, (fog.more.x & 2u) != 0u);@@ -284,7 +295,7 @@ fn solari(@builtin(global_invocation_id) id: vec3<u32>) {let L = sample_phase(g, V, rand_vec2f(&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);+ sky += sample_environment_map_light(L) * light_through(P, L, RAY_T_MAX);}}light += sky / f32(max(rays, 1u));diff --git a/systems/fog/src/froxel_volume.wesl b/systems/fog/src/froxel_volume.weslindex add758a8..e6b7c209 100644--- a/systems/fog/src/froxel_volume.wesl+++ b/systems/fog/src/froxel_volume.wesl@@ -13,6 +13,44 @@ struct Volume {// rgb: the scattering coefficient per metre (fog colour x scattering x density); a: anisotropyambient: vec4<f32>,shape: vec4<f32>,+ // x: the extinction per metre that dims light on its way to a point (froxel.rs, RAEA_FOG_SHADOW's rule)+ shadow: vec4<f32>,+}++// the optical depth light crosses in one volume on its way from p along dir (unit, world) for up to t_max metres: its+// `shadow` extinction x its shaped density along the part inside its box: closed for a plain box, else by 4+// Gauss-Legendre nodes (smooth, so the grid's cells and the hero pass's quadrature see no noise from it)+fn volume_depth(vol: Volume, p: vec3<f32>, dir: vec3<f32>, t_max: f32) -> f32 {+ if (vol.shadow.x <= 0.0) {+ return 0.0;+ }+ let o = (vol.local_from_world * vec4(p, 1.0)).xyz;+ let d = (vol.local_from_world * vec4(dir, 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), 0.0));+ 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) {+ return 0.0;+ }+ // a plain box (no soft faces, no taper: a hall's haze) thins as exp(-falloff x metres up), whose integral along+ // the ray is closed: exp(-k (up at near)) (1 - exp(-k dy (far - near))) / (k dy), k = falloff x height+ if (vol.shape.z <= 0.0 && vol.shape.w <= 0.0) {+ let k = vol.shape.x * vol.shape.y;+ let at_near = exp(-k * (o.y + 0.5 + d.y * near));+ let x = k * d.y * (far - near);+ var span = far - near;+ if (abs(x) > 1e-4) {+ span *= (1.0 - exp(-x)) / x;+ }+ return vol.shadow.x * at_near * span;+ }+ // unrolled, the nodes as literals+ let sum = 0.17392742256872692 * (volume_weight(vol.shape, o + d * mix(near, far, 0.06943184420297371)) + volume_weight(vol.shape, o + d * mix(near, far, 0.9305681557970263)))+ + 0.32607257743127307 * (volume_weight(vol.shape, o + d * mix(near, far, 0.33000947820757187)) + volume_weight(vol.shape, o + d * mix(near, far, 0.6699905217924281)));+ return vol.shadow.x * (far - near) * sum;}const FRAC_4_PI: f32 = 0.07957747154594767;diff --git a/vendor/bevy_solari/src/pathtracer/node.rs b/vendor/bevy_solari/src/pathtracer/node.rsindex c730af7c..d8b0dd87 100644--- a/vendor/bevy_solari/src/pathtracer/node.rs+++ b/vendor/bevy_solari/src/pathtracer/node.rs@@ -21,7 +21,7 @@ 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)+ // raea: the media when the scene has none: one volume of no extinction (froxel_volume.wesl's Volume, 128 bytes)no_media: Buffer,}@@ -58,7 +58,7 @@ pub fn init_pathtracer_pipelines(let no_media = render_device.create_buffer_with_data(&BufferInitDescriptor {label: Some("pathtracer_no_media"),- contents: &[0u8; 112],+ contents: &[0u8; 128],usage: BufferUsages::STORAGE,});commands.insert_resource(PathtracerPipelines {