euv-core 0.56.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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
use super::*;

/// Default empty `CsmCascadeSlice3D`.
impl Default for CsmCascadeSlice3D {
    /// Creates an identity placeholder `CsmCascadeSlice3D`.
    ///
    /// # Returns
    ///
    /// - `Self` - Default cascade slice.
    fn default() -> Self {
        Self {
            near_depth: 0.25,
            far_depth: 25.0,
            world_center: Vec3::zero(),
            snapped_center: Vec3::zero(),
            half_extent: 16.0,
            texel_size: 0.031_25,
            light_view: Mat4::identity(),
            light_proj: Mat4::identity(),
            light_view_proj: Mat4::identity(),
        }
    }
}

/// Practical-split Cascaded Shadow Map calculation and cascade selection for `CsmCascadeSplits`.
impl CsmCascadeSplits {
    /// Computes Practical-Split Cascaded Shadow Map splits with rotation-invariant bounding spheres and light-space texel snapping.
    ///
    /// # Arguments
    ///
    /// - `&Camera3D` - Active 3D perspective camera.
    /// - `f32` - Viewport width-to-height aspect ratio.
    /// - `Vec3` - Unit direction vector pointing toward the directional light.
    /// - `usize` - Requested cascade count (clamped to `1..=CSM_MAX_CASCADES`).
    /// - `f32` - Practical split lambda in `[0.0, 1.0]` (`0.0` uniform, `1.0` logarithmic).
    /// - `f32` - Maximum world-space shadow coverage distance in meters.
    /// - `u32` - Square shadow map edge resolution in texels.
    ///
    /// # Returns
    ///
    /// - `Self` - Texel-snapped directional shadow cascades.
    #[must_use]
    pub fn compute(
        camera: &Camera3D,
        aspect: f32,
        light_dir: Vec3,
        cascade_count: usize,
        lambda: f32,
        max_distance: f32,
        resolution: u32,
    ) -> Self {
        let count: usize = cascade_count.clamp(1, CSM_MAX_CASCADES);
        let safe_lambda: f32 = if lambda.is_finite() {
            lambda.clamp(0.0, 1.0)
        } else {
            0.65
        };
        let near_p: f32 = camera.get_near().max(0.05);
        let far_p: f32 = camera
            .get_far()
            .min(max_distance.max(near_p + 1.0))
            .max(near_p + 1.0);
        let res: u32 = resolution.max(32);
        let safe_aspect: f32 = aspect.max(0.1);
        let eff_fov: f32 = Camera3D::effective_vertical_fov_rad(camera.get_fov_deg(), safe_aspect);
        let tan_half_y: f32 = (eff_fov * 0.5).tan().max(0.05);
        let tan_half_x: f32 = tan_half_y * safe_aspect;
        let cam_pos: Vec3 = camera.get_position();
        let cam_fwd: Vec3 = camera.forward();
        let cam_right: Vec3 = camera.right();
        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
        let dir_to_light: Vec3 = light_dir.normalize();
        let (l_right, l_up, _): (Vec3, Vec3, Vec3) =
            light_orthonormal_basis(dir_to_light, Vec3::new(0.0, 1.0, 0.0));
        let mut splits: [f32; CSM_MAX_CASCADES + 1] = [near_p; CSM_MAX_CASCADES + 1];
        let depth_ratio: f32 = far_p / near_p;
        let depth_span: f32 = far_p - near_p;
        for (idx, slot) in splits.iter_mut().enumerate().take(count + 1).skip(1) {
            let frac: f32 = (idx as f32) / (count as f32);
            let log_d: f32 = near_p * depth_ratio.powf(frac);
            let uni_d: f32 = near_p + depth_span * frac;
            *slot = log_d * safe_lambda + uni_d * (1.0 - safe_lambda);
        }
        let mut slices: [CsmCascadeSlice3D; CSM_MAX_CASCADES] =
            [CsmCascadeSlice3D::default(); CSM_MAX_CASCADES];
        for idx in 0..count {
            let z0: f32 = splits[idx];
            let z1: f32 = splits[idx + 1];
            let h0: f32 = z0 * tan_half_y;
            let w0: f32 = z0 * tan_half_x;
            let h1: f32 = z1 * tan_half_y;
            let w1: f32 = z1 * tan_half_x;
            let c0: Vec3 = cam_pos.add(cam_fwd.scale(z0));
            let c1: Vec3 = cam_pos.add(cam_fwd.scale(z1));
            let corners: [Vec3; 8] = [
                c0.sub(cam_right.scale(w0)).sub(cam_up.scale(h0)),
                c0.add(cam_right.scale(w0)).sub(cam_up.scale(h0)),
                c0.add(cam_right.scale(w0)).add(cam_up.scale(h0)),
                c0.sub(cam_right.scale(w0)).add(cam_up.scale(h0)),
                c1.sub(cam_right.scale(w1)).sub(cam_up.scale(h1)),
                c1.add(cam_right.scale(w1)).sub(cam_up.scale(h1)),
                c1.add(cam_right.scale(w1)).add(cam_up.scale(h1)),
                c1.sub(cam_right.scale(w1)).add(cam_up.scale(h1)),
            ];
            let mut center_sum: Vec3 = Vec3::zero();
            for corner in corners.iter() {
                center_sum = center_sum.add(*corner);
            }
            let world_center: Vec3 = center_sum.scale(0.125);
            let mut radius_sq: f32 = 0.0;
            for corner in corners.iter() {
                radius_sq = radius_sq.max(corner.sub(world_center).length_sq());
            }
            let half_extent: f32 = radius_sq.sqrt().max(1.0);
            let texel_size: f32 = (2.0 * half_extent) / (res as f32);
            let proj_x: f32 = world_center.dot(l_right);
            let proj_y: f32 = world_center.dot(l_up);
            let proj_z: f32 = world_center.dot(dir_to_light);
            let snapped_x: f32 = (proj_x / texel_size).floor() * texel_size;
            let snapped_y: f32 = (proj_y / texel_size).floor() * texel_size;
            let snapped_center: Vec3 = l_right
                .scale(snapped_x)
                .add(l_up.scale(snapped_y))
                .add(dir_to_light.scale(proj_z));
            let depth_pad: f32 = half_extent * 3.0;
            let light_eye: Vec3 = snapped_center.add(dir_to_light.scale(depth_pad));
            let light_view: Mat4 = Mat4::look_at(light_eye, snapped_center, l_up);
            let light_proj: Mat4 = build_ortho_matrix(
                -half_extent,
                half_extent,
                -half_extent,
                half_extent,
                0.1,
                depth_pad * 2.0,
            );
            let light_view_proj: Mat4 = light_proj.mul(light_view);
            slices[idx] = CsmCascadeSlice3D {
                near_depth: z0,
                far_depth: z1,
                world_center,
                snapped_center,
                half_extent,
                texel_size,
                light_view,
                light_proj,
                light_view_proj,
            };
        }
        Self {
            cascade_count: count,
            lambda: safe_lambda,
            near_plane: near_p,
            far_plane: far_p,
            shadow_map_resolution: res,
            slices,
        }
    }

    /// Selects the active cascade index covering positive camera-space `view_depth`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Positive distance along camera forward axis in meters.
    ///
    /// # Returns
    ///
    /// - `usize` - Active cascade slice index in `0..cascade_count`.
    #[must_use]
    pub fn select_cascade(&self, view_depth: f32) -> usize {
        let count: usize = self.get_cascade_count().clamp(1, CSM_MAX_CASCADES);
        let slices: [CsmCascadeSlice3D; CSM_MAX_CASCADES] = self.get_slices();
        for (idx, slice) in slices.iter().take(count).enumerate() {
            if view_depth <= slice.get_far_depth() {
                return idx;
            }
        }
        count - 1
    }
}

/// Constructors, CSM computation, and direct shading helpers for `RigDirectionalLight3D`.
impl RigDirectionalLight3D {
    /// Creates a physical directional light pointing toward `direction` with linear `color` and `illuminance`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Direction vector pointing toward the emitter.
    /// - `Vec3` - Linear HDR RGB tint.
    /// - `f32` - Illuminance multiplier.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured directional light.
    #[must_use]
    pub fn new(direction: Vec3, color: Vec3, illuminance: f32) -> Self {
        Self {
            direction: direction.normalize(),
            color: Vec3::new(
                color.get_x().max(0.0),
                color.get_y().max(0.0),
                color.get_z().max(0.0),
            ),
            illuminance: if illuminance.is_finite() {
                illuminance.max(0.0)
            } else {
                0.0
            },
            angular_radius_rad: 0.004_65,
            cast_shadows: true,
            shadow_bias: 0.002,
            cascade_count: CSM_MAX_CASCADES,
            csm_lambda: 0.65,
            max_shadow_distance: 180.0,
        }
    }

    /// Creates a physical directional light tinted via correlated color temperature in Kelvin.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Direction vector pointing toward the emitter.
    /// - `f32` - Color temperature in Kelvin.
    /// - `f32` - Illuminance multiplier.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured Kelvin-tinted directional light.
    #[must_use]
    pub fn from_kelvin(direction: Vec3, kelvin: f32, illuminance: f32) -> Self {
        Self::new(direction, kelvin_to_linear_rgb(kelvin), illuminance)
    }

    /// Computes texel-snapped Cascaded Shadow Map splits for this directional light.
    ///
    /// # Arguments
    ///
    /// - `&Camera3D` - Active 3D perspective camera.
    /// - `f32` - Viewport aspect ratio.
    /// - `u32` - Shadow map edge resolution in texels.
    ///
    /// # Returns
    ///
    /// - `CsmCascadeSplits` - Computed cascade splits and view-projection matrices.
    #[must_use]
    pub fn compute_csm_splits(
        &self,
        camera: &Camera3D,
        aspect: f32,
        shadow_map_res: u32,
    ) -> CsmCascadeSplits {
        CsmCascadeSplits::compute(
            camera,
            aspect,
            self.get_direction(),
            self.get_cascade_count(),
            self.get_csm_lambda(),
            self.get_max_shadow_distance(),
            shadow_map_res,
        )
    }

