euv-core 0.52.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
use super::*;

/// Constructors for `PointLight3D`.
impl PointLight3D {
    /// Creates a physically based 3D point light from sRGB `color`, `intensity`, and `radius`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space center position.
    /// - `Color` - sRGB emission color.
    /// - `f32` - Luminous intensity multiplier.
    /// - `f32` - Maximum influence radius in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured point light.
    #[must_use]
    pub fn new(position: Vec3, color: Color, intensity: f32, radius: f32) -> Self {
        Self {
            position,
            color: Vec3::from_color(color),
            intensity: intensity.max(0.0),
            radius: radius.max(0.25),
            cast_shadows: false,
        }
    }

    /// Creates a physically based 3D point light from linear HDR RGB `color`, `intensity`, and `range`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space center position.
    /// - `Vec3` - Linear HDR RGB emission color.
    /// - `f32` - Luminous intensity in candela.
    /// - `f32` - Smooth `KHR_lights_punctual` attenuation cutoff range in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured point light.
    #[must_use]
    pub fn from_linear(position: Vec3, color: Vec3, intensity: f32, range: f32) -> Self {
        Self {
            position,
            color,
            intensity: intensity.max(0.0),
            radius: range.max(0.25),
            cast_shadows: false,
        }
    }

    /// Evaluates the exact Khronos `KHR_lights_punctual` windowed inverse-square range attenuation factor.
    ///
    /// # Arguments
    ///
    /// - `f32` - Squared distance from shading point to light in square meters.
    /// - `f32` - Maximum influence range in meters (`<= 0.0` disables range cutoff).
    ///
    /// # Returns
    ///
    /// - `f32` - Physical attenuation scalar in `[0.0, 1.0 / 1e-4]`.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn khr_attenuation(distance_sq: f32, range: f32) -> f32 {
        let safe_dist_sq: f32 = distance_sq.max(1.0e-4);
        if range <= 0.0 || !range.is_finite() {
            return 1.0 / safe_dist_sq;
        }
        let inv_range_sq: f32 = 1.0 / (range * range).max(1.0e-4);
        let ratio_sq: f32 = safe_dist_sq * inv_range_sq;
        let window: f32 = (1.0 - ratio_sq * ratio_sq).clamp(0.0, 1.0);
        (window * window) / safe_dist_sq
    }
}

/// Constructors for `SpotLight3D`.
impl SpotLight3D {
    /// Creates a physically based 3D spotlight from position, direction, sRGB color, intensity, range, and cone half-angles in degrees.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter origin.
    /// - `Vec3` - Beam direction vector (normalized automatically).
    /// - `Color` - sRGB emission color.
    /// - `f32` - Luminous intensity multiplier.
    /// - `f32` - Maximum beam range in meters.
    /// - `(f32, f32)` - `(inner_half_angle_deg, outer_half_angle_deg)` cone angles.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured spotlight.
    #[must_use]
    pub fn new(
        position: Vec3,
        direction: Vec3,
        color: Color,
        intensity: f32,
        range: f32,
        cone_deg: (f32, f32),
    ) -> Self {
        let (inner_deg, outer_deg): (f32, f32) = cone_deg;
        let clamped_inner: f32 = inner_deg.clamp(1.0, 80.0);
        let clamped_outer: f32 = outer_deg.clamp(clamped_inner + 1.0, 88.0);
        Self {
            position,
            direction: direction.normalize(),
            color: Vec3::from_color(color),
            intensity: intensity.max(0.0),
            range: range.max(0.5),
            inner_cos: clamped_inner.to_radians().cos(),
            outer_cos: clamped_outer.to_radians().cos(),
        }
    }

    /// Creates a physically based 3D spotlight directly from linear RGB `color` and radian cone angles (`KHR_lights_punctual`).
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter origin.
    /// - `Vec3` - Beam direction vector.
    /// - `Vec3` - Linear HDR RGB emission color.
    /// - `f32` - Luminous intensity in candela.
    /// - `f32` - Maximum attenuation range in meters.
    /// - `(f32, f32)` - `(inner_cone_rad, outer_cone_rad)` half-angles in radians.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured spotlight.
    #[must_use]
    pub fn from_linear(
        position: Vec3,
        direction: Vec3,
        color: Vec3,
        intensity: f32,
        range: f32,
        cone_rad: (f32, f32),
    ) -> Self {
        let (inner_rad, outer_rad): (f32, f32) = cone_rad;
        let clamped_inner: f32 = inner_rad.clamp(0.0, FRAC_PI_2 - 0.02);
        let clamped_outer: f32 = outer_rad.clamp(clamped_inner + 0.005, FRAC_PI_2 - 0.01);
        Self {
            position,
            direction: direction.normalize(),
            color,
            intensity: intensity.max(0.0),
            range: range.max(0.5),
            inner_cos: clamped_inner.cos(),
            outer_cos: clamped_outer.cos(),
        }
    }
}

