crcbl_render/shadow/atlas.rs
1//! The shadow atlas's space, handed out a rectangle at a time.
2//!
3//! Topic 45's atlas rung, first half: the image stops being a
4//! fixed grid a light indexes into and becomes a **quadtree the renderer
5//! allocates from**, so a far or small light can take a quarter or a sixteenth
6//! of what a near one takes and the same image holds many more maps. The other
7//! half is on the sampling side — a light's row names a slot and the shader
8//! reads that slot's rectangle rather than deriving a cell from a grid — and it
9//! is what lets a tile's size vary without a second sampling path.
10//!
11//! # A forest of quadtrees, one per [`TILE`]-sided cell
12//!
13//! The root of a quadtree has to be square and its levels are halvings, and the
14//! atlas is neither square by construction nor a power of two: its extent is
15//! [`super::ATLAS_COLUMNS`] by [`super::ATLAS_ROWS`] cells of [`TILE`] texels,
16//! and all three are free to change. So the roots are those cells — [`TILES`]
17//! of them, in [`tile_origin`] order — and each subdivides on its own. That is
18//! the generalisation of the grid rather than a replacement for it: ask every
19//! root for its whole self and the layout is the grid, texel for texel, which
20//! is what a frame whose maps all take whole cells still gets and what keeps
21//! every shadow golden where it was.
22//!
23//! # What a level is
24//!
25//! Level 0 is a whole root, [`TILE`] texels a side, and each level below it
26//! halves that down to [`MIN_TILE`] at level [`TILE_LEVELS`] − 1. A halving is
27//! a quarter of the area, so a light demoted one level costs a quarter of what
28//! it did.
29//!
30//! **[`MIN_TILE`] is a floor nothing has measured.** That plan's priority rung
31//! spends the levels above it — `super::tile_level` is the ladder — but the
32//! finest a scene in this tree reaches is a quarter of a cell's side, so
33//! nothing has yet shown where a halved map stops being worth its texels.
34//! [`TILE_LEVELS`] is a starting point with two bounds behind it and no
35//! measurement: the smallest tile is still far wider than the disc
36//! `mesh.slang` filters with — a map narrow enough for that reach spends its
37//! taps on its own edge clamp rather than on geometry — and one root divided
38//! that far already holds more maps than the light region has slots, so a
39//! deeper tree would be levels nothing could fill. `docs/backlog.md` carries
40//! the sweep.
41//!
42//! # Determinism, because the atlas is in every golden
43//!
44//! [`AtlasAllocator::allocate`] takes the **lowest free node** of the level it
45//! is asked for, and subdivides the lowest free node of the finest coarser
46//! level when that level has none. Two frames handed the same requests in the
47//! same order therefore get the same rectangles, which is what makes a shadow
48//! atlas comparable across runs at all.
49
50use super::{TILE, TILES, atlas_extent, tile_origin};
51
52/// Sizes the allocator hands out: [`TILE`] and each halving below it, so the
53/// finest is [`MIN_TILE`].
54///
55/// The depth of every root's quadtree. The module docs are where the floor is
56/// argued, and they are plain that it is a starting point rather than a
57/// measurement.
58pub const TILE_LEVELS: usize = 4;
59
60/// The smallest tile the allocator can hand out, in texels.
61///
62/// The last of [`TILE_LEVELS`]' halvings of [`TILE`]. A request finer than this
63/// is refused rather than rounded, which is [`AtlasAllocator::allocate`]'s own
64/// documented contract.
65pub const MIN_TILE: u32 = TILE >> (TILE_LEVELS - 1);
66
67const _: () = assert!(
68 MIN_TILE > 0,
69 "a tile of no texels is a shadow map with nothing in it; the atlas has \
70 fewer halvings in it than TILE_LEVELS asks for"
71);
72
73const _: () = assert!(
74 TILE.is_multiple_of(1u32 << (TILE_LEVELS - 1)),
75 "every halving of a tile has to be a whole number of texels, or the \
76 rectangles the allocator hands out do not tile the cell they came from"
77);
78
79/// A rectangle of the shadow atlas, in texels.
80///
81/// Square, because it is a node of a quadtree over a square cell — the two
82/// axes are one number and a reader that took them apart would be describing
83/// something this allocator cannot produce.
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub struct TileRect {
86 /// Texels from the atlas's left edge to this rectangle's.
87 pub x: u32,
88 /// Texels from its top edge to this rectangle's.
89 pub y: u32,
90 /// The rectangle's side, in texels. Zero for [`TileRect::EMPTY`].
91 pub side: u32,
92}
93
94impl TileRect {
95 /// The rectangle of an atlas slot **no map was rendered into**.
96 ///
97 /// Zero rather than a corner of the image, on
98 /// `crate::forward`'s reason for writing the identity into a free tile's
99 /// matrix: nothing samples a free slot — the rows that could name one carry
100 /// [`NO_SHADOW_TILE`](crcbl_shaders::light::NO_SHADOW_TILE) — so what the
101 /// value is for is a block dumped for debugging, where a side of zero says
102 /// "empty" and a plausible rectangle would not.
103 pub const EMPTY: Self = Self {
104 x: 0,
105 y: 0,
106 side: 0,
107 };
108
109 /// The rectangle as the shader reads it: a scale into the atlas in `xy` and
110 /// an offset in `zw`, so a point `t` of the tile's own `0..1` space is at
111 /// `zw + t * xy`.
112 ///
113 /// Two scales rather than one even though the rectangle is square: the
114 /// *atlas* need not be, and dividing a square by a rectangle's two extents
115 /// is what puts a tile's `0..1` on both of the image's axes.
116 #[must_use]
117 pub fn to_uv(self) -> [f32; 4] {
118 let (width, height) = atlas_extent();
119 #[expect(
120 clippy::cast_precision_loss,
121 reason = "an atlas extent is a few thousand texels"
122 )]
123 let (width, height) = (width as f32, height as f32);
124 #[expect(
125 clippy::cast_precision_loss,
126 reason = "a tile's origin and side are inside that extent"
127 )]
128 let (x, y, side) = (self.x as f32, self.y as f32, self.side as f32);
129 [side / width, side / height, x / width, y / height]
130 }
131}
132
133/// One tile the allocator handed out, and the only thing that names it.
134///
135/// A level and a node of that level, which is a *pure* description of a
136/// rectangle — [`Tile::rect`] needs no allocator to answer and so cannot
137/// disagree with one. What the allocator holds is whether the tile is still
138/// out; giving it back is [`AtlasAllocator::release`], which takes this by
139/// value so a caller cannot go on holding the handle it just returned.
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub struct Tile {
142 /// Which of [`TILE_LEVELS`] sizes this is: 0 is [`TILE`], each one below
143 /// halves it.
144 level: usize,
145 /// Which node of that level, in the order [`nodes_at`] lays them out.
146 node: usize,
147}
148
149impl Tile {
150 /// Which of [`TILE_LEVELS`] sizes this tile is: 0 a whole root cell, each
151 /// one below a halving of it.
152 ///
153 /// Read by [`Selection::lay_out`](super::Selection) to decide whether the
154 /// tile a slot already holds is the size that slot wants this frame — which
155 /// is the whole of the static-caching rung's retention rule, and the reason
156 /// a level is readable off a handle at all.
157 #[must_use]
158 pub const fn level(self) -> usize {
159 self.level
160 }
161
162 /// This tile's side in texels: [`TILE`] halved once per level.
163 #[must_use]
164 pub const fn side(self) -> u32 {
165 TILE >> self.level
166 }
167
168 /// Where this tile is in the atlas.
169 ///
170 /// A function of the handle alone. The root cell is [`tile_origin`]'s — so
171 /// a level-0 tile is exactly the cell the fixed grid had — and the node's
172 /// column and row inside it are the offset from there.
173 #[must_use]
174 pub fn rect(self) -> TileRect {
175 let (root, column, row) = decompose(self.level, self.node);
176 let (origin_x, origin_y) = tile_origin(root);
177 let side = self.side();
178 TileRect {
179 x: origin_x + column * side,
180 y: origin_y + row * side,
181 side,
182 }
183 }
184}
185
186/// How many nodes level `level` has: [`TILES`] roots, each divided into four
187/// once per level.
188const fn nodes_at(level: usize) -> usize {
189 TILES << (2 * level)
190}
191
192/// Which root, column and row node `node` of `level` is.
193///
194/// Row-major inside the root, roots in [`tile_origin`] order — the same
195/// convention on both axes of the recursion, which is what lets [`compose`] be
196/// its exact inverse.
197fn decompose(level: usize, node: usize) -> (usize, u32, u32) {
198 let across = 1usize << level;
199 let root = node / (across * across);
200 let inside = node % (across * across);
201 #[expect(
202 clippy::cast_possible_truncation,
203 reason = "a column or row inside a root is at most 2^(TILE_LEVELS - 1)"
204 )]
205 let (column, row) = ((inside % across) as u32, (inside / across) as u32);
206 (root, column, row)
207}
208
209/// The node of `level` at `column`, `row` of root `root`: [`decompose`]'s
210/// inverse.
211fn compose(level: usize, root: usize, column: u32, row: u32) -> usize {
212 let across = 1usize << level;
213 root * across * across + row as usize * across + column as usize
214}
215
216/// What the allocator knows about one node of one level.
217#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
218enum Node {
219 /// The node does not exist as a unit of its own: a coarser node covers it.
220 /// Every node below level 0 starts here.
221 #[default]
222 Absent,
223 /// The node exists and nothing holds it.
224 Free,
225 /// The node exists and a caller holds it.
226 Taken,
227 /// The node was divided; its four children are the units that exist.
228 Split,
229}
230
231/// The atlas's free space, as a quadtree over each of its [`TILES`] root cells.
232///
233/// [`Selection`](super::Selection) is this type's only caller in the renderer,
234/// and it holds its tiles **across frames**: a slot that wants the size it
235/// already has keeps the rectangle it has, and only a slot whose size changed
236/// or whose map is gone hands one back through [`release`](Self::release).
237/// Topic 45's static-caching rung is why — an atlas re-laid
238/// out from nothing every frame is one whose contents can never outlive the
239/// frame that drew them.
240#[derive(Clone, Debug, PartialEq, Eq)]
241pub struct AtlasAllocator {
242 /// `nodes[level]` is the state of every node of that level, `nodes_at` of
243 /// them, indexed as [`compose`] indexes them.
244 ///
245 /// A state per node rather than a free list per level: a free list would
246 /// have to be searched anyway to keep [`allocate`](Self::allocate)
247 /// deterministic, and the coalescing in [`release`](Self::release) asks
248 /// about a node's three siblings, which a list cannot answer.
249 nodes: Vec<Vec<Node>>,
250}
251
252impl Default for AtlasAllocator {
253 fn default() -> Self {
254 Self::new()
255 }
256}
257
258impl AtlasAllocator {
259 /// An allocator with the whole atlas free.
260 #[must_use]
261 pub fn new() -> Self {
262 Self {
263 nodes: (0..TILE_LEVELS)
264 .map(|level| {
265 let state = if level == 0 { Node::Free } else { Node::Absent };
266 vec![state; nodes_at(level)]
267 })
268 .collect(),
269 }
270 }
271
272 /// A tile of `level` — [`TILE`] halved `level` times — or `None` if the
273 /// atlas has no room for one.
274 ///
275 /// A level past [`TILE_LEVELS`] is refused rather than clamped: a caller
276 /// that asked for a map smaller than [`MIN_TILE`] and was handed a larger
277 /// one would be told it fit a budget it does not.
278 pub fn allocate(&mut self, level: usize) -> Option<Tile> {
279 let node = self.free_node(level)?;
280 self.nodes[level][node] = Node::Taken;
281 Some(Tile { level, node })
282 }
283
284 /// Gives `tile`'s space back, merging it into its parent wherever that
285 /// leaves all four of a node's children free.
286 ///
287 /// The merge is what makes the space *reusable at the size it was*: without
288 /// it an atlas that had once handed out a quarter tile could never hand out
289 /// a whole one again, however empty it was.
290 ///
291 /// `Selection::lay_out` is the caller: a slot whose map is gone, or whose
292 /// map wants a size other than the one it holds, gives its tile back here
293 /// before the frame's remaining requests are spent, and every other slot
294 /// keeps the rectangle it already had. Freeing one light's tiles while its
295 /// neighbours keep theirs is exactly what a tile with a lifetime longer
296 /// than one frame needs from an allocator.
297 pub fn release(&mut self, tile: Tile) {
298 let mut level = tile.level;
299 let mut node = tile.node;
300 self.nodes[level][node] = Node::Free;
301 while level > 0 {
302 let (root, column, row) = decompose(level, node);
303 let (parent_column, parent_row) = (column / 2, row / 2);
304 let siblings = [
305 (parent_column * 2, parent_row * 2),
306 (parent_column * 2 + 1, parent_row * 2),
307 (parent_column * 2, parent_row * 2 + 1),
308 (parent_column * 2 + 1, parent_row * 2 + 1),
309 ];
310 if !siblings.iter().all(|&(column, row)| {
311 self.nodes[level][compose(level, root, column, row)] == Node::Free
312 }) {
313 break;
314 }
315 for &(column, row) in &siblings {
316 let sibling = compose(level, root, column, row);
317 self.nodes[level][sibling] = Node::Absent;
318 }
319 let parent = compose(level - 1, root, parent_column, parent_row);
320 self.nodes[level - 1][parent] = Node::Free;
321 level -= 1;
322 node = parent;
323 }
324 }
325
326 /// The lowest free node of `level`, subdividing a coarser one if that level
327 /// has none free.
328 ///
329 /// The recursion is what makes the split lazy: a level-3 request against an
330 /// empty atlas splits one root, then one quarter, then one sixteenth, and
331 /// leaves the three siblings at each step free for the next request of that
332 /// size rather than dividing the whole image up front.
333 fn free_node(&mut self, level: usize) -> Option<usize> {
334 if level >= TILE_LEVELS {
335 return None;
336 }
337 if let Some(node) = self.nodes[level]
338 .iter()
339 .position(|node| *node == Node::Free)
340 {
341 return Some(node);
342 }
343 if level == 0 {
344 return None;
345 }
346 let parent = self.free_node(level - 1)?;
347 let (root, column, row) = decompose(level - 1, parent);
348 self.nodes[level - 1][parent] = Node::Split;
349 for (across, down) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
350 let child = compose(level, root, column * 2 + across, row * 2 + down);
351 self.nodes[level][child] = Node::Free;
352 }
353 Some(compose(level, root, column * 2, row * 2))
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360 use crate::shadow::{ATLAS_COLUMNS, ATLAS_ROWS};
361
362 /// Every rectangle the allocator hands out is inside the atlas, and no two
363 /// of them overlap — **at four different sizes at once**, which is the
364 /// whole of what a quadtree buys over the fixed grid it replaced.
365 ///
366 /// The overlap test is a texel-by-texel occupancy map rather than a
367 /// pairwise rectangle intersection, because an occupancy map also answers
368 /// the question a pairwise test cannot: how much of the image the
369 /// allocation actually covered. A run that allocated nothing would pass a
370 /// pairwise test perfectly.
371 #[test]
372 fn a_quadtree_hands_out_four_sizes_that_do_not_overlap() {
373 let mut allocator = AtlasAllocator::new();
374 let (width, height) = atlas_extent();
375 let mut covered = vec![false; (width * height) as usize];
376 let mut handed_out = 0usize;
377 let mut area = 0u64;
378 // One of every size, twice round, so a level is asked for both when its
379 // own free list is empty — which is the split — and when a previous
380 // request has already left a sibling free, which is not.
381 for _ in 0..2 {
382 for level in 0..TILE_LEVELS {
383 let tile = allocator
384 .allocate(level)
385 .unwrap_or_else(|| panic!("an empty atlas has room for a level-{level} tile"));
386 let rect = tile.rect();
387 assert_eq!(rect.side, TILE >> level, "a level-{level} tile's side");
388 assert!(
389 rect.x + rect.side <= width && rect.y + rect.side <= height,
390 "{rect:?} runs off an atlas of {width}x{height}"
391 );
392 for row in rect.y..rect.y + rect.side {
393 for column in rect.x..rect.x + rect.side {
394 let texel = (row * width + column) as usize;
395 assert!(
396 !covered[texel],
397 "texel ({column}, {row}) is in {rect:?} and in a tile handed out \
398 before it"
399 );
400 covered[texel] = true;
401 }
402 }
403 handed_out += 1;
404 area += u64::from(rect.side) * u64::from(rect.side);
405 }
406 }
407 assert_eq!(
408 handed_out,
409 2 * TILE_LEVELS,
410 "the loop above stopped handing out tiles"
411 );
412 assert_eq!(
413 area,
414 covered.iter().filter(|texel| **texel).count() as u64,
415 "the tiles' areas and the texels they covered disagree, so two of them \
416 overlapped or one was counted twice"
417 );
418 }
419
420 /// A released tile's space comes back — **at the size it was**, which is
421 /// the merge and not merely the free.
422 ///
423 /// The four quarters of one root are taken and given back, and the atlas is
424 /// then emptied of every whole cell: the last of those requests can only be
425 /// satisfied by the root that was subdivided, so it fails unless the four
426 /// quarters merged back into it.
427 #[test]
428 fn a_released_tile_s_space_is_reusable_at_its_own_size() {
429 let mut allocator = AtlasAllocator::new();
430 let quarters: Vec<Tile> = (0..4)
431 .map(|index| {
432 allocator
433 .allocate(1)
434 .unwrap_or_else(|| panic!("an empty atlas has room for quarter {index}"))
435 })
436 .collect();
437 // All four came out of one root, which is what makes the merge below
438 // the thing under test rather than an accident of where they landed.
439 let root = quarters[0].rect();
440 for quarter in &quarters {
441 let rect = quarter.rect();
442 assert_eq!(rect.side, TILE / 2, "a level-1 tile's side");
443 assert!(
444 rect.x / TILE == root.x / TILE && rect.y / TILE == root.y / TILE,
445 "{rect:?} is not in the cell the first quarter came from"
446 );
447 }
448 for quarter in quarters {
449 allocator.release(quarter);
450 }
451 let whole: Vec<TileRect> = (0..TILES)
452 .map(|index| {
453 allocator
454 .allocate(0)
455 .unwrap_or_else(|| {
456 panic!("cell {index} of {TILES} is not free after every quarter came back")
457 })
458 .rect()
459 })
460 .collect();
461 assert_eq!(whole.len(), TILES, "the loop above stopped allocating");
462 assert_eq!(
463 allocator.allocate(0),
464 None,
465 "the atlas handed out more whole cells than it has"
466 );
467 }
468
469 /// Level 0 is the fixed grid this allocator replaced, cell for cell.
470 ///
471 /// The behaviour every shadow golden in the tree was blessed under: ask for
472 /// [`TILES`] whole tiles in order and get [`tile_origin`]'s cells in order.
473 /// It is what says the machinery generalised the grid rather than moving
474 /// it.
475 #[test]
476 fn whole_tiles_come_out_where_the_fixed_grid_put_them() {
477 let mut allocator = AtlasAllocator::new();
478 for index in 0..TILES {
479 let rect = allocator
480 .allocate(0)
481 .unwrap_or_else(|| panic!("cell {index} of {TILES}"))
482 .rect();
483 let (x, y) = tile_origin(index);
484 assert_eq!(
485 rect,
486 TileRect { x, y, side: TILE },
487 "cell {index} is not where `tile_origin` puts it"
488 );
489 }
490 }
491
492 /// The atlas is exactly the roots the allocator divides, and a request
493 /// finer than [`MIN_TILE`] is refused rather than rounded up.
494 #[test]
495 fn the_roots_tile_the_atlas_and_a_finer_request_is_refused() {
496 assert_eq!(
497 atlas_extent(),
498 (TILE * ATLAS_COLUMNS, TILE * ATLAS_ROWS),
499 "the allocator's roots do not cover the image they are cut from"
500 );
501 assert_eq!(nodes_at(0), TILES, "level 0 is one node per root cell");
502 let mut allocator = AtlasAllocator::new();
503 assert_eq!(
504 allocator.allocate(TILE_LEVELS),
505 None,
506 "a request past the finest level was answered with a tile larger than it \
507 asked for"
508 );
509 }
510
511 /// A tile's `0..1` maps onto exactly its own rectangle of the atlas — the
512 /// arithmetic `mesh.slang` performs, read back on the host.
513 ///
514 /// **Exactly**, with no tolerance: every side and origin here is a whole
515 /// number of texels over an extent that is a power of two times the tile,
516 /// so each of these quotients is a dyadic rational a `f32` holds without
517 /// rounding. A comparison with a tolerance would pass on a scale that had
518 /// picked up the wrong axis's extent.
519 #[test]
520 fn a_rectangle_s_uv_puts_a_tile_s_corners_on_its_own_texels() {
521 let (width, height) = atlas_extent();
522 #[expect(
523 clippy::cast_precision_loss,
524 reason = "an atlas extent is a few thousand texels"
525 )]
526 let extent = [width as f32, height as f32];
527 let mut allocator = AtlasAllocator::new();
528 for level in 0..TILE_LEVELS {
529 let rect = allocator
530 .allocate(level)
531 .unwrap_or_else(|| panic!("a level-{level} tile"))
532 .rect();
533 let uv = rect.to_uv();
534 for (axis, extent) in extent.iter().enumerate() {
535 let origin = if axis == 0 { rect.x } else { rect.y };
536 #[expect(
537 clippy::cast_precision_loss,
538 reason = "an origin and a side are inside that extent"
539 )]
540 let (origin, side) = (origin as f32, rect.side as f32);
541 assert_eq!(
542 uv[2 + axis] * extent,
543 origin,
544 "a level-{level} tile's offset on axis {axis}"
545 );
546 assert_eq!(
547 (uv[2 + axis] + uv[axis]) * extent,
548 origin + side,
549 "a level-{level} tile's far edge on axis {axis}"
550 );
551 }
552 }
553 }
554}