crcbl_render/light_grid.rs
1//! The light list and the froxel grid a compute pass assigns it to.
2//!
3//! ```text
4//! begin_frame ──▶ light rows (host) ──▶ lights[frame]
5//! ──▶ grid extent + camera ──▶ params[frame]
6//!
7//! add_pass ──── compute "light-cluster" lights ──▶ grid[frame]
8//! ──▶ cull stats (overflow)
9//! │ graph barrier
10//! the caller's render pass ◀────┘ ShaderRead
11//! ```
12//!
13//! Topic 44's clustered forward (`docs/notes/rendering.md`), on the same
14//! discipline as [`crate::draw_gen`]: a compute pass produces a compacted list,
15//! the draw reads it, the CPU uploads deltas and nothing else.
16//!
17//! # The grid is device-local, and that is a seam rule rather than a preference
18//!
19//! A shader writes it, so it cannot live on an upload heap: D3D12 has no
20//! unordered-access view of an upload-heap resource at all — the flag is
21//! rejected at creation and the heap pins the resource to `GENERIC_READ` for its
22//! lifetime. [`crate::draw_gen`]'s module docs carry the full account and the
23//! device it took down twice. The **light list** is host-uploaded and bound
24//! read-only, which none of that applies to.
25//!
26//! # Overflow is a word of the culling statistics, not a buffer of its own
27//!
28//! `light_cluster.slang` adds every assignment its budget refused into
29//! [`CLUSTER_OVERFLOW_WORD`](crcbl_shaders::light::CLUSTER_OVERFLOW_WORD), which is the third word of the buffer
30//! `cull.slang` counts survivors into. Topic 03 §3.6 allows the frame loop one
31//! readback and that buffer is it; a counter of its own would be a second one to
32//! zero, to barrier and to copy back every frame. `clear_counters.slang` already
33//! zeroes the whole buffer because it is *told* how many words it has.
34//!
35//! # How large the grid gets, and what happens past that
36//!
37//! [`FROXEL_CAPACITY`] froxels are reserved at start-up, which is enough for a
38//! 4K frame at every depth slice. A frame whose tiles alone would not fit gets
39//! **coarser tiles** — the tile size is a per-frame number in the frame block
40//! rather than a constant, and [`Grid::for_frame`] doubles it until the grid
41//! fits — so a very large viewport is clustered less finely rather than writing
42//! off the end of a buffer. Slices are traded away first, tiles second, because
43//! losing depth resolution costs less than losing screen resolution.
44
45use crcbl_hal::{
46 BindGroupDesc, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutHandle, BufferDesc,
47 BufferHandle, BufferUsage, ComputePipelineHandle, Device, HalError, MemoryLocation,
48 PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, check_portable_storage_buffers,
49};
50use crcbl_shaders::light::{
51 self, CLUSTER_DEPTH_SLICES, CLUSTER_PARAMS_SIZE, CLUSTER_STRIDE, CLUSTER_TILE_PIXELS,
52 CLUSTER_WORKGROUP_SIZE, GpuLight, LIGHT_STRIDE,
53};
54use glam::{Mat4, Vec3};
55
56use crate::draw_gen::{UINT_STRIDE, bound, compute_pipeline, storage, uniform};
57use crate::graph::{BufferId, ImportedBuffer, RenderGraph};
58
59/// Froxels the grid buffer holds, and the ceiling [`Grid::for_frame`] fits a
60/// frame under.
61///
62/// Sixty-four thousand of them is 4.25 MB at [`CLUSTER_STRIDE`] words each. It
63/// covers a 3840×2160 frame at every one of [`CLUSTER_DEPTH_SLICES`] slices
64/// (60 × 34 × 24), and a 16384×16384 one — the largest image the engine will
65/// create — at one slice exactly (256 × 256). Between those, slices are given up
66/// before tiles are.
67pub const FROXEL_CAPACITY: u32 = 64 * 1024;
68
69/// The camera one frame's froxels are built around.
70///
71/// The four values arrive together because they are one camera's, and a
72/// clustering pass handed a view projection from one frame and an eye from
73/// another builds froxels no fragment is ever in — a failure that looks like
74/// lights switching off at tile boundaries.
75#[derive(Clone, Copy, Debug, PartialEq)]
76pub struct FrameView {
77 /// The viewport, in pixels.
78 pub extent: (u32, u32),
79 /// World → clip, the same matrix the frame draws with.
80 pub view_projection: Mat4,
81 /// World-space eye position.
82 pub eye: Vec3,
83 /// Whether the projection is a perspective one — see
84 /// [`Grid::for_frame`], which is where the two are told apart.
85 pub perspective: bool,
86}
87
88/// The extent of one frame's froxel grid.
89///
90/// Held together in one type because the four numbers are decided at once and
91/// are read by two shaders: writing three of them into the frame block and
92/// deriving the fourth somewhere else is how the clustering pass and the
93/// fragment stage would come to index different froxels.
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95pub struct Grid {
96 /// Froxels across the screen.
97 pub x: u32,
98 /// Froxels down the screen.
99 pub y: u32,
100 /// Depth slices: [`CLUSTER_DEPTH_SLICES`] for a perspective camera, `1` for
101 /// an orthographic one, and fewer than either where the grid would not fit.
102 pub slices: u32,
103 /// How many pixels wide and tall one tile is.
104 pub tile_pixels: u32,
105}
106
107impl Grid {
108 /// The grid for a viewport, under a froxel budget.
109 ///
110 /// `perspective` decides whether there is a depth split at all: an
111 /// orthographic camera's `clip.w` is `1` everywhere, so it has no view depth
112 /// for a slice index to come from, and it runs with one slice per tile
113 /// spanning its whole depth range. Coarser, correct, and stated — see
114 /// `light_cluster.slang`'s orthographic branch, which builds that froxel a
115 /// different way rather than pretending it is a perspective one.
116 #[must_use]
117 pub fn for_frame(extent: (u32, u32), perspective: bool, froxels: u32) -> Self {
118 let tiles = |tile: u32| {
119 (
120 extent.0.max(1).div_ceil(tile),
121 extent.1.max(1).div_ceil(tile),
122 )
123 };
124 // Coarsen until a single slice's worth of tiles fits. Terminates: the
125 // tile size doubles, so the count falls by four each round and reaches
126 // one, which fits any budget of at least one froxel.
127 let mut tile_pixels = CLUSTER_TILE_PIXELS.max(1);
128 let (mut x, mut y) = tiles(tile_pixels);
129 while x.saturating_mul(y) > froxels.max(1) {
130 tile_pixels = tile_pixels.saturating_mul(2);
131 (x, y) = tiles(tile_pixels);
132 }
133 let wanted = if perspective { CLUSTER_DEPTH_SLICES } else { 1 };
134 let slices = (froxels.max(1) / (x * y)).min(wanted).max(1);
135 Self {
136 x,
137 y,
138 slices,
139 tile_pixels,
140 }
141 }
142
143 /// How many froxels this grid has, which is the clustering dispatch's extent
144 /// and the number of records the pass writes.
145 #[must_use]
146 pub const fn froxels(&self) -> u32 {
147 self.x * self.y * self.slices
148 }
149
150 /// The four numbers as
151 /// [`FrameUniforms::cluster_grid`](crcbl_shaders::mesh::FrameUniforms::cluster_grid).
152 #[must_use]
153 pub const fn to_frame_block(&self) -> [u32; 4] {
154 [self.x, self.y, self.slices, self.tile_pixels]
155 }
156}
157
158/// How large a [`LightGrid`] is.
159#[derive(Clone, Copy, Debug)]
160pub struct LightGridDesc<'a> {
161 /// Debug name; every buffer is named after it.
162 pub label: Option<&'a str>,
163 /// How many frames in flight, and so how long every ring here is.
164 pub frames: usize,
165 /// Rows the light list holds.
166 pub lights: u32,
167 /// Froxels the grid holds, which is what [`Grid::for_frame`] is asked to fit
168 /// a frame under. [`FROXEL_CAPACITY`] unless a test wants a smaller one.
169 pub froxels: u32,
170 /// The culling-statistics ring the overflow counter is a word of — one
171 /// buffer per frame in flight, the one
172 /// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count) hands
173 /// out. Written by this pass and zeroed by the clearing dispatch that runs
174 /// ahead of it.
175 pub stats: &'a [BufferHandle],
176}
177
178/// The light list, the froxel grid, and the compute pass between them.
179#[derive(Debug)]
180pub struct LightGrid {
181 lights: Vec<BufferHandle>,
182 grid: Vec<BufferHandle>,
183 params: Vec<BufferHandle>,
184 groups: Vec<BindGroupHandle>,
185 layout: BindGroupLayoutHandle,
186 pipeline_layout: PipelineLayoutHandle,
187 pipeline: ComputePipelineHandle,
188 capacity: u32,
189 froxels: u32,
190}
191
192impl LightGrid {
193 /// Builds every buffer, the bind groups and the clustering pipeline.
194 ///
195 /// # Errors
196 ///
197 /// [`HalError`] if a resource could not be created, or if the descriptor
198 /// asks for a ring shorter than the statistics ring it was handed.
199 pub fn new(device: &dyn Device, desc: &LightGridDesc<'_>) -> Result<Self, HalError> {
200 if desc.frames == 0 || desc.lights == 0 || desc.froxels == 0 {
201 return Err(HalError::InvalidDescriptor(
202 "a light grid needs at least one frame in flight, one light row and one froxel"
203 .to_string(),
204 ));
205 }
206 if desc.stats.len() < desc.frames {
207 return Err(HalError::InvalidDescriptor(format!(
208 "a light grid over {} frames needs {} statistics buffers, got {}",
209 desc.frames,
210 desc.frames,
211 desc.stats.len()
212 )));
213 }
214 let label = desc.label.unwrap_or("lights");
215
216 let mut rollback = Rollback::default();
217 let result = Self::build(device, desc, label, &mut rollback);
218 if result.is_err() {
219 rollback.run(device);
220 }
221 result
222 }
223
224 fn build(
225 device: &dyn Device,
226 desc: &LightGridDesc<'_>,
227 label: &str,
228 rollback: &mut Rollback,
229 ) -> Result<Self, HalError> {
230 // `light_cluster.slang`'s declaration order, which is the only order
231 // Metal and D3D12 agree about — see `crcbl_shaders::declaration_order`.
232 let entries = [
233 uniform(0),
234 storage(1, true, crcbl_shaders::light::LIGHT_STRIDE as u32),
235 storage(2, false, UINT_STRIDE),
236 storage(3, false, UINT_STRIDE),
237 ];
238 let layout_desc = BindGroupLayoutDesc {
239 label: Some(label),
240 entries: &entries,
241 };
242 check_portable_storage_buffers(Some(label), &[&layout_desc])?;
243 let layout = device.create_bind_group_layout(&layout_desc)?;
244 rollback.layouts.push(layout);
245 let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
246 label: Some(label),
247 bind_group_layouts: &[layout],
248 push_constants: None,
249 })?;
250 rollback.pipeline_layouts.push(pipeline_layout);
251 let pipeline = compute_pipeline(
252 device,
253 label,
254 &crcbl_shaders::LIGHT_CLUSTER,
255 pipeline_layout,
256 CLUSTER_WORKGROUP_SIZE,
257 )?;
258 rollback.pipelines.push(pipeline);
259
260 let mut lights = Vec::with_capacity(desc.frames);
261 let mut grid = Vec::with_capacity(desc.frames);
262 let mut params = Vec::with_capacity(desc.frames);
263 let mut groups = Vec::with_capacity(desc.frames);
264 for frame in 0..desc.frames {
265 let mut buffer = |name: &str, size: u64, usage, memory| {
266 let handle = device.create_buffer(&BufferDesc {
267 label: Some(&format!("{label} {name} {frame}")),
268 size,
269 usage,
270 memory,
271 })?;
272 rollback.buffers.push(handle);
273 Ok::<_, HalError>(handle)
274 };
275 // Host-uploaded and bound **read-only** by both the clustering pass
276 // and the fragment stage, so the device-local rule the grid below is
277 // under does not reach it: what that rule is really about is a
278 // writable binding, and D3D12 refuses an unordered-access view of an
279 // upload heap rather than a shader resource view of one.
280 let list = buffer(
281 "list",
282 u64::from(desc.lights) * LIGHT_STRIDE as u64,
283 BufferUsage::STORAGE,
284 MemoryLocation::HostUpload,
285 )?;
286 // **Device-local, and `TRANSFER_SRC` so a test can read back what the
287 // GPU decided.** A shader writes this one.
288 let froxels = buffer(
289 "grid",
290 u64::from(desc.froxels) * u64::from(CLUSTER_STRIDE) * 4,
291 BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
292 MemoryLocation::DeviceLocal,
293 )?;
294 let block = buffer(
295 "params",
296 CLUSTER_PARAMS_SIZE as u64,
297 BufferUsage::UNIFORM,
298 MemoryLocation::HostUpload,
299 )?;
300 let group = device.create_bind_group(&BindGroupDesc {
301 label: Some(&format!("{label} {frame}")),
302 layout,
303 entries: &[
304 bound(0, block),
305 bound(1, list),
306 bound(2, froxels),
307 bound(3, desc.stats[frame]),
308 ],
309 // No binding here is an array, so nothing has a runtime length
310 // to declare — the same `None` every other pass in this crate
311 // passes.
312 variable_count: None,
313 })?;
314 rollback.groups.push(group);
315 lights.push(list);
316 grid.push(froxels);
317 params.push(block);
318 groups.push(group);
319 }
320
321 Ok(Self {
322 lights,
323 grid,
324 params,
325 groups,
326 layout,
327 pipeline_layout,
328 pipeline,
329 capacity: desc.lights,
330 froxels: desc.froxels,
331 })
332 }
333
334 /// Rows the light list holds.
335 #[must_use]
336 pub const fn capacity(&self) -> u32 {
337 self.capacity
338 }
339
340 /// Froxels the grid holds.
341 #[must_use]
342 pub const fn froxel_capacity(&self) -> u32 {
343 self.froxels
344 }
345
346 /// `frame`'s light list, for a caller binding it into a drawing pipeline.
347 ///
348 /// # Panics
349 ///
350 /// If `frame` is not a slot this was built with.
351 #[must_use]
352 pub fn lights(&self, frame: usize) -> BufferHandle {
353 self.lights[frame]
354 }
355
356 /// `frame`'s froxel grid, likewise — and the buffer a test copies out to see
357 /// which lights the pass assigned where.
358 ///
359 /// # Panics
360 ///
361 /// If `frame` is not a slot this was built with.
362 #[must_use]
363 pub fn grid(&self, frame: usize) -> BufferHandle {
364 self.grid[frame]
365 }
366
367 /// Writes `frame`'s light rows and the parameters the clustering pass reads.
368 ///
369 /// `rows` are written in order and **the sun is expected to be among them**;
370 /// nothing here treats any row specially, which is the point. Rows past
371 /// [`capacity`](Self::capacity) are refused rather than truncated: a light
372 /// silently missing from every froxel is the seam this whole module exists
373 /// to prevent, and it would not show up in the overflow counter — that
374 /// counts what the *froxel* budget refused, which is a different number.
375 ///
376 /// Call once per frame, before [`LightGrid::add_pass`], against the frame
377 /// slot the instance pool rotated to.
378 ///
379 /// # Errors
380 ///
381 /// [`HalError`] if a write failed, or if `rows` is longer than the list.
382 ///
383 /// # Panics
384 ///
385 /// If `frame` is not a slot this was built with.
386 pub fn begin_frame(
387 &self,
388 device: &dyn Device,
389 frame: usize,
390 rows: &[GpuLight],
391 grid: Grid,
392 view: FrameView,
393 ) -> Result<(), HalError> {
394 let count = u32::try_from(rows.len()).unwrap_or(u32::MAX);
395 if count > self.capacity {
396 return Err(HalError::InvalidDescriptor(format!(
397 "{count} lights in a list of {}; raise the renderer's light capacity rather than \
398 dropping one, which no counter would report",
399 self.capacity
400 )));
401 }
402 let mut bytes = vec![0u8; rows.len() * LIGHT_STRIDE];
403 for (slot, row) in rows.iter().enumerate() {
404 bytes[slot * LIGHT_STRIDE..(slot + 1) * LIGHT_STRIDE].copy_from_slice(&row.to_bytes());
405 }
406 if !bytes.is_empty() {
407 device.write_buffer(self.lights[frame], 0, &bytes)?;
408 }
409
410 // Row 3 of the view-projection, so the pass can take a point's view
411 // depth with one dot product. Handed over rather than derived from the
412 // inverse, so the depth the froxels are cut at and the depth
413 // `mesh.slang` recomputes for its slice come from the same matrix.
414 let columns = view.view_projection.to_cols_array();
415 let depth_row = [columns[3], columns[7], columns[11], columns[15]];
416 device.write_buffer(
417 self.params[frame],
418 0,
419 &light::ClusterParams {
420 inverse_view_proj: view.view_projection.inverse().to_cols_array(),
421 eye: view.eye.extend(1.0).to_array(),
422 depth_row,
423 grid_x: grid.x,
424 grid_y: grid.y,
425 slices: grid.slices,
426 light_count: count,
427 viewport_x: view.extent.0.max(1),
428 viewport_y: view.extent.1.max(1),
429 perspective: u32::from(view.perspective),
430 tile_pixels: grid.tile_pixels,
431 }
432 .to_bytes(),
433 )
434 }
435
436 /// How many passes [`add_pass`](Self::add_pass) adds to a frame.
437 ///
438 /// Exact, for [`DrawGen::MAX_PASSES`](crate::draw_gen::DrawGen::MAX_PASSES)'s
439 /// reason: the dispatch is one invocation per froxel and a frame always has
440 /// froxels, so the pass is never the one that drops out.
441 pub const MAX_PASSES: u32 = 1;
442
443 /// Adds the clustering pass to `graph` and returns the grid's id, for a
444 /// caller that has to declare its own read of it.
445 ///
446 /// `stats` is the id [`GeneratedDraws::visible_count_id`] handed back, not a
447 /// fresh import: the clearing dispatch zeroes
448 /// [`CLUSTER_OVERFLOW_WORD`](crcbl_shaders::light::CLUSTER_OVERFLOW_WORD) and this pass adds to it, and the barrier
449 /// between the two is the graph's — computed from the accesses both declare
450 /// on **one** id. Importing the same buffer twice would be two resources the
451 /// graph cannot order against each other.
452 ///
453 /// Must therefore be called *after*
454 /// [`DrawGen::add_passes`](crate::draw_gen::DrawGen::add_passes).
455 ///
456 /// # Panics
457 ///
458 /// If `frame` is not a slot this was built with.
459 ///
460 /// [`GeneratedDraws::visible_count_id`]: crate::draw_gen::GeneratedDraws::visible_count_id
461 pub fn add_pass(
462 &self,
463 graph: &mut RenderGraph<'_>,
464 frame: usize,
465 stats: BufferId,
466 grid: Grid,
467 ) -> BufferId {
468 // The grid arrives in the state the previous frame that used this slot
469 // left it in, which is the state declared as final: the drawing pass
470 // reads it. Vacuous on the first frame, and the real prior use on every
471 // later one.
472 let froxels = graph.import_buffer(
473 "light-grid",
474 ImportedBuffer {
475 buffer: self.grid[frame],
476 initial: ResourceState::ShaderRead,
477 final_state: ResourceState::ShaderRead,
478 },
479 );
480 let pipeline = self.pipeline;
481 let layout = self.pipeline_layout;
482 let group = self.groups[frame];
483 // One invocation per froxel, and never zero: `Grid::for_frame` floors
484 // every extent at one tile and one slice, and Metal rejects an empty
485 // dispatch outright rather than treating it as a no-op.
486 let groups = grid.froxels().div_ceil(CLUSTER_WORKGROUP_SIZE);
487 graph
488 .add_compute_pass("light-cluster")
489 // `ShaderReadWrite` on both rather than a write-only state: a
490 // storage-buffer descriptor permits reads whatever the shader does
491 // with it, and the overflow counter is genuinely read-modify-written.
492 .use_buffer(froxels, ResourceState::ShaderReadWrite)
493 .use_buffer(stats, ResourceState::ShaderReadWrite)
494 .execute(move |ctx| {
495 let encoder = ctx.encoder();
496 encoder.bind_compute_pipeline(pipeline);
497 encoder.bind_group(0, group, &[], layout);
498 encoder.dispatch(groups, 1, 1);
499 });
500 froxels
501 }
502
503 /// Releases everything, in dependency order. The device must be idle.
504 pub fn destroy(self, device: &dyn Device) {
505 device.destroy_compute_pipeline(self.pipeline);
506 device.destroy_pipeline_layout(self.pipeline_layout);
507 for group in self.groups {
508 device.destroy_bind_group(group);
509 }
510 device.destroy_bind_group_layout(self.layout);
511 for buffer in self.lights.into_iter().chain(self.grid).chain(self.params) {
512 device.destroy_buffer(buffer);
513 }
514 }
515}
516
517/// What a failed [`LightGrid::new`] has to give back, in the order it must.
518#[derive(Default)]
519struct Rollback {
520 pipelines: Vec<ComputePipelineHandle>,
521 pipeline_layouts: Vec<PipelineLayoutHandle>,
522 groups: Vec<BindGroupHandle>,
523 layouts: Vec<BindGroupLayoutHandle>,
524 buffers: Vec<BufferHandle>,
525}
526
527impl Rollback {
528 fn run(self, device: &dyn Device) {
529 for pipeline in self.pipelines {
530 device.destroy_compute_pipeline(pipeline);
531 }
532 for layout in self.pipeline_layouts {
533 device.destroy_pipeline_layout(layout);
534 }
535 for group in self.groups {
536 device.destroy_bind_group(group);
537 }
538 for layout in self.layouts {
539 device.destroy_bind_group_layout(layout);
540 }
541 for buffer in self.buffers {
542 device.destroy_buffer(buffer);
543 }
544 }
545}
546
547#[cfg(test)]
548mod tests {
549 use super::*;
550
551 /// The ordinary case: a 4K frame keeps the default tile size and every
552 /// slice, which is what [`FROXEL_CAPACITY`] was chosen to buy.
553 #[test]
554 fn a_4k_frame_keeps_the_default_tiles_and_every_slice() {
555 let grid = Grid::for_frame((3840, 2160), true, FROXEL_CAPACITY);
556 assert_eq!(grid.tile_pixels, CLUSTER_TILE_PIXELS);
557 assert_eq!(grid.slices, CLUSTER_DEPTH_SLICES);
558 assert_eq!((grid.x, grid.y), (60, 34));
559 assert!(
560 grid.froxels() <= FROXEL_CAPACITY,
561 "{} froxels in a buffer of {FROXEL_CAPACITY}",
562 grid.froxels()
563 );
564 }
565
566 /// An orthographic camera has one slice, whatever the budget allows, because
567 /// it has no view depth to slice by.
568 #[test]
569 fn an_orthographic_frame_gets_one_slice() {
570 let grid = Grid::for_frame((256, 192), false, FROXEL_CAPACITY);
571 assert_eq!(grid.slices, 1);
572 assert_eq!(grid.tile_pixels, CLUSTER_TILE_PIXELS);
573 assert_eq!((grid.x, grid.y), (4, 3));
574 }
575
576 /// Slices are given up before tiles are, and only when they have to be.
577 #[test]
578 fn a_budget_too_small_for_every_slice_loses_slices_first() {
579 // Four by three tiles at 256x192; a budget of 24 leaves two slices.
580 let grid = Grid::for_frame((256, 192), true, 24);
581 assert_eq!(grid.tile_pixels, CLUSTER_TILE_PIXELS, "tiles are kept");
582 assert_eq!((grid.x, grid.y), (4, 3));
583 assert_eq!(grid.slices, 2);
584 assert!(grid.froxels() <= 24);
585 }
586
587 /// Past that, tiles coarsen — and the result still fits, which is the whole
588 /// obligation. The largest image the engine will create is the case this
589 /// exists for.
590 #[test]
591 fn a_frame_too_large_for_the_budget_coarsens_its_tiles_and_still_fits() {
592 for extent in [(16384u32, 16384u32), (7680, 4320), (100_000, 100_000)] {
593 let grid = Grid::for_frame(extent, true, FROXEL_CAPACITY);
594 assert!(
595 grid.froxels() <= FROXEL_CAPACITY,
596 "{extent:?} produced {} froxels, over the {FROXEL_CAPACITY} the buffer holds",
597 grid.froxels()
598 );
599 assert!(grid.slices >= 1 && grid.x >= 1 && grid.y >= 1);
600 assert!(
601 u64::from(grid.x) * u64::from(grid.tile_pixels) >= u64::from(extent.0),
602 "the tiles must still cover the frame, or the fragments past them \
603 read a froxel built for somewhere else"
604 );
605 assert!(u64::from(grid.y) * u64::from(grid.tile_pixels) >= u64::from(extent.1));
606 }
607 }
608
609 /// A zero extent — a minimised window — is one froxel rather than a dispatch
610 /// of none, which Metal rejects outright.
611 #[test]
612 fn a_zero_extent_is_still_one_froxel() {
613 let grid = Grid::for_frame((0, 0), true, FROXEL_CAPACITY);
614 assert!(grid.froxels() >= 1);
615 assert_eq!((grid.x, grid.y), (1, 1));
616 }
617
618 #[test]
619 fn the_frame_block_carries_the_four_numbers_in_order() {
620 let grid = Grid {
621 x: 3,
622 y: 5,
623 slices: 7,
624 tile_pixels: 11,
625 };
626 assert_eq!(grid.to_frame_block(), [3, 5, 7, 11]);
627 assert_eq!(grid.froxels(), 105);
628 }
629}