/// Construction and representative-point GGX / LTC-aligned evaluation for `AreaLight3D`.
impl AreaLight3D {
    /// Constructs a rectangular Blender `AreaLight3D` oriented along `direction`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter center.
    /// - `Vec3` - Unit emitting normal pointing from emitter into scene.
    /// - `Vec3` - Linear HDR RGB emission color.
    /// - `f32` - Luminous intensity multiplier.
    /// - `(f32, f32)` - Aperture `(width, height)` in meters.
    /// - `f32` - Maximum attenuation 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 dir_unit: Vec3 = direction.normalize();
        let ref_up: Vec3 = if dir_unit.get_y().abs() > 0.95 {
            Vec3::new(0.0, 0.0, 1.0)
        } else {
            Vec3::new(0.0, 1.0, 0.0)
        };
        let right: Vec3 = ref_up.cross(dir_unit).normalize();
        let up: Vec3 = dir_unit.cross(right).normalize();
        Self {
            position,
            direction: dir_unit,
            right,
            up,
            color,
            intensity: intensity.max(0.0),
            width: dimensions.0.max(0.05),
            height: dimensions.1.max(0.05),
            range: range.max(1.0),
            shape: AreaLightShape3D::Rectangle,
            two_sided: false,
        }
    }

    /// Constructs a disk Blender `AreaLight3D` oriented along `direction`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter center.
    /// - `Vec3` - Unit emitting normal pointing from emitter into scene.
    /// - `Vec3` - Linear HDR RGB emission color.
    /// - `f32` - Luminous intensity multiplier.
    /// - `f32` - Disk emitter diameter in meters.
    /// - `f32` - Maximum attenuation cutoff range in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured disk area light.
    #[must_use]
    pub fn new_disk(
        position: Vec3,
        direction: Vec3,
        color: Vec3,
        intensity: f32,
        diameter: f32,
        range: f32,
    ) -> Self {
        let mut light: Self = Self::new_rect(
            position,
            direction,
            color,
            intensity,
            (diameter, diameter),
            range,
        );
        light.set_shape(AreaLightShape3D::Disk);
        light
    }

    /// Evaluates physically based diffuse irradiance and Karis representative-point GGX specular contribution for this rectangular or disk area light.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Area light reference.
    /// - `Vec3` - World-space surface shading position.
    /// - `Vec3` - Unit outward surface normal.
    /// - `Vec3` - Unit view direction pointing from surface toward camera.
    /// - `(Vec3, Vec3, f32, f32)` - `(albedo, f0_specular, perceptual_roughness, diffuse_scale)`.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Linear HDR direct radiance contributed by this area light.
    #[must_use]
    pub fn evaluate_pbr(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        view_dir: Vec3,
        material_terms: (Vec3, Vec3, f32, f32),
    ) -> Vec3 {
        let intensity: f32 = self.get_intensity();
        if intensity <= 1.0e-5 {
            return Vec3::zero();
        }
        let light_pos: Vec3 = self.get_position();
        let light_dir: Vec3 = self.get_direction();
        let light_right: Vec3 = self.get_right();
        let light_up: Vec3 = self.get_up();
        let half_w: f32 = self.get_width() * 0.5;
        let half_h: f32 = self.get_height() * 0.5;
        let from_light: Vec3 = world_pos.sub(light_pos);
        let plane_dist: f32 = from_light.dot(light_dir);
        if !self.get_two_sided() && plane_dist <= 0.0 {
            return Vec3::zero();
        }
        let center_dist_sq: f32 = from_light.length_sq();
        let range_val: f32 = self.get_range();
        if center_dist_sq >= range_val * range_val {
            return Vec3::zero();
        }
        let (albedo, f0, roughness, diffuse_scale): (Vec3, Vec3, f32, f32) = material_terms;
        let clamped_rough: f32 = roughness.clamp(0.04, 1.0);
        let alpha: f32 = clamped_rough * clamped_rough;
        let refl_dir: Vec3 = view_dir.scale(-1.0).reflect(normal).normalize();
        let r_dot_ldir: f32 = refl_dir.dot(light_dir);
        let hit_local: Vec3 = if r_dot_ldir.abs() > 1.0e-4 {
            let ray_t: f32 = (-plane_dist / r_dot_ldir).max(0.0);
            let plane_hit: Vec3 = world_pos.add(refl_dir.scale(ray_t));
            plane_hit.sub(light_pos)
        } else {
            from_light
        };
        let raw_u: f32 = hit_local.dot(light_right);
        let raw_v: f32 = hit_local.dot(light_up);
        let (clamped_u, clamped_v): (f32, f32) = match self.get_shape() {
            AreaLightShape3D::Rectangle => {
                (raw_u.clamp(-half_w, half_w), raw_v.clamp(-half_h, half_h))
            }
            AreaLightShape3D::Disk => {
                let norm_u: f32 = raw_u / half_w.max(1.0e-4);
                let norm_v: f32 = raw_v / half_h.max(1.0e-4);
                let rad_sq: f32 = norm_u * norm_u + norm_v * norm_v;
                if rad_sq > 1.0 {
                    let inv_rad: f32 = 1.0 / rad_sq.sqrt();
                    (raw_u * inv_rad, raw_v * inv_rad)
                } else {
                    (raw_u, raw_v)
                }
            }
        };
        let rep_point: Vec3 = light_pos
            .add(light_right.scale(clamped_u))
            .add(light_up.scale(clamped_v));
        let to_rep: Vec3 = rep_point.sub(world_pos);
        let rep_dist_sq: f32 = to_rep.length_sq().max(1.0e-4);
        let rep_dist: f32 = rep_dist_sq.sqrt();
        let spec_l: Vec3 = to_rep.scale(1.0 / rep_dist);
        let n_dot_l_spec: f32 = normal.dot(spec_l).max(0.0);
        let to_center: Vec3 = light_pos.sub(world_pos);
        let center_dist: f32 = center_dist_sq.max(1.0e-4).sqrt();
        let diff_l: Vec3 = to_center.scale(1.0 / center_dist);
        let emitter_facing: f32 = if self.get_two_sided() {
            diff_l.dot(light_dir).abs()
        } else {
            (-diff_l.dot(light_dir)).max(0.0)
        };
        let n_dot_l_diff: f32 = normal.dot(diff_l).max(0.0);
        let emitter_area: f32 = match self.get_shape() {
            AreaLightShape3D::Rectangle => self.get_width() * self.get_height(),
            AreaLightShape3D::Disk => PI * half_w * half_h,
        };
        let solid_angle: f32 =
            (emitter_area * emitter_facing) / (center_dist_sq + emitter_area / PI).max(1.0e-4);
        let range_ratio_sq: f32 = center_dist_sq / (range_val * range_val).max(1.0e-4);
        let range_win: f32 = (1.0 - range_ratio_sq * range_ratio_sq).clamp(0.0, 1.0);
        let window_sq: f32 = range_win * range_win;
        let diffuse_rgb: Vec3 =
            albedo.scale((diffuse_scale / PI) * n_dot_l_diff * solid_angle.min(PI) * window_sq);
        let spec_rgb: Vec3 = if n_dot_l_spec > 0.0 {
            let equiv_rad: f32 = (emitter_area / PI).sqrt();
            let alpha_prime: f32 = (alpha + equiv_rad / (2.0 * rep_dist)).clamp(0.04, 1.0);
            let alpha_p2: f32 = alpha_prime * alpha_prime;
            let energy_norm: f32 = (alpha / alpha_prime) * (alpha / alpha_prime);
            let half_vec: Vec3 = spec_l.add(view_dir).normalize();
            let n_dot_h: f32 = normal.dot(half_vec).max(0.0);
            let n_dot_v: f32 = normal.dot(view_dir).max(0.04);
            let v_dot_h: f32 = view_dir.dot(half_vec).clamp(0.0, 1.0);
            let ggx_den: f32 = n_dot_h * n_dot_h * (alpha_p2 - 1.0) + 1.0;
            let ggx_d: f32 = (alpha_p2 * energy_norm) / (PI * ggx_den * ggx_den).max(1.0e-4);
            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 spec_atten: f32 = PointLight3D::khr_attenuation(rep_dist_sq, range_val);
            let spec_scalar: f32 = ((ggx_d * 0.25) / (n_dot_l_spec.max(0.08) + n_dot_v)).min(6.0);
            fresnel.scale(spec_scalar * n_dot_l_spec * spec_atten * emitter_area.max(0.1))
        } else {
            Vec3::zero()
        };
        let radiance: Vec3 = self.get_color().scale(intensity);
        diffuse_rgb.add(spec_rgb).mul(radiance)
    }
}

/// Default pre-allocated 16x9x16 `LightClusterGrid3D`.
impl Default for LightClusterGrid3D {
    /// Creates an empty pre-allocated `LightClusterGrid3D` ready for zero-allocation per-frame light binning.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready clustered light grid.
    fn default() -> Self {
        let total_froxels: usize =
            LIGHT_CLUSTER_GRID_X * LIGHT_CLUSTER_GRID_Y * LIGHT_CLUSTER_GRID_Z;
        Self {
            near_plane: 0.3,
            far_plane: 420.0,
            log_depth_scale: (LIGHT_CLUSTER_GRID_Z as f32) / (420.0_f32 / 0.3_f32).ln(),
            depth_slice_max: [420.0; LIGHT_CLUSTER_GRID_Z],
            active_light_count: 0,
            total_assignments: 0,
            packed_lights: Vec::with_capacity(LIGHT_CLUSTER_MAX_LIGHTS),
            cluster_counts: vec![0_u16; total_froxels],
            cluster_indices: vec![0_u16; total_froxels * LIGHT_CLUSTER_MAX_PER_FROXEL],
        }
    }
}

