euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
use super::*;

/// Bilinear cubemap lookup for a single `CubeMapMip3D`.
impl CubeMapMip3D {
    /// Samples this 6-face cubemap mip along `direction` using per-face bilinear interpolation.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Lookup direction vector.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Linear HDR RGB radiance sample.
    #[must_use]
    pub fn sample(&self, direction: Vec3) -> Vec3 {
        let dim: usize = self.get_face_size().max(1) as usize;
        let texels: &[[f32; 3]] = self.get_texels().as_slice();
        if texels.len() < PROBE_CUBEMAP_FACES * dim * dim {
            return Vec3::zero();
        }
        let (face, u, v): (usize, f32, f32) = dir_to_cubemap_face_uv(direction);
        let fx: f32 = (u * (dim as f32) - 0.5).clamp(0.0, (dim - 1) as f32);
        let fy: f32 = (v * (dim as f32) - 0.5).clamp(0.0, (dim - 1) as f32);
        let x0: usize = fx.floor() as usize;
        let y0: usize = fy.floor() as usize;
        let x1: usize = (x0 + 1).min(dim - 1);
        let y1: usize = (y0 + 1).min(dim - 1);
        let tx: f32 = fx - (x0 as f32);
        let ty: f32 = fy - (y0 as f32);
        let face_offset: usize = face * dim * dim;
        let c00: [f32; 3] = texels[face_offset + y0 * dim + x0];
        let c10: [f32; 3] = texels[face_offset + y0 * dim + x1];
        let c01: [f32; 3] = texels[face_offset + y1 * dim + x0];
        let c11: [f32; 3] = texels[face_offset + y1 * dim + x1];
        let top: Vec3 = Vec3::from_array(c00).lerp(Vec3::from_array(c10), tx);
        let bot: Vec3 = Vec3::from_array(c01).lerp(Vec3::from_array(c11), tx);
        top.lerp(bot, ty)
    }
}

/// Baking, box-parallax correction, smooth blend-distance falloff, and trilinear roughness-mip sampling for `ReflectionProbe3D`.
impl ReflectionProbe3D {
    /// Bakes a 6-face GGX-prefiltered `ReflectionProbe3D` from any directional environment radiance closure.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Probe world-space capture center.
    /// - `AxisAlignedBox3D` - Local box volume for influence and parallax correction.
    /// - `f32` - Smooth blend fade margin in meters (`>= 0.01`).
    /// - `u32` - Base `mip 0` cubemap face resolution (clamped `>= 4`).
    /// - `usize` - Number of roughness mip levels (clamped `1..=6`).
    /// - `F` - Directional radiance callback mapping unit direction to linear HDR RGB.
    ///
    /// # Returns
    ///
    /// - `Self` - Prefiltered local reflection probe.
    #[must_use]
    pub fn bake_from_sampler<F>(
        position: Vec3,
        bounds: AxisAlignedBox3D,
        blend_distance: f32,
        face_size: u32,
        mip_count: usize,
        sampler: F,
    ) -> Self
    where
        F: Fn(Vec3) -> Vec3,
    {
        let base_dim: u32 = face_size.max(4);
        let mips_n: usize = mip_count.clamp(1, 6);
        let mut mip_levels: Vec<CubeMapMip3D> = Vec::with_capacity(mips_n);
        for mip in 0..mips_n {
            let dim_u32: u32 = (base_dim >> mip).max(2);
            let dim: usize = dim_u32 as usize;
            let roughness: f32 = if mips_n <= 1 {
                0.0
            } else {
                (mip as f32) / ((mips_n - 1) as f32)
            };
            let samples: u32 = if mip == 0 { 1 } else { 24 };
            let mut texels: Vec<[f32; 3]> = Vec::with_capacity(PROBE_CUBEMAP_FACES * dim * dim);
            for face in 0..PROBE_CUBEMAP_FACES {
                for row in 0..dim {
                    let v: f32 = ((row as f32) + 0.5) / (dim as f32);
                    for col in 0..dim {
                        let u: f32 = ((col as f32) + 0.5) / (dim as f32);
                        let normal: Vec3 = cubemap_face_uv_to_dir(face, u, v);
                        if mip == 0 {
                            let c: Vec3 = sampler(normal);
                            texels.push([
                                c.get_x().max(0.0),
                                c.get_y().max(0.0),
                                c.get_z().max(0.0),
                            ]);
                        } else {
                            let mut sum_rgb: Vec3 = Vec3::zero();
                            let mut weight_sum: f32 = 0.0;
                            for s_idx in 0..samples {
                                let xi: [f32; 2] = hammersley_2d(s_idx, samples);
                                let half_v: Vec3 = importance_sample_ggx(xi, normal, roughness);
                                let light: Vec3 = half_v
                                    .scale(2.0 * normal.dot(half_v))
                                    .sub(normal)
                                    .normalize();
                                let n_dot_l: f32 = normal.dot(light).max(0.0);
                                if n_dot_l > 0.0 {
                                    sum_rgb = sum_rgb.add(sampler(light).scale(n_dot_l));
                                    weight_sum += n_dot_l;
                                }
                            }
                            let inv_w: f32 = 1.0 / weight_sum.max(1.0e-5);
                            let filtered: Vec3 = sum_rgb.scale(inv_w);
                            texels.push([
                                filtered.get_x().max(0.0),
                                filtered.get_y().max(0.0),
                                filtered.get_z().max(0.0),
                            ]);
                        }
                    }
                }
            }
            mip_levels.push(CubeMapMip3D {
                face_size: dim_u32,
                roughness,
                texels,
            });
        }
        Self {
            position,
            bounds,
            blend_distance: blend_distance.max(0.01),
            intensity: 1.0,
            base_face_size: base_dim,
            mip_levels,
        }
    }

