Skip to main content

euv_core/game/engine3d/lighting/
impl.rs

1use super::*;
2
3/// Constructors for `PointLight3D`.
4impl PointLight3D {
5    /// Creates a physically based 3D point light from sRGB `color`, `intensity`, and `radius`.
6    ///
7    /// # Arguments
8    ///
9    /// - `Vec3` - World-space center position.
10    /// - `Color` - sRGB emission color.
11    /// - `f32` - Luminous intensity multiplier.
12    /// - `f32` - Maximum influence radius in meters.
13    ///
14    /// # Returns
15    ///
16    /// - `Self` - Configured point light.
17    #[must_use]
18    pub fn new(position: Vec3, color: Color, intensity: f32, radius: f32) -> Self {
19        Self {
20            position,
21            color: Vec3::from_color(color),
22            intensity: intensity.max(0.0),
23            radius: radius.max(0.25),
24            cast_shadows: false,
25        }
26    }
27
28    /// Creates a physically based 3D point light from linear HDR RGB `color`, `intensity`, and `range`.
29    ///
30    /// # Arguments
31    ///
32    /// - `Vec3` - World-space center position.
33    /// - `Vec3` - Linear HDR RGB emission color.
34    /// - `f32` - Luminous intensity in candela.
35    /// - `f32` - Smooth `KHR_lights_punctual` attenuation cutoff range in meters.
36    ///
37    /// # Returns
38    ///
39    /// - `Self` - Configured point light.
40    #[must_use]
41    pub fn from_linear(position: Vec3, color: Vec3, intensity: f32, range: f32) -> Self {
42        Self {
43            position,
44            color,
45            intensity: intensity.max(0.0),
46            radius: range.max(0.25),
47            cast_shadows: false,
48        }
49    }
50
51    /// Evaluates the exact Khronos `KHR_lights_punctual` windowed inverse-square range attenuation factor.
52    ///
53    /// # Arguments
54    ///
55    /// - `f32` - Squared distance from shading point to light in square meters.
56    /// - `f32` - Maximum influence range in meters (`<= 0.0` disables range cutoff).
57    ///
58    /// # Returns
59    ///
60    /// - `f32` - Physical attenuation scalar in `[0.0, 1.0 / 1e-4]`.
61    #[cfg_attr(not(target_arch = "wasm32"), inline)]
62    #[must_use]
63    pub fn khr_attenuation(distance_sq: f32, range: f32) -> f32 {
64        let safe_dist_sq: f32 = distance_sq.max(1.0e-4);
65        if range <= 0.0 || !range.is_finite() {
66            return 1.0 / safe_dist_sq;
67        }
68        let inv_range_sq: f32 = 1.0 / (range * range).max(1.0e-4);
69        let ratio_sq: f32 = safe_dist_sq * inv_range_sq;
70        let window: f32 = (1.0 - ratio_sq * ratio_sq).clamp(0.0, 1.0);
71        (window * window) / safe_dist_sq
72    }
73}
74
75/// Constructors for `SpotLight3D`.
76impl SpotLight3D {
77    /// Creates a physically based 3D spotlight from position, direction, sRGB color, intensity, range, and cone half-angles in degrees.
78    ///
79    /// # Arguments
80    ///
81    /// - `Vec3` - World-space emitter origin.
82    /// - `Vec3` - Beam direction vector (normalized automatically).
83    /// - `Color` - sRGB emission color.
84    /// - `f32` - Luminous intensity multiplier.
85    /// - `f32` - Maximum beam range in meters.
86    /// - `(f32, f32)` - `(inner_half_angle_deg, outer_half_angle_deg)` cone angles.
87    ///
88    /// # Returns
89    ///
90    /// - `Self` - Configured spotlight.
91    #[must_use]
92    pub fn new(
93        position: Vec3,
94        direction: Vec3,
95        color: Color,
96        intensity: f32,
97        range: f32,
98        cone_deg: (f32, f32),
99    ) -> Self {
100        let (inner_deg, outer_deg): (f32, f32) = cone_deg;
101        let clamped_inner: f32 = inner_deg.clamp(1.0, 80.0);
102        let clamped_outer: f32 = outer_deg.clamp(clamped_inner + 1.0, 88.0);
103        Self {
104            position,
105            direction: direction.normalize(),
106            color: Vec3::from_color(color),
107            intensity: intensity.max(0.0),
108            range: range.max(0.5),
109            inner_cos: clamped_inner.to_radians().cos(),
110            outer_cos: clamped_outer.to_radians().cos(),
111        }
112    }
113
114    /// Creates a physically based 3D spotlight directly from linear RGB `color` and radian cone angles (`KHR_lights_punctual`).
115    ///
116    /// # Arguments
117    ///
118    /// - `Vec3` - World-space emitter origin.
119    /// - `Vec3` - Beam direction vector.
120    /// - `Vec3` - Linear HDR RGB emission color.
121    /// - `f32` - Luminous intensity in candela.
122    /// - `f32` - Maximum attenuation range in meters.
123    /// - `(f32, f32)` - `(inner_cone_rad, outer_cone_rad)` half-angles in radians.
124    ///
125    /// # Returns
126    ///
127    /// - `Self` - Configured spotlight.
128    #[must_use]
129    pub fn from_linear(
130        position: Vec3,
131        direction: Vec3,
132        color: Vec3,
133        intensity: f32,
134        range: f32,
135        cone_rad: (f32, f32),
136    ) -> Self {
137        let (inner_rad, outer_rad): (f32, f32) = cone_rad;
138        let clamped_inner: f32 = inner_rad.clamp(0.0, FRAC_PI_2 - 0.02);
139        let clamped_outer: f32 = outer_rad.clamp(clamped_inner + 0.005, FRAC_PI_2 - 0.01);
140        Self {
141            position,
142            direction: direction.normalize(),
143            color,
144            intensity: intensity.max(0.0),
145            range: range.max(0.5),
146            inner_cos: clamped_inner.cos(),
147            outer_cos: clamped_outer.cos(),
148        }
149    }
150}
151
152/// Construction and representative-point GGX / LTC-aligned evaluation for `AreaLight3D`.
153impl AreaLight3D {
154    /// Constructs a rectangular Blender `AreaLight3D` oriented along `direction`.
155    ///
156    /// # Arguments
157    ///
158    /// - `Vec3` - World-space emitter center.
159    /// - `Vec3` - Unit emitting normal pointing from emitter into scene.
160    /// - `Vec3` - Linear HDR RGB emission color.
161    /// - `f32` - Luminous intensity multiplier.
162    /// - `(f32, f32)` - Aperture `(width, height)` in meters.
163    /// - `f32` - Maximum attenuation cutoff range in meters.
164    ///
165    /// # Returns
166    ///
167    /// - `Self` - Configured rectangular area light.
168    #[must_use]
169    pub fn new_rect(
170        position: Vec3,
171        direction: Vec3,
172        color: Vec3,
173        intensity: f32,
174        dimensions: (f32, f32),
175        range: f32,
176    ) -> Self {
177        let dir_unit: Vec3 = direction.normalize();
178        let ref_up: Vec3 = if dir_unit.get_y().abs() > 0.95 {
179            Vec3::new(0.0, 0.0, 1.0)
180        } else {
181            Vec3::new(0.0, 1.0, 0.0)
182        };
183        let right: Vec3 = ref_up.cross(dir_unit).normalize();
184        let up: Vec3 = dir_unit.cross(right).normalize();
185        Self {
186            position,
187            direction: dir_unit,
188            right,
189            up,
190            color,
191            intensity: intensity.max(0.0),
192            width: dimensions.0.max(0.05),
193            height: dimensions.1.max(0.05),
194            range: range.max(1.0),
195            shape: AreaLightShape3D::Rectangle,
196            two_sided: false,
197        }
198    }
199
200    /// Constructs a disk Blender `AreaLight3D` oriented along `direction`.
201    ///
202    /// # Arguments
203    ///
204    /// - `Vec3` - World-space emitter center.
205    /// - `Vec3` - Unit emitting normal pointing from emitter into scene.
206    /// - `Vec3` - Linear HDR RGB emission color.
207    /// - `f32` - Luminous intensity multiplier.
208    /// - `f32` - Disk emitter diameter in meters.
209    /// - `f32` - Maximum attenuation cutoff range in meters.
210    ///
211    /// # Returns
212    ///
213    /// - `Self` - Configured disk area light.
214    #[must_use]
215    pub fn new_disk(
216        position: Vec3,
217        direction: Vec3,
218        color: Vec3,
219        intensity: f32,
220        diameter: f32,
221        range: f32,
222    ) -> Self {
223        let mut light: Self = Self::new_rect(
224            position,
225            direction,
226            color,
227            intensity,
228            (diameter, diameter),
229            range,
230        );
231        light.set_shape(AreaLightShape3D::Disk);
232        light
233    }
234
235    /// Evaluates physically based diffuse irradiance and Karis representative-point GGX specular contribution for this rectangular or disk area light.
236    ///
237    /// # Arguments
238    ///
239    /// - `&Self` - Area light reference.
240    /// - `Vec3` - World-space surface shading position.
241    /// - `Vec3` - Unit outward surface normal.
242    /// - `Vec3` - Unit view direction pointing from surface toward camera.
243    /// - `(Vec3, Vec3, f32, f32)` - `(albedo, f0_specular, perceptual_roughness, diffuse_scale)`.
244    ///
245    /// # Returns
246    ///
247    /// - `Vec3` - Linear HDR direct radiance contributed by this area light.
248    #[must_use]
249    pub fn evaluate_pbr(
250        &self,
251        world_pos: Vec3,
252        normal: Vec3,
253        view_dir: Vec3,
254        material_terms: (Vec3, Vec3, f32, f32),
255    ) -> Vec3 {
256        let intensity: f32 = self.get_intensity();
257        if intensity <= 1.0e-5 {
258            return Vec3::zero();
259        }
260        let light_pos: Vec3 = self.get_position();
261        let light_dir: Vec3 = self.get_direction();
262        let light_right: Vec3 = self.get_right();
263        let light_up: Vec3 = self.get_up();
264        let half_w: f32 = self.get_width() * 0.5;
265        let half_h: f32 = self.get_height() * 0.5;
266        let from_light: Vec3 = world_pos.sub(light_pos);
267        let plane_dist: f32 = from_light.dot(light_dir);
268        if !self.get_two_sided() && plane_dist <= 0.0 {
269            return Vec3::zero();
270        }
271        let center_dist_sq: f32 = from_light.length_sq();
272        let range_val: f32 = self.get_range();
273        if center_dist_sq >= range_val * range_val {
274            return Vec3::zero();
275        }
276        let (albedo, f0, roughness, diffuse_scale): (Vec3, Vec3, f32, f32) = material_terms;
277        let clamped_rough: f32 = roughness.clamp(0.04, 1.0);
278        let alpha: f32 = clamped_rough * clamped_rough;
279        let refl_dir: Vec3 = view_dir.scale(-1.0).reflect(normal).normalize();
280        let r_dot_ldir: f32 = refl_dir.dot(light_dir);
281        let hit_local: Vec3 = if r_dot_ldir.abs() > 1.0e-4 {
282            let ray_t: f32 = (-plane_dist / r_dot_ldir).max(0.0);
283            let plane_hit: Vec3 = world_pos.add(refl_dir.scale(ray_t));
284            plane_hit.sub(light_pos)
285        } else {
286            from_light
287        };
288        let raw_u: f32 = hit_local.dot(light_right);
289        let raw_v: f32 = hit_local.dot(light_up);
290        let (clamped_u, clamped_v): (f32, f32) = match self.get_shape() {
291            AreaLightShape3D::Rectangle => {
292                (raw_u.clamp(-half_w, half_w), raw_v.clamp(-half_h, half_h))
293            }
294            AreaLightShape3D::Disk => {
295                let norm_u: f32 = raw_u / half_w.max(1.0e-4);
296                let norm_v: f32 = raw_v / half_h.max(1.0e-4);
297                let rad_sq: f32 = norm_u * norm_u + norm_v * norm_v;
298                if rad_sq > 1.0 {
299                    let inv_rad: f32 = 1.0 / rad_sq.sqrt();
300                    (raw_u * inv_rad, raw_v * inv_rad)
301                } else {
302                    (raw_u, raw_v)
303                }
304            }
305        };
306        let rep_point: Vec3 = light_pos
307            .add(light_right.scale(clamped_u))
308            .add(light_up.scale(clamped_v));
309        let to_rep: Vec3 = rep_point.sub(world_pos);
310        let rep_dist_sq: f32 = to_rep.length_sq().max(1.0e-4);
311        let rep_dist: f32 = rep_dist_sq.sqrt();
312        let spec_l: Vec3 = to_rep.scale(1.0 / rep_dist);
313        let n_dot_l_spec: f32 = normal.dot(spec_l).max(0.0);
314        let to_center: Vec3 = light_pos.sub(world_pos);
315        let center_dist: f32 = center_dist_sq.max(1.0e-4).sqrt();
316        let diff_l: Vec3 = to_center.scale(1.0 / center_dist);
317        let emitter_facing: f32 = if self.get_two_sided() {
318            diff_l.dot(light_dir).abs()
319        } else {
320            (-diff_l.dot(light_dir)).max(0.0)
321        };
322        let n_dot_l_diff: f32 = normal.dot(diff_l).max(0.0);
323        let emitter_area: f32 = match self.get_shape() {
324            AreaLightShape3D::Rectangle => self.get_width() * self.get_height(),
325            AreaLightShape3D::Disk => PI * half_w * half_h,
326        };
327        let solid_angle: f32 =
328            (emitter_area * emitter_facing) / (center_dist_sq + emitter_area / PI).max(1.0e-4);
329        let range_ratio_sq: f32 = center_dist_sq / (range_val * range_val).max(1.0e-4);
330        let range_win: f32 = (1.0 - range_ratio_sq * range_ratio_sq).clamp(0.0, 1.0);
331        let window_sq: f32 = range_win * range_win;
332        let diffuse_rgb: Vec3 =
333            albedo.scale((diffuse_scale / PI) * n_dot_l_diff * solid_angle.min(PI) * window_sq);
334        let spec_rgb: Vec3 = if n_dot_l_spec > 0.0 {
335            let equiv_rad: f32 = (emitter_area / PI).sqrt();
336            let alpha_prime: f32 = (alpha + equiv_rad / (2.0 * rep_dist)).clamp(0.04, 1.0);
337            let alpha_p2: f32 = alpha_prime * alpha_prime;
338            let energy_norm: f32 = (alpha / alpha_prime) * (alpha / alpha_prime);
339            let half_vec: Vec3 = spec_l.add(view_dir).normalize();
340            let n_dot_h: f32 = normal.dot(half_vec).max(0.0);
341            let n_dot_v: f32 = normal.dot(view_dir).max(0.04);
342            let v_dot_h: f32 = view_dir.dot(half_vec).clamp(0.0, 1.0);
343            let ggx_den: f32 = n_dot_h * n_dot_h * (alpha_p2 - 1.0) + 1.0;
344            let ggx_d: f32 = (alpha_p2 * energy_norm) / (PI * ggx_den * ggx_den).max(1.0e-4);
345            let om_vh: f32 = 1.0 - v_dot_h;
346            let pow5: f32 = om_vh * om_vh * om_vh * om_vh * om_vh;
347            let fresnel: Vec3 = f0.add(Vec3::splat(1.0).sub(f0).scale(pow5));
348            let spec_atten: f32 = PointLight3D::khr_attenuation(rep_dist_sq, range_val);
349            let spec_scalar: f32 = ((ggx_d * 0.25) / (n_dot_l_spec.max(0.08) + n_dot_v)).min(6.0);
350            fresnel.scale(spec_scalar * n_dot_l_spec * spec_atten * emitter_area.max(0.1))
351        } else {
352            Vec3::zero()
353        };
354        let radiance: Vec3 = self.get_color().scale(intensity);
355        diffuse_rgb.add(spec_rgb).mul(radiance)
356    }
357}
358
359/// Default pre-allocated 16x9x16 `LightClusterGrid3D`.
360impl Default for LightClusterGrid3D {
361    /// Creates an empty pre-allocated `LightClusterGrid3D` ready for zero-allocation per-frame light binning.
362    ///
363    /// # Returns
364    ///
365    /// - `Self` - Ready clustered light grid.
366    fn default() -> Self {
367        let total_froxels: usize =
368            LIGHT_CLUSTER_GRID_X * LIGHT_CLUSTER_GRID_Y * LIGHT_CLUSTER_GRID_Z;
369        Self {
370            near_plane: 0.3,
371            far_plane: 420.0,
372            log_depth_scale: (LIGHT_CLUSTER_GRID_Z as f32) / (420.0_f32 / 0.3_f32).ln(),
373            depth_slice_max: [420.0; LIGHT_CLUSTER_GRID_Z],
374            active_light_count: 0,
375            total_assignments: 0,
376            packed_lights: Vec::with_capacity(LIGHT_CLUSTER_MAX_LIGHTS),
377            cluster_counts: vec![0_u16; total_froxels],
378            cluster_indices: vec![0_u16; total_froxels * LIGHT_CLUSTER_MAX_PER_FROXEL],
379        }
380    }
381}
382
383/// 3D frustum froxel binning and Cook-Torrance GGX local light evaluation for `LightClusterGrid3D`.
384impl LightClusterGrid3D {
385    /// Returns whether any local point or spot lights are active in the current frame.
386    ///
387    /// # Returns
388    ///
389    /// - `bool` - `true` when at least one local light is binned.
390    #[cfg_attr(not(target_arch = "wasm32"), inline)]
391    #[must_use]
392    pub fn has_active_lights(&self) -> bool {
393        self.get_active_light_count() > 0
394    }
395
396    /// Bins all `point_lights` and `spot_lights` into the 16x9x16 logarithmic-Z camera frustum grid without heap allocations.
397    ///
398    /// # Arguments
399    ///
400    /// - `&Camera3D` - Active 3D perspective camera.
401    /// - `f32` - Viewport width-to-height aspect ratio.
402    /// - `&[PointLight3D]` - Active world-space point lights.
403    /// - `&[SpotLight3D]` - Active world-space spotlights.
404    pub fn build_clusters(
405        &mut self,
406        camera: &Camera3D,
407        aspect: f32,
408        point_lights: &[PointLight3D],
409        spot_lights: &[SpotLight3D],
410    ) {
411        let near_p: f32 = camera.get_near().max(0.15);
412        let far_p: f32 = camera.get_far().max(near_p + 1.0);
413        let log_scale: f32 = (LIGHT_CLUSTER_GRID_Z as f32) / (far_p / near_p).ln().max(1.0e-4);
414        self.set_near_plane(near_p);
415        self.set_far_plane(far_p);
416        self.set_log_depth_scale(log_scale);
417        let depth_ratio: f32 = far_p / near_p;
418        {
419            let Self {
420                depth_slice_max, ..
421            } = self;
422            for (slice_idx, slot) in depth_slice_max.iter_mut().enumerate() {
423                let frac: f32 = ((slice_idx + 1) as f32) / (LIGHT_CLUSTER_GRID_Z as f32);
424                *slot = near_p * depth_ratio.powf(frac);
425            }
426        }
427        let cam_pos: Vec3 = camera.get_position();
428        let cam_fwd: Vec3 = camera.forward();
429        let cam_right: Vec3 = camera.right();
430        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
431        let half_h: f32 = (camera.get_fov_deg().to_radians() * 0.5).tan().max(0.05);
432        let half_w: f32 = half_h * aspect.max(0.1);
433        let inv_half_w: f32 = 1.0 / half_w;
434        let inv_half_h: f32 = 1.0 / half_h;
435        let mut assignments: usize = 0;
436        let active_count: usize = {
437            let Self {
438                packed_lights,
439                cluster_counts,
440                cluster_indices,
441                ..
442            } = self;
443            packed_lights.clear();
444            if point_lights.is_empty() && spot_lights.is_empty() {
445                cluster_counts.fill(0);
446                0
447            } else {
448                cluster_counts.fill(0);
449                for point_light in point_lights.iter() {
450                    if packed_lights.len() >= LIGHT_CLUSTER_MAX_LIGHTS {
451                        break;
452                    }
453                    let rad: f32 = point_light.get_radius().max(0.25);
454                    let intensity: f32 = point_light.get_intensity();
455                    if intensity <= 1.0e-4 {
456                        continue;
457                    }
458                    let light_pos: Vec3 = point_light.get_position();
459                    let col: Vec3 = point_light.get_color().scale(intensity);
460                    let light_idx: u16 = packed_lights.len() as u16;
461                    packed_lights.push(PackedLocalLight {
462                        pos_inv_r2: [
463                            light_pos.get_x(),
464                            light_pos.get_y(),
465                            light_pos.get_z(),
466                            1.0 / (rad * rad),
467                        ],
468                        radiance_radius: [col.get_x(), col.get_y(), col.get_z(), rad],
469                        dir_outer_cos: [0.0, -1.0, 0.0, -2.0],
470                        inv_cone_span: [0.0; 4],
471                    });
472                    assignments += Self::bin_sphere_into_froxels(
473                        (cam_pos, cam_right, cam_up, cam_fwd),
474                        (inv_half_w, inv_half_h, near_p, far_p, log_scale),
475                        (light_pos, rad, light_idx),
476                        cluster_counts,
477                        cluster_indices,
478                    );
479                }
480                for spot_light in spot_lights.iter() {
481                    if packed_lights.len() >= LIGHT_CLUSTER_MAX_LIGHTS {
482                        break;
483                    }
484                    let range: f32 = spot_light.get_range().max(0.5);
485                    let intensity: f32 = spot_light.get_intensity();
486                    if intensity <= 1.0e-4 {
487                        continue;
488                    }
489                    let light_pos: Vec3 = spot_light.get_position();
490                    let light_dir: Vec3 = spot_light.get_direction().normalize();
491                    let col: Vec3 = spot_light.get_color().scale(intensity);
492                    let outer_cos: f32 = spot_light.get_outer_cos();
493                    let span: f32 = (spot_light.get_inner_cos() - outer_cos).max(SPOT_CONE_MIN_EPS);
494                    let light_idx: u16 = packed_lights.len() as u16;
495                    packed_lights.push(PackedLocalLight {
496                        pos_inv_r2: [
497                            light_pos.get_x(),
498                            light_pos.get_y(),
499                            light_pos.get_z(),
500                            1.0 / (range * range),
501                        ],
502                        radiance_radius: [col.get_x(), col.get_y(), col.get_z(), range],
503                        dir_outer_cos: [
504                            light_dir.get_x(),
505                            light_dir.get_y(),
506                            light_dir.get_z(),
507                            outer_cos,
508                        ],
509                        inv_cone_span: [1.0 / span, 0.0, 0.0, 0.0],
510                    });
511                    let cone_center: Vec3 = light_pos.add(light_dir.scale(range * 0.45));
512                    let cone_bound_rad: f32 = range * 0.45;
513                    assignments += Self::bin_sphere_into_froxels(
514                        (cam_pos, cam_right, cam_up, cam_fwd),
515                        (inv_half_w, inv_half_h, near_p, far_p, log_scale),
516                        (cone_center, cone_bound_rad, light_idx),
517                        cluster_counts,
518                        cluster_indices,
519                    );
520                }
521                packed_lights.len()
522            }
523        };
524        self.set_active_light_count(active_count);
525        self.set_total_assignments(assignments);
526    }
527
528    /// Bins a single light bounding sphere into all overlapped `(x, y, z)` froxels and returns the assignment count.
529    ///
530    /// # Arguments
531    ///
532    /// - `(Vec3, Vec3, Vec3, Vec3)` - Camera `(position, right, up, forward)` basis.
533    /// - `(f32, f32, f32, f32, f32)` - `(inv_half_w, inv_half_h, near_p, far_p, log_scale)` frustum parameters.
534    /// - `(Vec3, f32, u16)` - `(sphere_center, sphere_radius, light_index)`.
535    /// - `&mut [u16]` - Mutable froxel count table.
536    /// - `&mut [u16]` - Mutable flat froxel index array.
537    ///
538    /// # Returns
539    ///
540    /// - `usize` - Number of froxels updated for this light.
541    fn bin_sphere_into_froxels(
542        cam_basis: (Vec3, Vec3, Vec3, Vec3),
543        frustum_params: (f32, f32, f32, f32, f32),
544        sphere: (Vec3, f32, u16),
545        cluster_counts: &mut [u16],
546        cluster_indices: &mut [u16],
547    ) -> usize {
548        let (cam_pos, cam_right, cam_up, cam_fwd): (Vec3, Vec3, Vec3, Vec3) = cam_basis;
549        let (inv_half_w, inv_half_h, near_p, far_p, log_scale): (f32, f32, f32, f32, f32) =
550            frustum_params;
551        let (center, radius, light_idx): (Vec3, f32, u16) = sphere;
552        let rel: Vec3 = center.sub(cam_pos);
553        let vz: f32 = rel.dot(cam_fwd);
554        let z_min: f32 = vz - radius;
555        let z_max: f32 = vz + radius;
556        if z_max <= near_p || z_min >= far_p {
557            return 0;
558        }
559        let vx: f32 = rel.dot(cam_right);
560        let vy: f32 = rel.dot(cam_up);
561        let z_proj: f32 = vz.max(near_p);
562        let inv_z: f32 = 1.0 / z_proj;
563        let ndc_cx: f32 = vx * inv_z * inv_half_w;
564        let ndc_cy: f32 = vy * inv_z * inv_half_h;
565        let pad_x: f32 = if z_min <= near_p {
566            (radius / vz.max(2.0) * inv_half_w).clamp(0.35, 1.35)
567        } else {
568            (radius / z_min) * inv_half_w
569        };
570        let pad_y: f32 = if z_min <= near_p {
571            (radius / vz.max(2.0) * inv_half_h).clamp(0.35, 1.35)
572        } else {
573            (radius / z_min) * inv_half_h
574        };
575        let min_u: f32 = (ndc_cx - pad_x) * 0.5 + 0.5;
576        let max_u: f32 = (ndc_cx + pad_x) * 0.5 + 0.5;
577        let min_v: f32 = 0.5 - (ndc_cy + pad_y) * 0.5;
578        let max_v: f32 = 0.5 - (ndc_cy - pad_y) * 0.5;
579        let out_u: bool = max_u < 0.0 || min_u > 1.0;
580        let out_v: bool = max_v < 0.0 || min_v > 1.0;
581        if out_u || out_v {
582            return 0;
583        }
584        let gx_max: usize = LIGHT_CLUSTER_GRID_X - 1;
585        let gy_max: usize = LIGHT_CLUSTER_GRID_Y - 1;
586        let gz_max: usize = LIGHT_CLUSTER_GRID_Z - 1;
587        let cx0: usize =
588            ((min_u.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_X as f32)).floor() as usize).min(gx_max);
589        let cx1: usize =
590            ((max_u.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_X as f32)).floor() as usize).min(gx_max);
591        let cy0: usize =
592            ((min_v.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_Y as f32)).floor() as usize).min(gy_max);
593        let cy1: usize =
594            ((max_v.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_Y as f32)).floor() as usize).min(gy_max);
595        let cz0: usize = ((((z_min.max(near_p) / near_p).ln()) * log_scale)
596            .floor()
597            .max(0.0) as usize)
598            .min(gz_max);
599        let cz1: usize = ((((z_max.min(far_p) / near_p).ln()) * log_scale)
600            .floor()
601            .max(0.0) as usize)
602            .min(gz_max);
603        let slice_stride: usize = LIGHT_CLUSTER_GRID_X * LIGHT_CLUSTER_GRID_Y;
604        let mut count_added: usize = 0;
605        for cz in cz0..=cz1 {
606            let z_off: usize = cz * slice_stride;
607            for cy in cy0..=cy1 {
608                let y_off: usize = z_off + cy * LIGHT_CLUSTER_GRID_X;
609                for cx in cx0..=cx1 {
610                    let froxel: usize = y_off + cx;
611                    let cur: usize = cluster_counts[froxel] as usize;
612                    if cur < LIGHT_CLUSTER_MAX_PER_FROXEL {
613                        cluster_indices[froxel * LIGHT_CLUSTER_MAX_PER_FROXEL + cur] = light_idx;
614                        cluster_counts[froxel] = (cur + 1) as u16;
615                        count_added += 1;
616                    }
617                }
618            }
619        }
620        count_added
621    }
622
623    /// 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.
624    ///
625    /// # Arguments
626    ///
627    /// - `Vec3` - Pixel world-space surface position.
628    /// - `Vec3` - Unit outward surface normal.
629    /// - `Vec3` - Unit view direction pointing from surface toward camera.
630    /// - `(Vec3, Vec3, f32, f32)` - `(base_albedo, f0_specular, alpha2_ggx, diffuse_scale)`.
631    /// - `(f32, f32, f32)` - `(uv_x, uv_y, linear_depth)` normalized screen UV in `[0, 1]` and camera depth.
632    ///
633    /// # Returns
634    ///
635    /// - `Vec3` - Summed linear HDR direct radiance contributed by local clustered lights.
636    #[cfg_attr(not(target_arch = "wasm32"), inline)]
637    #[must_use]
638    pub fn evaluate_pixel(
639        &self,
640        world_pos: Vec3,
641        normal: Vec3,
642        view_dir: Vec3,
643        material_terms: (Vec3, Vec3, f32, f32),
644        screen_depth: (f32, f32, f32),
645    ) -> Vec3 {
646        if self.get_active_light_count() == 0 {
647            return Vec3::zero();
648        }
649        let (uv_x, uv_y, linear_depth): (f32, f32, f32) = screen_depth;
650        let near_p: f32 = self.get_near_plane();
651        if linear_depth < near_p || linear_depth > self.get_far_plane() {
652            return Vec3::zero();
653        }
654        let cx: usize = ((uv_x.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_X as f32)) as usize)
655            .min(LIGHT_CLUSTER_GRID_X - 1);
656        let cy: usize = ((uv_y.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_Y as f32)) as usize)
657            .min(LIGHT_CLUSTER_GRID_Y - 1);
658        let cz: usize = ((((linear_depth / near_p).ln()) * self.get_log_depth_scale()).max(0.0)
659            as usize)
660            .min(LIGHT_CLUSTER_GRID_Z - 1);
661        let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
662        let Self {
663            packed_lights,
664            cluster_counts,
665            cluster_indices,
666            ..
667        } = self;
668        let light_count: usize = cluster_counts[froxel] as usize;
669        if light_count == 0 {
670            return Vec3::zero();
671        }
672        let (albedo, f0, alpha2, diffuse_scale): (Vec3, Vec3, f32, f32) = material_terms;
673        let n_dot_v: f32 = normal.dot(view_dir).max(0.04);
674        let idx_base: usize = froxel * LIGHT_CLUSTER_MAX_PER_FROXEL;
675        let mut accum: Vec3 = Vec3::zero();
676        for slot in 0..light_count {
677            let light: PackedLocalLight = packed_lights[cluster_indices[idx_base + slot] as usize];
678            let to_light: Vec3 = Vec3::new(
679                light.pos_inv_r2[0] - world_pos.get_x(),
680                light.pos_inv_r2[1] - world_pos.get_y(),
681                light.pos_inv_r2[2] - world_pos.get_z(),
682            );
683            let dist_sq: f32 = to_light.length_sq();
684            let ratio_sq: f32 = dist_sq * light.pos_inv_r2[3];
685            if ratio_sq >= 1.0 {
686                continue;
687            }
688            let inv_dist: f32 = 1.0 / dist_sq.max(1.0e-4).sqrt();
689            let light_dir: Vec3 = to_light.scale(inv_dist);
690            let n_dot_l: f32 = normal.dot(light_dir);
691            if n_dot_l <= 0.0 {
692                continue;
693            }
694            let mut spot_factor: f32 = 1.0;
695            if light.dir_outer_cos[3] > -1.5 {
696                let beam_dir: Vec3 = Vec3::new(
697                    light.dir_outer_cos[0],
698                    light.dir_outer_cos[1],
699                    light.dir_outer_cos[2],
700                );
701                let cos_theta: f32 = (-light_dir.get_x()) * beam_dir.get_x()
702                    + (-light_dir.get_y()) * beam_dir.get_y()
703                    + (-light_dir.get_z()) * beam_dir.get_z();
704                if cos_theta <= light.dir_outer_cos[3] {
705                    continue;
706                }
707                let raw_spot: f32 =
708                    ((cos_theta - light.dir_outer_cos[3]) * light.inv_cone_span[0]).clamp(0.0, 1.0);
709                spot_factor = raw_spot * raw_spot;
710            }
711            let window: f32 = (1.0 - ratio_sq * ratio_sq).clamp(0.0, 1.0);
712            let atten: f32 = (window * window * spot_factor) / dist_sq.max(1.0e-4);
713            let half_vec: Vec3 = light_dir.add(view_dir).normalize();
714            let n_dot_h: f32 = normal.dot(half_vec).max(0.0);
715            let v_dot_h: f32 = view_dir.dot(half_vec).clamp(0.0, 1.0);
716            let denom: f32 = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
717            let ggx_d: f32 = alpha2 / (PI * denom * denom).max(1.0e-4);
718            let one_minus_vh: f32 = 1.0 - v_dot_h;
719            let pow5: f32 =
720                one_minus_vh * one_minus_vh * one_minus_vh * one_minus_vh * one_minus_vh;
721            let fresnel: Vec3 = f0.add(Vec3::splat(1.0).sub(f0).scale(pow5));
722            let spec_scalar: f32 = (ggx_d * 0.25) / (n_dot_l.max(0.08) + n_dot_v);
723            let diffuse_rgb: Vec3 = albedo.scale(diffuse_scale * (1.0 / PI));
724            let brdf_rgb: Vec3 = diffuse_rgb.add(fresnel.scale(spec_scalar.min(4.0)));
725            let light_rad: Vec3 = Vec3::new(
726                light.radiance_radius[0],
727                light.radiance_radius[1],
728                light.radiance_radius[2],
729            );
730            accum = accum.add(brdf_rgb.mul(light_rad).scale(n_dot_l * atten));
731        }
732        accum
733    }
734
735    /// Evaluates fast Lambertian linear-HDR local irradiance from the 3D froxel grid without `ln()` or GGX specular overhead (tuned for coarse deferred probe injection).
736    ///
737    /// # Arguments
738    ///
739    /// - `Vec3` - World-space surface position.
740    /// - `Vec3` - Unit outward surface normal.
741    /// - `(f32, f32, f32)` - `(uv_x, uv_y, linear_depth)` normalized screen UV in `[0, 1]` and camera depth.
742    ///
743    /// # Returns
744    ///
745    /// - `Vec3` - Summed linear HDR local diffuse irradiance RGB.
746    #[must_use]
747    pub fn evaluate_irradiance_fast(
748        &self,
749        world_pos: Vec3,
750        normal: Vec3,
751        screen_depth: (f32, f32, f32),
752    ) -> Vec3 {
753        if self.get_active_light_count() == 0 {
754            return Vec3::zero();
755        }
756        let (uv_x, uv_y, linear_depth): (f32, f32, f32) = screen_depth;
757        if linear_depth < self.get_near_plane() || linear_depth > self.get_far_plane() {
758            return Vec3::zero();
759        }
760        let cx: usize = ((uv_x.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_X as f32)) as usize)
761            .min(LIGHT_CLUSTER_GRID_X - 1);
762        let cy: usize = ((uv_y.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_Y as f32)) as usize)
763            .min(LIGHT_CLUSTER_GRID_Y - 1);
764        let Self {
765            depth_slice_max,
766            packed_lights,
767            cluster_counts,
768            cluster_indices,
769            ..
770        } = self;
771        let mut cz: usize = 0;
772        if linear_depth > depth_slice_max[7] {
773            cz = 8;
774        }
775        if linear_depth > depth_slice_max[cz + 3] {
776            cz += 4;
777        }
778        if linear_depth > depth_slice_max[cz + 1] {
779            cz += 2;
780        }
781        if linear_depth > depth_slice_max[cz] {
782            cz += 1;
783        }
784        let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
785        let light_count: usize = cluster_counts[froxel] as usize;
786        if light_count == 0 {
787            return Vec3::zero();
788        }
789        let idx_base: usize = froxel * LIGHT_CLUSTER_MAX_PER_FROXEL;
790        let mut accum_r: f32 = 0.0;
791        let mut accum_g: f32 = 0.0;
792        let mut accum_b: f32 = 0.0;
793        let wx: f32 = world_pos.get_x();
794        let wy: f32 = world_pos.get_y();
795        let wz: f32 = world_pos.get_z();
796        let nx: f32 = normal.get_x();
797        let ny: f32 = normal.get_y();
798        let nz: f32 = normal.get_z();
799        for slot in 0..light_count {
800            let light: PackedLocalLight = packed_lights[cluster_indices[idx_base + slot] as usize];
801            let dx: f32 = light.pos_inv_r2[0] - wx;
802            let dy: f32 = light.pos_inv_r2[1] - wy;
803            let dz: f32 = light.pos_inv_r2[2] - wz;
804            let dist_sq: f32 = dx.mul_add(dx, dy.mul_add(dy, dz * dz));
805            let ratio_sq: f32 = dist_sq * light.pos_inv_r2[3];
806            if ratio_sq >= 1.0 {
807                continue;
808            }
809            let ndotl_raw: f32 = dx.mul_add(nx, dy.mul_add(ny, dz * nz));
810            if ndotl_raw <= 0.0 {
811                continue;
812            }
813            let inv_dist: f32 = 1.0 / dist_sq.max(1.0e-4).sqrt();
814            let mut spot_factor: f32 = 1.0;
815            if light.dir_outer_cos[3] > -1.5 {
816                let cos_theta: f32 = -(dx * light.dir_outer_cos[0]
817                    + dy * light.dir_outer_cos[1]
818                    + dz * light.dir_outer_cos[2])
819                    * inv_dist;
820                if cos_theta <= light.dir_outer_cos[3] {
821                    continue;
822                }
823                let raw_spot: f32 =
824                    ((cos_theta - light.dir_outer_cos[3]) * light.inv_cone_span[0]).clamp(0.0, 1.0);
825                spot_factor = raw_spot * raw_spot;
826            }
827            let window: f32 = (1.0 - ratio_sq * ratio_sq).max(0.0);
828            let scale: f32 =
829                (window * window * spot_factor * ndotl_raw * inv_dist) / (dist_sq + 1.0);
830            accum_r = light.radiance_radius[0].mul_add(scale, accum_r);
831            accum_g = light.radiance_radius[1].mul_add(scale, accum_g);
832            accum_b = light.radiance_radius[2].mul_add(scale, accum_b);
833        }
834        Vec3::new(accum_r, accum_g, accum_b)
835    }
836
837    /// Returns the number of local lights assigned to a specific 3D froxel `(cx, cy, cz)`.
838    ///
839    /// # Arguments
840    ///
841    /// - `usize` - Froxel X coordinate in `0..16`.
842    /// - `usize` - Froxel Y coordinate in `0..9`.
843    /// - `usize` - Froxel Z coordinate in `0..16`.
844    ///
845    /// # Returns
846    ///
847    /// - `usize` - Count of binned lights in that froxel.
848    #[must_use]
849    pub fn froxel_light_count(&self, cx: usize, cy: usize, cz: usize) -> usize {
850        let out_xy: bool = cx >= LIGHT_CLUSTER_GRID_X || cy >= LIGHT_CLUSTER_GRID_Y;
851        if out_xy || cz >= LIGHT_CLUSTER_GRID_Z {
852            return 0;
853        }
854        let Self { cluster_counts, .. } = self;
855        let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
856        cluster_counts[froxel] as usize
857    }
858}
859
860/// Cascade construction, orthographic shadow rasterization, and PCF sampling for `VsmCascade`.
861impl VsmCascade {
862    /// Creates a new `VsmCascade` with `resolution x resolution` depth storage and `half_extent_m` world radius.
863    ///
864    /// # Arguments
865    ///
866    /// - `usize` - Shadow map edge resolution in texels (`>= 32`).
867    /// - `f32` - World-space half-extent in meters.
868    ///
869    /// # Returns
870    ///
871    /// - `Self` - Pre-allocated VSM cascade.
872    #[must_use]
873    pub fn new(resolution: usize, half_extent_m: f32) -> Self {
874        let res: usize = resolution.max(32);
875        let total: usize = res * res;
876        Self {
877            resolution: res,
878            half_extent_m: half_extent_m.max(8.0),
879            snapped_center: Vec3::zero(),
880            light_right: Vec3::new(1.0, 0.0, 0.0),
881            light_up: Vec3::new(0.0, 0.0, 1.0),
882            light_forward: Vec3::new(0.0, 1.0, 0.0),
883            depth_min: -160.0,
884            depth_max: 160.0,
885            static_valid: false,
886            static_depth: vec![1.0; total],
887            active_depth: vec![1.0; total],
888        }
889    }
890
891    /// Computes texel-snapped light-space orthonormal basis and center for `focus_pos` and `sun_dir`.
892    ///
893    /// # Arguments
894    ///
895    /// - `Vec3` - Camera focus point in world space.
896    /// - `Vec3` - Unit vector pointing toward the directional sun.
897    ///
898    /// # Returns
899    ///
900    /// - `(Vec3, Vec3, Vec3, Vec3)` - `(snapped_center, light_right, light_up, light_forward)`.
901    #[must_use]
902    fn compute_snapped_basis(&self, focus_pos: Vec3, sun_dir: Vec3) -> (Vec3, Vec3, Vec3, Vec3) {
903        let fwd: Vec3 = sun_dir.normalize();
904        let ref_up: Vec3 = if fwd.get_y().abs() > 0.95 {
905            Vec3::new(0.0, 0.0, 1.0)
906        } else {
907            Vec3::new(0.0, 1.0, 0.0)
908        };
909        let right: Vec3 = ref_up.cross(fwd).normalize();
910        let up: Vec3 = fwd.cross(right).normalize();
911        let texel_world: f32 = (self.get_half_extent_m() * 2.0) / (self.get_resolution() as f32);
912        let snap_step: f32 = (texel_world * 4.0).max(0.25);
913        let proj_r: f32 = (focus_pos.dot(right) / snap_step).floor() * snap_step;
914        let proj_u: f32 = (focus_pos.dot(up) / snap_step).floor() * snap_step;
915        let proj_f: f32 = (focus_pos.dot(fwd) / snap_step).floor() * snap_step;
916        let snapped: Vec3 = right
917            .scale(proj_r)
918            .add(up.scale(proj_u))
919            .add(fwd.scale(proj_f));
920        (snapped, right, up, fwd)
921    }
922
923    /// Builds the column-major orthographic light view-projection matrix matching `project_world_point` for GPU CSM shader lookups.
924    ///
925    /// # Arguments
926    ///
927    /// - `&Self` - Cascade reference.
928    ///
929    /// # Returns
930    ///
931    /// - `Mat4` - Column-major light-space orthographic projection matrix mapping world points to `[-1, 1]` XY and `[0, 1]` Z.
932    #[must_use]
933    pub fn light_view_proj(&self) -> Mat4 {
934        let right: Vec3 = self.get_light_right();
935        let up: Vec3 = self.get_light_up();
936        let fwd: Vec3 = self.get_light_forward();
937        let center: Vec3 = self.get_snapped_center();
938        let inv_extent: f32 = 1.0 / self.get_half_extent_m().max(1.0);
939        let depth_max: f32 = self.get_depth_max();
940        let inv_depth_span: f32 = 1.0 / (depth_max - self.get_depth_min()).max(1.0);
941        let rx: f32 = right.get_x() * inv_extent;
942        let ry: f32 = right.get_y() * inv_extent;
943        let rz: f32 = right.get_z() * inv_extent;
944        let ux: f32 = up.get_x() * inv_extent;
945        let uy: f32 = up.get_y() * inv_extent;
946        let uz: f32 = up.get_z() * inv_extent;
947        let zx: f32 = -fwd.get_x() * inv_depth_span;
948        let zy: f32 = -fwd.get_y() * inv_depth_span;
949        let zz: f32 = -fwd.get_z() * inv_depth_span;
950        let tx: f32 = -center.dot(right) * inv_extent;
951        let ty: f32 = -center.dot(up) * inv_extent;
952        let tz: f32 = (depth_max + center.dot(fwd)) * inv_depth_span;
953        Mat4::from_cols_array([
954            rx, ux, zx, 0.0, ry, uy, zy, 0.0, rz, uz, zz, 0.0, tx, ty, tz, 1.0,
955        ])
956    }
957
958    /// Projects a world-space point into normalized cascade UV coordinates and linear shadow depth `[0.0, 1.0]`.
959    ///
960    /// # Arguments
961    ///
962    /// - `Vec3` - World-space position to project.
963    ///
964    /// # Returns
965    ///
966    /// - `(f32, f32, f32)` - `(u_norm, v_norm, depth_norm)` where smaller `depth_norm` is closer to the sun.
967    #[cfg_attr(not(target_arch = "wasm32"), inline)]
968    #[must_use]
969    pub fn project_world_point(&self, world_pos: Vec3) -> (f32, f32, f32) {
970        let rel: Vec3 = world_pos.sub(self.get_snapped_center());
971        let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
972        let coord_u: f32 = rel.dot(self.get_light_right()) * inv_span + 0.5;
973        let coord_v: f32 = rel.dot(self.get_light_up()) * inv_span + 0.5;
974        let light_z: f32 = rel.dot(self.get_light_forward());
975        let depth_span: f32 = (self.get_depth_max() - self.get_depth_min()).max(1.0);
976        let depth_norm: f32 = (self.get_depth_max() - light_z) / depth_span;
977        (coord_u, coord_v, depth_norm)
978    }
979
980    /// Rasterizes a world-space triangle `(v0, v1, v2)` into the target shadow depth slice (`min` depth = closest to sun).
981    ///
982    /// # Arguments
983    ///
984    /// - `&mut [f32]` - Destination shadow depth buffer (`len == resolution * resolution`).
985    /// - `usize` - Shadow map edge resolution.
986    /// - `[(f32, f32, f32); 3]` - Projected `(u_norm, v_norm, depth_norm)` triangle vertices.
987    #[cfg_attr(not(target_arch = "wasm32"), inline)]
988    fn rasterize_shadow_tri(depth_buf: &mut [f32], res: usize, verts: [(f32, f32, f32); 3]) {
989        let res_f: f32 = res as f32;
990        let x0: f32 = verts[0].0 * res_f;
991        let y0: f32 = verts[0].1 * res_f;
992        let z0: f32 = verts[0].2;
993        let x1: f32 = verts[1].0 * res_f;
994        let y1: f32 = verts[1].1 * res_f;
995        let z1: f32 = verts[1].2;
996        let x2: f32 = verts[2].0 * res_f;
997        let y2: f32 = verts[2].1 * res_f;
998        let z2: f32 = verts[2].2;
999        let area: f32 = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);
1000        if area.abs() < 0.05 {
1001            return;
1002        }
1003        let max_i: i32 = (res as i32) - 1;
1004        let min_x: i32 = (x0.min(x1).min(x2).floor() as i32).max(0);
1005        let max_x: i32 = (x0.max(x1).max(x2).ceil() as i32).min(max_i);
1006        let min_y: i32 = (y0.min(y1).min(y2).floor() as i32).max(0);
1007        let max_y: i32 = (y0.max(y1).max(y2).ceil() as i32).min(max_i);
1008        if min_x > max_x || min_y > max_y {
1009            return;
1010        }
1011        let inv_area: f32 = 1.0 / area;
1012        for py in min_y..=max_y {
1013            let fy: f32 = (py as f32) + 0.5;
1014            let row_off: usize = (py as usize) * res;
1015            for px in min_x..=max_x {
1016                let fx: f32 = (px as f32) + 0.5;
1017                let w0: f32 = ((x1 - fx) * (y2 - fy) - (y1 - fy) * (x2 - fx)) * inv_area;
1018                let w1: f32 = ((x2 - fx) * (y0 - fy) - (y2 - fy) * (x0 - fx)) * inv_area;
1019                let w2: f32 = 1.0 - w0 - w1;
1020                if w0 >= -1.0e-4 && w1 >= -1.0e-4 && w2 >= -1.0e-4 {
1021                    let depth_val: f32 = (w0 * z0 + w1 * z1 + w2 * z2).clamp(0.0, 1.0);
1022                    let slot: &mut f32 = &mut depth_buf[row_off + (px as usize)];
1023                    if depth_val < *slot {
1024                        *slot = depth_val;
1025                    }
1026                }
1027            }
1028        }
1029    }
1030
1031    /// Rebuilds the cached static shadow map buffer for all static shadow-casting objects inside this cascade's bounds using real `LOD0` mesh geometry.
1032    ///
1033    /// # Arguments
1034    ///
1035    /// - `&World3D` - Active world supplying objects, mesh library, visibility, and deformed meshes.
1036    fn rebuild_static_depth(&mut self, world: &World3D) {
1037        let objects: &[SceneObject3D] = world.get_objects().as_slice();
1038        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
1039        let res: usize = self.get_resolution();
1040        let center: Vec3 = self.get_snapped_center();
1041        let reach: f32 = self.get_half_extent_m() * 1.5;
1042        let right: Vec3 = self.get_light_right();
1043        let up: Vec3 = self.get_light_up();
1044        let fwd: Vec3 = self.get_light_forward();
1045        let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
1046        let depth_max: f32 = self.get_depth_max();
1047        let inv_depth_span: f32 = 1.0 / (depth_max - self.get_depth_min()).max(1.0);
1048        {
1049            let Self { static_depth, .. } = self;
1050            static_depth.fill(1.0);
1051            for (obj_idx, obj) in objects.iter().enumerate() {
1052                if !obj.get_ray_trace_caster()
1053                    || obj.get_is_dynamic()
1054                    || !world.is_object_visible(obj_idx)
1055                {
1056                    continue;
1057                }
1058                let wb: AxisAlignedBox3D = obj.get_world_bounds();
1059                let obj_center: Vec3 = wb.center();
1060                let rel_c: Vec3 = obj_center.sub(center);
1061                let limit: f32 = reach + wb.radius();
1062                if rel_c.get_x().abs() > limit && rel_c.get_z().abs() > limit {
1063                    continue;
1064                }
1065                let Some(mesh) = world.deformed_mesh_for_object(obj_idx).or_else(|| {
1066                    mesh_lib
1067                        .get(obj.get_mesh_id())
1068                        .and_then(|chain: &MeshLodChain| chain.get_levels().first())
1069                }) else {
1070                    continue;
1071                };
1072                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1073                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
1074                let model: Mat4 = obj.get_transform().to_mat4();
1075                for tri in indices.iter() {
1076                    let (i0, i1, i2): (usize, usize, usize) =
1077                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1078                    let out_01: bool = i0 >= verts.len() || i1 >= verts.len();
1079                    if out_01 || i2 >= verts.len() {
1080                        continue;
1081                    }
1082                    let w0: Vec3 = model.mul_point3(verts[i0].get_position()).sub(center);
1083                    let w1: Vec3 = model.mul_point3(verts[i1].get_position()).sub(center);
1084                    let w2: Vec3 = model.mul_point3(verts[i2].get_position()).sub(center);
1085                    let p0: (f32, f32, f32) = (
1086                        w0.dot(right) * inv_span + 0.5,
1087                        w0.dot(up) * inv_span + 0.5,
1088                        (depth_max - w0.dot(fwd)) * inv_depth_span,
1089                    );
1090                    let p1: (f32, f32, f32) = (
1091                        w1.dot(right) * inv_span + 0.5,
1092                        w1.dot(up) * inv_span + 0.5,
1093                        (depth_max - w1.dot(fwd)) * inv_depth_span,
1094                    );
1095                    let p2: (f32, f32, f32) = (
1096                        w2.dot(right) * inv_span + 0.5,
1097                        w2.dot(up) * inv_span + 0.5,
1098                        (depth_max - w2.dot(fwd)) * inv_depth_span,
1099                    );
1100                    Self::rasterize_shadow_tri(static_depth.as_mut_slice(), res, [p0, p1, p2]);
1101                }
1102            }
1103        }
1104        self.set_static_valid(true);
1105    }
1106
1107    /// Copies the cached static shadow depth into `active_depth` and overlays dynamic shadow casters using real `LOD0` or live deformed mesh geometry.
1108    ///
1109    /// # Arguments
1110    ///
1111    /// - `&World3D` - Active world supplying objects, mesh library, visibility, and deformed meshes.
1112    fn overlay_dynamic_depth(&mut self, world: &World3D) {
1113        let objects: &[SceneObject3D] = world.get_objects().as_slice();
1114        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
1115        let res: usize = self.get_resolution();
1116        let center: Vec3 = self.get_snapped_center();
1117        let right: Vec3 = self.get_light_right();
1118        let up: Vec3 = self.get_light_up();
1119        let fwd: Vec3 = self.get_light_forward();
1120        let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
1121        let depth_max: f32 = self.get_depth_max();
1122        let inv_depth_span: f32 = 1.0 / (depth_max - self.get_depth_min()).max(1.0);
1123        let Self {
1124            static_depth,
1125            active_depth,
1126            ..
1127        } = self;
1128        active_depth.copy_from_slice(static_depth.as_slice());
1129        for (obj_idx, obj) in objects.iter().enumerate() {
1130            if !obj.get_ray_trace_caster()
1131                || !obj.get_is_dynamic()
1132                || !world.is_object_visible(obj_idx)
1133            {
1134                continue;
1135            }
1136            let Some(mesh) = world.deformed_mesh_for_object(obj_idx).or_else(|| {
1137                mesh_lib
1138                    .get(obj.get_mesh_id())
1139                    .and_then(|chain: &MeshLodChain| chain.get_levels().first())
1140            }) else {
1141                continue;
1142            };
1143            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1144            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
1145            let model: Mat4 = obj.get_transform().to_mat4();
1146            for tri in indices.iter() {
1147                let (i0, i1, i2): (usize, usize, usize) =
1148                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1149                let out_01: bool = i0 >= verts.len() || i1 >= verts.len();
1150                if out_01 || i2 >= verts.len() {
1151                    continue;
1152                }
1153                let w0: Vec3 = model.mul_point3(verts[i0].get_position()).sub(center);
1154                let w1: Vec3 = model.mul_point3(verts[i1].get_position()).sub(center);
1155                let w2: Vec3 = model.mul_point3(verts[i2].get_position()).sub(center);
1156                let p0: (f32, f32, f32) = (
1157                    w0.dot(right) * inv_span + 0.5,
1158                    w0.dot(up) * inv_span + 0.5,
1159                    (depth_max - w0.dot(fwd)) * inv_depth_span,
1160                );
1161                let p1: (f32, f32, f32) = (
1162                    w1.dot(right) * inv_span + 0.5,
1163                    w1.dot(up) * inv_span + 0.5,
1164                    (depth_max - w1.dot(fwd)) * inv_depth_span,
1165                );
1166                let p2: (f32, f32, f32) = (
1167                    w2.dot(right) * inv_span + 0.5,
1168                    w2.dot(up) * inv_span + 0.5,
1169                    (depth_max - w2.dot(fwd)) * inv_depth_span,
1170                );
1171                Self::rasterize_shadow_tri(active_depth.as_mut_slice(), res, [p0, p1, p2]);
1172            }
1173        }
1174    }
1175
1176    /// Evaluates rotated 16-tap Vogel-disk PCF shadow visibility at `world_pos` if inside this cascade's bounds.
1177    ///
1178    /// # Arguments
1179    ///
1180    /// - `Vec3` - World-space surface position.
1181    /// - `Vec3` - Unit outward surface normal for normal-offset acne prevention.
1182    /// - `Vec3` - Unit vector pointing toward the sun.
1183    ///
1184    /// # Returns
1185    ///
1186    /// - `Option<f32>` - Visibility in `[VSM_SHADOW_FLOOR, 1.0]`, or `None` if outside this cascade.
1187    #[cfg_attr(not(target_arch = "wasm32"), inline)]
1188    #[must_use]
1189    pub fn sample_pcf(&self, world_pos: Vec3, normal: Vec3, sun_dir: Vec3) -> Option<f32> {
1190        if !self.get_static_valid() {
1191            return None;
1192        }
1193        let texel_m: f32 = (self.get_half_extent_m() * 2.0) / (self.get_resolution() as f32);
1194        let biased_pos: Vec3 = world_pos.add(normal.scale(texel_m * 0.65));
1195        let (coord_u, coord_v, depth_norm): (f32, f32, f32) = self.project_world_point(biased_pos);
1196        if !(0.02..=0.98).contains(&coord_u)
1197            || !(0.02..=0.98).contains(&coord_v)
1198            || !(0.0..=1.0).contains(&depth_norm)
1199        {
1200            return None;
1201        }
1202        let res: usize = self.get_resolution();
1203        let res_f: f32 = res as f32;
1204        let max_idx: usize = res - 1;
1205        let n_dot_l: f32 = normal.dot(sun_dir).clamp(0.05, 1.0);
1206        let slope_bias: f32 = (0.0022 * (1.0 - n_dot_l) + 0.0014).clamp(0.0012, 0.008);
1207        let cmp_depth: f32 = depth_norm - slope_bias;
1208        let base_tx: f32 = coord_u * res_f;
1209        let base_ty: f32 = coord_v * res_f;
1210        let hash_seed: f32 = world_pos.get_x().mul_add(
1211            12.9898,
1212            world_pos
1213                .get_z()
1214                .mul_add(78.233, world_pos.get_y() * 37.719),
1215        );
1216        let rot_angle: f32 = (hash_seed.sin() * 43_758.547).fract() * TAU;
1217        let cos_rot: f32 = rot_angle.cos() * VSM_VOGEL_FILTER_RADIUS_TEXELS;
1218        let sin_rot: f32 = rot_angle.sin() * VSM_VOGEL_FILTER_RADIUS_TEXELS;
1219        let Self { active_depth, .. } = self;
1220        let mut lit_taps: f32 = 0.0;
1221        for &(tap_x, tap_y) in VSM_VOGEL_TAPS_16.iter() {
1222            let rot_x: f32 = tap_x * cos_rot - tap_y * sin_rot;
1223            let rot_y: f32 = tap_x * sin_rot + tap_y * cos_rot;
1224            let tx: usize = ((base_tx + rot_x).floor().max(0.0) as usize).min(max_idx);
1225            let ty: usize = ((base_ty + rot_y).floor().max(0.0) as usize).min(max_idx);
1226            if cmp_depth <= active_depth[ty * res + tx] {
1227                lit_taps += 1.0 / 16.0;
1228            }
1229        }
1230        Some(VSM_SHADOW_FLOOR + (1.0 - VSM_SHADOW_FLOOR) * lit_taps)
1231    }
1232}
1233
1234/// Default 4-cascade Practical Split `VirtualShadowMap`.
1235impl Default for VirtualShadowMap {
1236    /// Creates a 4-cascade Practical Split `VirtualShadowMap` sized to `VSM_DEFAULT_CASCADE_RES`.
1237    ///
1238    /// # Returns
1239    ///
1240    /// - `Self` - Ready four-cascade virtual shadow map.
1241    fn default() -> Self {
1242        Self::with_resolution(VSM_DEFAULT_CASCADE_RES)
1243    }
1244}
1245
1246/// Static page cache management, Practical Split cascade fitting, and 16-tap Vogel-disk PCF sampling for `VirtualShadowMap`.
1247impl VirtualShadowMap {
1248    /// Computes the 4 Practical Split Scheme cascade split depths `[d0, d1, d2, d3]` between `near_plane` and `far_plane`.
1249    ///
1250    /// # Arguments
1251    ///
1252    /// - `f32` - Camera near plane distance in meters.
1253    /// - `f32` - Maximum directional shadow distance in meters.
1254    /// - `f32` - Practical Split lambda in `[0.0, 1.0]` (`0.0` uniform, `1.0` logarithmic).
1255    ///
1256    /// # Returns
1257    ///
1258    /// - `[f32; VSM_CASCADE_COUNT]` - Strictly increasing far split distances for cascades `0..4`.
1259    #[must_use]
1260    pub fn compute_practical_splits(
1261        near_plane: f32,
1262        far_plane: f32,
1263        lambda: f32,
1264    ) -> [f32; VSM_CASCADE_COUNT] {
1265        let near_val: f32 = near_plane.max(0.1);
1266        let far_val: f32 = far_plane.max(near_val + 4.0);
1267        let blend_lambda: f32 = lambda.clamp(0.0, 1.0);
1268        let ratio: f32 = far_val / near_val;
1269        let mut splits: [f32; VSM_CASCADE_COUNT] = [0.0; VSM_CASCADE_COUNT];
1270        for (cascade_idx, split_slot) in splits.iter_mut().enumerate().take(VSM_CASCADE_COUNT) {
1271            let frac: f32 = ((cascade_idx + 1) as f32) / (VSM_CASCADE_COUNT as f32);
1272            let log_split: f32 = near_val * ratio.powf(frac);
1273            let lin_split: f32 = near_val + (far_val - near_val) * frac;
1274            *split_slot = lin_split + (log_split - lin_split) * blend_lambda;
1275        }
1276        splits
1277    }
1278
1279    /// Constructs a 4-cascade `VirtualShadowMap` with all cascades sized to `resolution x resolution`.
1280    ///
1281    /// # Arguments
1282    ///
1283    /// - `usize` - Per-cascade shadow map edge resolution in texels (`>= 32`).
1284    ///
1285    /// # Returns
1286    ///
1287    /// - `Self` - Pre-allocated four-cascade virtual shadow map.
1288    #[must_use]
1289    pub fn with_resolution(resolution: usize) -> Self {
1290        let splits: [f32; VSM_CASCADE_COUNT] =
1291            Self::compute_practical_splits(0.25, VSM_CSM_MAX_DISTANCE_M, VSM_CSM_LAMBDA);
1292        let extents: [f32; VSM_CASCADE_COUNT] = [
1293            VSM_CASCADE_NEAR_EXTENT_M,
1294            (splits[1] * 0.72).max(28.0),
1295            (splits[2] * 0.78).max(64.0),
1296            VSM_CASCADE_FAR_EXTENT_M,
1297        ];
1298        Self {
1299            cascades: [
1300                VsmCascade::new(resolution, extents[0]),
1301                VsmCascade::new(resolution, extents[1]),
1302                VsmCascade::new(resolution, extents[2]),
1303                VsmCascade::new(resolution, extents[3]),
1304            ],
1305            cascade_split_depths: splits,
1306            cached_sun_dir: Vec3::zero(),
1307            cached_static_epoch: u64::MAX,
1308            static_cache_hits: 0,
1309            static_rebuilds: 0,
1310        }
1311    }
1312
1313    /// Returns a reference to the finest near contact cascade (`cascades[0]`).
1314    ///
1315    /// # Returns
1316    ///
1317    /// - `&VsmCascade` - Near shadow cascade reference.
1318    #[must_use]
1319    pub fn get_cascade_near(&self) -> &VsmCascade {
1320        &self.get_cascades()[0]
1321    }
1322
1323    /// Returns a reference to the farthest skyline cascade (`cascades[3]`).
1324    ///
1325    /// # Returns
1326    ///
1327    /// - `&VsmCascade` - Far shadow cascade reference.
1328    #[must_use]
1329    pub fn get_cascade_far(&self) -> &VsmCascade {
1330        &self.get_cascades()[VSM_CASCADE_COUNT - 1]
1331    }
1332
1333    /// Returns the column-major orthographic light view-projection matrix for cascade `cascade_idx`.
1334    ///
1335    /// # Arguments
1336    ///
1337    /// - `&Self` - Virtual shadow map reference.
1338    /// - `usize` - Cascade index in `0..4`.
1339    ///
1340    /// # Returns
1341    ///
1342    /// - `Mat4` - Orthographic light view-projection matrix for the requested cascade.
1343    #[must_use]
1344    pub fn cascade_light_view_proj(&self, cascade_idx: usize) -> Mat4 {
1345        let clamped_idx: usize = cascade_idx.min(VSM_CASCADE_COUNT - 1);
1346        self.get_cascades()[clamped_idx].light_view_proj()
1347    }
1348
1349    /// Invalidates all four static shadow cascades so the next update re-rasterizes static geometry cleanly.
1350    pub fn invalidate(&mut self) {
1351        for cascade in self.get_mut_cascades().iter_mut() {
1352            cascade.set_static_valid(false);
1353        }
1354    }
1355
1356    /// Synchronizes all four Practical-Split shadow cascades with `world`, reusing cached static pages whenever sun, static epoch, and snapped centers are unchanged.
1357    ///
1358    /// # Arguments
1359    ///
1360    /// - `&World3D` - Active 3D world supplying camera, sun, objects, and mesh library.
1361    pub fn update_from_world(&mut self, world: &World3D) {
1362        let sun_dir: Vec3 = world.get_sun().get_direction().normalize();
1363        let cam: Camera3D = world.get_camera();
1364        let cam_pos: Vec3 = cam.get_position();
1365        let cam_fwd: Vec3 = cam.forward();
1366        let near_p: f32 = cam.get_near().max(0.15);
1367        let far_p: f32 = cam.get_far().min(VSM_CSM_MAX_DISTANCE_M).max(near_p + 12.0);
1368        let splits: [f32; VSM_CASCADE_COUNT] =
1369            Self::compute_practical_splits(near_p, far_p, VSM_CSM_LAMBDA);
1370        self.set_cascade_split_depths(splits);
1371        let static_epoch: u64 = world.get_static_bvh_rebuilds();
1372        let sun_changed: bool = self.get_cached_sun_dir().dot(sun_dir) < 0.9998;
1373        let epoch_changed: bool = self.get_cached_static_epoch() != static_epoch;
1374        let mut rebuilt_any: bool = false;
1375        let mut hit_any: bool = false;
1376        let mut prev_split: f32 = near_p;
1377        for (cascade_idx, &split_far) in splits.iter().enumerate().take(VSM_CASCADE_COUNT) {
1378            let mid_dist: f32 = (prev_split + split_far) * 0.5;
1379            let focus_pt: Vec3 = cam_pos.add(cam_fwd.scale(mid_dist));
1380            prev_split = split_far;
1381            let cascade: &mut VsmCascade = &mut self.get_mut_cascades()[cascade_idx];
1382            let (snap_c, r_b, u_b, f_b): (Vec3, Vec3, Vec3, Vec3) =
1383                cascade.compute_snapped_basis(focus_pt, sun_dir);
1384            let moved: bool = cascade.get_snapped_center().sub(snap_c).length_sq() > 1.0e-3;
1385            let dirty_light: bool = !cascade.get_static_valid() || sun_changed;
1386            let dirty_world: bool = epoch_changed || moved;
1387            if dirty_light || dirty_world {
1388                cascade.set_snapped_center(snap_c);
1389                cascade.set_light_right(r_b);
1390                cascade.set_light_up(u_b);
1391                cascade.set_light_forward(f_b);
1392                cascade.rebuild_static_depth(world);
1393                rebuilt_any = true;
1394            } else {
1395                hit_any = true;
1396            }
1397            cascade.overlay_dynamic_depth(world);
1398        }
1399        self.set_cached_sun_dir(sun_dir);
1400        self.set_cached_static_epoch(static_epoch);
1401        if rebuilt_any {
1402            self.set_static_rebuilds(self.get_static_rebuilds().saturating_add(1));
1403        } else if hit_any {
1404            self.set_static_cache_hits(self.get_static_cache_hits().saturating_add(1));
1405        }
1406    }
1407
1408    /// Samples multi-cascade rotated 16-tap Vogel-disk PCF shadow visibility at `world_pos` across all 4 cascades with smooth inter-cascade boundary blending.
1409    ///
1410    /// # Arguments
1411    ///
1412    /// - `Vec3` - World-space surface position.
1413    /// - `Vec3` - Unit outward surface normal.
1414    /// - `Vec3` - Unit directional sun vector.
1415    ///
1416    /// # Returns
1417    ///
1418    /// - `f32` - Smooth sun visibility in `[0.22, 1.0]` (`1.0` outside all four cascades).
1419    #[cfg_attr(not(target_arch = "wasm32"), inline)]
1420    #[must_use]
1421    pub fn sample_visibility(&self, world_pos: Vec3, normal: Vec3, sun_dir: Vec3) -> f32 {
1422        let cascades: &[VsmCascade; VSM_CASCADE_COUNT] = self.get_cascades();
1423        for cascade_idx in 0..VSM_CASCADE_COUNT {
1424            let cascade: &VsmCascade = &cascades[cascade_idx];
1425            if let Some(vis_cur) = cascade.sample_pcf(world_pos, normal, sun_dir) {
1426                if cascade_idx + 1 < VSM_CASCADE_COUNT {
1427                    let (coord_u, coord_v, _): (f32, f32, f32) =
1428                        cascade.project_world_point(world_pos);
1429                    let edge_dist: f32 = coord_u.min(1.0 - coord_u).min(coord_v.min(1.0 - coord_v));
1430                    if edge_dist < 0.08
1431                        && let Some(vis_next) =
1432                            cascades[cascade_idx + 1].sample_pcf(world_pos, normal, sun_dir)
1433                    {
1434                        let blend_t: f32 = ((0.08 - edge_dist) / 0.06).clamp(0.0, 1.0);
1435                        return vis_cur + (vis_next - vis_cur) * blend_t;
1436                    }
1437                }
1438                return vis_cur;
1439            }
1440        }
1441        1.0
1442    }
1443}