/// 3D frustum froxel binning and Cook-Torrance GGX local light evaluation for `LightClusterGrid3D`.
impl LightClusterGrid3D {
    /// Returns whether any local point or spot lights are active in the current frame.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when at least one local light is binned.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn has_active_lights(&self) -> bool {
        self.get_active_light_count() > 0
    }

    /// Bins all `point_lights` and `spot_lights` into the 16x9x16 logarithmic-Z camera frustum grid without heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Camera3D` - Active 3D perspective camera.
    /// - `f32` - Viewport width-to-height aspect ratio.
    /// - `&[PointLight3D]` - Active world-space point lights.
    /// - `&[SpotLight3D]` - Active world-space spotlights.
    pub fn build_clusters(
        &mut self,
        camera: &Camera3D,
        aspect: f32,
        point_lights: &[PointLight3D],
        spot_lights: &[SpotLight3D],
    ) {
        let near_p: f32 = camera.get_near().max(0.15);
        let far_p: f32 = camera.get_far().max(near_p + 1.0);
        let log_scale: f32 = (LIGHT_CLUSTER_GRID_Z as f32) / (far_p / near_p).ln().max(1.0e-4);
        self.set_near_plane(near_p);
        self.set_far_plane(far_p);
        self.set_log_depth_scale(log_scale);
        let depth_ratio: f32 = far_p / near_p;
        {
            let Self {
                depth_slice_max, ..
            } = self;
            for (slice_idx, slot) in depth_slice_max.iter_mut().enumerate() {
                let frac: f32 = ((slice_idx + 1) as f32) / (LIGHT_CLUSTER_GRID_Z as f32);
                *slot = near_p * depth_ratio.powf(frac);
            }
        }
        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 half_h: f32 = (camera.get_fov_deg().to_radians() * 0.5).tan().max(0.05);
        let half_w: f32 = half_h * aspect.max(0.1);
        let inv_half_w: f32 = 1.0 / half_w;
        let inv_half_h: f32 = 1.0 / half_h;
        let mut assignments: usize = 0;
        let active_count: usize = {
            let Self {
                packed_lights,
                cluster_counts,
                cluster_indices,
                ..
            } = self;
            packed_lights.clear();
            if point_lights.is_empty() && spot_lights.is_empty() {
                cluster_counts.fill(0);
                0
            } else {
                cluster_counts.fill(0);
                for point_light in point_lights.iter() {
                    if packed_lights.len() >= LIGHT_CLUSTER_MAX_LIGHTS {
                        break;
                    }
                    let rad: f32 = point_light.get_radius().max(0.25);
                    let intensity: f32 = point_light.get_intensity();
                    if intensity <= 1.0e-4 {
                        continue;
                    }
                    let light_pos: Vec3 = point_light.get_position();
                    let col: Vec3 = point_light.get_color().scale(intensity);
                    let light_idx: u16 = packed_lights.len() as u16;
                    packed_lights.push(PackedLocalLight {
                        pos_inv_r2: [
                            light_pos.get_x(),
                            light_pos.get_y(),
                            light_pos.get_z(),
                            1.0 / (rad * rad),
                        ],
                        radiance_radius: [col.get_x(), col.get_y(), col.get_z(), rad],
                        dir_outer_cos: [0.0, -1.0, 0.0, -2.0],
                        inv_cone_span: [0.0; 4],
                    });
                    assignments += Self::bin_sphere_into_froxels(
                        (cam_pos, cam_right, cam_up, cam_fwd),
                        (inv_half_w, inv_half_h, near_p, far_p, log_scale),
                        (light_pos, rad, light_idx),
                        cluster_counts,
                        cluster_indices,
                    );
                }
                for spot_light in spot_lights.iter() {
                    if packed_lights.len() >= LIGHT_CLUSTER_MAX_LIGHTS {
                        break;
                    }
                    let range: f32 = spot_light.get_range().max(0.5);
                    let intensity: f32 = spot_light.get_intensity();
                    if intensity <= 1.0e-4 {
                        continue;
                    }
                    let light_pos: Vec3 = spot_light.get_position();
                    let light_dir: Vec3 = spot_light.get_direction().normalize();
                    let col: Vec3 = spot_light.get_color().scale(intensity);
                    let outer_cos: f32 = spot_light.get_outer_cos();
                    let span: f32 = (spot_light.get_inner_cos() - outer_cos).max(SPOT_CONE_MIN_EPS);
                    let light_idx: u16 = packed_lights.len() as u16;
                    packed_lights.push(PackedLocalLight {
                        pos_inv_r2: [
                            light_pos.get_x(),
                            light_pos.get_y(),
                            light_pos.get_z(),
                            1.0 / (range * range),
                        ],
                        radiance_radius: [col.get_x(), col.get_y(), col.get_z(), range],
                        dir_outer_cos: [
                            light_dir.get_x(),
                            light_dir.get_y(),
                            light_dir.get_z(),
                            outer_cos,
                        ],
                        inv_cone_span: [1.0 / span, 0.0, 0.0, 0.0],
                    });
                    let cone_center: Vec3 = light_pos.add(light_dir.scale(range * 0.45));
                    let cone_bound_rad: f32 = range * 0.45;
                    assignments += Self::bin_sphere_into_froxels(
                        (cam_pos, cam_right, cam_up, cam_fwd),
                        (inv_half_w, inv_half_h, near_p, far_p, log_scale),
                        (cone_center, cone_bound_rad, light_idx),
                        cluster_counts,
                        cluster_indices,
                    );
                }
                packed_lights.len()
            }
        };
        self.set_active_light_count(active_count);
        self.set_total_assignments(assignments);
    }

    /// Bins a single light bounding sphere into all overlapped `(x, y, z)` froxels and returns the assignment count.
    ///
    /// # Arguments
    ///
    /// - `(Vec3, Vec3, Vec3, Vec3)` - Camera `(position, right, up, forward)` basis.
    /// - `(f32, f32, f32, f32, f32)` - `(inv_half_w, inv_half_h, near_p, far_p, log_scale)` frustum parameters.
    /// - `(Vec3, f32, u16)` - `(sphere_center, sphere_radius, light_index)`.
    /// - `&mut [u16]` - Mutable froxel count table.
    /// - `&mut [u16]` - Mutable flat froxel index array.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of froxels updated for this light.
    fn bin_sphere_into_froxels(
        cam_basis: (Vec3, Vec3, Vec3, Vec3),
        frustum_params: (f32, f32, f32, f32, f32),
        sphere: (Vec3, f32, u16),
        cluster_counts: &mut [u16],
        cluster_indices: &mut [u16],
    ) -> usize {
        let (cam_pos, cam_right, cam_up, cam_fwd): (Vec3, Vec3, Vec3, Vec3) = cam_basis;
        let (inv_half_w, inv_half_h, near_p, far_p, log_scale): (f32, f32, f32, f32, f32) =
            frustum_params;
        let (center, radius, light_idx): (Vec3, f32, u16) = sphere;
        let rel: Vec3 = center.sub(cam_pos);
        let vz: f32 = rel.dot(cam_fwd);
        let z_min: f32 = vz - radius;
        let z_max: f32 = vz + radius;
        if z_max <= near_p || z_min >= far_p {
            return 0;
        }
        let vx: f32 = rel.dot(cam_right);
        let vy: f32 = rel.dot(cam_up);
        let z_proj: f32 = vz.max(near_p);
        let inv_z: f32 = 1.0 / z_proj;
        let ndc_cx: f32 = vx * inv_z * inv_half_w;
        let ndc_cy: f32 = vy * inv_z * inv_half_h;
        let pad_x: f32 = if z_min <= near_p {
            (radius / vz.max(2.0) * inv_half_w).clamp(0.35, 1.35)
        } else {
            (radius / z_min) * inv_half_w
        };
        let pad_y: f32 = if z_min <= near_p {
            (radius / vz.max(2.0) * inv_half_h).clamp(0.35, 1.35)
        } else {
            (radius / z_min) * inv_half_h
        };
        let min_u: f32 = (ndc_cx - pad_x) * 0.5 + 0.5;
        let max_u: f32 = (ndc_cx + pad_x) * 0.5 + 0.5;
        let min_v: f32 = 0.5 - (ndc_cy + pad_y) * 0.5;
        let max_v: f32 = 0.5 - (ndc_cy - pad_y) * 0.5;
        let out_u: bool = max_u < 0.0 || min_u > 1.0;
        let out_v: bool = max_v < 0.0 || min_v > 1.0;
        if out_u || out_v {
            return 0;
        }
        let gx_max: usize = LIGHT_CLUSTER_GRID_X - 1;
        let gy_max: usize = LIGHT_CLUSTER_GRID_Y - 1;
        let gz_max: usize = LIGHT_CLUSTER_GRID_Z - 1;
        let cx0: usize =
            ((min_u.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_X as f32)).floor() as usize).min(gx_max);
        let cx1: usize =
            ((max_u.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_X as f32)).floor() as usize).min(gx_max);
        let cy0: usize =
            ((min_v.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_Y as f32)).floor() as usize).min(gy_max);
        let cy1: usize =
            ((max_v.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_Y as f32)).floor() as usize).min(gy_max);
        let cz0: usize = ((((z_min.max(near_p) / near_p).ln()) * log_scale)
            .floor()
            .max(0.0) as usize)
            .min(gz_max);
        let cz1: usize = ((((z_max.min(far_p) / near_p).ln()) * log_scale)
            .floor()
            .max(0.0) as usize)
            .min(gz_max);
        let slice_stride: usize = LIGHT_CLUSTER_GRID_X * LIGHT_CLUSTER_GRID_Y;
        let mut count_added: usize = 0;
        for cz in cz0..=cz1 {
            let z_off: usize = cz * slice_stride;
            for cy in cy0..=cy1 {
                let y_off: usize = z_off + cy * LIGHT_CLUSTER_GRID_X;
                for cx in cx0..=cx1 {
                    let froxel: usize = y_off + cx;
                    let cur: usize = cluster_counts[froxel] as usize;
                    if cur < LIGHT_CLUSTER_MAX_PER_FROXEL {
                        cluster_indices[froxel * LIGHT_CLUSTER_MAX_PER_FROXEL + cur] = light_idx;
                        cluster_counts[froxel] = (cur + 1) as u16;
                        count_added += 1;
                    }
                }
            }
        }
        count_added
    }

    /// Evaluates all local point and spot lights assigned to the pixel's 3D froxel using UE5 windowed inverse-square PBR attenuation and Cook-Torrance GGX specular.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Pixel world-space surface position.
    /// - `Vec3` - Unit outward surface normal.
    /// - `Vec3` - Unit view direction pointing from surface toward camera.
    /// - `(Vec3, Vec3, f32, f32)` - `(base_albedo, f0_specular, alpha2_ggx, diffuse_scale)`.
    /// - `(f32, f32, f32)` - `(uv_x, uv_y, linear_depth)` normalized screen UV in `[0, 1]` and camera depth.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Summed linear HDR direct radiance contributed by local clustered lights.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn evaluate_pixel(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        view_dir: Vec3,
        material_terms: (Vec3, Vec3, f32, f32),
        screen_depth: (f32, f32, f32),
    ) -> Vec3 {
        if self.get_active_light_count() == 0 {
            return Vec3::zero();
        }
        let (uv_x, uv_y, linear_depth): (f32, f32, f32) = screen_depth;
        let near_p: f32 = self.get_near_plane();
        if linear_depth < near_p || linear_depth > self.get_far_plane() {
            return Vec3::zero();
        }
        let cx: usize = ((uv_x.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_X as f32)) as usize)
            .min(LIGHT_CLUSTER_GRID_X - 1);
        let cy: usize = ((uv_y.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_Y as f32)) as usize)
            .min(LIGHT_CLUSTER_GRID_Y - 1);
        let cz: usize = ((((linear_depth / near_p).ln()) * self.get_log_depth_scale()).max(0.0)
            as usize)
            .min(LIGHT_CLUSTER_GRID_Z - 1);
        let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
        let Self {
            packed_lights,
            cluster_counts,
            cluster_indices,
            ..
        } = self;
        let light_count: usize = cluster_counts[froxel] as usize;
        if light_count == 0 {
            return Vec3::zero();
        }
        let (albedo, f0, alpha2, diffuse_scale): (Vec3, Vec3, f32, f32) = material_terms;
        let n_dot_v: f32 = normal.dot(view_dir).max(0.04);
        let idx_base: usize = froxel * LIGHT_CLUSTER_MAX_PER_FROXEL;
        let mut accum: Vec3 = Vec3::zero();
        for slot in 0..light_count {
            let light: PackedLocalLight = packed_lights[cluster_indices[idx_base + slot] as usize];
            let to_light: Vec3 = Vec3::new(
                light.pos_inv_r2[0] - world_pos.get_x(),
                light.pos_inv_r2[1] - world_pos.get_y(),
                light.pos_inv_r2[2] - world_pos.get_z(),
            );
            let dist_sq: f32 = to_light.length_sq();
            let ratio_sq: f32 = dist_sq * light.pos_inv_r2[3];
            if ratio_sq >= 1.0 {
                continue;
            }
            let inv_dist: f32 = 1.0 / dist_sq.max(1.0e-4).sqrt();
            let light_dir: Vec3 = to_light.scale(inv_dist);
            let n_dot_l: f32 = normal.dot(light_dir);
            if n_dot_l <= 0.0 {
                continue;
            }
            let mut spot_factor: f32 = 1.0;
            if light.dir_outer_cos[3] > -1.5 {
                let beam_dir: Vec3 = Vec3::new(
                    light.dir_outer_cos[0],
                    light.dir_outer_cos[1],
                    light.dir_outer_cos[2],
                );
                let cos_theta: f32 = (-light_dir.get_x()) * beam_dir.get_x()
                    + (-light_dir.get_y()) * beam_dir.get_y()
                    + (-light_dir.get_z()) * beam_dir.get_z();
                if cos_theta <= light.dir_outer_cos[3] {
                    continue;
                }
                let raw_spot: f32 =
                    ((cos_theta - light.dir_outer_cos[3]) * light.inv_cone_span[0]).clamp(0.0, 1.0);
                spot_factor = raw_spot * raw_spot;
            }
            let window: f32 = (1.0 - ratio_sq * ratio_sq).clamp(0.0, 1.0);
            let atten: f32 = (window * window * spot_factor) / dist_sq.max(1.0e-4);
            let half_vec: Vec3 = light_dir.add(view_dir).normalize();
            let n_dot_h: f32 = normal.dot(half_vec).max(0.0);
            let v_dot_h: f32 = view_dir.dot(half_vec).clamp(0.0, 1.0);
            let denom: f32 = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
            let ggx_d: f32 = alpha2 / (PI * denom * denom).max(1.0e-4);
            let one_minus_vh: f32 = 1.0 - v_dot_h;
            let pow5: f32 =
                one_minus_vh * one_minus_vh * one_minus_vh * one_minus_vh * one_minus_vh;
            let fresnel: Vec3 = f0.add(Vec3::splat(1.0).sub(f0).scale(pow5));
            let spec_scalar: f32 = (ggx_d * 0.25) / (n_dot_l.max(0.08) + n_dot_v);
            let diffuse_rgb: Vec3 = albedo.scale(diffuse_scale * (1.0 / PI));
            let brdf_rgb: Vec3 = diffuse_rgb.add(fresnel.scale(spec_scalar.min(4.0)));
            let light_rad: Vec3 = Vec3::new(
                light.radiance_radius[0],
                light.radiance_radius[1],
                light.radiance_radius[2],
            );
            accum = accum.add(brdf_rgb.mul(light_rad).scale(n_dot_l * atten));
        }
        accum
    }

    /// Evaluates fast Lambertian linear-HDR local irradiance from the 3D froxel grid without `ln()` or GGX specular overhead (tuned for coarse deferred probe injection).
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space surface position.
    /// - `Vec3` - Unit outward surface normal.
    /// - `(f32, f32, f32)` - `(uv_x, uv_y, linear_depth)` normalized screen UV in `[0, 1]` and camera depth.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Summed linear HDR local diffuse irradiance RGB.
    #[must_use]
    pub fn evaluate_irradiance_fast(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        screen_depth: (f32, f32, f32),
    ) -> Vec3 {
        if self.get_active_light_count() == 0 {
            return Vec3::zero();
        }
        let (uv_x, uv_y, linear_depth): (f32, f32, f32) = screen_depth;
        if linear_depth < self.get_near_plane() || linear_depth > self.get_far_plane() {
            return Vec3::zero();
        }
        let cx: usize = ((uv_x.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_X as f32)) as usize)
            .min(LIGHT_CLUSTER_GRID_X - 1);
        let cy: usize = ((uv_y.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_Y as f32)) as usize)
            .min(LIGHT_CLUSTER_GRID_Y - 1);
        let Self {
            depth_slice_max,
            packed_lights,
            cluster_counts,
            cluster_indices,
            ..
        } = self;
        let mut cz: usize = 0;
        if linear_depth > depth_slice_max[7] {
            cz = 8;
        }
        if linear_depth > depth_slice_max[cz + 3] {
            cz += 4;
        }
        if linear_depth > depth_slice_max[cz + 1] {
            cz += 2;
        }
        if linear_depth > depth_slice_max[cz] {
            cz += 1;
        }
        let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
        let light_count: usize = cluster_counts[froxel] as usize;
        if light_count == 0 {
            return Vec3::zero();
        }
        let idx_base: usize = froxel * LIGHT_CLUSTER_MAX_PER_FROXEL;
        let mut accum_r: f32 = 0.0;
        let mut accum_g: f32 = 0.0;
        let mut accum_b: f32 = 0.0;
        let wx: f32 = world_pos.get_x();
        let wy: f32 = world_pos.get_y();
        let wz: f32 = world_pos.get_z();
        let nx: f32 = normal.get_x();
        let ny: f32 = normal.get_y();
        let nz: f32 = normal.get_z();
        for slot in 0..light_count {
            let light: PackedLocalLight = packed_lights[cluster_indices[idx_base + slot] as usize];
            let dx: f32 = light.pos_inv_r2[0] - wx;
            let dy: f32 = light.pos_inv_r2[1] - wy;
            let dz: f32 = light.pos_inv_r2[2] - wz;
            let dist_sq: f32 = dx.mul_add(dx, dy.mul_add(dy, dz * dz));
            let ratio_sq: f32 = dist_sq * light.pos_inv_r2[3];
            if ratio_sq >= 1.0 {
                continue;
            }
            let ndotl_raw: f32 = dx.mul_add(nx, dy.mul_add(ny, dz * nz));
            if ndotl_raw <= 0.0 {
                continue;
            }
            let inv_dist: f32 = 1.0 / dist_sq.max(1.0e-4).sqrt();
            let mut spot_factor: f32 = 1.0;
            if light.dir_outer_cos[3] > -1.5 {
                let cos_theta: f32 = -(dx * light.dir_outer_cos[0]
                    + dy * light.dir_outer_cos[1]
                    + dz * light.dir_outer_cos[2])
                    * inv_dist;
                if cos_theta <= light.dir_outer_cos[3] {
                    continue;
                }
                let raw_spot: f32 =
                    ((cos_theta - light.dir_outer_cos[3]) * light.inv_cone_span[0]).clamp(0.0, 1.0);
                spot_factor = raw_spot * raw_spot;
            }
            let window: f32 = (1.0 - ratio_sq * ratio_sq).max(0.0);
            let scale: f32 =
                (window * window * spot_factor * ndotl_raw * inv_dist) / (dist_sq + 1.0);
            accum_r = light.radiance_radius[0].mul_add(scale, accum_r);
            accum_g = light.radiance_radius[1].mul_add(scale, accum_g);
            accum_b = light.radiance_radius[2].mul_add(scale, accum_b);
        }
        Vec3::new(accum_r, accum_g, accum_b)
    }

    /// Returns the number of local lights assigned to a specific 3D froxel `(cx, cy, cz)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Froxel X coordinate in `0..16`.
    /// - `usize` - Froxel Y coordinate in `0..9`.
    /// - `usize` - Froxel Z coordinate in `0..16`.
    ///
    /// # Returns
    ///
    /// - `usize` - Count of binned lights in that froxel.
    #[must_use]
    pub fn froxel_light_count(&self, cx: usize, cy: usize, cz: usize) -> usize {
        let out_xy: bool = cx >= LIGHT_CLUSTER_GRID_X || cy >= LIGHT_CLUSTER_GRID_Y;
        if out_xy || cz >= LIGHT_CLUSTER_GRID_Z {
            return 0;
        }
        let Self { cluster_counts, .. } = self;
        let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
        cluster_counts[froxel] as usize
    }
}

