use crcbl_hal::{
BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BlendFactor, BlendOp,
BlendState, BufferDesc, BufferHandle, BufferUsage, ClearValue, ColorTargetState, ColorWrites,
Device, FilterMode, Format, GraphicsPipelineHandle, HalError, ImageViewHandle, ImageViewType,
LoadOp, MemoryLocation, PipelineLayoutDesc, PipelineLayoutHandle, SampleType,
SamplerAddressMode, SamplerDesc, SamplerHandle, ShaderStages, StoreOp,
check_portable_storage_buffers,
};
use crcbl_shaders::{BLOOM_COMPOSITE, BLOOM_DOWN, BLOOM_UP, bloom};
use crate::graph::{ImageId, RenderGraph};
use crate::ssao::cached_group;
const FULLSCREEN_VERTICES: u32 = 3;
type GroupCache = Option<(Vec<ImageViewHandle>, BindGroupHandle)>;
pub(crate) const MAX_MIPS: u32 = 6;
pub(crate) const MIN_MIP_EXTENT: u32 = 8;
const CHAIN_FORMAT: Format = Format::Rgba16Float;
pub(crate) fn mips_for(extent: (u32, u32)) -> u32 {
let (mut width, mut height) = extent;
let mut mips = 0;
while mips < MAX_MIPS {
let (next_width, next_height) = (width / 2, height / 2);
if next_width < MIN_MIP_EXTENT || next_height < MIN_MIP_EXTENT {
break;
}
width = next_width;
height = next_height;
mips += 1;
}
mips
}
pub(crate) fn mip_extent(extent: (u32, u32), mip: u32) -> (u32, u32) {
assert!(
mip <= mips_for(extent),
"level {mip} is past the {} this chain has at {extent:?}",
mips_for(extent)
);
let (mut width, mut height) = extent;
for _ in 0..mip {
width /= 2;
height /= 2;
}
(width, height)
}
#[derive(Debug)]
pub(crate) struct Bloom {
sampler: SamplerHandle,
layout: BindGroupLayoutHandle,
pipeline_layout: PipelineLayoutHandle,
down_pipeline: GraphicsPipelineHandle,
up_pipeline: GraphicsPipelineHandle,
composite_layout: BindGroupLayoutHandle,
composite_pipeline_layout: PipelineLayoutHandle,
composite_pipeline: GraphicsPipelineHandle,
uniforms: Vec<BufferHandle>,
down_groups: Vec<Vec<GroupCache>>,
up_groups: Vec<Vec<GroupCache>>,
composite_groups: Vec<GroupCache>,
}
impl Bloom {
pub(crate) const MAX_PASSES: u32 = 2 * MAX_MIPS;
pub(crate) fn passes_for(extent: (u32, u32)) -> u32 {
match mips_for(extent) {
0 => 0,
mips => 2 * mips,
}
}
pub(crate) fn new(
device: &dyn Device,
frames: usize,
build_fullscreen: impl Fn(
&dyn Device,
&str,
&crcbl_shaders::Shader,
PipelineLayoutHandle,
&[ColorTargetState],
) -> Result<GraphicsPipelineHandle, HalError>,
) -> Result<Self, HalError> {
let sampler = device.create_sampler(&SamplerDesc {
label: Some("bloom chain"),
mag_filter: FilterMode::Linear,
min_filter: FilterMode::Linear,
mip_filter: FilterMode::Linear,
address_mode: [SamplerAddressMode::ClampToEdge; 3],
..SamplerDesc::default()
})?;
let entries = [
BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::Sampler { comparison: false },
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::UniformBuffer { dynamic: false },
count: 1,
flags: BindingFlags::empty(),
},
];
let desc = BindGroupLayoutDesc {
label: Some("bloom chain"),
entries: &entries,
};
check_portable_storage_buffers(Some("bloom chain"), &[&desc])?;
let layout = device.create_bind_group_layout(&desc)?;
let set_layouts = [layout];
let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("bloom chain"),
bind_group_layouts: &set_layouts,
push_constants: None,
})?;
let composite_entries = [
BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::Sampler { comparison: false },
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 3,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::UniformBuffer { dynamic: false },
count: 1,
flags: BindingFlags::empty(),
},
];
let composite_desc = BindGroupLayoutDesc {
label: Some("bloom composite"),
entries: &composite_entries,
};
check_portable_storage_buffers(Some("bloom 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("bloom composite"),
bind_group_layouts: &composite_set_layouts,
push_constants: None,
})?;
let opaque = [ColorTargetState::opaque(CHAIN_FORMAT)];
let additive = [ColorTargetState {
format: CHAIN_FORMAT,
blend: Some(BlendState {
color_src: BlendFactor::One,
color_dst: BlendFactor::One,
color_op: BlendOp::Add,
alpha_src: BlendFactor::Zero,
alpha_dst: BlendFactor::One,
alpha_op: BlendOp::Add,
}),
write_mask: ColorWrites::ALL,
}];
let down_pipeline =
build_fullscreen(device, "bloom down", &BLOOM_DOWN, pipeline_layout, &opaque)?;
let up_pipeline =
build_fullscreen(device, "bloom up", &BLOOM_UP, pipeline_layout, &additive)?;
let composite_pipeline = build_fullscreen(
device,
"bloom composite",
&BLOOM_COMPOSITE,
composite_pipeline_layout,
&opaque,
)?;
let mut uniforms = Vec::with_capacity(frames * Self::MAX_PASSES as usize);
for _ in 0..frames * Self::MAX_PASSES as usize {
uniforms.push(device.create_buffer(&BufferDesc {
label: Some("bloom params"),
size: bloom::PARAMS_SIZE as u64,
usage: BufferUsage::UNIFORM,
memory: MemoryLocation::HostUpload,
})?);
}
Ok(Self {
sampler,
layout,
pipeline_layout,
down_pipeline,
up_pipeline,
composite_layout,
composite_pipeline_layout,
composite_pipeline,
uniforms,
down_groups: vec![vec![None; MAX_MIPS as usize]; frames],
up_groups: vec![vec![None; MAX_MIPS as usize]; frames],
composite_groups: vec![None; frames],
})
}
pub(crate) fn begin_frame(
&self,
device: &dyn Device,
frame: usize,
extent: (u32, u32),
) -> Result<(), HalError> {
let mips = mips_for(extent);
for step in 0..Self::passes_for(extent) {
let (source, karis, strength) = if step < mips {
let karis = if step == 0 {
bloom::KARIS_ON
} else {
bloom::KARIS_OFF
};
(step, karis, 0.0)
} else if step < 2 * mips - 1 {
(2 * mips - step, bloom::KARIS_OFF, 0.0)
} else {
(1, bloom::KARIS_OFF, bloom::DEFAULT_STRENGTH)
};
let (width, height) = mip_extent(extent, source);
let params = bloom::BloomParams {
inv_source: [1.0 / width as f32, 1.0 / height as f32],
karis,
strength,
};
device.write_buffer(
self.uniforms[frame * Self::MAX_PASSES as usize + step as usize],
0,
¶ms.to_bytes(),
)?;
}
Ok(())
}
pub(crate) fn add_passes<'a>(
&'a mut self,
graph: &mut RenderGraph<'a>,
frame: usize,
extent: (u32, u32),
scene: ImageId,
mips: &[ImageId],
composited: ImageId,
) {
let count = mips_for(extent);
assert_eq!(
mips.len(),
count as usize,
"the caller created {} chain images for an extent whose chain is {count} levels",
mips.len()
);
assert!(count > 0, "a chain with no levels records no passes");
let base = frame * Self::MAX_PASSES as usize;
let layout = self.layout;
let pipeline_layout = self.pipeline_layout;
let down_pipeline = self.down_pipeline;
let up_pipeline = self.up_pipeline;
let sampler = self.sampler;
let mut down_cache = self.down_groups[frame].iter_mut();
let mut up_cache = self.up_groups[frame].iter_mut();
let composite_cache = &mut self.composite_groups[frame];
for level in 1..=count {
let source = if level == 1 {
scene
} else {
mips[level as usize - 2]
};
let target = mips[level as usize - 1];
let uniforms = self.uniforms[base + level as usize - 1];
let cached = down_cache
.next()
.unwrap_or_else(|| unreachable!("MAX_MIPS slots and at most MAX_MIPS levels"));
graph
.add_render_pass(format!("bloom-down-{level}"))
.color(
target,
LoadOp::DontCare,
StoreOp::Store,
ClearValue::default(),
)
.read_image(source)
.execute(move |ctx| {
let view = ctx.image_view(source);
let device = ctx.device();
let entries = chain_entries(view, sampler, uniforms);
let Some(group) =
cached_group(cached, device, &[(0, view)], "bloom down", layout, &entries)
else {
return;
};
let encoder = ctx.encoder();
encoder.bind_graphics_pipeline(down_pipeline);
encoder.bind_group(0, group, &[], pipeline_layout);
encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
});
}
for level in (1..count).rev() {
let source = mips[level as usize];
let target = mips[level as usize - 1];
let uniforms = self.uniforms[base + (2 * count - 1 - level) as usize];
let cached = up_cache
.next()
.unwrap_or_else(|| unreachable!("MAX_MIPS slots and at most MAX_MIPS-1 steps"));
graph
.add_render_pass(format!("bloom-up-{level}"))
.color(target, LoadOp::Load, StoreOp::Store, ClearValue::default())
.read_image(source)
.execute(move |ctx| {
let view = ctx.image_view(source);
let device = ctx.device();
let entries = chain_entries(view, sampler, uniforms);
let Some(group) =
cached_group(cached, device, &[(0, view)], "bloom up", layout, &entries)
else {
return;
};
let encoder = ctx.encoder();
encoder.bind_graphics_pipeline(up_pipeline);
encoder.bind_group(0, group, &[], pipeline_layout);
encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
});
}
let composite_layout = self.composite_layout;
let composite_pipeline_layout = self.composite_pipeline_layout;
let composite_pipeline = self.composite_pipeline;
let level_one = mips[0];
let uniforms = self.uniforms[base + (2 * count - 1) as usize];
graph
.add_render_pass("bloom-composite")
.color(
composited,
LoadOp::DontCare,
StoreOp::Store,
ClearValue::default(),
)
.read_image(scene)
.read_image(level_one)
.execute(move |ctx| {
let scene_view = ctx.image_view(scene);
let bloom_view = ctx.image_view(level_one);
let device = ctx.device();
let entries = [
BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::ImageView(scene_view),
},
BindGroupEntry {
binding: 1,
array_index: 0,
resource: BindingResource::ImageView(bloom_view),
},
BindGroupEntry {
binding: 2,
array_index: 0,
resource: BindingResource::Sampler(sampler),
},
BindGroupEntry {
binding: 3,
array_index: 0,
resource: BindingResource::whole_buffer(uniforms),
},
];
let Some(group) = cached_group(
composite_cache,
device,
&[(0, scene_view), (1, bloom_view)],
"bloom composite",
composite_layout,
&entries,
) else {
return;
};
let encoder = ctx.encoder();
encoder.bind_graphics_pipeline(composite_pipeline);
encoder.bind_group(0, group, &[], composite_pipeline_layout);
encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
});
}
pub(crate) fn destroy(self, device: &dyn Device) {
for cached in self
.down_groups
.into_iter()
.chain(self.up_groups)
.flatten()
.flatten()
.chain(self.composite_groups.into_iter().flatten())
{
device.destroy_bind_group(cached.1);
}
for buffer in self.uniforms {
device.destroy_buffer(buffer);
}
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_graphics_pipeline(self.up_pipeline);
device.destroy_graphics_pipeline(self.down_pipeline);
device.destroy_pipeline_layout(self.pipeline_layout);
device.destroy_bind_group_layout(self.layout);
device.destroy_sampler(self.sampler);
}
}
fn chain_entries(
view: ImageViewHandle,
sampler: SamplerHandle,
uniforms: BufferHandle,
) -> [BindGroupEntry; 3] {
[
BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::ImageView(view),
},
BindGroupEntry {
binding: 1,
array_index: 0,
resource: BindingResource::Sampler(sampler),
},
BindGroupEntry {
binding: 2,
array_index: 0,
resource: BindingResource::whole_buffer(uniforms),
},
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_chain_stops_before_a_level_falls_under_the_filter_footprint() {
for (extent, expected) in [
((1920, 1080), MAX_MIPS),
((1280, 720), MAX_MIPS),
((256, 192), 4),
((97, 61), 2),
((64, 48), 2),
((16, 16), 1),
((256, 15), 0),
((1, 1), 0),
] {
assert_eq!(mips_for(extent), expected, "{extent:?}");
for mip in 1..=mips_for(extent) {
let (width, height) = mip_extent(extent, mip);
assert!(
width >= MIN_MIP_EXTENT && height >= MIN_MIP_EXTENT,
"{extent:?} level {mip} is {width}x{height}, under the filter's own footprint"
);
}
}
}
#[test]
fn the_pass_ceiling_is_the_longest_chain_this_module_will_build() {
assert_eq!(Bloom::passes_for((1920, 1080)), Bloom::MAX_PASSES);
assert_eq!(Bloom::passes_for((256, 192)), 8);
assert_eq!(Bloom::passes_for((16, 16)), 2);
assert_eq!(
Bloom::passes_for((1, 1)),
0,
"a target with no chain records nothing, rather than a composite with \
nothing to composite"
);
for extent in [(1920, 1080), (256, 192), (97, 61), (16, 16), (1, 1)] {
assert!(
Bloom::passes_for(extent) <= Bloom::MAX_PASSES,
"{extent:?} records {} passes, past the ceiling of {}",
Bloom::passes_for(extent),
Bloom::MAX_PASSES
);
}
}
#[test]
fn every_level_is_the_floor_of_half_the_level_above_it() {
for extent in [(1920, 1080), (256, 192), (97, 61), (16, 16)] {
assert_eq!(mip_extent(extent, 0), extent, "level 0 is the scene itself");
for mip in 1..=mips_for(extent) {
let above = mip_extent(extent, mip - 1);
assert_eq!(
mip_extent(extent, mip),
(above.0 / 2, above.1 / 2),
"{extent:?} level {mip}"
);
}
}
}
}