Search across packages, versions, files, declarations, and comments. Use multiple terms to narrow results (AND), and add @vertex, @fragment, or @compute to filter by shader stage.
1// A postprocessing shader that implements volumetric fog via raymarching and
2// sampling directional light shadow maps.
3//
4// The overall approach is a combination of the volumetric rendering in [1] and
5// the shadow map raymarching in [2]. First, we raytrace the AABB of the fog
6// volume in order to determine how long our ray is. Then we do a raymarch, with
7// physically-based calculations at each step to determine how much light was
8// absorbed, scattered out, and scattered in. To determine in-scattering, we
9// sample the shadow map for the light to determine whether the point was in
10// shadow or not.
11//
12// [1]: https://www.scratchapixel.com/lessons/3d-basic-rendering/volume-rendering-for-developers/intro-volume-rendering.html
13//
14// [2]: http://www.alexandre-pestana.com/volumetric-lights/
16#import bevy_core_pipeline::fullscreen_vertex_shader::FullscreenVertexOutput
17#import bevy_pbr::mesh_functions::{get_world_from_local, mesh_position_local_to_clip}
18#import bevy_pbr::mesh_view_bindings::{globals, lights, view, clusterable_objects}
19#import bevy_pbr::mesh_view_types::{
20 DIRECTIONAL_LIGHT_FLAGS_VOLUMETRIC_BIT,
21 POINT_LIGHT_FLAGS_SHADOWS_ENABLED_BIT,
22 POINT_LIGHT_FLAGS_VOLUMETRIC_BIT,
23 POINT_LIGHT_FLAGS_SPOT_LIGHT_Y_NEGATIVE,
24 ClusterableObject
26#import bevy_pbr::shadow_sampling::{
27 sample_shadow_map_hardware,
28 sample_shadow_cubemap,
29 sample_shadow_map,
30 SPOT_SHADOW_TEXEL_SIZE
32#import bevy_pbr::shadows::{get_cascade_index, world_to_directional_light_local}
33#import bevy_pbr::utils::interleaved_gradient_noise
34#import bevy_pbr::view_transformations::{
35 depth_ndc_to_view_z,
36 frag_coord_to_ndc,
37 position_ndc_to_view,
38 position_ndc_to_world,
39 position_view_to_world
41#import bevy_pbr::clustered_forward as clustering
42#import bevy_pbr::lighting::getDistanceAttenuation;
44// The GPU version of [`VolumetricFog`]. See the comments in
45// `volumetric_fog/mod.rs` for descriptions of the fields here.
46struct VolumetricFog {
47 clip_from_local: mat4x4<f32>,
48 uvw_from_world: mat4x4<f32>,
49 far_planes: array<vec4<f32>, 3>,
50 fog_color: vec3<f32>,
51 light_tint: vec3<f32>,
52 ambient_color: vec3<f32>,
53 ambient_intensity: f32,
54 step_count: u32,
55 bounding_radius: f32,
56 absorption: f32,
57 scattering: f32,
58 density_factor: f32,
59 density_texture_offset: vec3<f32>,
60 scattering_asymmetry: f32,
61 light_intensity: f32,
62 jitter_strength: f32,
65@group(1) @binding(0) var<uniform> volumetric_fog: VolumetricFog;
67#ifdef MULTISAMPLED
68@group(1) @binding(1) var depth_texture: texture_depth_multisampled_2d;
69#else
70@group(1) @binding(1) var depth_texture: texture_depth_2d;
71#endif
73#ifdef DENSITY_TEXTURE
74@group(1) @binding(2) var density_texture: texture_3d<f32>;
75@group(1) @binding(3) var density_sampler: sampler;
76#endif // DENSITY_TEXTURE
78// 1 / (4π)
79const FRAC_4_PI: f32 = 0.07957747154594767;
81struct Vertex {
82 @builtin(instance_index) instance_index: u32,
83 @location(0) position: vec3<f32>,
86@vertex
87fn vertex(vertex: Vertex) -> @builtin(position) vec4<f32> {
88 return volumetric_fog.clip_from_local * vec4<f32>(vertex.position, 1.0);
91// The common Henyey-Greenstein asymmetric phase function [1] [2].
92//
93// This determines how much light goes toward the viewer as opposed to away from
94// the viewer. From a visual point of view, it controls how the light shafts
95// appear and disappear as the camera looks at the light source.
96//
97// [1]: https://www.scratchapixel.com/lessons/3d-basic-rendering/volume-rendering-for-developers/ray-marching-get-it-right.html
98//
99// [2]: https://www.pbr-book.org/4ed/Volume_Scattering/Phase_Functions#TheHenyeyndashGreensteinPhaseFunction
100fn henyey_greenstein(neg_LdotV: f32) -> f32 {
101 let g = volumetric_fog.scattering_asymmetry;
102 let denom = 1.0 + g * g - 2.0 * g * neg_LdotV;
103 return FRAC_4_PI * (1.0 - g * g) / (denom * sqrt(denom));
106@fragment
107fn fragment(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
108 // Unpack the `volumetric_fog` settings.
109 let uvw_from_world = volumetric_fog.uvw_from_world;
110 let fog_color = volumetric_fog.fog_color;
111 let ambient_color = volumetric_fog.ambient_color;
112 let ambient_intensity = volumetric_fog.ambient_intensity;
113 let step_count = volumetric_fog.step_count;
114 let bounding_radius = volumetric_fog.bounding_radius;
115 let absorption = volumetric_fog.absorption;
116 let scattering = volumetric_fog.scattering;
117 let density_factor = volumetric_fog.density_factor;
118 let density_texture_offset = volumetric_fog.density_texture_offset;
119 let light_tint = volumetric_fog.light_tint;
120 let light_intensity = volumetric_fog.light_intensity;
121 let jitter_strength = volumetric_fog.jitter_strength;
123 // Unpack the view.
124 let exposure = view.exposure;
126 // Sample the depth to put an upper bound on the length of the ray (as we
127 // shouldn't trace through solid objects). If this is multisample, just use
128 // sample 0; this is approximate but good enough.
129 let frag_coord = position;
130 let ndc_end_depth_from_buffer = textureLoad(depth_texture, vec2<i32>(frag_coord.xy), 0);
131 let view_end_depth_from_buffer = -position_ndc_to_view(
132 frag_coord_to_ndc(vec4(position.xy, ndc_end_depth_from_buffer, 1.0))).z;
134 // Calculate the start position of the ray. Since we're only rendering front
135 // faces of the AABB, this is the current fragment's depth.
136 let view_start_pos = position_ndc_to_view(frag_coord_to_ndc(frag_coord));
138 // Calculate the end position of the ray. This requires us to raytrace the
139 // three back faces of the AABB to find the one that our ray intersects.
140 var end_depth_view = 0.0;
141 for (var plane_index = 0; plane_index < 3; plane_index += 1) {
142 let plane = volumetric_fog.far_planes[plane_index];
143 let other_plane_a = volumetric_fog.far_planes[(plane_index + 1) % 3];
144 let other_plane_b = volumetric_fog.far_planes[(plane_index + 2) % 3];
146 // Calculate the intersection of the ray and the plane. The ray must
147 // intersect in front of us (t > 0).
148 let t = -plane.w / dot(plane.xyz, view_start_pos.xyz);
149 if (t < 0.0) {
150 continue;
151 }
152 let hit_pos = view_start_pos.xyz * t;
154 // The intersection point must be in front of the other backfaces.
155 let other_sides = vec2(
156 dot(vec4(hit_pos, 1.0), other_plane_a) >= 0.0,
157 dot(vec4(hit_pos, 1.0), other_plane_b) >= 0.0
158 );
160 // If those tests pass, we found our backface.
161 if (all(other_sides)) {
162 end_depth_view = -hit_pos.z;
163 break;
164 }
165 }
167 // Starting at the end depth, which we got above, figure out how long the
168 // ray we want to trace is and the length of each increment.
169 end_depth_view = min(end_depth_view, view_end_depth_from_buffer);
171 // We assume world and view have the same scale here.
172 let start_depth_view = -depth_ndc_to_view_z(frag_coord.z);
173 let ray_length_view = abs(end_depth_view - start_depth_view);
174 let inv_step_count = 1.0 / f32(step_count);
175 let step_size_world = ray_length_view * inv_step_count;
177 let directional_light_count = lights.n_directional_lights;
179 // Calculate the ray origin (`Ro`) and the ray direction (`Rd`) in NDC,
180 // view, and world coordinates.
181 let Rd_ndc = vec3(frag_coord_to_ndc(position).xy, 1.0);
182 let Rd_view = normalize(position_ndc_to_view(Rd_ndc));
183 var Ro_world = position_view_to_world(view_start_pos.xyz);
184 let Rd_world = normalize(position_ndc_to_world(Rd_ndc) - view.world_position);
186 // Offset by jitter.
187 let jitter = interleaved_gradient_noise(position.xy, globals.frame_count) * jitter_strength;
188 Ro_world += Rd_world * jitter;
190 // Use Beer's law [1] [2] to calculate the maximum amount of light that each
191 // directional light could contribute, and modulate that value by the light
192 // tint and fog color. (The actual value will in turn be modulated by the
193 // phase according to the Henyey-Greenstein formula.)
194 //
195 // [1]: https://www.scratchapixel.com/lessons/3d-basic-rendering/volume-rendering-for-developers/intro-volume-rendering.html
196 //
197 // [2]: https://en.wikipedia.org/wiki/Beer%E2%80%93Lambert_law
199 // Use Beer's law again to accumulate the ambient light all along the path.
200 var accumulated_color = exp(-ray_length_view * (absorption + scattering)) * ambient_color *
201 ambient_intensity;
203 // This is the amount of the background that shows through. We're actually
204 // going to recompute this over and over again for each directional light,
205 // coming up with the same values each time.
206 var background_alpha = 1.0;
208 // If we have a density texture, transform to its local space.
209#ifdef DENSITY_TEXTURE
210 let Ro_uvw = (uvw_from_world * vec4(Ro_world, 1.0)).xyz;
211 let Rd_step_uvw = mat3x3(uvw_from_world[0].xyz, uvw_from_world[1].xyz, uvw_from_world[2].xyz) *
212 (Rd_world * step_size_world);
213#endif // DENSITY_TEXTURE
215 for (var light_index = 0u; light_index < directional_light_count; light_index += 1u) {
216 // Volumetric lights are all sorted first, so the first time we come to
217 // a non-volumetric light, we know we've seen them all.
218 let light = &lights.directional_lights[light_index];
219 if (((*light).flags & DIRECTIONAL_LIGHT_FLAGS_VOLUMETRIC_BIT) == 0) {
220 break;
221 }
223 // Offset the depth value by the bias.
224 let depth_offset = (*light).shadow_depth_bias * (*light).direction_to_light.xyz;
226 // Compute phase, which determines the fraction of light that's
227 // scattered toward the camera instead of away from it.
228 let neg_LdotV = dot(normalize((*light).direction_to_light.xyz), Rd_world);
229 let phase = henyey_greenstein(neg_LdotV);
231 // Reset `background_alpha` for a new raymarch.
232 background_alpha = 1.0;
234 // Start raymarching.
235 for (var step = 0u; step < step_count; step += 1u) {
236 // As an optimization, break if we've gotten too dark.
237 if (background_alpha < 0.001) {
238 break;
239 }
241 // Calculate where we are in the ray.
242 let P_world = Ro_world + Rd_world * f32(step) * step_size_world;
243 let P_view = Rd_view * f32(step) * step_size_world;
245 var density = density_factor;
246#ifdef DENSITY_TEXTURE
247 // Take the density texture into account, if there is one.
248 //
249 // The uvs should never go outside the (0, 0, 0) to (1, 1, 1) box,
250 // but sometimes due to floating point error they can. Handle this
251 // case.
252 let P_uvw = Ro_uvw + Rd_step_uvw * f32(step);
253 if (all(P_uvw >= vec3(0.0)) && all(P_uvw <= vec3(1.0))) {
254 density *= textureSample(density_texture, density_sampler, P_uvw + density_texture_offset).r;
255 } else {
256 density = 0.0;
257 }
258#endif // DENSITY_TEXTURE
260 // Calculate absorption (amount of light absorbed by the fog) and
261 // out-scattering (amount of light the fog scattered away).
262 let sample_attenuation = exp(-step_size_world * density * (absorption + scattering));
264 // Process absorption and out-scattering.
265 background_alpha *= sample_attenuation;
267 // Compute in-scattering (amount of light other fog particles
268 // scattered into this ray). This is where any directional light is
269 // scattered in.
271 // Prepare to sample the shadow map.
272 let cascade_index = get_cascade_index(light_index, P_view.z);
273 let light_local = world_to_directional_light_local(
274 light_index,
275 cascade_index,
276 vec4(P_world + depth_offset, 1.0)
277 );
279 // If we're outside the shadow map entirely, local light attenuation
280 // is zero.
281 var local_light_attenuation = f32(light_local.w != 0.0);
283 // Otherwise, sample the shadow map to determine whether, and by how
284 // much, this sample is in the light.
285 if (local_light_attenuation != 0.0) {
286 let cascade = &(*light).cascades[cascade_index];
287 let array_index = i32((*light).depth_texture_base_index + cascade_index);
288 local_light_attenuation =
289 sample_shadow_map_hardware(light_local.xy, light_local.z, array_index);
290 }
292 if (local_light_attenuation != 0.0) {
293 let light_attenuation = exp(-density * bounding_radius * (absorption + scattering));
294 let light_factors_per_step = fog_color * light_tint * light_attenuation *
295 scattering * density * step_size_world * light_intensity * exposure;
297 // Modulate the factor we calculated above by the phase, fog color,
298 // light color, light tint.
299 let light_color_per_step = (*light).color.rgb * phase * light_factors_per_step;
301 // Accumulate the light.
302 accumulated_color += light_color_per_step * local_light_attenuation *
303 background_alpha;
304 }
305 }
306 }
308 // Point lights and Spot lights
309 let view_z = view_start_pos.z;
310 let is_orthographic = view.clip_from_view[3].w == 1.0;
311 let cluster_index = clustering::fragment_cluster_index(frag_coord.xy, view_z, is_orthographic);
312 let offset_and_counts = clustering::unpack_offset_and_counts(cluster_index);
313 let spot_light_start_index = offset_and_counts[0] + offset_and_counts[1];
314 for (var i: u32 = offset_and_counts[0]; i < offset_and_counts[0] + offset_and_counts[1] + offset_and_counts[2]; i = i + 1u) {
315 let light_id = clustering::get_clusterable_object_id(i);
316 let light = &clusterable_objects.data[light_id];
317 if (((*light).flags & POINT_LIGHT_FLAGS_VOLUMETRIC_BIT) == 0) {
318 continue;
319 }
321 // Reset `background_alpha` for a new raymarch.
322 background_alpha = 1.0;
324 // Start raymarching.
325 for (var step = 0u; step < step_count; step += 1u) {
326 // As an optimization, break if we've gotten too dark.
327 if (background_alpha < 0.001) {
328 break;
329 }
331 // Calculate where we are in the ray.
332 let P_world = Ro_world + Rd_world * f32(step) * step_size_world;
333 let P_view = Rd_view * f32(step) * step_size_world;
335 var density = density_factor;
337 let light_to_frag = (*light).position_radius.xyz - P_world;
338 let V = Rd_world;
339 let L = normalize(light_to_frag);
340 let distance_square = dot(light_to_frag, light_to_frag);
341 let distance_atten = getDistanceAttenuation(distance_square, (*light).color_inverse_square_range.w);
342 var local_light_attenuation = distance_atten;
343 if (i < spot_light_start_index) {
344 var shadow: f32 = 1.0;
345 if (((*light).flags & POINT_LIGHT_FLAGS_SHADOWS_ENABLED_BIT) != 0u) {
346 shadow = fetch_point_shadow_without_normal(light_id, vec4(P_world, 1.0));
347 }
348 local_light_attenuation *= shadow;
349 } else {
350 // spot light attenuation
351 // reconstruct spot dir from x/z and y-direction flag
352 var spot_dir = vec3<f32>((*light).light_custom_data.x, 0.0, (*light).light_custom_data.y);
353 spot_dir.y = sqrt(max(0.0, 1.0 - spot_dir.x * spot_dir.x - spot_dir.z * spot_dir.z));
354 if ((*light).flags & POINT_LIGHT_FLAGS_SPOT_LIGHT_Y_NEGATIVE) != 0u {
355 spot_dir.y = -spot_dir.y;
356 }
357 let light_to_frag = (*light).position_radius.xyz - P_world;
359 // calculate attenuation based on filament formula https://google.github.io/filament/Filament.html#listing_glslpunctuallight
360 // spot_scale and spot_offset have been precomputed
361 // note we normalize here to get "l" from the filament listing. spot_dir is already normalized
362 let cd = dot(-spot_dir, normalize(light_to_frag));
363 let attenuation = saturate(cd * (*light).light_custom_data.z + (*light).light_custom_data.w);
364 let spot_attenuation = attenuation * attenuation;
366 var shadow: f32 = 1.0;
367 if (((*light).flags & POINT_LIGHT_FLAGS_SHADOWS_ENABLED_BIT) != 0u) {
368 shadow = fetch_spot_shadow_without_normal(light_id, vec4(P_world, 1.0));
369 }
370 local_light_attenuation *= spot_attenuation * shadow;
371 }
373 // Calculate absorption (amount of light absorbed by the fog) and
374 // out-scattering (amount of light the fog scattered away).
375 let sample_attenuation = exp(-step_size_world * density * (absorption + scattering));
377 // Process absorption and out-scattering.
378 background_alpha *= sample_attenuation;
380 let light_attenuation = exp(-density * bounding_radius * (absorption + scattering));
381 let light_factors_per_step = fog_color * light_tint * light_attenuation *
382 scattering * density * step_size_world * light_intensity * 0.1;
384 // Modulate the factor we calculated above by the phase, fog color,
385 // light color, light tint.
386 let light_color_per_step = (*light).color_inverse_square_range.rgb * light_factors_per_step;
388 // Accumulate the light.
389 accumulated_color += light_color_per_step * local_light_attenuation *
390 background_alpha;
391 }
392 }
394 // We're done! Return the color with alpha so it can be blended onto the
395 // render target.
396 return vec4(accumulated_color, 1.0 - background_alpha);
399fn fetch_point_shadow_without_normal(light_id: u32, frag_position: vec4<f32>) -> f32 {
400 let light = &clusterable_objects.data[light_id];
402 // because the shadow maps align with the axes and the frustum planes are at 45 degrees
403 // we can get the worldspace depth by taking the largest absolute axis
404 let surface_to_light = (*light).position_radius.xyz - frag_position.xyz;
405 let surface_to_light_abs = abs(surface_to_light);
406 let distance_to_light = max(surface_to_light_abs.x, max(surface_to_light_abs.y, surface_to_light_abs.z));
408 // The normal bias here is already scaled by the texel size at 1 world unit from the light.
409 // The texel size increases proportionally with distance from the light so multiplying by
410 // distance to light scales the normal bias to the texel size at the fragment distance.
411 let depth_offset = (*light).shadow_depth_bias * normalize(surface_to_light.xyz);
412 let offset_position = frag_position.xyz + depth_offset;
414 // similar largest-absolute-axis trick as above, but now with the offset fragment position
415 let frag_ls = offset_position.xyz - (*light).position_radius.xyz ;
416 let abs_position_ls = abs(frag_ls);
417 let major_axis_magnitude = max(abs_position_ls.x, max(abs_position_ls.y, abs_position_ls.z));
419 // NOTE: These simplifications come from multiplying:
420 // projection * vec4(0, 0, -major_axis_magnitude, 1.0)
421 // and keeping only the terms that have any impact on the depth.
422 // Projection-agnostic approach:
423 let zw = -major_axis_magnitude * (*light).light_custom_data.xy + (*light).light_custom_data.zw;
424 let depth = zw.x / zw.y;
426 // Do the lookup, using HW PCF and comparison. Cubemaps assume a left-handed coordinate space,
427 // so we have to flip the z-axis when sampling.
428 let flip_z = vec3(1.0, 1.0, -1.0);
429 return sample_shadow_cubemap(frag_ls * flip_z, distance_to_light, depth, light_id);
432fn fetch_spot_shadow_without_normal(light_id: u32, frag_position: vec4<f32>) -> f32 {
433 let light = &clusterable_objects.data[light_id];
435 let surface_to_light = (*light).position_radius.xyz - frag_position.xyz;
437 // construct the light view matrix
438 var spot_dir = vec3<f32>((*light).light_custom_data.x, 0.0, (*light).light_custom_data.y);
439 // reconstruct spot dir from x/z and y-direction flag
440 spot_dir.y = sqrt(max(0.0, 1.0 - spot_dir.x * spot_dir.x - spot_dir.z * spot_dir.z));
441 if (((*light).flags & POINT_LIGHT_FLAGS_SPOT_LIGHT_Y_NEGATIVE) != 0u) {
442 spot_dir.y = -spot_dir.y;
443 }
445 // view matrix z_axis is the reverse of transform.forward()
446 let fwd = -spot_dir;
447 let offset_position =
448 -surface_to_light
449 + ((*light).shadow_depth_bias * normalize(surface_to_light));
451 // the construction of the up and right vectors needs to precisely mirror the code
452 // in render/light.rs:spot_light_view_matrix
453 var sign = -1.0;
454 if (fwd.z >= 0.0) {
455 sign = 1.0;
456 }
457 let a = -1.0 / (fwd.z + sign);
458 let b = fwd.x * fwd.y * a;
459 let up_dir = vec3<f32>(1.0 + sign * fwd.x * fwd.x * a, sign * b, -sign * fwd.x);
460 let right_dir = vec3<f32>(-b, -sign - fwd.y * fwd.y * a, fwd.y);
461 let light_inv_rot = mat3x3<f32>(right_dir, up_dir, fwd);
463 // because the matrix is a pure rotation matrix, the inverse is just the transpose, and to calculate
464 // the product of the transpose with a vector we can just post-multiply instead of pre-multiplying.
465 // this allows us to keep the matrix construction code identical between CPU and GPU.
466 let projected_position = offset_position * light_inv_rot;
468 // divide xy by perspective matrix "f" and by -projected.z (projected.z is -projection matrix's w)
469 // to get ndc coordinates
470 let f_div_minus_z = 1.0 / ((*light).spot_light_tan_angle * -projected_position.z);
471 let shadow_xy_ndc = projected_position.xy * f_div_minus_z;
472 // convert to uv coordinates
473 let shadow_uv = shadow_xy_ndc * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5, 0.5);
475 // 0.1 must match POINT_LIGHT_NEAR_Z
476 let depth = 0.1 / -projected_position.z;
478 return sample_shadow_map(
479 shadow_uv,
480 depth,
481 i32(light_id) + lights.spot_light_shadowmap_offset,
482 SPOT_SHADOW_TEXEL_SIZE
483 );
Contents