/// Cascade construction, orthographic shadow rasterization, and PCF sampling for `VsmCascade`.
impl VsmCascade {
    /// Creates a new `VsmCascade` with `resolution x resolution` depth storage and `half_extent_m` world radius.
    ///
    /// # Arguments
    ///
    /// - `usize` - Shadow map edge resolution in texels (`>= 32`).
    /// - `f32` - World-space half-extent in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated VSM cascade.
    #[must_use]
    pub fn new(resolution: usize, half_extent_m: f32) -> Self {
        let res: usize = resolution.max(32);
        let total: usize = res * res;
        Self {
            resolution: res,
            half_extent_m: half_extent_m.max(8.0),
            snapped_center: Vec3::zero(),
            light_right: Vec3::new(1.0, 0.0, 0.0),
            light_up: Vec3::new(0.0, 0.0, 1.0),
            light_forward: Vec3::new(0.0, 1.0, 0.0),
            depth_min: -160.0,
            depth_max: 160.0,
            static_valid: false,
            static_depth: vec![1.0; total],
            active_depth: vec![1.0; total],
        }
    }

    /// Computes texel-snapped light-space orthonormal basis and center for `focus_pos` and `sun_dir`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Camera focus point in world space.
    /// - `Vec3` - Unit vector pointing toward the directional sun.
    ///
    /// # Returns
    ///
    /// - `(Vec3, Vec3, Vec3, Vec3)` - `(snapped_center, light_right, light_up, light_forward)`.
    #[must_use]
    fn compute_snapped_basis(&self, focus_pos: Vec3, sun_dir: Vec3) -> (Vec3, Vec3, Vec3, Vec3) {
        let fwd: Vec3 = sun_dir.normalize();
        let ref_up: Vec3 = if fwd.get_y().abs() > 0.95 {
            Vec3::new(0.0, 0.0, 1.0)
        } else {
            Vec3::new(0.0, 1.0, 0.0)
        };
        let right: Vec3 = ref_up.cross(fwd).normalize();
        let up: Vec3 = fwd.cross(right).normalize();
        let texel_world: f32 = (self.get_half_extent_m() * 2.0) / (self.get_resolution() as f32);
        let snap_step: f32 = (texel_world * 4.0).max(0.25);
        let proj_r: f32 = (focus_pos.dot(right) / snap_step).floor() * snap_step;
        let proj_u: f32 = (focus_pos.dot(up) / snap_step).floor() * snap_step;
        let proj_f: f32 = (focus_pos.dot(fwd) / snap_step).floor() * snap_step;
        let snapped: Vec3 = right
            .scale(proj_r)
            .add(up.scale(proj_u))
            .add(fwd.scale(proj_f));
        (snapped, right, up, fwd)
    }