    /// Bakes a local `ReflectionProbe3D` combining `PhysicalSky3D` and local highlights from `LightRig3D`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Probe capture center.
    /// - `AxisAlignedBox3D` - Parallax and influence box bounds.
    /// - `f32` - Smooth blend fade margin in meters.
    /// - `(u32, usize)` - `(base_face_size, mip_count)` cubemap pyramid settings.
    /// - `&PhysicalSky3D` - Atmospheric sky dome.
    /// - `Vec3` - Unit sun direction.
    /// - `&LightRig3D` - Scene light rig contributing local specular highlights.
    ///
    /// # Returns
    ///
    /// - `Self` - Prefiltered reflection probe.
    #[must_use]
    pub fn bake_from_sky_and_rig(
        position: Vec3,
        bounds: AxisAlignedBox3D,
        blend_distance: f32,
        resolution_mips: (u32, usize),
        sky: &PhysicalSky3D,
        sun_dir: Vec3,
        rig: &LightRig3D,
    ) -> Self {
        let (face_size, mip_count): (u32, usize) = resolution_mips;
        Self::bake_from_sampler(
            position,
            bounds,
            blend_distance,
            face_size,
            mip_count,
            |dir: Vec3| -> Vec3 {
                let mut rad: Vec3 = sky.evaluate_sky_radiance(dir, sun_dir);
                for pt in rig.get_point_lights().iter() {
                    let to_pt: Vec3 = pt.get_position().sub(position);
                    let dist_sq: f32 = to_pt.length_sq().max(0.04);
                    let pt_dir: Vec3 = to_pt.scale(1.0 / dist_sq.sqrt());
                    let align: f32 = dir.dot(pt_dir).max(0.0).powi(12);
                    let atten: f32 = pt.attenuation(dist_sq);
                    rad = rad.add(pt.get_color().scale(pt.get_intensity() * atten * align));
                }
                rad
            },
        )
    }

