use crcbl_hal::{
BindGroupDesc, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutHandle, BufferDesc,
BufferHandle, BufferUsage, ComputePipelineHandle, Device, HalError, MemoryLocation,
PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, check_portable_storage_buffers,
};
use crcbl_shaders::light::{
self, CLUSTER_DEPTH_SLICES, CLUSTER_PARAMS_SIZE, CLUSTER_STRIDE, CLUSTER_TILE_PIXELS,
CLUSTER_WORKGROUP_SIZE, GpuLight, LIGHT_STRIDE,
};
use glam::{Mat4, Vec3};
use crate::draw_gen::{UINT_STRIDE, bound, compute_pipeline, storage, uniform};
use crate::graph::{BufferId, ImportedBuffer, RenderGraph};
pub const FROXEL_CAPACITY: u32 = 64 * 1024;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameView {
pub extent: (u32, u32),
pub view_projection: Mat4,
pub eye: Vec3,
pub perspective: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Grid {
pub x: u32,
pub y: u32,
pub slices: u32,
pub tile_pixels: u32,
}
impl Grid {
#[must_use]
pub fn for_frame(extent: (u32, u32), perspective: bool, froxels: u32) -> Self {
let tiles = |tile: u32| {
(
extent.0.max(1).div_ceil(tile),
extent.1.max(1).div_ceil(tile),
)
};
let mut tile_pixels = CLUSTER_TILE_PIXELS.max(1);
let (mut x, mut y) = tiles(tile_pixels);
while x.saturating_mul(y) > froxels.max(1) {
tile_pixels = tile_pixels.saturating_mul(2);
(x, y) = tiles(tile_pixels);
}
let wanted = if perspective { CLUSTER_DEPTH_SLICES } else { 1 };
let slices = (froxels.max(1) / (x * y)).min(wanted).max(1);
Self {
x,
y,
slices,
tile_pixels,
}
}
#[must_use]
pub const fn froxels(&self) -> u32 {
self.x * self.y * self.slices
}
#[must_use]
pub const fn to_frame_block(&self) -> [u32; 4] {
[self.x, self.y, self.slices, self.tile_pixels]
}
}
#[derive(Clone, Copy, Debug)]
pub struct LightGridDesc<'a> {
pub label: Option<&'a str>,
pub frames: usize,
pub lights: u32,
pub froxels: u32,
pub stats: &'a [BufferHandle],
}
#[derive(Debug)]
pub struct LightGrid {
lights: Vec<BufferHandle>,
grid: Vec<BufferHandle>,
params: Vec<BufferHandle>,
groups: Vec<BindGroupHandle>,
layout: BindGroupLayoutHandle,
pipeline_layout: PipelineLayoutHandle,
pipeline: ComputePipelineHandle,
capacity: u32,
froxels: u32,
}
impl LightGrid {
pub fn new(device: &dyn Device, desc: &LightGridDesc<'_>) -> Result<Self, HalError> {
if desc.frames == 0 || desc.lights == 0 || desc.froxels == 0 {
return Err(HalError::InvalidDescriptor(
"a light grid needs at least one frame in flight, one light row and one froxel"
.to_string(),
));
}
if desc.stats.len() < desc.frames {
return Err(HalError::InvalidDescriptor(format!(
"a light grid over {} frames needs {} statistics buffers, got {}",
desc.frames,
desc.frames,
desc.stats.len()
)));
}
let label = desc.label.unwrap_or("lights");
let mut rollback = Rollback::default();
let result = Self::build(device, desc, label, &mut rollback);
if result.is_err() {
rollback.run(device);
}
result
}
fn build(
device: &dyn Device,
desc: &LightGridDesc<'_>,
label: &str,
rollback: &mut Rollback,
) -> Result<Self, HalError> {
let entries = [
uniform(0),
storage(1, true, crcbl_shaders::light::LIGHT_STRIDE as u32),
storage(2, false, UINT_STRIDE),
storage(3, false, UINT_STRIDE),
];
let layout_desc = BindGroupLayoutDesc {
label: Some(label),
entries: &entries,
};
check_portable_storage_buffers(Some(label), &[&layout_desc])?;
let layout = device.create_bind_group_layout(&layout_desc)?;
rollback.layouts.push(layout);
let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some(label),
bind_group_layouts: &[layout],
push_constants: None,
})?;
rollback.pipeline_layouts.push(pipeline_layout);
let pipeline = compute_pipeline(
device,
label,
&crcbl_shaders::LIGHT_CLUSTER,
pipeline_layout,
CLUSTER_WORKGROUP_SIZE,
)?;
rollback.pipelines.push(pipeline);
let mut lights = Vec::with_capacity(desc.frames);
let mut grid = Vec::with_capacity(desc.frames);
let mut params = Vec::with_capacity(desc.frames);
let mut groups = Vec::with_capacity(desc.frames);
for frame in 0..desc.frames {
let mut buffer = |name: &str, size: u64, usage, memory| {
let handle = device.create_buffer(&BufferDesc {
label: Some(&format!("{label} {name} {frame}")),
size,
usage,
memory,
})?;
rollback.buffers.push(handle);
Ok::<_, HalError>(handle)
};
let list = buffer(
"list",
u64::from(desc.lights) * LIGHT_STRIDE as u64,
BufferUsage::STORAGE,
MemoryLocation::HostUpload,
)?;
let froxels = buffer(
"grid",
u64::from(desc.froxels) * u64::from(CLUSTER_STRIDE) * 4,
BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
MemoryLocation::DeviceLocal,
)?;
let block = buffer(
"params",
CLUSTER_PARAMS_SIZE as u64,
BufferUsage::UNIFORM,
MemoryLocation::HostUpload,
)?;
let group = device.create_bind_group(&BindGroupDesc {
label: Some(&format!("{label} {frame}")),
layout,
entries: &[
bound(0, block),
bound(1, list),
bound(2, froxels),
bound(3, desc.stats[frame]),
],
variable_count: None,
})?;
rollback.groups.push(group);
lights.push(list);
grid.push(froxels);
params.push(block);
groups.push(group);
}
Ok(Self {
lights,
grid,
params,
groups,
layout,
pipeline_layout,
pipeline,
capacity: desc.lights,
froxels: desc.froxels,
})
}
#[must_use]
pub const fn capacity(&self) -> u32 {
self.capacity
}
#[must_use]
pub const fn froxel_capacity(&self) -> u32 {
self.froxels
}
#[must_use]
pub fn lights(&self, frame: usize) -> BufferHandle {
self.lights[frame]
}
#[must_use]
pub fn grid(&self, frame: usize) -> BufferHandle {
self.grid[frame]
}
pub fn begin_frame(
&self,
device: &dyn Device,
frame: usize,
rows: &[GpuLight],
grid: Grid,
view: FrameView,
) -> Result<(), HalError> {
let count = u32::try_from(rows.len()).unwrap_or(u32::MAX);
if count > self.capacity {
return Err(HalError::InvalidDescriptor(format!(
"{count} lights in a list of {}; raise the renderer's light capacity rather than \
dropping one, which no counter would report",
self.capacity
)));
}
let mut bytes = vec![0u8; rows.len() * LIGHT_STRIDE];
for (slot, row) in rows.iter().enumerate() {
bytes[slot * LIGHT_STRIDE..(slot + 1) * LIGHT_STRIDE].copy_from_slice(&row.to_bytes());
}
if !bytes.is_empty() {
device.write_buffer(self.lights[frame], 0, &bytes)?;
}
let columns = view.view_projection.to_cols_array();
let depth_row = [columns[3], columns[7], columns[11], columns[15]];
device.write_buffer(
self.params[frame],
0,
&light::ClusterParams {
inverse_view_proj: view.view_projection.inverse().to_cols_array(),
eye: view.eye.extend(1.0).to_array(),
depth_row,
grid_x: grid.x,
grid_y: grid.y,
slices: grid.slices,
light_count: count,
viewport_x: view.extent.0.max(1),
viewport_y: view.extent.1.max(1),
perspective: u32::from(view.perspective),
tile_pixels: grid.tile_pixels,
}
.to_bytes(),
)
}
pub const MAX_PASSES: u32 = 1;
pub fn add_pass(
&self,
graph: &mut RenderGraph<'_>,
frame: usize,
stats: BufferId,
grid: Grid,
) -> BufferId {
let froxels = graph.import_buffer(
"light-grid",
ImportedBuffer {
buffer: self.grid[frame],
initial: ResourceState::ShaderRead,
final_state: ResourceState::ShaderRead,
},
);
let pipeline = self.pipeline;
let layout = self.pipeline_layout;
let group = self.groups[frame];
let groups = grid.froxels().div_ceil(CLUSTER_WORKGROUP_SIZE);
graph
.add_compute_pass("light-cluster")
.use_buffer(froxels, ResourceState::ShaderReadWrite)
.use_buffer(stats, ResourceState::ShaderReadWrite)
.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(pipeline);
encoder.bind_group(0, group, &[], layout);
encoder.dispatch(groups, 1, 1);
});
froxels
}
pub fn destroy(self, device: &dyn Device) {
device.destroy_compute_pipeline(self.pipeline);
device.destroy_pipeline_layout(self.pipeline_layout);
for group in self.groups {
device.destroy_bind_group(group);
}
device.destroy_bind_group_layout(self.layout);
for buffer in self.lights.into_iter().chain(self.grid).chain(self.params) {
device.destroy_buffer(buffer);
}
}
}
#[derive(Default)]
struct Rollback {
pipelines: Vec<ComputePipelineHandle>,
pipeline_layouts: Vec<PipelineLayoutHandle>,
groups: Vec<BindGroupHandle>,
layouts: Vec<BindGroupLayoutHandle>,
buffers: Vec<BufferHandle>,
}
impl Rollback {
fn run(self, device: &dyn Device) {
for pipeline in self.pipelines {
device.destroy_compute_pipeline(pipeline);
}
for layout in self.pipeline_layouts {
device.destroy_pipeline_layout(layout);
}
for group in self.groups {
device.destroy_bind_group(group);
}
for layout in self.layouts {
device.destroy_bind_group_layout(layout);
}
for buffer in self.buffers {
device.destroy_buffer(buffer);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_4k_frame_keeps_the_default_tiles_and_every_slice() {
let grid = Grid::for_frame((3840, 2160), true, FROXEL_CAPACITY);
assert_eq!(grid.tile_pixels, CLUSTER_TILE_PIXELS);
assert_eq!(grid.slices, CLUSTER_DEPTH_SLICES);
assert_eq!((grid.x, grid.y), (60, 34));
assert!(
grid.froxels() <= FROXEL_CAPACITY,
"{} froxels in a buffer of {FROXEL_CAPACITY}",
grid.froxels()
);
}
#[test]
fn an_orthographic_frame_gets_one_slice() {
let grid = Grid::for_frame((256, 192), false, FROXEL_CAPACITY);
assert_eq!(grid.slices, 1);
assert_eq!(grid.tile_pixels, CLUSTER_TILE_PIXELS);
assert_eq!((grid.x, grid.y), (4, 3));
}
#[test]
fn a_budget_too_small_for_every_slice_loses_slices_first() {
let grid = Grid::for_frame((256, 192), true, 24);
assert_eq!(grid.tile_pixels, CLUSTER_TILE_PIXELS, "tiles are kept");
assert_eq!((grid.x, grid.y), (4, 3));
assert_eq!(grid.slices, 2);
assert!(grid.froxels() <= 24);
}
#[test]
fn a_frame_too_large_for_the_budget_coarsens_its_tiles_and_still_fits() {
for extent in [(16384u32, 16384u32), (7680, 4320), (100_000, 100_000)] {
let grid = Grid::for_frame(extent, true, FROXEL_CAPACITY);
assert!(
grid.froxels() <= FROXEL_CAPACITY,
"{extent:?} produced {} froxels, over the {FROXEL_CAPACITY} the buffer holds",
grid.froxels()
);
assert!(grid.slices >= 1 && grid.x >= 1 && grid.y >= 1);
assert!(
u64::from(grid.x) * u64::from(grid.tile_pixels) >= u64::from(extent.0),
"the tiles must still cover the frame, or the fragments past them \
read a froxel built for somewhere else"
);
assert!(u64::from(grid.y) * u64::from(grid.tile_pixels) >= u64::from(extent.1));
}
}
#[test]
fn a_zero_extent_is_still_one_froxel() {
let grid = Grid::for_frame((0, 0), true, FROXEL_CAPACITY);
assert!(grid.froxels() >= 1);
assert_eq!((grid.x, grid.y), (1, 1));
}
#[test]
fn the_frame_block_carries_the_four_numbers_in_order() {
let grid = Grid {
x: 3,
y: 5,
slices: 7,
tile_pixels: 11,
};
assert_eq!(grid.to_frame_block(), [3, 5, 7, 11]);
assert_eq!(grid.froxels(), 105);
}
}