use crcbl_hal::{
BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
BufferUsage, ClearValue, ColorTargetState, Device, Format, GraphicsPipelineHandle, HalError,
ImageViewHandle, ImageViewType, LoadOp, MemoryLocation, PipelineLayoutDesc,
PipelineLayoutHandle, SampleType, ShaderStages, StoreOp, check_portable_storage_buffers,
};
use crcbl_shaders::{SSR, SSR_BLUR, sky_prefilter, ssr};
use crate::graph::{ImageId, RenderGraph};
use crate::partial::Partial;
use crate::ssao::cached_group;
use crate::texture::{UploadBatch, UploadedTexture};
const SKY_PREFILTER_BINDING: u32 = 5 + crate::hiz::MAX_LEVELS;
const SKY_PREFILTER_SIZE: u32 = sky_prefilter::PREFILTER_SIZE as u32;
const DFG_BINDING: u32 = SKY_PREFILTER_BINDING + 1;
const PROBE_VISIBILITY_BINDING: u32 = DFG_BINDING + 1;
const SKY_VIEW_BINDING: u32 = PROBE_VISIBILITY_BINDING + 1;
const FULLSCREEN_VERTICES: u32 = 3;
pub const MIN_SSR_RESOLUTION: f32 = 1.0 / ssr::MAX_BLOCK as f32;
crcbl_console::convar! {
pub static r_ssr_resolution: f32 in 0.25 ..= 1.0 = 1.0;
}
pub(crate) fn resolution_scale() -> f32 {
r_ssr_resolution.get_f32().clamp(MIN_SSR_RESOLUTION, 1.0)
}
pub(crate) fn march_extent(extent: (u32, u32), scale: f32) -> (u32, u32) {
let scale = f64::from(scale);
let axis = |length: u32| ((f64::from(length) * scale).ceil() as u32).clamp(1, length.max(1));
(axis(extent.0), axis(extent.1))
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct SsrImages {
pub(crate) depth: ImageId,
pub(crate) color: ImageId,
pub(crate) reflectivity: ImageId,
pub(crate) reflection: ImageId,
pub(crate) composited: ImageId,
pub(crate) pyramid: [ImageId; crate::hiz::MAX_LEVELS as usize],
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct SsrEnvironment {
pub(crate) probes: BufferHandle,
pub(crate) probe_id: crate::graph::BufferId,
pub(crate) probe_visibility: ImageViewHandle,
pub(crate) sky_view: BufferHandle,
}
#[derive(Debug)]
pub(crate) struct Ssr {
uniforms: Vec<BufferHandle>,
pipelines: SsrPipelines,
groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
blur_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
sky_prefilter: UploadedTexture,
dfg: ImageViewHandle,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct SsrLayouts {
layout: BindGroupLayoutHandle,
pipeline_layout: PipelineLayoutHandle,
blur_layout: BindGroupLayoutHandle,
blur_pipeline_layout: PipelineLayoutHandle,
}
impl SsrLayouts {
const TARGETS: [ColorTargetState; 1] = [ColorTargetState::opaque(Format::Rgba16Float)];
pub(crate) fn new(device: &dyn Device, made: &mut Partial<'_>) -> Result<Self, HalError> {
let 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::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 4,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: crcbl_shaders::probe::PROBE_STRIDE as u32,
},
count: 1,
flags: BindingFlags::empty(),
},
];
let mut entries = entries.to_vec();
entries.push(BindGroupLayoutEntry {
binding: SKY_PREFILTER_BINDING,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
});
entries.push(BindGroupLayoutEntry {
binding: DFG_BINDING,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
});
entries.push(BindGroupLayoutEntry {
binding: PROBE_VISIBILITY_BINDING,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2Array,
sample_type: SampleType::UnfilterableFloat,
},
count: 1,
flags: BindingFlags::empty(),
});
entries.push(BindGroupLayoutEntry {
binding: SKY_VIEW_BINDING,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: crcbl_shaders::atmosphere::SKY_VIEW_ROW_BYTES as u32,
},
count: 1,
flags: BindingFlags::empty(),
});
entries.extend(
(0..crate::hiz::MAX_LEVELS).map(|level| BindGroupLayoutEntry {
binding: 5 + level,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Depth,
},
count: 1,
flags: BindingFlags::empty(),
}),
);
let desc = BindGroupLayoutDesc {
label: Some("ssr"),
entries: &entries,
};
check_portable_storage_buffers(Some("ssr"), &[&desc])?;
let layout = made.add(device.create_bind_group_layout(&desc)?);
let set_layouts = [layout];
let pipeline_layout = made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("ssr"),
bind_group_layouts: &set_layouts,
push_constants: None,
})?);
let blur_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::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
},
];
let blur_desc = BindGroupLayoutDesc {
label: Some("ssr blur"),
entries: &blur_entries,
};
check_portable_storage_buffers(Some("ssr blur"), &[&blur_desc])?;
let blur_layout = made.add(device.create_bind_group_layout(&blur_desc)?);
let blur_set_layouts = [blur_layout];
let blur_pipeline_layout =
made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("ssr blur"),
bind_group_layouts: &blur_set_layouts,
push_constants: None,
})?);
Ok(Self {
layout,
pipeline_layout,
blur_layout,
blur_pipeline_layout,
})
}
pub(crate) fn march(
self,
device: &dyn Device,
build_fullscreen: impl Fn(
&dyn Device,
&str,
&crcbl_shaders::Shader,
PipelineLayoutHandle,
&[ColorTargetState],
) -> Result<GraphicsPipelineHandle, HalError>,
) -> Result<GraphicsPipelineHandle, HalError> {
build_fullscreen(device, "ssr", &SSR, self.pipeline_layout, &Self::TARGETS)
}
pub(crate) fn blur(
self,
device: &dyn Device,
build_fullscreen: impl Fn(
&dyn Device,
&str,
&crcbl_shaders::Shader,
PipelineLayoutHandle,
&[ColorTargetState],
) -> Result<GraphicsPipelineHandle, HalError>,
) -> Result<GraphicsPipelineHandle, HalError> {
build_fullscreen(
device,
"ssr blur",
&SSR_BLUR,
self.blur_pipeline_layout,
&Self::TARGETS,
)
}
pub(crate) fn finish(
self,
pipeline: GraphicsPipelineHandle,
blur_pipeline: GraphicsPipelineHandle,
) -> SsrPipelines {
SsrPipelines {
layouts: self,
pipeline,
blur_pipeline,
}
}
}
#[derive(Debug)]
pub(crate) struct SsrPipelines {
layouts: SsrLayouts,
pipeline: GraphicsPipelineHandle,
blur_pipeline: GraphicsPipelineHandle,
}
impl SsrPipelines {
pub(crate) fn new(
device: &dyn Device,
build_fullscreen: impl Fn(
&dyn Device,
&str,
&crcbl_shaders::Shader,
PipelineLayoutHandle,
&[ColorTargetState],
) -> Result<GraphicsPipelineHandle, HalError>,
) -> Result<Self, HalError> {
let mut made = Partial::new(device);
let layouts = SsrLayouts::new(device, &mut made)?;
let pipeline = made.add(layouts.march(device, &build_fullscreen)?);
let blur_pipeline = made.add(layouts.blur(device, build_fullscreen)?);
made.keep();
Ok(layouts.finish(pipeline, blur_pipeline))
}
fn hold(&self, made: &mut Partial<'_>) {
let layouts = self.layouts;
made.add(layouts.layout);
made.add(layouts.pipeline_layout);
made.add(layouts.blur_layout);
made.add(layouts.blur_pipeline_layout);
made.add(self.pipeline);
made.add(self.blur_pipeline);
}
pub(crate) fn destroy(self, device: &dyn Device) {
device.destroy_graphics_pipeline(self.blur_pipeline);
device.destroy_pipeline_layout(self.layouts.blur_pipeline_layout);
device.destroy_bind_group_layout(self.layouts.blur_layout);
device.destroy_graphics_pipeline(self.pipeline);
device.destroy_pipeline_layout(self.layouts.pipeline_layout);
device.destroy_bind_group_layout(self.layouts.layout);
}
}
impl Ssr {
pub(crate) const PASSES: u32 = 2;
pub(crate) fn new(
device: &dyn Device,
uploads: &mut UploadBatch<'_>,
pipelines: SsrPipelines,
dfg: ImageViewHandle,
frames: usize,
) -> Result<Self, HalError> {
let mut made = Partial::new(device);
pipelines.hold(&mut made);
let built = Self::build(device, uploads, pipelines, dfg, frames, &mut made);
match built {
Ok(_) => made.keep(),
Err(_) => uploads.abandon(),
}
built
}
fn build(
device: &dyn Device,
uploads: &mut UploadBatch<'_>,
pipelines: SsrPipelines,
dfg: ImageViewHandle,
frames: usize,
made: &mut Partial<'_>,
) -> Result<Self, HalError> {
let sky_prefilter = made.add_texture(uploads.texture(
"sky prefilter table",
Format::Rgba8Unorm,
(SKY_PREFILTER_SIZE, SKY_PREFILTER_SIZE),
&[&[&sky_prefilter::texels()]],
ImageViewType::D2,
)?);
let mut uniforms = Vec::with_capacity(frames);
for _ in 0..frames {
uniforms.push(made.add(device.create_buffer(&BufferDesc {
label: Some("ssr params"),
size: ssr::PARAMS_SIZE as u64,
usage: BufferUsage::UNIFORM,
memory: MemoryLocation::HostUpload,
})?));
}
Ok(Self {
uniforms,
pipelines,
groups: vec![None; frames],
blur_groups: vec![None; frames],
sky_prefilter,
dfg,
})
}
pub(crate) fn uniforms(&self, frame: usize) -> BufferHandle {
self.uniforms[frame]
}
pub(crate) fn sky_prefilter_view(&self) -> ImageViewHandle {
self.sky_prefilter.view
}
pub(crate) fn begin_frame(
&self,
device: &dyn Device,
frame: usize,
params: ssr::SsrParams,
) -> Result<(), HalError> {
device.write_buffer(self.uniforms[frame], 0, ¶ms.to_bytes())
}
pub(crate) fn add_passes<'a>(
&'a mut self,
graph: &mut RenderGraph<'a>,
frame: usize,
images: SsrImages,
environment: SsrEnvironment,
) {
let SsrEnvironment {
probes,
probe_id,
probe_visibility,
sky_view,
} = environment;
let SsrImages {
depth,
color,
reflectivity,
reflection,
composited,
pyramid,
} = images;
let pipeline = self.pipelines.pipeline;
let pipeline_layout = self.pipelines.layouts.pipeline_layout;
let layout = self.pipelines.layouts.layout;
let uniforms = self.uniforms[frame];
let sky_prefilter_view = self.sky_prefilter.view;
let dfg_view = self.dfg;
let (groups, blur_groups) = (&mut self.groups, &mut self.blur_groups);
let cached = &mut groups[frame];
let blur_cached = &mut blur_groups[frame];
let mut pyramid_reads: Vec<ImageId> = Vec::with_capacity(pyramid.len());
for level in pyramid {
if level != depth && !pyramid_reads.contains(&level) {
pyramid_reads.push(level);
}
}
let mut pass = graph
.add_render_pass("ssr")
.color(
reflection,
LoadOp::DontCare,
StoreOp::Store,
ClearValue::default(),
)
.read_image(color)
.read_image(depth)
.read_image(reflectivity)
.read_buffer(probe_id);
for level in pyramid_reads {
pass = pass.read_image(level);
}
pass.execute(move |ctx| {
let color_view = ctx.image_view(color);
let depth_view = ctx.image_view(depth);
let material_view = ctx.image_view(reflectivity);
let device = ctx.device();
const BASE_ENTRY_COUNT: usize = 9;
const BASE_KEY_COUNT: usize = 4;
let base: [BindGroupEntry; BASE_ENTRY_COUNT] = [
BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::whole_buffer(uniforms),
},
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::ImageView(material_view),
},
BindGroupEntry {
binding: 4,
array_index: 0,
resource: BindingResource::whole_buffer(probes),
},
BindGroupEntry {
binding: SKY_PREFILTER_BINDING,
array_index: 0,
resource: BindingResource::ImageView(sky_prefilter_view),
},
BindGroupEntry {
binding: DFG_BINDING,
array_index: 0,
resource: BindingResource::ImageView(dfg_view),
},
BindGroupEntry {
binding: PROBE_VISIBILITY_BINDING,
array_index: 0,
resource: BindingResource::ImageView(probe_visibility),
},
BindGroupEntry {
binding: SKY_VIEW_BINDING,
array_index: 0,
resource: BindingResource::whole_buffer(sky_view),
},
];
let pyramid_views = pyramid.map(|level| ctx.image_view(level));
let entries: [BindGroupEntry; BASE_ENTRY_COUNT + crate::hiz::MAX_LEVELS as usize] =
std::array::from_fn(|index| {
if index < base.len() {
base[index]
} else {
let level = index - base.len();
BindGroupEntry {
binding: 5 + u32::try_from(level)
.unwrap_or_else(|_| unreachable!("a pyramid of a few levels")),
array_index: 0,
resource: BindingResource::ImageView(pyramid_views[level]),
}
}
});
let base_key: [(u32, ImageViewHandle); BASE_KEY_COUNT] = [
(1, depth_view),
(2, color_view),
(3, material_view),
(PROBE_VISIBILITY_BINDING, probe_visibility),
];
let key: [(u32, ImageViewHandle); BASE_KEY_COUNT + crate::hiz::MAX_LEVELS as usize] =
std::array::from_fn(|index| {
if index < base_key.len() {
base_key[index]
} else {
let level = index - base_key.len();
(
5 + u32::try_from(level)
.unwrap_or_else(|_| unreachable!("a pyramid of a few levels")),
pyramid_views[level],
)
}
});
let Some(group) = cached_group(cached, device, &key, "ssr", 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);
});
let blur_pipeline = self.pipelines.blur_pipeline;
let blur_pipeline_layout = self.pipelines.layouts.blur_pipeline_layout;
let blur_layout = self.pipelines.layouts.blur_layout;
graph
.add_render_pass("ssr-blur")
.color(
composited,
LoadOp::DontCare,
StoreOp::Store,
ClearValue::default(),
)
.read_image(reflection)
.read_image(color)
.read_image(depth)
.execute(move |ctx| {
let color_view = ctx.image_view(color);
let depth_view = ctx.image_view(depth);
let reflection_view = ctx.image_view(reflection);
let device = ctx.device();
let entries = [
BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::whole_buffer(uniforms),
},
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::ImageView(reflection_view),
},
];
let Some(group) = cached_group(
blur_cached,
device,
&[(1, depth_view), (2, color_view), (3, reflection_view)],
"ssr blur",
blur_layout,
&entries,
) else {
return;
};
let encoder = ctx.encoder();
encoder.bind_graphics_pipeline(blur_pipeline);
encoder.bind_group(0, group, &[], blur_pipeline_layout);
encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
});
}
pub(crate) fn destroy(self, device: &dyn Device) {
for cached in self.groups.into_iter().chain(self.blur_groups).flatten() {
device.destroy_bind_group(cached.1);
}
self.pipelines.destroy(device);
for buffer in self.uniforms {
device.destroy_buffer(buffer);
}
self.sky_prefilter.destroy(device);
}
}
#[cfg(test)]
mod tests {
use super::{MIN_SSR_RESOLUTION, march_extent, r_ssr_resolution};
#[test]
fn the_march_extent_covers_even_odd_and_single_pixel_frames() {
assert_eq!(march_extent((1920, 1080), 1.0), (1920, 1080));
assert_eq!(march_extent((1920, 1080), 0.75), (1440, 810));
assert_eq!(march_extent((1920, 1080), 0.5), (960, 540));
assert_eq!(march_extent((1920, 1080), 0.25), (480, 270));
assert_eq!(march_extent((1921, 1081), 0.5), (961, 541));
assert_eq!(march_extent((1921, 1081), 0.75), (1441, 811));
assert_eq!(march_extent((1, 1), 0.25), (1, 1));
}
#[test]
fn no_block_at_the_floor_is_wider_than_the_march_walks() {
for length in 1..=4096u32 {
let (working, _) = march_extent((length, 1), MIN_SSR_RESOLUTION);
let widest = length.div_ceil(working);
assert!(
widest <= crcbl_shaders::ssr::MAX_BLOCK,
"a {length}-pixel axis at the floor gives {widest}-pixel blocks"
);
}
}
#[test]
fn the_console_range_is_the_range_the_march_honours() {
assert_eq!(
r_ssr_resolution.kind(),
crcbl_console::Kind::Float {
min: MIN_SSR_RESOLUTION,
max: 1.0,
},
);
assert_eq!(
r_ssr_resolution.default(),
&crcbl_console::Value::Float(1.0)
);
}
}