    /// Applies Lagarde box-parallax correction to reflection vector `reflect_dir` originating at `world_pos`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space shading point.
    /// - `Vec3` - World-space reflection direction vector.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Parallax-corrected unit cubemap lookup direction anchored at `self.position`.
    #[must_use]
    pub fn parallax_correct_direction(&self, world_pos: Vec3, reflect_dir: Vec3) -> Vec3 {
        let dir: Vec3 = reflect_dir.normalize();
        let mn: Vec3 = self.get_bounds().get_min();
        let mx: Vec3 = self.get_bounds().get_max();
        let rx: f32 = if dir.get_x().abs() > 1.0e-6 {
            dir.get_x()
        } else {
            1.0e-6
        };
        let ry: f32 = if dir.get_y().abs() > 1.0e-6 {
            dir.get_y()
        } else {
            1.0e-6
        };
        let rz: f32 = if dir.get_z().abs() > 1.0e-6 {
            dir.get_z()
        } else {
            1.0e-6
        };
        let t0x: f32 = (mn.get_x() - world_pos.get_x()) / rx;
        let t1x: f32 = (mx.get_x() - world_pos.get_x()) / rx;
        let t0y: f32 = (mn.get_y() - world_pos.get_y()) / ry;
        let t1y: f32 = (mx.get_y() - world_pos.get_y()) / ry;
        let t0z: f32 = (mn.get_z() - world_pos.get_z()) / rz;
        let t1z: f32 = (mx.get_z() - world_pos.get_z()) / rz;
        let far_x: f32 = t0x.max(t1x);
        let far_y: f32 = t0y.max(t1y);
        let far_z: f32 = t0z.max(t1z);
        let t_hit: f32 = far_x.min(far_y).min(far_z).max(0.0);
        let hit_pos: Vec3 = world_pos.add(dir.scale(t_hit));
        let corrected: Vec3 = hit_pos.sub(self.get_position());
        if corrected.length_sq() > 1.0e-8 {
            corrected.normalize()
        } else {
            dir
        }
    }

    /// Evaluates the smooth Hermite box-influence blend weight in `[0.0, 1.0]` at `world_pos`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space shading point.
    ///
    /// # Returns
    ///
    /// - `f32` - Smooth influence weight (`1.0` inside inner core, `0.0` outside box bounds).
    #[must_use]
    pub fn blend_weight(&self, world_pos: Vec3) -> f32 {
        let mn: Vec3 = self.get_bounds().get_min();
        let mx: Vec3 = self.get_bounds().get_max();
        let dx: f32 = (world_pos.get_x() - mn.get_x()).min(mx.get_x() - world_pos.get_x());
        let dy: f32 = (world_pos.get_y() - mn.get_y()).min(mx.get_y() - world_pos.get_y());
        let dz: f32 = (world_pos.get_z() - mn.get_z()).min(mx.get_z() - world_pos.get_z());
        let min_dist: f32 = dx.min(dy).min(dz);
        if min_dist <= 0.0 {
            return 0.0;
        }
        let margin: f32 = self.get_blend_distance().max(1.0e-4);
        let t: f32 = (min_dist / margin).clamp(0.0, 1.0);
        t * t * (3.0 - 2.0 * t)
    }

    /// Samples parallax-corrected trilinearly filtered specular radiance and influence weight `(radiance, weight)`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space shading position.
    /// - `Vec3` - World-space reflection vector.
    /// - `f32` - Surface perceptual roughness in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `(Vec3, f32)` - `(prefiltered_specular_rgb, blend_weight)` tuple.
    #[must_use]
    pub fn sample_specular(
        &self,
        world_pos: Vec3,
        reflect_dir: Vec3,
        roughness: f32,
    ) -> (Vec3, f32) {
        let weight: f32 = self.blend_weight(world_pos);
        let mips: &[CubeMapMip3D] = self.get_mip_levels().as_slice();
        if weight <= 0.0 || mips.is_empty() {
            return (Vec3::zero(), 0.0);
        }
        let lookup_dir: Vec3 = self.parallax_correct_direction(world_pos, reflect_dir);
        let max_mip: f32 = (mips.len() - 1) as f32;
        let lod: f32 = roughness.clamp(0.0, 1.0) * max_mip;
        let m0: usize = lod.floor() as usize;
        let m1: usize = (m0 + 1).min(mips.len() - 1);
        let frac: f32 = lod - (m0 as f32);
        let c0: Vec3 = mips[m0].sample(lookup_dir);
        let c1: Vec3 = if m0 == m1 {
            c0
        } else {
            mips[m1].sample(lookup_dir)
        };
        let rad: Vec3 = c0.lerp(c1, frac).scale(self.get_intensity().max(0.0));
        (rad, weight)
    }
}

