Skip to main content

crcbl_render/
light.rs

1//! The lights a frame carries, and the rows they become.
2//!
3//! ```text
4//!  DirectionalLight ──┐
5//!  Light::Point    ───┤
6//!  Light::Spot     ───┼──▶ [GpuLight] ──▶ light_cluster.slang ──▶ froxel grid
7//!  Light::Rect     ───┘                                              │
8//!                                            mesh.slang's fragment ◀─┘
9//! ```
10//!
11//! Topic 44's "Many lights" (`docs/notes/rendering.md`): a light is a row in a
12//! storage buffer, the sun included. The sun keeps a type of its own on this
13//! side — it is the light that owns the ambient term and the shadow cascades,
14//! and [`ForwardRenderer::begin_frame`] has always taken one — but it stops
15//! being a special case where it mattered, which is in the shader.
16//!
17//! [`ForwardRenderer::begin_frame`]: crate::forward::ForwardRenderer::begin_frame
18
19use crcbl_shaders::light::{self, GpuLight};
20use glam::Vec3;
21
22use crate::camera::DirectionalLight;
23
24/// A light that lives somewhere, as distinct from the sun, which does not.
25///
26/// Three variants and one row: the shader loop shades all four kinds with one
27/// BRDF, which is topic 44's "one material table, one
28/// BRDF, one set of inputs" holding by construction rather than by four copies
29/// of it agreeing.
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub enum Light {
32    /// Radiates equally in every direction, out to its radius.
33    Point(PointLight),
34    /// A point light with a cone over it.
35    Spot(SpotLight),
36    /// A rectangle that radiates from one of its faces.
37    Rect(RectLight),
38}
39
40/// A light radiating equally in every direction.
41#[derive(Clone, Copy, Debug, PartialEq)]
42pub struct PointLight {
43    /// Where it is, in render space.
44    pub position: Vec3,
45    /// How far its influence reaches, in world units.
46    ///
47    /// **A hard bound, not a fade cut short.** The shader's falloff reaches
48    /// exactly zero here, and the clustering pass culls against this same
49    /// number — so a light is either in a froxel's list or contributing nothing
50    /// to it, and there is no radius at which the two disagree and leave a seam.
51    /// Larger costs more froxels, not a softer edge.
52    pub radius: f32,
53    /// Colour premultiplied by intensity. **May exceed 1.0**, like the sun's:
54    /// the scene target is `Rgba16Float` precisely so that it can.
55    pub color: Vec3,
56    /// Whether this is a **fill** light: one that lights but casts no shadow and
57    /// adds no specular.
58    ///
59    /// Topic 44's rung 5 asked for it beside the area lights.
60    /// It is how a stack with no baked bounce lights the far end of a room
61    /// without paying for a shadow map or leaving a highlight where no fixture
62    /// is. `crcbl_shaders::light::FLAG_FILL` is the row's bit;
63    /// [`shadow::Selection`](crate::shadow::Selection) refuses such a light a
64    /// tile and `mesh.slang` refuses it a lobe.
65    ///
66    /// **Every kind carries it**, on this field's terms exactly, and
67    /// [`Light::is_fill`] is where one question is asked of the three.
68    pub fill: bool,
69}
70
71/// A point light with a cone over it.
72#[derive(Clone, Copy, Debug, PartialEq)]
73pub struct SpotLight {
74    /// Where it is, in render space.
75    pub position: Vec3,
76    /// How far its influence reaches, on [`PointLight::radius`]'s terms exactly.
77    pub radius: f32,
78    /// Colour premultiplied by intensity.
79    pub color: Vec3,
80    /// The direction the cone points **along**, away from the light.
81    ///
82    /// The opposite convention from [`DirectionalLight::direction`], and
83    /// deliberately: a spot points *at* something and a sun comes *from*
84    /// somewhere, so each field is the vector a caller has. The shader is what
85    /// reconciles them, and its `spot_cone` says where the negation is.
86    ///
87    /// Normalised on the way into the row.
88    pub direction: Vec3,
89    /// Half-angle of the cone's bright core, in radians. Full brightness inside.
90    pub inner_angle: f32,
91    /// Half-angle at which the cone closes, in radians. Dark outside.
92    ///
93    /// Must be at least [`inner_angle`](Self::inner_angle); [`Light::row`]
94    /// widens it to that if it is not, rather than emitting a row whose two
95    /// cosines the shader would divide the wrong way round.
96    pub outer_angle: f32,
97    /// Whether this is a **fill** light, on [`PointLight::fill`]'s terms
98    /// exactly: it lights, casts no shadow and adds no specular.
99    pub fill: bool,
100}
101
102/// A rectangle that radiates from one of its faces — topic 44's
103/// rung 5, shaded through the linearly transformed cosine fit in
104/// [`crcbl_shaders::ltc`].
105///
106/// # What a rectangle is here
107///
108/// A centre, a plane, two half-extents and a side. The plane is
109/// [`direction`](Self::direction) — the way the panel faces, so a surface behind
110/// it is not lit at all — and [`tangent`](Self::tangent), which names the `u`
111/// axis inside it; the `v` axis is their cross product and is not stored.
112/// Neither vector has to arrive unit or perpendicular: [`Light::row`] normalises
113/// and orthogonalises them on the way into the row, because a row that broke
114/// either would be a rectangle that is not one and no picture would say so.
115///
116/// # The winding, which is what makes it one-sided
117///
118/// `v` is `cross(tangent, direction)`, and the shader walks the corners
119/// `-u-v, +u-v, +u+v, -u+v`. That order makes the spherical polygon's integral
120/// **positive** for a receiver on the side [`direction`](Self::direction) points
121/// at and negative behind it, and the shader takes the positive half. So a panel
122/// lights the room it faces and nothing on the other side of its own wall —
123/// which is what a window is, and what saves the far half of a scene from being
124/// lit through the floor.
125#[derive(Clone, Copy, Debug, PartialEq)]
126pub struct RectLight {
127    /// The centre of the rectangle, in render space.
128    pub position: Vec3,
129    /// How far its influence reaches **from that centre**, in world units.
130    ///
131    /// [`PointLight::radius`]'s terms, and the same hard bound: the shading
132    /// window reaches exactly zero here and `light_cluster.slang` culls against
133    /// this same sphere, so there is no radius at which the two disagree.
134    /// Measured from the centre rather than from the nearest corner, which is
135    /// what makes those two the same number — so a large panel wants a radius
136    /// comfortably past its own half-diagonal or it will fade out before its own
137    /// edge does.
138    pub radius: f32,
139    /// Colour premultiplied by intensity — the radiance leaving the face.
140    ///
141    /// **A radiance rather than a power**, which is what makes a rectangle
142    /// behave: doubling its extent doubles the light in the room, because it is
143    /// twice the emitter. A caller holding a lumen figure divides by the area.
144    pub color: Vec3,
145    /// The direction the face radiates along, away from the panel.
146    ///
147    /// [`SpotLight::direction`]'s convention — a fixture points *at* something —
148    /// and normalised on the way into the row.
149    pub direction: Vec3,
150    /// The `u` axis of the rectangle's plane, which fixes how it is turned about
151    /// its own normal.
152    ///
153    /// Orthogonalised against [`direction`](Self::direction) and normalised on
154    /// the way into the row, so a caller may hand over any vector that is not
155    /// parallel to the normal — a world axis, usually. One exactly parallel to
156    /// it leaves the rectangle without a plane, and [`Light::row`] picks a
157    /// perpendicular rather than emitting a row of nothings.
158    pub tangent: Vec3,
159    /// Half the rectangle's extent along `u`, in world units.
160    pub half_width: f32,
161    /// Half its extent along `v`, which is `cross(tangent, direction)`.
162    pub half_height: f32,
163    /// Whether this is a **fill** light, on [`PointLight::fill`]'s terms
164    /// exactly: it lights, casts no shadow and adds no specular.
165    ///
166    /// A rectangle is refused a shadow map for a second reason as well — it
167    /// radiates from a surface, so there is no centre of projection to render
168    /// one from — and on this kind the flag is the specular half alone.
169    pub fill: bool,
170}
171
172impl RectLight {
173    /// The rectangle's plane, as a unit normal and a unit `u` axis inside it.
174    ///
175    /// The whole of the orthogonalisation the row needs, in one place because
176    /// [`Light::row`] and [`Light::sphere`] would otherwise each have an opinion
177    /// about a degenerate rectangle. A normal that is not a direction at all
178    /// becomes `+Z`, and a tangent parallel to the normal becomes whichever
179    /// world axis is least like it — both of which are arbitrary, and both of
180    /// which are a rectangle rather than a row of `NaN`s.
181    #[must_use]
182    pub fn frame(&self) -> (Vec3, Vec3) {
183        let normal = self.direction.normalize_or_zero();
184        let normal = if normal.length_squared() > 0.0 {
185            normal
186        } else {
187            Vec3::Z
188        };
189        let across = self.tangent - normal * self.tangent.dot(normal);
190        let tangent = across.normalize_or_zero();
191        if tangent.length_squared() > 0.0 {
192            return (normal, tangent);
193        }
194        // The tangent was parallel to the normal, so it names no plane. Any
195        // perpendicular will do — the rectangle is then turned arbitrarily about
196        // its own axis, which is the only thing the caller left unsaid.
197        let seed = if normal.z.abs() < 0.9 {
198            Vec3::Z
199        } else {
200            Vec3::X
201        };
202        (normal, seed.cross(normal).normalize())
203    }
204}
205
206impl Light {
207    /// Whether this light is a **fill** light: one that lights, casts no shadow
208    /// and adds no specular.
209    ///
210    /// A method on the enum rather than a match at each caller, so
211    /// [`shadow::Selection`](crate::shadow::Selection) asks one question of a
212    /// light rather than three. Every kind carries the field and
213    /// [`PointLight::fill`] is where it is described.
214    #[must_use]
215    pub const fn is_fill(&self) -> bool {
216        match self {
217            Self::Point(point) => point.fill,
218            Self::Spot(spot) => spot.fill,
219            Self::Rect(rect) => rect.fill,
220        }
221    }
222
223    /// This light as the row the shaders read, occluding through the light tiles
224    /// starting at `base_tile`.
225    ///
226    /// **The first tile, not the only one**: a spot occludes through that tile
227    /// alone and a point light through the
228    /// [`POINT_FACES`](crate::shadow::POINT_FACES) tiles from there, one per cube
229    /// face, which the shader selects between. `shadow::Selection` is what hands
230    /// the run out.
231    ///
232    /// `None` is a light with no map of its own, which is the ordinary case: the
233    /// atlas holds [`shadow::LIGHT_TILES`](crate::shadow::LIGHT_TILES) light
234    /// tiles and a scene may want more than they hold. Such a light still lights
235    /// and simply does not occlude — topic 45's honest
236    /// degradation, and the reason the budget is a quality knob rather than a
237    /// correctness cliff.
238    #[must_use]
239    pub fn row(&self, base_tile: Option<usize>) -> GpuLight {
240        let shadow_tile = base_tile.map_or(light::NO_SHADOW_TILE, |base| {
241            u32::try_from(base).unwrap_or(light::NO_SHADOW_TILE)
242        });
243        // One reading of the flag for all three kinds, rather than an arm that
244        // could be the one to forget it: `is_fill` is the same question
245        // `shadow::Selection` asked before it refused this light a tile.
246        let flags = if self.is_fill() { light::FLAG_FILL } else { 0 };
247        match self {
248            Self::Point(point) => GpuLight {
249                position: point.position.extend(point.radius).to_array(),
250                color: point.color.extend(0.0).to_array(),
251                direction: [0.0; 4],
252                tangent: [0.0; 4],
253                kind: light::KIND_POINT,
254                cos_inner: 0.0,
255                shadow_tile,
256                flags,
257            },
258            Self::Spot(spot) => {
259                // **Widened rather than trusted.** The shader divides by
260                // `cos_inner - cos_outer` and a caller who wrote the two angles
261                // the wrong way round would get a lit cone exterior — a picture,
262                // not an error. Clamping here is the one place that can be
263                // enforced for every backend at once.
264                let outer = spot.outer_angle.max(spot.inner_angle);
265                GpuLight {
266                    position: spot.position.extend(spot.radius).to_array(),
267                    color: spot.color.extend(0.0).to_array(),
268                    direction: spot
269                        .direction
270                        .normalize_or_zero()
271                        .extend(outer.cos())
272                        .to_array(),
273                    tangent: [0.0; 4],
274                    kind: light::KIND_SPOT,
275                    cos_inner: spot.inner_angle.cos(),
276                    shadow_tile,
277                    flags,
278                }
279            }
280            Self::Rect(rect) => {
281                let (normal, tangent) = rect.frame();
282                GpuLight {
283                    position: rect.position.extend(rect.radius).to_array(),
284                    color: rect.color.extend(0.0).to_array(),
285                    // The `w`s are the two half-extents, each beside the axis it
286                    // is measured along — `crcbl_shaders::light::KIND_RECT` is
287                    // the map.
288                    direction: normal.extend(rect.half_height).to_array(),
289                    tangent: tangent.extend(rect.half_width).to_array(),
290                    kind: light::KIND_RECT,
291                    cos_inner: 0.0,
292                    shadow_tile,
293                    flags,
294                }
295            }
296        }
297    }
298
299    /// Where this light is and how far it reaches, for a caller that has to
300    /// bound it — the clustering pass's test, on the host.
301    #[must_use]
302    pub const fn sphere(&self) -> (Vec3, f32) {
303        match self {
304            Self::Point(point) => (point.position, point.radius),
305            Self::Spot(spot) => (spot.position, spot.radius),
306            // The rectangle's own centre and reach, and deliberately not a
307            // sphere grown to hold its corners: `light_cluster.slang` culls
308            // against exactly the radius `mesh.slang`'s window goes to zero at,
309            // and a bound that disagreed with the window is the seam
310            // `RectLight::radius` exists to rule out.
311            Self::Rect(rect) => (rect.position, rect.radius),
312        }
313    }
314}
315
316/// The sun as a row: topic 44's "a light is a row, and so is the sun" — "a
317/// directional light is flagged as affecting every cluster".
318///
319/// The direction is normalised here and nowhere else, which is what lets
320/// `mesh.slang`'s `normalize` of it be the same arithmetic the single-light form
321/// performed on `FrameUniforms::light_direction` — the whole reason the goldens
322/// can be expected not to move across the conversion.
323#[must_use]
324pub fn sun_row(sun: &DirectionalLight) -> GpuLight {
325    GpuLight {
326        // No position and no radius: a directional light has neither, and the
327        // clustering pass never asks — it puts every directional row in every
328        // froxel before it looks at anything else.
329        position: [0.0; 4],
330        color: sun.color.extend(0.0).to_array(),
331        direction: sun.direction.normalize_or_zero().extend(0.0).to_array(),
332        tangent: [0.0; 4],
333        kind: light::KIND_DIRECTIONAL,
334        cos_inner: 0.0,
335        // **The sun occludes through the cascades, not through a light tile.**
336        // A directional row naming a tile would sample a spot's map with the
337        // sun's geometry, so it names none — and `mesh.slang` reaches the
338        // cascades by `kind` rather than by this field, which is why the two
339        // cannot be confused.
340        shadow_tile: light::NO_SHADOW_TILE,
341        flags: 0,
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348
349    /// The sun's row carries the same normalised direction and the same colour
350    /// the frame block used to, which is the whole of the conversion's contract.
351    #[test]
352    fn the_sun_s_row_is_the_frame_block_s_two_fields() {
353        let sun = DirectionalLight::default();
354        let row = sun_row(&sun);
355        assert_eq!(row.kind, light::KIND_DIRECTIONAL);
356        let normalised = sun.direction.normalize_or_zero();
357        assert_eq!(
358            [row.direction[0], row.direction[1], row.direction[2]],
359            normalised.to_array(),
360            "the row must carry the same bits the uniform block carried, or the \
361             shader's `normalize` is not the same arithmetic"
362        );
363        assert_eq!(
364            [row.color[0], row.color[1], row.color[2]],
365            sun.color.to_array()
366        );
367        assert_eq!(
368            row.position, [0.0; 4],
369            "a directional light has no position and no radius"
370        );
371    }
372
373    #[test]
374    fn a_point_light_carries_its_radius_in_the_position_s_w() {
375        let row = Light::Point(PointLight {
376            position: Vec3::new(1.0, 2.0, 3.0),
377            radius: 7.0,
378            color: Vec3::new(0.25, 0.5, 0.75),
379            fill: false,
380        })
381        .row(None);
382        assert_eq!(row.kind, light::KIND_POINT);
383        assert_eq!(row.position, [1.0, 2.0, 3.0, 7.0]);
384        assert_eq!(row.color, [0.25, 0.5, 0.75, 0.0]);
385    }
386
387    /// A caller who swapped the two angles gets a cone that is merely hard-edged
388    /// rather than one lit on the outside.
389    #[test]
390    fn a_spot_with_its_angles_the_wrong_way_round_is_widened_not_inverted() {
391        let spot = SpotLight {
392            position: Vec3::ZERO,
393            radius: 5.0,
394            color: Vec3::ONE,
395            direction: Vec3::new(0.0, -2.0, 0.0),
396            inner_angle: 0.6,
397            outer_angle: 0.2,
398            fill: false,
399        };
400        let row = Light::Spot(spot).row(None);
401        assert_eq!(row.kind, light::KIND_SPOT);
402        assert!(
403            row.cos_inner >= row.direction[3],
404            "the inner cosine must not be smaller than the outer one, or the \
405             shader divides by a negative and lights the outside of the cone: \
406             inner {} outer {}",
407            row.cos_inner,
408            row.direction[3]
409        );
410        assert_eq!(
411            [row.direction[0], row.direction[1], row.direction[2]],
412            [0.0, -1.0, 0.0],
413            "the cone axis is normalised on the way in"
414        );
415    }
416
417    #[test]
418    fn a_spot_the_right_way_round_keeps_both_of_its_angles() {
419        let row = Light::Spot(SpotLight {
420            position: Vec3::ZERO,
421            radius: 5.0,
422            color: Vec3::ONE,
423            direction: -Vec3::Y,
424            inner_angle: 0.2,
425            outer_angle: 0.6,
426            fill: false,
427        })
428        .row(None);
429        assert!((row.cos_inner - 0.2_f32.cos()).abs() < 1e-6);
430        assert!((row.direction[3] - 0.6_f32.cos()).abs() < 1e-6);
431    }
432
433    /// **Every kind's row carries the fill bit**, which is the half of the flag
434    /// `mesh.slang` enforces — it drops the specular lobe on `FLAG_FILL` and
435    /// asks nothing about the kind.
436    ///
437    /// Each light is written twice, filled and not, so a row that set the bit
438    /// unconditionally fails here rather than reading as a light that is always
439    /// matte.
440    #[test]
441    fn a_fill_light_of_any_kind_carries_the_flag_into_its_row() {
442        let point = PointLight {
443            position: Vec3::ZERO,
444            radius: 5.0,
445            color: Vec3::ONE,
446            fill: false,
447        };
448        let spot = SpotLight {
449            position: Vec3::ZERO,
450            radius: 5.0,
451            color: Vec3::ONE,
452            direction: -Vec3::Y,
453            inner_angle: 0.2,
454            outer_angle: 0.6,
455            fill: false,
456        };
457        let rect = RectLight {
458            position: Vec3::ZERO,
459            radius: 5.0,
460            color: Vec3::ONE,
461            direction: -Vec3::Y,
462            tangent: Vec3::X,
463            half_width: 0.5,
464            half_height: 0.25,
465            fill: false,
466        };
467        for (kind, light) in [
468            ("point", Light::Point(point)),
469            ("spot", Light::Spot(spot)),
470            ("rect", Light::Rect(rect)),
471        ] {
472            assert_eq!(
473                light.row(None).flags,
474                0,
475                "an ordinary {kind} light's row must carry no flags"
476            );
477            let filled = match light {
478                Light::Point(point) => Light::Point(PointLight {
479                    fill: true,
480                    ..point
481                }),
482                Light::Spot(spot) => Light::Spot(SpotLight { fill: true, ..spot }),
483                Light::Rect(rect) => Light::Rect(RectLight { fill: true, ..rect }),
484            };
485            assert!(filled.is_fill(), "a filled {kind} light must answer yes");
486            assert_eq!(
487                filled.row(None).flags,
488                light::FLAG_FILL,
489                "a fill {kind} light's row must carry the bit `mesh.slang` drops \
490                 the specular on"
491            );
492        }
493    }
494}