    /// Builds the column-major orthographic light view-projection matrix matching `project_world_point` for GPU CSM shader lookups.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Cascade reference.
    ///
    /// # Returns
    ///
    /// - `Mat4` - Column-major light-space orthographic projection matrix mapping world points to `[-1, 1]` XY and `[0, 1]` Z.
    #[must_use]
    pub fn light_view_proj(&self) -> Mat4 {
        let right: Vec3 = self.get_light_right();
        let up: Vec3 = self.get_light_up();
        let fwd: Vec3 = self.get_light_forward();
        let center: Vec3 = self.get_snapped_center();
        let inv_extent: f32 = 1.0 / self.get_half_extent_m().max(1.0);
        let depth_max: f32 = self.get_depth_max();
        let inv_depth_span: f32 = 1.0 / (depth_max - self.get_depth_min()).max(1.0);
        let rx: f32 = right.get_x() * inv_extent;
        let ry: f32 = right.get_y() * inv_extent;
        let rz: f32 = right.get_z() * inv_extent;
        let ux: f32 = up.get_x() * inv_extent;
        let uy: f32 = up.get_y() * inv_extent;
        let uz: f32 = up.get_z() * inv_extent;
        let zx: f32 = -fwd.get_x() * inv_depth_span;
        let zy: f32 = -fwd.get_y() * inv_depth_span;
        let zz: f32 = -fwd.get_z() * inv_depth_span;
        let tx: f32 = -center.dot(right) * inv_extent;
        let ty: f32 = -center.dot(up) * inv_extent;
        let tz: f32 = (depth_max + center.dot(fwd)) * inv_depth_span;
        Mat4::from_cols_array([
            rx, ux, zx, 0.0, ry, uy, zy, 0.0, rz, uz, zz, 0.0, tx, ty, tz, 1.0,
        ])
    }