/// Evaluation and linear interpolation methods for `Sh9Probe3D`.
impl Sh9Probe3D {
    /// Returns an all-zero L2 Spherical Harmonics probe.
    ///
    /// # Returns
    ///
    /// - `Self` - Zeroed SH9 probe.
    #[must_use]
    pub const fn zero() -> Self {
        Self {
            coefficients: [[0.0; 3]; SH9_BAND_COUNT],
        }
    }

    /// Evaluates diffuse HDR RGB irradiance along surface `normal` using L2 Spherical Harmonics reconstruction.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space surface normal.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Clamped non-negative finite diffuse irradiance RGB.
    #[must_use]
    pub fn evaluate_irradiance(&self, normal: Vec3) -> Vec3 {
        let basis: [f32; 9] = eval_sh_l2_basis(normal.normalize());
        let coeffs: [[f32; 3]; SH9_BAND_COUNT] = self.get_coefficients();
        let mut r: f32 = 0.0;
        let mut g: f32 = 0.0;
        let mut b: f32 = 0.0;
        for band in 0..SH9_BAND_COUNT {
            let w: f32 = basis[band];
            r += coeffs[band][0] * w;
            g += coeffs[band][1] * w;
            b += coeffs[band][2] * w;
        }
        Vec3::new(
            if r.is_finite() { r.max(0.0) } else { 0.0 },
            if g.is_finite() { g.max(0.0) } else { 0.0 },
            if b.is_finite() { b.max(0.0) } else { 0.0 },
        )
    }

    /// Linearly blends all 9 RGB SH bands between `self` and `other` by factor `t`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Target SH9 probe.
    /// - `f32` - Blend factor in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Interpolated SH9 probe.
    #[must_use]
    pub fn lerp(self, other: Self, t: f32) -> Self {
        let k: f32 = t.clamp(0.0, 1.0);
        let a: [[f32; 3]; SH9_BAND_COUNT] = self.get_coefficients();
        let b: [[f32; 3]; SH9_BAND_COUNT] = other.get_coefficients();
        let mut out: [[f32; 3]; SH9_BAND_COUNT] = [[0.0; 3]; SH9_BAND_COUNT];
        for band in 0..SH9_BAND_COUNT {
            out[band][0] = a[band][0] + (b[band][0] - a[band][0]) * k;
            out[band][1] = a[band][1] + (b[band][1] - a[band][1]) * k;
            out[band][2] = a[band][2] + (b[band][2] - a[band][2]) * k;
        }
        Self::new(out)
    }
}

/// 3D regular lattice management, SH9 probe baking, and trilinear normal-biased sampling for `LightProbeGrid3D`.
impl LightProbeGrid3D {
    /// Creates a pre-allocated regular 3D `LightProbeGrid3D` spanning `bounds` with dimensions `dims = [nx, ny, nz]`.
    ///
    /// # Arguments
    ///
    /// - `AxisAlignedBox3D` - World-space probe volume bounds.
    /// - `[usize; 3]` - Grid resolution `[nx, ny, nz]` (each clamped `>= 1`).
    /// - `f32` - Surface normal bias offset in meters (`>= 0.0`).
    ///
    /// # Returns
    ///
    /// - `Self` - Zero-initialized light probe grid.
    #[must_use]
    pub fn new(bounds: AxisAlignedBox3D, dims: [usize; 3], normal_bias: f32) -> Self {
        let nx: usize = dims[0].max(1);
        let ny: usize = dims[1].max(1);
        let nz: usize = dims[2].max(1);
        Self {
            bounds,
            dims: [nx, ny, nz],
            normal_bias: if normal_bias.is_finite() {
                normal_bias.max(0.0)
            } else {
                0.0
            },
            probes: vec![Sh9Probe3D::zero(); nx * ny * nz],
        }
    }

