use crate::settings::FogQuality;
use crate::view::bindings::FogVolume;
use crate::view::frame::FrameContext;
use volumes::Volumes;
pub(crate) static VOLUMETRIC_FOG: crate::shading::Module = crate::shading::Module {
name: "volumetric_fog",
source: include_str!("fog.wgsl"),
deps: &[
&crate::shading::BIND_LIT,
&crate::shading::LIGHTS,
&crate::shading::DIRECTIONAL_SHADOW,
&crate::shading::SHADOW_MASK_NONE,
&crate::shading::CONTACT_SHADOW_NONE,
&crate::shading::ENVIRONMENT,
&crate::shading::PBR,
&crate::shading::RECT_LIGHT,
&crate::shading::FOG,
&crate::shading::FINITE,
&crate::shading::sky::SKY,
],
};
pub(crate) const INJECT_ENTRY: &str = "inject";
pub(crate) const FILTER_FROXELS_ENTRY: &str = "filter_froxels";
pub(crate) const INTEGRATE_ENTRY: &str = "integrate";
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
const INJECT_GROUP: u32 = 4;
const FILTER_GROUP: u32 = 8;
const FILTER_RUN: u32 = 8;
const INTEGRATE_GROUP: u32 = 8;
const TEMPORAL_FRAMES: u32 = 16;
const TEMPORAL_REPROJECT_AMOUNT: f32 = 0.9;
const MAX_ANISOTROPY: f32 = 0.9;
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct FroxelVolumeUniform {
world_from_view: [[f32; 4]; 4],
previous_clip_from_world: [[f32; 4]; 4],
projection: [f32; 4],
size: [u32; 3],
frame: u32,
albedo: [f32; 3],
density: f32,
render_size: [f32; 2],
length: f32,
detail_spread: f32,
height: f32,
height_falloff: f32,
anisotropy: f32,
temporal_blend: f32,
ambient: f32,
volume_count: u32,
previous_length: f32,
start: f32,
volume_layout: crate::shading::fog::FogLayout,
padding_layout: [u32; 3],
}
#[cfg(test)]
pub(crate) fn mirrors() -> Vec<crate::shading::layout_tests::Mirror> {
use crate::shading::layout_tests::mirror;
vec![mirror!(
"volumetric_fog",
"FroxelVolume",
FroxelVolumeUniform,
[
world_from_view,
previous_clip_from_world,
projection,
size,
frame,
albedo,
density,
render_size,
length,
detail_spread,
height,
height_falloff,
anisotropy,
temporal_blend,
ambient,
volume_count,
previous_length,
start,
volume_layout,
]
)]
}
#[cfg(test)]
pub(crate) fn constants() -> [crate::shading::layout_tests::Constant; 1] {
[crate::shading::layout_tests::Constant::new(
"volumetric_fog",
"FOG_MOST_VOLUMES",
naga::Literal::U32(volume_froxels::MOST_VOLUMES as u32),
)]
}
pub(crate) fn froxels(quality: FogQuality, render: [u32; 2], largest: u32) -> [u32; 3] {
let (side, depth) = quality.volume();
let [width, height] = render.map(|v| v.max(1) as f32);
let across = |aspect: f32| ((side as f32 * aspect.sqrt()) as u32).clamp(1, largest);
[across(width / height), across(height / width), depth]
}
struct Pipelines {
inject: wgpu::ComputePipeline,
filter: [wgpu::ComputePipeline; 2],
integrate: wgpu::ComputePipeline,
}
pub(crate) struct VolumetricFog {
pipelines: Option<Pipelines>,
no_aerial: wgpu::TextureView,
inject_layout: wgpu::BindGroupLayout,
filter_layout: wgpu::BindGroupLayout,
integrate_layout: wgpu::BindGroupLayout,
uniform: wgpu::Buffer,
reached: volume_froxels::ReachedFroxels,
sampler: wgpu::Sampler,
volumes: Volumes,
}
impl Pipelines {
fn new(
device: &wgpu::Device,
lit: &wgpu::BindGroupLayout,
inject_layout: &wgpu::BindGroupLayout,
filter_layout: &wgpu::BindGroupLayout,
integrate_layout: &wgpu::BindGroupLayout,
) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("volumetric fog"),
source: wgpu::ShaderSource::Wgsl(crate::shading::compose(&[&VOLUMETRIC_FOG]).into()),
});
let pipeline = |label,
layouts: &[Option<&wgpu::BindGroupLayout>],
entry,
constants: &[(&str, f64)]| {
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some(label),
bind_group_layouts: layouts,
immediate_size: 0,
});
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some(label),
layout: Some(&layout),
module: &shader,
entry_point: Some(entry),
compilation_options: wgpu::PipelineCompilationOptions {
constants,
..Default::default()
},
cache: None,
})
};
let inject = pipeline(
"volumetric fog injection",
&[Some(lit), Some(inject_layout)],
INJECT_ENTRY,
&[],
);
let filter = [0., 1.].map(|axis| {
pipeline(
"volumetric fog filter",
&[None, Some(filter_layout)],
FILTER_FROXELS_ENTRY,
&[("filter_axis", axis)],
)
});
let integrate = pipeline(
"volumetric fog integration",
&[None, Some(integrate_layout)],
INTEGRATE_ENTRY,
&[],
);
Self {
inject,
filter,
integrate,
}
}
}
impl VolumetricFog {
pub fn new(device: &wgpu::Device) -> Self {
let uniform = wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let texture = |binding, filterable| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable },
view_dimension: wgpu::TextureViewDimension::D3,
multisampled: false,
},
count: None,
};
let storage = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::WriteOnly,
format: FORMAT,
view_dimension: wgpu::TextureViewDimension::D3,
},
count: None,
};
let read_only_storage = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let inject_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("volumetric fog injection"),
entries: &[
uniform,
texture(1, true),
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
storage(3),
read_only_storage(6),
read_only_storage(9),
],
});
let filter_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("volumetric fog filter"),
entries: &[uniform, texture(7, false), storage(8)],
});
let integrate_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("volumetric fog integration"),
entries: &[
uniform,
texture(4, false),
storage(5),
texture(10, true),
wgpu::BindGroupLayoutEntry {
binding: 11,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let uniform = crate::counters::buffer(
device,
&wgpu::BufferDescriptor {
label: Some("volumetric fog froxels"),
size: size_of::<FroxelVolumeUniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
},
);
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("volumetric fog"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let volumes = Volumes::new(device, &filter_layout, &uniform, ([1; 3], [1; 3]));
let no_aerial = device
.create_texture(&wgpu::TextureDescriptor {
label: Some("no aerial perspective"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D3,
format: FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default());
Self {
pipelines: None,
no_aerial,
inject_layout,
filter_layout,
integrate_layout,
uniform,
reached: volume_froxels::ReachedFroxels::new(device),
sampler,
volumes,
}
}
pub fn prepare(
&mut self,
device: &wgpu::Device,
(quality, aerial): (Option<FogQuality>, bool),
render: [u32; 2],
) {
let layout = crate::shading::fog::FogLayout::new(
quality.map(|quality| (quality.volume().1, 1.)),
aerial,
);
let (size, integrated_size) = match quality {
Some(quality) => {
let size = froxels(quality, render, device.limits().max_texture_dimension_3d);
(size, [size[0], size[1], layout.slices()])
}
None if aerial => {
let side = crate::shading::sky::AERIAL_SIDE;
([1; 3], [side, side, layout.slices()])
}
None => {
let volumes = &mut self.volumes;
volumes.integrate = None;
if volumes.size == [1; 3] && volumes.integrated_size != [1; 3] {
*volumes =
Volumes::new(device, &self.filter_layout, &self.uniform, ([1; 3], [1; 3]));
}
return;
}
};
if self.volumes.size != size {
self.volumes = Volumes::new(
device,
&self.filter_layout,
&self.uniform,
(size, integrated_size),
);
} else if self.volumes.integrated_size != integrated_size {
self.volumes.resize_integrated(
device,
&self.filter_layout,
&self.uniform,
integrated_size,
);
}
}
#[cfg(test)]
pub fn holds_aerial(&self) -> bool {
let volumes = &self.volumes;
volumes
.integrate
.as_ref()
.is_some_and(|(bound, _)| *bound != self.no_aerial)
|| (volumes.size == [1; 3] && volumes.integrated_size != [1; 3])
}
pub fn volume(&self) -> FogVolume<'_> {
FogVolume {
view: &self.volumes.integrated,
sampler: &self.sampler,
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
pub fn test_volumes(&self) -> [&wgpu::TextureView; 3] {
let volumes = &self.volumes;
let last = volumes.holds.last();
[
&volumes.scattering[last],
&volumes.scattering[volumes.integrated_from],
&volumes.integrated,
]
}
pub fn encode(&mut self, ctx: &mut FrameContext<'_>, aerial: Option<&wgpu::TextureView>) {
let history = ctx.history;
let volumes = &mut self.volumes;
let held = volumes
.holds
.frame(&history, ctx.effective.fog.map(|_| ctx.input.fog.length));
let Some(layout) = ctx.effective.fog_layout(ctx.input) else {
return;
};
let aerial = aerial.filter(|_| layout.aerial_slices > 0);
let pipelines = self.pipelines.get_or_insert_with(|| {
Pipelines::new(
ctx.device,
&ctx.bindings.lit.layout,
&self.inject_layout,
&self.filter_layout,
&self.integrate_layout,
)
});
let fog = ctx.input.fog;
let camera = ctx.input.camera;
let [width, height, _] = volumes.integrated_size;
let mut uniform = FroxelVolumeUniform {
world_from_view: camera.view.inverse().to_cols_array_2d(),
previous_clip_from_world: history.previous.to_cols_array_2d(),
projection: crate::shading::fog::froxel_projection(camera.projection),
size: match held {
Some(_) => volumes.size,
None => [width, height, 0],
},
frame: history.frames % TEMPORAL_FRAMES,
albedo: fog.albedo,
density: fog.density.max(0.),
render_size: ctx.sizes.render.map(|v| v as f32),
length: fog.length,
detail_spread: crate::shading::fog::DETAIL_SPREAD,
height: fog.height,
height_falloff: fog.height_falloff.max(0.),
anisotropy: fog.anisotropy.clamp(-MAX_ANISOTROPY, MAX_ANISOTROPY),
temporal_blend: if held.is_some_and(|(_, previous)| previous.is_some()) {
TEMPORAL_REPROJECT_AMOUNT
} else {
0.
},
ambient: fog.ambient.max(0.),
volume_count: 0,
previous_length: held
.and_then(|(_, previous)| previous)
.unwrap_or(fog.length),
start: fog.effective_start(),
volume_layout: layout,
padding_layout: [0; 3],
};
volumes.bind_aerial(
ctx.device,
&self.integrate_layout,
&self.uniform,
(aerial.unwrap_or(&self.no_aerial), &self.sampler),
);
let Some((index, _)) = held else {
crate::counters::write_buffer(
ctx.queue,
&self.uniform,
0,
bytemuck::bytes_of(&uniform),
);
let mut pass = ctx
.encoder
.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("volumetric fog integration"),
timestamp_writes: ctx.timing.and_then(|t| t.compute_pass("fog integration")),
});
pass.set_pipeline(&pipelines.integrate);
pass.set_bind_group(1, volumes.integrate_group(0), &[]);
pass.dispatch_workgroups(
width.div_ceil(INTEGRATE_GROUP),
height.div_ceil(INTEGRATE_GROUP),
1,
);
return;
};
uniform.volume_count = self.reached.write(
ctx.device,
ctx.queue,
&ctx.scene.transient.fog_volume_corners,
camera.view,
&uniform,
);
let fog_volumes = &ctx.scene.transient.fog_volumes;
let reached = &self.reached.buffer;
if volumes
.inject
.as_ref()
.is_none_or(|(scene, bound, _)| scene != fog_volumes || bound != reached)
{
let groups = [0, 1].map(|index| {
let view = wgpu::BindingResource::TextureView;
ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("volumetric fog injection"),
layout: &self.inject_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: self.uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: view(&volumes.scattering[1 - index]),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: view(&volumes.scattering[index]),
},
wgpu::BindGroupEntry {
binding: 6,
resource: fog_volumes.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 9,
resource: reached.as_entire_binding(),
},
],
})
});
volumes.inject = Some((fog_volumes.clone(), reached.clone(), groups));
}
let inject = &volumes.inject.as_ref().unwrap().2[index];
crate::counters::write_buffer(ctx.queue, &self.uniform, 0, bytemuck::bytes_of(&uniform));
let [x, y, z] = volumes.size;
let mut pass = ctx
.encoder
.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("volumetric fog injection"),
timestamp_writes: ctx.timing.and_then(|t| t.compute_pass("fog injection")),
});
pass.set_pipeline(&pipelines.inject);
pass.set_bind_group(0, ctx.bindings.camera_lit(), &[]);
pass.set_bind_group(1, inject, &[]);
pass.dispatch_workgroups(
x.div_ceil(INJECT_GROUP),
y.div_ceil(INJECT_GROUP),
z.div_ceil(INJECT_GROUP),
);
drop(pass);
volumes.integrated_from = index;
if ctx.effective.fog_filter {
let mut pass = ctx
.encoder
.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("volumetric fog filter"),
timestamp_writes: ctx.timing.and_then(|t| t.compute_pass("fog filter")),
});
let groups = |side: u32, along: bool| {
side.div_ceil(FILTER_GROUP * if along { FILTER_RUN } else { 1 })
};
for (axis, (pipeline, group)) in pipelines
.filter
.iter()
.zip(&volumes.filter[index])
.enumerate()
{
pass.set_pipeline(pipeline);
pass.set_bind_group(1, group, &[]);
pass.dispatch_workgroups(groups(x, axis == 0), groups(y, axis == 1), z);
}
volumes.holds.filtered(index);
volumes.integrated_from = 1 - index;
}
let mut pass = ctx
.encoder
.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("volumetric fog integration"),
timestamp_writes: ctx.timing.and_then(|t| t.compute_pass("fog integration")),
});
pass.set_pipeline(&pipelines.integrate);
pass.set_bind_group(1, volumes.integrate_group(volumes.integrated_from), &[]);
pass.dispatch_workgroups(x.div_ceil(INTEGRATE_GROUP), y.div_ceil(INTEGRATE_GROUP), 1);
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests;
pub(crate) mod volume_froxels;
mod volumes;