    /// Projects a world-space point into normalized cascade UV coordinates and linear shadow depth `[0.0, 1.0]`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space position to project.
    ///
    /// # Returns
    ///
    /// - `(f32, f32, f32)` - `(u_norm, v_norm, depth_norm)` where smaller `depth_norm` is closer to the sun.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn project_world_point(&self, world_pos: Vec3) -> (f32, f32, f32) {
        let rel: Vec3 = world_pos.sub(self.get_snapped_center());
        let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
        let coord_u: f32 = rel.dot(self.get_light_right()) * inv_span + 0.5;
        let coord_v: f32 = rel.dot(self.get_light_up()) * inv_span + 0.5;
        let light_z: f32 = rel.dot(self.get_light_forward());
        let depth_span: f32 = (self.get_depth_max() - self.get_depth_min()).max(1.0);
        let depth_norm: f32 = (self.get_depth_max() - light_z) / depth_span;
        (coord_u, coord_v, depth_norm)
    }

    /// Rasterizes a world-space triangle `(v0, v1, v2)` into the target shadow depth slice (`min` depth = closest to sun).
    ///
    /// # Arguments
    ///
    /// - `&mut [f32]` - Destination shadow depth buffer (`len == resolution * resolution`).
    /// - `usize` - Shadow map edge resolution.
    /// - `[(f32, f32, f32); 3]` - Projected `(u_norm, v_norm, depth_norm)` triangle vertices.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    fn rasterize_shadow_tri(depth_buf: &mut [f32], res: usize, verts: [(f32, f32, f32); 3]) {
        let res_f: f32 = res as f32;
        let x0: f32 = verts[0].0 * res_f;
        let y0: f32 = verts[0].1 * res_f;
        let z0: f32 = verts[0].2;
        let x1: f32 = verts[1].0 * res_f;
        let y1: f32 = verts[1].1 * res_f;
        let z1: f32 = verts[1].2;
        let x2: f32 = verts[2].0 * res_f;
        let y2: f32 = verts[2].1 * res_f;
        let z2: f32 = verts[2].2;
        let area: f32 = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);
        if area.abs() < 0.05 {
            return;
        }
        let max_i: i32 = (res as i32) - 1;
        let min_x: i32 = (x0.min(x1).min(x2).floor() as i32).max(0);
        let max_x: i32 = (x0.max(x1).max(x2).ceil() as i32).min(max_i);
        let min_y: i32 = (y0.min(y1).min(y2).floor() as i32).max(0);
        let max_y: i32 = (y0.max(y1).max(y2).ceil() as i32).min(max_i);
        if min_x > max_x || min_y > max_y {
            return;
        }
        let inv_area: f32 = 1.0 / area;
        for py in min_y..=max_y {
            let fy: f32 = (py as f32) + 0.5;
            let row_off: usize = (py as usize) * res;
            for px in min_x..=max_x {
                let fx: f32 = (px as f32) + 0.5;
                let w0: f32 = ((x1 - fx) * (y2 - fy) - (y1 - fy) * (x2 - fx)) * inv_area;
                let w1: f32 = ((x2 - fx) * (y0 - fy) - (y2 - fy) * (x0 - fx)) * inv_area;
                let w2: f32 = 1.0 - w0 - w1;
                if w0 >= -1.0e-4 && w1 >= -1.0e-4 && w2 >= -1.0e-4 {
                    let depth_val: f32 = (w0 * z0 + w1 * z1 + w2 * z2).clamp(0.0, 1.0);
                    let slot: &mut f32 = &mut depth_buf[row_off + (px as usize)];
                    if depth_val < *slot {
                        *slot = depth_val;
                    }
                }
            }
        }
    }

    /// Rebuilds the cached static shadow map buffer for all static shadow-casting objects inside this cascade's bounds using real `LOD0` mesh geometry.
    ///
    /// # Arguments
    ///
    /// - `&World3D` - Active world supplying objects, mesh library, visibility, and deformed meshes.
    fn rebuild_static_depth(&mut self, world: &World3D) {
        let objects: &[SceneObject3D] = world.get_objects().as_slice();
        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
        let res: usize = self.get_resolution();
        let center: Vec3 = self.get_snapped_center();
        let reach: f32 = self.get_half_extent_m() * 1.5;
        let right: Vec3 = self.get_light_right();
        let up: Vec3 = self.get_light_up();
        let fwd: Vec3 = self.get_light_forward();
        let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
        let depth_max: f32 = self.get_depth_max();
        let inv_depth_span: f32 = 1.0 / (depth_max - self.get_depth_min()).max(1.0);
        {
            let Self { static_depth, .. } = self;
            static_depth.fill(1.0);
            for (obj_idx, obj) in objects.iter().enumerate() {
                if !obj.get_ray_trace_caster()
                    || obj.get_is_dynamic()
                    || !world.is_object_visible(obj_idx)
                {
                    continue;
                }
                let wb: AxisAlignedBox3D = obj.get_world_bounds();
                let obj_center: Vec3 = wb.center();
                let rel_c: Vec3 = obj_center.sub(center);
                let limit: f32 = reach + wb.radius();
                if rel_c.get_x().abs() > limit && rel_c.get_z().abs() > limit {
                    continue;
                }
                let Some(mesh) = world.deformed_mesh_for_object(obj_idx).or_else(|| {
                    mesh_lib
                        .get(obj.get_mesh_id())
                        .and_then(|chain: &MeshLodChain| chain.get_levels().first())
                }) else {
                    continue;
                };
                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
                let model: Mat4 = obj.get_transform().to_mat4();
                for tri in indices.iter() {
                    let (i0, i1, i2): (usize, usize, usize) =
                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
                    let out_01: bool = i0 >= verts.len() || i1 >= verts.len();
                    if out_01 || i2 >= verts.len() {
                        continue;
                    }
                    let w0: Vec3 = model.mul_point3(verts[i0].get_position()).sub(center);
                    let w1: Vec3 = model.mul_point3(verts[i1].get_position()).sub(center);
                    let w2: Vec3 = model.mul_point3(verts[i2].get_position()).sub(center);
                    let p0: (f32, f32, f32) = (
                        w0.dot(right) * inv_span + 0.5,
                        w0.dot(up) * inv_span + 0.5,
                        (depth_max - w0.dot(fwd)) * inv_depth_span,
                    );
                    let p1: (f32, f32, f32) = (
                        w1.dot(right) * inv_span + 0.5,
                        w1.dot(up) * inv_span + 0.5,
                        (depth_max - w1.dot(fwd)) * inv_depth_span,
                    );
                    let p2: (f32, f32, f32) = (
                        w2.dot(right) * inv_span + 0.5,
                        w2.dot(up) * inv_span + 0.5,
                        (depth_max - w2.dot(fwd)) * inv_depth_span,
                    );
                    Self::rasterize_shadow_tri(static_depth.as_mut_slice(), res, [p0, p1, p2]);
                }
            }
        }
        self.set_static_valid(true);
    }

    /// Copies the cached static shadow depth into `active_depth` and overlays dynamic shadow casters using real `LOD0` or live deformed mesh geometry.
    ///
    /// # Arguments
    ///
    /// - `&World3D` - Active world supplying objects, mesh library, visibility, and deformed meshes.
    fn overlay_dynamic_depth(&mut self, world: &World3D) {
        let objects: &[SceneObject3D] = world.get_objects().as_slice();
        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
        let res: usize = self.get_resolution();
        let center: Vec3 = self.get_snapped_center();
        let right: Vec3 = self.get_light_right();
        let up: Vec3 = self.get_light_up();
        let fwd: Vec3 = self.get_light_forward();
        let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
        let depth_max: f32 = self.get_depth_max();
        let inv_depth_span: f32 = 1.0 / (depth_max - self.get_depth_min()).max(1.0);
        let Self {
            static_depth,
            active_depth,
            ..
        } = self;
        active_depth.copy_from_slice(static_depth.as_slice());
        for (obj_idx, obj) in objects.iter().enumerate() {
            if !obj.get_ray_trace_caster()
                || !obj.get_is_dynamic()
                || !world.is_object_visible(obj_idx)
            {
                continue;
            }
            let Some(mesh) = world.deformed_mesh_for_object(obj_idx).or_else(|| {
                mesh_lib
                    .get(obj.get_mesh_id())
                    .and_then(|chain: &MeshLodChain| chain.get_levels().first())
            }) else {
                continue;
            };
            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
            let model: Mat4 = obj.get_transform().to_mat4();
            for tri in indices.iter() {
                let (i0, i1, i2): (usize, usize, usize) =
                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
                let out_01: bool = i0 >= verts.len() || i1 >= verts.len();
                if out_01 || i2 >= verts.len() {
                    continue;
                }
                let w0: Vec3 = model.mul_point3(verts[i0].get_position()).sub(center);
                let w1: Vec3 = model.mul_point3(verts[i1].get_position()).sub(center);
                let w2: Vec3 = model.mul_point3(verts[i2].get_position()).sub(center);
                let p0: (f32, f32, f32) = (
                    w0.dot(right) * inv_span + 0.5,
                    w0.dot(up) * inv_span + 0.5,
                    (depth_max - w0.dot(fwd)) * inv_depth_span,
                );
                let p1: (f32, f32, f32) = (
                    w1.dot(right) * inv_span + 0.5,
                    w1.dot(up) * inv_span + 0.5,
                    (depth_max - w1.dot(fwd)) * inv_depth_span,
                );
                let p2: (f32, f32, f32) = (
                    w2.dot(right) * inv_span + 0.5,
                    w2.dot(up) * inv_span + 0.5,
                    (depth_max - w2.dot(fwd)) * inv_depth_span,
                );
                Self::rasterize_shadow_tri(active_depth.as_mut_slice(), res, [p0, p1, p2]);
            }
        }
    }

    /// Evaluates rotated 16-tap Vogel-disk PCF shadow visibility at `world_pos` if inside this cascade's bounds.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space surface position.
    /// - `Vec3` - Unit outward surface normal for normal-offset acne prevention.
    /// - `Vec3` - Unit vector pointing toward the sun.
    ///
    /// # Returns
    ///
    /// - `Option<f32>` - Visibility in `[VSM_SHADOW_FLOOR, 1.0]`, or `None` if outside this cascade.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn sample_pcf(&self, world_pos: Vec3, normal: Vec3, sun_dir: Vec3) -> Option<f32> {
        if !self.get_static_valid() {
            return None;
        }
        let texel_m: f32 = (self.get_half_extent_m() * 2.0) / (self.get_resolution() as f32);
        let biased_pos: Vec3 = world_pos.add(normal.scale(texel_m * 0.65));
        let (coord_u, coord_v, depth_norm): (f32, f32, f32) = self.project_world_point(biased_pos);
        if !(0.02..=0.98).contains(&coord_u)
            || !(0.02..=0.98).contains(&coord_v)
            || !(0.0..=1.0).contains(&depth_norm)
        {
            return None;
        }
        let res: usize = self.get_resolution();
        let res_f: f32 = res as f32;
        let max_idx: usize = res - 1;
        let n_dot_l: f32 = normal.dot(sun_dir).clamp(0.05, 1.0);
        let slope_bias: f32 = (0.0022 * (1.0 - n_dot_l) + 0.0014).clamp(0.0012, 0.008);
        let cmp_depth: f32 = depth_norm - slope_bias;
        let base_tx: f32 = coord_u * res_f;
        let base_ty: f32 = coord_v * res_f;
        let hash_seed: f32 = world_pos.get_x().mul_add(
            12.9898,
            world_pos
                .get_z()
                .mul_add(78.233, world_pos.get_y() * 37.719),
        );
        let rot_angle: f32 = (hash_seed.sin() * 43_758.547).fract() * TAU;
        let cos_rot: f32 = rot_angle.cos() * VSM_VOGEL_FILTER_RADIUS_TEXELS;
        let sin_rot: f32 = rot_angle.sin() * VSM_VOGEL_FILTER_RADIUS_TEXELS;
        let Self { active_depth, .. } = self;
        let mut lit_taps: f32 = 0.0;
        for &(tap_x, tap_y) in VSM_VOGEL_TAPS_16.iter() {
            let rot_x: f32 = tap_x * cos_rot - tap_y * sin_rot;
            let rot_y: f32 = tap_x * sin_rot + tap_y * cos_rot;
            let tx: usize = ((base_tx + rot_x).floor().max(0.0) as usize).min(max_idx);
            let ty: usize = ((base_ty + rot_y).floor().max(0.0) as usize).min(max_idx);
            if cmp_depth <= active_depth[ty * res + tx] {
                lit_taps += 1.0 / 16.0;
            }
        }
        Some(VSM_SHADOW_FLOOR + (1.0 - VSM_SHADOW_FLOOR) * lit_taps)
    }
}