    /// Computes the flat array index of probe `(ix, iy, iz)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Grid X index.
    /// - `usize` - Grid Y index.
    /// - `usize` - Grid Z index.
    ///
    /// # Returns
    ///
    /// - `usize` - Flat probe index into `self.probes`.
    #[must_use]
    pub fn probe_index(&self, ix: usize, iy: usize, iz: usize) -> usize {
        let dims: [usize; 3] = self.get_dims();
        let cx: usize = ix.min(dims[0] - 1);
        let cy: usize = iy.min(dims[1] - 1);
        let cz: usize = iz.min(dims[2] - 1);
        (cz * dims[1] + cy) * dims[0] + cx
    }

    /// Computes the world-space position of probe `(ix, iy, iz)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Grid X index.
    /// - `usize` - Grid Y index.
    /// - `usize` - Grid Z index.
    ///
    /// # Returns
    ///
    /// - `Vec3` - World-space center of the requested probe.
    #[must_use]
    pub fn probe_position(&self, ix: usize, iy: usize, iz: usize) -> Vec3 {
        let dims: [usize; 3] = self.get_dims();
        let mn: Vec3 = self.get_bounds().get_min();
        let mx: Vec3 = self.get_bounds().get_max();
        let fx: f32 = if dims[0] <= 1 {
            0.5
        } else {
            (ix.min(dims[0] - 1) as f32) / ((dims[0] - 1) as f32)
        };
        let fy: f32 = if dims[1] <= 1 {
            0.5
        } else {
            (iy.min(dims[1] - 1) as f32) / ((dims[1] - 1) as f32)
        };
        let fz: f32 = if dims[2] <= 1 {
            0.5
        } else {
            (iz.min(dims[2] - 1) as f32) / ((dims[2] - 1) as f32)
        };
        Vec3::new(
            mn.get_x() + (mx.get_x() - mn.get_x()) * fx,
            mn.get_y() + (mx.get_y() - mn.get_y()) * fy,
            mn.get_z() + (mx.get_z() - mn.get_z()) * fz,
        )
    }

    /// Returns the stored `Sh9Probe3D` at lattice index `(ix, iy, iz)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Grid X index.
    /// - `usize` - Grid Y index.
    /// - `usize` - Grid Z index.
    ///
    /// # Returns
    ///
    /// - `Sh9Probe3D` - Stored L2 SH probe.
    #[must_use]
    pub fn probe_at(&self, ix: usize, iy: usize, iz: usize) -> Sh9Probe3D {
        let idx: usize = self.probe_index(ix, iy, iz);
        self.get_probes()[idx]
    }

    /// Overwrites the stored `Sh9Probe3D` at lattice index `(ix, iy, iz)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Grid X index.
    /// - `usize` - Grid Y index.
    /// - `usize` - Grid Z index.
    /// - `Sh9Probe3D` - New SH9 probe coefficients.
    pub fn set_probe_at(&mut self, ix: usize, iy: usize, iz: usize, probe: Sh9Probe3D) {
        let idx: usize = self.probe_index(ix, iy, iz);
        self.get_mut_probes()[idx] = probe;
    }

