use crcbl_hal::{
BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BlendState, BufferDesc,
BufferHandle, BufferUsage, ColorTargetState, ColorWrites, CompareOp, DepthBias,
DepthStencilState, Device, Format, GraphicsPipelineDesc, GraphicsPipelineHandle, HalError,
LoadOp, MemoryLocation, MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle,
PrimitiveState, ShaderEntry, ShaderModuleDesc, ShaderStages, StoreOp,
check_portable_storage_buffers,
};
use crcbl_shaders::{GRID, Stage};
use glam::{Mat4, Vec2, Vec3};
use crate::graph::{ImageId, RenderGraph};
const FULLSCREEN_VERTICES: u32 = 3;
const PARAMS_SIZE: usize = 64 + 64 + 16 + 16 + 16;
pub const PARALLEL_EPSILON: f32 = 1e-7;
pub const DERIVATIVE_FLOOR: f32 = 1e-8;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GridStyle {
pub spacing: f32,
pub coarse_multiple: f32,
pub line_width: f32,
pub fade_distance: f32,
pub fine_color: [f32; 4],
pub coarse_color: [f32; 4],
}
impl Default for GridStyle {
fn default() -> Self {
Self {
spacing: 1.0,
coarse_multiple: 10.0,
line_width: 1.0,
fade_distance: 100.0,
fine_color: [0.32, 0.32, 0.32, 0.55],
coarse_color: [0.55, 0.55, 0.55, 0.8],
}
}
}
impl GridStyle {
const CELLS_ACROSS: f32 = 10.0;
const FADE_MULTIPLE: f32 = 20.0;
const MIN_SPACING: f32 = 1e-4;
const MAX_SPACING: f32 = 1e6;
#[must_use]
pub fn for_extent(extent: f32) -> Self {
if !extent.is_finite() || extent <= 0.0 {
return Self::default();
}
let ideal = (extent / Self::CELLS_ACROSS).clamp(Self::MIN_SPACING, Self::MAX_SPACING);
let spacing = 10.0f32
.powf(ideal.log10().round())
.clamp(Self::MIN_SPACING, Self::MAX_SPACING);
Self {
spacing,
fade_distance: extent * Self::FADE_MULTIPLE,
..Self::default()
}
}
}
#[must_use]
pub fn plane_hit(origin: Vec3, direction: Vec3) -> Option<f32> {
if direction.y.abs() <= PARALLEL_EPSILON {
return None;
}
let distance = -origin.y / direction.y;
(distance > 0.0).then_some(distance)
}
#[must_use]
pub fn line_coverage(cell: f32, derivative: f32, line_width: f32) -> f32 {
let offset = cell - 0.5;
let to_line = (offset - offset.floor() - 0.5).abs() / derivative.max(DERIVATIVE_FLOOR);
(line_width * 0.5 + 0.5 - to_line).clamp(0.0, 1.0)
}
#[must_use]
pub fn resolvable(derivative: f32, line_width: f32) -> f32 {
(2.0 * (1.0 - line_width * derivative)).clamp(0.0, 1.0)
}
#[must_use]
pub fn scale_coverage(cell: Vec2, derivative: Vec2, line_width: f32) -> f32 {
let coverage = line_coverage(cell.x, derivative.x, line_width).max(line_coverage(
cell.y,
derivative.y,
line_width,
));
coverage * resolvable(derivative.x.max(derivative.y), line_width)
}
#[must_use]
pub fn distance_fade(distance: f32, fade_distance: f32) -> f32 {
(1.0 - distance / fade_distance).clamp(0.0, 1.0)
}
#[must_use]
pub fn composite(style: &GridStyle, fine: f32, coarse: f32, fade: f32) -> [f32; 4] {
let coarse_alpha = style.coarse_color[3] * coarse * fade;
let fine_alpha = style.fine_color[3] * fine * fade * (1.0 - coarse_alpha);
[
style.coarse_color[0] * coarse_alpha + style.fine_color[0] * fine_alpha,
style.coarse_color[1] * coarse_alpha + style.fine_color[1] * fine_alpha,
style.coarse_color[2] * coarse_alpha + style.fine_color[2] * fine_alpha,
coarse_alpha + fine_alpha,
]
}
fn params_bytes(inv_view_proj: Mat4, view_proj: Mat4, style: &GridStyle) -> [u8; PARAMS_SIZE] {
let mut bytes = [0u8; PARAMS_SIZE];
let mut at = 0;
let rows = [
style.spacing,
style.coarse_multiple,
style.line_width,
style.fade_distance,
];
let values = inv_view_proj
.to_cols_array()
.into_iter()
.chain(view_proj.to_cols_array())
.chain(rows)
.chain(style.fine_color)
.chain(style.coarse_color);
for value in values {
bytes[at..at + 4].copy_from_slice(&value.to_le_bytes());
at += 4;
}
debug_assert_eq!(at, PARAMS_SIZE, "the block is written whole");
bytes
}
#[derive(Debug)]
pub struct Grid {
layout: BindGroupLayoutHandle,
pipeline_layout: PipelineLayoutHandle,
pipeline: GraphicsPipelineHandle,
uniforms: Vec<BufferHandle>,
groups: Vec<BindGroupHandle>,
style: GridStyle,
}
impl Grid {
pub fn new(
device: &dyn Device,
frames: usize,
target_format: Format,
depth_format: Format,
) -> Result<Self, HalError> {
let mut rollback = Rollback::default();
match Self::build(device, frames, target_format, depth_format, &mut rollback) {
Ok(grid) => Ok(grid),
Err(error) => {
rollback.run(device);
Err(error)
}
}
}
fn build(
device: &dyn Device,
frames: usize,
target_format: Format,
depth_format: Format,
rollback: &mut Rollback,
) -> Result<Self, HalError> {
let entries = [BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::UniformBuffer { dynamic: false },
count: 1,
flags: BindingFlags::empty(),
}];
let desc = BindGroupLayoutDesc {
label: Some("grid"),
entries: &entries,
};
check_portable_storage_buffers(Some("grid"), &[&desc])?;
let layout = device.create_bind_group_layout(&desc)?;
rollback.bind_group_layouts.push(layout);
let set_layouts = [layout];
let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("grid"),
bind_group_layouts: &set_layouts,
push_constants: None,
})?;
rollback.pipeline_layouts.push(pipeline_layout);
let mut uniforms = Vec::with_capacity(frames);
let mut groups = Vec::with_capacity(frames);
for _ in 0..frames {
let buffer = device.create_buffer(&BufferDesc {
label: Some("grid params"),
size: PARAMS_SIZE as u64,
usage: BufferUsage::UNIFORM,
memory: MemoryLocation::HostUpload,
})?;
rollback.buffers.push(buffer);
uniforms.push(buffer);
let group = device.create_bind_group(&BindGroupDesc {
label: Some("grid params"),
layout,
entries: &[BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::whole_buffer(buffer),
}],
variable_count: None,
})?;
rollback.bind_groups.push(group);
groups.push(group);
}
let vertex = entry(Stage::Vertex)?;
let fragment = entry(Stage::Fragment)?;
let module = device.create_shader_module(&ShaderModuleDesc {
label: Some(GRID.source()),
spirv: GRID.spirv(),
wgsl: GRID.wgsl(),
msl: GRID.msl(),
dxil: &GRID.dxil_containers(),
})?;
let targets = [ColorTargetState {
format: target_format,
blend: Some(BlendState::premultiplied()),
write_mask: ColorWrites::ALL,
}];
let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
label: Some("grid"),
layout: pipeline_layout,
vertex: ShaderEntry {
module,
entry_point: vertex,
},
fragment: Some(ShaderEntry {
module,
entry_point: fragment,
}),
primitive: PrimitiveState::default(),
depth_stencil: Some(DepthStencilState {
format: depth_format,
depth_write: false,
depth_compare: CompareOp::Greater,
stencil: None,
bias: DepthBias::default(),
}),
multisample: MultisampleState::default(),
color_targets: &targets,
});
device.destroy_shader_module(module);
let pipeline = pipeline?;
rollback.pipelines.push(pipeline);
Ok(Self {
layout,
pipeline_layout,
pipeline,
uniforms,
groups,
style: GridStyle::default(),
})
}
#[must_use]
pub const fn style(&self) -> &GridStyle {
&self.style
}
pub const fn set_style(&mut self, style: GridStyle) {
self.style = style;
}
pub fn add_pass<'a>(
&'a self,
graph: &mut RenderGraph<'a>,
frame: usize,
target: ImageId,
depth: ImageId,
view_proj: Mat4,
inv_view_proj: Mat4,
) {
let pipeline = self.pipeline;
let pipeline_layout = self.pipeline_layout;
let group = self.groups[frame];
let uniforms = self.uniforms[frame];
let bytes = params_bytes(inv_view_proj, view_proj, &self.style);
graph
.add_render_pass("grid")
.color(target, LoadOp::Load, StoreOp::Store, Default::default())
.depth_read(depth)
.execute(move |ctx| {
if let Err(error) = ctx.device().write_buffer(uniforms, 0, &bytes) {
crcbl_core::log::error!("graph: grid params write failed: {error}");
return;
}
let encoder = ctx.encoder();
encoder.bind_graphics_pipeline(pipeline);
encoder.bind_group(0, group, &[], pipeline_layout);
encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
});
}
pub fn destroy(self, device: &dyn Device) {
for group in self.groups {
device.destroy_bind_group(group);
}
for buffer in self.uniforms {
device.destroy_buffer(buffer);
}
device.destroy_graphics_pipeline(self.pipeline);
device.destroy_pipeline_layout(self.pipeline_layout);
device.destroy_bind_group_layout(self.layout);
}
}
fn entry(stage: Stage) -> Result<&'static str, HalError> {
GRID.entry_point(stage).ok_or_else(|| {
HalError::ShaderCompilation(format!(
"grid.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V and \
its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix"
))
})
}
#[derive(Default)]
struct Rollback {
buffers: Vec<BufferHandle>,
bind_groups: Vec<BindGroupHandle>,
bind_group_layouts: Vec<BindGroupLayoutHandle>,
pipeline_layouts: Vec<PipelineLayoutHandle>,
pipelines: Vec<GraphicsPipelineHandle>,
}
impl Rollback {
fn run(self, device: &dyn Device) {
for group in self.bind_groups {
device.destroy_bind_group(group);
}
for buffer in self.buffers {
device.destroy_buffer(buffer);
}
for pipeline in self.pipelines {
device.destroy_graphics_pipeline(pipeline);
}
for layout in self.pipeline_layouts {
device.destroy_pipeline_layout(layout);
}
for layout in self.bind_group_layouts {
device.destroy_bind_group_layout(layout);
}
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
#[test]
fn a_derived_style_keeps_a_power_of_ten_cell_at_any_scale() {
for extent in [0.05f32, 1.0, 12.0, 500.0, 20_000.0] {
let style = GridStyle::for_extent(extent);
let decades = style.spacing.log10();
assert!(
(decades - decades.round()).abs() < 1e-4,
"a {extent} m subject chose a {} m cell, which is not a power of ten and so is \
not a number anyone can count in",
style.spacing
);
let across = extent / style.spacing;
assert!(
(1.0..=100.0).contains(&across),
"a {extent} m subject spans {across} cells of {} m — outside the range where the \
grid says anything about its scale",
style.spacing
);
assert!(
style.fade_distance > extent,
"a {extent} m subject fades at {}, so the ground would end inside the model",
style.fade_distance
);
}
}
#[test]
fn a_degenerate_extent_falls_back_to_the_default_style() {
for extent in [0.0f32, -3.0, f32::NAN, f32::INFINITY] {
let style = GridStyle::for_extent(extent);
assert_eq!(
style.spacing,
GridStyle::default().spacing,
"an extent of {extent} should fall back, not derive"
);
assert!(style.spacing.is_finite() && style.fade_distance.is_finite());
}
}
use crcbl_hal::null::{NullInstance, Recorder};
use crcbl_hal::{
CommandEncoderDesc, DeviceDesc, Features, ImageUsage, Instance, QueueHandle, QueueKind,
ResourceState,
};
use crate::transient::{TransientImageDesc, TransientPool};
const SOURCE: &str = include_str!("../../crcbl-shaders/shaders/grid.slang");
fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
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 {
label: None,
adapter: adapter.id,
required_features: Features::GPU_DRIVEN,
optional_features: Features::PUSH_CONSTANTS,
compatible_surface: None,
})
.expect("the null backend always opens");
let queue = device.queue(QueueKind::Graphics).expect("always present");
(recorder, device, queue)
}
#[test]
fn the_hit_is_the_distance_along_a_unit_direction() {
let hit = plane_hit(Vec3::new(0.0, 2.0, 0.0), Vec3::new(0.0, -1.0, 0.0));
assert_eq!(hit, Some(2.0));
let diagonal = Vec3::new(0.0, -1.0, -1.0).normalize();
let hit = plane_hit(Vec3::new(0.0, 1.0, 0.0), diagonal).expect("it crosses");
assert!(
(hit - 2.0f32.sqrt()).abs() < 1e-6,
"a 45° ray from 1 m up travels √2 m to the ground, not {hit}"
);
}
#[test]
fn a_ray_parallel_to_the_ground_never_hits_it() {
assert_eq!(
plane_hit(Vec3::new(0.0, 5.0, 0.0), Vec3::new(0.0, 0.0, -1.0)),
None
);
assert_eq!(
plane_hit(
Vec3::new(0.0, 5.0, 0.0),
Vec3::new(0.0, PARALLEL_EPSILON * 0.5, -1.0)
),
None
);
}
#[test]
fn a_plane_behind_the_camera_is_not_a_hit() {
assert_eq!(
plane_hit(Vec3::new(0.0, 2.0, 0.0), Vec3::new(0.0, 1.0, 0.0)),
None
);
assert_eq!(
plane_hit(Vec3::ZERO, Vec3::new(0.0, -1.0, 0.0)),
None,
"a zero-distance hit is the camera itself"
);
}
#[test]
fn a_line_is_the_same_pixel_width_at_any_zoom() {
let width = 2.0;
for derivative in [0.001f32, 0.01, 0.1] {
let edge = derivative * (width * 0.5 + 0.5);
let coverage = line_coverage(edge, derivative, width);
assert!(
coverage < 1e-4,
"at {derivative} cells/px the line's edge read {coverage}"
);
let half = derivative * width * 0.5;
let coverage = line_coverage(half, derivative, width);
assert!(
(coverage - 0.5).abs() < 1e-4,
"at {derivative} cells/px the half-covered point read {coverage}"
);
assert_eq!(line_coverage(0.0, derivative, width), 1.0, "{derivative}");
}
}
#[test]
fn a_hairline_on_a_pixel_boundary_is_still_drawn() {
let (derivative, width) = (0.01f32, 1.0);
let centred: f32 = [-1.0f32, 0.0, 1.0]
.into_iter()
.map(|pixel| line_coverage(pixel * derivative, derivative, width))
.sum();
let straddling: f32 = [-1.5f32, -0.5, 0.5, 1.5]
.into_iter()
.map(|pixel| line_coverage(pixel * derivative, derivative, width))
.sum();
assert!(
line_coverage(0.5 * derivative, derivative, width) > 0.0,
"a line on a pixel boundary vanished"
);
assert!(
(centred - straddling).abs() < 1e-4,
"the same line put {centred} on screen at a pixel centre and {straddling} at a \
boundary; it would flicker as the camera moves"
);
}
#[test]
fn the_lines_repeat_on_both_sides_of_the_origin() {
let (derivative, width) = (0.01f32, 1.0);
for cell in [-3.0f32, -1.0, 0.0, 1.0, 7.0] {
assert_eq!(
line_coverage(cell, derivative, width),
1.0,
"cell boundary {cell} is a line"
);
}
for cell in [-2.5f32, -0.5, 0.5, 6.5] {
assert_eq!(
line_coverage(cell, derivative, width),
0.0,
"cell centre {cell} is not a line"
);
}
}
#[test]
fn a_scale_stops_once_its_lines_have_merged() {
let width = 1.0;
assert_eq!(resolvable(1.0, width), 0.0);
assert_eq!(resolvable(0.5, width), 1.0);
assert_eq!(resolvable(0.75, width), 0.5);
assert_eq!(resolvable(0.001, width), 1.0);
assert_eq!(resolvable(0.5, 2.0), 0.0);
}
#[test]
fn scale_coverage_applies_the_density_term() {
let width = 1.0;
let on_a_line = Vec2::ZERO;
assert_eq!(
scale_coverage(on_a_line, Vec2::splat(0.001), width),
1.0,
"a resolvable line is fully covered"
);
assert_eq!(
scale_coverage(on_a_line, Vec2::splat(1.0), width),
0.0,
"a merged scale draws nothing even on a line"
);
}
#[test]
fn a_crossing_is_no_brighter_than_a_line() {
let (derivative, width) = (Vec2::splat(0.01), 1.0);
let on_one_line = scale_coverage(Vec2::new(0.0, 0.5), derivative, width);
let on_a_crossing = scale_coverage(Vec2::ZERO, derivative, width);
assert_eq!(on_a_crossing, on_one_line);
}
#[test]
fn the_fade_reaches_zero_at_the_fade_distance() {
assert_eq!(distance_fade(0.0, 100.0), 1.0);
assert_eq!(distance_fade(50.0, 100.0), 0.5);
assert_eq!(distance_fade(100.0, 100.0), 0.0);
assert_eq!(distance_fade(1000.0, 100.0), 0.0);
}
#[test]
fn the_composite_is_premultiplied() {
let style = GridStyle::default();
for (fine, coarse, fade) in [
(1.0f32, 1.0f32, 1.0f32),
(1.0, 0.0, 1.0),
(0.0, 1.0, 0.5),
(0.4, 0.7, 0.9),
] {
let [r, g, b, a] = composite(&style, fine, coarse, fade);
assert!((0.0..=1.0).contains(&a), "alpha {a} left 0..=1");
for channel in [r, g, b] {
assert!(
channel <= a + 1e-6,
"channel {channel} exceeds its own alpha {a}, so it is not premultiplied"
);
}
}
assert_eq!(composite(&style, 0.0, 0.0, 1.0), [0.0, 0.0, 0.0, 0.0]);
assert_eq!(composite(&style, 1.0, 1.0, 0.0), [0.0, 0.0, 0.0, 0.0]);
}
#[test]
fn the_coarse_lines_composite_over_the_fine_ones() {
let style = GridStyle {
fine_color: [1.0, 0.0, 0.0, 1.0],
coarse_color: [0.0, 1.0, 0.0, 1.0],
..GridStyle::default()
};
assert_eq!(composite(&style, 1.0, 1.0, 1.0), [0.0, 1.0, 0.0, 1.0]);
let style = GridStyle {
coarse_color: [0.0, 1.0, 0.0, 0.5],
..style
};
assert_eq!(composite(&style, 1.0, 1.0, 1.0), [0.5, 0.5, 0.0, 1.0]);
}
#[test]
fn the_uniform_block_matches_the_struct_grid_slang_declares() {
let declarations = [
"float4x4 inv_view_proj;",
"float4x4 view_proj;",
"float4 params;",
"float4 fine_color;",
"float4 coarse_color;",
];
let mut last = 0;
for declaration in declarations {
let at = SOURCE
.find(declaration)
.unwrap_or_else(|| panic!("grid.slang does not declare `{declaration}`"));
assert!(
at > last,
"grid.slang declares `{declaration}` in a different order than params_bytes \
writes it"
);
last = at;
}
}
#[test]
fn the_constants_match_the_ones_grid_slang_declares() {
for declaration in [
format!("static const float PARALLEL_EPSILON = {PARALLEL_EPSILON:e};"),
format!("static const float DERIVATIVE_FLOOR = {DERIVATIVE_FLOOR:e};"),
] {
assert!(
SOURCE.contains(&declaration),
"grid.slang does not declare `{declaration}`"
);
}
}
#[test]
fn the_ray_origin_is_unprojected_at_the_seams_near_plane() {
let declaration = format!(
"static const float NEAR_DEPTH = {:.1};",
crcbl_hal::depth::NEAR
);
assert!(
SOURCE.contains(&declaration),
"grid.slang does not declare `{declaration}`"
);
}
#[test]
fn the_block_is_two_matrices_and_three_rows() {
let style = GridStyle {
spacing: 2.0,
coarse_multiple: 5.0,
line_width: 3.0,
fade_distance: 7.0,
fine_color: [0.1, 0.2, 0.3, 0.4],
coarse_color: [0.5, 0.6, 0.7, 0.8],
};
let bytes = params_bytes(Mat4::IDENTITY, Mat4::from_scale(Vec3::splat(2.0)), &style);
assert_eq!(bytes.len(), PARAMS_SIZE);
assert_eq!(&bytes[0..4], &1.0f32.to_le_bytes(), "inv_view_proj[0][0]");
assert_eq!(&bytes[64..68], &2.0f32.to_le_bytes(), "view_proj[0][0]");
assert_eq!(&bytes[128..132], &2.0f32.to_le_bytes(), "spacing");
assert_eq!(&bytes[132..136], &5.0f32.to_le_bytes(), "coarse_multiple");
assert_eq!(&bytes[136..140], &3.0f32.to_le_bytes(), "line_width");
assert_eq!(&bytes[140..144], &7.0f32.to_le_bytes(), "fade_distance");
assert_eq!(&bytes[144..148], &0.1f32.to_le_bytes(), "fine_color.r");
assert_eq!(&bytes[160..164], &0.5f32.to_le_bytes(), "coarse_color.r");
assert_eq!(&bytes[172..176], &0.8f32.to_le_bytes(), "coarse_color.a");
}
#[test]
fn the_pass_writes_the_inverse_first_and_the_forward_matrix_second() {
let (recorder, device, queue) = open();
let device = device.as_ref();
let grid = Grid::new(device, 1, Format::Rgba16Float, Format::D32Float)
.expect("the null backend builds every pipeline");
let view_proj = Mat4::from_scale_rotation_translation(
Vec3::new(1.5, 0.75, 2.0),
glam::Quat::from_rotation_y(0.7),
Vec3::new(3.0, -2.0, 11.0),
);
let inv_view_proj = view_proj.inverse();
let mut pool = TransientPool::new();
let mut graph = RenderGraph::new(queue);
let color = graph.create_image(
"scene-color",
TransientImageDesc::new(
(64, 48),
Format::Rgba16Float,
ImageUsage::COLOR_ATTACHMENT | ImageUsage::SAMPLED,
),
);
let depth = graph.create_image(
"scene-depth",
TransientImageDesc::new(
(64, 48),
Format::D32Float,
ImageUsage::DEPTH_STENCIL_ATTACHMENT | ImageUsage::SAMPLED,
),
);
grid.add_pass(&mut graph, 0, color, depth, view_proj, inv_view_proj);
let compiled = graph.compile(&pool).expect("the graph compiles");
let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
label: Some("grid block"),
queue,
});
compiled
.execute(device, &mut pool, encoder.as_mut(), None)
.expect("the graph executed");
let written = recorder
.buffer_bytes(grid.uniforms[0])
.expect("the pass body wrote the block");
assert_eq!(
&written[..64],
&inv_view_proj
.to_cols_array()
.iter()
.flat_map(|value| value.to_le_bytes())
.collect::<Vec<u8>>()[..],
"the inverse view-projection is the block's first member",
);
assert_eq!(
&written[64..128],
&view_proj
.to_cols_array()
.iter()
.flat_map(|value| value.to_le_bytes())
.collect::<Vec<u8>>()[..],
"the forward view-projection is the block's second member",
);
drop(encoder);
grid.destroy(device);
pool.destroy(device);
}
#[test]
fn the_pass_loads_its_target_and_only_reads_depth() {
let (_recorder, device, queue) = open();
let grid = Grid::new(device.as_ref(), 2, Format::Rgba16Float, Format::D32Float)
.expect("the null backend builds every pipeline");
let mut pool = TransientPool::new();
let mut graph = RenderGraph::new(queue);
let color = graph.create_image(
"scene-color",
TransientImageDesc::new(
(64, 48),
Format::Rgba16Float,
ImageUsage::COLOR_ATTACHMENT | ImageUsage::SAMPLED,
),
);
let depth = graph.create_image(
"scene-depth",
TransientImageDesc::new(
(64, 48),
Format::D32Float,
ImageUsage::DEPTH_STENCIL_ATTACHMENT | ImageUsage::SAMPLED,
),
);
grid.add_pass(&mut graph, 0, color, depth, Mat4::IDENTITY, Mat4::IDENTITY);
let compiled = graph.compile(&pool).expect("the graph compiles");
assert_eq!(compiled.passes().len(), 1);
let barriers = compiled.passes()[0].barriers();
let depth_barrier = barriers
.images
.iter()
.find(|barrier| barrier.to == ResourceState::DepthStencilRead)
.expect("the depth image is attached read-only");
assert_eq!(depth_barrier.to, ResourceState::DepthStencilRead);
assert!(
barriers
.images
.iter()
.all(|barrier| barrier.to != ResourceState::DepthStencilWrite),
"the grid must never take a writable depth attachment"
);
drop(compiled);
grid.destroy(device.as_ref());
pool.destroy(device.as_ref());
}
#[test]
fn the_block_is_a_ring() {
let (_recorder, device, _queue) = open();
let grid = Grid::new(device.as_ref(), 3, Format::Rgba16Float, Format::D32Float)
.expect("the null backend builds every pipeline");
assert_eq!(grid.uniforms.len(), 3);
assert_eq!(grid.groups.len(), 3);
for (slot, buffer) in grid.uniforms.iter().enumerate() {
for other in &grid.uniforms[slot + 1..] {
assert_ne!(buffer, other, "two frames share a block");
}
}
for (slot, group) in grid.groups.iter().enumerate() {
for other in &grid.groups[slot + 1..] {
assert_ne!(group, other, "two frames share a group");
}
}
grid.destroy(device.as_ref());
}
#[test]
fn the_style_reaches_the_block() {
let (_recorder, device, _queue) = open();
let mut grid = Grid::new(device.as_ref(), 1, Format::Rgba16Float, Format::D32Float)
.expect("the null backend builds every pipeline");
assert_eq!(grid.style().spacing, 1.0);
grid.set_style(GridStyle {
spacing: 0.25,
..GridStyle::default()
});
let bytes = params_bytes(Mat4::IDENTITY, Mat4::IDENTITY, grid.style());
assert_eq!(&bytes[128..132], &0.25f32.to_le_bytes());
grid.destroy(device.as_ref());
}
}