/// Default 4-cascade Practical Split `VirtualShadowMap`.
impl Default for VirtualShadowMap {
    /// Creates a 4-cascade Practical Split `VirtualShadowMap` sized to `VSM_DEFAULT_CASCADE_RES`.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready four-cascade virtual shadow map.
    fn default() -> Self {
        Self::with_resolution(VSM_DEFAULT_CASCADE_RES)
    }
}

/// Static page cache management, Practical Split cascade fitting, and 16-tap Vogel-disk PCF sampling for `VirtualShadowMap`.
impl VirtualShadowMap {
    /// Computes the 4 Practical Split Scheme cascade split depths `[d0, d1, d2, d3]` between `near_plane` and `far_plane`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Camera near plane distance in meters.
    /// - `f32` - Maximum directional shadow distance in meters.
    /// - `f32` - Practical Split lambda in `[0.0, 1.0]` (`0.0` uniform, `1.0` logarithmic).
    ///
    /// # Returns
    ///
    /// - `[f32; VSM_CASCADE_COUNT]` - Strictly increasing far split distances for cascades `0..4`.
    #[must_use]
    pub fn compute_practical_splits(
        near_plane: f32,
        far_plane: f32,
        lambda: f32,
    ) -> [f32; VSM_CASCADE_COUNT] {
        let near_val: f32 = near_plane.max(0.1);
        let far_val: f32 = far_plane.max(near_val + 4.0);
        let blend_lambda: f32 = lambda.clamp(0.0, 1.0);
        let ratio: f32 = far_val / near_val;
        let mut splits: [f32; VSM_CASCADE_COUNT] = [0.0; VSM_CASCADE_COUNT];
        for (cascade_idx, split_slot) in splits.iter_mut().enumerate().take(VSM_CASCADE_COUNT) {
            let frac: f32 = ((cascade_idx + 1) as f32) / (VSM_CASCADE_COUNT as f32);
            let log_split: f32 = near_val * ratio.powf(frac);
            let lin_split: f32 = near_val + (far_val - near_val) * frac;
            *split_slot = lin_split + (log_split - lin_split) * blend_lambda;
        }
        splits
    }

