1use super::*;
2
3impl PointLight3D {
5 #[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
29impl SpotLight3D {
31 #[must_use]
46 pub fn new(
47 position: Vec3,
48 direction: Vec3,
49 color: Color,
50 intensity: f32,
51 range: f32,
52 cone_deg: (f32, f32),
53 ) -> Self {
54 let (inner_deg, outer_deg): (f32, f32) = cone_deg;
55 let clamped_inner: f32 = inner_deg.clamp(1.0, 80.0);
56 let clamped_outer: f32 = outer_deg.clamp(clamped_inner + 1.0, 88.0);
57 Self {
58 position,
59 direction: direction.normalize(),
60 color: Vec3::from_color(color),
61 intensity: intensity.max(0.0),
62 range: range.max(0.5),
63 inner_cos: clamped_inner.to_radians().cos(),
64 outer_cos: clamped_outer.to_radians().cos(),
65 }
66 }
67}
68
69impl Default for LightClusterGrid3D {
71 fn default() -> Self {
77 let total_froxels: usize =
78 LIGHT_CLUSTER_GRID_X * LIGHT_CLUSTER_GRID_Y * LIGHT_CLUSTER_GRID_Z;
79 Self {
80 near_plane: 0.3,
81 far_plane: 420.0,
82 log_depth_scale: (LIGHT_CLUSTER_GRID_Z as f32) / (420.0_f32 / 0.3_f32).ln(),
83 depth_slice_max: [420.0; LIGHT_CLUSTER_GRID_Z],
84 active_light_count: 0,
85 total_assignments: 0,
86 packed_lights: Vec::with_capacity(LIGHT_CLUSTER_MAX_LIGHTS),
87 cluster_counts: vec![0_u16; total_froxels],
88 cluster_indices: vec![0_u16; total_froxels * LIGHT_CLUSTER_MAX_PER_FROXEL],
89 }
90 }
91}
92
93impl LightClusterGrid3D {
95 #[cfg_attr(not(target_arch = "wasm32"), inline)]
101 #[must_use]
102 pub fn has_active_lights(&self) -> bool {
103 self.get_active_light_count() > 0
104 }
105
106 pub fn build_clusters(
115 &mut self,
116 camera: &Camera3D,
117 aspect: f32,
118 point_lights: &[PointLight3D],
119 spot_lights: &[SpotLight3D],
120 ) {
121 let near_p: f32 = camera.get_near().max(0.15);
122 let far_p: f32 = camera.get_far().max(near_p + 1.0);
123 let log_scale: f32 = (LIGHT_CLUSTER_GRID_Z as f32) / (far_p / near_p).ln().max(1.0e-4);
124 self.set_near_plane(near_p);
125 self.set_far_plane(far_p);
126 self.set_log_depth_scale(log_scale);
127 let depth_ratio: f32 = far_p / near_p;
128 {
129 let Self {
130 depth_slice_max, ..
131 } = self;
132 for (slice_idx, slot) in depth_slice_max.iter_mut().enumerate() {
133 let frac: f32 = ((slice_idx + 1) as f32) / (LIGHT_CLUSTER_GRID_Z as f32);
134 *slot = near_p * depth_ratio.powf(frac);
135 }
136 }
137 let cam_pos: Vec3 = camera.get_position();
138 let cam_fwd: Vec3 = camera.forward();
139 let cam_right: Vec3 = camera.right();
140 let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
141 let half_h: f32 = (camera.get_fov_deg().to_radians() * 0.5).tan().max(0.05);
142 let half_w: f32 = half_h * aspect.max(0.1);
143 let inv_half_w: f32 = 1.0 / half_w;
144 let inv_half_h: f32 = 1.0 / half_h;
145 let mut assignments: usize = 0;
146 let active_count: usize = {
147 let Self {
148 packed_lights,
149 cluster_counts,
150 cluster_indices,
151 ..
152 } = self;
153 packed_lights.clear();
154 if point_lights.is_empty() && spot_lights.is_empty() {
155 cluster_counts.fill(0);
156 0
157 } else {
158 cluster_counts.fill(0);
159 for point_light in point_lights.iter() {
160 if packed_lights.len() >= LIGHT_CLUSTER_MAX_LIGHTS {
161 break;
162 }
163 let rad: f32 = point_light.get_radius().max(0.25);
164 let intensity: f32 = point_light.get_intensity();
165 if intensity <= 1.0e-4 {
166 continue;
167 }
168 let light_pos: Vec3 = point_light.get_position();
169 let col: Vec3 = point_light.get_color().scale(intensity);
170 let light_idx: u16 = packed_lights.len() as u16;
171 packed_lights.push(PackedLocalLight {
172 pos_inv_r2: [
173 light_pos.get_x(),
174 light_pos.get_y(),
175 light_pos.get_z(),
176 1.0 / (rad * rad),
177 ],
178 radiance_radius: [col.get_x(), col.get_y(), col.get_z(), rad],
179 dir_outer_cos: [0.0, -1.0, 0.0, -2.0],
180 inv_cone_span: [0.0; 4],
181 });
182 assignments += Self::bin_sphere_into_froxels(
183 (cam_pos, cam_right, cam_up, cam_fwd),
184 (inv_half_w, inv_half_h, near_p, far_p, log_scale),
185 (light_pos, rad, light_idx),
186 cluster_counts,
187 cluster_indices,
188 );
189 }
190 for spot_light in spot_lights.iter() {
191 if packed_lights.len() >= LIGHT_CLUSTER_MAX_LIGHTS {
192 break;
193 }
194 let range: f32 = spot_light.get_range().max(0.5);
195 let intensity: f32 = spot_light.get_intensity();
196 if intensity <= 1.0e-4 {
197 continue;
198 }
199 let light_pos: Vec3 = spot_light.get_position();
200 let light_dir: Vec3 = spot_light.get_direction().normalize();
201 let col: Vec3 = spot_light.get_color().scale(intensity);
202 let outer_cos: f32 = spot_light.get_outer_cos();
203 let span: f32 = (spot_light.get_inner_cos() - outer_cos).max(SPOT_CONE_MIN_EPS);
204 let light_idx: u16 = packed_lights.len() as u16;
205 packed_lights.push(PackedLocalLight {
206 pos_inv_r2: [
207 light_pos.get_x(),
208 light_pos.get_y(),
209 light_pos.get_z(),
210 1.0 / (range * range),
211 ],
212 radiance_radius: [col.get_x(), col.get_y(), col.get_z(), range],
213 dir_outer_cos: [
214 light_dir.get_x(),
215 light_dir.get_y(),
216 light_dir.get_z(),
217 outer_cos,
218 ],
219 inv_cone_span: [1.0 / span, 0.0, 0.0, 0.0],
220 });
221 let cone_center: Vec3 = light_pos.add(light_dir.scale(range * 0.45));
222 let cone_bound_rad: f32 = range * 0.45;
223 assignments += Self::bin_sphere_into_froxels(
224 (cam_pos, cam_right, cam_up, cam_fwd),
225 (inv_half_w, inv_half_h, near_p, far_p, log_scale),
226 (cone_center, cone_bound_rad, light_idx),
227 cluster_counts,
228 cluster_indices,
229 );
230 }
231 packed_lights.len()
232 }
233 };
234 self.set_active_light_count(active_count);
235 self.set_total_assignments(assignments);
236 }
237
238 fn bin_sphere_into_froxels(
252 cam_basis: (Vec3, Vec3, Vec3, Vec3),
253 frustum_params: (f32, f32, f32, f32, f32),
254 sphere: (Vec3, f32, u16),
255 cluster_counts: &mut [u16],
256 cluster_indices: &mut [u16],
257 ) -> usize {
258 let (cam_pos, cam_right, cam_up, cam_fwd): (Vec3, Vec3, Vec3, Vec3) = cam_basis;
259 let (inv_half_w, inv_half_h, near_p, far_p, log_scale): (f32, f32, f32, f32, f32) =
260 frustum_params;
261 let (center, radius, light_idx): (Vec3, f32, u16) = sphere;
262 let rel: Vec3 = center.sub(cam_pos);
263 let vz: f32 = rel.dot(cam_fwd);
264 let z_min: f32 = vz - radius;
265 let z_max: f32 = vz + radius;
266 if z_max <= near_p || z_min >= far_p {
267 return 0;
268 }
269 let vx: f32 = rel.dot(cam_right);
270 let vy: f32 = rel.dot(cam_up);
271 let z_proj: f32 = vz.max(near_p);
272 let inv_z: f32 = 1.0 / z_proj;
273 let ndc_cx: f32 = vx * inv_z * inv_half_w;
274 let ndc_cy: f32 = vy * inv_z * inv_half_h;
275 let pad_x: f32 = if z_min <= near_p {
276 (radius / vz.max(2.0) * inv_half_w).clamp(0.35, 1.35)
277 } else {
278 (radius / z_min) * inv_half_w
279 };
280 let pad_y: f32 = if z_min <= near_p {
281 (radius / vz.max(2.0) * inv_half_h).clamp(0.35, 1.35)
282 } else {
283 (radius / z_min) * inv_half_h
284 };
285 let min_u: f32 = (ndc_cx - pad_x) * 0.5 + 0.5;
286 let max_u: f32 = (ndc_cx + pad_x) * 0.5 + 0.5;
287 let min_v: f32 = 0.5 - (ndc_cy + pad_y) * 0.5;
288 let max_v: f32 = 0.5 - (ndc_cy - pad_y) * 0.5;
289 let out_u: bool = max_u < 0.0 || min_u > 1.0;
290 let out_v: bool = max_v < 0.0 || min_v > 1.0;
291 if out_u || out_v {
292 return 0;
293 }
294 let gx_max: usize = LIGHT_CLUSTER_GRID_X - 1;
295 let gy_max: usize = LIGHT_CLUSTER_GRID_Y - 1;
296 let gz_max: usize = LIGHT_CLUSTER_GRID_Z - 1;
297 let cx0: usize =
298 ((min_u.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_X as f32)).floor() as usize).min(gx_max);
299 let cx1: usize =
300 ((max_u.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_X as f32)).floor() as usize).min(gx_max);
301 let cy0: usize =
302 ((min_v.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_Y as f32)).floor() as usize).min(gy_max);
303 let cy1: usize =
304 ((max_v.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_Y as f32)).floor() as usize).min(gy_max);
305 let cz0: usize = ((((z_min.max(near_p) / near_p).ln()) * log_scale)
306 .floor()
307 .max(0.0) as usize)
308 .min(gz_max);
309 let cz1: usize = ((((z_max.min(far_p) / near_p).ln()) * log_scale)
310 .floor()
311 .max(0.0) as usize)
312 .min(gz_max);
313 let slice_stride: usize = LIGHT_CLUSTER_GRID_X * LIGHT_CLUSTER_GRID_Y;
314 let mut count_added: usize = 0;
315 for cz in cz0..=cz1 {
316 let z_off: usize = cz * slice_stride;
317 for cy in cy0..=cy1 {
318 let y_off: usize = z_off + cy * LIGHT_CLUSTER_GRID_X;
319 for cx in cx0..=cx1 {
320 let froxel: usize = y_off + cx;
321 let cur: usize = cluster_counts[froxel] as usize;
322 if cur < LIGHT_CLUSTER_MAX_PER_FROXEL {
323 cluster_indices[froxel * LIGHT_CLUSTER_MAX_PER_FROXEL + cur] = light_idx;
324 cluster_counts[froxel] = (cur + 1) as u16;
325 count_added += 1;
326 }
327 }
328 }
329 }
330 count_added
331 }
332
333 #[cfg_attr(not(target_arch = "wasm32"), inline)]
347 #[must_use]
348 pub fn evaluate_pixel(
349 &self,
350 world_pos: Vec3,
351 normal: Vec3,
352 view_dir: Vec3,
353 material_terms: (Vec3, Vec3, f32, f32),
354 screen_depth: (f32, f32, f32),
355 ) -> Vec3 {
356 if self.get_active_light_count() == 0 {
357 return Vec3::zero();
358 }
359 let (uv_x, uv_y, linear_depth): (f32, f32, f32) = screen_depth;
360 let near_p: f32 = self.get_near_plane();
361 if linear_depth < near_p || linear_depth > self.get_far_plane() {
362 return Vec3::zero();
363 }
364 let cx: usize = ((uv_x.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_X as f32)) as usize)
365 .min(LIGHT_CLUSTER_GRID_X - 1);
366 let cy: usize = ((uv_y.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_Y as f32)) as usize)
367 .min(LIGHT_CLUSTER_GRID_Y - 1);
368 let cz: usize = ((((linear_depth / near_p).ln()) * self.get_log_depth_scale()).max(0.0)
369 as usize)
370 .min(LIGHT_CLUSTER_GRID_Z - 1);
371 let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
372 let Self {
373 packed_lights,
374 cluster_counts,
375 cluster_indices,
376 ..
377 } = self;
378 let light_count: usize = cluster_counts[froxel] as usize;
379 if light_count == 0 {
380 return Vec3::zero();
381 }
382 let (albedo, f0, alpha2, diffuse_scale): (Vec3, Vec3, f32, f32) = material_terms;
383 let n_dot_v: f32 = normal.dot(view_dir).max(0.04);
384 let idx_base: usize = froxel * LIGHT_CLUSTER_MAX_PER_FROXEL;
385 let mut accum: Vec3 = Vec3::zero();
386 for slot in 0..light_count {
387 let light: PackedLocalLight = packed_lights[cluster_indices[idx_base + slot] as usize];
388 let to_light: Vec3 = Vec3::new(
389 light.pos_inv_r2[0] - world_pos.get_x(),
390 light.pos_inv_r2[1] - world_pos.get_y(),
391 light.pos_inv_r2[2] - world_pos.get_z(),
392 );
393 let dist_sq: f32 = to_light.length_sq();
394 let ratio_sq: f32 = dist_sq * light.pos_inv_r2[3];
395 if ratio_sq >= 1.0 {
396 continue;
397 }
398 let inv_dist: f32 = 1.0 / dist_sq.max(1.0e-4).sqrt();
399 let light_dir: Vec3 = to_light.scale(inv_dist);
400 let n_dot_l: f32 = normal.dot(light_dir);
401 if n_dot_l <= 0.0 {
402 continue;
403 }
404 let mut spot_factor: f32 = 1.0;
405 if light.dir_outer_cos[3] > -1.5 {
406 let beam_dir: Vec3 = Vec3::new(
407 light.dir_outer_cos[0],
408 light.dir_outer_cos[1],
409 light.dir_outer_cos[2],
410 );
411 let cos_theta: f32 = (-light_dir.get_x()) * beam_dir.get_x()
412 + (-light_dir.get_y()) * beam_dir.get_y()
413 + (-light_dir.get_z()) * beam_dir.get_z();
414 if cos_theta <= light.dir_outer_cos[3] {
415 continue;
416 }
417 let raw_spot: f32 =
418 ((cos_theta - light.dir_outer_cos[3]) * light.inv_cone_span[0]).clamp(0.0, 1.0);
419 spot_factor = raw_spot * raw_spot;
420 }
421 let window: f32 = (1.0 - ratio_sq * ratio_sq).max(0.0);
422 let atten: f32 = (window * window * spot_factor) / (dist_sq + 1.0);
423 let half_vec: Vec3 = light_dir.add(view_dir).normalize();
424 let n_dot_h: f32 = normal.dot(half_vec).max(0.0);
425 let v_dot_h: f32 = view_dir.dot(half_vec).clamp(0.0, 1.0);
426 let denom: f32 = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
427 let ggx_d: f32 = alpha2 / (PI * denom * denom).max(1.0e-4);
428 let one_minus_vh: f32 = 1.0 - v_dot_h;
429 let pow5: f32 =
430 one_minus_vh * one_minus_vh * one_minus_vh * one_minus_vh * one_minus_vh;
431 let fresnel: Vec3 = f0.add(Vec3::splat(1.0).sub(f0).scale(pow5));
432 let spec_scalar: f32 = (ggx_d * 0.25) / (n_dot_l.max(0.08) + n_dot_v);
433 let diffuse_rgb: Vec3 = albedo.scale(diffuse_scale * (1.0 / PI));
434 let brdf_rgb: Vec3 = diffuse_rgb.add(fresnel.scale(spec_scalar.min(4.0)));
435 let light_rad: Vec3 = Vec3::new(
436 light.radiance_radius[0],
437 light.radiance_radius[1],
438 light.radiance_radius[2],
439 );
440 accum = accum.add(brdf_rgb.mul(light_rad).scale(n_dot_l * atten));
441 }
442 accum
443 }
444
445 #[must_use]
457 pub fn evaluate_irradiance_fast(
458 &self,
459 world_pos: Vec3,
460 normal: Vec3,
461 screen_depth: (f32, f32, f32),
462 ) -> Vec3 {
463 if self.get_active_light_count() == 0 {
464 return Vec3::zero();
465 }
466 let (uv_x, uv_y, linear_depth): (f32, f32, f32) = screen_depth;
467 if linear_depth < self.get_near_plane() || linear_depth > self.get_far_plane() {
468 return Vec3::zero();
469 }
470 let cx: usize = ((uv_x.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_X as f32)) as usize)
471 .min(LIGHT_CLUSTER_GRID_X - 1);
472 let cy: usize = ((uv_y.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_Y as f32)) as usize)
473 .min(LIGHT_CLUSTER_GRID_Y - 1);
474 let Self {
475 depth_slice_max,
476 packed_lights,
477 cluster_counts,
478 cluster_indices,
479 ..
480 } = self;
481 let mut cz: usize = 0;
482 if linear_depth > depth_slice_max[7] {
483 cz = 8;
484 }
485 if linear_depth > depth_slice_max[cz + 3] {
486 cz += 4;
487 }
488 if linear_depth > depth_slice_max[cz + 1] {
489 cz += 2;
490 }
491 if linear_depth > depth_slice_max[cz] {
492 cz += 1;
493 }
494 let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
495 let light_count: usize = cluster_counts[froxel] as usize;
496 if light_count == 0 {
497 return Vec3::zero();
498 }
499 let idx_base: usize = froxel * LIGHT_CLUSTER_MAX_PER_FROXEL;
500 let mut accum_r: f32 = 0.0;
501 let mut accum_g: f32 = 0.0;
502 let mut accum_b: f32 = 0.0;
503 let wx: f32 = world_pos.get_x();
504 let wy: f32 = world_pos.get_y();
505 let wz: f32 = world_pos.get_z();
506 let nx: f32 = normal.get_x();
507 let ny: f32 = normal.get_y();
508 let nz: f32 = normal.get_z();
509 for slot in 0..light_count {
510 let light: PackedLocalLight = packed_lights[cluster_indices[idx_base + slot] as usize];
511 let dx: f32 = light.pos_inv_r2[0] - wx;
512 let dy: f32 = light.pos_inv_r2[1] - wy;
513 let dz: f32 = light.pos_inv_r2[2] - wz;
514 let dist_sq: f32 = dx.mul_add(dx, dy.mul_add(dy, dz * dz));
515 let ratio_sq: f32 = dist_sq * light.pos_inv_r2[3];
516 if ratio_sq >= 1.0 {
517 continue;
518 }
519 let ndotl_raw: f32 = dx.mul_add(nx, dy.mul_add(ny, dz * nz));
520 if ndotl_raw <= 0.0 {
521 continue;
522 }
523 let inv_dist: f32 = 1.0 / dist_sq.max(1.0e-4).sqrt();
524 let mut spot_factor: f32 = 1.0;
525 if light.dir_outer_cos[3] > -1.5 {
526 let cos_theta: f32 = -(dx * light.dir_outer_cos[0]
527 + dy * light.dir_outer_cos[1]
528 + dz * light.dir_outer_cos[2])
529 * inv_dist;
530 if cos_theta <= light.dir_outer_cos[3] {
531 continue;
532 }
533 let raw_spot: f32 =
534 ((cos_theta - light.dir_outer_cos[3]) * light.inv_cone_span[0]).clamp(0.0, 1.0);
535 spot_factor = raw_spot * raw_spot;
536 }
537 let window: f32 = (1.0 - ratio_sq * ratio_sq).max(0.0);
538 let scale: f32 =
539 (window * window * spot_factor * ndotl_raw * inv_dist) / (dist_sq + 1.0);
540 accum_r = light.radiance_radius[0].mul_add(scale, accum_r);
541 accum_g = light.radiance_radius[1].mul_add(scale, accum_g);
542 accum_b = light.radiance_radius[2].mul_add(scale, accum_b);
543 }
544 Vec3::new(accum_r, accum_g, accum_b)
545 }
546
547 #[must_use]
559 pub fn froxel_light_count(&self, cx: usize, cy: usize, cz: usize) -> usize {
560 let out_xy: bool = cx >= LIGHT_CLUSTER_GRID_X || cy >= LIGHT_CLUSTER_GRID_Y;
561 if out_xy || cz >= LIGHT_CLUSTER_GRID_Z {
562 return 0;
563 }
564 let Self { cluster_counts, .. } = self;
565 let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
566 cluster_counts[froxel] as usize
567 }
568}
569
570impl VsmCascade {
572 #[must_use]
583 pub fn new(resolution: usize, half_extent_m: f32) -> Self {
584 let res: usize = resolution.max(32);
585 let total: usize = res * res;
586 Self {
587 resolution: res,
588 half_extent_m: half_extent_m.max(8.0),
589 snapped_center: Vec3::zero(),
590 light_right: Vec3::new(1.0, 0.0, 0.0),
591 light_up: Vec3::new(0.0, 0.0, 1.0),
592 light_forward: Vec3::new(0.0, 1.0, 0.0),
593 depth_min: -160.0,
594 depth_max: 160.0,
595 static_valid: false,
596 static_depth: vec![1.0; total],
597 active_depth: vec![1.0; total],
598 }
599 }
600
601 #[must_use]
612 fn compute_snapped_basis(&self, focus_pos: Vec3, sun_dir: Vec3) -> (Vec3, Vec3, Vec3, Vec3) {
613 let fwd: Vec3 = sun_dir.normalize();
614 let ref_up: Vec3 = if fwd.get_y().abs() > 0.95 {
615 Vec3::new(0.0, 0.0, 1.0)
616 } else {
617 Vec3::new(0.0, 1.0, 0.0)
618 };
619 let right: Vec3 = ref_up.cross(fwd).normalize();
620 let up: Vec3 = fwd.cross(right).normalize();
621 let texel_world: f32 = (self.get_half_extent_m() * 2.0) / (self.get_resolution() as f32);
622 let snap_step: f32 = (texel_world * 16.0).max(2.0);
623 let proj_r: f32 = (focus_pos.dot(right) / snap_step).floor() * snap_step;
624 let proj_u: f32 = (focus_pos.dot(up) / snap_step).floor() * snap_step;
625 let proj_f: f32 = (focus_pos.dot(fwd) / snap_step).floor() * snap_step;
626 let snapped: Vec3 = right
627 .scale(proj_r)
628 .add(up.scale(proj_u))
629 .add(fwd.scale(proj_f));
630 (snapped, right, up, fwd)
631 }
632
633 #[cfg_attr(not(target_arch = "wasm32"), inline)]
643 #[must_use]
644 pub fn project_world_point(&self, world_pos: Vec3) -> (f32, f32, f32) {
645 let rel: Vec3 = world_pos.sub(self.get_snapped_center());
646 let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
647 let coord_u: f32 = rel.dot(self.get_light_right()) * inv_span + 0.5;
648 let coord_v: f32 = rel.dot(self.get_light_up()) * inv_span + 0.5;
649 let light_z: f32 = rel.dot(self.get_light_forward());
650 let depth_span: f32 = (self.get_depth_max() - self.get_depth_min()).max(1.0);
651 let depth_norm: f32 = (self.get_depth_max() - light_z) / depth_span;
652 (coord_u, coord_v, depth_norm)
653 }
654
655 #[cfg_attr(not(target_arch = "wasm32"), inline)]
663 fn rasterize_shadow_tri(depth_buf: &mut [f32], res: usize, verts: [(f32, f32, f32); 3]) {
664 let res_f: f32 = res as f32;
665 let x0: f32 = verts[0].0 * res_f;
666 let y0: f32 = verts[0].1 * res_f;
667 let z0: f32 = verts[0].2;
668 let x1: f32 = verts[1].0 * res_f;
669 let y1: f32 = verts[1].1 * res_f;
670 let z1: f32 = verts[1].2;
671 let x2: f32 = verts[2].0 * res_f;
672 let y2: f32 = verts[2].1 * res_f;
673 let z2: f32 = verts[2].2;
674 let area: f32 = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);
675 if area.abs() < 0.05 {
676 return;
677 }
678 let max_i: i32 = (res as i32) - 1;
679 let min_x: i32 = (x0.min(x1).min(x2).floor() as i32).max(0);
680 let max_x: i32 = (x0.max(x1).max(x2).ceil() as i32).min(max_i);
681 let min_y: i32 = (y0.min(y1).min(y2).floor() as i32).max(0);
682 let max_y: i32 = (y0.max(y1).max(y2).ceil() as i32).min(max_i);
683 if min_x > max_x || min_y > max_y {
684 return;
685 }
686 let inv_area: f32 = 1.0 / area;
687 for py in min_y..=max_y {
688 let fy: f32 = (py as f32) + 0.5;
689 let row_off: usize = (py as usize) * res;
690 for px in min_x..=max_x {
691 let fx: f32 = (px as f32) + 0.5;
692 let w0: f32 = ((x1 - fx) * (y2 - fy) - (y1 - fy) * (x2 - fx)) * inv_area;
693 let w1: f32 = ((x2 - fx) * (y0 - fy) - (y2 - fy) * (x0 - fx)) * inv_area;
694 let w2: f32 = 1.0 - w0 - w1;
695 if w0 >= -1.0e-4 && w1 >= -1.0e-4 && w2 >= -1.0e-4 {
696 let depth_val: f32 = (w0 * z0 + w1 * z1 + w2 * z2).clamp(0.0, 1.0);
697 let slot: &mut f32 = &mut depth_buf[row_off + (px as usize)];
698 if depth_val < *slot {
699 *slot = depth_val;
700 }
701 }
702 }
703 }
704 }
705
706 fn rebuild_static_depth(&mut self, objects: &[SceneObject3D], mesh_lib: &[MeshLodChain]) {
713 let res: usize = self.get_resolution();
714 let center: Vec3 = self.get_snapped_center();
715 let reach: f32 = self.get_half_extent_m() * 1.5;
716 let right: Vec3 = self.get_light_right();
717 let up: Vec3 = self.get_light_up();
718 let fwd: Vec3 = self.get_light_forward();
719 let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
720 let depth_max: f32 = self.get_depth_max();
721 let inv_depth_span: f32 = 1.0 / (depth_max - self.get_depth_min()).max(1.0);
722 {
723 let Self { static_depth, .. } = self;
724 static_depth.fill(1.0);
725 for obj in objects.iter() {
726 if !obj.get_ray_trace_caster() || obj.get_is_dynamic() {
727 continue;
728 }
729 let wb: AxisAlignedBox3D = obj.get_world_bounds();
730 let obj_center: Vec3 = wb.center();
731 let rel_c: Vec3 = obj_center.sub(center);
732 let limit: f32 = reach + wb.radius();
733 if rel_c.get_x().abs() > limit && rel_c.get_z().abs() > limit {
734 continue;
735 }
736 let Some(mesh) = mesh_lib
737 .get(obj.get_mesh_id())
738 .and_then(|chain: &MeshLodChain| chain.get_levels().last())
739 else {
740 continue;
741 };
742 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
743 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
744 let model: Mat4 = obj.get_transform().to_mat4();
745 for tri in indices.iter() {
746 let (i0, i1, i2): (usize, usize, usize) =
747 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
748 let out_01: bool = i0 >= verts.len() || i1 >= verts.len();
749 if out_01 || i2 >= verts.len() {
750 continue;
751 }
752 let w0: Vec3 = model.mul_point3(verts[i0].get_position()).sub(center);
753 let w1: Vec3 = model.mul_point3(verts[i1].get_position()).sub(center);
754 let w2: Vec3 = model.mul_point3(verts[i2].get_position()).sub(center);
755 let p0: (f32, f32, f32) = (
756 w0.dot(right) * inv_span + 0.5,
757 w0.dot(up) * inv_span + 0.5,
758 (depth_max - w0.dot(fwd)) * inv_depth_span,
759 );
760 let p1: (f32, f32, f32) = (
761 w1.dot(right) * inv_span + 0.5,
762 w1.dot(up) * inv_span + 0.5,
763 (depth_max - w1.dot(fwd)) * inv_depth_span,
764 );
765 let p2: (f32, f32, f32) = (
766 w2.dot(right) * inv_span + 0.5,
767 w2.dot(up) * inv_span + 0.5,
768 (depth_max - w2.dot(fwd)) * inv_depth_span,
769 );
770 Self::rasterize_shadow_tri(static_depth.as_mut_slice(), res, [p0, p1, p2]);
771 }
772 }
773 }
774 self.set_static_valid(true);
775 }
776
777 fn overlay_dynamic_depth(&mut self, objects: &[SceneObject3D], mesh_lib: &[MeshLodChain]) {
784 let res: usize = self.get_resolution();
785 let center: Vec3 = self.get_snapped_center();
786 let right: Vec3 = self.get_light_right();
787 let up: Vec3 = self.get_light_up();
788 let fwd: Vec3 = self.get_light_forward();
789 let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
790 let depth_max: f32 = self.get_depth_max();
791 let inv_depth_span: f32 = 1.0 / (depth_max - self.get_depth_min()).max(1.0);
792 let Self {
793 static_depth,
794 active_depth,
795 ..
796 } = self;
797 active_depth.copy_from_slice(static_depth.as_slice());
798 for obj in objects.iter() {
799 if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
800 continue;
801 }
802 let Some(mesh) = mesh_lib
803 .get(obj.get_mesh_id())
804 .and_then(|chain: &MeshLodChain| chain.get_levels().last())
805 else {
806 continue;
807 };
808 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
809 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
810 let model: Mat4 = obj.get_transform().to_mat4();
811 for tri in indices.iter() {
812 let (i0, i1, i2): (usize, usize, usize) =
813 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
814 let out_01: bool = i0 >= verts.len() || i1 >= verts.len();
815 if out_01 || i2 >= verts.len() {
816 continue;
817 }
818 let w0: Vec3 = model.mul_point3(verts[i0].get_position()).sub(center);
819 let w1: Vec3 = model.mul_point3(verts[i1].get_position()).sub(center);
820 let w2: Vec3 = model.mul_point3(verts[i2].get_position()).sub(center);
821 let p0: (f32, f32, f32) = (
822 w0.dot(right) * inv_span + 0.5,
823 w0.dot(up) * inv_span + 0.5,
824 (depth_max - w0.dot(fwd)) * inv_depth_span,
825 );
826 let p1: (f32, f32, f32) = (
827 w1.dot(right) * inv_span + 0.5,
828 w1.dot(up) * inv_span + 0.5,
829 (depth_max - w1.dot(fwd)) * inv_depth_span,
830 );
831 let p2: (f32, f32, f32) = (
832 w2.dot(right) * inv_span + 0.5,
833 w2.dot(up) * inv_span + 0.5,
834 (depth_max - w2.dot(fwd)) * inv_depth_span,
835 );
836 Self::rasterize_shadow_tri(active_depth.as_mut_slice(), res, [p0, p1, p2]);
837 }
838 }
839 }
840
841 #[cfg_attr(not(target_arch = "wasm32"), inline)]
853 #[must_use]
854 pub fn sample_pcf(&self, world_pos: Vec3, normal: Vec3, sun_dir: Vec3) -> Option<f32> {
855 if !self.get_static_valid() {
856 return None;
857 }
858 let texel_m: f32 = (self.get_half_extent_m() * 2.0) / (self.get_resolution() as f32);
859 let biased_pos: Vec3 = world_pos.add(normal.scale(texel_m * 0.65));
860 let (coord_u, coord_v, depth_norm): (f32, f32, f32) = self.project_world_point(biased_pos);
861 if !(0.02..=0.98).contains(&coord_u)
862 || !(0.02..=0.98).contains(&coord_v)
863 || !(0.0..=1.0).contains(&depth_norm)
864 {
865 return None;
866 }
867 let res: usize = self.get_resolution();
868 let res_f: f32 = res as f32;
869 let max_idx: usize = res - 1;
870 let n_dot_l: f32 = normal.dot(sun_dir).clamp(0.05, 1.0);
871 let slope_bias: f32 = (0.0022 * (1.0 - n_dot_l) + 0.0014).clamp(0.0012, 0.008);
872 let cmp_depth: f32 = depth_norm - slope_bias;
873 let base_tx: f32 = coord_u * res_f;
874 let base_ty: f32 = coord_v * res_f;
875 let Self { active_depth, .. } = self;
876 let mut lit_taps: f32 = 0.0;
877 for &(ox, oy) in VSM_PCF_OFFSETS_4.iter() {
878 let tx: usize = ((base_tx + ox).floor().max(0.0) as usize).min(max_idx);
879 let ty: usize = ((base_ty + oy).floor().max(0.0) as usize).min(max_idx);
880 if cmp_depth <= active_depth[ty * res + tx] {
881 lit_taps += 0.25;
882 }
883 }
884 Some(VSM_SHADOW_FLOOR + (1.0 - VSM_SHADOW_FLOOR) * lit_taps)
885 }
886}
887
888impl Default for VirtualShadowMap {
890 fn default() -> Self {
896 Self::with_resolution(VSM_DEFAULT_CASCADE_RES)
897 }
898}
899
900impl VirtualShadowMap {
902 #[must_use]
912 pub fn with_resolution(resolution: usize) -> Self {
913 Self {
914 cascade_near: VsmCascade::new(resolution, VSM_CASCADE_NEAR_EXTENT_M),
915 cascade_far: VsmCascade::new(resolution, VSM_CASCADE_FAR_EXTENT_M),
916 cached_sun_dir: Vec3::zero(),
917 cached_static_epoch: u64::MAX,
918 static_cache_hits: 0,
919 static_rebuilds: 0,
920 }
921 }
922
923 pub fn invalidate(&mut self) {
925 self.get_mut_cascade_near().set_static_valid(false);
926 self.get_mut_cascade_far().set_static_valid(false);
927 }
928
929 pub fn update_from_world(&mut self, world: &World3D) {
935 let sun_dir: Vec3 = world.get_sun().get_direction().normalize();
936 let cam: Camera3D = world.get_camera();
937 let focus_near: Vec3 = cam.get_position().add(cam.forward().scale(18.0));
938 let focus_far: Vec3 = cam.get_position().add(cam.forward().scale(48.0));
939 let static_epoch: u64 = world.get_static_bvh_rebuilds();
940 let sun_changed: bool = self.get_cached_sun_dir().dot(sun_dir) < 0.9998;
941 let epoch_changed: bool = self.get_cached_static_epoch() != static_epoch;
942 let objects: &[SceneObject3D] = world.get_objects().as_slice();
943 let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
944 let mut rebuilt_any: bool = false;
945 let mut hit_any: bool = false;
946 {
947 let near_c: &mut VsmCascade = self.get_mut_cascade_near();
948 let (snap_c, r_b, u_b, f_b): (Vec3, Vec3, Vec3, Vec3) =
949 near_c.compute_snapped_basis(focus_near, sun_dir);
950 let moved: bool = near_c.get_snapped_center().sub(snap_c).length_sq() > 1.0e-3;
951 let dirty_light: bool = !near_c.get_static_valid() || sun_changed;
952 let dirty_world: bool = epoch_changed || moved;
953 if dirty_light || dirty_world {
954 near_c.set_snapped_center(snap_c);
955 near_c.set_light_right(r_b);
956 near_c.set_light_up(u_b);
957 near_c.set_light_forward(f_b);
958 near_c.rebuild_static_depth(objects, mesh_lib);
959 rebuilt_any = true;
960 } else {
961 hit_any = true;
962 }
963 near_c.overlay_dynamic_depth(objects, mesh_lib);
964 }
965 {
966 let far_c: &mut VsmCascade = self.get_mut_cascade_far();
967 let (snap_c, r_b, u_b, f_b): (Vec3, Vec3, Vec3, Vec3) =
968 far_c.compute_snapped_basis(focus_far, sun_dir);
969 let moved: bool = far_c.get_snapped_center().sub(snap_c).length_sq() > 1.0e-3;
970 let dirty_light: bool = !far_c.get_static_valid() || sun_changed;
971 let dirty_world: bool = epoch_changed || moved;
972 if dirty_light || dirty_world {
973 far_c.set_snapped_center(snap_c);
974 far_c.set_light_right(r_b);
975 far_c.set_light_up(u_b);
976 far_c.set_light_forward(f_b);
977 far_c.rebuild_static_depth(objects, mesh_lib);
978 rebuilt_any = true;
979 } else {
980 hit_any = true;
981 }
982 far_c.overlay_dynamic_depth(objects, mesh_lib);
983 }
984 self.set_cached_sun_dir(sun_dir);
985 self.set_cached_static_epoch(static_epoch);
986 if rebuilt_any {
987 self.set_static_rebuilds(self.get_static_rebuilds().saturating_add(1));
988 } else if hit_any {
989 self.set_static_cache_hits(self.get_static_cache_hits().saturating_add(1));
990 }
991 }
992
993 #[cfg_attr(not(target_arch = "wasm32"), inline)]
1005 #[must_use]
1006 pub fn sample_visibility(&self, world_pos: Vec3, normal: Vec3, sun_dir: Vec3) -> f32 {
1007 if let Some(near_vis) = self
1008 .get_cascade_near()
1009 .sample_pcf(world_pos, normal, sun_dir)
1010 {
1011 return near_vis;
1012 }
1013 if let Some(far_vis) = self
1014 .get_cascade_far()
1015 .sample_pcf(world_pos, normal, sun_dir)
1016 {
1017 return far_vis;
1018 }
1019 1.0
1020 }
1021}