    /// Automatically bakes every probe in the 3D grid from `LightRig3D` and `PhysicalSky3D` into L2 Spherical Harmonics.
    ///
    /// # Arguments
    ///
    /// - `&LightRig3D` - Scene lighting rig (directional, point, spot, and area lights).
    /// - `&PhysicalSky3D` - Physical atmospheric sky dome.
    /// - `Vec3` - Unit sun direction for sky evaluation.
    /// - `u32` - Sky-dome Hammersley sphere sample count (`0` uses default `128`).
    pub fn bake_from_rig_and_sky(
        &mut self,
        rig: &LightRig3D,
        sky: &PhysicalSky3D,
        sun_dir: Vec3,
        sky_samples: u32,
    ) {
        let dims: [usize; 3] = self.get_dims();
        let samples: u32 = if sky_samples == 0 {
            PROBE_SH_DEFAULT_SKY_SAMPLES
        } else {
            sky_samples.max(16)
        };
        let mut sky_sh: [[f32; 3]; SH9_BAND_COUNT] = [[0.0; 3]; SH9_BAND_COUNT];
        let sphere_w: f32 = (4.0 * PI) / (samples as f32);
        for idx in 0..samples {
            let xi: [f32; 2] = hammersley_2d(idx, samples);
            let z: f32 = 1.0 - 2.0 * xi[1];
            let r_xy: f32 = (1.0 - z * z).max(0.0).sqrt();
            let phi: f32 = TAU * xi[0];
            let dir: Vec3 = Vec3::new(r_xy * phi.cos(), z, r_xy * phi.sin()).normalize();
            let rad: Vec3 = sky.evaluate_sky_radiance(dir, sun_dir);
            accumulate_sh9_directional(&mut sky_sh, dir, rad.scale(sphere_w / PI));
        }
        for dir_light in rig.get_directional_lights().iter() {
            let illum: f32 = dir_light.get_illuminance();
            if illum > 1.0e-6 {
                accumulate_sh9_directional(
                    &mut sky_sh,
                    dir_light.get_direction(),
                    dir_light.get_color().scale(illum),
                );
            }
        }
        for iz in 0..dims[2] {
            for iy in 0..dims[1] {
                for ix in 0..dims[0] {
                    let pos: Vec3 = self.probe_position(ix, iy, iz);
                    let mut coeffs: [[f32; 3]; SH9_BAND_COUNT] = sky_sh;
                    for pt in rig.get_point_lights().iter() {
                        let to_pt: Vec3 = pt.get_position().sub(pos);
                        let dist_sq: f32 = to_pt.length_sq();
                        let atten: f32 = pt.attenuation(dist_sq);
                        if atten > 1.0e-6 {
                            let dir: Vec3 = if dist_sq > 1.0e-8 {
                                to_pt.scale(1.0 / dist_sq.sqrt())
                            } else {
                                Vec3::new(0.0, 1.0, 0.0)
                            };
                            accumulate_sh9_directional(
                                &mut coeffs,
                                dir,
                                pt.get_color().scale(pt.get_intensity() * atten),
                            );
                        }
                    }
                    for spot in rig.get_spot_lights().iter() {
                        let to_spot: Vec3 = spot.get_position().sub(pos);
                        let dist_sq: f32 = to_spot.length_sq();
                        let atten: f32 = lagarde_attenuation(
                            dist_sq,
                            spot.get_source_radius(),
                            spot.get_range(),
                        );
                        let mask: f32 = spot.evaluate_cone_and_cookie(pos);
                        if atten * mask > 1.0e-6 {
                            let dir: Vec3 = if dist_sq > 1.0e-8 {
                                to_spot.scale(1.0 / dist_sq.sqrt())
                            } else {
                                Vec3::new(0.0, 1.0, 0.0)
                            };
                            accumulate_sh9_directional(
                                &mut coeffs,
                                dir,
                                spot.get_color().scale(spot.get_intensity() * atten * mask),
                            );
                        }
                    }
                    for area in rig.get_area_lights().iter() {
                        let to_area: Vec3 = area.get_position().sub(pos);
                        let dist_sq: f32 = to_area.length_sq();
                        let atten: f32 = lagarde_attenuation(
                            dist_sq,
                            (area.get_width() * area.get_height() / PI).sqrt().max(0.05),
                            area.get_range(),
                        );
                        if atten > 1.0e-6 {
                            let dir: Vec3 = if dist_sq > 1.0e-8 {
                                to_area.scale(1.0 / dist_sq.sqrt())
                            } else {
                                Vec3::new(0.0, 1.0, 0.0)
                            };
                            let facing: f32 = if area.get_two_sided() {
                                dir.dot(area.get_direction()).abs().max(0.25)
                            } else {
                                (-dir.dot(area.get_direction())).max(0.0)
                            };
                            let solid: f32 =
                                (area.get_width() * area.get_height() * facing * atten).min(PI);
                            if solid > 1.0e-6 {
                                accumulate_sh9_directional(
                                    &mut coeffs,
                                    dir,
                                    area.get_color().scale(area.get_intensity() * solid / PI),
                                );
                            }
                        }
                    }
                    self.set_probe_at(ix, iy, iz, Sh9Probe3D::new(coeffs));
                }
            }
        }
    }

