use crcbl_hal::{
BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle, BufferUsage, ClearValue,
ColorTargetState, Device, Format, GraphicsPipelineHandle, HalError, LoadOp, MemoryLocation,
PipelineLayoutDesc, PipelineLayoutHandle, ShaderStages, StoreOp,
check_portable_storage_buffers,
};
use crcbl_shaders::{SKY, atmosphere, sky};
use crate::graph::{ImageId, RenderGraph};
const FULLSCREEN_VERTICES: u32 = 3;
const SKY_VIEW_BINDING: u32 = 1;
#[derive(Debug)]
pub(crate) struct SkyPass {
uniforms: Vec<BufferHandle>,
luts: Vec<BufferHandle>,
aerials: Vec<BufferHandle>,
groups: Vec<BindGroupHandle>,
layout: crcbl_hal::BindGroupLayoutHandle,
pipeline_layout: PipelineLayoutHandle,
pipeline: GraphicsPipelineHandle,
}
impl SkyPass {
pub(crate) const PASSES: u64 = 1;
pub(crate) fn new(
device: &dyn Device,
frames: usize,
color_format: Format,
depth_format: Format,
build_tested_fullscreen: impl Fn(
&dyn Device,
&str,
&crcbl_shaders::Shader,
PipelineLayoutHandle,
&[ColorTargetState],
Format,
) -> Result<GraphicsPipelineHandle, HalError>,
) -> Result<Self, HalError> {
let entries = [
BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::UniformBuffer { dynamic: false },
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: SKY_VIEW_BINDING,
visibility: ShaderStages::VERTEX.union(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(),
},
];
let desc = BindGroupLayoutDesc {
label: Some("sky"),
entries: &entries,
};
check_portable_storage_buffers(Some("sky"), &[&desc])?;
let layout = device.create_bind_group_layout(&desc)?;
let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("sky"),
bind_group_layouts: &[layout],
push_constants: None,
})?;
let pipeline = build_tested_fullscreen(
device,
"sky",
&SKY,
pipeline_layout,
&[ColorTargetState::opaque(color_format)],
depth_format,
)?;
let mut uniforms = Vec::with_capacity(frames);
let mut luts = Vec::with_capacity(frames);
let mut aerials = Vec::with_capacity(frames);
let mut groups = Vec::with_capacity(frames);
for _ in 0..frames {
let buffer = device.create_buffer(&BufferDesc {
label: Some("sky params"),
size: sky::PARAMS_SIZE as u64,
usage: BufferUsage::UNIFORM,
memory: MemoryLocation::HostUpload,
})?;
uniforms.push(buffer);
let lut = device.create_buffer(&BufferDesc {
label: Some("sky view lut"),
size: atmosphere::SKY_VIEW_BUFFER_BYTES as u64,
usage: BufferUsage::STORAGE,
memory: MemoryLocation::HostUpload,
})?;
device.write_buffer(lut, 0, &vec![0u8; atmosphere::SKY_VIEW_BUFFER_BYTES])?;
luts.push(lut);
let aerial = device.create_buffer(&BufferDesc {
label: Some("aerial view lut"),
size: atmosphere::AERIAL_VIEW_BUFFER_BYTES as u64,
usage: BufferUsage::STORAGE,
memory: MemoryLocation::HostUpload,
})?;
device.write_buffer(aerial, 0, &vec![0u8; atmosphere::AERIAL_VIEW_BUFFER_BYTES])?;
aerials.push(aerial);
groups.push(device.create_bind_group(&BindGroupDesc {
label: Some("sky"),
layout,
entries: &[
BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::whole_buffer(buffer),
},
BindGroupEntry {
binding: SKY_VIEW_BINDING,
array_index: 0,
resource: BindingResource::whole_buffer(lut),
},
],
variable_count: None,
})?);
}
Ok(Self {
uniforms,
luts,
aerials,
groups,
layout,
pipeline_layout,
pipeline,
})
}
pub(crate) fn begin_frame(
&self,
device: &dyn Device,
frame: usize,
inv_proj: [f32; 16],
inv_view: [f32; 16],
gradient: &crcbl_shaders::sky::SkyGradient,
sky_view: Option<&atmosphere::SkyView>,
) -> Result<(), HalError> {
let params = sky::SkyParams {
inv_proj,
inv_view,
sky: gradient.rows(),
atmosphere: match sky_view {
Some(view) => {
let sun = view.sun_direction();
[sun[0], sun[1], sun[2], sky::ATMOSPHERE_ON]
}
None => [0.0, 0.0, 0.0, sky::ATMOSPHERE_OFF],
},
sun_disc: match sky_view {
Some(view) => {
let disc = view.sun_disc();
[
disc[0],
disc[1],
disc[2],
atmosphere::SUN_ANGULAR_RADIUS_VERSINE,
]
}
None => [0.0; 4],
},
};
device.write_buffer(self.uniforms[frame], 0, ¶ms.to_bytes())?;
if let Some(view) = sky_view {
device.write_buffer(self.luts[frame], 0, &view.rows())?;
device.write_buffer(self.aerials[frame], 0, &view.aerial().rows())?;
}
Ok(())
}
pub(crate) fn aerial(&self, frame: usize) -> BufferHandle {
self.aerials[frame]
}
pub(crate) fn lut(&self, frame: usize) -> BufferHandle {
self.luts[frame]
}
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) fn luts(&self) -> &[BufferHandle] {
&self.luts
}
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) fn aerials(&self) -> &[BufferHandle] {
&self.aerials
}
pub(crate) fn add_pass<'a>(
&'a self,
graph: &mut RenderGraph<'a>,
frame: usize,
color: ImageId,
depth: ImageId,
) {
let pipeline = self.pipeline;
let pipeline_layout = self.pipeline_layout;
let group = self.groups[frame];
graph
.add_render_pass("sky")
.color(color, LoadOp::Load, StoreOp::Store, ClearValue::default())
.depth_read(depth)
.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_graphics_pipeline(pipeline);
encoder.bind_group(0, group, &[], pipeline_layout);
encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
});
}
pub(crate) fn destroy(self, device: &dyn Device) {
for group in self.groups {
device.destroy_bind_group(group);
}
device.destroy_graphics_pipeline(self.pipeline);
device.destroy_pipeline_layout(self.pipeline_layout);
device.destroy_bind_group_layout(self.layout);
for buffer in self
.uniforms
.into_iter()
.chain(self.luts)
.chain(self.aerials)
{
device.destroy_buffer(buffer);
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn the_triangle_sits_exactly_at_the_far_plane() {
let source = include_str!("../../crcbl-shaders/shaders/sky.slang");
let emitted = source
.split_once(
"output.position = float4(output.uv * float2(2.0, -2.0) + float2(-1.0, 1.0),",
)
.expect("sky.slang emits its triangle from `uv`")
.1
.split_once(',')
.expect("the position has a `z` and a `w`")
.0
.trim()
.parse::<f32>()
.expect("the `z` is a literal");
assert_eq!(
emitted,
crcbl_hal::depth::CLEAR,
"sky.slang emits its triangle at {emitted}, which is no longer the reversed-Z far \
plane the depth test compares it against"
);
}
#[test]
fn the_declared_pass_count_is_the_one_the_body_adds() {
let source = include_str!("sky_pass.rs");
let body = source
.split_once("pub(crate) fn add_pass<'a>(")
.expect("this file declares `add_pass`")
.1
.split_once("\n }")
.expect("the function has a body")
.0;
let added = body.matches("add_render_pass(").count() as u64;
assert_eq!(added, super::SkyPass::PASSES);
}
}