    /// Constructs a 4-cascade `VirtualShadowMap` with all cascades sized to `resolution x resolution`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Per-cascade shadow map edge resolution in texels (`>= 32`).
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated four-cascade virtual shadow map.
    #[must_use]
    pub fn with_resolution(resolution: usize) -> Self {
        let splits: [f32; VSM_CASCADE_COUNT] =
            Self::compute_practical_splits(0.25, VSM_CSM_MAX_DISTANCE_M, VSM_CSM_LAMBDA);
        let extents: [f32; VSM_CASCADE_COUNT] = [
            VSM_CASCADE_NEAR_EXTENT_M,
            (splits[1] * 0.72).max(28.0),
            (splits[2] * 0.78).max(64.0),
            VSM_CASCADE_FAR_EXTENT_M,
        ];
        Self {
            cascades: [
                VsmCascade::new(resolution, extents[0]),
                VsmCascade::new(resolution, extents[1]),
                VsmCascade::new(resolution, extents[2]),
                VsmCascade::new(resolution, extents[3]),
            ],
            cascade_split_depths: splits,
            cached_sun_dir: Vec3::zero(),
            cached_static_epoch: u64::MAX,
            static_cache_hits: 0,
            static_rebuilds: 0,
        }
    }

    /// Returns a reference to the finest near contact cascade (`cascades[0]`).
    ///
    /// # Returns
    ///
    /// - `&VsmCascade` - Near shadow cascade reference.
    #[must_use]
    pub fn get_cascade_near(&self) -> &VsmCascade {
        &self.get_cascades()[0]
    }

    /// Returns a reference to the farthest skyline cascade (`cascades[3]`).
    ///
    /// # Returns
    ///
    /// - `&VsmCascade` - Far shadow cascade reference.
    #[must_use]
    pub fn get_cascade_far(&self) -> &VsmCascade {
        &self.get_cascades()[VSM_CASCADE_COUNT - 1]
    }

    /// Returns the column-major orthographic light view-projection matrix for cascade `cascade_idx`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Virtual shadow map reference.
    /// - `usize` - Cascade index in `0..4`.
    ///
    /// # Returns
    ///
    /// - `Mat4` - Orthographic light view-projection matrix for the requested cascade.
    #[must_use]
    pub fn cascade_light_view_proj(&self, cascade_idx: usize) -> Mat4 {
        let clamped_idx: usize = cascade_idx.min(VSM_CASCADE_COUNT - 1);
        self.get_cascades()[clamped_idx].light_view_proj()
    }

    /// Invalidates all four static shadow cascades so the next update re-rasterizes static geometry cleanly.
    pub fn invalidate(&mut self) {
        for cascade in self.get_mut_cascades().iter_mut() {
            cascade.set_static_valid(false);
        }
    }

    /// Synchronizes all four Practical-Split shadow cascades with `world`, reusing cached static pages whenever sun, static epoch, and snapped centers are unchanged.
    ///
    /// # Arguments
    ///
    /// - `&World3D` - Active 3D world supplying camera, sun, objects, and mesh library.
    pub fn update_from_world(&mut self, world: &World3D) {
        let sun_dir: Vec3 = world.get_sun().get_direction().normalize();
        let cam: Camera3D = world.get_camera();
        let cam_pos: Vec3 = cam.get_position();
        let cam_fwd: Vec3 = cam.forward();
        let near_p: f32 = cam.get_near().max(0.15);
        let far_p: f32 = cam.get_far().min(VSM_CSM_MAX_DISTANCE_M).max(near_p + 12.0);
        let splits: [f32; VSM_CASCADE_COUNT] =
            Self::compute_practical_splits(near_p, far_p, VSM_CSM_LAMBDA);
        self.set_cascade_split_depths(splits);
        let static_epoch: u64 = world.get_static_bvh_rebuilds();
        let sun_changed: bool = self.get_cached_sun_dir().dot(sun_dir) < 0.9998;
        let epoch_changed: bool = self.get_cached_static_epoch() != static_epoch;
        let mut rebuilt_any: bool = false;
        let mut hit_any: bool = false;
        let mut prev_split: f32 = near_p;
        for (cascade_idx, &split_far) in splits.iter().enumerate().take(VSM_CASCADE_COUNT) {
            let mid_dist: f32 = (prev_split + split_far) * 0.5;
            let focus_pt: Vec3 = cam_pos.add(cam_fwd.scale(mid_dist));
            prev_split = split_far;
            let cascade: &mut VsmCascade = &mut self.get_mut_cascades()[cascade_idx];
            let (snap_c, r_b, u_b, f_b): (Vec3, Vec3, Vec3, Vec3) =
                cascade.compute_snapped_basis(focus_pt, sun_dir);
            let moved: bool = cascade.get_snapped_center().sub(snap_c).length_sq() > 1.0e-3;
            let dirty_light: bool = !cascade.get_static_valid() || sun_changed;
            let dirty_world: bool = epoch_changed || moved;
            if dirty_light || dirty_world {
                cascade.set_snapped_center(snap_c);
                cascade.set_light_right(r_b);
                cascade.set_light_up(u_b);
                cascade.set_light_forward(f_b);
                cascade.rebuild_static_depth(world);
                rebuilt_any = true;
            } else {
                hit_any = true;
            }
            cascade.overlay_dynamic_depth(world);
        }
        self.set_cached_sun_dir(sun_dir);
        self.set_cached_static_epoch(static_epoch);
        if rebuilt_any {
            self.set_static_rebuilds(self.get_static_rebuilds().saturating_add(1));
        } else if hit_any {
            self.set_static_cache_hits(self.get_static_cache_hits().saturating_add(1));
        }
    }

    /// Samples multi-cascade rotated 16-tap Vogel-disk PCF shadow visibility at `world_pos` across all 4 cascades with smooth inter-cascade boundary blending.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space surface position.
    /// - `Vec3` - Unit outward surface normal.
    /// - `Vec3` - Unit directional sun vector.
    ///
    /// # Returns
    ///
    /// - `f32` - Smooth sun visibility in `[0.22, 1.0]` (`1.0` outside all four cascades).
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn sample_visibility(&self, world_pos: Vec3, normal: Vec3, sun_dir: Vec3) -> f32 {
        let cascades: &[VsmCascade; VSM_CASCADE_COUNT] = self.get_cascades();
        for cascade_idx in 0..VSM_CASCADE_COUNT {
            let cascade: &VsmCascade = &cascades[cascade_idx];
            if let Some(vis_cur) = cascade.sample_pcf(world_pos, normal, sun_dir) {
                if cascade_idx + 1 < VSM_CASCADE_COUNT {
                    let (coord_u, coord_v, _): (f32, f32, f32) =
                        cascade.project_world_point(world_pos);
                    let edge_dist: f32 = coord_u.min(1.0 - coord_u).min(coord_v.min(1.0 - coord_v));
                    if edge_dist < 0.08
                        && let Some(vis_next) =
                            cascades[cascade_idx + 1].sample_pcf(world_pos, normal, sun_dir)
                    {
                        let blend_t: f32 = ((0.08 - edge_dist) / 0.06).clamp(0.0, 1.0);
                        return vis_cur + (vis_next - vis_cur) * blend_t;
                    }
                }
                return vis_cur;
            }
        }
        1.0
    }
}