    /// Converts this rig directional light into `euv-core`'s world `DirectionalLight3D` descriptor.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Linear sky zenith color.
    /// - `Vec3` - Linear sky horizon color.
    /// - `f32` - Time of day in `[0.0, 24.0]` hours.
    ///
    /// # Returns
    ///
    /// - `DirectionalLight3D` - Compatible world directional light.
    #[must_use]
    pub fn to_world_directional(
        &self,
        sky_zenith: Vec3,
        sky_horizon: Vec3,
        time_of_day: f32,
    ) -> DirectionalLight3D {
        let mut light: DirectionalLight3D = DirectionalLight3D::default();
        light
            .set_direction(self.get_direction().normalize())
            .set_color(self.get_color().scale(self.get_illuminance()))
            .set_sky_zenith(sky_zenith)
            .set_sky_horizon(sky_horizon)
            .set_time_of_day(time_of_day.rem_euclid(24.0));
        light
    }

    /// Evaluates direct Cook-Torrance GGX shading contributed by this directional light.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Surface normal.
    /// - `Vec3` - Outgoing view direction.
    /// - `&PbrMaterial` - Surface PBR material.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Direct reflected linear HDR RGB radiance.
    #[must_use]
    pub fn evaluate_direct(&self, normal: Vec3, view_dir: Vec3, material: &PbrMaterial) -> Vec3 {
        let illum: f32 = self.get_illuminance();
        if illum <= 1.0e-6 {
            return Vec3::zero();
        }
        let brdf: Vec3 =
            evaluate_cook_torrance_brdf(normal, view_dir, self.get_direction(), material);
        brdf.mul(self.get_color().scale(illum))
    }
}

/// Constructors, attenuation, and 6-face omnidirectional cube-shadow frustums for `RigPointLight3D`.
impl RigPointLight3D {
    /// Creates a physical point light with linear `color`, `intensity`, and cutoff `range`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter center.
    /// - `Vec3` - Linear HDR RGB emission color.
    /// - `f32` - Luminous intensity multiplier.
    /// - `f32` - Maximum Lagarde attenuation range in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured point light.
    #[must_use]
    pub fn new(position: Vec3, color: Vec3, intensity: f32, range: f32) -> Self {
        Self {
            position,
            color: Vec3::new(
                color.get_x().max(0.0),
                color.get_y().max(0.0),
                color.get_z().max(0.0),
            ),
            intensity: if intensity.is_finite() {
                intensity.max(0.0)
            } else {
                0.0
            },
            source_radius: 0.08,
            range: if range.is_finite() {
                range.max(0.25)
            } else {
                10.0
            },
            cast_shadows: false,
            shadow_near: 0.1,
        }
    }

    /// Creates a physical point light tinted by blackbody color temperature in Kelvin.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter center.
    /// - `f32` - Color temperature in Kelvin.
    /// - `f32` - Luminous intensity multiplier.
    /// - `f32` - Maximum attenuation range in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured Kelvin-tinted point light.
    #[must_use]
    pub fn from_kelvin(position: Vec3, kelvin: f32, intensity: f32, range: f32) -> Self {
        Self::new(position, kelvin_to_linear_rgb(kelvin), intensity, range)
    }

    /// Sets the physical emitter source radius `r` in meters for `1 / (d^2 + r^2)` falloff.
    ///
    /// # Arguments
    ///
    /// - `f32` - Physical emitter sphere radius in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated point light.
    #[must_use]
    pub fn with_source_radius(mut self, radius: f32) -> Self {
        self.set_source_radius(radius.max(MIN_SOURCE_RADIUS));
        self
    }

    /// Enables or disables 6-face omnidirectional cube shadows for this point light.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether cube shadows are enabled.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated point light.
    #[must_use]
    pub fn with_shadows(mut self, enabled: bool) -> Self {
        self.set_cast_shadows(enabled);
        self
    }

    /// Evaluates Lagarde-windowed inverse-square attenuation at squared distance `distance_sq`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Squared distance in square meters.
    ///
    /// # Returns
    ///
    /// - `f32` - Physical attenuation scalar.
    #[must_use]
    pub fn attenuation(&self, distance_sq: f32) -> f32 {
        lagarde_attenuation(distance_sq, self.get_source_radius(), self.get_range())
    }

    /// Builds all six 90-degree omnidirectional cubemap shadow frustum descriptors (`+X, -X, +Y, -Y, +Z, -Z`).
    ///
    /// # Returns
    ///
    /// - `[CubeShadowFace3D; 6]` - Six square perspective view-projection matrices and frustums.
    #[must_use]
    pub fn cube_shadow_frustums(&self) -> [CubeShadowFace3D; 6] {
        let pos: Vec3 = self.get_position();
        let near_p: f32 = self.get_shadow_near().clamp(0.02, self.get_range() * 0.25);
        let far_p: f32 = self.get_range().max(near_p + 0.1);
        let proj: Mat4 = Mat4::perspective(FRAC_PI_2, 1.0, near_p, far_p);
        let face_axes: [(Vec3, Vec3); 6] = [
            (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, -1.0, 0.0)),
            (Vec3::new(-1.0, 0.0, 0.0), Vec3::new(0.0, -1.0, 0.0)),
            (Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0)),
            (Vec3::new(0.0, -1.0, 0.0), Vec3::new(0.0, 0.0, -1.0)),
            (Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, -1.0, 0.0)),
            (Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, -1.0, 0.0)),
        ];
        let mut faces: [CubeShadowFace3D; 6] = [CubeShadowFace3D::new(
            0,
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(0.0, -1.0, 0.0),
            Mat4::identity(),
            Frustum3D::from_view_proj(&Mat4::identity()),
        ); 6];
        for (idx, (fwd, up)) in face_axes.iter().enumerate() {
            let view: Mat4 = Mat4::look_at(pos, pos.add(*fwd), *up);
            let vp: Mat4 = proj.mul(view);
            faces[idx] =
                CubeShadowFace3D::new(idx as u8, *fwd, *up, vp, Frustum3D::from_view_proj(&vp));
        }
        faces
    }

    /// Converts this light into `euv-core`'s core `PointLight3D` descriptor.
    ///
    /// # Returns
    ///
    /// - `PointLight3D` - Compatible core point light.
    #[must_use]
    pub fn to_core_point_light(&self) -> PointLight3D {
        let mut core_pt: PointLight3D = PointLight3D::from_linear(
            self.get_position(),
            self.get_color(),
            self.get_intensity(),
            self.get_range(),
        );
        core_pt.set_cast_shadows(self.get_cast_shadows());
        core_pt
    }

    /// Evaluates direct Cook-Torrance GGX shading contributed by this point light at `world_pos`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space shading point.
    /// - `Vec3` - Surface normal.
    /// - `Vec3` - Outgoing view direction.
    /// - `&PbrMaterial` - Surface PBR material.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Direct reflected linear HDR RGB radiance.
    #[must_use]
    pub fn evaluate_direct(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        view_dir: Vec3,
        material: &PbrMaterial,
    ) -> Vec3 {
        let intensity: f32 = self.get_intensity();
        if intensity <= 1.0e-6 {
            return Vec3::zero();
        }
        let to_light: Vec3 = self.get_position().sub(world_pos);
        let dist_sq: f32 = to_light.length_sq();
        let atten: f32 = self.attenuation(dist_sq);
        if atten <= 0.0 {
            return Vec3::zero();
        }
        let light_dir: Vec3 = if dist_sq > 1.0e-8 {
            to_light.scale(1.0 / dist_sq.sqrt())
        } else {
            normal.normalize()
        };
        let brdf: Vec3 = evaluate_cook_torrance_brdf(normal, view_dir, light_dir, material);
        brdf.mul(self.get_color().scale(intensity * atten))
    }
}

/// Procedural and bilinearly sampled 2D cookie/gobo evaluation for `SpotCookieMask`.
impl SpotCookieMask {
    /// Evaluates the 2D cookie/gobo transmittance factor in `[0.0, 1.0]` at normalized beam UV coordinates.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Normalized 2D beam projection coordinate in `[0.0, 1.0]^2` (centered at `(0.5, 0.5)`).
    ///
    /// # Returns
    ///
    /// - `f32` - Transmittance mask scalar in `[0.0, 1.0]`.
    #[must_use]
    pub fn sample(&self, uv: Vec2) -> f32 {
        let u: f32 = uv.get_x();
        let v: f32 = uv.get_y();
        if !u.is_finite()
            || !v.is_finite()
            || !(0.0..=1.0).contains(&u)
            || !(0.0..=1.0).contains(&v)
        {
            return 0.0;
        }
        match self {
            Self::None => 1.0,
            Self::RadialWindow {
                panes_x,
                panes_y,
                mullion_width,
            } => {
                let cx: f32 = u * 2.0 - 1.0;
                let cy: f32 = v * 2.0 - 1.0;
                let r_sq: f32 = cx * cx + cy * cy;
                if r_sq >= 1.0 {
                    return 0.0;
                }
                let radial: f32 = (1.0 - r_sq).clamp(0.0, 1.0).sqrt();
                let px: f32 = (*panes_x).max(1) as f32;
                let py: f32 = (*panes_y).max(1) as f32;
                let half_bar: f32 = mullion_width.clamp(0.01, 0.4) * 0.5;
                let fx: f32 = (u * px).fract();
                let fy: f32 = (v * py).fract();
                let open_x: f32 = if fx < half_bar || fx > (1.0 - half_bar) {
                    0.0
                } else {
                    1.0
                };
                let open_y: f32 = if fy < half_bar || fy > (1.0 - half_bar) {
                    0.0
                } else {
                    1.0
                };
                (radial * open_x * open_y).clamp(0.0, 1.0)
            }
            Self::VenetianBlinds {
                slat_count,
                open_ratio,
                tilt_rad,
            } => {
                let cx: f32 = u - 0.5;
                let cy: f32 = v - 0.5;
                let rot_y: f32 = cx * tilt_rad.sin() + cy * tilt_rad.cos() + 0.5;
                let slats: f32 = (*slat_count).max(1) as f32;
                let phase: f32 = (rot_y * slats).rem_euclid(1.0);
                let open: f32 = open_ratio.clamp(0.05, 0.95);
                let edge: f32 = 0.04;
                if phase < open - edge {
                    1.0
                } else if phase < open + edge {
                    let t: f32 = ((open + edge - phase) / (2.0 * edge)).clamp(0.0, 1.0);
                    t * t * (3.0 - 2.0 * t)
                } else {
                    0.0
                }
            }
            Self::FoliageCanopy {
                frequency,
                density,
                seed,
            } => {
                let freq: f32 = frequency.clamp(0.5, 32.0);
                let s0: f32 = (*seed as f32) * 0.618_034;
                let px: f32 = u * freq * TAU;
                let py: f32 = v * freq * TAU;
                let wave_a: f32 = (px + s0).sin() * (py - s0 * 0.7).cos();
                let wave_b: f32 =
                    (px * 1.73 - py * 1.19 + s0 * 1.3).sin() * (py * 1.91 + px * 0.67).cos();
                let wave_c: f32 = (px * 2.83 + py * 2.41 - s0 * 2.1).cos();
                let pattern: f32 =
                    (0.5 + 0.25 * wave_a + 0.15 * wave_b + 0.1 * wave_c).clamp(0.0, 1.0);
                let cutoff: f32 = density.clamp(0.0, 0.98);
                let span: f32 = (1.0 - cutoff).max(0.05);
                let t: f32 = ((pattern - cutoff) / span).clamp(0.0, 1.0);
                t * t * (3.0 - 2.0 * t)
            }
            Self::CustomGrid {
                width,
                height,
                values,
            } => {
                let w: usize = *width as usize;
                let h: usize = *height as usize;
                if w == 0 || h == 0 || values.len() < w * h {
                    return 1.0;
                }
                let fx: f32 = (u * ((w - 1) as f32)).clamp(0.0, (w - 1) as f32);
                let fy: f32 = (v * ((h - 1) as f32)).clamp(0.0, (h - 1) as f32);
                let x0: usize = fx.floor() as usize;
                let y0: usize = fy.floor() as usize;
                let x1: usize = (x0 + 1).min(w - 1);
                let y1: usize = (y0 + 1).min(h - 1);
                let tx: f32 = fx - (x0 as f32);
                let ty: f32 = fy - (y0 as f32);
                let v00: f32 = values[y0 * w + x0].clamp(0.0, 1.0);
                let v10: f32 = values[y0 * w + x1].clamp(0.0, 1.0);
                let v01: f32 = values[y1 * w + x0].clamp(0.0, 1.0);
                let v11: f32 = values[y1 * w + x1].clamp(0.0, 1.0);
                let top: f32 = v00 + (v10 - v00) * tx;
                let bot: f32 = v01 + (v11 - v01) * tx;
                (top + (bot - top) * ty).clamp(0.0, 1.0)
            }
        }
    }
}