    /// Trilinearly interpolates the 8 surrounding L2 SH9 probes with normal bias and evaluates diffuse irradiance along `normal`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space shading point.
    /// - `Vec3` - World-space surface normal.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Trilinearly interpolated linear HDR diffuse irradiance RGB.
    #[must_use]
    pub fn sample_irradiance(&self, world_pos: Vec3, normal: Vec3) -> Vec3 {
        let unit_n: Vec3 = normal.normalize();
        let query: Vec3 = world_pos.add(unit_n.scale(self.get_normal_bias()));
        let dims: [usize; 3] = self.get_dims();
        let mn: Vec3 = self.get_bounds().get_min();
        let mx: Vec3 = self.get_bounds().get_max();
        let span_x: f32 = (mx.get_x() - mn.get_x()).max(1.0e-5);
        let span_y: f32 = (mx.get_y() - mn.get_y()).max(1.0e-5);
        let span_z: f32 = (mx.get_z() - mn.get_z()).max(1.0e-5);
        let ux: f32 = ((query.get_x() - mn.get_x()) / span_x).clamp(0.0, 1.0);
        let uy: f32 = ((query.get_y() - mn.get_y()) / span_y).clamp(0.0, 1.0);
        let uz: f32 = ((query.get_z() - mn.get_z()) / span_z).clamp(0.0, 1.0);
        let fx: f32 = ux * ((dims[0] - 1) as f32);
        let fy: f32 = uy * ((dims[1] - 1) as f32);
        let fz: f32 = uz * ((dims[2] - 1) as f32);
        let x0: usize = fx.floor() as usize;
        let y0: usize = fy.floor() as usize;
        let z0: usize = fz.floor() as usize;
        let x1: usize = (x0 + 1).min(dims[0] - 1);
        let y1: usize = (y0 + 1).min(dims[1] - 1);
        let z1: usize = (z0 + 1).min(dims[2] - 1);
        let tx: f32 = fx - (x0 as f32);
        let ty: f32 = fy - (y0 as f32);
        let tz: f32 = fz - (z0 as f32);
        let c000: Sh9Probe3D = self.probe_at(x0, y0, z0);
        let c100: Sh9Probe3D = self.probe_at(x1, y0, z0);
        let c010: Sh9Probe3D = self.probe_at(x0, y1, z0);
        let c110: Sh9Probe3D = self.probe_at(x1, y1, z0);
        let c001: Sh9Probe3D = self.probe_at(x0, y0, z1);
        let c101: Sh9Probe3D = self.probe_at(x1, y0, z1);
        let c011: Sh9Probe3D = self.probe_at(x0, y1, z1);
        let c111: Sh9Probe3D = self.probe_at(x1, y1, z1);
        let c00: Sh9Probe3D = c000.lerp(c100, tx);
        let c10: Sh9Probe3D = c010.lerp(c110, tx);
        let c01: Sh9Probe3D = c001.lerp(c101, tx);
        let c11: Sh9Probe3D = c011.lerp(c111, tx);
        let c0: Sh9Probe3D = c00.lerp(c10, ty);
        let c1: Sh9Probe3D = c01.lerp(c11, ty);
        let blended: Sh9Probe3D = c0.lerp(c1, tz);
        blended.evaluate_irradiance(unit_n)
    }
}