crcbl_render/shadow.rs
1//! Where each shadow map looks, and how far: the sun's cascades, a spot light's
2//! cone and a point light's six faces.
3//!
4//! Topic 45's shadows (`docs/notes/rendering.md`), arithmetic half. This
5//! module owns the matrices and the tile budget; [`crate::forward`] owns the
6//! atlas, the depth-only pipeline and the per-tile cull that fills them. The
7//! split is where the testable part is: a cascade matrix is a pure function of a
8//! camera and a light direction, a spot's is a pure function of the light, and
9//! the tile budget is a pure function of the light list — so every claim below
10//! is checked here without a device in the room.
11//!
12//! # One atlas, [`TILES`] slots, and an allocator behind them
13//!
14//! The maps live side by side in a single `D32Float` image rather than as layers
15//! of an array. That is a consequence of the render graph, not a preference: a
16//! [`crate::graph`] render pass attaches an *image*, and there is no way to
17//! attach layer `i` of one. Tiles need nothing the graph does not already have —
18//! the shadow pass sets a viewport over a tile and draws — so the tile count is
19//! a constant either side of the seam and not a feature request.
20//! `mesh.slang`'s `shadow_atlas` says the same from the sampling side.
21//!
22//! A **slot** is one map: an index into the frame block's matrices, and the
23//! number a light's row carries. The split of them is topic 18's 2026-08-13
24//! decision: **the sun's cascades take the first [`CASCADES`] slots and the rest
25//! are handed out one per shadowed spot and [`POINT_FACES`] per shadowed
26//! point**, with [`LIGHT_TILES`] of them. A light that gets no slots still lights
27//! and simply does not occlude, which is what makes the budget a quality knob
28//! rather than a correctness cliff — see [`Selection`].
29//!
30//! **Where a slot's map lives in the image is a separate question, and
31//! [`AtlasAllocator`] answers it.** Topic 45's atlas rung: the
32//! image is a quadtree over [`ATLAS_COLUMNS`] by [`ATLAS_ROWS`] root cells of
33//! [`TILE`] texels, a map takes a whole cell or a halving of one down to
34//! [`MIN_TILE`], and the shader reads the rectangle it landed in — see
35//! [`Selection::atlas_rect`] and `mesh.slang`'s `atlas_uv`.
36//!
37//! **What asks for a halving is the priority rung, and it is `coverage`**:
38//! how much of the frame's height a light's map covers on screen decides both
39//! which lights are worth a run of tiles and how large each of those tiles is.
40//! A light covering less than `WHOLE_CELL_COVERAGE` takes a quarter of a cell,
41//! and each halving of its coverage below that takes another —
42//! `tile_level` is the ladder and `LEVEL_HOLD_RATIO` the band that stops a
43//! light on a threshold halving and doubling its map every frame. A frame whose
44//! lights all clear the top of the ladder lays out exactly as the fixed grid
45//! did, cell for cell.
46//!
47//! # Two budgets, because they buy different things
48//!
49//! [`LIGHT_TILES`] is atlas space and [`LIGHT_SLOTS`] is *cull* space, and the
50//! two stopped being one number the moment a light could own six tiles:
51//!
52//! * A tile is [`TILE`]² of `D32Float`, and the atlas is allocated once for the
53//! renderer's life. [`POINT_FACES`] of them is what a point light needs to be
54//! shadowable at all, since its faces have to fit in the region together, and
55//! [`LIGHT_TILES`] holds two such runs with two tiles over — so two cubes and
56//! two cones fit side by side.
57//! * A slot is one shadowed *light*, and what it costs is a
58//! [`DrawGen`](crate::draw_gen::DrawGen) — roughly five megabytes, most of it
59//! per-instance LOD hysteresis state that is device-local and permanent. Topic
60//! 18's fourth decision is that a point light gets **one** of these rather than
61//! one per face: the six faces' union is the light's sphere, which is what the
62//! cull tests against anyway, so one visible set feeds all six draws through
63//! six matrices into six tiles. A face draws what is behind it and the
64//! rasteriser discards it.
65//!
66//! So the light region holds two point lights *and* two spots, or [`LIGHT_SLOTS`]
67//! spots, and a frame with more shadow-worthy lights than either budget covers
68//! shadows the most influential ones it can fit and lights the rest without
69//! occluding. A *third* point light is what no longer fits: three cubes are three
70//! times [`POINT_FACES`] tiles and the region is not that long.
71//!
72//! # The 2026-08-26 re-tiling, which cost no memory
73//!
74//! The region held [`POINT_FACES`] tiles and one over until 2026-08-26, so
75//! exactly one point light in any scene could occlude — and a rig with a light
76//! either side of a walkway, which is an ordinary rig, had the torch that lost
77//! the tie *re-lighting* the shadow its twin cast. Widening the grid by a column
78//! and a row while shrinking [`TILE`] to match leaves [`atlas_extent`] where it
79//! was to the texel, so the image, its `D32Float` format and its memory are
80//! unchanged and the whole cost is per-tile resolution. What is *not* free is
81//! [`LIGHT_SLOTS`]: a slot is a [`DrawGen`](crate::draw_gen::DrawGen), so the
82//! culls this budget added are device-local memory the atlas did not ask for.
83//!
84//! # Which filter samples them, and the seam that shows two at once
85//!
86//! [`r_shadow_filter`] is the one knob here that reaches into `mesh.slang`'s
87//! sampling rather than into this module's arithmetic: topic 45's ladder
88//! has three filter rungs and, until it existed, only the top one was in the
89//! tree. [`Filter`] is the set, [`filter`] is the near side of the comparison
90//! and [`shipped_filter`] is the far one.
91//!
92//! **The seam is per pixel and not per pass**, which is what [`r_shadow_split`]
93//! buys and what makes it unlike `crate::ssao::r_ssao_split`: the occlusion
94//! gather is a full-screen pass, so its two sides are two recordings under two
95//! scissors and cost one target's worth of fragments between them. The filter
96//! lives in a scene draw, where a second recording is every triangle again — so
97//! the two modes and the seam's column ride in
98//! [`crcbl_shaders::mesh::FrameUniforms::shadow_filter`] and the fragment picks
99//! its own side. `crate::split`'s header carries both shapes.
100//!
101//! **`pcss` is the default and is what every golden was blessed at**, and a
102//! frame nobody has touched either variable on writes a row of zeroes — one
103//! mode in both lanes and no column — which is the picture this engine drew
104//! before the row existed.
105//!
106//! # Stability: a sphere around the eye, snapped to texels
107//!
108//! The classic cascade shimmer is a shadow edge crawling along a static surface
109//! while the camera moves. It has two causes and this module removes both:
110//!
111//! * **The cascade's extent changing with the camera's orientation.** A box
112//! fitted to the split's view frustum is tight but rotates with the camera, so
113//! every frame resamples the same geometry at a different scale. [`Cascades`]
114//! uses a *sphere* instead, and its radius is [`Cascades::far`] — a number that
115//! depends on the split alone. Rotating the camera cannot change it.
116//! * **The cascade's origin moving by a fraction of a texel.** Fixed by
117//! quantising the light-space origin to whole texels, which is what
118//! `snap_to_texel` does and what the ortho box below is built around.
119//!
120//! The cost of the sphere is resolution: a sphere of radius `r` centred on the
121//! eye covers everything within `r`, including the half of it behind the camera
122//! that will never be shaded. A frustum-fitted box would be roughly twice as
123//! dense for the same tile. That is the trade, taken deliberately: the tight fit
124//! is the version that has to branch on [`Projection`](crate::Projection) — an
125//! orthographic camera has no field of view to build corners from — and a shadow
126//! pass that is correct on one projection and wrong on the other is worse than
127//! one that is uniformly coarser.
128
129mod atlas;
130mod cadence;
131
132use glam::{Mat4, Vec3, Vec4Swizzles};
133
134pub use atlas::{AtlasAllocator, MIN_TILE, TILE_LEVELS, Tile, TileRect};
135pub use cadence::{Cadence, GROUPS, Group, r_shadow_cadence, r_shadow_faces};
136
137use crate::camera::Camera;
138use crate::cull::Frustum;
139use crate::light::{Light, PointLight, SpotLight};
140
141crcbl_console::convar! {
142 /// Which shadow filter runs: `pcss` ships, `disc` drops the blocker search,
143 /// `box` is the 3×3.
144 pub static r_shadow_filter: &'static str one_of ["pcss", "disc", "box"] = "pcss";
145}
146
147crcbl_console::convar! {
148 /// Compare the console's shadow filter against the shipped one: seam at 0..1.
149 pub static r_shadow_split: f32 in 0.0 ..= 1.0 = 0.0;
150}
151
152/// The shadow filter a fragment runs — topic 45's ladder, with
153/// every rung of it still in the tree.
154///
155/// **A uniform lane and not a pipeline**, which is what separates this from
156/// `crate::ssao`'s `Technique`: the occlusion gather is a full-screen pass and
157/// two of them are two shaders, where this is a branch inside a *scene* draw.
158/// `crate::split`'s header is where the consequence is argued — a scene pass
159/// cannot record itself twice under a scissor without drawing every triangle
160/// twice, so the seam rides in the frame block and `mesh.slang`'s
161/// `shadow_filter_mode` picks a side per fragment.
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub enum Filter {
164 /// The blocker search sizes the sun's disc per fragment and the punctual
165 /// maps take it at its fixed reach: the ninth, tenth and eleventh decisions
166 /// together. **What ships**, and what every golden was blessed under.
167 Pcss,
168 /// The same rotated disc at the fixed reach for the sun as well, so no
169 /// blocker search runs and no penumbra widens with its caster's height: the
170 /// ninth and eleventh decisions without the tenth.
171 Disc,
172 /// The 3×3 hardware-PCF box the ninth decision replaced.
173 Box,
174}
175
176impl Filter {
177 /// Every shadow filter, from cheapest to highest quality.
178 pub const ALL: [Self; 3] = [Self::Box, Self::Disc, Self::Pcss];
179
180 /// The name [`r_shadow_filter`] holds for this one.
181 ///
182 /// The `convar!` needs literals, so the names are written twice — three
183 /// times counting `mesh.slang`'s constants — and this module's
184 /// `the_variable_names_are_the_filters_labels` is what holds this copy to
185 /// the other two.
186 #[must_use]
187 pub const fn label(self) -> &'static str {
188 match self {
189 Self::Pcss => "pcss",
190 Self::Disc => "disc",
191 Self::Box => "box",
192 }
193 }
194
195 /// The value `mesh.slang` compares against, which is this filter's place in
196 /// [`crcbl_shaders::mesh::SHADOW_FILTERS`].
197 ///
198 /// Derived from the list rather than written down, so a filter inserted in
199 /// the middle of it renumbers here rather than silently selecting its
200 /// neighbour.
201 #[must_use]
202 pub fn mode(self) -> u32 {
203 let at = crcbl_shaders::mesh::SHADOW_FILTERS
204 .iter()
205 .position(|label| *label == self.label())
206 // Unreachable while `the_variable_names_are_the_filters_labels`
207 // passes: that test is what holds the two lists to one set of
208 // names. Zero is what ships, which is the answer a caller would
209 // rather have than a panic in a frame.
210 .unwrap_or(0);
211 u32::try_from(at).unwrap_or(0)
212 }
213
214 /// The filter `name` names, or [`None`] for a name outside the set.
215 #[must_use]
216 pub fn from_name(name: &str) -> Option<Self> {
217 FILTERS.into_iter().find(|filter| filter.label() == name)
218 }
219}
220
221/// The order [`r_shadow_filter`] declares its names in.
222///
223/// `crate::ssao`'s `TECHNIQUES` has the same shape for the same reason: the
224/// macro takes literals, so the names exist twice. The test below holds this
225/// order to the convar and shader orders.
226const FILTERS: [Filter; 3] = [Filter::Pcss, Filter::Disc, Filter::Box];
227
228/// [`r_shadow_filter`] as the near side of the seam wants it.
229#[must_use]
230pub fn filter() -> Filter {
231 Filter::from_name(r_shadow_filter.get_enum()).unwrap_or(Filter::Pcss)
232}
233
234/// The filter the engine ships, for the other side of the seam.
235///
236/// `crate::ssao`'s `shipped_technique` exactly: read off the variable's own
237/// declared default rather than written down, so the far side follows a default
238/// that moves and the comparison is never a configuration against itself.
239#[must_use]
240pub fn shipped_filter() -> Filter {
241 match r_shadow_filter.default() {
242 crcbl_console::Value::Enum(name) => Filter::from_name(name).unwrap_or(Filter::Pcss),
243 // Unreachable by construction: `convar!` builds an enum cell and its
244 // default together. This is what a `match` needs.
245 _ => Filter::Pcss,
246 }
247}
248
249/// [`r_shadow_split`] as `crate::split::halves` wants it, or `None` for a
250/// frame comparing nothing.
251///
252/// `crate::ssao`'s `split_at` rule: **zero is off and is the default**, so a
253/// frame nobody has touched the console on draws one filter everywhere — a
254/// comparison is something a person asks for, and every golden in this
255/// workspace was blessed without one. `halves` refuses a seam at either edge
256/// anyway, so this is the readable spelling of a rule that holds whatever
257/// reaches it.
258#[must_use]
259pub fn split_at() -> Option<f32> {
260 let at = r_shadow_split.get_f32();
261 (at > 0.0 && at < 1.0).then_some(at)
262}
263
264/// The lock [`r_shadow_filter`], [`r_shadow_split`], [`r_shadow_bias`] and
265/// [`r_shadow_normal_offset`] are moved under.
266///
267/// **In this module rather than beside the test that takes it**, on
268/// `crate::ssao::TECHNIQUE_SWITCH`'s terms exactly: two files move these
269/// variables — this module's own tests and `crate::forward`'s
270/// `shadow_filter_switch` — and a `cargo test` run shares one process between
271/// them, so a variable one left moved is a frame the other did not ask for.
272///
273/// **One lock for the four variables**, unlike the occlusion chain's, because
274/// they are read into two rows of one block: a test that moved the filter while
275/// another moved the seam would be reading a lane neither of them wrote, and the
276/// bias pair's row is rebuilt by [`Cascades::params`] beside it.
277///
278/// **Last in the lock order**, after `crate::ssao::TECHNIQUE_SWITCH`. A test
279/// that takes it with the others takes it after all of them, so there is no
280/// cycle to have.
281#[cfg(test)]
282pub(crate) static FILTER_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
283
284/// How many cascades the sun's shadow map is split into.
285///
286/// The shader's number, not a second one: `crcbl_shaders::mesh` is where it
287/// lives and where it is checked against the `.slang` sources, because the
288/// uniform block's layout depends on it.
289pub const CASCADES: usize = crcbl_shaders::mesh::SHADOW_CASCADES;
290
291/// How many **tiles** the atlas has for shadowed lights beside the cascades.
292///
293/// The shader's number for the same reason [`CASCADES`] is: the frame block
294/// carries one matrix per light tile, so a block sized differently on the two
295/// sides puts every member after it at the wrong offset.
296pub const LIGHT_TILES: usize = crcbl_shaders::mesh::SHADOW_LIGHT_TILES;
297
298/// Tiles one point light's shadow map is: the six faces of a cube.
299///
300/// The shader's number as well, because it is how far apart two of a light's
301/// tiles are and `mesh.slang`'s `point_face` adds it to a row's base.
302pub const POINT_FACES: usize = crcbl_shaders::mesh::SHADOW_POINT_FACES;
303
304/// How many lights a frame can shadow at once.
305///
306/// **Not a shader number**, unlike [`LIGHT_TILES`], and the module docs say why:
307/// nothing in a shader counts lights, and what this bounds is the number of
308/// [`DrawGen`](crate::draw_gen::DrawGen)s the renderer holds — one cull per
309/// shadowed light, whether that light is one tile or six.
310///
311/// Four, which is what the light region is sized for: two point lights' cubes
312/// and two spots' maps beside them. A fifth shadowed light is refused here, and a
313/// *third* point light is refused by [`Selection`] running out of tiles rather
314/// than by a rule of its own — the two budgets bind in different places, which
315/// is why they are two numbers.
316pub const LIGHT_SLOTS: usize = 4;
317
318/// The side of one **root cell** of the shadow atlas, in texels.
319///
320/// The largest map the allocator can hand out and the size of every cell of the
321/// grid the quadtree's roots are laid out on — not the size of every map, which
322/// is [`Assignment::level`]'s answer and varies with `coverage`.
323///
324/// **A host number, and no longer the shader's.** `mesh.slang` used to declare
325/// it because every shadow bias there is denominated in the texels of the map
326/// being sampled, and while every map was a whole cell the two were the same
327/// number; since the priority rung they are not, and the shader reads each map's
328/// own side out of its `shadow_atlas_rect` instead. What it sizes here is the
329/// image — see [`atlas_extent`] — which is a fact about the resource the
330/// renderer allocates and about nothing a shader can see.
331pub const TILE: u32 = crcbl_shaders::mesh::SHADOW_TILE;
332
333/// Tiles across the atlas.
334///
335/// At least [`CASCADES`], which is what keeps the cascades in the top row at the
336/// origins they were blessed at — see [`tile_origin`].
337pub const ATLAS_COLUMNS: u32 = crcbl_shaders::mesh::SHADOW_ATLAS_COLUMNS;
338
339/// Tiles down it.
340///
341/// A grid rather than one row: a point light is [`POINT_FACES`] tiles of exactly
342/// this kind, and a single row holding [`TILES`] of them beside the cascades
343/// would be an image several times wider than it is tall, for no gain. The
344/// addressing below is written in terms of both extents, and so is
345/// `mesh.slang`'s.
346pub const ATLAS_ROWS: u32 = crcbl_shaders::mesh::SHADOW_ATLAS_ROWS;
347
348/// Tiles in the whole atlas: [`CASCADES`] for the sun and [`LIGHT_TILES`] for
349/// the lights that fit.
350pub const TILES: usize = (ATLAS_COLUMNS * ATLAS_ROWS) as usize;
351
352const _: () = assert!(
353 TILES == CASCADES + LIGHT_TILES,
354 "every tile of the grid is either a cascade's or a light's; a grid with a \
355 tile nothing owns is atlas nothing writes and nothing samples"
356);
357
358const _: () = assert!(
359 LIGHT_SLOTS <= LIGHT_TILES,
360 "a slot with no tile to render into is a cull dispatch whose result nothing \
361 can sample"
362);
363
364/// The widest half-angle a spot can have and still be given a tile, in radians.
365///
366/// A spot's map is one perspective projection whose field of view is twice the
367/// cone's outer half-angle, and a projection's field of view cannot reach 180°:
368/// the tangent runs to infinity and the matrix stops being one. So a cone wider
369/// than this is **refused a tile** rather than given a map that covers part of
370/// it — [`Selection`] is where that happens, and the light then lights without
371/// occluding, which is the same honest degradation as running out of tiles.
372///
373/// 80° leaves `tan` at under six, so the near plane's footprint stays a sane
374/// multiple of the tile it is rendered into.
375pub const MAX_SPOT_HALF_ANGLE: f32 = 80.0 * std::f32::consts::PI / 180.0;
376
377/// A punctual light's near plane, in world units.
378///
379/// Everything nearer than this to the light is inside it and casts nothing. It
380/// is the only knob a perspective shadow map's depth distribution really has —
381/// under reversed-Z the precision piles up at the near plane, so this being
382/// small is what makes a caster far from the light cheap in depth resolution and
383/// not the other way round.
384///
385/// One number for a spot's cone and a point light's faces, because it is one
386/// piece of knowledge: how close to a light something has to be before it stops
387/// being a caster and starts being the light's own housing.
388const PUNCTUAL_NEAR: f32 = 0.05;
389
390/// How far from the eye the sun's shadows reach, in world units.
391///
392/// Past this every surface is lit: the last cascade's box ends, the sampling
393/// code takes its out-of-bounds path, and a distant hillside is simply not
394/// shadowed. That is the honest failure for a shadow map, and the alternative —
395/// extending the last cascade to the far plane — spends the whole atlas on
396/// geometry too far away to see the result on.
397///
398/// Not a field on [`DirectionalLight`](crate::DirectionalLight): it is a
399/// property of how much shadow detail a *view* is willing to pay for, which
400/// topic 18 puts on the per-camera stack when there is one to put it on.
401pub const DISTANCE: f32 = 24.0;
402
403/// How much of the practical split scheme is logarithmic rather than uniform.
404///
405/// The two extremes are both wrong in the usual way: a uniform split gives the
406/// nearest cascade — the one filling most of the screen — almost no resolution,
407/// and a fully logarithmic one gives the far cascades so little that their
408/// texels are visible as steps. `0.7` is the conventional compromise and is
409/// where every reference implementation of this scheme sits.
410const SPLIT_LAMBDA: f32 = 0.7;
411
412/// Distance in front of the light's near plane that still writes depth, in world
413/// units.
414///
415/// A caster between the sun and the cascade's sphere is outside the sphere and
416/// must still darken what is inside it, so the light's box is pulled back this
417/// far and its near plane put at zero. Too small and a tall object stops casting
418/// as the camera approaches its base; too large and the depth range stretches
419/// for nothing.
420///
421/// **It used to set the size of a light leak, and no longer does.** The sun's
422/// bias was denominated in shadow-clip depth, so its world meaning was this
423/// number plus `2 * radius` — 88 m on the outer cascade, of which 40 was this —
424/// and a bias of 0.0094 in clip was 0.83 m of world slack against walls 0.15 m
425/// thick. [`DEPTH_BIAS_TEXELS`] is what removed the coupling; this is a caster
426/// budget again.
427///
428/// **Taken from the shader rather than declared here**, because the sampling
429/// side inverts the box this builds: `mesh.slang`'s `sun_penumbra_texels` reads
430/// `2 * radius + SHADOW_CASTER_REACH` back out of a shadow-clip depth to get the
431/// metres a penumbra is sized from. Two declarations would let the matrix and
432/// its inverse drift apart.
433const CASTER_REACH: f32 = crcbl_shaders::mesh::SHADOW_CASTER_REACH;
434
435/// The constant part of the sun's shadow comparison bias, in **texels of the
436/// cascade the fragment landed in**.
437///
438/// # Texels, because a texel is what acne is made of
439///
440/// Acne is the shadow map quantising a receiver's own depth away across one
441/// texel, so what has to be covered is a world distance: the footprint of one
442/// texel, times how fast the surface climbs across it. `sun_visibility` in
443/// `shaders/mesh.slang` converts through `2 * radius / TILE` — the footprint of
444/// one texel of a cascade of that radius — and offsets the world position
445/// towards the light before projecting, exactly as `punctual_visibility` does
446/// for a cone or a cube face. One denomination for both light types.
447///
448/// The number this replaced was denominated in shadow-clip depth, which for an
449/// orthographic projection is linear and therefore looks like a world distance
450/// — the argument the shader used to carry. What it actually scaled with was the
451/// cascade's whole depth range, [`CASTER_REACH`] included, so it grew when a
452/// scene needed more caster reach and shrank when it needed less. The visible
453/// consequence was `apps/lantern`'s room: a lit strip 0.60 m wide along the foot
454/// of a wall, and a band down the left of the back wall three times too bright.
455///
456/// # This is the term the offset cannot predict, and one scene sets it
457///
458/// Depth quantisation is not what it covers: a cascade's range is tens of metres
459/// over a `D32Float`, so that error is micrometres, and what a texel's footprint
460/// explains on the facet the fragment is actually on is
461/// [`NORMAL_OFFSET_TEXELS`]' job — it walks the lookup sideways until it reads a
462/// texel the receiver owns. What is left over is the **seam between two
463/// facets**: adjacent triangles of a tessellated surface climb at different
464/// rates, and the texel their shared edge falls in stores the steeper one's
465/// depth wherever the lookup lands. No offset read off either facet predicts the
466/// other's, and this is what covers the difference.
467///
468/// `crcbl_render::scene::demo`'s dunes patch is the surface that sets it — an
469/// analytic height field sampled onto one-metre quads, so a facet's neighbours
470/// are as far from it in slope as anything in the tree. Counting the pixels in
471/// its lit valley floor that sit more than ten luma below the median of their
472/// own neighbourhood, at [`NORMAL_OFFSET_TEXELS`] held at two, on radv at
473/// 1280×960:
474///
475/// | Constant, in texels | Dark pixels in the valley |
476/// | ------------------- | ------------------------- |
477/// | 0 | 173 |
478/// | 0.5 | 45 |
479/// | 1 (shipped) | 24 |
480/// | 1.5 | 24 |
481/// | 2 | 24 |
482/// | 3 | 24 |
483///
484/// One is where the count stops falling, and there is **no margin above it**:
485/// what it covers is a bounded, understood quantity rather than a cover for an
486/// unknown, so buying margin in it is buying `apps/lantern`'s wall-foot strip
487/// back for nothing.
488///
489/// # Three was the number while the second term was a depth bias
490///
491/// It fell to one when [`NORMAL_OFFSET_TEXELS`] replaced a slope-scaled *depth*
492/// bias — the same count, but moving the receiver towards the light rather than
493/// across its own map. That term is what the wall-foot strip was made of:
494/// `apps/lantern`'s floor lies at a slope of 3.17, so two texels per unit of
495/// `tan` was six and a half texels of depth slack wherever the sun grazes, on
496/// top of this constant's three.
497///
498/// Measured through `apps/lantern`'s 1280×960 review frame on radv, walking the
499/// floor out from the `-x` wall at `room::SHADED_FLOOR`'s own line:
500///
501/// | Artefact | Depth-biased slope | Normal offset |
502/// | --------------------------------------- | ------------------ | ------------- |
503/// | Peak luma in the strip at the wall's foot | 140.3 | 51.0 |
504/// | Lit strip's half-fall width | 0.391 m | none |
505/// | Cornice lift over the shadowed back wall | 78.3 luma | 11.7 luma |
506/// | Dark pixels in the dunes' valley floor | 60 | 24 |
507///
508/// **51.0 is the shadowed floor's own value**, which is what makes the second
509/// column say the leak is gone rather than narrowed: the profile never rises
510/// above the shadow it is walking through, so there is no half-fall to measure.
511/// `crcbl_render::scene::demo`'s dunes patch reads 5 dark pixels before and 3
512/// after at the golden's own 256×192.
513///
514/// What it cost is recorded rather than hidden: the brass block's foot picks up
515/// a scalloped fringe a couple of pixels deep, on the period of the shadow
516/// texel, where the offset walks a receiver near a silhouette across the edge of
517/// its own caster. It is the standard cost of this direction, it is bounded by
518/// the offset itself, and it is a tenth the size of the strip it replaced.
519///
520/// # And a half back, when the filter grew a radius
521///
522/// One held while the filter was a 3×3 box, whose furthest tap is one texel out.
523/// `mesh.slang`'s `SHADOW_FILTER_TEXELS` reaches two, and a tap two texels out
524/// reads a depth two texels' worth of the receiver's own slope away — which this
525/// constant, and not [`NORMAL_OFFSET_TEXELS`], is what covers: an offset along
526/// the normal moves every tap together and cannot close a gap between them. The
527/// dunes patch, counted as above with the disc filter at two texels:
528///
529/// | This constant | Dark pixels in the valley | Strip at the wall's foot |
530/// | ------------- | ------------------------- | ------------------------ |
531/// | 1 | 47 | none |
532/// | 1.5 (shipped) | 25 | none |
533/// | 2 | 24 | 0.015 m |
534///
535/// A half-texel is where the count returns to what the box filter had and the
536/// strip has not yet come back. Two buys one more dark pixel and 15 mm of lit
537/// floor at the wall — a fortieth of the 0.391 m the seventh decision removed,
538/// but the wrong direction — so 1.5 ships.
539///
540/// # The console reads the cell, not this constant
541///
542/// [`r_shadow_bias`] declares this value as its own default and
543/// [`Cascades::params`] reads that variable, so the count a frame is drawn with
544/// is whatever the console holds. It is there for
545/// `apps/sundial`'s milestone 2 — the comparison, not the
546/// rung: acne and peter-panning are pulled in opposite directions by this number
547/// and a fixture is the only place that trade can be looked at. The variable's
548/// range starts at zero, which is where the acne it covers is read, and stops
549/// comfortably past 112 texels, which is where `apps/sundial`'s plinth has lost
550/// its shadow over the whole strip that fixture's camera can see — so nothing at
551/// the top of it draws anything the walk has not already drawn.
552const DEPTH_BIAS_TEXELS: f32 = 1.5;
553
554/// How far along its own geometric normal a receiver is moved before the sun's
555/// shadow lookup, per unit of `sin(acos(Ng·L))`, in the same texels.
556///
557/// `Ng` and not `N`: the offset is read off the rasterised facet, which is
558/// `geometric_normal_of` in `shaders/mesh.slang` and its own reason. Why the
559/// direction is the normal and not the light, and why a sine bounds it where the
560/// tangent it replaced had to be clamped, is `shadow_normal_offset` in that file.
561///
562/// # What sets it, and what caps it
563///
564/// The dunes patch again, at [`DEPTH_BIAS_TEXELS`] held at one and the filter
565/// still a 3×3 box, counted the same way, on radv at 1280×960:
566///
567/// | Offset, in texels | Dark pixels in the valley |
568/// | ----------------- | ------------------------- |
569/// | 0 | 1159 |
570/// | 1 | 74 |
571/// | 2 (shipped) | 24 |
572/// | 3 | 22 |
573/// | 4 | 22 |
574///
575/// Two is where the count reaches its floor — the last two rows are two pixels
576/// apart, which is the noise in this measurement — and the ceiling above it is
577/// **the thinnest wall in the tree**. An offset moves a receiver bodily, so one
578/// larger than the geometry it stands against moves it through: at
579/// [`DISTANCE`]'s outer cascade a texel is 62.5 mm of world, so two of them is
580/// 125 mm and `apps/lantern`'s walls are a shell of `room::SHELL`, which is
581/// 150 mm. Three would be 187.5 mm and past it. That bound is a property
582/// of the scene rather than of this number, so it is the *reason* two is shipped
583/// rather than three and not a claim that a leak was seen — none was.
584///
585/// # The console reads the cell here too
586///
587/// [`r_shadow_normal_offset`] declares this value as its default, on
588/// [`DEPTH_BIAS_TEXELS`]' terms exactly and for its reason. **The ceiling is a
589/// long way past the bound above**, and deliberately: two texels is what ships
590/// because three would move a receiver through `apps/lantern`'s shell, and a
591/// variable that stopped at the shipped count could not show what walking
592/// through one looks like. It stops comfortably past 44 texels, which is where
593/// `apps/sundial`'s plinth loses its whole shadow rather than only its contact —
594/// that fixture's
595/// `the_two_bias_counts_trade_acne_against_the_plinths_own_contact` is what
596/// measured it.
597const NORMAL_OFFSET_TEXELS: f32 = 2.0;
598
599crcbl_console::convar! {
600 /// The sun's constant shadow bias, in texels of the cascade a fragment
601 /// landed in. Too little draws acne; too much lifts a shadow off its caster.
602 pub static r_shadow_bias: f32 in 0.0 ..= 128.0 = DEPTH_BIAS_TEXELS;
603}
604
605crcbl_console::convar! {
606 /// How far along its own normal a receiver moves before the sun's shadow
607 /// lookup, in the same cascade texels.
608 pub static r_shadow_normal_offset: f32 in 0.0 ..= 64.0 = NORMAL_OFFSET_TEXELS;
609}
610
611/// The cascade matrices a frame shades and culls with.
612///
613/// One [`Mat4`] per cascade plus the split distances the fragment stage selects
614/// between them with. Everything here is what goes into
615/// `crcbl_shaders::mesh::FrameUniforms`; nothing in it names a GPU resource.
616#[derive(Clone, Copy, Debug, PartialEq)]
617pub struct Cascades {
618 /// World → cascade `i`'s shadow clip. Orthographic and **reversed-Z**, like
619 /// every other projection in the engine.
620 pub view_proj: [Mat4; CASCADES],
621 /// How far from the eye cascade `i` reaches, in world units, and therefore
622 /// the radius of the sphere it is fitted to.
623 ///
624 /// A `[f32; 4]` rather than a `[f32; CASCADES]` because that is the shape
625 /// the uniform block's `float4` takes; components past [`CASCADES`] repeat
626 /// the last real split, so an out-of-range read — which cannot happen —
627 /// would select the widest cascade rather than a zero that shadows
628 /// everything.
629 pub far: [f32; 4],
630}
631
632impl Cascades {
633 /// The cascade split distances, nearest first.
634 ///
635 /// The practical split scheme: a blend of a logarithmic and a uniform
636 /// division of `near .. DISTANCE`, weighted by [`SPLIT_LAMBDA`].
637 fn splits(near: f32) -> [f32; CASCADES] {
638 let mut out = [DISTANCE; CASCADES];
639 for (index, far) in out.iter_mut().enumerate() {
640 #[expect(
641 clippy::cast_precision_loss,
642 reason = "a cascade index is at most four"
643 )]
644 let ratio = (index + 1) as f32 / CASCADES as f32;
645 let logarithmic = near * (DISTANCE / near).powf(ratio);
646 let uniform = near.mul_add(1.0 - ratio, DISTANCE * ratio);
647 *far = SPLIT_LAMBDA.mul_add(logarithmic, (1.0 - SPLIT_LAMBDA) * uniform);
648 }
649 out
650 }
651
652 /// Builds this frame's cascades for `camera` under a light shining *from*
653 /// `to_light`.
654 ///
655 /// `to_light` is the same "towards the light" convention
656 /// [`DirectionalLight::direction`](crate::DirectionalLight::direction) uses,
657 /// and it does not have to be normalised.
658 ///
659 /// # Panics
660 ///
661 /// If `to_light` has no direction — a zero or non-finite vector — or if the
662 /// camera is degenerate, on [`Camera::view`]'s terms. Both produce a matrix
663 /// of `NaN`s that reaches the shader as an empty shadow map, which is the
664 /// failure mode this whole slice can hide behind.
665 #[must_use]
666 pub fn new(camera: &Camera, to_light: Vec3) -> Self {
667 let to_light = to_light.normalize_or_zero();
668 assert!(
669 to_light.length_squared() > 0.0,
670 "the sun must point somewhere: {to_light:?} has no direction"
671 );
672 // Only the eye is read, so an orthographic camera needs no special case:
673 // the sphere is centred on the eye whatever the projection is.
674 let eye = camera.eye;
675 assert!(eye.is_finite(), "the camera's eye is not finite: {eye:?}");
676
677 let near = match camera.projection {
678 crate::camera::Projection::Perspective { near, .. }
679 | crate::camera::Projection::Orthographic { near, .. } => near.max(f32::MIN_POSITIVE),
680 };
681 let splits = Self::splits(near);
682
683 let mut view_proj = [Mat4::IDENTITY; CASCADES];
684 for (index, matrix) in view_proj.iter_mut().enumerate() {
685 *matrix = cascade_matrix(eye, to_light, splits[index]);
686 }
687 // The last real split fills the unused components; see `far`.
688 let mut far = [splits[CASCADES - 1]; 4];
689 far[..CASCADES].copy_from_slice(&splits);
690 Self { view_proj, far }
691 }
692
693 /// The `shadow_params` vector the fragment stage reads: the atlas's two
694 /// texel sizes, then the constant and normal-offset biases — the biases in
695 /// **cascade texels**, which is the unit this module's `DEPTH_BIAS_TEXELS`
696 /// explains and `sun_visibility` in `shaders/mesh.slang` converts.
697 ///
698 /// **The two biases come from [`r_shadow_bias`] and
699 /// [`r_shadow_normal_offset`] rather than from the constants**, whose values
700 /// those variables declare as their defaults. This vector is rebuilt for
701 /// every frame's block, so a cell moved between two frames reaches the second
702 /// of them — which is what makes the pair a comparison a person can walk
703 /// rather than a rebuild.
704 ///
705 /// **Both texel sizes, even where the grid is square and they are equal.**
706 /// The shader's PCF kernel steps in *tile* space and scales by
707 /// [`ATLAS_COLUMNS`] and [`ATLAS_ROWS`] to get back to one shadow-map texel,
708 /// so a grid that is not square — which it stops being the moment a point
709 /// light's six tiles arrive — needs the two apart. Deriving one from the
710 /// other is how that kernel ends up sampling a rectangle.
711 #[must_use]
712 pub fn params() -> [f32; 4] {
713 let (width, height) = atlas_extent();
714 #[expect(
715 clippy::cast_precision_loss,
716 reason = "an atlas extent is a few thousand texels"
717 )]
718 let inverse = [1.0 / width as f32, 1.0 / height as f32];
719 [
720 inverse[0],
721 inverse[1],
722 r_shadow_bias.get_f32(),
723 r_shadow_normal_offset.get_f32(),
724 ]
725 }
726}
727
728/// The shadow atlas's extent in texels: an [`ATLAS_COLUMNS`] by [`ATLAS_ROWS`]
729/// grid of [`TILE`]-sided tiles.
730#[must_use]
731pub const fn atlas_extent() -> (u32, u32) {
732 (TILE * ATLAS_COLUMNS, TILE * ATLAS_ROWS)
733}
734
735/// Where root cell `index` starts in the atlas, in texels.
736///
737/// Row-major, so the first cells are the top row while [`ATLAS_COLUMNS`] is at
738/// least [`CASCADES`]. That is the arrangement the cascade goldens were blessed
739/// under; the texels themselves move whenever [`TILE`] or [`ATLAS_COLUMNS`]
740/// does, so a change to either is one those goldens have to be re-blessed
741/// through.
742///
743/// **A cell, not a slot.** It is [`AtlasAllocator`]'s root order — where a
744/// level-0 tile lands — and a slot's map is wherever the allocator put it, which
745/// is [`Selection::atlas_rect`]. The two coincide while every map takes a whole
746/// cell, which is what this rung shipped with.
747#[must_use]
748pub const fn tile_origin(index: usize) -> (u32, u32) {
749 let index = index as u32;
750 (
751 TILE * (index % ATLAS_COLUMNS),
752 TILE * (index / ATLAS_COLUMNS),
753 )
754}
755
756/// Which atlas tile light tile `tile` of the light region is.
757///
758/// The one place the "cascades first, then the lights" split is written down.
759/// Both the viewport the shadow pass sets and the tile `mesh.slang` samples come
760/// through it — the shader's own `light_tile` is the same arithmetic, and
761/// `crcbl_shaders::mesh`'s drift test is what holds the two together.
762#[must_use]
763pub const fn light_tile(tile: usize) -> usize {
764 CASCADES + tile
765}
766
767/// How many light tiles `light` needs to be shadowed: [`POINT_FACES`] for a
768/// point light, one for a spot.
769///
770/// The whole of what makes the light region a run allocator rather than an array
771/// of slots, so it is one function both [`Selection`] and [`crate::forward`] ask
772/// rather than a `match` each.
773#[must_use]
774pub const fn tile_span(light: &Light) -> usize {
775 match light {
776 Light::Point(_) => POINT_FACES,
777 Light::Spot(_) => 1,
778 // **No tiles, and never asked for any**: [`can_be_shadowed`] refuses a
779 // rectangle before [`Selection`] reaches this, so the run allocator
780 // never sees a zero-length run. The zero is what a rectangle's span
781 // actually is rather than a placeholder — an area light has no single
782 // view to render a map from, and giving it one is a rung of its own that
783 // `docs/backlog.md` carries.
784 Light::Rect(_) => 0,
785 }
786}
787
788/// One cascade's world → shadow-clip matrix: an orthographic box around a
789/// sphere of `radius` centred on `eye`, snapped to whole texels.
790fn cascade_matrix(eye: Vec3, to_light: Vec3, radius: f32) -> Mat4 {
791 // A basis that is not parallel to the light. `Vec3::Y` is the usual up and
792 // is wrong for exactly one light — one straight overhead, which is the
793 // commonest light there is — so the fallback is picked rather than asserted
794 // against.
795 let up = if to_light.dot(Vec3::Y).abs() > 0.99 {
796 Vec3::Z
797 } else {
798 Vec3::Y
799 };
800 // **The light's view is anchored at the world origin, not at the camera.**
801 // That is what makes the snap below mean anything: a view built from the
802 // eye moves whenever the eye does, so quantising a position *inside* it
803 // quantises a coordinate whose own frame is already sliding — the matrix
804 // changes for a sub-texel step and the shimmer the snap exists to remove is
805 // still there. Anchored, the frame is a pure function of the light, and
806 // every cascade of every frame measures against the same one.
807 let view = glam::camera::rh::view::look_at_mat4(Vec3::ZERO, -to_light, up);
808
809 // The snap. The sphere's centre is expressed in that fixed light frame and
810 // quantised to whole texels, so a camera that moves by less than one
811 // texel's worth of world produces a byte-identical matrix and the shadow
812 // edges on a static surface do not move at all.
813 #[expect(
814 clippy::cast_precision_loss,
815 reason = "a tile is a few thousand texels"
816 )]
817 let texel = 2.0 * radius / TILE as f32;
818 let centre = snap_to_texel((view * eye.extend(1.0)).xyz(), texel);
819
820 // Right-handed view space looks down `-z`, so a light-space depth is `-z`.
821 // The near end is pulled back past the sphere so a caster standing between
822 // the sun and it still writes depth; the far end is the back of the sphere
823 // and nothing beyond it can shadow anything inside.
824 let farthest = radius - centre.z;
825 let nearest = -centre.z - radius - CASTER_REACH;
826
827 glam::camera::rh::proj::directx::orthographic(
828 centre.x - radius,
829 centre.x + radius,
830 centre.y - radius,
831 centre.y + radius,
832 // **Swapped, and that is the whole reversal** — the same trick, for the
833 // same reason, as `Projection::Orthographic`'s. The constructor maps its
834 // fifth argument to depth 0 and its sixth to depth 1, so handing it the
835 // far distance and then the near one puts 1.0 at the light. That is
836 // reversed-Z, and it is what `CompareOp::Greater` everywhere else
837 // expects.
838 farthest,
839 nearest,
840 ) * view
841}
842
843/// A spot's world → shadow-clip matrix: a **perspective** projection down the
844/// cone, reversed-Z, covering the cone exactly.
845///
846/// # Why there is no texel snap here
847///
848/// The cascades are snapped to whole texels because their box follows the
849/// camera, so a sub-texel step of the eye would otherwise resample a static
850/// surface at a new offset and crawl its shadow edges. Nothing about a spot's
851/// map depends on the camera: it is a pure function of the light's own position,
852/// axis and cone, so a still light produces a byte-identical matrix frame after
853/// frame and there is nothing to quantise away. `a_still_spot_produces_the_same_matrix`
854/// is the assertion, and it is the same guarantee the snap buys the sun rather
855/// than a weaker one.
856///
857/// The snap could not transfer even if it were wanted: it works by quantising a
858/// position in a *fixed light frame* whose texel size is constant across the
859/// whole map, and a perspective map's texel covers a world footprint that grows
860/// linearly with depth. There is no one step to round to.
861///
862/// # Panics
863///
864/// If the light's axis has no direction or its position is not finite. Both
865/// produce a matrix of `NaN`s, which reaches the shader as a map that shadows
866/// nothing — the failure this whole slice can hide behind.
867#[must_use]
868pub fn spot_matrix(spot: &SpotLight) -> Mat4 {
869 let axis = spot.direction.normalize_or_zero();
870 assert!(
871 axis.length_squared() > 0.0,
872 "a spot must point somewhere: {:?} has no direction",
873 spot.direction
874 );
875 assert!(
876 spot.position.is_finite(),
877 "the spot's position is not finite: {:?}",
878 spot.position
879 );
880
881 // A basis that is not parallel to the axis, on `cascade_matrix`'s terms and
882 // for its reason: a spot pointing straight down is the commonest spot there
883 // is, and it is exactly the one `Vec3::Y` cannot be the up vector of.
884 let up = if axis.dot(Vec3::Y).abs() > 0.99 {
885 Vec3::Z
886 } else {
887 Vec3::Y
888 };
889 let view = glam::camera::rh::view::look_at_mat4(spot.position, spot.position + axis, up);
890
891 // The cone's outer half-angle is the projection's *half* field of view, so
892 // the map covers the cone and no more: every texel of the tile is somewhere
893 // the light can reach. `SpotLight::outer_angle` may be narrower than the
894 // inner one on the way in — `Light::row` widens it rather than trusting it
895 // — so the same widening happens here, or the map would be narrower than the
896 // cone it is sampled for.
897 let outer = spot.outer_angle.max(spot.inner_angle);
898 let far = spot.radius.max(PUNCTUAL_NEAR * 2.0);
899
900 glam::camera::rh::proj::directx::perspective(
901 2.0 * outer,
902 // Square: the tile is, and a cone has no other aspect ratio to have.
903 1.0,
904 // **Swapped, and that is the whole reversal** — the same trick, for the
905 // same reason, as `cascade_matrix`'s orthographic pair and
906 // `Projection::Perspective`'s. The constructor maps its third argument
907 // to depth 0 and its fourth to depth 1, so handing it the far distance
908 // and then the near one puts 1.0 at the light. That is reversed-Z, and
909 // it is what `CompareOp::Greater` everywhere else expects.
910 far,
911 PUNCTUAL_NEAR,
912 ) * view
913}
914
915/// The direction point-light face `face` looks along.
916///
917/// **The cube-map convention**: `+X, -X, +Y, -Y, +Z, -Z` as faces 0 to 5. It is a
918/// convention rather than a derivation, and the only thing that has to agree with
919/// it is `point_face` in `shaders/mesh.slang`, which picks a face out of the
920/// largest component of the direction from the light. A shader selecting face 3
921/// where the host built face 2's matrix samples a map of somewhere else, and
922/// draws a frame that has shadows in it —
923/// `every_face_of_a_point_light_covers_its_own_direction_and_no_other` is what
924/// refuses that here, and `crcbl`'s `Scene::PointShadow` is what refuses it
925/// through the shader.
926///
927/// # Panics
928///
929/// If `face` is not one of [`POINT_FACES`] faces.
930#[must_use]
931pub fn face_axis(face: usize) -> Vec3 {
932 match face {
933 0 => Vec3::X,
934 1 => Vec3::NEG_X,
935 2 => Vec3::Y,
936 3 => Vec3::NEG_Y,
937 4 => Vec3::Z,
938 5 => Vec3::NEG_Z,
939 _ => panic!("a point light has {POINT_FACES} faces, not a face {face}"),
940 }
941}
942
943/// A point light's world → shadow-clip matrix for face `face`: a **90°
944/// perspective** down that face's axis, reversed-Z.
945///
946/// The six of them tile the whole sphere exactly, which is what makes selecting
947/// one by the major axis of the direction from the light correct rather than
948/// approximate: at 90° with a square aspect the frustum's edge planes are the
949/// diagonals `|x| = |z|` and `|y| = |z|`, and those are precisely where the major
950/// axis changes.
951///
952/// # Why there is no texel snap here
953///
954/// [`spot_matrix`]'s reason exactly: nothing about the map depends on the camera,
955/// so a still light produces a byte-identical matrix frame after frame and there
956/// is nothing to quantise away.
957///
958/// # Panics
959///
960/// If the light's position is not finite, or if `face` is not one of
961/// [`POINT_FACES`] faces. A non-finite position produces a matrix of `NaN`s,
962/// which reaches the shader as a map that shadows nothing — the failure this
963/// whole slice can hide behind.
964#[must_use]
965pub fn point_matrix(point: &PointLight, face: usize) -> Mat4 {
966 assert!(
967 point.position.is_finite(),
968 "the point light's position is not finite: {:?}",
969 point.position
970 );
971 let axis = face_axis(face);
972 // A basis that is not parallel to the axis, on `cascade_matrix`'s terms. Two
973 // of the six faces look along `Y`, so the fallback is picked rather than
974 // asserted against — and *which* up vector a face takes only has to be
975 // consistent, because both the matrix that renders the tile and the matrix
976 // that samples it are this one. A cube map would have to match the API's own
977 // per-face orientation; an atlas of six ordinary maps has no such obligation.
978 let up = if axis.y == 0.0 { Vec3::Y } else { Vec3::Z };
979 let view = glam::camera::rh::view::look_at_mat4(point.position, point.position + axis, up);
980
981 let far = point.radius.max(PUNCTUAL_NEAR * 2.0);
982 glam::camera::rh::proj::directx::perspective(
983 // 90°, and it is the field of view that makes six faces a sphere: a
984 // narrower one leaves a gap at every face's edge, a wider one overlaps
985 // and wastes the tile.
986 std::f32::consts::FRAC_PI_2,
987 // Square: the tile is, and a cube face has no other aspect ratio.
988 1.0,
989 // **Swapped, and that is the whole reversal** — `spot_matrix`'s pair,
990 // for its reason.
991 far,
992 PUNCTUAL_NEAR,
993 ) * view
994}
995
996/// The frustum a point light's **one** cull runs against: the axis-aligned box
997/// around its sphere of influence.
998///
999/// Topic 18's fourth decision, in the only place it has arithmetic. A cascade and
1000/// a spot cull against `Frustum::from_view_projection` of the matrix they render
1001/// with, and a point light has six of those — so it culls against what all six
1002/// share instead, which is the sphere the light reaches at all. Conservative
1003/// against every face and against the sphere itself (a box is larger), which is
1004/// the safe direction: a caster wrongly kept costs vertex work on one face, and
1005/// one wrongly rejected is a missing shadow.
1006#[must_use]
1007pub fn point_frustum(point: &PointLight) -> Frustum {
1008 let (centre, radius) = (point.position, point.radius);
1009 // Inward normals, on `Frustum`'s convention: a point is inside a plane when
1010 // `normal · p + w >= 0`.
1011 Frustum {
1012 planes: [
1013 glam::Vec4::new(1.0, 0.0, 0.0, radius - centre.x),
1014 glam::Vec4::new(-1.0, 0.0, 0.0, radius + centre.x),
1015 glam::Vec4::new(0.0, 1.0, 0.0, radius - centre.y),
1016 glam::Vec4::new(0.0, -1.0, 0.0, radius + centre.y),
1017 glam::Vec4::new(0.0, 0.0, 1.0, radius - centre.z),
1018 glam::Vec4::new(0.0, 0.0, -1.0, radius + centre.z),
1019 ],
1020 }
1021}
1022
1023/// Whether a light can be given tiles at all.
1024///
1025/// Split out so the reason a light was refused is one predicate rather than a
1026/// condition buried in a fold: a zero radius has no frustum, a non-finite
1027/// position has no view, a cone at or past [`MAX_SPOT_HALF_ANGLE`] has no
1028/// projection, a **fill** light was asked not to occlude, and an area light has
1029/// no single view a map could be rendered from. All of them light without
1030/// occluding.
1031///
1032/// The fill test is the leading one and covers every kind, and it is the only
1033/// thing standing between a fill point light or spot and a tile: every variant
1034/// carries [`fill`](crate::PointLight::fill) now, and the arms below judge a
1035/// light by its shape alone. Delete the test and
1036/// `a_fill_light_is_refused_a_tile_where_the_same_light_takes_one` goes red,
1037/// which is what the flag's shadow half is asserted by. The `Rect` arm refuses
1038/// a rectangle regardless, so on that kind alone the test still decides
1039/// nothing.
1040///
1041/// What *is* enforced is that this function is the only thing that hands a
1042/// light a tile, so a fill light's row carries `NO_SHADOW_TILE` and
1043/// `mesh.slang` needs no test of its own for the shadow — only for the
1044/// specular, which is the flag's other half and is enforced there.
1045fn can_be_shadowed(light: &Light) -> bool {
1046 if light.is_fill() {
1047 return false;
1048 }
1049 match light {
1050 Light::Point(point) => point.radius > 0.0 && point.position.is_finite(),
1051 Light::Spot(spot) => {
1052 spot.radius > 0.0
1053 && spot.direction.normalize_or_zero().length_squared() > 0.0
1054 && spot.position.is_finite()
1055 && spot.outer_angle.max(spot.inner_angle) < MAX_SPOT_HALF_ANGLE
1056 }
1057 // A rectangle radiates from a surface rather than from a point, so
1058 // there is no single centre of projection a shadow map could be
1059 // rendered from. An area light's shadow is a rung of its own, and
1060 // `docs/backlog.md` records that it is not built.
1061 Light::Rect(_) => false,
1062 }
1063}
1064
1065/// How wide a light's shadow map is in the world, at the far end of the frustum
1066/// it is rendered with.
1067///
1068/// **The map's own footprint, not the light's sphere**, and the difference is
1069/// the whole reason this is a function rather than `2 * radius`: a spot's map
1070/// covers its cone and a point light's face covers a right angle, so two lights
1071/// of one radius spread their texels over world regions that differ by
1072/// `tan(outer)`. A narrow cone already has fine texels at the size it was given,
1073/// and judging it by its sphere would demote it for being narrow.
1074///
1075/// A rectangle has no map — [`can_be_shadowed`] refuses it one — so it has no
1076/// footprint either, and the zero it answers with is what
1077/// [`tile_span`] answers for the same light and for the same reason.
1078fn map_extent(light: &Light) -> f32 {
1079 match light {
1080 // A cube face is a 90° frustum, so its half-angle's tangent is one and
1081 // the far face is exactly the light's diameter across. `point_matrix`
1082 // is where that right angle is built.
1083 Light::Point(point) => 2.0 * point.radius,
1084 Light::Spot(spot) => {
1085 // The widened angle `spot_matrix` projects with, not the field as
1086 // it arrived: `Light::row` widens an outer angle narrower than the
1087 // inner one, and a footprint taken from the narrower of the two
1088 // would describe a map nothing renders.
1089 let outer = spot.outer_angle.max(spot.inner_angle);
1090 2.0 * spot.radius * outer.tan()
1091 }
1092 Light::Rect(_) => 0.0,
1093 }
1094}
1095
1096/// How much of the frame's **height** a light's shadow map covers on screen.
1097///
1098/// Topic 18's rule — "projected screen influence", the metric family
1099/// topic 25's level selection uses — with the two refinements this
1100/// module's priority rung needed to make one number answer two questions:
1101///
1102/// * **[`map_extent`] rather than the sphere's diameter**, so the number is
1103/// about the map rather than about the light. What decides both which lights
1104/// deserve a tile and how large that tile should be is how many texels a map
1105/// delivers per pixel of what it covers, and a spot's map covers its cone.
1106/// * **A fraction of the frame rather than a count of pixels**, which makes it
1107/// independent of the viewport: the projection's own scale over the distance
1108/// to the light, with no viewport height in it at all. A scene therefore
1109/// allocates the same tiles at 256×192 as at 1920×1080, which is what makes a
1110/// golden at the small extent evidence about the large one.
1111///
1112/// **An orthographic camera has no distance falloff**, so its coverage is the
1113/// footprint over the visible height and nothing else —
1114/// [`Projection::pixels_per_unit`](crate::camera::Projection::pixels_per_unit)
1115/// at a height of one is exactly that scale for both variants, and the divide
1116/// is what only a perspective camera takes. The distance is floored so a light
1117/// the eye is standing inside is the most important light there is rather than
1118/// an infinity.
1119fn coverage(light: &Light, camera: &Camera) -> f32 {
1120 let scale = camera.projection.pixels_per_unit(1.0);
1121 let extent = map_extent(light);
1122 if camera.projection.is_orthographic() {
1123 return extent * scale;
1124 }
1125 let (position, _) = light.sphere();
1126 extent * scale / camera.eye.distance(position).max(1e-4)
1127}
1128
1129/// How much better a challenger must be before it takes a tile off the light
1130/// holding it.
1131///
1132/// The selection's hysteresis, and it is owed for the reason
1133/// topic 25's was: two lights either side of the cutoff would
1134/// otherwise swap tiles whenever the camera drifts, and a shadow appearing and
1135/// disappearing frame to frame is far worse than the wrong one of two being
1136/// shadowed. Applied as a bonus on the incumbent's score, which is the same
1137/// shape as `ForwardRenderer::lod_hold_ratio` — a level is held until the error
1138/// clearly drops.
1139const HOLD_RATIO: f32 = 1.25;
1140
1141/// The [`coverage`] at which a light's map is worth a whole root cell, and
1142/// therefore the top of the ladder [`tile_level`] walks.
1143///
1144/// # The ladder halves with the tile, which is why one number sets it
1145///
1146/// A level of the quadtree is a halving of the tile's side, so the coverage that
1147/// earns it halves too: a map covering half as much of the frame delivers the
1148/// same texels per pixel at half the side. Every threshold below the first is
1149/// therefore this over a power of two, and there is one number here rather than
1150/// [`TILE_LEVELS`] of them.
1151///
1152/// # What the number is, and what it is not
1153///
1154/// **It is the conservative end of a sweep, set by the fixtures that must not
1155/// move.** Read as texels per pixel it is generous: a quarter of a 1080-pixel
1156/// frame is 270 pixels of footprint against a whole cell's [`TILE`] texels, so
1157/// the shipped anchor hands a light nearly three shadow texels for every screen
1158/// pixel its map covers. The parameter-free rule is one texel per pixel, which
1159/// is where a map stops being oversampled — a light keeps a whole cell only
1160/// while its footprint spans more than half [`TILE`] pixels of the frame, so the
1161/// anchor would have to be that over the frame's height and would *rise* as the
1162/// frame shrinks. At the 256×192 every golden in this tree is blessed at, it
1163/// demotes every punctual light in the tree, `apps/lantern`'s pair included.
1164/// Shipping it is a re-bless of every punctual shadow golden, which is a
1165/// measurement rung rather than this one; `docs/backlog.md` carries it.
1166///
1167/// Measured against the tree's own fixtures, as this metric is independent of
1168/// the extent they are rendered at:
1169///
1170/// | Fixture | Coverage | Level here |
1171/// | ------------------------------------ | -------- | ---------- |
1172/// | `Scene::PointShadow`'s lamp | 3.06 | 0 |
1173/// | `Scene::SpotShadow`'s cone | 1.41 | 0 |
1174/// | `apps/lantern`'s lamp, worst of orbit | 1.06 | 0 |
1175/// | `apps/lantern`'s corner spot | 0.37 | 0 |
1176///
1177/// The corner spot is the one that binds: at this anchor it clears a whole cell
1178/// by half as much again, and at an anchor of 0.375 it would not. Nothing in the
1179/// tree sits inside the band [`LEVEL_HOLD_RATIO`] opens under it.
1180const WHOLE_CELL_COVERAGE: f32 = 0.25;
1181
1182/// How far a light's [`coverage`] must fall below the threshold that earned it
1183/// its tile before the tile halves.
1184///
1185/// Topic 25's "switch-up and switch-down differ", at this module's
1186/// other boundary: without a band a light drifting along a threshold halves and
1187/// doubles its map every frame, and a shadow whose resolution flickers is worse
1188/// than one that is a size too small. A ratio rather than an offset because the
1189/// thresholds are a geometric ladder — a fixed offset is most of the bottom rung
1190/// and none of the top.
1191///
1192/// The same fifth of the budget `ForwardRenderer::lod_hold_ratio` opens for the
1193/// same reason, and it is deliberately the same number: the two bands are one
1194/// rule about one kind of flicker, and a reader who has understood one has
1195/// understood the other.
1196const LEVEL_HOLD_RATIO: f32 = 0.8;
1197
1198/// The [`coverage`] a map must reach to be worth level `level`.
1199///
1200/// [`WHOLE_CELL_COVERAGE`] halved once per level, so the ladder's steps are the
1201/// quadtree's own. The coarsest level has no threshold — every eligible light
1202/// gets at least [`MIN_TILE`] — and asking for one past the ladder answers with
1203/// a coverage nothing reaches rather than with a level nothing can allocate.
1204fn level_threshold(level: usize) -> f32 {
1205 if level + 1 >= TILE_LEVELS {
1206 return 0.0;
1207 }
1208 #[expect(
1209 clippy::cast_precision_loss,
1210 reason = "the guard above bounds the shift by TILE_LEVELS"
1211 )]
1212 let halvings = (1u32 << level) as f32;
1213 WHOLE_CELL_COVERAGE / halvings
1214}
1215
1216/// Which of [`TILE_LEVELS`] tile sizes a map of `coverage` earns, given the
1217/// level it held last frame.
1218///
1219/// Topic 45's priority rung: a near, large light takes a whole
1220/// cell and a far or narrow one takes a halving of it. `previous` is the level
1221/// this light held last frame, or [`None`] for a light that held none — and a
1222/// light with no history starts at the coarsest level and climbs, which is
1223/// exactly the answer the ladder gives with no band at all. That is the property
1224/// `a_light_with_no_history_lands_where_the_sharp_ladder_puts_it` reads back.
1225///
1226/// The two walks are the band: a tile grows only once the coverage reaches the
1227/// finer level's threshold outright, and shrinks only once it falls
1228/// [`LEVEL_HOLD_RATIO`] below the one it holds. Between them the previous answer
1229/// stands, which is the whole of the hysteresis.
1230fn tile_level(coverage: f32, previous: Option<usize>) -> usize {
1231 let mut level = previous.unwrap_or(TILE_LEVELS - 1).min(TILE_LEVELS - 1);
1232 while level > 0 && coverage >= level_threshold(level - 1) {
1233 level -= 1;
1234 }
1235 while level + 1 < TILE_LEVELS && coverage < level_threshold(level) * LEVEL_HOLD_RATIO {
1236 level += 1;
1237 }
1238 level
1239}
1240
1241/// Whether `span` tiles from `base` are inside the light region and all free.
1242///
1243/// A function rather than a closure inside [`Selection::update`]'s loop, because
1244/// the loop takes `used` mutably as soon as it has an answer.
1245fn run_is_free(used: &[bool; LIGHT_TILES], base: usize, span: usize) -> bool {
1246 base + span <= LIGHT_TILES && used[base..base + span].iter().all(|tile| !*tile)
1247}
1248
1249/// One shadowed light: which light it is, where its run of tiles starts, and
1250/// how large each of them is.
1251///
1252/// The triple rather than a light index alone, because a slot no longer decides
1253/// a tile: a spot owns one tile and a point owns [`POINT_FACES`], so where a
1254/// light's map lives is an allocation and not an index — and since
1255/// topic 45's priority rung, how *large* it is is an allocation
1256/// too.
1257#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1258pub struct Assignment {
1259 /// Which light, as an index into the list [`Selection::update`] was given.
1260 pub light: usize,
1261 /// The first of the light's tiles, as an index into the atlas's light region
1262 /// — so [`light_tile`] of it is the atlas tile, and it is also the number
1263 /// `Light::row` puts in `GpuLight::shadow_tile`.
1264 pub base: usize,
1265 /// Which of [`TILE_LEVELS`] sizes each of those tiles is: 0 a whole root
1266 /// cell of [`TILE`] texels, each one below a halving of it.
1267 ///
1268 /// **One level for the whole run**, which is what a point light needs: its
1269 /// six faces are one map of one sphere seen six ways, and a cube with one
1270 /// face finer than its neighbour would change resolution across a seam.
1271 ///
1272 /// Carried on the assignment rather than recomputed because it is the
1273 /// hysteresis' memory — `tile_level` reads last frame's level out of
1274 /// [`Selection::slots`] to decide this frame's.
1275 pub level: usize,
1276}
1277
1278/// Which lights hold the atlas's light tiles, and its memory of last frame.
1279///
1280/// Topic 18's 2026-08-13 rule, whole: eligible lights are ranked by projected
1281/// screen influence, ties break by index so a frame's answer does not depend on
1282/// the order a caller happened to build the list in, they take slots and runs of
1283/// tiles in that order until either budget runs out, and an incumbent keeps what
1284/// it holds until a challenger clearly beats it.
1285///
1286/// **A light that gets no tiles still lights.** Nothing here removes a light from
1287/// the frame; it decides which of them also occlude. A light can miss out two
1288/// ways — no free slot, or no free *run* long enough — and the second is what a
1289/// scene with three point lights hits: two cubes leave less than a cube behind
1290/// them, so the third point light lights without occluding while a spot ranked
1291/// below it still fits in the tiles left over.
1292#[derive(Clone, Debug, Default, PartialEq, Eq)]
1293pub struct Selection {
1294 /// What holds slot `i`, or `None` if the slot is free.
1295 slots: [Option<Assignment>; LIGHT_SLOTS],
1296 /// The atlas's free space, spent and given back by [`Selection::lay_out`]
1297 /// once per [`Selection::update`].
1298 ///
1299 /// Kept here rather than rebuilt because it holds what every slot is
1300 /// holding: since topic 45's static-caching rung a tile
1301 /// outlives the frame it was allocated in, so an allocator built fresh each
1302 /// frame would be one that could not describe what the image contains.
1303 allocator: AtlasAllocator,
1304 /// The tile behind slot `i`'s rectangle, or [`None`] for a slot no map is
1305 /// rendered into.
1306 ///
1307 /// The allocator's own handle rather than a second record of it: `rects` is
1308 /// what everything else reads and this is what gives that rectangle back.
1309 /// Indexed as `rects` is.
1310 tiles: [Option<Tile>; TILES],
1311 /// Where atlas slot `i`'s map was rendered, or [`TileRect::EMPTY`] for a
1312 /// slot no map was rendered into.
1313 ///
1314 /// Indexed the way the frame block's matrices are — the cascades first,
1315 /// then [`light_tile`] of a light-region slot — so the row that names a
1316 /// matrix names this rectangle too.
1317 rects: [TileRect; TILES],
1318}
1319
1320impl Selection {
1321 /// Re-runs the selection over `lights` for `camera`.
1322 ///
1323 /// `lights` is the caller's own list and the indices below are into it; a
1324 /// caller whose shader rows are offset from it — the sun is row 0 — maps
1325 /// them itself.
1326 ///
1327 /// **The whole camera rather than its eye**, since the priority rung: what
1328 /// a light's map covers on screen depends on the projection as well as on
1329 /// the distance, and `coverage` is the one number both the ranking and the
1330 /// tile size are decided by.
1331 pub fn update(&mut self, lights: &[Light], camera: &Camera) {
1332 // Last frame's answer, kept whole: an incumbent's score is boosted and
1333 // its run is preferred, and both need to be read after `self.slots` has
1334 // been rebuilt.
1335 let previous = self.slots;
1336 let held_by = |index: usize| {
1337 previous
1338 .iter()
1339 .flatten()
1340 .find(|assignment| assignment.light == index)
1341 };
1342
1343 // Score every eligible light, with the incumbents' scores boosted. That
1344 // ordering *is* the hysteresis: a challenger takes a held tile only by
1345 // beating the incumbent by `HOLD_RATIO`, which is the statement this
1346 // constant is written as. An incumbent that has dropped off the end of
1347 // the list, or stopped being eligible, is simply not in the ranking — the
1348 // list is rebuilt every frame and an index is only meaningful against the
1349 // list it was taken from.
1350 //
1351 // The coverage rides beside the score rather than being recomputed for
1352 // the light that wins a run: the score *is* the coverage with the
1353 // incumbent's bonus on it, and the tile size below is decided by the
1354 // coverage without it — one measurement, read twice.
1355 let mut ranked: Vec<(usize, f32, f32)> = lights
1356 .iter()
1357 .enumerate()
1358 .filter(|(_, light)| can_be_shadowed(light))
1359 .map(|(index, light)| {
1360 let coverage = coverage(light, camera);
1361 let score = coverage
1362 * if held_by(index).is_some() {
1363 HOLD_RATIO
1364 } else {
1365 1.0
1366 };
1367 (index, score, coverage)
1368 })
1369 .collect();
1370 // Descending by score, ties by index. `total_cmp` rather than
1371 // `partial_cmp`: a `NaN` score would otherwise make the comparator
1372 // inconsistent and the sort's output arbitrary, and this is a frame's
1373 // *stable* answer or it is nothing.
1374 ranked.sort_by(|left, right| right.1.total_cmp(&left.1).then(left.0.cmp(&right.0)));
1375
1376 // Hand out runs in rank order. **Not truncated to the slot count first**:
1377 // a light that cannot fit — a point light with a spot already holding a
1378 // tile in the middle of the region — must not take the budget down with
1379 // it, so the walk continues and a smaller light behind it can still be
1380 // shadowed.
1381 let mut used = [false; LIGHT_TILES];
1382 let mut chosen: Vec<Assignment> = Vec::with_capacity(LIGHT_SLOTS);
1383 for (index, _, coverage) in ranked {
1384 if chosen.len() == LIGHT_SLOTS {
1385 break;
1386 }
1387 let span = tile_span(&lights[index]);
1388 // The run it already had, if that run is still free — so a light's
1389 // map does not move across the atlas while it goes on being
1390 // selected. Otherwise the first run long enough.
1391 let Some(base) = held_by(index)
1392 .map(|assignment| assignment.base)
1393 .filter(|base| run_is_free(&used, *base, span))
1394 .or_else(|| (0..LIGHT_TILES).find(|base| run_is_free(&used, *base, span)))
1395 else {
1396 continue;
1397 };
1398 for tile in &mut used[base..base + span] {
1399 *tile = true;
1400 }
1401 // The priority rung's answer, and the band around it: the level this
1402 // light held last frame is what [`tile_level`] holds against, and a
1403 // light that held none climbs the ladder from its bottom — which is
1404 // the sharp answer.
1405 let level = tile_level(coverage, held_by(index).map(|held| held.level));
1406 chosen.push(Assignment {
1407 light: index,
1408 base,
1409 level,
1410 });
1411 }
1412
1413 // Incumbents keep the slot they had, so a light's cull — and with it the
1414 // per-instance LOD state that `DrawGen` holds for it — does not jump
1415 // between slots while the light is still selected. Whatever is left fills
1416 // the free slots in rank order.
1417 let mut slots = [None; LIGHT_SLOTS];
1418 for assignment in &chosen {
1419 if let Some(slot) = previous
1420 .iter()
1421 .position(|held| held.is_some_and(|held| held.light == assignment.light))
1422 {
1423 slots[slot] = Some(*assignment);
1424 }
1425 }
1426 for assignment in &chosen {
1427 if slots.contains(&Some(*assignment)) {
1428 continue;
1429 }
1430 if let Some(free) = slots.iter_mut().find(|slot| slot.is_none()) {
1431 *free = Some(*assignment);
1432 }
1433 }
1434 self.slots = slots;
1435 self.lay_out(lights);
1436 }
1437
1438 /// Hands each occupied atlas slot a rectangle of the image, **keeping the
1439 /// one it already holds wherever it can**.
1440 ///
1441 /// **The cascades first and always**, whatever the light budget did: the
1442 /// shadow pass draws them every frame, and a fragment samples them on a
1443 /// frame with [`RenderEffects::SHADOWS`](crate::RenderEffects::SHADOWS) off
1444 /// too — it finds the pass's clear and comes back lit, which it can only do
1445 /// through a rectangle that names real texels. Then the light region's
1446 /// occupied slots, in slot order.
1447 ///
1448 /// **A cascade always takes a whole cell**, and a light's tiles take the
1449 /// level [`tile_level`] gave its assignment. The sun's map is the one this
1450 /// module never demotes: it covers the whole view rather than a light's
1451 /// reach, so there is no coverage to measure it by and every fragment the
1452 /// camera draws is a fragment it may shadow.
1453 ///
1454 /// # Retention, which is what makes the image outlive the frame
1455 ///
1456 /// Topic 45's static-caching rung: a slot that wants the
1457 /// size it already holds keeps the *same texels*, and only a slot whose map
1458 /// is gone or whose size changed hands its tile back to
1459 /// [`AtlasAllocator::release`]. A frame that changed nothing therefore
1460 /// re-derives exactly the rectangles the image was drawn with, which is the
1461 /// precondition for not drawing it again — see
1462 /// `ForwardRenderer::shadow_atlas_inputs`, which decides that.
1463 ///
1464 /// It also means the rectangles are a function of the frames before this
1465 /// one and not of this one alone. What is *not* history-dependent is the
1466 /// case every golden in the tree is blessed under: an empty allocator and a
1467 /// frame whose maps all take whole cells lays out cell for cell in slot
1468 /// order, and every frame after it that wants the same sizes keeps it.
1469 ///
1470 /// # Coarsest first, and that is what makes the fit a fact
1471 ///
1472 /// The requests that still need a tile are sorted by level before they are
1473 /// spent, so every whole cell is handed out before anything subdivides one.
1474 /// Spending a finer request first is what would break it — a level-1 request
1475 /// splits a root and leaves three quarters that no whole cell can use — and
1476 /// it is the only ordering constraint the allocator has.
1477 ///
1478 /// The allocation cannot run out, which is why the failure below is
1479 /// `unreachable!` rather than a fallback: a fallback here would be a map
1480 /// rendered into a rectangle another map is also using. There are at most
1481 /// [`TILES`] slots — a cascade or a light tile each, which is what the
1482 /// assertion beside [`LIGHT_TILES`] counts — and each wants at most a whole
1483 /// root. A retained tile occupies at most one root, so `k` of them leave at
1484 /// least `TILES - k` whole roots free against at most `TILES - k` remaining
1485 /// requests, none of which needs more than one.
1486 fn lay_out(&mut self, lights: &[Light]) {
1487 // What each atlas slot wants this frame, or `None` where no map is
1488 // rendered into it. Per slot rather than per light because a point
1489 // light's run is `POINT_FACES` tiles of one level and the atlas
1490 // addresses tiles.
1491 let mut wanted: [Option<usize>; TILES] = [None; TILES];
1492 for want in &mut wanted[..CASCADES] {
1493 *want = Some(0);
1494 }
1495 for assignment in self.slots.iter().flatten() {
1496 let Some(light) = lights.get(assignment.light) else {
1497 continue;
1498 };
1499 let span = tile_span(light);
1500 for tile in assignment.base..assignment.base + span {
1501 wanted[light_tile(tile)] = Some(assignment.level);
1502 }
1503 }
1504
1505 // Give back every tile whose slot no longer wants exactly what it
1506 // holds, **before** anything is allocated: the space a demoted light
1507 // frees is space the frame's remaining requests may need, and a merge
1508 // that ran after them would come too late to answer a whole cell.
1509 for (slot, want) in wanted.iter().enumerate() {
1510 let Some(held) = self.tiles[slot] else {
1511 continue;
1512 };
1513 if *want == Some(held.level()) {
1514 continue;
1515 }
1516 self.allocator.release(held);
1517 self.tiles[slot] = None;
1518 self.rects[slot] = TileRect::EMPTY;
1519 }
1520
1521 // The slots still owed a tile and the level each wants, in slot order —
1522 // an array rather than a `Vec` because the count is bounded by the
1523 // atlas's own slots and this runs every frame.
1524 let mut requests = [(0usize, 0usize); TILES];
1525 let mut count = 0;
1526 for (slot, want) in wanted.iter().enumerate() {
1527 let Some(level) = *want else {
1528 continue;
1529 };
1530 if self.tiles[slot].is_some() {
1531 continue;
1532 }
1533 requests[count] = (slot, level);
1534 count += 1;
1535 }
1536 // Stable, so the order within one level is still the slot order every
1537 // shadow golden was blessed under: a frame whose lights all take whole
1538 // cells lays out exactly as the fixed grid did.
1539 requests[..count].sort_by_key(|(_, level)| *level);
1540
1541 for &(slot, level) in &requests[..count] {
1542 let tile = self.allocator.allocate(level).unwrap_or_else(|| {
1543 unreachable!("a whole root cell per atlas slot, coarsest first")
1544 });
1545 self.tiles[slot] = Some(tile);
1546 self.rects[slot] = tile.rect();
1547 }
1548 }
1549
1550 /// What holds each slot, in slot order.
1551 #[must_use]
1552 pub const fn slots(&self) -> &[Option<Assignment>; LIGHT_SLOTS] {
1553 &self.slots
1554 }
1555
1556 /// Where atlas slot `slot`'s map was rendered, in texels — the viewport the
1557 /// shadow pass sets over it.
1558 ///
1559 /// [`TileRect::EMPTY`] for a slot no map was rendered into, and for a `slot`
1560 /// past [`TILES`], which is the same answer for the same reason: nothing
1561 /// sampled a map there.
1562 #[must_use]
1563 pub fn atlas_rect(&self, slot: usize) -> TileRect {
1564 self.rects.get(slot).copied().unwrap_or(TileRect::EMPTY)
1565 }
1566
1567 /// The same rectangles as the shader reads them, ready for
1568 /// [`FrameUniforms::shadow_atlas_rect`](crcbl_shaders::mesh::FrameUniforms::shadow_atlas_rect):
1569 /// a scale into the atlas in `xy` and an offset in `zw`, one row per slot.
1570 #[must_use]
1571 pub fn atlas_rects(&self) -> [[f32; 4]; TILES] {
1572 self.rects.map(TileRect::to_uv)
1573 }
1574
1575 /// Where light `index`'s run of tiles starts, if it was given one.
1576 ///
1577 /// The number a row carries: `Light::row` puts it in `GpuLight::shadow_tile`
1578 /// and the shader reads `light_view_proj` at it — plus the face, for a point
1579 /// light.
1580 #[must_use]
1581 pub fn base_of(&self, index: usize) -> Option<usize> {
1582 self.slots
1583 .iter()
1584 .flatten()
1585 .find(|assignment| assignment.light == index)
1586 .map(|assignment| assignment.base)
1587 }
1588}
1589
1590/// Quantises a light-space position to whole `texel`-sized steps.
1591///
1592/// Separate from [`cascade_matrix`] because it is the half that is checkable on
1593/// its own: "the snapped value is a whole number of texels" is an assertion, and
1594/// "the shadow does not shimmer" is not.
1595///
1596/// All three components, not just the two across the map: the depth range is
1597/// derived from `z`, so leaving it unquantised would move the near and far
1598/// planes every frame and with them the depth a given caster stores — which is
1599/// the same shimmer one axis further in.
1600fn snap_to_texel(position: Vec3, texel: f32) -> Vec3 {
1601 if texel <= 0.0 || !texel.is_finite() {
1602 return position;
1603 }
1604 (position / texel).floor() * texel
1605}
1606
1607#[cfg(test)]
1608mod tests {
1609 use super::*;
1610 use crate::camera::Projection;
1611
1612 fn camera_at(eye: Vec3) -> Camera {
1613 Camera {
1614 eye,
1615 target: eye + Vec3::NEG_Z,
1616 ..Camera::default()
1617 }
1618 }
1619
1620 const SUN: Vec3 = Vec3::new(0.4, 0.8, 0.6);
1621
1622 /// The splits must be strictly increasing and must end exactly at the
1623 /// distance shadows are declared to reach.
1624 ///
1625 /// A scheme that overshot would leave the last cascade covering geometry the
1626 /// fragment stage has already decided is out of range; one that undershot
1627 /// would leave a lit gap before it.
1628 #[test]
1629 fn the_splits_increase_and_end_at_the_shadow_distance() {
1630 let splits = Cascades::splits(0.1);
1631 assert!(
1632 (splits[CASCADES - 1] - DISTANCE).abs() < 1e-4,
1633 "the last split is the shadow distance: {splits:?}"
1634 );
1635 for window in splits.windows(2) {
1636 assert!(
1637 window[1] > window[0],
1638 "the splits must increase: {splits:?}"
1639 );
1640 }
1641 assert!(splits[0] > 0.0, "a cascade with no reach: {splits:?}");
1642 }
1643
1644 /// **The cascade must actually contain the split it names.**
1645 ///
1646 /// This is the assertion that fails if the sphere, the pull-back or the
1647 /// reversed-Z swap is wrong, and it is deliberately about points rather than
1648 /// about the matrix: a point at the edge of the cascade's reach, in every
1649 /// direction, must land inside the unit box with a depth in `0..1`. A
1650 /// projection that mapped everything outside the box would render an empty
1651 /// shadow map, which is the exact failure a golden image cannot see.
1652 #[test]
1653 fn every_point_within_a_cascades_reach_lands_inside_its_box() {
1654 let camera = camera_at(Vec3::new(3.0, 1.0, -2.0));
1655 let cascades = Cascades::new(&camera, SUN);
1656 for (index, matrix) in cascades.view_proj.iter().enumerate() {
1657 let radius = cascades.far[index];
1658 for direction in [
1659 Vec3::X,
1660 Vec3::NEG_X,
1661 Vec3::Y,
1662 Vec3::NEG_Y,
1663 Vec3::Z,
1664 Vec3::NEG_Z,
1665 Vec3::ONE.normalize(),
1666 ] {
1667 // Just inside the sphere, so the texel snap's half-texel of
1668 // slack cannot be what carries the point.
1669 let point = camera.eye + direction * (radius * 0.98);
1670 let clip = *matrix * point.extend(1.0);
1671 let ndc = clip.xyz() / clip.w;
1672 assert!(
1673 ndc.x.abs() <= 1.0 && ndc.y.abs() <= 1.0,
1674 "cascade {index} does not cover {direction:?}: ndc {ndc:?}"
1675 );
1676 assert!(
1677 (0.0..=1.0).contains(&ndc.z),
1678 "cascade {index} puts {direction:?} outside its depth range: ndc {ndc:?}"
1679 );
1680 }
1681 }
1682 }
1683
1684 /// Reversed-Z, stated as the only thing that distinguishes it: a point
1685 /// nearer the light gets the **larger** depth.
1686 ///
1687 /// The whole shadow comparison is `Greater`, so a matrix that mapped depth
1688 /// the conventional way would invert every shadow in the scene — lighting
1689 /// exactly what it should darken, which reads as a bug in the light
1690 /// direction rather than in the projection.
1691 #[test]
1692 fn a_caster_nearer_the_light_gets_the_larger_depth() {
1693 let camera = camera_at(Vec3::ZERO);
1694 let cascades = Cascades::new(&camera, SUN);
1695 let to_light = SUN.normalize();
1696 let matrix = cascades.view_proj[0];
1697 let near_light = (matrix * (to_light * 2.0).extend(1.0)).z;
1698 let far_light = (matrix * (to_light * -2.0).extend(1.0)).z;
1699 assert!(
1700 near_light > far_light,
1701 "reversed-Z: {near_light} must exceed {far_light}"
1702 );
1703 }
1704
1705 /// **Rotating the camera must not change a cascade at all**, which is the
1706 /// property the sphere buys and the reason it is a sphere.
1707 ///
1708 /// A box fitted to the split's view frustum would fail this outright, and
1709 /// the visible consequence is a shadow edge crawling across a wall while the
1710 /// player turns on the spot.
1711 #[test]
1712 fn turning_on_the_spot_leaves_every_cascade_alone() {
1713 let eye = Vec3::new(-2.0, 3.0, 5.0);
1714 let looking_north = Cascades::new(&camera_at(eye), SUN);
1715 let looking_east = Cascades::new(
1716 &Camera {
1717 eye,
1718 target: eye + Vec3::X,
1719 ..Camera::default()
1720 },
1721 SUN,
1722 );
1723 assert_eq!(
1724 looking_north, looking_east,
1725 "a cascade must not depend on where the camera looks"
1726 );
1727 // And the projection type is not a rotation either: an orthographic
1728 // camera at the same place gets the same cascades, because only the eye
1729 // and the near plane are read.
1730 let orthographic = Cascades::new(
1731 &camera_at(eye).with_projection(Projection::Orthographic {
1732 half_height: 4.0,
1733 near: 0.1,
1734 far: 50.0,
1735 }),
1736 SUN,
1737 );
1738 assert_eq!(looking_north, orthographic);
1739 }
1740
1741 /// Sub-texel camera motion must produce a **byte-identical** matrix.
1742 ///
1743 /// This is the snap, and it is asserted as equality rather than as "close"
1744 /// on purpose: the shimmer it removes is caused by a difference far smaller
1745 /// than any tolerance a test would pick, so anything short of equality would
1746 /// pass with the snap deleted.
1747 #[test]
1748 fn moving_less_than_one_texel_changes_nothing() {
1749 let eye = Vec3::new(1.0, 2.0, 3.0);
1750 let splits = Cascades::splits(0.1);
1751 #[expect(
1752 clippy::cast_precision_loss,
1753 reason = "a tile is a few thousand texels"
1754 )]
1755 let texel = 2.0 * splits[0] / TILE as f32;
1756 let still = Cascades::new(&camera_at(eye), SUN);
1757 // A tenth of a texel, along an axis the light basis is not parallel to.
1758 let nudged = Cascades::new(&camera_at(eye + Vec3::X * texel * 0.1), SUN);
1759 assert_eq!(
1760 still.view_proj[0], nudged.view_proj[0],
1761 "a sub-texel move must snap to the same origin"
1762 );
1763 // And a move of many texels must *not* — or the assertion above would
1764 // be passing because the matrix ignores the eye entirely.
1765 let moved = Cascades::new(&camera_at(eye + Vec3::X * texel * 40.0), SUN);
1766 assert_ne!(
1767 still.view_proj[0], moved.view_proj[0],
1768 "the cascade must follow the camera at all"
1769 );
1770 }
1771
1772 /// A light straight overhead is the commonest light there is, and it is the
1773 /// one the obvious up vector is parallel to.
1774 #[test]
1775 fn a_light_straight_overhead_still_produces_a_basis() {
1776 let cascades = Cascades::new(&camera_at(Vec3::ZERO), Vec3::Y);
1777 for (index, matrix) in cascades.view_proj.iter().enumerate() {
1778 assert!(
1779 matrix.to_cols_array().iter().all(|value| value.is_finite()),
1780 "cascade {index} is not finite under an overhead sun: {matrix:?}"
1781 );
1782 }
1783 // And it is a real projection, not a degenerate one: the origin is
1784 // inside the box.
1785 let clip = cascades.view_proj[0] * Vec3::ZERO.extend(1.0);
1786 let ndc = clip.xyz() / clip.w;
1787 assert!(ndc.x.abs() <= 1.0 && ndc.y.abs() <= 1.0 && (0.0..=1.0).contains(&ndc.z));
1788 }
1789
1790 /// The atlas is a grid of equal tiles, and every tile has one of its own.
1791 ///
1792 /// **Two tiles sharing an origin is the failure this is here for**: the
1793 /// shadow pass sets a viewport per tile out of `tile_origin` and the shader
1794 /// addresses one out of the same arithmetic, so a collision is two maps
1795 /// written over each other and read as one — a picture, and a plausible one.
1796 #[test]
1797 fn every_tile_of_the_grid_has_an_origin_of_its_own() {
1798 let (width, height) = atlas_extent();
1799 assert_eq!(width, TILE * ATLAS_COLUMNS);
1800 assert_eq!(height, TILE * ATLAS_ROWS);
1801 let params = Cascades::params();
1802 #[expect(clippy::cast_precision_loss, reason = "an extent is a few thousand")]
1803 let expected = [1.0 / width as f32, 1.0 / height as f32];
1804 assert!((params[0] - expected[0]).abs() < f32::EPSILON);
1805 assert!((params[1] - expected[1]).abs() < f32::EPSILON);
1806 assert!(params[2] > 0.0 && params[3] > 0.0, "the bias must bias");
1807
1808 let origins: Vec<(u32, u32)> = (0..TILES).map(tile_origin).collect();
1809 for (index, origin) in origins.iter().enumerate() {
1810 assert!(
1811 origin.0 + TILE <= width && origin.1 + TILE <= height,
1812 "tile {index} at {origin:?} runs off a {width}x{height} atlas"
1813 );
1814 assert_eq!(
1815 origins.iter().filter(|other| *other == origin).count(),
1816 1,
1817 "tile {index}'s origin {origin:?} is shared with another tile"
1818 );
1819 }
1820
1821 // **The cascades are the first tiles and they are in the top row**,
1822 // which is the arrangement the sun's goldens were blessed under: cascade
1823 // `i` rasterises into exactly the texels it did before the grid gained a
1824 // second row, so a change to the grid's shape leaves them alone.
1825 for cascade in 0..CASCADES {
1826 assert_eq!(tile_origin(cascade), (TILE * cascade as u32, 0));
1827 }
1828 // And every light tile is past every cascade's, which is the whole of the
1829 // split.
1830 for tile in 0..LIGHT_TILES {
1831 assert!(light_tile(tile) >= CASCADES && light_tile(tile) < TILES);
1832 }
1833 }
1834
1835 fn spot_at(position: Vec3, direction: Vec3) -> SpotLight {
1836 SpotLight {
1837 position,
1838 radius: 4.0,
1839 color: Vec3::ONE,
1840 direction,
1841 inner_angle: 0.2,
1842 outer_angle: 0.5,
1843 fill: false,
1844 }
1845 }
1846
1847 /// **Reversed-Z, stated as the only thing that distinguishes it**: a caster
1848 /// nearer the light gets the larger depth, the near plane is 1 and the
1849 /// radius is 0.
1850 ///
1851 /// The comparison sampler is `Greater` everywhere in this engine, so a
1852 /// matrix built the conventional way round would light exactly what it
1853 /// should darken — which reads as a bug in the cone rather than in the
1854 /// projection, and which no golden can tell from a scene with no occluder.
1855 #[test]
1856 fn a_caster_nearer_a_spot_gets_the_larger_depth() {
1857 let spot = spot_at(Vec3::new(0.0, 2.0, 0.0), Vec3::NEG_Y);
1858 let matrix = spot_matrix(&spot);
1859 let depth_at = |distance: f32| {
1860 let point = spot.position + Vec3::NEG_Y * distance;
1861 let clip = matrix * point.extend(1.0);
1862 (clip.xyz() / clip.w).z
1863 };
1864 let near = depth_at(0.5);
1865 let far = depth_at(3.0);
1866 assert!(
1867 near > far,
1868 "reversed-Z: a caster at 0.5 stores {near} and one at 3.0 stores {far}"
1869 );
1870 // And the two ends land where reversed-Z says: the near plane at 1 and
1871 // the radius at 0. An assertion about the *order* alone would pass on a
1872 // matrix whose range was 0.4..0.6, which is a map with almost no
1873 // precision in it.
1874 assert!(
1875 (depth_at(PUNCTUAL_NEAR) - 1.0).abs() < 1e-4,
1876 "the near plane must store 1.0, got {}",
1877 depth_at(PUNCTUAL_NEAR)
1878 );
1879 assert!(
1880 depth_at(spot.radius).abs() < 1e-4,
1881 "the radius must store 0.0, got {}",
1882 depth_at(spot.radius)
1883 );
1884 // Every depth in between is inside the range the comparison runs over.
1885 for step in 1..40u8 {
1886 let depth =
1887 depth_at(PUNCTUAL_NEAR + (spot.radius - PUNCTUAL_NEAR) * f32::from(step) / 40.0);
1888 assert!(
1889 (0.0..=1.0).contains(&depth),
1890 "a caster inside the cone stored {depth}, outside 0..1"
1891 );
1892 }
1893 }
1894
1895 /// The map covers the cone and stops there: a point on the cone's outer edge
1896 /// is at the frustum's edge, and one well outside it is out of the box.
1897 ///
1898 /// A projection wider than the cone spends texels where the light has
1899 /// already fallen to zero; one narrower leaves a ring of the lit pool with
1900 /// no map behind it, which reads as a shadow that stops short of the pool's
1901 /// edge.
1902 #[test]
1903 fn a_spots_map_covers_its_cone_and_no_more() {
1904 let spot = spot_at(Vec3::new(1.0, 2.0, -1.0), Vec3::new(0.0, -1.0, 0.0));
1905 let matrix = spot_matrix(&spot);
1906 let ndc_of = |point: Vec3| {
1907 let clip = matrix * point.extend(1.0);
1908 clip.xyz() / clip.w
1909 };
1910 // A metre below the light, the cone's outer edge is `tan(outer)` out.
1911 let drop = 1.0;
1912 let edge = spot.outer_angle.tan() * drop;
1913 let on_edge = ndc_of(spot.position + Vec3::new(edge, -drop, 0.0));
1914 assert!(
1915 (on_edge.x.abs() - 1.0).abs() < 1e-3,
1916 "the cone's edge must land on the frustum's, got {on_edge:?}"
1917 );
1918 let inside = ndc_of(spot.position + Vec3::new(edge * 0.5, -drop, 0.0));
1919 assert!(inside.x.abs() < 1.0 && inside.y.abs() < 1.0, "{inside:?}");
1920 let outside = ndc_of(spot.position + Vec3::new(edge * 1.5, -drop, 0.0));
1921 assert!(outside.x.abs() > 1.0, "{outside:?}");
1922 // And behind the light is behind the light: the shader's `clip.w <= 0`
1923 // guard is what turns this into "lit" rather than a mirrored sample.
1924 let behind = matrix * (spot.position + Vec3::Y).extend(1.0);
1925 assert!(
1926 behind.w <= 0.0,
1927 "a point behind the spot has w {}",
1928 behind.w
1929 );
1930 }
1931
1932 /// A spot pointing straight down is the commonest spot there is, and it is
1933 /// the one the obvious up vector is parallel to.
1934 #[test]
1935 fn a_spot_pointing_straight_down_still_produces_a_basis() {
1936 let matrix = spot_matrix(&spot_at(Vec3::new(0.0, 3.0, 0.0), Vec3::NEG_Y));
1937 assert!(
1938 matrix.to_cols_array().iter().all(|value| value.is_finite()),
1939 "a spot pointing down produced {matrix:?}"
1940 );
1941 let clip = matrix * Vec3::ZERO.extend(1.0);
1942 let ndc = clip.xyz() / clip.w;
1943 assert!(ndc.x.abs() <= 1.0 && ndc.y.abs() <= 1.0 && (0.0..=1.0).contains(&ndc.z));
1944 }
1945
1946 /// **A still spot produces a byte-identical matrix**, which is the stability
1947 /// the cascades need a texel snap for and a spot gets for free.
1948 ///
1949 /// Asserted as equality rather than as "close", exactly as the cascades'
1950 /// snap is: shimmer is caused by a difference far below any tolerance a test
1951 /// would pick, so anything short of equality would pass on a matrix that
1952 /// moved every frame. The camera is not in the arithmetic at all, so this is
1953 /// a statement about `spot_matrix`'s inputs and nothing else.
1954 #[test]
1955 fn a_still_spot_produces_the_same_matrix() {
1956 let spot = spot_at(Vec3::new(0.5, 2.0, -1.5), Vec3::new(0.2, -1.0, 0.1));
1957 assert_eq!(spot_matrix(&spot), spot_matrix(&spot));
1958 // And a spot that *moved* does not, or the equality above would be
1959 // passing because the matrix ignores the light.
1960 let mut moved = spot;
1961 moved.position.x += 0.5;
1962 assert_ne!(spot_matrix(&spot), spot_matrix(&moved));
1963 }
1964
1965 fn point_at(position: Vec3, radius: f32) -> PointLight {
1966 PointLight {
1967 position,
1968 radius,
1969 color: Vec3::ONE,
1970 fill: false,
1971 }
1972 }
1973
1974 /// Whether `point` is inside the frustum `matrix` projects with, on the
1975 /// shader's terms exactly: `mesh.slang`'s `punctual_visibility` refuses a
1976 /// non-positive `w` first and then a point outside the unit box or outside
1977 /// the depth range.
1978 fn inside(matrix: Mat4, point: Vec3) -> bool {
1979 let clip = matrix * point.extend(1.0);
1980 if clip.w <= 0.0 {
1981 return false;
1982 }
1983 let ndc = clip.xyz() / clip.w;
1984 ndc.x.abs() <= 1.0 && ndc.y.abs() <= 1.0 && (0.0..=1.0).contains(&ndc.z)
1985 }
1986
1987 /// **Each face covers one named direction and none of the other five**,
1988 /// which is the assertion a face indexing mistake cannot survive.
1989 ///
1990 /// The six directions are written out here rather than taken from
1991 /// [`face_axis`], and that is the whole point of the test: a table compared
1992 /// against itself passes on any *permutation* of the six, and a permutation
1993 /// is exactly what a wrong convention is. This list is `mesh.slang`'s
1994 /// `point_face` transcribed — it picks a face out of the largest component of
1995 /// the direction from the light, in this order — so a host that built its
1996 /// matrices in another order fails here rather than in a frame where five of
1997 /// the six faces sample somewhere else.
1998 ///
1999 /// It is also not "the six matrices differ" or "a caster projects somewhere
2000 /// sensible", both of which pass on any order at all.
2001 #[test]
2002 fn every_face_of_a_point_light_covers_its_own_direction_and_no_other() {
2003 let light = point_at(Vec3::new(0.5, -1.0, 2.0), 4.0);
2004 let convention = [
2005 (0, Vec3::X),
2006 (1, Vec3::NEG_X),
2007 (2, Vec3::Y),
2008 (3, Vec3::NEG_Y),
2009 (4, Vec3::Z),
2010 (5, Vec3::NEG_Z),
2011 ];
2012 assert_eq!(
2013 convention.len(),
2014 POINT_FACES,
2015 "the convention below has to name every face there is"
2016 );
2017 for (face, axis) in convention {
2018 let towards = light.position + axis * 2.0;
2019 for other in 0..POINT_FACES {
2020 let matrix = point_matrix(&light, other);
2021 assert_eq!(
2022 inside(matrix, towards),
2023 other == face,
2024 "a caster at {towards:?} is {axis:?} of the light, which is face {face}, \
2025 and face {other}'s matrix {} it",
2026 if other == face {
2027 "does not cover"
2028 } else {
2029 "covers"
2030 }
2031 );
2032 }
2033 }
2034 }
2035
2036 /// **The six faces leave no direction uncovered**, which is the other half:
2037 /// a set of matrices that each covered only their own axis and nothing
2038 /// between them would pass the test above and leave a shadow with holes in
2039 /// it wherever the light shines diagonally.
2040 ///
2041 /// A spiral of directions rather than the six axes, because the axes are the
2042 /// case that cannot fail — the corners between three faces are where a field
2043 /// of view narrower than 90° stops reaching.
2044 #[test]
2045 fn the_six_faces_between_them_cover_every_direction() {
2046 let light = point_at(Vec3::new(-2.0, 0.5, 1.0), 6.0);
2047 let matrices: Vec<Mat4> = (0..POINT_FACES)
2048 .map(|face| point_matrix(&light, face))
2049 .collect();
2050 for step in 0..512u32 {
2051 // A Fibonacci spiral: `z` walks the range and the angle turns by the
2052 // golden ratio, which spreads the samples over the sphere rather than
2053 // clustering them at its poles the way a latitude/longitude grid
2054 // does.
2055 let fraction = (f64::from(step) + 0.5) / 512.0;
2056 let z = 1.0 - 2.0 * fraction;
2057 let radius = (1.0 - z * z).max(0.0).sqrt();
2058 let angle = std::f64::consts::PI * (3.0 - 5.0f64.sqrt()) * f64::from(step);
2059 #[expect(clippy::cast_possible_truncation, reason = "a direction is an f32")]
2060 let direction = Vec3::new(
2061 (radius * angle.cos()) as f32,
2062 (radius * angle.sin()) as f32,
2063 z as f32,
2064 );
2065 let caster = light.position + direction * 3.0;
2066 let covered = matrices
2067 .iter()
2068 .filter(|matrix| inside(**matrix, caster))
2069 .count();
2070 assert!(
2071 covered >= 1,
2072 "no face covers a caster {direction:?} from the light, so a shadow cast that \
2073 way would be missing"
2074 );
2075 }
2076 }
2077
2078 /// **Reversed-Z on a face**, stated as the only thing that distinguishes it,
2079 /// and checked on every face rather than on one: a caster nearer the light
2080 /// gets the larger depth, the near plane stores 1 and the radius stores 0.
2081 ///
2082 /// The same claim `a_caster_nearer_a_spot_gets_the_larger_depth` makes, and
2083 /// it is made again rather than assumed to carry over: this is a different
2084 /// field of view through a different constructor call, and a matrix built the
2085 /// conventional way round lights exactly what it should darken.
2086 #[test]
2087 fn a_caster_nearer_a_point_lights_face_gets_the_larger_depth() {
2088 let light = point_at(Vec3::new(0.0, 2.0, 0.0), 4.0);
2089 for face in 0..POINT_FACES {
2090 let matrix = point_matrix(&light, face);
2091 let depth_at = |distance: f32| {
2092 let clip = matrix * (light.position + face_axis(face) * distance).extend(1.0);
2093 (clip.xyz() / clip.w).z
2094 };
2095 let near = depth_at(0.5);
2096 let far = depth_at(3.0);
2097 assert!(
2098 near > far,
2099 "reversed-Z on face {face}: a caster at 0.5 stores {near} and one at 3.0 \
2100 stores {far}"
2101 );
2102 assert!(
2103 (depth_at(PUNCTUAL_NEAR) - 1.0).abs() < 1e-4,
2104 "face {face}'s near plane must store 1.0, got {}",
2105 depth_at(PUNCTUAL_NEAR)
2106 );
2107 assert!(
2108 depth_at(light.radius).abs() < 1e-4,
2109 "face {face}'s radius must store 0.0, got {}",
2110 depth_at(light.radius)
2111 );
2112 }
2113 }
2114
2115 /// A point light straight over the origin is the commonest one there is, and
2116 /// two of its faces look along the axis the obvious up vector is.
2117 #[test]
2118 fn the_faces_that_look_along_y_still_produce_a_basis() {
2119 let light = point_at(Vec3::new(0.0, 3.0, 0.0), 5.0);
2120 for face in 0..POINT_FACES {
2121 let matrix = point_matrix(&light, face);
2122 assert!(
2123 matrix.to_cols_array().iter().all(|value| value.is_finite()),
2124 "face {face} produced {matrix:?}"
2125 );
2126 }
2127 // And the `-Y` face really does look at the floor under it, which is the
2128 // one a degenerate basis would leave empty.
2129 assert!(inside(point_matrix(&light, 3), Vec3::ZERO));
2130 }
2131
2132 /// **A still light produces a byte-identical matrix**, on `spot_matrix`'s
2133 /// terms and for its reason: there is no texel snap here, so this is what
2134 /// says none is needed.
2135 #[test]
2136 fn a_still_point_light_produces_the_same_matrices() {
2137 let light = point_at(Vec3::new(0.5, 2.0, -1.5), 4.0);
2138 for face in 0..POINT_FACES {
2139 assert_eq!(point_matrix(&light, face), point_matrix(&light, face));
2140 }
2141 // And a light that *moved* does not, or the equality above would be
2142 // passing because the matrix ignores the light.
2143 let mut moved = light;
2144 moved.position.x += 0.5;
2145 assert_ne!(point_matrix(&light, 0), point_matrix(&moved, 0));
2146 }
2147
2148 /// The one cull a point light gets must keep what is inside its reach and
2149 /// reject what is outside it.
2150 ///
2151 /// The union of the six faces is the light's sphere — topic 18's fourth
2152 /// decision — so this is the frustum all six draws share, and a box that
2153 /// rejected a caster inside the light's radius would be a missing shadow on
2154 /// whichever face it belonged to.
2155 #[test]
2156 fn a_point_lights_cull_keeps_what_is_inside_its_radius() {
2157 let light = point_at(Vec3::new(1.0, 2.0, -3.0), 4.0);
2158 let frustum = point_frustum(&light);
2159 for face in 0..POINT_FACES {
2160 let axis = face_axis(face);
2161 let near = crate::cull::Aabb {
2162 min: light.position + axis - Vec3::splat(0.1),
2163 max: light.position + axis + Vec3::splat(0.1),
2164 };
2165 assert!(
2166 frustum.intersects(&near),
2167 "a caster a unit along face {face} is inside the light's reach"
2168 );
2169 let beyond = crate::cull::Aabb {
2170 min: light.position + axis * 12.0 - Vec3::splat(0.1),
2171 max: light.position + axis * 12.0 + Vec3::splat(0.1),
2172 };
2173 assert!(
2174 !frustum.intersects(&beyond),
2175 "a caster three radii along face {face} cannot shadow anything this light lights"
2176 );
2177 }
2178 }
2179
2180 fn spot_light_at(position: Vec3, radius: f32) -> Light {
2181 Light::Spot(SpotLight {
2182 position,
2183 radius,
2184 color: Vec3::ONE,
2185 direction: Vec3::NEG_Y,
2186 inner_angle: 0.2,
2187 outer_angle: 0.5,
2188 fill: false,
2189 })
2190 }
2191
2192 /// A slot holding light `light` from tile `base` at a whole root cell, for
2193 /// the assertions below.
2194 ///
2195 /// Level 0 rather than a parameter because every light in the lists these
2196 /// assertions are built from covers more of the frame than
2197 /// [`WHOLE_CELL_COVERAGE`]: what they are about is which light gets a run,
2198 /// and the size of that run is
2199 /// [`the_tile_size_falls_with_the_coverage`]'s subject instead.
2200 const fn held(light: usize, base: usize) -> Option<Assignment> {
2201 Some(Assignment {
2202 light,
2203 base,
2204 level: 0,
2205 })
2206 }
2207
2208 /// The budget goes to the lights with the largest projected influence, and a
2209 /// light that misses out gets no slot at all.
2210 ///
2211 /// **Radius over distance, not distance alone**: a small light close to the
2212 /// eye and a large one further off are the pair that tells the two rules
2213 /// apart, and the list below is built so that the nearest light is *not* the
2214 /// most influential one.
2215 #[test]
2216 fn the_tiles_go_to_the_largest_projected_influence() {
2217 let eye = Vec3::ZERO;
2218 // One light more than there are slots, so exactly one has to miss out.
2219 let lights = [
2220 // 0.5 / 1 = 0.5 — nearest, and the least influential.
2221 spot_light_at(Vec3::new(0.0, 0.0, -1.0), 0.5),
2222 // 8 / 4 = 2.0 — the most influential.
2223 spot_light_at(Vec3::new(0.0, 0.0, -4.0), 8.0),
2224 // 3 / 2 = 1.5.
2225 spot_light_at(Vec3::new(0.0, 0.0, -2.0), 3.0),
2226 // 5 / 5 = 1.0.
2227 spot_light_at(Vec3::new(0.0, 0.0, -5.0), 5.0),
2228 // 2.25 / 3 = 0.75.
2229 spot_light_at(Vec3::new(0.0, 0.0, -3.0), 2.25),
2230 ];
2231 let mut selection = Selection::default();
2232 selection.update(&lights, &camera_at(eye));
2233 assert_eq!(
2234 selection.slots(),
2235 &[held(1, 0), held(2, 1), held(3, 2), held(4, 3)],
2236 "the largest influences take the slots and the first tiles, in rank order"
2237 );
2238 assert_eq!(selection.base_of(1), Some(0));
2239 assert_eq!(selection.base_of(2), Some(1));
2240 assert_eq!(selection.base_of(3), Some(2));
2241 assert_eq!(selection.base_of(4), Some(3));
2242 assert_eq!(
2243 selection.base_of(0),
2244 None,
2245 "the light past the budget gets no tile — it still lights, it just \
2246 does not occlude"
2247 );
2248 }
2249
2250 /// Two lights of exactly equal influence break by index, so a frame's answer
2251 /// does not depend on the order a caller happened to build the list in.
2252 #[test]
2253 fn an_exact_tie_breaks_by_index() {
2254 // One more than there are slots, or the tie decides nothing: every light
2255 // would be shadowed whichever way it broke.
2256 let lights = [
2257 spot_light_at(Vec3::new(3.0, 0.0, 0.0), 1.0),
2258 spot_light_at(Vec3::new(-3.0, 0.0, 0.0), 1.0),
2259 spot_light_at(Vec3::new(0.0, 3.0, 0.0), 1.0),
2260 spot_light_at(Vec3::new(0.0, -3.0, 0.0), 1.0),
2261 spot_light_at(Vec3::new(0.0, 0.0, 3.0), 1.0),
2262 ];
2263 let mut selection = Selection::default();
2264 selection.update(&lights, &camera_at(Vec3::ZERO));
2265 assert_eq!(
2266 selection.slots(),
2267 &[held(0, 0), held(1, 1), held(2, 2), held(3, 3)]
2268 );
2269 assert_eq!(
2270 selection.base_of(4),
2271 None,
2272 "the last light of an all-way tie is the one that loses it"
2273 );
2274 }
2275
2276 /// **A light drifting across the cutoff must not flicker its shadow on and
2277 /// off**, which is the hysteresis and the reason it is owed.
2278 ///
2279 /// The incumbent is overtaken by a hair and keeps its tile; overtaken
2280 /// clearly, it loses it. Both halves, because a rule that never yields is
2281 /// not hysteresis — it is a first-come allocation, and the more important
2282 /// light would never get a map.
2283 #[test]
2284 fn an_incumbent_keeps_its_tile_until_a_challenger_clearly_beats_it() {
2285 // One slot's worth of contention: a list no longer than `LIGHT_SLOTS`
2286 // means nothing is contended, so it is one longer than the budget. The
2287 // light at the end is the outsider and the one before it the incumbent
2288 // it comes for.
2289 let contender = |influence: f32| spot_light_at(Vec3::new(0.0, 0.0, -1.0), influence);
2290 let mut lights = [
2291 contender(5.0),
2292 contender(4.0),
2293 contender(3.0),
2294 contender(2.0),
2295 contender(1.0),
2296 ];
2297 let mut selection = Selection::default();
2298 selection.update(&lights, &camera_at(Vec3::ZERO));
2299 assert_eq!(
2300 selection.slots(),
2301 &[held(0, 0), held(1, 1), held(2, 2), held(3, 3)]
2302 );
2303
2304 // The outsider edges past the incumbent by a few per cent. It does not
2305 // take the tile, and — this is the half that matters — the incumbent
2306 // stays in the *same* slot and on the *same* tile rather than being
2307 // reshuffled.
2308 lights[4] = contender(2.1);
2309 selection.update(&lights, &camera_at(Vec3::ZERO));
2310 assert_eq!(
2311 selection.slots(),
2312 &[held(0, 0), held(1, 1), held(2, 2), held(3, 3)],
2313 "a challenger 5% ahead must not take a held tile"
2314 );
2315
2316 // Clearly past it, and the tile changes hands.
2317 lights[4] = contender(2.0 * HOLD_RATIO + 0.1);
2318 selection.update(&lights, &camera_at(Vec3::ZERO));
2319 assert_eq!(
2320 selection.slots(),
2321 &[held(0, 0), held(1, 1), held(2, 2), held(4, 3)],
2322 "a challenger past the hold ratio must take the tile"
2323 );
2324 }
2325
2326 /// A light with no map at all is refused a tile rather than given one it
2327 /// cannot fill — and the tile goes to the next light instead.
2328 ///
2329 /// A cone at or past a right angle has no perspective projection, and a light
2330 /// with no radius has no frustum. Both still light.
2331 #[test]
2332 fn a_light_with_no_map_is_refused_a_tile_and_the_next_one_takes_it() {
2333 let mut wide = spot_light_at(Vec3::new(0.0, 0.0, -1.0), 10.0);
2334 if let Light::Spot(spot) = &mut wide {
2335 spot.outer_angle = MAX_SPOT_HALF_ANGLE + 0.01;
2336 }
2337 let lights = [
2338 // A point light with no reach: influence is infinite by the metric
2339 // and there is no frustum to render, which is why eligibility is a
2340 // predicate of its own rather than a consequence of the ranking.
2341 Light::Point(point_at(Vec3::new(0.0, 0.0, -1.0), 0.0)),
2342 wide,
2343 spot_light_at(Vec3::new(0.0, 0.0, -2.0), 1.0),
2344 spot_light_at(Vec3::new(0.0, 0.0, -3.0), 1.0),
2345 spot_light_at(Vec3::new(0.0, 0.0, -4.0), 1.0),
2346 spot_light_at(Vec3::new(0.0, 0.0, -5.0), 1.0),
2347 ];
2348 let mut selection = Selection::default();
2349 selection.update(&lights, &camera_at(Vec3::ZERO));
2350 assert_eq!(
2351 selection.slots(),
2352 &[held(2, 0), held(3, 1), held(4, 2), held(5, 3)],
2353 "the two brightest are ineligible, so the tiles go to the ones that are"
2354 );
2355 }
2356
2357 /// **A fill light is refused a tile, where the same light not marked fill
2358 /// takes one** — the flag's shadow half, which is [`can_be_shadowed`]'s
2359 /// leading test and nothing else.
2360 ///
2361 /// The pair is the assertion. A fill light getting no tile is equally what
2362 /// a build that shadowed nothing at all would report, so the run before it
2363 /// is the same light with the flag cleared and it has to take tile 0. Only
2364 /// `fill` differs between the two: the position, the radius and the cone
2365 /// are copied from the one value.
2366 #[test]
2367 fn a_fill_light_is_refused_a_tile_where_the_same_light_takes_one() {
2368 // Built once and copied with the flag set, so the pair below differs in
2369 // `fill` and in nothing else — same position, same radius, same cone.
2370 let point = point_at(Vec3::new(0.0, 0.0, -2.0), 4.0);
2371 let spot = spot_at(Vec3::new(0.0, 0.0, -2.0), Vec3::NEG_Y);
2372 let pairs = [
2373 (
2374 "point",
2375 Light::Point(point),
2376 Light::Point(PointLight {
2377 fill: true,
2378 ..point
2379 }),
2380 ),
2381 (
2382 "spot",
2383 Light::Spot(spot),
2384 Light::Spot(SpotLight { fill: true, ..spot }),
2385 ),
2386 ];
2387 for (kind, casting, filling) in pairs {
2388 let mut selection = Selection::default();
2389 selection.update(&[casting], &camera_at(Vec3::ZERO));
2390 assert_eq!(
2391 selection.base_of(0),
2392 Some(0),
2393 "a {kind} light that is not fill must take the first tile, or \
2394 the refusal below would pass against a build that shadows \
2395 nothing"
2396 );
2397 let mut selection = Selection::default();
2398 selection.update(&[filling], &camera_at(Vec3::ZERO));
2399 assert_eq!(
2400 selection.base_of(0),
2401 None,
2402 "a fill {kind} light lights without occluding, so it is handed \
2403 no tile at all"
2404 );
2405 }
2406 }
2407
2408 /// **A point light and a spot are shadowed in the same frame**, which is what
2409 /// the light region having a tile over a whole cube buys.
2410 ///
2411 /// The budget's shape, stated as the frame a caller actually gets: the cube
2412 /// is [`POINT_FACES`] tiles and the region is longer than that, so the spot's
2413 /// map is a tile left over and both lights occlude. Until [`LIGHT_TILES`]
2414 /// grew past [`POINT_FACES`] this pair was the plan's documented degradation
2415 /// — the point took everything and the spot lit without occluding — and an
2416 /// ordinary lighting rig hit it.
2417 ///
2418 /// The spot's base is asserted, not just that it has one: it must land
2419 /// *after* the cube rather than inside it, and "it got a tile" is true
2420 /// either way.
2421 #[test]
2422 fn a_point_light_and_a_spot_behind_it_are_both_shadowed() {
2423 let lights = [
2424 Light::Point(point_at(Vec3::new(0.0, 0.0, -1.0), 4.0)),
2425 spot_light_at(Vec3::new(0.0, 0.0, -2.0), 1.0),
2426 ];
2427 let mut selection = Selection::default();
2428 selection.update(&lights, &camera_at(Vec3::ZERO));
2429 assert_eq!(
2430 selection.slots(),
2431 &[held(0, 0), held(1, POINT_FACES), None, None],
2432 "the point light's cube is the first {POINT_FACES} tiles and the spot's map is \
2433 the one after it"
2434 );
2435 assert_eq!(selection.base_of(0), Some(0));
2436 assert_eq!(selection.base_of(1), Some(POINT_FACES));
2437 }
2438
2439 /// **Two point lights both occlude in one frame**, which is what the
2440 /// 2026-08-26 re-tiling of the atlas was for.
2441 ///
2442 /// Until then [`LIGHT_TILES`] was one tile past a single cube, so the second
2443 /// of a pair of torches was refused a run and *re-lit* the shadow its twin
2444 /// cast — a rig with a light either side of a walkway, which is an ordinary
2445 /// rig, had no working shadow at all.
2446 ///
2447 /// Both halves are asserted, because the host handing out a run is only half
2448 /// of a light that casts: `mesh.slang` admits a point light's cube only where
2449 /// the whole run is inside the region, written there as
2450 /// `shadow_tile <= SHADOW_LIGHT_TILES - SHADOW_POINT_FACES`, and a base of
2451 /// [`POINT_FACES`] failed that test on every backend while the region was
2452 /// seven tiles long.
2453 #[test]
2454 fn two_point_lights_are_both_shadowed() {
2455 let lights = [
2456 Light::Point(point_at(Vec3::new(-2.0, 0.0, -1.0), 4.0)),
2457 Light::Point(point_at(Vec3::new(2.0, 0.0, -1.0), 4.0)),
2458 ];
2459 let mut selection = Selection::default();
2460 selection.update(&lights, &camera_at(Vec3::ZERO));
2461 assert_eq!(
2462 selection.slots(),
2463 &[held(0, 0), held(1, POINT_FACES), None, None],
2464 "the first cube takes the first {POINT_FACES} tiles and the second the \
2465 {POINT_FACES} after it"
2466 );
2467 for light in 0..lights.len() {
2468 let base = selection
2469 .base_of(light)
2470 .unwrap_or_else(|| panic!("point light {light} was given no run"));
2471 assert!(
2472 base + POINT_FACES <= LIGHT_TILES,
2473 "point light {light}'s run starts at {base}, which `mesh.slang` refuses: \
2474 its faces run off the end of a {LIGHT_TILES}-tile region"
2475 );
2476 }
2477 }
2478
2479 /// A point light that cannot fit does not take the budget down with it, and
2480 /// **the lights around it keep their tiles**.
2481 ///
2482 /// The fragmentation case, and the reason the allocation walks the whole
2483 /// ranking rather than stopping at the first light it cannot place. Two cubes
2484 /// leave [`LIGHT_TILES`] minus twice [`POINT_FACES`] tiles behind them, which
2485 /// is less than a cube, so a *third* point light is what no longer fits. A
2486 /// walk that stopped there would be a frame where a distant point light
2487 /// silently switched off a nearer spot's shadow.
2488 #[test]
2489 fn a_point_light_that_cannot_fit_leaves_the_lights_around_it_alone() {
2490 let lights = [
2491 Light::Point(point_at(Vec3::new(0.0, 0.0, -1.0), 4.0)),
2492 Light::Point(point_at(Vec3::new(0.0, 0.0, -2.0), 6.0)),
2493 Light::Point(point_at(Vec3::new(0.0, 0.0, -4.0), 2.0)),
2494 spot_light_at(Vec3::new(0.0, 0.0, -3.0), 1.0),
2495 ];
2496 let mut selection = Selection::default();
2497 selection.update(&lights, &camera_at(Vec3::ZERO));
2498 assert_eq!(
2499 selection.slots(),
2500 &[
2501 held(0, 0),
2502 held(1, POINT_FACES),
2503 held(3, 2 * POINT_FACES),
2504 None
2505 ],
2506 "two cubes fill the region but for what is left of it, the third point light \
2507 does not fit in that, and the spot ranked behind it still takes a tile of it"
2508 );
2509 assert_eq!(
2510 selection.base_of(2),
2511 None,
2512 "the third cube has nowhere to go"
2513 );
2514 }
2515
2516 /// Every run a selection hands out is inside the region and no two runs
2517 /// overlap, whatever the list is.
2518 ///
2519 /// **Two lights sharing a tile is the failure this is here for**: both would
2520 /// render into it, the second over the first, and both would sample it — a
2521 /// picture, and a plausible one. Asserted over a list that changes kind under
2522 /// a held index, which is the case the incumbents' preference for their own
2523 /// run has to survive.
2524 #[test]
2525 fn no_two_lights_are_ever_given_the_same_tile() {
2526 let spot = spot_light_at(Vec3::new(0.0, 0.0, -1.0), 4.0);
2527 let other = spot_light_at(Vec3::new(0.0, 0.0, -2.0), 2.0);
2528 let point = Light::Point(point_at(Vec3::new(0.0, 0.0, -1.0), 4.0));
2529 let mut selection = Selection::default();
2530 for lights in [
2531 vec![spot, other],
2532 // The light at index 0 is a point light now, and it wants a whole
2533 // cube's run where its incumbent run had one tile.
2534 vec![point, other],
2535 vec![other, point],
2536 vec![point],
2537 vec![spot, other, point],
2538 // More cubes than the region has runs for, which is where a light
2539 // that is refused one must not leave a partial run behind it.
2540 vec![point, point, point],
2541 vec![point, spot, point, other, point],
2542 ] {
2543 selection.update(&lights, &camera_at(Vec3::ZERO));
2544 let mut used = [false; LIGHT_TILES];
2545 for assignment in selection.slots().iter().flatten() {
2546 let span = tile_span(&lights[assignment.light]);
2547 assert!(
2548 assignment.base + span <= LIGHT_TILES,
2549 "light {} runs off the end of the region from {}",
2550 assignment.light,
2551 assignment.base
2552 );
2553 for tile in &mut used[assignment.base..assignment.base + span] {
2554 assert!(!*tile, "two lights hold one tile: {:?}", selection.slots());
2555 *tile = true;
2556 }
2557 }
2558 }
2559 }
2560
2561 /// Where a spot of this list's shape has to stand for its map to cover
2562 /// `wanted` of the frame's height.
2563 ///
2564 /// [`coverage`] inverted, through the module's own [`map_extent`] and the
2565 /// camera's own scale rather than through a second copy of the arithmetic:
2566 /// what the assertions below are about is the *ladder* and its band, and a
2567 /// distance written as a literal would make them about the scorer's
2568 /// constants instead and go stale the moment one moved.
2569 fn distance_for(wanted: f32, light: &Light, camera: &Camera) -> f32 {
2570 map_extent(light) * camera.projection.pixels_per_unit(1.0) / wanted
2571 }
2572
2573 /// A spot standing far enough down `-z` to cover `wanted` of the frame.
2574 fn spot_covering(wanted: f32, camera: &Camera) -> Light {
2575 let template = spot_light_at(Vec3::ZERO, 1.0);
2576 let distance = distance_for(wanted, &template, camera);
2577 spot_light_at(Vec3::new(0.0, 0.0, -distance), 1.0)
2578 }
2579
2580 /// **A light with no history lands exactly where the ladder with no band at
2581 /// all would put it**, which is what makes a frame's first answer
2582 /// reproducible rather than a function of what ran before it.
2583 ///
2584 /// The two walks in [`tile_level`] start from the coarsest level, so the
2585 /// shrink walk cannot fire on a fresh light and the grow walk stops at the
2586 /// first threshold the coverage does not clear. Asserted against the ladder
2587 /// written out independently — the first level whose threshold the coverage
2588 /// reaches — rather than against [`tile_level`]'s own walk.
2589 #[test]
2590 fn a_light_with_no_history_lands_where_the_sharp_ladder_puts_it() {
2591 // A fine grid over the whole ladder and well past its top, so every rung
2592 // is sampled inside the band `LEVEL_HOLD_RATIO` opens under its
2593 // threshold as well as outside it. Coarser steps would land on the
2594 // thresholds themselves and miss the only coverages where a start from
2595 // the wrong end of the ladder gives a different answer.
2596 for numerator in 1..=512u32 {
2597 let coverage = f32::from(u16::try_from(numerator).expect("a small count")) / 512.0;
2598 let sharp = (0..TILE_LEVELS)
2599 .find(|level| coverage >= level_threshold(*level))
2600 .unwrap_or(TILE_LEVELS - 1);
2601 assert_eq!(
2602 tile_level(coverage, None),
2603 sharp,
2604 "a coverage of {coverage} with no history"
2605 );
2606 }
2607 }
2608
2609 /// **A light sitting on a threshold does not flicker its tile size**, and
2610 /// the band is crossed in both directions.
2611 ///
2612 /// The half that a one-sided test would miss is the second pair: a rule that
2613 /// never shrinks is not hysteresis, it is a tile a light keeps for ever, and
2614 /// a scene that walked away from its lights would spend the atlas on maps
2615 /// nothing can see. Every coverage below is written as a fraction of
2616 /// [`WHOLE_CELL_COVERAGE`] so the assertion is about the band rather than
2617 /// about where the ladder happens to start.
2618 #[test]
2619 fn a_light_on_a_threshold_holds_its_tile_size_until_it_clearly_crosses() {
2620 let inside_band = WHOLE_CELL_COVERAGE * (1.0 + LEVEL_HOLD_RATIO) / 2.0;
2621 let past_band = WHOLE_CELL_COVERAGE * LEVEL_HOLD_RATIO * 0.95;
2622 assert!(
2623 past_band < WHOLE_CELL_COVERAGE * LEVEL_HOLD_RATIO && inside_band < WHOLE_CELL_COVERAGE,
2624 "both excursions must be below the threshold, or the test is about the grow walk"
2625 );
2626
2627 // Holding a whole cell, drifting under the threshold but not out of the
2628 // band: the tile stays whole.
2629 assert_eq!(tile_level(inside_band, Some(0)), 0);
2630 // Clearly under it: the tile halves.
2631 assert_eq!(tile_level(past_band, Some(0)), 1);
2632 // And back the other way. Inside the band from below is *not* enough —
2633 // a challenger has to reach the threshold outright — and past it is.
2634 assert_eq!(tile_level(inside_band, Some(1)), 1);
2635 assert_eq!(tile_level(WHOLE_CELL_COVERAGE, Some(1)), 0);
2636 }
2637
2638 /// **A far or narrow light takes a halving of a cell and a near, large one
2639 /// takes the whole of it**, which is the priority rung's whole claim and the
2640 /// first thing in this tree to ask [`AtlasAllocator`] for anything but level
2641 /// zero.
2642 ///
2643 /// Read off the rectangles rather than off the levels, because the rectangle
2644 /// is what the shadow pass sets its viewport to and what the shader samples
2645 /// through: a level that never reached the allocator would still pass an
2646 /// assertion about [`Assignment::level`].
2647 #[test]
2648 fn the_tile_size_falls_with_the_coverage() {
2649 let camera = camera_at(Vec3::ZERO);
2650 // One coverage comfortably inside each rung of the ladder: the top one
2651 // well clear of the anchor, then each threshold's midpoint below it, and
2652 // one under the last threshold entirely.
2653 let lights: Vec<Light> = (0..TILE_LEVELS)
2654 .map(|level| {
2655 let wanted = if level + 1 == TILE_LEVELS {
2656 level_threshold(level - 1) * 0.5
2657 } else {
2658 level_threshold(level) * 1.5
2659 };
2660 spot_covering(wanted, &camera)
2661 })
2662 .collect();
2663 let mut selection = Selection::default();
2664 selection.update(&lights, &camera);
2665 for (level, _) in lights.iter().enumerate() {
2666 let base = selection
2667 .base_of(level)
2668 .unwrap_or_else(|| panic!("light {level} was given no tile"));
2669 let rect = selection.atlas_rect(light_tile(base));
2670 assert_eq!(
2671 rect.side,
2672 TILE >> level,
2673 "light {level} was laid out at {rect:?}, not the level-{level} tile its \
2674 coverage earned"
2675 );
2676 }
2677 // And the allocation is still a partition: every size at once is exactly
2678 // where a quadtree can hand out a rectangle inside another one.
2679 let (width, height) = atlas_extent();
2680 let mut covered = vec![false; (width * height) as usize];
2681 for slot in 0..TILES {
2682 let rect = selection.atlas_rect(slot);
2683 for row in rect.y..rect.y + rect.side {
2684 for column in rect.x..rect.x + rect.side {
2685 let texel = (row * width + column) as usize;
2686 assert!(
2687 !covered[texel],
2688 "texel ({column}, {row}) is in slot {slot}'s {rect:?} and in a \
2689 slot laid out before it"
2690 );
2691 covered[texel] = true;
2692 }
2693 }
2694 }
2695 }
2696
2697 /// The same claim through a whole [`Selection`], with the light *moving*:
2698 /// a small excursion across the threshold does not change the rectangle it
2699 /// is rendered into, and a large one does.
2700 ///
2701 /// The unit test above is about [`tile_level`]; this one is about the memory
2702 /// that feeds it. A selection that rebuilt its assignments without carrying
2703 /// last frame's level would pass that test and flicker here, because every
2704 /// frame would be a fresh light landing at the sharp answer.
2705 #[test]
2706 fn a_moving_light_keeps_its_tile_size_across_a_small_excursion() {
2707 let camera = camera_at(Vec3::ZERO);
2708 let inside_band = WHOLE_CELL_COVERAGE * (1.0 + LEVEL_HOLD_RATIO) / 2.0;
2709 let past_band = WHOLE_CELL_COVERAGE * LEVEL_HOLD_RATIO * 0.95;
2710 let mut selection = Selection::default();
2711 let side = |selection: &Selection| {
2712 selection
2713 .atlas_rect(light_tile(selection.base_of(0).expect("a tile")))
2714 .side
2715 };
2716
2717 selection.update(
2718 &[spot_covering(WHOLE_CELL_COVERAGE * 2.0, &camera)],
2719 &camera,
2720 );
2721 assert_eq!(
2722 side(&selection),
2723 TILE,
2724 "a light well over the anchor is a whole cell"
2725 );
2726
2727 selection.update(&[spot_covering(inside_band, &camera)], &camera);
2728 assert_eq!(
2729 side(&selection),
2730 TILE,
2731 "a light that drifted under the threshold but not out of the band must keep \
2732 the tile it had"
2733 );
2734
2735 selection.update(&[spot_covering(past_band, &camera)], &camera);
2736 assert_eq!(
2737 side(&selection),
2738 TILE >> 1,
2739 "a light clearly under the threshold must take the halving"
2740 );
2741
2742 selection.update(&[spot_covering(inside_band, &camera)], &camera);
2743 assert_eq!(
2744 side(&selection),
2745 TILE >> 1,
2746 "coming back inside the band is not reaching the threshold, so the tile stays \
2747 halved — the half of the band a one-sided test would miss"
2748 );
2749
2750 selection.update(&[spot_covering(WHOLE_CELL_COVERAGE, &camera)], &camera);
2751 assert_eq!(
2752 side(&selection),
2753 TILE,
2754 "reaching the threshold outright takes the whole cell back"
2755 );
2756 }
2757
2758 /// **A narrow cone is not demoted for being narrow.**
2759 ///
2760 /// [`coverage`] is about the map rather than about the light, which is the
2761 /// difference between this rung and "radius over distance": two lights of
2762 /// one radius at one distance spread their texels over world regions that
2763 /// differ by `tan(outer)`, and the narrow one already has the finer texels.
2764 /// Judging it by its sphere would hand the whole cell to the light that
2765 /// needs it least.
2766 #[test]
2767 fn a_narrow_cone_outscores_a_wide_one_of_the_same_reach() {
2768 let camera = camera_at(Vec3::ZERO);
2769 let at = Vec3::new(0.0, 0.0, -4.0);
2770 let mut narrow = spot_light_at(at, 1.0);
2771 if let Light::Spot(spot) = &mut narrow {
2772 spot.inner_angle = 0.05;
2773 spot.outer_angle = 0.1;
2774 }
2775 let wide = spot_light_at(at, 1.0);
2776 assert!(
2777 coverage(&narrow, &camera) < coverage(&wide, &camera),
2778 "a cone covering less of the frame must score below a wider one at the same reach"
2779 );
2780 // And the sphere metric this replaced cannot tell them apart at all,
2781 // which is the reason the footprint is read instead.
2782 assert_eq!(narrow.sphere().1, wide.sphere().1);
2783 }
2784
2785 /// **A slot with no map hands the shader a rectangle of zeros, and that is
2786 /// the condition every lookup in `mesh.slang` guards on.**
2787 ///
2788 /// The host half of `crcbl_shaders::mesh`'s
2789 /// `no_shadow_lookup_divides_by_a_rectangle_before_it_checks_one`: that
2790 /// test says the shader answers "lit" before it divides by a rectangle
2791 /// whose `x` is not positive, and this says the rectangle it will be handed
2792 /// for an empty slot is exactly that. Neither half is worth anything on its
2793 /// own — a guard on a condition the host never produces is dead, and a host
2794 /// producing a condition nothing guards is
2795 /// `crates/crcbl/tests/forward_e2e/depth_probe.rs`'s black frame on
2796 /// llvmpipe 20.1.2.
2797 ///
2798 /// **And a real tile is never mistaken for an empty one**, which is the
2799 /// other half of a two-sided condition: the finest tile the allocator can
2800 /// hand out is [`MIN_TILE`] texels, so its scale into the atlas is a
2801 /// positive number and no map is ever read as absent.
2802 #[test]
2803 fn a_slot_with_no_map_hands_the_shader_a_rectangle_of_zeros() {
2804 assert_eq!(
2805 TileRect::EMPTY.to_uv(),
2806 [0.0; 4],
2807 "an empty slot's rectangle is what `mesh.slang`'s `atlas_rect_is_empty` tests, and \
2808 it tests `x` against zero"
2809 );
2810
2811 // A frame with no shadowed light at all — `depth_probe.rs`'s frame, and
2812 // every light-region slot of it.
2813 let mut selection = Selection::default();
2814 selection.update(&[], &camera_at(Vec3::ZERO));
2815 for tile in 0..LIGHT_TILES {
2816 assert_eq!(
2817 selection.atlas_rect(light_tile(tile)).to_uv(),
2818 [0.0; 4],
2819 "light tile {tile} of a frame with no shadowed light must read as empty"
2820 );
2821 }
2822
2823 // And every size a light can actually be given reads as present.
2824 for level in 0..TILE_LEVELS {
2825 let mut allocator = AtlasAllocator::new();
2826 let tile = allocator
2827 .allocate(level)
2828 .unwrap_or_else(|| panic!("an empty atlas has room for a level-{level} tile"));
2829 assert!(
2830 tile.rect().to_uv()[0] > 0.0,
2831 "a level-{level} tile reads as an empty slot, so `mesh.slang` would answer lit \
2832 through a map that was rendered"
2833 );
2834 }
2835 }
2836
2837 /// **A frame that changed nothing lays out on exactly the texels the last
2838 /// one did**, which is the precondition every cached shadow map rests on:
2839 /// the shader reads a rectangle out of `atlas_rects`, and a map not redrawn
2840 /// this frame is only readable through the rectangle it *was* drawn into.
2841 ///
2842 /// The rectangles alone would be a weak claim — they were equal before this
2843 /// rung too, because the allocator was replayed from empty in the same
2844 /// order every frame. What says the tiles were *kept* rather than
2845 /// re-derived is the second half: the allocation is compared against a
2846 /// selection that has only ever seen this one frame, so the layout a
2847 /// caching frame carries forward is still the layout a golden was blessed
2848 /// under.
2849 #[test]
2850 fn a_still_frame_keeps_the_texels_the_last_one_drew_into() {
2851 let camera = camera_at(Vec3::ZERO);
2852 let lights = [
2853 Light::Point(point_at(Vec3::new(0.0, 0.0, -3.0), 4.0)),
2854 spot_light_at(Vec3::new(0.0, 0.0, -2.0), 2.0),
2855 ];
2856 let mut selection = Selection::default();
2857 selection.update(&lights, &camera);
2858 let first: Vec<TileRect> = (0..TILES).map(|slot| selection.atlas_rect(slot)).collect();
2859 assert!(
2860 first[..CASCADES].iter().all(|rect| rect.side == TILE),
2861 "the cascades must hold whole cells for this to be about the lights: {first:?}"
2862 );
2863 for round in 0..4 {
2864 selection.update(&lights, &camera);
2865 let again: Vec<TileRect> = (0..TILES).map(|slot| selection.atlas_rect(slot)).collect();
2866 assert_eq!(
2867 again, first,
2868 "round {round} moved a map that nothing asked to move"
2869 );
2870 }
2871
2872 let mut fresh = Selection::default();
2873 fresh.update(&lights, &camera);
2874 assert_eq!(
2875 selection, fresh,
2876 "a selection that has held its tiles for five frames must hold exactly what one \
2877 that has just laid them out holds — allocator included, or the atlas is drifting \
2878 towards a layout no golden was blessed under"
2879 );
2880 }
2881
2882 /// **Every tile a light stopped needing comes back**, merged, so an atlas
2883 /// that has churned through lights is the atlas it started as.
2884 ///
2885 /// The leak assertion for `AtlasAllocator::release`'s only caller, and it
2886 /// is deliberately about the allocator rather than about the rectangles: a
2887 /// `lay_out` that released nothing would still hand out plausible
2888 /// rectangles for a long time, and would then run out of atlas on a frame
2889 /// nothing about the scene explains. Compared against a selection that has
2890 /// only ever seen the empty list, so a quarter cell left out on loan is a
2891 /// difference in the quadtree even while every rectangle still reads empty.
2892 #[test]
2893 fn a_light_that_leaves_hands_every_tile_it_held_back() {
2894 let camera = camera_at(Vec3::ZERO);
2895 let spot = spot_light_at(Vec3::new(0.0, 0.0, -1.0), 4.0);
2896 let other = spot_light_at(Vec3::new(0.0, 0.0, -2.0), 2.0);
2897 let point = Light::Point(point_at(Vec3::new(0.0, 0.0, -1.0), 4.0));
2898 let mut selection = Selection::default();
2899 for lights in [
2900 vec![spot, other],
2901 vec![point, other],
2902 vec![point],
2903 vec![],
2904 vec![spot, other, point],
2905 vec![point, point, point],
2906 vec![spot_covering(WHOLE_CELL_COVERAGE / 8.0, &camera)],
2907 vec![point, spot, point, other, point],
2908 ] {
2909 selection.update(&lights, &camera);
2910 }
2911 selection.update(&[], &camera);
2912
2913 let mut fresh = Selection::default();
2914 fresh.update(&[], &camera);
2915 assert_eq!(
2916 selection, fresh,
2917 "the atlas is not back where it started after every light left it"
2918 );
2919 }
2920
2921 /// **Demoting one light moves no other light\'s map**, which is the whole of
2922 /// what holding a tile across frames buys over laying the atlas out again.
2923 ///
2924 /// This is the assertion a `lay_out` that released everything and replayed
2925 /// the requests cannot pass, and it is the reason the retention is not
2926 /// merely an optimisation: the requests are spent coarsest first, so a
2927 /// light that demotes changes *where in that order* every request after it
2928 /// falls, and a replay hands the light behind it a different root. The map
2929 /// in that root was not redrawn — nothing about it changed — so a shader
2930 /// reading the new rectangle reads its neighbour\'s texels.
2931 ///
2932 /// Built so the demoting light is the one that sorts *first*: with the
2933 /// order the other way round a replay lands on the same answer by accident,
2934 /// and the test would pass without the retention being there at all.
2935 #[test]
2936 fn demoting_one_light_leaves_the_maps_around_it_where_they_were() {
2937 let camera = camera_at(Vec3::ZERO);
2938 // The first is the brighter of the two, so it takes the first run and
2939 // is the request the demotion reorders; the second is what must not
2940 // move under it.
2941 let near = spot_covering(WHOLE_CELL_COVERAGE * 4.0, &camera);
2942 let steady = spot_covering(WHOLE_CELL_COVERAGE * 2.0, &camera);
2943 let mut selection = Selection::default();
2944 selection.update(&[near, steady], &camera);
2945 assert_eq!(
2946 selection.base_of(0),
2947 Some(0),
2948 "the brighter light must hold the first run for this to be about the reordering"
2949 );
2950 let before = selection.atlas_rect(light_tile(1));
2951 assert_eq!(
2952 before.side, TILE,
2953 "the steady light must start on a whole cell"
2954 );
2955
2956 selection.update(
2957 &[spot_covering(WHOLE_CELL_COVERAGE / 8.0, &camera), steady],
2958 &camera,
2959 );
2960 assert!(
2961 selection.atlas_rect(light_tile(0)).side < TILE,
2962 "the first light did not demote, so nothing reordered"
2963 );
2964 assert_eq!(
2965 selection.atlas_rect(light_tile(1)),
2966 before,
2967 "the steady light\'s map moved because its neighbour demoted"
2968 );
2969 }
2970
2971 /// **A demotion gives the cell back whole**, so the space a light stopped
2972 /// needing is space the next whole-cell request can have.
2973 ///
2974 /// The merge in [`AtlasAllocator::release`] read from the renderer's side:
2975 /// a light demoted down the ladder splits a root, and the promotion back up
2976 /// can only be answered by that same root if the four quarters — and the
2977 /// sixteenths under them — merged on the way back.
2978 #[test]
2979 fn a_demoted_light_gives_its_cell_back_and_can_take_it_again() {
2980 let camera = camera_at(Vec3::ZERO);
2981 let near = [spot_covering(WHOLE_CELL_COVERAGE * 2.0, &camera)];
2982 let far = [spot_covering(WHOLE_CELL_COVERAGE / 8.0, &camera)];
2983 let tile = |selection: &Selection| selection.atlas_rect(light_tile(0)).side;
2984
2985 let mut selection = Selection::default();
2986 selection.update(&near, &camera);
2987 assert_eq!(
2988 tile(&selection),
2989 TILE,
2990 "a near light must earn a whole cell"
2991 );
2992
2993 selection.update(&far, &camera);
2994 let demoted = tile(&selection);
2995 assert!(
2996 demoted < TILE,
2997 "the far light kept a whole cell, so this test is not about a demotion"
2998 );
2999
3000 selection.update(&near, &camera);
3001 assert_eq!(
3002 tile(&selection),
3003 TILE,
3004 "the cell the demotion released did not come back whole"
3005 );
3006 let mut fresh = Selection::default();
3007 fresh.update(&near, &camera);
3008 assert_eq!(
3009 selection, fresh,
3010 "a round trip down the ladder and back left the atlas fragmented"
3011 );
3012 }
3013
3014 /// An incumbent that leaves the list — or stops being eligible — frees its
3015 /// tile rather than holding an index into a list that no longer has it.
3016 ///
3017 /// The list is rebuilt every frame, so an index is only meaningful against
3018 /// the list it came from. Carrying one across a shorter list is how a slot
3019 /// ends up naming a light that is not there.
3020 #[test]
3021 fn an_incumbent_that_leaves_the_list_frees_its_tile() {
3022 let lights = [
3023 spot_light_at(Vec3::new(0.0, 0.0, -1.0), 1.0),
3024 spot_light_at(Vec3::new(0.0, 0.0, -2.0), 1.0),
3025 ];
3026 let mut selection = Selection::default();
3027 selection.update(&lights, &camera_at(Vec3::ZERO));
3028 assert_eq!(selection.slots(), &[held(0, 0), held(1, 1), None, None]);
3029
3030 selection.update(&lights[..1], &camera_at(Vec3::ZERO));
3031 assert_eq!(selection.slots(), &[held(0, 0), None, None, None]);
3032
3033 selection.update(&[], &camera_at(Vec3::ZERO));
3034 assert_eq!(selection.slots(), &[None; LIGHT_SLOTS]);
3035 }
3036
3037 /// [`FILTERS`], [`r_shadow_filter`] and
3038 /// [`crcbl_shaders::mesh::SHADOW_FILTERS`] must name the same set, in the
3039 /// same order.
3040 ///
3041 /// `crate::ssao`'s `the_variable_names_are_the_techniques_labels` is this
3042 /// test on the other enum variable, with a third list to hold: the console's
3043 /// literals, this module's labels and the shader's constants are three
3044 /// copies of one set of names, and `mesh.slang` numbers its constants by
3045 /// position in the shader's list. A name that drifted would be a value a
3046 /// person can set and [`filter`] answers with [`Filter::Pcss`] — the
3047 /// selector silently doing nothing; an *order* that drifted would be a mode
3048 /// the shader reads as its neighbour, which is a filter nobody asked for.
3049 ///
3050 /// **It holds the names and not the enum's completeness**, on the occlusion
3051 /// chain's terms: a variant added to [`Filter`] and left out of [`FILTERS`]
3052 /// passes here, and costs nothing a frame can reach because the console
3053 /// cannot name it.
3054 #[test]
3055 fn the_variable_names_are_the_filters_labels() {
3056 let crcbl_console::Kind::Enum(names) = r_shadow_filter.kind() else {
3057 panic!("`r_shadow_filter` is an enum variable");
3058 };
3059 let labels: Vec<&str> = FILTERS.into_iter().map(Filter::label).collect();
3060 assert_eq!(names, labels.as_slice());
3061 assert_eq!(
3062 labels.as_slice(),
3063 crcbl_shaders::mesh::SHADOW_FILTERS.as_slice(),
3064 "the shader numbers its `SHADOW_FILTER_*` constants by position in its own list, \
3065 so a set that differs here is a mode the fragment reads as another filter"
3066 );
3067 for filter in Filter::ALL {
3068 assert_eq!(Filter::from_name(filter.label()), Some(filter));
3069 }
3070 assert_eq!(Filter::from_name("soft"), None);
3071 // And the numbering itself, which is the half a set comparison cannot
3072 // see: `Filter::mode` searches by label, so a list in the right order
3073 // with the wrong lookup would still pass above.
3074 for (mode, filter) in FILTERS.into_iter().enumerate() {
3075 assert_eq!(
3076 filter.mode() as usize,
3077 mode,
3078 "`{}` is the shader's mode {}, not {mode}",
3079 filter.label(),
3080 filter.mode()
3081 );
3082 }
3083 }
3084
3085 /// A frame nobody has touched the console on runs what ships, and so does
3086 /// the far side of the seam whatever the console holds.
3087 ///
3088 /// `crate::ssao`'s `the_seams_other_side_is_the_technique_that_ships`, and
3089 /// the same failure: a [`shipped_filter`] that followed the console would be
3090 /// a comparison of one filter against itself, which is a seam that draws one
3091 /// picture and says nothing.
3092 #[test]
3093 fn the_seams_other_side_is_the_filter_that_ships() {
3094 use crcbl_console::Value;
3095
3096 let _guard = FILTER_SWITCH
3097 .lock()
3098 .unwrap_or_else(std::sync::PoisonError::into_inner);
3099 let before = r_shadow_filter.get_enum();
3100 assert_eq!(
3101 filter(),
3102 Filter::Pcss,
3103 "a frame nobody has touched the console on must sample through the filter every \
3104 golden in this workspace was blessed under"
3105 );
3106 let shipped_before = shipped_filter();
3107
3108 r_shadow_filter
3109 .set(&Value::Enum(Filter::Box.label()))
3110 .expect("a writable enum in the set");
3111 // Anti-vacuity: the knob has to have actually moved, or the equality
3112 // below holds of a console nobody changed.
3113 assert_eq!(
3114 filter(),
3115 Filter::Box,
3116 "the getter did not follow the console"
3117 );
3118 assert_eq!(
3119 shipped_filter(),
3120 shipped_before,
3121 "the shipped filter moved when the console did, so the seam compares a filter \
3122 against itself"
3123 );
3124 assert_ne!(
3125 shipped_filter(),
3126 filter(),
3127 "the shipped filter is what the console holds, so both sides of the seam run one \
3128 kernel"
3129 );
3130
3131 r_shadow_filter
3132 .set(&Value::Enum(before))
3133 .expect("putting the filter back");
3134 }
3135
3136 /// A seam at either end of [`r_shadow_split`]'s range is no comparison, and
3137 /// the default is one of them.
3138 ///
3139 /// `crate::ssao::split_at`'s rule, asserted here because this is a second
3140 /// copy of it: a default that compared would put a seam through every
3141 /// golden in the workspace, and an end of the range that compared would ask
3142 /// `crate::split::halves` for a rectangle with no columns in it.
3143 #[test]
3144 fn a_seam_at_either_edge_is_no_comparison() {
3145 use crcbl_console::Value;
3146
3147 let _guard = FILTER_SWITCH
3148 .lock()
3149 .unwrap_or_else(std::sync::PoisonError::into_inner);
3150 let before = r_shadow_split.get_f32();
3151 assert_eq!(
3152 split_at(),
3153 None,
3154 "a frame nobody has touched the console on must draw one filter over the whole \
3155 target, which is what every golden in this workspace was blessed as"
3156 );
3157 for (at, wanted) in [
3158 (0.0, None),
3159 (1.0, None),
3160 (0.5, Some(0.5)),
3161 (0.25, Some(0.25)),
3162 ] {
3163 r_shadow_split
3164 .set(&Value::Float(at))
3165 .expect("a writable float in range");
3166 assert_eq!(split_at(), wanted, "a seam asked for at {at}");
3167 }
3168 r_shadow_split
3169 .set(&Value::Float(before))
3170 .expect("putting the seam back");
3171 }
3172}