/// Constructors, penumbra + cookie projection, and shadow frustums for `RigSpotLight3D`.
impl RigSpotLight3D {
    /// Creates a physical spotlight with radian inner/outer cone half-angles.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter origin.
    /// - `Vec3` - Beam direction vector.
    /// - `Vec3` - Linear HDR RGB color.
    /// - `f32` - Luminous intensity multiplier.
    /// - `f32` - Maximum cutoff range in meters.
    /// - `(f32, f32)` - `(inner_angle_rad, outer_angle_rad)` cone half-angles in radians.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured spotlight.
    #[must_use]
    pub fn new(
        position: Vec3,
        direction: Vec3,
        color: Vec3,
        intensity: f32,
        range: f32,
        cone_rad: (f32, f32),
    ) -> Self {
        let inner: f32 = cone_rad.0.clamp(0.01, FRAC_PI_2 - 0.03);
        let outer: f32 = cone_rad.1.clamp(inner + 0.01, FRAC_PI_2 - 0.01);
        Self {
            position,
            direction: direction.normalize(),
            up_hint: Vec3::new(0.0, 1.0, 0.0),
            color: Vec3::new(
                color.get_x().max(0.0),
                color.get_y().max(0.0),
                color.get_z().max(0.0),
            ),
            intensity: if intensity.is_finite() {
                intensity.max(0.0)
            } else {
                0.0
            },
            source_radius: 0.08,
            range: if range.is_finite() {
                range.max(0.5)
            } else {
                16.0
            },
            inner_angle_rad: inner,
            outer_angle_rad: outer,
            cast_shadows: true,
            cookie: SpotCookieMask::None,
        }
    }

    /// Creates a physical spotlight tinted via Kelvin color temperature.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter origin.
    /// - `Vec3` - Beam direction vector.
    /// - `f32` - Color temperature in Kelvin.
    /// - `f32` - Luminous intensity multiplier.
    /// - `f32` - Maximum range in meters.
    /// - `(f32, f32)` - `(inner_angle_rad, outer_angle_rad)` cone half-angles.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured Kelvin-tinted spotlight.
    #[must_use]
    pub fn from_kelvin(
        position: Vec3,
        direction: Vec3,
        kelvin: f32,
        intensity: f32,
        range: f32,
        cone_rad: (f32, f32),
    ) -> Self {
        Self::new(
            position,
            direction,
            kelvin_to_linear_rgb(kelvin),
            intensity,
            range,
            cone_rad,
        )
    }

    /// Attaches a 2D cookie/gobo projection mask to this spotlight.
    ///
    /// # Arguments
    ///
    /// - `SpotCookieMask` - Procedural or custom-grid cookie mask.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated spotlight.
    #[must_use]
    pub fn with_cookie(mut self, cookie: SpotCookieMask) -> Self {
        self.set_cookie(cookie);
        self
    }

    /// Computes a tight bounding sphere enclosing this spotlight's cone for Forward+ clustering.
    ///
    /// # Returns
    ///
    /// - `(Vec3, f32)` - `(center, radius)` bounding sphere in world space.
    #[must_use]
    pub fn bounding_sphere(&self) -> (Vec3, f32) {
        let range: f32 = self.get_range();
        let outer: f32 = self.get_outer_angle_rad();
        let cos_o: f32 = outer.cos();
        let dir: Vec3 = self.get_direction().normalize();
        if outer > FRAC_PI_2 * 0.5 {
            let center: Vec3 = self.get_position().add(dir.scale(range * cos_o));
            let radius: f32 = range * outer.sin();
            (center, radius)
        } else {
            let radius: f32 = range / (2.0 * cos_o.max(0.05));
            let center: Vec3 = self.get_position().add(dir.scale(radius));
            (center, radius)
        }
    }

    /// Evaluates smoothstep cone penumbra multiplied by the projected 2D cookie mask at `world_pos`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space shading point.
    ///
    /// # Returns
    ///
    /// - `f32` - Combined cone penumbra and cookie transmittance in `[0.0, 1.0]`.
    #[must_use]
    pub fn evaluate_cone_and_cookie(&self, world_pos: Vec3) -> f32 {
        let from_light: Vec3 = world_pos.sub(self.get_position());
        let dist: f32 = from_light.length();
        if dist <= 1.0e-6 {
            return 1.0;
        }
        let beam_dir: Vec3 = self.get_direction().normalize();
        let to_point: Vec3 = from_light.scale(1.0 / dist);
        let cos_angle: f32 = to_point.dot(beam_dir);
        let outer_cos: f32 = self.get_outer_angle_rad().cos();
        if cos_angle <= outer_cos {
            return 0.0;
        }
        let inner_cos: f32 = self.get_inner_angle_rad().cos();
        let penumbra: f32 = if cos_angle >= inner_cos {
            1.0
        } else {
            let t: f32 =
                ((cos_angle - outer_cos) / (inner_cos - outer_cos).max(1.0e-5)).clamp(0.0, 1.0);
            t * t * (3.0 - 2.0 * t)
        };
        if matches!(self.get_cookie(), SpotCookieMask::None) {
            return penumbra;
        }
        let (right, up, fwd): (Vec3, Vec3, Vec3) =
            light_orthonormal_basis(beam_dir, self.get_up_hint());
        let local_z: f32 = from_light.dot(fwd).max(1.0e-4);
        let tan_outer: f32 = self.get_outer_angle_rad().tan().max(1.0e-4);
        let proj_x: f32 = from_light.dot(right) / (local_z * tan_outer);
        let proj_y: f32 = from_light.dot(up) / (local_z * tan_outer);
        let uv: Vec2 = Vec2::new(proj_x * 0.5 + 0.5, proj_y * 0.5 + 0.5);
        penumbra * self.get_cookie().sample(uv)
    }

    /// Computes the perspective shadow view-projection matrix covering the outer spotlight cone.
    ///
    /// # Returns
    ///
    /// - `Mat4` - Perspective shadow view-projection matrix.
    #[must_use]
    pub fn shadow_view_proj(&self) -> Mat4 {
        let pos: Vec3 = self.get_position();
        let (_, up, fwd): (Vec3, Vec3, Vec3) =
            light_orthonormal_basis(self.get_direction(), self.get_up_hint());
        let fov_rad: f32 = (self.get_outer_angle_rad() * 2.0).clamp(0.05, PI - 0.05);
        let view: Mat4 = Mat4::look_at(pos, pos.add(fwd), up);
        let proj: Mat4 = Mat4::perspective(fov_rad, 1.0, 0.1, self.get_range().max(0.5));
        proj.mul(view)
    }

    /// Extracts the 6-plane culling frustum of this spotlight's shadow projection.
    ///
    /// # Returns
    ///
    /// - `Frustum3D` - Spotlight culling frustum.
    #[must_use]
    pub fn shadow_frustum(&self) -> Frustum3D {
        Frustum3D::from_view_proj(&self.shadow_view_proj())
    }

    /// Converts this spotlight into `euv-core`'s core `SpotLight3D` descriptor.
    ///
    /// # Returns
    ///
    /// - `SpotLight3D` - Compatible core spotlight.
    #[must_use]
    pub fn to_core_spot_light(&self) -> SpotLight3D {
        SpotLight3D::from_linear(
            self.get_position(),
            self.get_direction(),
            self.get_color(),
            self.get_intensity(),
            self.get_range(),
            (self.get_inner_angle_rad(), self.get_outer_angle_rad()),
        )
    }

    /// Evaluates direct Cook-Torrance GGX shading contributed by this spotlight (including cookie projection).
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space shading point.
    /// - `Vec3` - Surface normal.
    /// - `Vec3` - Outgoing view direction.
    /// - `&PbrMaterial` - Surface PBR material.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Direct reflected linear HDR RGB radiance.
    #[must_use]
    pub fn evaluate_direct(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        view_dir: Vec3,
        material: &PbrMaterial,
    ) -> Vec3 {
        let intensity: f32 = self.get_intensity();
        if intensity <= 1.0e-6 {
            return Vec3::zero();
        }
        let to_light: Vec3 = self.get_position().sub(world_pos);
        let dist_sq: f32 = to_light.length_sq();
        let atten: f32 = lagarde_attenuation(dist_sq, self.get_source_radius(), self.get_range());
        if atten <= 0.0 {
            return Vec3::zero();
        }
        let mask: f32 = self.evaluate_cone_and_cookie(world_pos);
        if mask <= 0.0 {
            return Vec3::zero();
        }
        let light_dir: Vec3 = if dist_sq > 1.0e-8 {
            to_light.scale(1.0 / dist_sq.sqrt())
        } else {
            normal.normalize()
        };
        let brdf: Vec3 = evaluate_cook_torrance_brdf(normal, view_dir, light_dir, material);
        brdf.mul(self.get_color().scale(intensity * atten * mask))
    }
}

