crcbl_render/grid.rs
1//! The infinite ground grid: one full-screen pass that ray-casts the plane
2//! `y = 0` and blends its cell lines over the scene.
3//!
4//! ```text
5//! scene-colour ───────────────────────────┐
6//! ▼
7//! scene-depth ──(tested, never written)──▶ grid ──▶ scene-colour
8//! ▲
9//! inverse view-projection
10//! ```
11//!
12//! `docs/backlog.md` settled both halves of this before it was written. The
13//! **technique** is the screen-space one — Blender's overlay grid, Godot 4's
14//! editor grid and Unity's — because a grid drawn as geometry has lines whose
15//! screen width changes with zoom, so it needs a density LOD, and it either
16//! stops at its own edges or is drawn absurdly large. And the **place** is this
17//! crate rather than a sample, because every `.slang` in the workspace lives in
18//! `crcbl-shaders` and because the depth image the grid has to be occluded by
19//! is here.
20//!
21//! # What this module is, and what it is not
22//!
23//! It is the pass and its pipeline, and nothing here reads a camera type: the
24//! pass takes the two matrices it needs and no more.
25//!
26//! [`crate::forward`] is what puts it in a frame, behind an opt-in that is off
27//! by default — see [`ForwardRenderer::set_ground_grid`] — and it adds this pass
28//! **after** the tonemap rather than before it. The grid is reference chrome, so
29//! it is drawn in display space where its colour is the same at any exposure,
30//! which is what Blender's overlays do; drawn into the HDR target it would be
31//! tonemapped like geometry and shift with scene brightness. It still tests
32//! against the scene depth, so real geometry occludes it.
33//!
34//! [`ForwardRenderer::set_ground_grid`]: crate::forward::ForwardRenderer::set_ground_grid
35//!
36//! [`Grid`] is deliberately **not** re-exported at the crate root, unlike most
37//! of this crate's types: [`crate::light_grid::Grid`] already holds that name at
38//! the root and means the froxel grid, and two `Grid`s one `use` apart is worse
39//! than one path segment.
40//!
41//! # The maths lives twice, on purpose
42//!
43//! `shaders/grid.slang` owns the real implementation, and nothing in this
44//! workspace can execute a fragment shader: there is no CPU path that runs one,
45//! and the golden suite compares whole images rather than the rule that
46//! produced them. So the coverage rule, the fade and the plane intersection are
47//! written a second time here — [`plane_hit`], [`line_coverage`],
48//! [`resolvable`], [`scale_coverage`], [`distance_fade`] and [`composite`] —
49//! and it is that copy the tests hold.
50//!
51//! Two of them cannot be a literal transcription and say so in their own docs:
52//! `fwidth` has no meaning off a rasteriser, so the Rust half takes the
53//! derivative as an argument where the shader computes it. Everything else is
54//! the same expression in the same order.
55
56use crcbl_hal::{
57 BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
58 BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BlendState, BufferDesc,
59 BufferHandle, BufferUsage, ColorTargetState, ColorWrites, CompareOp, DepthBias,
60 DepthStencilState, Device, Format, GraphicsPipelineDesc, GraphicsPipelineHandle, HalError,
61 LoadOp, MemoryLocation, MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle,
62 PrimitiveState, ShaderEntry, ShaderModuleDesc, ShaderStages, StoreOp,
63 check_portable_storage_buffers,
64};
65use crcbl_shaders::{GRID, Stage};
66use glam::{Mat4, Vec2, Vec3};
67
68use crate::graph::{ImageId, RenderGraph};
69
70/// Vertices in the over-sized full-screen triangle `grid.slang` generates from
71/// `SV_VertexID`. No geometry is bound anywhere — see `shaders/tonemap.slang`,
72/// which carries the shape's *why*.
73const FULLSCREEN_VERTICES: u32 = 3;
74
75/// Bytes of the uniform block: two `float4x4` and three `float4` rows.
76///
77/// `std140` gives a `float4x4` four sixteen-byte columns and a `float4` one
78/// row, and the total is already a multiple of sixteen, so there is no tail
79/// padding to write.
80const PARAMS_SIZE: usize = 64 + 64 + 16 + 16 + 16;
81
82/// How nearly parallel to the ground a ray may be before [`plane_hit`] treats
83/// it as missing the plane, matching `static const float PARALLEL_EPSILON` in
84/// `shaders/grid.slang`.
85///
86/// The direction is a unit vector, so this is the sine of the angle to the
87/// ground.
88pub const PARALLEL_EPSILON: f32 = 1e-7;
89
90/// The floor put under a derivative before [`line_coverage`] divides by it,
91/// matching `static const float DERIVATIVE_FLOOR` in `shaders/grid.slang`.
92///
93/// A derivative of exactly zero is what a perfectly axis-aligned top-down view
94/// produces on one of the two axes, and the division would otherwise return an
95/// infinity that clamps to a full-coverage line across the whole frame.
96pub const DERIVATIVE_FLOOR: f32 = 1e-8;
97
98/// How the grid is drawn.
99///
100/// Every field lands in the shader's `params`, `fine_color` and `coarse_color`
101/// rows — see `shaders/grid.slang` for what each one does to a fragment.
102#[derive(Clone, Copy, Debug, PartialEq)]
103pub struct GridStyle {
104 /// The fine cell size, in world units.
105 pub spacing: f32,
106 /// How many fine cells make one coarse cell.
107 pub coarse_multiple: f32,
108 /// Line width, in **pixels**. Constant at any zoom, which is the whole
109 /// point of taking coverage from a screen-space derivative.
110 pub line_width: f32,
111 /// The distance, in world units, at which the grid has faded to nothing.
112 pub fade_distance: f32,
113 /// The fine lines' linear RGB, with their peak opacity in `a`.
114 pub fine_color: [f32; 4],
115 /// The coarse lines' linear RGB, with their peak opacity in `a`.
116 /// Composited over the fine lines.
117 pub coarse_color: [f32; 4],
118}
119
120impl Default for GridStyle {
121 /// One-metre cells with a heavier line every ten, fading out at a hundred
122 /// metres.
123 ///
124 /// A metre because that is the unit the rest of the engine's 3D content is
125 /// authored in — `crcbl_greybox::primitives` sizes every prototype solid in
126 /// metres — so the fine cell is the size of the smallest thing anyone
127 /// places, and the coarse cell is the ten-metre block a room is laid out
128 /// on.
129 fn default() -> Self {
130 Self {
131 spacing: 1.0,
132 coarse_multiple: 10.0,
133 line_width: 1.0,
134 fade_distance: 100.0,
135 fine_color: [0.32, 0.32, 0.32, 0.55],
136 coarse_color: [0.55, 0.55, 0.55, 0.8],
137 }
138 }
139}
140
141impl GridStyle {
142 /// Roughly how many fine cells should span the thing being looked at.
143 ///
144 /// Ten is the count that makes a cell read as a *unit of the model* rather
145 /// than as texture: fewer and the grid stops giving a sense of scale, more
146 /// and the fine lines merge before the model fills the view.
147 const CELLS_ACROSS: f32 = 10.0;
148
149 /// How far past the subject the grid runs before it has faded out.
150 ///
151 /// The grid has to reach the horizon at the framing distance or the ground
152 /// visibly ends in mid-air behind the model.
153 const FADE_MULTIPLE: f32 = 20.0;
154
155 /// The narrowest and widest fine cell this will choose, in world units.
156 ///
157 /// A degenerate or absurd extent otherwise picks a spacing that makes the
158 /// whole grid one line or none, and `f32` runs out of precision either way.
159 const MIN_SPACING: f32 = 1e-4;
160 const MAX_SPACING: f32 = 1e6;
161
162 /// A style scaled to a subject `extent` world units across.
163 ///
164 /// [`Default`] is a metre grid fading at a hundred, which suits content
165 /// authored at human scale and nothing else: a five-centimetre model sits
166 /// inside a single cell, and a five-hundred-metre one is entirely past the
167 /// fade. A viewer opening arbitrary documents cannot assume either.
168 ///
169 /// **The spacing snaps to a power of ten.** A cell of `0.1`, `1` or `10`
170 /// units is a number a person can count in and do arithmetic with, which is
171 /// the grid's whole job; a cell of `3.7` gives the same line density and
172 /// tells the eye nothing. Blender's adaptive grid steps by powers of ten
173 /// for the same reason. So this picks the power of ten nearest to
174 /// `extent / CELLS_ACROSS` rather than that value itself.
175 ///
176 /// A non-finite or non-positive `extent` returns [`Default`] — there is no
177 /// scale to derive one from, and a `log10` of zero is `-inf`.
178 #[must_use]
179 pub fn for_extent(extent: f32) -> Self {
180 if !extent.is_finite() || extent <= 0.0 {
181 return Self::default();
182 }
183 let ideal = (extent / Self::CELLS_ACROSS).clamp(Self::MIN_SPACING, Self::MAX_SPACING);
184 let spacing = 10.0f32
185 .powf(ideal.log10().round())
186 .clamp(Self::MIN_SPACING, Self::MAX_SPACING);
187 Self {
188 spacing,
189 fade_distance: extent * Self::FADE_MULTIPLE,
190 ..Self::default()
191 }
192 }
193}
194
195/// Distance along `direction` from `origin` to the ground plane `y = 0`, or
196/// [`None`] when the ray does not reach it.
197///
198/// The engine is right-handed with **+Y up and −Z forward**, so the ground is
199/// the `XZ` plane and the intersection is one division. The two ways it has no
200/// answer are the two `grid.slang` drops a fragment for:
201///
202/// * **Parallel.** A `direction.y` within [`PARALLEL_EPSILON`] of zero never
203/// reaches the plane, however far the ray runs.
204/// * **Behind.** A non-positive distance is a plane the ray is travelling away
205/// from — the camera is below the ground looking up, or above it looking up.
206///
207/// `direction` is expected normalised, which is what makes the result a
208/// distance in world units and what [`distance_fade`] then reads.
209#[must_use]
210pub fn plane_hit(origin: Vec3, direction: Vec3) -> Option<f32> {
211 if direction.y.abs() <= PARALLEL_EPSILON {
212 return None;
213 }
214 let distance = -origin.y / direction.y;
215 (distance > 0.0).then_some(distance)
216}
217
218/// Coverage of the nearest line along one axis, in `0..=1`.
219///
220/// `cell` is the world coordinate **in cells** — the shader's `plane / spacing`
221/// — and `derivative` is how much of it one pixel spans, which is what the
222/// shader gets from `fwidth` and this function has to be handed: a derivative
223/// is a property of a rasterised quad and does not exist off one.
224///
225/// Their quotient is therefore a distance in **pixels**, and that is the whole
226/// technique: the line is the same width on screen at any zoom and needs no
227/// density LOD.
228///
229/// # It is the exact box filter, not a ramp
230///
231/// `line_width / 2 + 0.5 - distance` is how much of a `line_width`-wide band
232/// centred on the line falls inside a one-pixel box `distance` pixels away from
233/// it. The extra half over a ramp from the line to half a width out is what
234/// keeps a hairline that lands on a pixel *boundary* from disappearing: a ramp
235/// gives it zero coverage on both sides, so a one-pixel grid drops whole lines
236/// depending on where the camera happens to sit. This form gives that line a
237/// half on each side, and puts the same total ink on screen wherever it lands.
238///
239/// A real GPU is what found that: drawn with a ramp, the line through world
240/// `x = 0` was missing from a top-down frame while the one through `x = 2` was
241/// not.
242#[must_use]
243pub fn line_coverage(cell: f32, derivative: f32, line_width: f32) -> f32 {
244 // `fract` in the shader's sense — `x - floor(x)`, so this is the distance
245 // to the nearest integer cell boundary in `0..=0.5` for a negative
246 // coordinate too.
247 let offset = cell - 0.5;
248 let to_line = (offset - offset.floor() - 0.5).abs() / derivative.max(DERIVATIVE_FLOOR);
249 (line_width * 0.5 + 0.5 - to_line).clamp(0.0, 1.0)
250}
251
252/// How much of one scale survives once its lines start to merge, in `0..=1`.
253///
254/// A line `line_width` pixels across covers `line_width * derivative` of every
255/// cell, so once that reaches one the lines have joined into a sheet. The scale
256/// is faded out over the upper half of that range, which is what keeps the
257/// horizon from turning into aliased grey mush.
258#[must_use]
259pub fn resolvable(derivative: f32, line_width: f32) -> f32 {
260 (2.0 * (1.0 - line_width * derivative)).clamp(0.0, 1.0)
261}
262
263/// Coverage of one grid scale, in `0..=1`.
264///
265/// `cell` and `derivative` are per-axis, in the units [`line_coverage`]
266/// documents. The two axes are combined with `max` rather than added: a pixel
267/// on a crossing is on one line, not on two, and adding would draw a bright dot
268/// at every intersection.
269#[must_use]
270pub fn scale_coverage(cell: Vec2, derivative: Vec2, line_width: f32) -> f32 {
271 let coverage = line_coverage(cell.x, derivative.x, line_width).max(line_coverage(
272 cell.y,
273 derivative.y,
274 line_width,
275 ));
276 coverage * resolvable(derivative.x.max(derivative.y), line_width)
277}
278
279/// How much of the grid is left at `distance`, in `0..=1`.
280///
281/// Linear to zero at [`GridStyle::fade_distance`], so the grid has no edge for
282/// a camera to fly past and the horizon — where [`resolvable`] is already
283/// falling — has nothing left to alias.
284#[must_use]
285pub fn distance_fade(distance: f32, fade_distance: f32) -> f32 {
286 (1.0 - distance / fade_distance).clamp(0.0, 1.0)
287}
288
289/// The two scales composited into one **premultiplied** RGBA fragment.
290///
291/// The coarse lines go over the fine ones, and the pair is resolved here rather
292/// than by two draws — so what the blender receives is already `colour * alpha`
293/// and `crcbl_hal::BlendState::premultiplied` has nothing left to multiply.
294#[must_use]
295pub fn composite(style: &GridStyle, fine: f32, coarse: f32, fade: f32) -> [f32; 4] {
296 let coarse_alpha = style.coarse_color[3] * coarse * fade;
297 let fine_alpha = style.fine_color[3] * fine * fade * (1.0 - coarse_alpha);
298 [
299 style.coarse_color[0] * coarse_alpha + style.fine_color[0] * fine_alpha,
300 style.coarse_color[1] * coarse_alpha + style.fine_color[1] * fine_alpha,
301 style.coarse_color[2] * coarse_alpha + style.fine_color[2] * fine_alpha,
302 coarse_alpha + fine_alpha,
303 ]
304}
305
306/// The uniform block `grid.slang` declares, as the bytes its buffer holds.
307///
308/// Both matrices are **column-major**, the order `glam::Mat4::to_cols_array`
309/// produces and the order every other block this crate writes is in — see
310/// `crcbl_shaders::ssao::SsaoParams`, whose `proj` pair these two are siblings
311/// of.
312fn params_bytes(inv_view_proj: Mat4, view_proj: Mat4, style: &GridStyle) -> [u8; PARAMS_SIZE] {
313 let mut bytes = [0u8; PARAMS_SIZE];
314 let mut at = 0;
315 let rows = [
316 style.spacing,
317 style.coarse_multiple,
318 style.line_width,
319 style.fade_distance,
320 ];
321 let values = inv_view_proj
322 .to_cols_array()
323 .into_iter()
324 .chain(view_proj.to_cols_array())
325 .chain(rows)
326 .chain(style.fine_color)
327 .chain(style.coarse_color);
328 for value in values {
329 bytes[at..at + 4].copy_from_slice(&value.to_le_bytes());
330 at += 4;
331 }
332 debug_assert_eq!(at, PARAMS_SIZE, "the block is written whole");
333 bytes
334}
335
336/// Everything the grid pass owns.
337///
338/// Built once by [`Grid::new`] and released by [`Grid::destroy`], which is the
339/// shape every other resource group in this crate has — see
340/// [`crate::ui_pass::UiRenderer`].
341#[derive(Debug)]
342pub struct Grid {
343 layout: BindGroupLayoutHandle,
344 pipeline_layout: PipelineLayoutHandle,
345 pipeline: GraphicsPipelineHandle,
346 /// `[frame]`: the uniform block. One per frame in flight for the frame
347 /// uniforms' reason exactly — the previous frame may still be reading last
348 /// frame's while this one is written.
349 uniforms: Vec<BufferHandle>,
350 /// `[frame]`: the group naming [`Grid::uniforms`], and nothing else.
351 ///
352 /// Built here rather than in the pass body, unlike [`crate::ssao`]'s: this
353 /// pass binds no graph transient, so there is no view that only exists once
354 /// a pass is running.
355 groups: Vec<BindGroupHandle>,
356 style: GridStyle,
357}
358
359impl Grid {
360 /// Builds the pipeline and the uniform ring.
361 ///
362 /// `target_format` is the colour attachment the grid blends over and
363 /// `depth_format` the depth attachment it is tested against; both are
364 /// pipeline state, so a caller that renders into a different pair needs a
365 /// different [`Grid`].
366 ///
367 /// # Errors
368 ///
369 /// [`HalError`] from any seam call. Everything created before the failure
370 /// is released, so a failed build leaks nothing.
371 pub fn new(
372 device: &dyn Device,
373 frames: usize,
374 target_format: Format,
375 depth_format: Format,
376 ) -> Result<Self, HalError> {
377 let mut rollback = Rollback::default();
378 match Self::build(device, frames, target_format, depth_format, &mut rollback) {
379 Ok(grid) => Ok(grid),
380 Err(error) => {
381 rollback.run(device);
382 Err(error)
383 }
384 }
385 }
386
387 /// The body of [`Grid::new`], recording what it has created into `rollback`
388 /// as it goes.
389 fn build(
390 device: &dyn Device,
391 frames: usize,
392 target_format: Format,
393 depth_format: Format,
394 rollback: &mut Rollback,
395 ) -> Result<Self, HalError> {
396 // One binding, and it is the whole interface: the pass samples nothing.
397 // The plane it draws is reconstructed per fragment out of the matrices
398 // in this block, which is what makes the grid infinite without a vertex
399 // buffer, a texture or a scene resource of any kind.
400 let entries = [BindGroupLayoutEntry {
401 binding: 0,
402 // `FRAGMENT` alone, which is where every read of the block is: the
403 // vertex stage generates three corners out of `SV_VertexID` and
404 // looks at nothing. Slang's Metal target still lists the buffer in
405 // the vertex entry point's signature, and `ssao.slang` — the other
406 // full-screen pass with a block — ships exactly that pairing.
407 visibility: ShaderStages::FRAGMENT,
408 kind: BindingKind::UniformBuffer { dynamic: false },
409 count: 1,
410 flags: BindingFlags::empty(),
411 }];
412 let desc = BindGroupLayoutDesc {
413 label: Some("grid"),
414 entries: &entries,
415 };
416 check_portable_storage_buffers(Some("grid"), &[&desc])?;
417 let layout = device.create_bind_group_layout(&desc)?;
418 rollback.bind_group_layouts.push(layout);
419
420 let set_layouts = [layout];
421 let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
422 label: Some("grid"),
423 bind_group_layouts: &set_layouts,
424 // No range at all, for [`crate::ui_pass`]'s reason: the block
425 // arrives through the bind group so that there is one code path on
426 // every backend, including the one with no push constants.
427 push_constants: None,
428 })?;
429 rollback.pipeline_layouts.push(pipeline_layout);
430
431 let mut uniforms = Vec::with_capacity(frames);
432 let mut groups = Vec::with_capacity(frames);
433 for _ in 0..frames {
434 let buffer = device.create_buffer(&BufferDesc {
435 label: Some("grid params"),
436 size: PARAMS_SIZE as u64,
437 usage: BufferUsage::UNIFORM,
438 memory: MemoryLocation::HostUpload,
439 })?;
440 rollback.buffers.push(buffer);
441 uniforms.push(buffer);
442 let group = device.create_bind_group(&BindGroupDesc {
443 label: Some("grid params"),
444 layout,
445 entries: &[BindGroupEntry {
446 binding: 0,
447 array_index: 0,
448 resource: BindingResource::whole_buffer(buffer),
449 }],
450 variable_count: None,
451 })?;
452 rollback.bind_groups.push(group);
453 groups.push(group);
454 }
455
456 // Entry points resolved before the module exists, for
457 // [`crate::ui_pass`]'s reason: a manifest that disagreed with the
458 // artifact would otherwise fail inside the descriptor literal, with the
459 // module already created and nothing holding it.
460 let vertex = entry(Stage::Vertex)?;
461 let fragment = entry(Stage::Fragment)?;
462 let module = device.create_shader_module(&ShaderModuleDesc {
463 label: Some(GRID.source()),
464 spirv: GRID.spirv(),
465 wgsl: GRID.wgsl(),
466 msl: GRID.msl(),
467 // A container per entry point, for the reason
468 // [`crate::forward`]'s mesh module gives.
469 dxil: &GRID.dxil_containers(),
470 })?;
471 let targets = [ColorTargetState {
472 format: target_format,
473 // **Premultiplied, not straight alpha.** `grid.slang` composites
474 // its two scales itself and emits `colour * alpha`, so the blender
475 // must not multiply again — see that file's header.
476 blend: Some(BlendState::premultiplied()),
477 write_mask: ColorWrites::ALL,
478 }];
479 let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
480 label: Some("grid"),
481 layout: pipeline_layout,
482 vertex: ShaderEntry {
483 module,
484 entry_point: vertex,
485 },
486 fragment: Some(ShaderEntry {
487 module,
488 entry_point: fragment,
489 }),
490 // The triangle is deliberately oversized, so two of its vertices
491 // are outside the viewport and its winding is not worth reasoning
492 // about.
493 primitive: PrimitiveState::default(),
494 depth_stencil: Some(DepthStencilState {
495 format: depth_format,
496 // **Tested, never written.** The grid is chrome: geometry in
497 // front of it must hide it, and it must not hide anything drawn
498 // after it — which is what a depth write would do.
499 depth_write: false,
500 // `Greater` and not `GreaterOrEqual`, unlike a pass drawing
501 // against its own prepass: this pass has no prepass entry, so
502 // equality here is the grid landing exactly on a surface the
503 // scene already drew, and the scene wins.
504 depth_compare: CompareOp::Greater,
505 stencil: None,
506 bias: DepthBias::default(),
507 }),
508 multisample: MultisampleState::default(),
509 color_targets: &targets,
510 });
511 device.destroy_shader_module(module);
512 let pipeline = pipeline?;
513 rollback.pipelines.push(pipeline);
514
515 Ok(Self {
516 layout,
517 pipeline_layout,
518 pipeline,
519 uniforms,
520 groups,
521 style: GridStyle::default(),
522 })
523 }
524
525 /// How the grid is drawn.
526 #[must_use]
527 pub const fn style(&self) -> &GridStyle {
528 &self.style
529 }
530
531 /// Replaces [`Grid::style`]. Takes effect on the next
532 /// [`Grid::add_pass`], which is what writes the block.
533 pub const fn set_style(&mut self, style: GridStyle) {
534 self.style = style;
535 }
536
537 /// Adds the `grid` pass to `graph`, blending over `target` and tested
538 /// against `depth`.
539 ///
540 /// `depth` must be the depth the scene was drawn into and must still hold
541 /// it — the pass attaches it read-only, so it is neither cleared nor
542 /// written and a later pass sees exactly what the scene left. `target` is
543 /// loaded rather than cleared for the same reason: the grid blends over
544 /// what is already there.
545 ///
546 /// `inv_view_proj` is the camera's inverse view-projection, which is the
547 /// camera fact the fragment stage builds its ray from: it unprojects two
548 /// clip-space points per pixel to get that pixel's view ray. `view_proj` is
549 /// the ordinary one, and it travels in the block beside it because the
550 /// fragment stage has to project its plane hit back to the `SV_Depth` it is
551 /// tested at — and no shader can invert a matrix.
552 ///
553 /// **Both are taken rather than one derived from the other.** Every caller
554 /// is drawing a frame it already has a view-projection for, and a
555 /// [`Mat4::inverse`] per frame to recover a matrix the caller was holding is
556 /// arithmetic for nothing.
557 ///
558 /// # Panics
559 ///
560 /// If `frame` is not a slot this was built with.
561 pub fn add_pass<'a>(
562 &'a self,
563 graph: &mut RenderGraph<'a>,
564 frame: usize,
565 target: ImageId,
566 depth: ImageId,
567 view_proj: Mat4,
568 inv_view_proj: Mat4,
569 ) {
570 let pipeline = self.pipeline;
571 let pipeline_layout = self.pipeline_layout;
572 let group = self.groups[frame];
573 let uniforms = self.uniforms[frame];
574 let bytes = params_bytes(inv_view_proj, view_proj, &self.style);
575
576 graph
577 .add_render_pass("grid")
578 .color(target, LoadOp::Load, StoreOp::Store, Default::default())
579 // Read-only: attached so the hardware depth test runs, and declared
580 // this way so the graph moves it to a depth-read state rather than
581 // to one that would let this pass write it.
582 .depth_read(depth)
583 .execute(move |ctx| {
584 // A host-visible write, not a command: it lands before this
585 // frame is submitted, and the buffer is one of the ring, so the
586 // rotation that makes any other per-frame block safe makes this
587 // safe.
588 if let Err(error) = ctx.device().write_buffer(uniforms, 0, &bytes) {
589 // Recording a pass that draws nothing beats aborting the
590 // frame, as everywhere else in this crate: the grid
591 // vanishes for a frame, the log says why, the next frame
592 // retries.
593 crcbl_core::log::error!("graph: grid params write failed: {error}");
594 return;
595 }
596 let encoder = ctx.encoder();
597 encoder.bind_graphics_pipeline(pipeline);
598 encoder.bind_group(0, group, &[], pipeline_layout);
599 encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
600 });
601 }
602
603 /// Releases everything, in dependency order. The device must be idle.
604 pub fn destroy(self, device: &dyn Device) {
605 for group in self.groups {
606 device.destroy_bind_group(group);
607 }
608 for buffer in self.uniforms {
609 device.destroy_buffer(buffer);
610 }
611 device.destroy_graphics_pipeline(self.pipeline);
612 device.destroy_pipeline_layout(self.pipeline_layout);
613 device.destroy_bind_group_layout(self.layout);
614 }
615}
616
617/// `grid.slang`'s entry point for `stage`.
618fn entry(stage: Stage) -> Result<&'static str, HalError> {
619 GRID.entry_point(stage).ok_or_else(|| {
620 HalError::ShaderCompilation(format!(
621 "grid.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V and \
622 its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix"
623 ))
624 })
625}
626
627/// What a partly-built [`Grid`] has to give back.
628///
629/// [`Grid::build`] creates a handful of objects with `?` between them and the
630/// seam's `destroy_*` is explicit, so a failure half way through would
631/// otherwise leak everything created before it. [`crate::ui_pass`] carries the
632/// same shape for the same reason.
633#[derive(Default)]
634struct Rollback {
635 buffers: Vec<BufferHandle>,
636 bind_groups: Vec<BindGroupHandle>,
637 bind_group_layouts: Vec<BindGroupLayoutHandle>,
638 pipeline_layouts: Vec<PipelineLayoutHandle>,
639 pipelines: Vec<GraphicsPipelineHandle>,
640}
641
642impl Rollback {
643 /// Releases everything recorded, in dependency order.
644 fn run(self, device: &dyn Device) {
645 for group in self.bind_groups {
646 device.destroy_bind_group(group);
647 }
648 for buffer in self.buffers {
649 device.destroy_buffer(buffer);
650 }
651 for pipeline in self.pipelines {
652 device.destroy_graphics_pipeline(pipeline);
653 }
654 for layout in self.pipeline_layouts {
655 device.destroy_pipeline_layout(layout);
656 }
657 for layout in self.bind_group_layouts {
658 device.destroy_bind_group_layout(layout);
659 }
660 }
661}
662
663// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
664#[cfg(all(test, not(target_arch = "wasm32")))]
665mod tests {
666 use super::*;
667
668 /// A style derived for a subject keeps a countable cell and reaches past it.
669 ///
670 /// The two properties that matter, at four scales spanning ten orders of
671 /// magnitude: the cell is a power of ten (so the grid is something a person
672 /// can count in), and the model spans a sane number of cells rather than
673 /// sitting inside one or drowning in them.
674 #[test]
675 fn a_derived_style_keeps_a_power_of_ten_cell_at_any_scale() {
676 for extent in [0.05f32, 1.0, 12.0, 500.0, 20_000.0] {
677 let style = GridStyle::for_extent(extent);
678
679 let decades = style.spacing.log10();
680 assert!(
681 (decades - decades.round()).abs() < 1e-4,
682 "a {extent} m subject chose a {} m cell, which is not a power of ten and so is \
683 not a number anyone can count in",
684 style.spacing
685 );
686
687 let across = extent / style.spacing;
688 assert!(
689 (1.0..=100.0).contains(&across),
690 "a {extent} m subject spans {across} cells of {} m — outside the range where the \
691 grid says anything about its scale",
692 style.spacing
693 );
694 assert!(
695 style.fade_distance > extent,
696 "a {extent} m subject fades at {}, so the ground would end inside the model",
697 style.fade_distance
698 );
699 }
700 }
701
702 /// A scale-less subject falls back rather than computing a `log10` of zero.
703 ///
704 /// `for_extent` is fed a bounding box, and a document can produce a
705 /// degenerate one — a single point, or the empty scene the viewer refuses
706 /// only *after* it has framed. Zero would give `-inf` and a `NaN` spacing,
707 /// which is a grid that never draws and never says why.
708 #[test]
709 fn a_degenerate_extent_falls_back_to_the_default_style() {
710 for extent in [0.0f32, -3.0, f32::NAN, f32::INFINITY] {
711 let style = GridStyle::for_extent(extent);
712 assert_eq!(
713 style.spacing,
714 GridStyle::default().spacing,
715 "an extent of {extent} should fall back, not derive"
716 );
717 assert!(style.spacing.is_finite() && style.fade_distance.is_finite());
718 }
719 }
720
721 use crcbl_hal::null::{NullInstance, Recorder};
722 use crcbl_hal::{
723 CommandEncoderDesc, DeviceDesc, Features, ImageUsage, Instance, QueueHandle, QueueKind,
724 ResourceState,
725 };
726
727 use crate::transient::{TransientImageDesc, TransientPool};
728
729 /// The source the artifacts in `crcbl-shaders` were built from — the
730 /// manifest hash-pins it, so this is the same file, and reading it is how
731 /// the mirrors below are checked at all.
732 const SOURCE: &str = include_str!("../../crcbl-shaders/shaders/grid.slang");
733
734 fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
735 let recorder = Recorder::new();
736 let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
737 let adapter = instance.adapters().remove(0);
738 let device = instance
739 .create_device(&DeviceDesc {
740 label: None,
741 adapter: adapter.id,
742 required_features: Features::GPU_DRIVEN,
743 optional_features: Features::PUSH_CONSTANTS,
744 compatible_surface: None,
745 })
746 .expect("the null backend always opens");
747 let queue = device.queue(QueueKind::Graphics).expect("always present");
748 (recorder, device, queue)
749 }
750
751 // -----------------------------------------------------------------------
752 // The plane
753 // -----------------------------------------------------------------------
754
755 /// Straight down from two metres up is two metres of ray.
756 #[test]
757 fn the_hit_is_the_distance_along_a_unit_direction() {
758 let hit = plane_hit(Vec3::new(0.0, 2.0, 0.0), Vec3::new(0.0, -1.0, 0.0));
759 assert_eq!(hit, Some(2.0));
760
761 // Forty-five degrees down, looking along −Z: the hypotenuse of a
762 // one-metre drop.
763 let diagonal = Vec3::new(0.0, -1.0, -1.0).normalize();
764 let hit = plane_hit(Vec3::new(0.0, 1.0, 0.0), diagonal).expect("it crosses");
765 assert!(
766 (hit - 2.0f32.sqrt()).abs() < 1e-6,
767 "a 45° ray from 1 m up travels √2 m to the ground, not {hit}"
768 );
769 }
770
771 /// A ray with no vertical component never reaches the ground.
772 #[test]
773 fn a_ray_parallel_to_the_ground_never_hits_it() {
774 assert_eq!(
775 plane_hit(Vec3::new(0.0, 5.0, 0.0), Vec3::new(0.0, 0.0, -1.0)),
776 None
777 );
778 // Just inside the epsilon, which is the boundary the shader shares.
779 assert_eq!(
780 plane_hit(
781 Vec3::new(0.0, 5.0, 0.0),
782 Vec3::new(0.0, PARALLEL_EPSILON * 0.5, -1.0)
783 ),
784 None
785 );
786 }
787
788 /// A camera above the ground looking up is looking away from it.
789 #[test]
790 fn a_plane_behind_the_camera_is_not_a_hit() {
791 assert_eq!(
792 plane_hit(Vec3::new(0.0, 2.0, 0.0), Vec3::new(0.0, 1.0, 0.0)),
793 None
794 );
795 // And a camera standing exactly on the plane: the hit is at zero
796 // distance, which is the fragment's own pixel and not a surface.
797 assert_eq!(
798 plane_hit(Vec3::ZERO, Vec3::new(0.0, -1.0, 0.0)),
799 None,
800 "a zero-distance hit is the camera itself"
801 );
802 }
803
804 // -----------------------------------------------------------------------
805 // Coverage
806 // -----------------------------------------------------------------------
807
808 /// **The claim the whole technique rests on.** Two cameras a hundred times
809 /// apart in zoom see the same line width, because coverage is a function of
810 /// the distance to the line *in pixels*.
811 #[test]
812 fn a_line_is_the_same_pixel_width_at_any_zoom() {
813 let width = 2.0;
814 for derivative in [0.001f32, 0.01, 0.1] {
815 // A pixel box centred half a width plus half a pixel out overlaps
816 // the band by nothing: that is the last pixel the line reaches.
817 let edge = derivative * (width * 0.5 + 0.5);
818 let coverage = line_coverage(edge, derivative, width);
819 assert!(
820 coverage < 1e-4,
821 "at {derivative} cells/px the line's edge read {coverage}"
822 );
823 // Half a width out, the box straddles the band's edge and takes
824 // half of it — whatever the zoom.
825 let half = derivative * width * 0.5;
826 let coverage = line_coverage(half, derivative, width);
827 assert!(
828 (coverage - 0.5).abs() < 1e-4,
829 "at {derivative} cells/px the half-covered point read {coverage}"
830 );
831 // And the line itself is solid.
832 assert_eq!(line_coverage(0.0, derivative, width), 1.0, "{derivative}");
833 }
834 }
835
836 /// **What a real GPU found.** A hairline landing exactly on a pixel
837 /// boundary must still be drawn: the two pixels either side take half each,
838 /// rather than both taking nothing.
839 ///
840 /// The coverage a line puts on screen is the same wherever it lands between
841 /// two pixel centres, which is what stops a one-pixel grid dropping and
842 /// regaining whole lines as the camera moves.
843 #[test]
844 fn a_hairline_on_a_pixel_boundary_is_still_drawn() {
845 // One cell per hundred pixels, and a one-pixel line.
846 let (derivative, width) = (0.01f32, 1.0);
847 // The line exactly on a pixel *centre*: that pixel takes all of it and
848 // its neighbours none.
849 let centred: f32 = [-1.0f32, 0.0, 1.0]
850 .into_iter()
851 .map(|pixel| line_coverage(pixel * derivative, derivative, width))
852 .sum();
853 // The line exactly on a pixel *boundary*: the two either side halve it.
854 let straddling: f32 = [-1.5f32, -0.5, 0.5, 1.5]
855 .into_iter()
856 .map(|pixel| line_coverage(pixel * derivative, derivative, width))
857 .sum();
858 assert!(
859 line_coverage(0.5 * derivative, derivative, width) > 0.0,
860 "a line on a pixel boundary vanished"
861 );
862 assert!(
863 (centred - straddling).abs() < 1e-4,
864 "the same line put {centred} on screen at a pixel centre and {straddling} at a \
865 boundary; it would flicker as the camera moves"
866 );
867 }
868
869 /// The lines repeat every cell, and `floor` rather than a truncation is
870 /// what makes that true on the negative side of the origin.
871 #[test]
872 fn the_lines_repeat_on_both_sides_of_the_origin() {
873 let (derivative, width) = (0.01f32, 1.0);
874 for cell in [-3.0f32, -1.0, 0.0, 1.0, 7.0] {
875 assert_eq!(
876 line_coverage(cell, derivative, width),
877 1.0,
878 "cell boundary {cell} is a line"
879 );
880 }
881 for cell in [-2.5f32, -0.5, 0.5, 6.5] {
882 assert_eq!(
883 line_coverage(cell, derivative, width),
884 0.0,
885 "cell centre {cell} is not a line"
886 );
887 }
888 }
889
890 /// A scale whose lines have merged into a sheet contributes nothing, which
891 /// is what stops the horizon aliasing.
892 #[test]
893 fn a_scale_stops_once_its_lines_have_merged() {
894 let width = 1.0;
895 // A pixel spanning a whole cell: the lines are continuous, and the
896 // scale is gone.
897 assert_eq!(resolvable(1.0, width), 0.0);
898 // Half a cell per pixel — a line covering half of every cell — is
899 // where the fade starts, and it is half way down at three quarters.
900 assert_eq!(resolvable(0.5, width), 1.0);
901 assert_eq!(resolvable(0.75, width), 0.5);
902 // A cell far wider than a pixel is untouched.
903 assert_eq!(resolvable(0.001, width), 1.0);
904
905 // It is the *product* that decides, so a wider line merges sooner: two
906 // pixels of line in a two-pixel cell is the same sheet.
907 assert_eq!(resolvable(0.5, 2.0), 0.0);
908 }
909
910 /// The density term is applied, not merely computed: a coverage of 1 at a
911 /// derivative past the merge point still comes out as nothing.
912 #[test]
913 fn scale_coverage_applies_the_density_term() {
914 let width = 1.0;
915 let on_a_line = Vec2::ZERO;
916 assert_eq!(
917 scale_coverage(on_a_line, Vec2::splat(0.001), width),
918 1.0,
919 "a resolvable line is fully covered"
920 );
921 assert_eq!(
922 scale_coverage(on_a_line, Vec2::splat(1.0), width),
923 0.0,
924 "a merged scale draws nothing even on a line"
925 );
926 }
927
928 /// The axes combine with `max`, so a crossing is no brighter than a line.
929 #[test]
930 fn a_crossing_is_no_brighter_than_a_line() {
931 let (derivative, width) = (Vec2::splat(0.01), 1.0);
932 let on_one_line = scale_coverage(Vec2::new(0.0, 0.5), derivative, width);
933 let on_a_crossing = scale_coverage(Vec2::ZERO, derivative, width);
934 assert_eq!(on_a_crossing, on_one_line);
935 }
936
937 // -----------------------------------------------------------------------
938 // Fade and composite
939 // -----------------------------------------------------------------------
940
941 /// The fade is a ramp to nothing at the fade distance, with no edge past
942 /// it.
943 #[test]
944 fn the_fade_reaches_zero_at_the_fade_distance() {
945 assert_eq!(distance_fade(0.0, 100.0), 1.0);
946 assert_eq!(distance_fade(50.0, 100.0), 0.5);
947 assert_eq!(distance_fade(100.0, 100.0), 0.0);
948 assert_eq!(distance_fade(1000.0, 100.0), 0.0);
949 }
950
951 /// The fragment is premultiplied: every channel is inside its own alpha, so
952 /// `src + dst * (1 - a)` composites it correctly.
953 #[test]
954 fn the_composite_is_premultiplied() {
955 let style = GridStyle::default();
956 for (fine, coarse, fade) in [
957 (1.0f32, 1.0f32, 1.0f32),
958 (1.0, 0.0, 1.0),
959 (0.0, 1.0, 0.5),
960 (0.4, 0.7, 0.9),
961 ] {
962 let [r, g, b, a] = composite(&style, fine, coarse, fade);
963 assert!((0.0..=1.0).contains(&a), "alpha {a} left 0..=1");
964 for channel in [r, g, b] {
965 assert!(
966 channel <= a + 1e-6,
967 "channel {channel} exceeds its own alpha {a}, so it is not premultiplied"
968 );
969 }
970 }
971 // Nothing covered is nothing drawn — the fragment the shader discards.
972 assert_eq!(composite(&style, 0.0, 0.0, 1.0), [0.0, 0.0, 0.0, 0.0]);
973 assert_eq!(composite(&style, 1.0, 1.0, 0.0), [0.0, 0.0, 0.0, 0.0]);
974 }
975
976 /// The coarse lines go over the fine ones: where both are covered, the
977 /// result is the coarse colour's, not a sum brighter than either.
978 #[test]
979 fn the_coarse_lines_composite_over_the_fine_ones() {
980 let style = GridStyle {
981 fine_color: [1.0, 0.0, 0.0, 1.0],
982 coarse_color: [0.0, 1.0, 0.0, 1.0],
983 ..GridStyle::default()
984 };
985 // Both fully covered, and the coarse scale is opaque: the fine lines
986 // are entirely hidden.
987 assert_eq!(composite(&style, 1.0, 1.0, 1.0), [0.0, 1.0, 0.0, 1.0]);
988 // Half-opaque coarse lines let exactly half the fine ones through.
989 let style = GridStyle {
990 coarse_color: [0.0, 1.0, 0.0, 0.5],
991 ..style
992 };
993 assert_eq!(composite(&style, 1.0, 1.0, 1.0), [0.5, 0.5, 0.0, 1.0]);
994 }
995
996 // -----------------------------------------------------------------------
997 // The block, and the shader it mirrors
998 // -----------------------------------------------------------------------
999
1000 /// The block the shader declares, member for member and in this order.
1001 ///
1002 /// The offsets [`params_bytes`] writes are what make this the check that
1003 /// the *shader* agrees about which matrix comes first — swapping them
1004 /// produces a grid drawn in a camera nobody is looking through, which is
1005 /// still a picture.
1006 #[test]
1007 fn the_uniform_block_matches_the_struct_grid_slang_declares() {
1008 let declarations = [
1009 "float4x4 inv_view_proj;",
1010 "float4x4 view_proj;",
1011 "float4 params;",
1012 "float4 fine_color;",
1013 "float4 coarse_color;",
1014 ];
1015 let mut last = 0;
1016 for declaration in declarations {
1017 let at = SOURCE
1018 .find(declaration)
1019 .unwrap_or_else(|| panic!("grid.slang does not declare `{declaration}`"));
1020 assert!(
1021 at > last,
1022 "grid.slang declares `{declaration}` in a different order than params_bytes \
1023 writes it"
1024 );
1025 last = at;
1026 }
1027 }
1028
1029 /// The constants the two halves share, checked against the shader text.
1030 ///
1031 /// Nothing else can catch a drift here: the shader compiles either way, and
1032 /// a mismatch shows up only as a grid that behaves differently from the one
1033 /// these tests describe.
1034 #[test]
1035 fn the_constants_match_the_ones_grid_slang_declares() {
1036 for declaration in [
1037 format!("static const float PARALLEL_EPSILON = {PARALLEL_EPSILON:e};"),
1038 format!("static const float DERIVATIVE_FLOOR = {DERIVATIVE_FLOOR:e};"),
1039 ] {
1040 assert!(
1041 SOURCE.contains(&declaration),
1042 "grid.slang does not declare `{declaration}`"
1043 );
1044 }
1045 }
1046
1047 /// The depth the shader unprojects its ray origin at is the seam's near
1048 /// plane.
1049 ///
1050 /// Reversed-Z sends the far plane to `w = 0`, so unprojecting there divides
1051 /// by nothing — the near plane is the end of the ray that is always safe,
1052 /// and it is only the near plane while `depth::NEAR` says so.
1053 #[test]
1054 fn the_ray_origin_is_unprojected_at_the_seams_near_plane() {
1055 let declaration = format!(
1056 "static const float NEAR_DEPTH = {:.1};",
1057 crcbl_hal::depth::NEAR
1058 );
1059 assert!(
1060 SOURCE.contains(&declaration),
1061 "grid.slang does not declare `{declaration}`"
1062 );
1063 }
1064
1065 /// The block is two matrices and three rows, in that order, little-endian.
1066 #[test]
1067 fn the_block_is_two_matrices_and_three_rows() {
1068 let style = GridStyle {
1069 spacing: 2.0,
1070 coarse_multiple: 5.0,
1071 line_width: 3.0,
1072 fade_distance: 7.0,
1073 fine_color: [0.1, 0.2, 0.3, 0.4],
1074 coarse_color: [0.5, 0.6, 0.7, 0.8],
1075 };
1076 let bytes = params_bytes(Mat4::IDENTITY, Mat4::from_scale(Vec3::splat(2.0)), &style);
1077
1078 assert_eq!(bytes.len(), PARAMS_SIZE);
1079 assert_eq!(&bytes[0..4], &1.0f32.to_le_bytes(), "inv_view_proj[0][0]");
1080 assert_eq!(&bytes[64..68], &2.0f32.to_le_bytes(), "view_proj[0][0]");
1081 assert_eq!(&bytes[128..132], &2.0f32.to_le_bytes(), "spacing");
1082 assert_eq!(&bytes[132..136], &5.0f32.to_le_bytes(), "coarse_multiple");
1083 assert_eq!(&bytes[136..140], &3.0f32.to_le_bytes(), "line_width");
1084 assert_eq!(&bytes[140..144], &7.0f32.to_le_bytes(), "fade_distance");
1085 assert_eq!(&bytes[144..148], &0.1f32.to_le_bytes(), "fine_color.r");
1086 assert_eq!(&bytes[160..164], &0.5f32.to_le_bytes(), "coarse_color.r");
1087 assert_eq!(&bytes[172..176], &0.8f32.to_le_bytes(), "coarse_color.a");
1088 }
1089
1090 // -----------------------------------------------------------------------
1091 // The pass
1092 // -----------------------------------------------------------------------
1093
1094 /// **The pass writes the two matrices the way round its arguments say.**
1095 ///
1096 /// The block's own layout is [`the_block_is_two_matrices_and_three_rows`]'s
1097 /// and the shader's is
1098 /// [`the_uniform_block_matches_the_struct_grid_slang_declares`]'s; what
1099 /// neither can see is the one line inside [`Grid::add_pass`] that hands them
1100 /// to [`params_bytes`]. Swapped there, the grid is drawn through a camera
1101 /// nobody is looking through — which is still a picture, and still passes
1102 /// every other test in this file.
1103 ///
1104 /// So this runs the recorded pass body and reads the uniform buffer back off
1105 /// the null recorder, which is the only place in the tree that keeps what a
1106 /// host write put in one.
1107 #[test]
1108 fn the_pass_writes_the_inverse_first_and_the_forward_matrix_second() {
1109 let (recorder, device, queue) = open();
1110 let device = device.as_ref();
1111 let grid = Grid::new(device, 1, Format::Rgba16Float, Format::D32Float)
1112 .expect("the null backend builds every pipeline");
1113
1114 // Two matrices that are each other's inverse and are plainly not equal,
1115 // so reading one where the other belongs cannot pass by coincidence.
1116 let view_proj = Mat4::from_scale_rotation_translation(
1117 Vec3::new(1.5, 0.75, 2.0),
1118 glam::Quat::from_rotation_y(0.7),
1119 Vec3::new(3.0, -2.0, 11.0),
1120 );
1121 let inv_view_proj = view_proj.inverse();
1122
1123 let mut pool = TransientPool::new();
1124 let mut graph = RenderGraph::new(queue);
1125 let color = graph.create_image(
1126 "scene-color",
1127 TransientImageDesc::new(
1128 (64, 48),
1129 Format::Rgba16Float,
1130 ImageUsage::COLOR_ATTACHMENT | ImageUsage::SAMPLED,
1131 ),
1132 );
1133 let depth = graph.create_image(
1134 "scene-depth",
1135 TransientImageDesc::new(
1136 (64, 48),
1137 Format::D32Float,
1138 ImageUsage::DEPTH_STENCIL_ATTACHMENT | ImageUsage::SAMPLED,
1139 ),
1140 );
1141 grid.add_pass(&mut graph, 0, color, depth, view_proj, inv_view_proj);
1142
1143 let compiled = graph.compile(&pool).expect("the graph compiles");
1144 let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
1145 label: Some("grid block"),
1146 queue,
1147 });
1148 compiled
1149 .execute(device, &mut pool, encoder.as_mut(), None)
1150 .expect("the graph executed");
1151
1152 let written = recorder
1153 .buffer_bytes(grid.uniforms[0])
1154 .expect("the pass body wrote the block");
1155 assert_eq!(
1156 &written[..64],
1157 &inv_view_proj
1158 .to_cols_array()
1159 .iter()
1160 .flat_map(|value| value.to_le_bytes())
1161 .collect::<Vec<u8>>()[..],
1162 "the inverse view-projection is the block's first member",
1163 );
1164 assert_eq!(
1165 &written[64..128],
1166 &view_proj
1167 .to_cols_array()
1168 .iter()
1169 .flat_map(|value| value.to_le_bytes())
1170 .collect::<Vec<u8>>()[..],
1171 "the forward view-projection is the block's second member",
1172 );
1173
1174 drop(encoder);
1175 grid.destroy(device);
1176 pool.destroy(device);
1177 }
1178
1179 /// The pass attaches the colour target and reads the depth without writing
1180 /// it — which is the whole of what "occluded by the scene, invisible to it"
1181 /// means at the graph level.
1182 #[test]
1183 fn the_pass_loads_its_target_and_only_reads_depth() {
1184 let (_recorder, device, queue) = open();
1185 let grid = Grid::new(device.as_ref(), 2, Format::Rgba16Float, Format::D32Float)
1186 .expect("the null backend builds every pipeline");
1187
1188 let mut pool = TransientPool::new();
1189 let mut graph = RenderGraph::new(queue);
1190 let color = graph.create_image(
1191 "scene-color",
1192 TransientImageDesc::new(
1193 (64, 48),
1194 Format::Rgba16Float,
1195 ImageUsage::COLOR_ATTACHMENT | ImageUsage::SAMPLED,
1196 ),
1197 );
1198 let depth = graph.create_image(
1199 "scene-depth",
1200 TransientImageDesc::new(
1201 (64, 48),
1202 Format::D32Float,
1203 ImageUsage::DEPTH_STENCIL_ATTACHMENT | ImageUsage::SAMPLED,
1204 ),
1205 );
1206 grid.add_pass(&mut graph, 0, color, depth, Mat4::IDENTITY, Mat4::IDENTITY);
1207
1208 let compiled = graph.compile(&pool).expect("the graph compiles");
1209 assert_eq!(compiled.passes().len(), 1);
1210 let barriers = compiled.passes()[0].barriers();
1211 let depth_barrier = barriers
1212 .images
1213 .iter()
1214 .find(|barrier| barrier.to == ResourceState::DepthStencilRead)
1215 .expect("the depth image is attached read-only");
1216 assert_eq!(depth_barrier.to, ResourceState::DepthStencilRead);
1217 assert!(
1218 barriers
1219 .images
1220 .iter()
1221 .all(|barrier| barrier.to != ResourceState::DepthStencilWrite),
1222 "the grid must never take a writable depth attachment"
1223 );
1224
1225 drop(compiled);
1226 grid.destroy(device.as_ref());
1227 pool.destroy(device.as_ref());
1228 }
1229
1230 /// Every frame slot gets its own block and its own group, so a frame in
1231 /// flight cannot have last frame's camera overwritten under it.
1232 #[test]
1233 fn the_block_is_a_ring() {
1234 let (_recorder, device, _queue) = open();
1235 let grid = Grid::new(device.as_ref(), 3, Format::Rgba16Float, Format::D32Float)
1236 .expect("the null backend builds every pipeline");
1237 assert_eq!(grid.uniforms.len(), 3);
1238 assert_eq!(grid.groups.len(), 3);
1239 for (slot, buffer) in grid.uniforms.iter().enumerate() {
1240 for other in &grid.uniforms[slot + 1..] {
1241 assert_ne!(buffer, other, "two frames share a block");
1242 }
1243 }
1244 for (slot, group) in grid.groups.iter().enumerate() {
1245 for other in &grid.groups[slot + 1..] {
1246 assert_ne!(group, other, "two frames share a group");
1247 }
1248 }
1249 grid.destroy(device.as_ref());
1250 }
1251
1252 /// The style is what the block carries, so setting it is visible in the
1253 /// bytes rather than only in the field.
1254 #[test]
1255 fn the_style_reaches_the_block() {
1256 let (_recorder, device, _queue) = open();
1257 let mut grid = Grid::new(device.as_ref(), 1, Format::Rgba16Float, Format::D32Float)
1258 .expect("the null backend builds every pipeline");
1259 assert_eq!(grid.style().spacing, 1.0);
1260 grid.set_style(GridStyle {
1261 spacing: 0.25,
1262 ..GridStyle::default()
1263 });
1264 let bytes = params_bytes(Mat4::IDENTITY, Mat4::IDENTITY, grid.style());
1265 assert_eq!(&bytes[128..132], &0.25f32.to_le_bytes());
1266 grid.destroy(device.as_ref());
1267 }
1268}