use crcbl_hal::{
BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
BufferUsage, ClearValue, ColorTargetState, ComputePipelineHandle, Device, Format,
GraphicsPipelineHandle, HalError, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, SampleType, SamplerHandle,
ShaderStages, StoreOp, check_portable_storage_buffers,
};
use crcbl_shaders::sky::{ATMOSPHERE_OFF, ATMOSPHERE_ON};
use crcbl_shaders::volumetric::{
FROXEL_STRIDE, LIGHTING_STRIDE, LOCAL_COLUMN_OFF, LOCAL_COLUMN_ON, PARAMS_SIZE,
VolumetricParams, WORKGROUP_SIZE,
};
use crcbl_shaders::{VOLUMETRIC, VOLUMETRIC_COMPOSITE};
use crate::camera::{DirectionalLight, Fog};
use crate::draw_gen::{UINT_STRIDE, bound, compute_pipeline_entry, storage, uniform};
use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
use crate::light_grid::{FrameView, Grid, LightGrid};
use crate::shadow::{self, Cascades};
use crate::ssao::cached_group;
const FULLSCREEN_VERTICES: u32 = 3;
#[derive(Clone, Copy, Debug)]
pub(crate) struct VolumetricImages {
pub(crate) depth: ImageId,
pub(crate) color: ImageId,
pub(crate) composited: ImageId,
pub(crate) shadow_atlas: ImageId,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct VolumetricReads {
pub(crate) light_grid: BufferId,
pub(crate) local: bool,
pub(crate) aerial: BufferHandle,
}
#[derive(Clone, Copy, Debug)]
pub struct FroxelBuffers {
pub params: BufferHandle,
pub froxels: BufferHandle,
pub lighting: BufferHandle,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Medium<'a> {
pub(crate) fog: Fog,
pub(crate) sun: &'a DirectionalLight,
pub(crate) cascades: &'a Cascades,
pub(crate) light_view_proj: &'a [[f32; 16]; shadow::LIGHT_TILES],
pub(crate) atlas_rects: &'a [[f32; 4]; shadow::TILES],
pub(crate) local: bool,
pub(crate) aerial: Option<[f32; 3]>,
}
#[derive(Debug)]
pub(crate) struct Volumetric {
params: Vec<BufferHandle>,
froxels: Vec<BufferHandle>,
lighting: Vec<BufferHandle>,
compute_layout: BindGroupLayoutHandle,
compute_pipeline_layout: PipelineLayoutHandle,
scatter: ComputePipelineHandle,
integrate: ComputePipelineHandle,
compute_groups: Vec<BindGroupHandle>,
composite_layout: BindGroupLayoutHandle,
composite_pipeline_layout: PipelineLayoutHandle,
composite_pipeline: GraphicsPipelineHandle,
composite_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
}
impl Volumetric {
pub(crate) const PASSES: u32 = Self::COLUMN_PASSES + Self::COMPOSITE_PASSES;
pub(crate) const COLUMN_PASSES: u32 = 2;
pub(crate) const COMPOSITE_PASSES: u32 = 1;
pub(crate) fn new(
device: &dyn Device,
frames: usize,
froxels: u32,
shadow_atlas: ImageViewHandle,
shadow_sampler: SamplerHandle,
lights: &LightGrid,
build_fullscreen: impl Fn(
&dyn Device,
&str,
&crcbl_shaders::Shader,
PipelineLayoutHandle,
&[ColorTargetState],
) -> Result<GraphicsPipelineHandle, HalError>,
) -> Result<Self, HalError> {
if frames == 0 || froxels == 0 {
return Err(HalError::InvalidDescriptor(
"a froxel volume needs at least one frame in flight and one froxel".to_string(),
));
}
let compute_entries = [
uniform(0),
storage(1, false, crcbl_shaders::volumetric::FROXEL_STRIDE as u32),
BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Depth,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 3,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::Sampler { comparison: true },
count: 1,
flags: BindingFlags::empty(),
},
storage(4, false, crcbl_shaders::volumetric::LIGHTING_STRIDE as u32),
storage(5, true, crcbl_shaders::light::LIGHT_STRIDE as u32),
storage(6, true, UINT_STRIDE),
];
let compute_desc = BindGroupLayoutDesc {
label: Some("volumetric"),
entries: &compute_entries,
};
check_portable_storage_buffers(Some("volumetric"), &[&compute_desc])?;
let compute_layout = device.create_bind_group_layout(&compute_desc)?;
let compute_set_layouts = [compute_layout];
let compute_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("volumetric"),
bind_group_layouts: &compute_set_layouts,
push_constants: None,
})?;
let scatter = compute_pipeline_entry(
device,
"volumetric scatter",
&VOLUMETRIC,
"scatterMain",
compute_pipeline_layout,
WORKGROUP_SIZE,
)?;
let integrate = compute_pipeline_entry(
device,
"volumetric integrate",
&VOLUMETRIC,
"integrateMain",
compute_pipeline_layout,
WORKGROUP_SIZE,
)?;
let composite_entries = [
BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::UniformBuffer { dynamic: false },
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Depth,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 3,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: crcbl_shaders::volumetric::FROXEL_STRIDE as u32,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 4,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: crcbl_shaders::volumetric::LIGHTING_STRIDE as u32,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 5,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: crcbl_shaders::atmosphere::AERIAL_VIEW_ROW_BYTES as u32,
},
count: 1,
flags: BindingFlags::empty(),
},
];
let composite_desc = BindGroupLayoutDesc {
label: Some("volumetric composite"),
entries: &composite_entries,
};
check_portable_storage_buffers(Some("volumetric composite"), &[&composite_desc])?;
let composite_layout = device.create_bind_group_layout(&composite_desc)?;
let composite_set_layouts = [composite_layout];
let composite_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("volumetric composite"),
bind_group_layouts: &composite_set_layouts,
push_constants: None,
})?;
let targets = [ColorTargetState::opaque(Format::Rgba16Float)];
let composite_pipeline = build_fullscreen(
device,
"volumetric composite",
&VOLUMETRIC_COMPOSITE,
composite_pipeline_layout,
&targets,
)?;
let mut params = Vec::with_capacity(frames);
let mut volumes = Vec::with_capacity(frames);
let mut lighting = Vec::with_capacity(frames);
let mut compute_groups = Vec::with_capacity(frames);
for frame in 0..frames {
let block = device.create_buffer(&BufferDesc {
label: Some(&format!("volumetric params {frame}")),
size: PARAMS_SIZE as u64,
usage: BufferUsage::UNIFORM | BufferUsage::TRANSFER_SRC,
memory: MemoryLocation::HostUpload,
})?;
let volume = device.create_buffer(&BufferDesc {
label: Some(&format!("volumetric froxels {frame}")),
size: u64::from(froxels) * FROXEL_STRIDE as u64,
usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
memory: MemoryLocation::DeviceLocal,
})?;
let seen = device.create_buffer(&BufferDesc {
label: Some(&format!("volumetric lighting {frame}")),
size: u64::from(froxels) * LIGHTING_STRIDE as u64,
usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
memory: MemoryLocation::DeviceLocal,
})?;
let group = device.create_bind_group(&BindGroupDesc {
label: Some(&format!("volumetric {frame}")),
layout: compute_layout,
entries: &[
bound(0, block),
bound(1, volume),
BindGroupEntry {
binding: 2,
array_index: 0,
resource: BindingResource::ImageView(shadow_atlas),
},
BindGroupEntry {
binding: 3,
array_index: 0,
resource: BindingResource::Sampler(shadow_sampler),
},
bound(4, seen),
bound(5, lights.lights(frame)),
bound(6, lights.grid(frame)),
],
variable_count: None,
})?;
params.push(block);
volumes.push(volume);
lighting.push(seen);
compute_groups.push(group);
}
Ok(Self {
params,
froxels: volumes,
lighting,
compute_layout,
compute_pipeline_layout,
scatter,
integrate,
compute_groups,
composite_layout,
composite_pipeline_layout,
composite_pipeline,
composite_groups: vec![None; frames],
})
}
pub(crate) fn begin_frame(
&self,
device: &dyn Device,
frame: usize,
grid: Grid,
view: FrameView,
medium: Medium<'_>,
) -> Result<(), HalError> {
let Medium {
fog,
sun,
cascades,
light_view_proj,
atlas_rects,
local,
aerial,
} = medium;
let columns = view.view_projection.to_cols_array();
let depth_row = [columns[3], columns[7], columns[11], columns[15]];
let mut shadow_view_proj = [[0.0f32; 16]; shadow::CASCADES];
for (matrix, cascade) in shadow_view_proj.iter_mut().zip(&cascades.view_proj) {
*matrix = cascade.to_cols_array();
}
device.write_buffer(
self.params[frame],
0,
&VolumetricParams {
inverse_view_proj: view.view_projection.inverse().to_cols_array(),
eye: view.eye.extend(1.0).to_array(),
depth_row,
fog_params: [
fog.density,
fog.falloff,
fog.reference_height,
if local {
LOCAL_COLUMN_ON
} else {
LOCAL_COLUMN_OFF
},
],
fog_color: fog.color.extend(0.0).to_array(),
sun_direction: sun
.direction
.normalize_or_zero()
.extend(fog.anisotropy)
.to_array(),
sun_radiance: (sun.color * fog.sun_scattering)
.extend(fog.light_scattering)
.to_array(),
shadow_view_proj,
cascade_far: cascades.far,
shadow_params: Cascades::params(),
grid_x: grid.x,
grid_y: grid.y,
slices: grid.slices,
tile_pixels: grid.tile_pixels,
viewport_x: view.extent.0.max(1),
viewport_y: view.extent.1.max(1),
froxel_count: grid.froxels(),
light_view_proj: *light_view_proj,
shadow_atlas_rect: *atlas_rects,
aerial_params: match aerial {
Some(sun) => [sun[0], sun[1], sun[2], ATMOSPHERE_ON],
None => [0.0, 0.0, 0.0, ATMOSPHERE_OFF],
},
}
.to_bytes(),
)
}
pub(crate) fn buffers(&self, frame: usize) -> FroxelBuffers {
FroxelBuffers {
params: self.params[frame],
froxels: self.froxels[frame],
lighting: self.lighting[frame],
}
}
pub(crate) fn add_passes<'a>(
&'a mut self,
graph: &mut RenderGraph<'a>,
frame: usize,
grid: Grid,
images: VolumetricImages,
reads: VolumetricReads,
) -> (BufferId, BufferId) {
let VolumetricReads {
light_grid,
local,
aerial,
} = reads;
let VolumetricImages {
depth,
color,
composited,
shadow_atlas,
} = images;
let volume = graph.import_buffer(
"volumetric-froxels",
ImportedBuffer {
buffer: self.froxels[frame],
initial: ResourceState::ShaderRead,
final_state: ResourceState::ShaderRead,
},
);
let seen = graph.import_buffer(
"volumetric-lighting",
ImportedBuffer {
buffer: self.lighting[frame],
initial: ResourceState::ShaderRead,
final_state: ResourceState::ShaderRead,
},
);
let compute_layout = self.compute_pipeline_layout;
let compute_group = self.compute_groups[frame];
let scatter = self.scatter;
let integrate = self.integrate;
if local {
let froxel_groups = grid.froxels().div_ceil(WORKGROUP_SIZE);
graph
.add_compute_pass("volumetric-scatter")
.use_buffer(volume, ResourceState::ShaderReadWrite)
.use_buffer(seen, ResourceState::ShaderReadWrite)
.read_image(shadow_atlas)
.read_buffer(light_grid)
.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(scatter);
encoder.bind_group(0, compute_group, &[], compute_layout);
encoder.dispatch(froxel_groups, 1, 1);
});
let tile_groups = grid
.x
.max(1)
.saturating_mul(grid.y.max(1))
.div_ceil(WORKGROUP_SIZE);
graph
.add_compute_pass("volumetric-integrate")
.use_buffer(volume, ResourceState::ShaderReadWrite)
.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(integrate);
encoder.bind_group(0, compute_group, &[], compute_layout);
encoder.dispatch(tile_groups, 1, 1);
});
}
let pipeline = self.composite_pipeline;
let pipeline_layout = self.composite_pipeline_layout;
let layout = self.composite_layout;
let params = self.params[frame];
let froxels = self.froxels[frame];
let lighting = self.lighting[frame];
let cached = &mut self.composite_groups[frame];
graph
.add_render_pass("volumetric-composite")
.color(
composited,
LoadOp::DontCare,
StoreOp::Store,
ClearValue::default(),
)
.read_image(color)
.read_image(depth)
.read_buffer(volume)
.read_buffer(seen)
.execute(move |ctx| {
let color_view = ctx.image_view(color);
let depth_view = ctx.image_view(depth);
let device = ctx.device();
let entries = [
BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::whole_buffer(params),
},
BindGroupEntry {
binding: 1,
array_index: 0,
resource: BindingResource::ImageView(depth_view),
},
BindGroupEntry {
binding: 2,
array_index: 0,
resource: BindingResource::ImageView(color_view),
},
BindGroupEntry {
binding: 3,
array_index: 0,
resource: BindingResource::whole_buffer(froxels),
},
BindGroupEntry {
binding: 4,
array_index: 0,
resource: BindingResource::whole_buffer(lighting),
},
BindGroupEntry {
binding: 5,
array_index: 0,
resource: BindingResource::whole_buffer(aerial),
},
];
let Some(group) = cached_group(
cached,
device,
&[(1, depth_view), (2, color_view)],
"volumetric composite",
layout,
&entries,
) else {
return;
};
let encoder = ctx.encoder();
encoder.bind_graphics_pipeline(pipeline);
encoder.bind_group(0, group, &[], pipeline_layout);
encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
});
(volume, seen)
}
pub(crate) fn destroy(self, device: &dyn Device) {
for cached in self.composite_groups.into_iter().flatten() {
device.destroy_bind_group(cached.1);
}
device.destroy_graphics_pipeline(self.composite_pipeline);
device.destroy_pipeline_layout(self.composite_pipeline_layout);
device.destroy_bind_group_layout(self.composite_layout);
device.destroy_compute_pipeline(self.integrate);
device.destroy_compute_pipeline(self.scatter);
device.destroy_pipeline_layout(self.compute_pipeline_layout);
for group in self.compute_groups {
device.destroy_bind_group(group);
}
device.destroy_bind_group_layout(self.compute_layout);
for buffer in self
.params
.into_iter()
.chain(self.froxels)
.chain(self.lighting)
{
device.destroy_buffer(buffer);
}
}
}