/// Constructors, geometry helpers, and representative-point tube shading for `RigAreaLight3D`.
impl RigAreaLight3D {
    /// Creates a rectangular quad area light oriented along emitting normal `direction`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter center.
    /// - `Vec3` - Outward emitting surface normal.
    /// - `Vec3` - Linear HDR RGB radiance color.
    /// - `f32` - Luminous radiance multiplier.
    /// - `(f32, f32)` - `(width, height)` quad dimensions in meters.
    /// - `f32` - Maximum cutoff range in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured rectangular area light.
    #[must_use]
    pub fn new_rect(
        position: Vec3,
        direction: Vec3,
        color: Vec3,
        intensity: f32,
        dimensions: (f32, f32),
        range: f32,
    ) -> Self {
        let (right, up, fwd): (Vec3, Vec3, Vec3) =
            light_orthonormal_basis(direction, Vec3::new(0.0, 1.0, 0.0));
        Self {
            position,
            direction: fwd,
            right,
            up,
            color: Vec3::new(
                color.get_x().max(0.0),
                color.get_y().max(0.0),
                color.get_z().max(0.0),
            ),
            intensity: if intensity.is_finite() {
                intensity.max(0.0)
            } else {
                0.0
            },
            width: dimensions.0.max(0.04),
            height: dimensions.1.max(0.04),
            range: range.max(0.5),
            shape: RigAreaLightShape3D::Rect,
            two_sided: false,
        }
    }

    /// Creates a circular or elliptical disk area light oriented along emitting normal `direction`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space disk center.
    /// - `Vec3` - Outward emitting surface normal.
    /// - `Vec3` - Linear HDR RGB radiance color.
    /// - `f32` - Luminous radiance multiplier.
    /// - `(f32, f32)` - `(width_diameter, height_diameter)` in meters.
    /// - `f32` - Maximum cutoff range in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured disk area light.
    #[must_use]
    pub fn new_disk(
        position: Vec3,
        direction: Vec3,
        color: Vec3,
        intensity: f32,
        diameters: (f32, f32),
        range: f32,
    ) -> Self {
        let mut light: Self =
            Self::new_rect(position, direction, color, intensity, diameters, range);
        light.set_shape(RigAreaLightShape3D::Disk);
        light
    }

    /// Creates a linear capsule/tube area light spanning from `start` to `end` with cross-section `radius`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space tube start endpoint.
    /// - `Vec3` - World-space tube end endpoint.
    /// - `f32` - Tube cross-section radius in meters.
    /// - `Vec3` - Linear HDR RGB radiance color.
    /// - `f32` - Luminous radiance multiplier.
    /// - `f32` - Maximum cutoff range in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured linear tube area light.
    #[must_use]
    pub fn new_tube(
        start: Vec3,
        end: Vec3,
        radius: f32,
        color: Vec3,
        intensity: f32,
        range: f32,
    ) -> Self {
        let center: Vec3 = start.add(end).scale(0.5);
        let seg: Vec3 = end.sub(start);
        let length: f32 = seg.length().max(0.05);
        let axis: Vec3 = if seg.length_sq() > 1.0e-8 {
            seg.scale(1.0 / length)
        } else {
            Vec3::new(1.0, 0.0, 0.0)
        };
        let ref_up: Vec3 = if axis.get_y().abs() < 0.95 {
            Vec3::new(0.0, 1.0, 0.0)
        } else {
            Vec3::new(0.0, 0.0, 1.0)
        };
        let direction: Vec3 = ref_up.cross(axis).normalize();
        let up: Vec3 = direction.cross(axis).normalize();
        let safe_rad: f32 = radius.max(0.01);
        Self {
            position: center,
            direction,
            right: axis,
            up,
            color: Vec3::new(
                color.get_x().max(0.0),
                color.get_y().max(0.0),
                color.get_z().max(0.0),
            ),
            intensity: if intensity.is_finite() {
                intensity.max(0.0)
            } else {
                0.0
            },
            width: length,
            height: safe_rad * 2.0,
            range: range.max(0.5),
            shape: RigAreaLightShape3D::Tube,
            two_sided: true,
        }
    }

    /// Sets whether this area light emits from both front and back faces.
    ///
    /// # Arguments
    ///
    /// - `bool` - Two-sided emission flag.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated area light.
    #[must_use]
    pub fn with_two_sided(mut self, enabled: bool) -> Self {
        self.set_two_sided(enabled);
        self
    }

    /// Returns the four world-space quad corners wound counter-clockwise when viewed from the lit front side.
    ///
    /// # Returns
    ///
    /// - `[Vec3; 4]` - Quad corner positions in world space.
    #[must_use]
    pub fn quad_corners(&self) -> [Vec3; 4] {
        let pos: Vec3 = self.get_position();
        let half_w: Vec3 = self.get_right().scale(self.get_width() * 0.5);
        let half_h: Vec3 = self.get_up().scale(self.get_height() * 0.5);
        [
            pos.sub(half_w).add(half_h),
            pos.add(half_w).add(half_h),
            pos.add(half_w).sub(half_h),
            pos.sub(half_w).sub(half_h),
        ]
    }

    /// Returns the world-space `(start, end)` endpoints of a linear tube area light.
    ///
    /// # Returns
    ///
    /// - `(Vec3, Vec3)` - Tube endpoints along `right`.
    #[must_use]
    pub fn tube_endpoints(&self) -> (Vec3, Vec3) {
        let half_vec: Vec3 = self.get_right().scale(self.get_width() * 0.5);
        let pos: Vec3 = self.get_position();
        (pos.sub(half_vec), pos.add(half_vec))
    }

    /// Returns the cross-section radius of a tube area light in meters.
    ///
    /// # Returns
    ///
    /// - `f32` - Tube radius (`height * 0.5`).
    #[must_use]
    pub fn tube_radius(&self) -> f32 {
        (self.get_height() * 0.5).max(0.01)
    }

    /// Computes a world-space bounding sphere enclosing this area light's influence range.
    ///
    /// # Returns
    ///
    /// - `(Vec3, f32)` - `(center, radius)` world bounding sphere.
    #[must_use]
    pub fn bounding_sphere(&self) -> (Vec3, f32) {
        let half_diag: f32 =
            (self.get_width() * self.get_width() + self.get_height() * self.get_height()).sqrt()
                * 0.5;
        (self.get_position(), self.get_range() + half_diag)
    }

    /// Evaluates closest-point representative GGX shading and analytical line-integral diffuse falloff for a tube light.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space shading position.
    /// - `Vec3` - Surface normal vector.
    /// - `Vec3` - Outgoing view direction pointing toward camera.
    /// - `&PbrMaterial` - Metallic-roughness PBR surface material.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Linear HDR reflected RGB radiance.
    #[must_use]
    pub fn evaluate_tube_representative(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        view_dir: Vec3,
        material: &PbrMaterial,
    ) -> Vec3 {
        let intensity: f32 = self.get_intensity();
        if intensity <= 1.0e-6 {
            return Vec3::zero();
        }
        let unit_n: Vec3 = normal.normalize();
        let unit_v: Vec3 = view_dir.normalize();
        let (end_a, end_b): (Vec3, Vec3) = self.tube_endpoints();
        let l0: Vec3 = end_a.sub(world_pos);
        let l1: Vec3 = end_b.sub(world_pos);
        let radius: f32 = self.tube_radius();
        let l0_z: f32 = l0.dot(unit_n);
        let l1_z: f32 = l1.dot(unit_n);
        if l0_z + radius <= 0.0 && l1_z + radius <= 0.0 {
            return Vec3::zero();
        }
        let ld: Vec3 = l1.sub(l0);
        let ld_len_sq: f32 = ld.length_sq().max(1.0e-6);
        let closest_t: f32 = (-l0.dot(ld) / ld_len_sq).clamp(0.0, 1.0);
        let closest_vec: Vec3 = l0.add(ld.scale(closest_t));
        let range_atten: f32 =
            lagarde_attenuation(closest_vec.length_sq(), radius, self.get_range());
        if range_atten <= 0.0 {
            return Vec3::zero();
        }
        let len0: f32 = l0.length().max(radius);
        let len1: f32 = l1.length().max(radius);
        let n_dot_l0: f32 = (l0_z / len0).clamp(0.0, 1.0);
        let n_dot_l1: f32 = (l1_z / len1).clamp(0.0, 1.0);
        let line_diffuse_form: f32 = ((n_dot_l0 + n_dot_l1) * 0.5)
            * (2.0 * radius * ld_len_sq.sqrt()
                / (len0 * len1 + l0.dot(l1).max(0.0) + radius * radius))
                .clamp(0.0, 1.0);
        let refl: Vec3 = unit_v.scale(-1.0).reflect(unit_n).normalize();
        let r_dot_l0: f32 = refl.dot(l0);
        let r_dot_ld: f32 = refl.dot(ld);
        let spec_num: f32 = r_dot_l0 * r_dot_ld - l0.dot(ld);
        let spec_den: f32 = ld_len_sq - r_dot_ld * r_dot_ld;
        let spec_t: f32 = if spec_den.abs() > 1.0e-6 {
            (spec_num / spec_den).clamp(0.0, 1.0)
        } else {
            closest_t
        };
        let mut to_rep: Vec3 = l0.add(ld.scale(spec_t));
        let center_to_ray: Vec3 = refl.scale(to_rep.dot(refl)).sub(to_rep);
        let ctr_len: f32 = center_to_ray.length();
        if ctr_len > 1.0e-6 {
            to_rep = to_rep.add(center_to_ray.scale((radius / ctr_len).clamp(0.0, 1.0)));
        }
        let rep_dist: f32 = to_rep.length().max(radius);
        let spec_l: Vec3 = to_rep.scale(1.0 / rep_dist);
        let n_dot_l_spec: f32 = unit_n.dot(spec_l).max(0.0);
        let rough: f32 = material.get_roughness().clamp(0.04, 1.0);
        let alpha: f32 = rough * rough;
        let alpha_p: f32 = (alpha + radius / (2.0 * rep_dist)).clamp(0.04, 1.0);
        let energy_norm: f32 = (alpha / alpha_p) * (alpha / alpha_p);
        let base_col: Vec3 = Vec3::new(
            material.get_base_color().get_x().clamp(0.0, 1.0),
            material.get_base_color().get_y().clamp(0.0, 1.0),
            material.get_base_color().get_z().clamp(0.0, 1.0),
        );
        let metallic: f32 = material.get_metallic().clamp(0.0, 1.0);
        let f0: Vec3 = Vec3::splat(0.04).lerp(base_col, metallic);
        let spec_rgb: Vec3 = if n_dot_l_spec > 0.0 {
            let half_v: Vec3 = unit_v.add(spec_l).normalize();
            let n_dot_h: f32 = unit_n.dot(half_v).max(0.0);
            let v_dot_h: f32 = unit_v.dot(half_v).clamp(0.0, 1.0);
            let n_dot_v: f32 = unit_n.dot(unit_v).max(0.02);
            let ap2: f32 = alpha_p * alpha_p;
            let d_den: f32 = n_dot_h * n_dot_h * (ap2 - 1.0) + 1.0;
            let ggx_d: f32 = (ap2 * energy_norm) / (PI * d_den * d_den).max(1.0e-5);
            let om_vh: f32 = 1.0 - v_dot_h;
            let pow5: f32 = om_vh * om_vh * om_vh * om_vh * om_vh;
            let fresnel: Vec3 = f0.add(Vec3::splat(1.0).sub(f0).scale(pow5));
            let vis: f32 = 0.25 / (n_dot_l_spec + n_dot_v).max(0.05);
            fresnel.scale((ggx_d * vis * n_dot_l_spec * range_atten).min(4.0))
        } else {
            Vec3::zero()
        };
        let diff_rgb: Vec3 = base_col.scale((1.0 - metallic) * line_diffuse_form / PI);
        let rad: Vec3 = self.get_color().scale(intensity);
        diff_rgb.add(spec_rgb).mul(rad)
    }

