use crcbl_hal::{
BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
BufferUsage, ComputePipelineHandle, Device, HalError, ImageViewHandle, ImageViewType,
MemoryLocation, PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, SampleType,
ShaderStages, check_portable_storage_buffers,
};
use crcbl_shaders::probe::ProbeVolume;
use crcbl_shaders::probe_gather::{
GATHER_PARAMS_SIZE, GATHER_WORKGROUP_SIZE, GatherParams, PRODUCER_STRIDE, PunctualProducer,
};
use crate::draw_gen::{bound, compute_pipeline, storage, uniform};
use crate::graph::{BufferId, ImageId, RenderGraph};
use crate::ssao::cached_group;
const POSITION_STRIDE: u64 = 16;
const PRODUCER_ROWS: usize = crate::shadow::LIGHT_TILES;
#[derive(Clone, Copy, Debug)]
pub(crate) struct ProbeGatherDesc<'a> {
pub(crate) label: Option<&'a str>,
pub(crate) volume: ProbeVolume,
pub(crate) probes: &'a [BufferHandle],
}
#[derive(Debug)]
pub(crate) struct ProbeGather {
layout: BindGroupLayoutHandle,
pipeline_layout: PipelineLayoutHandle,
pipeline: ComputePipelineHandle,
params: Vec<BufferHandle>,
probes: Vec<BufferHandle>,
positions: BufferHandle,
producers: Vec<BufferHandle>,
groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
rows: u32,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct RsmTargets {
pub(crate) albedo: ImageId,
pub(crate) normal: ImageId,
pub(crate) world: ImageId,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct RsmImages {
pub(crate) sun: RsmTargets,
pub(crate) punctual: RsmTargets,
}
impl ProbeGather {
pub(crate) const PASSES: u32 = 1;
pub(crate) fn new(device: &dyn Device, desc: &ProbeGatherDesc<'_>) -> Result<Self, HalError> {
let rows = desc.volume.total();
if desc.probes.is_empty() || rows == 0 {
return Err(HalError::InvalidDescriptor(
"a probe gather needs at least one frame in flight and one probe".to_string(),
));
}
let label = desc.label.unwrap_or("probe gather");
let mut rollback = Rollback::default();
let result = Self::build(device, desc, label, rows, &mut rollback);
if result.is_err() {
rollback.run(device);
}
result
}
fn build(
device: &dyn Device,
desc: &ProbeGatherDesc<'_>,
label: &str,
rows: u32,
rollback: &mut Rollback,
) -> Result<Self, HalError> {
let sampled = |binding: u32, view_type: ImageViewType| BindGroupLayoutEntry {
binding,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::SampledImage {
view_type,
sample_type: SampleType::UnfilterableFloat,
},
count: 1,
flags: BindingFlags::empty(),
};
let entries = [
uniform(0),
storage(1, true, size_of::<[f32; 4]>() as u32),
sampled(2, ImageViewType::D2Array),
sampled(3, ImageViewType::D2),
sampled(4, ImageViewType::D2),
sampled(5, ImageViewType::D2),
storage(6, false, size_of::<[f32; 4]>() as u32),
sampled(7, ImageViewType::D2),
sampled(8, ImageViewType::D2),
sampled(9, ImageViewType::D2),
storage(
10,
true,
crcbl_shaders::probe_gather::PRODUCER_STRIDE as u32,
),
];
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::PROBE_GATHER,
pipeline_layout,
GATHER_WORKGROUP_SIZE,
)?;
rollback.pipelines.push(pipeline);
let positions = device.create_buffer(&BufferDesc {
label: Some(&format!("{label} positions")),
size: u64::from(rows) * POSITION_STRIDE,
usage: BufferUsage::STORAGE,
memory: MemoryLocation::HostUpload,
})?;
rollback.buffers.push(positions);
device.write_buffer(positions, 0, &position_table(&desc.volume))?;
let mut params = Vec::with_capacity(desc.probes.len());
let mut producers = Vec::with_capacity(desc.probes.len());
for frame in 0..desc.probes.len() {
let block = device.create_buffer(&BufferDesc {
label: Some(&format!("{label} params {frame}")),
size: GATHER_PARAMS_SIZE as u64,
usage: BufferUsage::UNIFORM,
memory: MemoryLocation::HostUpload,
})?;
rollback.buffers.push(block);
params.push(block);
let table = device.create_buffer(&BufferDesc {
label: Some(&format!("{label} producers {frame}")),
size: (PRODUCER_ROWS * PRODUCER_STRIDE) as u64,
usage: BufferUsage::STORAGE,
memory: MemoryLocation::HostUpload,
})?;
rollback.buffers.push(table);
producers.push(table);
}
Ok(Self {
layout,
pipeline_layout,
pipeline,
params,
probes: desc.probes.to_vec(),
positions,
producers,
groups: vec![None; desc.probes.len()],
rows,
})
}
pub(crate) fn begin_frame(
&self,
device: &dyn Device,
frame: usize,
sun_color: [f32; 3],
texel_area: f32,
producers: &[PunctualProducer],
) -> Result<(), HalError> {
let producers = &producers[..producers.len().min(PRODUCER_ROWS)];
let params = GatherParams {
sun_color,
texel_area,
rsm_side: crcbl_shaders::probe_gather::RSM_SIDE,
probes: self.rows,
producers: u32::try_from(producers.len())
.unwrap_or_else(|_| unreachable!("bounded by the atlas's light tiles")),
};
device.write_buffer(self.params[frame], 0, ¶ms.to_bytes())?;
let mut bytes = Vec::with_capacity(producers.len() * PRODUCER_STRIDE);
for producer in producers {
bytes.extend_from_slice(&producer.to_bytes());
}
if bytes.is_empty() {
return Ok(());
}
device.write_buffer(self.producers[frame], 0, &bytes)
}
pub(crate) fn add_pass<'a>(
&'a mut self,
graph: &mut RenderGraph<'a>,
frame: usize,
images: RsmImages,
visibility: ImageViewHandle,
table: BufferId,
) {
let pipeline = self.pipeline;
let pipeline_layout = self.pipeline_layout;
let layout = self.layout;
let params = self.params[frame];
let positions = self.positions;
let rows = self.rows;
let probes = self.probes[frame];
let producers = self.producers[frame];
let cached = &mut self.groups[frame];
graph
.add_compute_pass("probe-gather")
.read_image(images.sun.albedo)
.read_image(images.sun.normal)
.read_image(images.sun.world)
.read_image(images.punctual.albedo)
.read_image(images.punctual.normal)
.read_image(images.punctual.world)
.use_buffer(table, ResourceState::ShaderReadWrite)
.execute(move |ctx| {
let albedo = ctx.image_view(images.sun.albedo);
let normal = ctx.image_view(images.sun.normal);
let world = ctx.image_view(images.sun.world);
let punctual_albedo = ctx.image_view(images.punctual.albedo);
let punctual_normal = ctx.image_view(images.punctual.normal);
let punctual_world = ctx.image_view(images.punctual.world);
let device = ctx.device();
let entries = [
bound(0, params),
bound(1, positions),
BindGroupEntry {
binding: 2,
array_index: 0,
resource: BindingResource::ImageView(visibility),
},
BindGroupEntry {
binding: 3,
array_index: 0,
resource: BindingResource::ImageView(albedo),
},
BindGroupEntry {
binding: 4,
array_index: 0,
resource: BindingResource::ImageView(normal),
},
BindGroupEntry {
binding: 5,
array_index: 0,
resource: BindingResource::ImageView(world),
},
bound(6, probes),
BindGroupEntry {
binding: 7,
array_index: 0,
resource: BindingResource::ImageView(punctual_albedo),
},
BindGroupEntry {
binding: 8,
array_index: 0,
resource: BindingResource::ImageView(punctual_normal),
},
BindGroupEntry {
binding: 9,
array_index: 0,
resource: BindingResource::ImageView(punctual_world),
},
bound(10, producers),
];
let Some(group) = cached_group(
cached,
device,
&[
(2, visibility),
(3, albedo),
(4, normal),
(5, world),
(7, punctual_albedo),
(8, punctual_normal),
(9, punctual_world),
],
"probe gather",
layout,
&entries,
) else {
return;
};
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(pipeline);
encoder.bind_group(0, group, &[], pipeline_layout);
encoder.dispatch(rows, 1, 1);
});
}
pub(crate) fn rewrite_positions(
&self,
device: &dyn Device,
volume: &ProbeVolume,
) -> Result<(), HalError> {
device.write_buffer(self.positions, 0, &position_table(volume))
}
pub(crate) fn destroy(self, device: &dyn Device) {
device.destroy_compute_pipeline(self.pipeline);
device.destroy_pipeline_layout(self.pipeline_layout);
for (_, group) in self.groups.into_iter().flatten() {
device.destroy_bind_group(group);
}
device.destroy_bind_group_layout(self.layout);
device.destroy_buffer(self.positions);
for buffer in self.params.into_iter().chain(self.producers) {
device.destroy_buffer(buffer);
}
}
}
fn position_table(volume: &ProbeVolume) -> Vec<u8> {
let rows = volume.total() as usize;
let mut bytes = vec![0u8; rows * POSITION_STRIDE as usize];
for level in 0..volume.level_count() {
for z in 0..volume.counts[2] {
for y in 0..volume.counts[1] {
for x in 0..volume.counts[0] {
let cell = [x, y, z];
let at = volume.row(level, cell) as usize * POSITION_STRIDE as usize;
let Some(slot) = bytes.get_mut(at..at + 3 * size_of::<f32>()) else {
continue;
};
for (lane, value) in volume.position(level, cell).into_iter().enumerate() {
slot[lane * 4..lane * 4 + 4].copy_from_slice(&value.to_le_bytes());
}
}
}
}
}
bytes
}
#[derive(Default)]
struct Rollback {
pipelines: Vec<ComputePipelineHandle>,
pipeline_layouts: Vec<PipelineLayoutHandle>,
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 layout in self.layouts {
device.destroy_bind_group_layout(layout);
}
for buffer in self.buffers {
device.destroy_buffer(buffer);
}
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crcbl_hal::null::{NullInstance, Recorder};
use crcbl_hal::{DeviceDesc, Instance, QueueKind};
fn volume() -> ProbeVolume {
ProbeVolume {
origin: [-1.0, 0.5, 2.0],
inv_spacing: [0.5, 0.25, 1.0],
counts: [2, 3, 4],
levels: 2,
steps: crcbl_shaders::probe::ProbeSteps::default(),
}
}
fn producer() -> PunctualProducer {
PunctualProducer {
position: [1.0, 2.0, 3.0],
radius: 4.0,
color: [0.5, 0.25, 0.125],
cos_outer: 0.5,
axis: [0.0, -1.0, 0.0],
cos_inner: 0.9,
origin: [16, 32],
side: 16,
kind: crcbl_shaders::light::KIND_SPOT,
}
}
fn read(bytes: &[u8], row: usize) -> [f32; 3] {
let at = row * POSITION_STRIDE as usize;
let mut out = [0.0f32; 3];
for (axis, value) in out.iter_mut().enumerate() {
let start = at + axis * 4;
*value = f32::from_le_bytes(
bytes[start..start + 4]
.try_into()
.expect("four bytes of a float"),
);
}
out
}
#[test]
fn a_position_table_walks_the_volume_in_row_order() {
let mut scrolled = volume();
scrolled.steps[0] = [1, -1, 2];
scrolled.steps[1] = [0, 1, -3];
for volume in [volume(), scrolled] {
let bytes = position_table(&volume);
assert_eq!(
bytes.len(),
volume.total() as usize * POSITION_STRIDE as usize
);
for level in 0..volume.level_count() {
for z in 0..volume.counts[2] {
for y in 0..volume.counts[1] {
for x in 0..volume.counts[0] {
let row = volume.row(level, [x, y, z]) as usize;
assert_eq!(
read(&bytes, row),
volume.position(level, [x, y, z]),
"row {row} is not probe ({x}, {y}, {z}) of level {level}"
);
}
}
}
}
}
let volume = volume();
let bytes = position_table(&volume);
assert_ne!(read(&bytes, 1), read(&bytes, 0));
}
#[test]
fn a_gather_with_no_probes_is_refused() {
let recorder = Recorder::new();
let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
let adapter = instance.adapters().remove(0);
let device = instance
.create_device(&DeviceDesc::for_adapter(adapter.id))
.expect("the null backend always opens");
let queue = device.queue(QueueKind::Graphics).expect("always present");
let table = crate::probe::ProbeTable::new(
device.as_ref(),
queue,
&crate::probe::ProbeTableDesc {
label: Some("test"),
capacity: 1,
frames: 1,
},
)
.expect("the null backend accepts every descriptor");
let before = recorder.total_live_objects();
let error = ProbeGather::new(
device.as_ref(),
&ProbeGatherDesc {
label: Some("test"),
volume: ProbeVolume::default(),
probes: &[table.buffer(0)],
},
)
.expect_err("a volume of no probes is a dispatch of no workgroups");
assert!(
matches!(&error, HalError::InvalidDescriptor(message)
if message.contains("one probe")),
"got: {error:?}"
);
assert_eq!(
recorder.total_live_objects(),
before,
"a refusal creates nothing"
);
table.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_gather_leaks_nothing() {
let recorder = Recorder::new();
let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
let adapter = instance.adapters().remove(0);
let device = instance
.create_device(&DeviceDesc::for_adapter(adapter.id))
.expect("the null backend always opens");
let queue = device.queue(QueueKind::Graphics).expect("always present");
let volume = volume();
let table = crate::probe::ProbeTable::new(
device.as_ref(),
queue,
&crate::probe::ProbeTableDesc {
label: Some("test"),
capacity: volume.total(),
frames: 2,
},
)
.expect("the null backend accepts every descriptor");
let before = recorder.total_live_objects();
let gather = ProbeGather::new(
device.as_ref(),
&ProbeGatherDesc {
label: Some("test"),
volume,
probes: &[table.buffer(0), table.buffer(1)],
},
)
.expect("the null backend accepts every descriptor");
assert!(recorder.total_live_objects() > before);
gather
.begin_frame(device.as_ref(), 0, [1.0, 1.0, 1.0], 0.25, &[producer()])
.expect("a host-upload write always lands");
gather.destroy(device.as_ref());
assert_eq!(recorder.total_live_objects(), before);
table.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_producer_table_is_bounded_by_the_atlas_s_light_tiles() {
let recorder = Recorder::new();
let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
let adapter = instance.adapters().remove(0);
let device = instance
.create_device(&DeviceDesc::for_adapter(adapter.id))
.expect("the null backend always opens");
let queue = device.queue(QueueKind::Graphics).expect("always present");
let volume = volume();
let table = crate::probe::ProbeTable::new(
device.as_ref(),
queue,
&crate::probe::ProbeTableDesc {
label: Some("test"),
capacity: volume.total(),
frames: 1,
},
)
.expect("the null backend accepts every descriptor");
let gather = ProbeGather::new(
device.as_ref(),
&ProbeGatherDesc {
label: Some("test"),
volume,
probes: &[table.buffer(0)],
},
)
.expect("the null backend accepts every descriptor");
let too_many = vec![producer(); PRODUCER_ROWS + 3];
gather
.begin_frame(device.as_ref(), 0, [1.0; 3], 0.25, &too_many)
.expect("the table takes the rows it has room for and no more");
gather.destroy(device.as_ref());
table.destroy(device.as_ref());
recorder.assert_valid();
}
}