    /// Converts rectangular or disk area lights into `euv-core`'s core `AreaLight3D` (`None` for `Tube`).
    ///
    /// # Returns
    ///
    /// - `Option<AreaLight3D>` - Compatible core area light for `Rect` or `Disk`, or `None` for `Tube`.
    #[must_use]
    pub fn to_core_area_light(&self) -> Option<AreaLight3D> {
        let mut core_light: AreaLight3D = match self.get_shape() {
            RigAreaLightShape3D::Rect => AreaLight3D::new_rect(
                self.get_position(),
                self.get_direction(),
                self.get_color(),
                self.get_intensity(),
                (self.get_width(), self.get_height()),
                self.get_range(),
            ),
            RigAreaLightShape3D::Disk => AreaLight3D::new_disk(
                self.get_position(),
                self.get_direction(),
                self.get_color(),
                self.get_intensity(),
                0.5 * (self.get_width() + self.get_height()),
                self.get_range(),
            ),
            RigAreaLightShape3D::Tube => return None,
        };
        core_light.set_two_sided(self.get_two_sided());
        Some(core_light)
    }
}

/// Triangle-area CDF construction and QMC importance sampling for `EmissiveMeshLight3D`.
impl EmissiveMeshLight3D {
    /// Builds an `EmissiveMeshLight3D` from a `Mesh3D` using each triangle's material `emissive` radiance scaled by `emission_scale`.
    ///
    /// # Arguments
    ///
    /// - `&Mesh3D` - Source indexed triangle mesh.
    /// - `&Transform3D` - World-space placement transform.
    /// - `f32` - Linear radiance multiplier applied to mesh emissive color.
    /// - `f32` - Smooth attenuation cutoff range in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed emissive mesh light with flux-area CDF.
    #[must_use]
    pub fn from_mesh(
        mesh: &Mesh3D,
        transform: &Transform3D,
        emission_scale: f32,
        range: f32,
    ) -> Self {
        Self::build_from_mesh(mesh, transform, None, emission_scale, range)
    }

    /// Builds an `EmissiveMeshLight3D` overriding every triangle's emission with uniform linear `radiance`.
    ///
    /// # Arguments
    ///
    /// - `&Mesh3D` - Source indexed triangle mesh.
    /// - `&Transform3D` - World-space placement transform.
    /// - `Vec3` - Uniform linear HDR RGB emission radiance.
    /// - `f32` - Smooth attenuation cutoff range in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed emissive mesh light with area CDF.
    #[must_use]
    pub fn from_mesh_with_radiance(
        mesh: &Mesh3D,
        transform: &Transform3D,
        radiance: Vec3,
        range: f32,
    ) -> Self {
        Self::build_from_mesh(mesh, transform, Some(radiance), 1.0, range)
    }

    /// Shared triangle extraction and normalized flux-weighted CDF builder for `EmissiveMeshLight3D`.
    ///
    /// # Arguments
    ///
    /// - `&Mesh3D` - Source indexed triangle mesh.
    /// - `&Transform3D` - World-space placement transform.
    /// - `Option<Vec3>` - Optional uniform radiance override.
    /// - `f32` - Radiance scale multiplier.
    /// - `f32` - Maximum range cutoff in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed emissive mesh emitter.
    #[must_use]
    fn build_from_mesh(
        mesh: &Mesh3D,
        transform: &Transform3D,
        radiance_override: Option<Vec3>,
        emission_scale: f32,
        range: f32,
    ) -> Self {
        let model: Mat4 = transform.to_mat4();
        let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
        let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
        let sub_mats: &[PbrMaterial] = mesh.get_sub_materials().as_slice();
        let tri_mats: &[u16] = mesh.get_tri_materials().as_slice();
        let default_emissive: Vec3 = mesh.get_material().get_emissive();
        let safe_scale: f32 = if emission_scale.is_finite() {
            emission_scale.max(0.0)
        } else {
            1.0
        };
        let mut triangles: Vec<EmissiveTriangle3D> = Vec::with_capacity(indices.len());
        let mut weights: Vec<f32> = Vec::with_capacity(indices.len());
        let mut min_pt: Vec3 = Vec3::splat(f32::INFINITY);
        let mut max_pt: Vec3 = Vec3::splat(f32::NEG_INFINITY);
        let mut total_area: f32 = 0.0;
        let mut total_flux: f32 = 0.0;
        for (tri_idx, tri) in indices.iter().enumerate() {
            let i0: usize = tri[0] as usize;
            let i1: usize = tri[1] as usize;
            let i2: usize = tri[2] as usize;
            if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
                continue;
            }
            let raw_emissive: Vec3 = match radiance_override {
                Some(col) => col,
                None => {
                    let slot: usize = tri_mats.get(tri_idx).copied().unwrap_or(0) as usize;
                    if slot > 0 && slot <= sub_mats.len() {
                        sub_mats[slot - 1].get_emissive()
                    } else {
                        default_emissive
                    }
                }
            };
            let emissive: Vec3 = Vec3::new(
                raw_emissive.get_x().max(0.0),
                raw_emissive.get_y().max(0.0),
                raw_emissive.get_z().max(0.0),
            )
            .scale(safe_scale);
            let lum: f32 =
                0.2126 * emissive.get_x() + 0.7152 * emissive.get_y() + 0.0722 * emissive.get_z();
            if lum <= 1.0e-6 {
                continue;
            }
            let p0: Vec3 = model.mul_point3(verts[i0].get_position());
            let p1: Vec3 = model.mul_point3(verts[i1].get_position());
            let p2: Vec3 = model.mul_point3(verts[i2].get_position());
            let cross_e: Vec3 = p1.sub(p0).cross(p2.sub(p0));
            let double_area: f32 = cross_e.length();
            if double_area <= 1.0e-7 {
                continue;
            }
            let area: f32 = 0.5 * double_area;
            let normal: Vec3 = cross_e.scale(1.0 / double_area);
            let flux: f32 = area * lum;
            triangles.push(EmissiveTriangle3D::new(p0, p1, p2, normal, area, emissive));
            weights.push(flux);
            total_area += area;
            total_flux += flux;
            min_pt = min_pt.min(p0).min(p1).min(p2);
            max_pt = max_pt.max(p0).max(p1).max(p2);
        }
        let mut cdf: Vec<f32> = Vec::with_capacity(weights.len());
        let mut accum: f32 = 0.0;
        if total_flux > 0.0 {
            let inv_flux: f32 = 1.0 / total_flux;
            for (idx, w) in weights.iter().enumerate() {
                accum += *w * inv_flux;
                if idx + 1 == weights.len() {
                    cdf.push(1.0);
                } else {
                    cdf.push(accum.clamp(0.0, 1.0));
                }
            }
        }
        let bounds: AxisAlignedBox3D = if triangles.is_empty() {
            AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero())
        } else {
            AxisAlignedBox3D::new(min_pt, max_pt)
        };
        Self {
            triangles,
            cdf,
            total_area,
            total_flux_weight: total_flux,
            bounds,
            range: range.max(0.5),
            two_sided: true,
        }
    }

    /// Importance-samples a surface point on the emissive mesh in O(log T) time using the precomputed triangle CDF.
    ///
    /// # Arguments
    ///
    /// - `f32` - Uniform random scalar in `[0.0, 1.0)` selecting the triangle via binary search.
    /// - `f32` - First uniform barycentric sample in `[0.0, 1.0)`.
    /// - `f32` - Second uniform barycentric sample in `[0.0, 1.0)`.
    ///
    /// # Returns
    ///
    /// - `Option<EmissiveMeshSample3D>` - Sampled world point, normal, radiance, and area PDF, or `None` if empty.
    #[must_use]
    pub fn sample_point(
        &self,
        u_tri: f32,
        u_bary_0: f32,
        u_bary_1: f32,
    ) -> Option<EmissiveMeshSample3D> {
        let tris: &[EmissiveTriangle3D] = self.get_triangles().as_slice();
        let cdf: &[f32] = self.get_cdf().as_slice();
        if tris.is_empty() || cdf.len() != tris.len() {
            return None;
        }
        let target: f32 = u_tri.clamp(0.0, 0.999_999);
        let mut lo: usize = 0;
        let mut hi: usize = cdf.len() - 1;
        while lo < hi {
            let mid: usize = lo + (hi - lo) / 2;
            if cdf[mid] < target {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        let tri: EmissiveTriangle3D = tris[lo];
        let prev_cdf: f32 = if lo == 0 { 0.0 } else { cdf[lo - 1] };
        let tri_prob: f32 = (cdf[lo] - prev_cdf).max(1.0e-7);
        let su0: f32 = u_bary_0.clamp(0.0, 1.0).sqrt();
        let b0: f32 = 1.0 - su0;
        let b1: f32 = u_bary_1.clamp(0.0, 1.0) * su0;
        let b2: f32 = (1.0 - b0 - b1).max(0.0);
        let pos: Vec3 = tri
            .get_v0()
            .scale(b0)
            .add(tri.get_v1().scale(b1))
            .add(tri.get_v2().scale(b2));
        let pdf_area: f32 = tri_prob / tri.get_area().max(1.0e-6);
        Some(EmissiveMeshSample3D::new(
            pos,
            tri.get_normal(),
            tri.get_emissive_radiance(),
            pdf_area,
        ))
    }

    /// Estimates direct illumination from this emissive mesh via deterministic Hammersley area-CDF Monte Carlo integration.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space shading point.
    /// - `Vec3` - Surface normal.
    /// - `Vec3` - Outgoing view direction.
    /// - `&PbrMaterial` - Surface PBR material.
    /// - `u32` - Number of QMC surface samples (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Vec3` - Estimated direct reflected linear HDR RGB radiance.
    #[must_use]
    pub fn evaluate_direct_qmc(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        view_dir: Vec3,
        material: &PbrMaterial,
        sample_count: u32,
    ) -> Vec3 {
        if self.get_triangles().is_empty() || sample_count == 0 {
            return Vec3::zero();
        }
        let count: u32 = sample_count.max(1);
        let mut sum: Vec3 = Vec3::zero();
        for idx in 0..count {
            let xi: [f32; 2] = hammersley_2d(idx, count);
            let u_tri: f32 = ((idx as f32) + 0.5) / (count as f32);
            let Some(sample) = self.sample_point(u_tri, xi[0], xi[1]) else {
                continue;
            };
            let to_light: Vec3 = sample.get_position().sub(world_pos);
            let dist_sq: f32 = to_light.length_sq();
            let atten: f32 = lagarde_attenuation(dist_sq, 0.05, self.get_range());
            if atten <= 0.0 {
                continue;
            }
            let dist: f32 = dist_sq.max(1.0e-6).sqrt();
            let light_dir: Vec3 = to_light.scale(1.0 / dist);
            let emitter_cos: f32 = if self.get_two_sided() {
                light_dir.dot(sample.get_normal()).abs()
            } else {
                (-light_dir.dot(sample.get_normal())).max(0.0)
            };
            if emitter_cos <= 1.0e-5 {
                continue;
            }
            let brdf: Vec3 = evaluate_cook_torrance_brdf(normal, view_dir, light_dir, material);
            let weight: f32 = (emitter_cos * atten) / sample.get_pdf_area().max(1.0e-5);
            sum = sum.add(brdf.mul(sample.get_radiance()).scale(weight));
        }
        sum.scale(1.0 / (count as f32))
    }
}

/// Default empty `LightRig3D`.
impl Default for LightRig3D {
    /// Creates an empty `LightRig3D` with neutral minimal ambient fill.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty light rig.
    fn default() -> Self {
        Self::empty()
    }
}

/// Composable light builders, direct evaluation, and scene presets for `LightRig3D`.
impl LightRig3D {
    /// Creates an empty `LightRig3D` ready to receive lights.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty light rig.
    #[must_use]
    pub fn empty() -> Self {
        Self {
            directional_lights: Vec::new(),
            point_lights: Vec::new(),
            spot_lights: Vec::new(),
            area_lights: Vec::new(),
            emissive_meshes: Vec::new(),
            ambient_color: Vec3::new(0.08, 0.09, 0.11),
            ambient_intensity: 0.15,
        }
    }

    /// Appends a directional Sun/Moon light to this rig.
    ///
    /// # Arguments
    ///
    /// - `RigDirectionalLight3D` - Directional light to add.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable rig reference for chaining.
    pub fn add_directional(&mut self, light: RigDirectionalLight3D) -> &mut Self {
        self.get_mut_directional_lights().push(light);
        self
    }

    /// Appends a physical point light to this rig.
    ///
    /// # Arguments
    ///
    /// - `RigPointLight3D` - Point light to add.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable rig reference for chaining.
    pub fn add_point(&mut self, light: RigPointLight3D) -> &mut Self {
        self.get_mut_point_lights().push(light);
        self
    }

    /// Appends a physical spotlight to this rig.
    ///
    /// # Arguments
    ///
    /// - `RigSpotLight3D` - Spotlight to add.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable rig reference for chaining.
    pub fn add_spot(&mut self, light: RigSpotLight3D) -> &mut Self {
        self.get_mut_spot_lights().push(light);
        self
    }

    /// Appends an analytical Rect, Disk, or Tube area light to this rig.
    ///
    /// # Arguments
    ///
    /// - `RigAreaLight3D` - Area light to add.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable rig reference for chaining.
    pub fn add_area(&mut self, light: RigAreaLight3D) -> &mut Self {
        self.get_mut_area_lights().push(light);
        self
    }

    /// Appends an emissive triangle-mesh light to this rig.
    ///
    /// # Arguments
    ///
    /// - `EmissiveMeshLight3D` - Emissive mesh light to add.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable rig reference for chaining.
    pub fn add_emissive_mesh(&mut self, light: EmissiveMeshLight3D) -> &mut Self {
        self.get_mut_emissive_meshes().push(light);
        self
    }

    /// Returns the total count of local clusterable lights (`point + spot + area`).
    ///
    /// # Returns
    ///
    /// - `usize` - Total local light count.
    #[must_use]
    pub fn total_local_light_count(&self) -> usize {
        self.get_point_lights().len() + self.get_spot_lights().len() + self.get_area_lights().len()
    }

    /// Evaluates combined direct PBR + LTC radiance across all emitters in this rig.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space shading point.
    /// - `Vec3` - Surface normal.
    /// - `Vec3` - Outgoing view direction pointing toward camera.
    /// - `&PbrMaterial` - Metallic-roughness surface material.
    /// - `&LtcAreaLightEvaluator` - Analytical GGX LTC area-light evaluator.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Accumulated direct linear HDR RGB radiance.
    #[must_use]
    pub fn evaluate_direct_lighting(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        view_dir: Vec3,
        material: &PbrMaterial,
        ltc: &LtcAreaLightEvaluator,
    ) -> Vec3 {
        let mut total: Vec3 = self
            .get_ambient_color()
            .mul(material.get_base_color())
            .scale(
                self.get_ambient_intensity().max(0.0)
                    * (1.0 - material.get_metallic().clamp(0.0, 1.0)),
            );
        for dir_light in self.get_directional_lights().iter() {
            total = total.add(dir_light.evaluate_direct(normal, view_dir, material));
        }
        for pt_light in self.get_point_lights().iter() {
            total = total.add(pt_light.evaluate_direct(world_pos, normal, view_dir, material));
        }
        for spot_light in self.get_spot_lights().iter() {
            total = total.add(spot_light.evaluate_direct(world_pos, normal, view_dir, material));
        }
        for area_light in self.get_area_lights().iter() {
            total = total
                .add(ltc.evaluate_area_light(area_light, world_pos, normal, view_dir, material));
        }
        for emissive_mesh in self.get_emissive_meshes().iter() {
            total = total.add(emissive_mesh.evaluate_direct_qmc(
                world_pos,
                normal,
                view_dir,
                material,
                EMISSIVE_DEFAULT_SAMPLES,
            ));
        }
        total
    }

    /// Built-in classic studio three-point lighting preset (warm softbox Rect key, cool Disk fill, crisp rim Spot).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured three-point studio `LightRig3D`.
    #[must_use]
    pub fn studio_three_point() -> Self {
        let mut rig: Self = Self::empty();
        rig.set_ambient_color(Vec3::new(0.06, 0.065, 0.075));
        rig.set_ambient_intensity(0.12);
        rig.add_area(RigAreaLight3D::new_rect(
            Vec3::new(3.5, 3.2, 3.0),
            Vec3::new(-0.62, -0.52, -0.58),
            kelvin_to_linear_rgb(5_600.0),
            6.5,
            (2.4, 1.6),
            24.0,
        ));
        rig.add_area(RigAreaLight3D::new_disk(
            Vec3::new(-4.0, 2.2, 2.5),
            Vec3::new(0.74, -0.36, -0.56),
            kelvin_to_linear_rgb(7_200.0),
            2.8,
            (2.2, 2.2),
            24.0,
        ));
        rig.add_spot(RigSpotLight3D::from_kelvin(
            Vec3::new(-1.0, 4.0, -4.5),
            Vec3::new(0.18, -0.62, 0.76),
            6_400.0,
            28.0,
            22.0,
            (0.24, 0.48),
        ));
        rig
    }

    /// Built-in golden-hour outdoor preset (low warm 3600K sun with 4-cascade CSM + atmospheric bounce fill).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured golden-hour outdoor `LightRig3D`.
    #[must_use]
    pub fn golden_hour_outdoor() -> Self {
        let mut rig: Self = Self::empty();
        rig.set_ambient_color(Vec3::new(0.24, 0.19, 0.22));
        rig.set_ambient_intensity(0.25);
        rig.add_directional(RigDirectionalLight3D::from_kelvin(
            Vec3::new(0.84, 0.24, -0.49),
            3_600.0,
            4.8,
        ));
        rig.add_point(
            RigPointLight3D::from_kelvin(Vec3::new(-8.0, 3.5, 6.0), 4_200.0, 12.0, 28.0)
                .with_source_radius(0.35),
        );
        rig
    }

    /// Built-in cyberpunk neon street preset (cool moonlight, cyan/magenta linear Tube lights, sodium street lamps, Venetian-blinds Spot).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured cyberpunk neon street `LightRig3D`.
    #[must_use]
    pub fn cyberpunk_neon_street() -> Self {
        let mut rig: Self = Self::empty();
        rig.set_ambient_color(Vec3::new(0.03, 0.05, 0.09));
        rig.set_ambient_intensity(0.15);
        rig.add_directional(RigDirectionalLight3D::from_kelvin(
            Vec3::new(-0.35, 0.72, -0.60),
            9_500.0,
            0.45,
        ));
        rig.add_area(RigAreaLight3D::new_tube(
            Vec3::new(-3.2, 2.8, 0.0),
            Vec3::new(-3.2, 2.8, -5.0),
            0.09,
            Vec3::new(0.08, 0.92, 1.0),
            8.5,
            20.0,
        ));
        rig.add_area(RigAreaLight3D::new_tube(
            Vec3::new(3.2, 3.4, -1.0),
            Vec3::new(3.2, 1.4, -1.0),
            0.08,
            Vec3::new(1.0, 0.12, 0.68),
            9.0,
            18.0,
        ));
        rig.add_point(
            RigPointLight3D::from_kelvin(Vec3::new(0.0, 6.2, -6.5), 2_200.0, 38.0, 22.0)
                .with_source_radius(0.18)
                .with_shadows(true),
        );
        rig.add_spot(
            RigSpotLight3D::from_kelvin(
                Vec3::new(4.5, 4.2, 2.5),
                Vec3::new(-0.68, -0.58, -0.45),
                5_200.0,
                32.0,
                20.0,
                (0.28, 0.56),
            )
            .with_cookie(SpotCookieMask::VenetianBlinds {
                slat_count: 8,
                open_ratio: 0.52,
                tilt_rad: 0.15,
            }),
        );
        rig
    }

    /// Built-in dramatic museum spotlight preset (dark gallery floor, crisp overhead RadialWindow key spot, warm sculpture accent).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured museum gallery `LightRig3D`.
    #[must_use]
    pub fn dramatic_museum_spot() -> Self {
        let mut rig: Self = Self::empty();
        rig.set_ambient_color(Vec3::new(0.02, 0.022, 0.028));
        rig.set_ambient_intensity(0.08);
        rig.add_spot(
            RigSpotLight3D::from_kelvin(
                Vec3::new(0.0, 6.0, 1.2),
                Vec3::new(0.0, -0.97, -0.24),
                3_200.0,
                55.0,
                16.0,
                (0.16, 0.34),
            )
            .with_cookie(SpotCookieMask::RadialWindow {
                panes_x: 2,
                panes_y: 2,
                mullion_width: 0.06,
            }),
        );
        rig.add_spot(RigSpotLight3D::from_kelvin(
            Vec3::new(-2.8, 4.2, -2.5),
            Vec3::new(0.55, -0.68, 0.48),
            4_600.0,
            22.0,
            14.0,
            (0.18, 0.40),
        ));
        rig
    }
}

/// Default pre-allocated `16 x 9 x 24` `ForwardPlusLightGrid`.
impl Default for ForwardPlusLightGrid {
    /// Creates a default `16 x 9 x 24` Forward+ clustered light grid pre-allocated for zero steady-state heap allocations.
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated Forward+ clustered light grid.
    fn default() -> Self {
        Self::new(
            FORWARD_PLUS_DEFAULT_NX,
            FORWARD_PLUS_DEFAULT_NY,
            FORWARD_PLUS_DEFAULT_NZ,
            FORWARD_PLUS_DEFAULT_MAX_LIGHTS_PER_CLUSTER,
        )
    }
}

/// Pre-allocated O(L * touched_clusters) clustered frustum culling and lookup for `ForwardPlusLightGrid`.
impl ForwardPlusLightGrid {
    /// Creates a pre-allocated `nx x ny x nz` Forward+ clustered light grid.
    ///
    /// # Arguments
    ///
    /// - `usize` - Horizontal cluster count (`>= 1`).
    /// - `usize` - Vertical cluster count (`>= 1`).
    /// - `usize` - Exponential depth slice count (`>= 1`).
    /// - `usize` - Maximum lights stored per cluster (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated Forward+ light grid.
    #[must_use]
    pub fn new(nx: usize, ny: usize, nz: usize, max_lights_per_cluster: usize) -> Self {
        let safe_nx: usize = nx.max(1);
        let safe_ny: usize = ny.max(1);
        let safe_nz: usize = nz.max(1);
        let safe_max: usize = max_lights_per_cluster.max(1);
        let total_clusters: usize = safe_nx * safe_ny * safe_nz;
        let default_near: f32 = 0.25;
        let default_far: f32 = 250.0;
        Self {
            nx: safe_nx,
            ny: safe_ny,
            nz: safe_nz,
            max_lights_per_cluster: safe_max,
            near_plane: default_near,
            far_plane: default_far,
            tan_half_y: 0.577_35,
            tan_half_x: 1.026_4,
            log_depth_scale: (safe_nz as f32) / (default_far / default_near).ln(),
            total_assignments: 0,
            depth_splits: vec![default_near; safe_nz + 1],
            cluster_aabbs_view: vec![
                AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
                total_clusters
            ],
            light_refs: Vec::with_capacity(FORWARD_PLUS_DEFAULT_MAX_LOCAL_LIGHTS),
            cluster_counts: vec![0_u32; total_clusters],
            cluster_indices: vec![0_u32; total_clusters * safe_max],
        }
    }

    /// Transforms a world-space point into camera-local Forward+ view coordinates `(right, up, forward_depth)`.
    ///
    /// # Arguments
    ///
    /// - `&Camera3D` - Active perspective camera.
    /// - `Vec3` - World-space point.
    ///
    /// # Returns
    ///
    /// - `Vec3` - View-space coordinates `(vx, vy, vz)` with positive `vz` along camera forward.
    #[must_use]
    pub fn world_to_view(camera: &Camera3D, world_pos: Vec3) -> Vec3 {
        let rel: Vec3 = world_pos.sub(camera.get_position());
        let fwd: Vec3 = camera.forward();
        let right: Vec3 = camera.right();
        let up: Vec3 = right.cross(fwd).normalize();
        Vec3::new(rel.dot(right), rel.dot(up), rel.dot(fwd))
    }

    /// Rebuilds view-space cluster AABBs and assigns all Point, Spot, and Area lights from `rig` in O(L * touched_clusters) with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Camera3D` - Active 3D perspective camera.
    /// - `f32` - Viewport width-to-height aspect ratio.
    /// - `&LightRig3D` - Scene lighting rig supplying Point, Spot, and Area emitters.
    pub fn rebuild(&mut self, camera: &Camera3D, aspect: f32, rig: &LightRig3D) {
        let nx: usize = self.get_nx();
        let ny: usize = self.get_ny();
        let nz: usize = self.get_nz();
        let max_per: usize = self.get_max_lights_per_cluster();
        let safe_aspect: f32 = aspect.max(0.1);
        let near_p: f32 = camera.get_near().max(0.05);
        let far_p: f32 = camera.get_far().max(near_p + 1.0);
        let eff_fov: f32 = Camera3D::effective_vertical_fov_rad(camera.get_fov_deg(), safe_aspect);
        let tan_half_y: f32 = (eff_fov * 0.5).tan().max(0.05);
        let tan_half_x: f32 = tan_half_y * safe_aspect;
        let log_scale: f32 = (nz as f32) / (far_p / near_p).ln().max(1.0e-5);
        self.set_near_plane(near_p);
        self.set_far_plane(far_p);
        self.set_tan_half_y(tan_half_y);
        self.set_tan_half_x(tan_half_x);
        self.set_log_depth_scale(log_scale);
        let cam_pos: Vec3 = camera.get_position();
        let cam_fwd: Vec3 = camera.forward();
        let cam_right: Vec3 = camera.right();
        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
        let depth_ratio: f32 = far_p / near_p;
        let inv_nx: f32 = 2.0 / (nx as f32);
        let inv_ny: f32 = 2.0 / (ny as f32);
        let assignments: usize = {
            let Self {
                depth_splits,
                cluster_aabbs_view,
                light_refs,
                cluster_counts,
                cluster_indices,
                ..
            } = self;
            for (iz, slot) in depth_splits.iter_mut().enumerate() {
                let frac: f32 = (iz as f32) / (nz as f32);
                *slot = near_p * depth_ratio.powf(frac);
            }
            for iz in 0..nz {
                let z0: f32 = depth_splits[iz];
                let z1: f32 = depth_splits[iz + 1];
                for iy in 0..ny {
                    let ny0: f32 = -1.0 + (iy as f32) * inv_ny;
                    let ny1: f32 = -1.0 + ((iy + 1) as f32) * inv_ny;
                    let y0_a: f32 = ny0 * tan_half_y * z0;
                    let y0_b: f32 = ny0 * tan_half_y * z1;
                    let y1_a: f32 = ny1 * tan_half_y * z0;
                    let y1_b: f32 = ny1 * tan_half_y * z1;
                    let min_y: f32 = y0_a.min(y0_b);
                    let max_y: f32 = y1_a.max(y1_b);
                    for ix in 0..nx {
                        let nx0: f32 = -1.0 + (ix as f32) * inv_nx;
                        let nx1: f32 = -1.0 + ((ix + 1) as f32) * inv_nx;
                        let x0_a: f32 = nx0 * tan_half_x * z0;
                        let x0_b: f32 = nx0 * tan_half_x * z1;
                        let x1_a: f32 = nx1 * tan_half_x * z0;
                        let x1_b: f32 = nx1 * tan_half_x * z1;
                        let min_x: f32 = x0_a.min(x0_b);
                        let max_x: f32 = x1_a.max(x1_b);
                        let c_idx: usize = (iz * ny + iy) * nx + ix;
                        cluster_aabbs_view[c_idx] = AxisAlignedBox3D::new(
                            Vec3::new(min_x, min_y, z0),
                            Vec3::new(max_x, max_y, z1),
                        );
                    }
                }
            }
            cluster_counts.fill(0);
            light_refs.clear();
            let max_refs: usize = light_refs.capacity();
            for (idx, pt) in rig.get_point_lights().iter().enumerate() {
                if light_refs.len() >= max_refs {
                    break;
                }
                if pt.get_intensity() <= 1.0e-6 {
                    continue;
                }
                light_refs.push(ClusteredLightRef::new(
                    ClusteredLightKind::Point,
                    idx as u32,
                    pt.get_position(),
                    pt.get_range(),
                ));
            }
            for (idx, spot) in rig.get_spot_lights().iter().enumerate() {
                if light_refs.len() >= max_refs {
                    break;
                }
                if spot.get_intensity() <= 1.0e-6 {
                    continue;
                }
                let (center, rad): (Vec3, f32) = spot.bounding_sphere();
                light_refs.push(ClusteredLightRef::new(
                    ClusteredLightKind::Spot,
                    idx as u32,
                    center,
                    rad,
                ));
            }
            for (idx, area) in rig.get_area_lights().iter().enumerate() {
                if light_refs.len() >= max_refs {
                    break;
                }
                if area.get_intensity() <= 1.0e-6 {
                    continue;
                }
                let (center, rad): (Vec3, f32) = area.bounding_sphere();
                light_refs.push(ClusteredLightRef::new(
                    ClusteredLightKind::Area,
                    idx as u32,
                    center,
                    rad,
                ));
            }
            let mut total_assigned: usize = 0;
            for (slot_idx, lref) in light_refs.iter().enumerate() {
                let rel: Vec3 = lref.get_bounding_center().sub(cam_pos);
                let view_center: Vec3 =
                    Vec3::new(rel.dot(cam_right), rel.dot(cam_up), rel.dot(cam_fwd));
                let radius: f32 = lref.get_bounding_radius().max(0.0);
                let vz: f32 = view_center.get_z();
                if vz + radius < near_p || vz - radius > far_p {
                    continue;
                }
                let z_lo: f32 = (vz - radius).max(near_p);
                let z_hi: f32 = (vz + radius).min(far_p);
                let raw_iz0: usize =
                    (((z_lo / near_p).ln() * log_scale).floor().max(0.0) as usize).min(nz - 1);
                let raw_iz1: usize =
                    (((z_hi / near_p).ln() * log_scale).floor().max(0.0) as usize).min(nz - 1);
                let iz_min: usize = raw_iz0.saturating_sub(1);
                let iz_max: usize = (raw_iz1 + 1).min(nz - 1);
                let vx: f32 = view_center.get_x();
                let vy: f32 = view_center.get_y();
                let r_sq: f32 = radius * radius;
                for iz in iz_min..=iz_max {
                    let z0: f32 = depth_splits[iz];
                    let z1: f32 = depth_splits[iz + 1];
                    let dz: f32 = if vz < z0 {
                        z0 - vz
                    } else if vz > z1 {
                        vz - z1
                    } else {
                        0.0
                    };
                    if dz > radius {
                        continue;
                    }
                    let r_xy: f32 = (r_sq - dz * dz).max(0.0).sqrt();
                    let x_min: f32 = vx - r_xy;
                    let x_max: f32 = vx + r_xy;
                    let y_min: f32 = vy - r_xy;
                    let y_max: f32 = vy + r_xy;
                    let inv_wx0: f32 = 1.0 / (tan_half_x * z0).max(1.0e-5);
                    let inv_wx1: f32 = 1.0 / (tan_half_x * z1).max(1.0e-5);
                    let inv_wy0: f32 = 1.0 / (tan_half_y * z0).max(1.0e-5);
                    let inv_wy1: f32 = 1.0 / (tan_half_y * z1).max(1.0e-5);
                    let ndc_x_lo: f32 = (x_min * inv_wx0).min(x_min * inv_wx1);
                    let ndc_x_hi: f32 = (x_max * inv_wx0).max(x_max * inv_wx1);
                    let ndc_y_lo: f32 = (y_min * inv_wy0).min(y_min * inv_wy1);
                    let ndc_y_hi: f32 = (y_max * inv_wy0).max(y_max * inv_wy1);
                    let out_x: bool = ndc_x_hi < -1.0 || ndc_x_lo > 1.0;
                    let out_y: bool = ndc_y_hi < -1.0 || ndc_y_lo > 1.0;
                    if out_x || out_y {
                        continue;
                    }
                    let ix0: usize =
                        (((ndc_x_lo * 0.5 + 0.5).clamp(0.0, 1.0) * (nx as f32)).floor() as usize)
                            .min(nx - 1)
                            .saturating_sub(1);
                    let ix1: usize = ((((ndc_x_hi * 0.5 + 0.5).clamp(0.0, 1.0) * (nx as f32))
                        .floor() as usize)
                        + 1)
                    .min(nx - 1);
                    let iy0: usize =
                        (((ndc_y_lo * 0.5 + 0.5).clamp(0.0, 1.0) * (ny as f32)).floor() as usize)
                            .min(ny - 1)
                            .saturating_sub(1);
                    let iy1: usize = ((((ndc_y_hi * 0.5 + 0.5).clamp(0.0, 1.0) * (ny as f32))
                        .floor() as usize)
                        + 1)
                    .min(ny - 1);
                    for iy in iy0..=iy1 {
                        for ix in ix0..=ix1 {
                            let c_idx: usize = (iz * ny + iy) * nx + ix;
                            if !sphere_intersects_aabb(
                                view_center,
                                radius,
                                cluster_aabbs_view[c_idx],
                            ) {
                                continue;
                            }
                            let count: usize = cluster_counts[c_idx] as usize;
                            if count < max_per {
                                cluster_indices[c_idx * max_per + count] = slot_idx as u32;
                                cluster_counts[c_idx] = (count + 1) as u32;
                                total_assigned += 1;
                            }
                        }
                    }
                }
            }
            total_assigned
        };
        self.set_total_assignments(assignments);
    }

    /// Returns the view-space AABB of cluster `(ix, iy, iz)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Horizontal cluster index `ix`.
    /// - `usize` - Vertical cluster index `iy`.
    /// - `usize` - Depth slice index `iz`.
    ///
    /// # Returns
    ///
    /// - `AxisAlignedBox3D` - View-space bounding box of the requested cluster.
    #[must_use]
    pub fn cluster_aabb_view(&self, ix: usize, iy: usize, iz: usize) -> AxisAlignedBox3D {
        let nx: usize = self.get_nx();
        let ny: usize = self.get_ny();
        let nz: usize = self.get_nz();
        let cx: usize = ix.min(nx - 1);
        let cy: usize = iy.min(ny - 1);
        let cz: usize = iz.min(nz - 1);
        let idx: usize = (cz * ny + cy) * nx + cx;
        self.get_cluster_aabbs_view()[idx]
    }

    /// Returns the slice of assigned local light slot indices for cluster `(ix, iy, iz)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Horizontal cluster index `ix`.
    /// - `usize` - Vertical cluster index `iy`.
    /// - `usize` - Depth slice index `iz`.
    ///
    /// # Returns
    ///
    /// - `&[u32]` - Active local light slot indices inside `light_refs`.
    #[must_use]
    pub fn cluster_lights(&self, ix: usize, iy: usize, iz: usize) -> &[u32] {
        let nx: usize = self.get_nx();
        let ny: usize = self.get_ny();
        let nz: usize = self.get_nz();
        if ix >= nx || iy >= ny || iz >= nz {
            return &[];
        }
        let c_idx: usize = (iz * ny + iy) * nx + ix;
        let max_per: usize = self.get_max_lights_per_cluster();
        let count: usize = (self.get_cluster_counts()[c_idx] as usize).min(max_per);
        let base: usize = c_idx * max_per;
        &self.get_cluster_indices()[base..base + count]
    }

    /// Resolves a clustered light slot index to its `ClusteredLightRef` descriptor.
    ///
    /// # Arguments
    ///
    /// - `u32` - Light slot index returned by `cluster_lights`.
    ///
    /// # Returns
    ///
    /// - `Option<ClusteredLightRef>` - Clustered light handle if valid.
    #[must_use]
    pub fn light_ref(&self, light_slot: u32) -> Option<ClusteredLightRef> {
        self.get_light_refs().get(light_slot as usize).copied()
    }

    /// Returns the number of local lights packed into this frame's grid.
    ///
    /// # Returns
    ///
    /// - `usize` - Packed light count.
    #[must_use]
    pub fn active_light_count(&self) -> usize {
        self.get_light_refs().len()
    }

    /// Maps normalized screen coordinates `ndc_x, ndc_y in [-1, 1]` and positive `view_depth` to `(ix, iy, iz)`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Horizontal NDC in `[-1.0, 1.0]`.
    /// - `f32` - Vertical NDC in `[-1.0, 1.0]`.
    /// - `f32` - Positive camera-space forward depth in meters.
    ///
    /// # Returns
    ///
    /// - `Option<(usize, usize, usize)>` - Enclosing cluster coordinate if within frustum bounds.
    #[must_use]
    pub fn cluster_coord_for_screen(
        &self,
        ndc_x: f32,
        ndc_y: f32,
        view_depth: f32,
    ) -> Option<(usize, usize, usize)> {
        let near_p: f32 = self.get_near_plane();
        let far_p: f32 = self.get_far_plane();
        let out_z: bool = view_depth < near_p || view_depth > far_p;
        let out_xy: bool = ndc_x.abs() > 1.0 || ndc_y.abs() > 1.0;
        if out_z || out_xy {
            return None;
        }
        let nx: usize = self.get_nx();
        let ny: usize = self.get_ny();
        let nz: usize = self.get_nz();
        let ix: usize = (((ndc_x * 0.5 + 0.5) * (nx as f32)).floor() as usize).min(nx - 1);
        let iy: usize = (((ndc_y * 0.5 + 0.5) * (ny as f32)).floor() as usize).min(ny - 1);
        let iz: usize = ((((view_depth / near_p).ln()) * self.get_log_depth_scale())
            .floor()
            .max(0.0) as usize)
            .min(nz - 1);
        Some((ix, iy, iz))
    }

    /// Returns pre-allocated buffer capacities `(aabbs, light_refs, counts, indices)` to audit zero steady-state allocations.
    ///
    /// # Returns
    ///
    /// - `(usize, usize, usize, usize)` - Internal buffer capacities.
    #[must_use]
    pub fn buffer_capacities(&self) -> (usize, usize, usize, usize) {
        (
            self.get_cluster_aabbs_view().capacity(),
            self.get_light_refs().capacity(),
            self.get_cluster_counts().capacity(),
            self.get_cluster_indices().capacity(),
        )
    }

    /// Returns raw backing allocation pointers `(cluster_indices_ptr, light_refs_ptr)` verifying in-place reuse across rebuilds.
    ///
    /// # Returns
    ///
    /// - `(usize, usize)` - Backing allocation addresses of internal buffers.
    #[must_use]
    pub fn buffer_addresses(&self) -> (usize, usize) {
        (
            self.get_cluster_indices().as_ptr() as usize,
            self.get_light_refs().as_ptr() as usize,
        )
    }
}