1use super::*;
2
3impl Default for Transform3D {
5 fn default() -> Self {
11 Self {
12 position: Vec3::zero(),
13 rotation: Quat::identity(),
14 scale: Vec3::splat(1.0),
15 }
16 }
17}
18
19impl Transform3D {
21 #[must_use]
33 pub fn new(position: Vec3, yaw_rad: f32, scale: Vec3) -> Self {
34 Self {
35 position,
36 rotation: Quat::from_axis_angle(Vec3::new(0.0, 1.0, 0.0), yaw_rad),
37 scale,
38 }
39 }
40
41 #[must_use]
53 pub fn from_trs(position: Vec3, rotation: Quat, scale: Vec3) -> Self {
54 Self {
55 position,
56 rotation: rotation.normalize(),
57 scale,
58 }
59 }
60
61 #[must_use]
71 pub fn from_matrix(matrix: Mat4) -> Self {
72 let (position, rotation, scale): (Vec3, Quat, Vec3) = matrix.decompose_trs();
73 Self {
74 position,
75 rotation: rotation.normalize(),
76 scale,
77 }
78 }
79
80 #[must_use]
91 pub fn with_rotation(mut self, rotation: Quat) -> Self {
92 self.set_rotation(rotation.normalize());
93 self
94 }
95
96 #[must_use]
109 pub fn with_euler(mut self, yaw_rad: f32, pitch_rad: f32, roll_rad: f32) -> Self {
110 self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
111 self
112 }
113
114 #[must_use]
120 pub fn euler_yxz(&self) -> (f32, f32, f32) {
121 let elems: [f32; 16] = self.get_rotation().to_mat4().get_elements();
122 let rot00: f32 = elems[0];
123 let rot10: f32 = elems[1];
124 let rot20: f32 = elems[2];
125 let rot11: f32 = elems[5];
126 let rot02: f32 = elems[8];
127 let rot12: f32 = elems[9];
128 let rot22: f32 = elems[10];
129 let sin_pitch: f32 = (-rot12).clamp(-1.0, 1.0);
130 let pitch_rad: f32 = sin_pitch.asin();
131 if rot12.abs() < 0.99999 {
132 let yaw_rad: f32 = rot02.atan2(rot22);
133 let roll_rad: f32 = rot10.atan2(rot11);
134 (yaw_rad, pitch_rad, roll_rad)
135 } else {
136 let yaw_rad: f32 = (-rot20).atan2(rot00);
137 (yaw_rad, pitch_rad, 0.0)
138 }
139 }
140
141 #[must_use]
147 pub fn get_yaw_rad(&self) -> f32 {
148 self.euler_yxz().0
149 }
150
151 #[must_use]
157 pub fn get_pitch_rad(&self) -> f32 {
158 self.euler_yxz().1
159 }
160
161 #[must_use]
167 pub fn get_roll_rad(&self) -> f32 {
168 self.euler_yxz().2
169 }
170
171 pub fn set_yaw_rad(&mut self, yaw_rad: f32) {
178 let (_, pitch_rad, roll_rad): (f32, f32, f32) = self.euler_yxz();
179 self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
180 }
181
182 pub fn set_pitch_rad(&mut self, pitch_rad: f32) {
189 let (yaw_rad, _, roll_rad): (f32, f32, f32) = self.euler_yxz();
190 self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
191 }
192
193 pub fn set_roll_rad(&mut self, roll_rad: f32) {
200 let (yaw_rad, pitch_rad, _): (f32, f32, f32) = self.euler_yxz();
201 self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
202 }
203
204 #[must_use]
216 pub fn lerp(self, other: Self, blend_factor: f32) -> Self {
217 let clamped_t: f32 = blend_factor.clamp(0.0, 1.0);
218 Self {
219 position: self.get_position().lerp(other.get_position(), clamped_t),
220 rotation: self.get_rotation().slerp(other.get_rotation(), clamped_t),
221 scale: self.get_scale().lerp(other.get_scale(), clamped_t),
222 }
223 }
224
225 #[must_use]
237 pub fn lerp_shortest_angle(self, other: Self, blend_factor: f32) -> Self {
238 self.lerp(other, blend_factor)
239 }
240
241 #[must_use]
251 pub fn to_mat4(&self) -> Mat4 {
252 Mat4::from_trs_quat(self.get_position(), self.get_rotation(), self.get_scale())
253 }
254
255 #[must_use]
265 pub fn to_inv_mat4(&self) -> Mat4 {
266 self.to_mat4().inverse().unwrap_or_else(Mat4::identity)
267 }
268
269 #[must_use]
279 pub fn normal_mat3(&self) -> [Vec3; 3] {
280 self.to_mat4().normal_matrix_3x3()
281 }
282
283 #[must_use]
294 fn rotate_vec(&self, vec_value: Vec3) -> Vec3 {
295 self.get_rotation().rotate_vec3(vec_value)
296 }
297
298 #[must_use]
309 pub fn transform_point(&self, vec_value: Vec3) -> Vec3 {
310 let direction_vec: Vec3 = self.get_scale();
311 let scaled: Vec3 = Vec3::new(
312 vec_value.get_x() * direction_vec.get_x(),
313 vec_value.get_y() * direction_vec.get_y(),
314 vec_value.get_z() * direction_vec.get_z(),
315 );
316 self.rotate_vec(scaled).add(self.get_position())
317 }
318
319 #[must_use]
330 pub fn transform_normal(&self, vec_value: Vec3) -> Vec3 {
331 self.rotate_vec(vec_value).normalize()
332 }
333
334 #[must_use]
345 pub fn transform_bounds(&self, local: AxisAlignedBox3D) -> AxisAlignedBox3D {
346 self.to_mat4().transform_bounds(local)
347 }
348
349 #[must_use]
360 pub fn to_oriented_box(&self, local: AxisAlignedBox3D) -> OrientedBox3D {
361 let local_center: Vec3 = local.get_min().add(local.get_max()).scale(0.5);
362 let local_half: Vec3 = local.get_max().sub(local.get_min()).scale(0.5);
363 let vec_value: Vec3 = self.get_scale();
364 let center: Vec3 = self.transform_point(local_center);
365 let ax: Vec3 = self.rotate_vec(Vec3::new(1.0, 0.0, 0.0)).normalize();
366 let ay: Vec3 = self.rotate_vec(Vec3::new(0.0, 1.0, 0.0)).normalize();
367 let az: Vec3 = self.rotate_vec(Vec3::new(0.0, 0.0, 1.0)).normalize();
368 let half_extents: Vec3 = Vec3::new(
369 (local_half.get_x() * vec_value.get_x()).abs().max(1e-4),
370 (local_half.get_y() * vec_value.get_y()).abs().max(1e-4),
371 (local_half.get_z() * vec_value.get_z()).abs().max(1e-4),
372 );
373 OrientedBox3D::new(center, [ax, ay, az], half_extents)
374 }
375}
376
377impl OrientedBox3D {
379 #[must_use]
389 pub fn from_bounds(bounds_rect: AxisAlignedBox3D) -> Self {
390 let center: Vec3 = bounds_rect.get_min().add(bounds_rect.get_max()).scale(0.5);
391 let half: Vec3 = bounds_rect.get_max().sub(bounds_rect.get_min()).scale(0.5);
392 Self::new(
393 center,
394 [
395 Vec3::new(1.0, 0.0, 0.0),
396 Vec3::new(0.0, 1.0, 0.0),
397 Vec3::new(0.0, 0.0, 1.0),
398 ],
399 Vec3::new(
400 half.get_x().abs().max(1e-4),
401 half.get_y().abs().max(1e-4),
402 half.get_z().abs().max(1e-4),
403 ),
404 )
405 }
406
407 #[must_use]
417 pub fn to_world_bounds(&self) -> AxisAlignedBox3D {
418 let vec_value: Vec3 = self.get_center();
419 let axes: [Vec3; 3] = self.get_axes();
420 let height_val: Vec3 = self.get_half_extents();
421 let ex: f32 = axes[0].get_x().abs() * height_val.get_x()
422 + axes[1].get_x().abs() * height_val.get_y()
423 + axes[2].get_x().abs() * height_val.get_z();
424 let ey: f32 = axes[0].get_y().abs() * height_val.get_x()
425 + axes[1].get_y().abs() * height_val.get_y()
426 + axes[2].get_y().abs() * height_val.get_z();
427 let ez: f32 = axes[0].get_z().abs() * height_val.get_x()
428 + axes[1].get_z().abs() * height_val.get_y()
429 + axes[2].get_z().abs() * height_val.get_z();
430 let ext: Vec3 = Vec3::new(ex, ey, ez);
431 AxisAlignedBox3D::new(vec_value.sub(ext), vec_value.add(ext))
432 }
433
434 #[must_use]
447 pub fn intersect_triangle_world(
448 &self,
449 w0: Vec3,
450 w1: Vec3,
451 w2: Vec3,
452 ) -> Option<(Vec3, f32, Vec3)> {
453 let vec_value: Vec3 = self.get_center();
454 let axes: [Vec3; 3] = self.get_axes();
455 let height_val: Vec3 = self.get_half_extents();
456 let d0: Vec3 = w0.sub(vec_value);
457 let d1: Vec3 = w1.sub(vec_value);
458 let d2: Vec3 = w2.sub(vec_value);
459 let v0: Vec3 = Vec3::new(d0.dot(axes[0]), d0.dot(axes[1]), d0.dot(axes[2]));
460 let v1: Vec3 = Vec3::new(d1.dot(axes[0]), d1.dot(axes[1]), d1.dot(axes[2]));
461 let v2: Vec3 = Vec3::new(d2.dot(axes[0]), d2.dot(axes[1]), d2.dot(axes[2]));
462 let min_x: f32 = v0.get_x().min(v1.get_x()).min(v2.get_x());
463 let max_x: f32 = v0.get_x().max(v1.get_x()).max(v2.get_x());
464 if min_x >= height_val.get_x() || max_x <= -height_val.get_x() {
465 return None;
466 }
467 let min_y: f32 = v0.get_y().min(v1.get_y()).min(v2.get_y());
468 let max_y: f32 = v0.get_y().max(v1.get_y()).max(v2.get_y());
469 if min_y >= height_val.get_y() || max_y <= -height_val.get_y() {
470 return None;
471 }
472 let min_z: f32 = v0.get_z().min(v1.get_z()).min(v2.get_z());
473 let max_z: f32 = v0.get_z().max(v1.get_z()).max(v2.get_z());
474 if min_z >= height_val.get_z() || max_z <= -height_val.get_z() {
475 return None;
476 }
477 let mut best_pen: f32 = f32::INFINITY;
478 let mut best_local_n: Vec3 = Vec3::new(0.0, 1.0, 0.0);
479 let box_axes: [(f32, f32, f32, Vec3); 3] = [
480 (min_x, max_x, height_val.get_x(), Vec3::new(1.0, 0.0, 0.0)),
481 (min_y, max_y, height_val.get_y(), Vec3::new(0.0, 1.0, 0.0)),
482 (min_z, max_z, height_val.get_z(), Vec3::new(0.0, 0.0, 1.0)),
483 ];
484 for (t_min, t_max, half_e, axis) in box_axes {
485 let pen: f32 = (half_e - t_min).min(t_max + half_e);
486 if pen <= 1e-6 {
487 return None;
488 }
489 if pen < best_pen {
490 best_pen = pen;
491 best_local_n = if t_min + t_max > 0.0 {
492 axis.scale(-1.0)
493 } else {
494 axis
495 };
496 }
497 }
498 let e0: Vec3 = v1.sub(v0);
499 let e1: Vec3 = v2.sub(v1);
500 let e2: Vec3 = v0.sub(v2);
501 let face_raw: Vec3 = e0.cross(v2.sub(v0));
502 let face_len_sq: f32 = face_raw.length_sq();
503 if face_len_sq > 1e-12 {
504 let face_n: Vec3 = face_raw.scale(1.0 / face_len_sq.sqrt());
505 let dist: f32 = face_n.dot(v0);
506 let red_val: f32 = height_val.get_x() * face_n.get_x().abs()
507 + height_val.get_y() * face_n.get_y().abs()
508 + height_val.get_z() * face_n.get_z().abs();
509 let pen: f32 = red_val - dist.abs();
510 if pen <= 1e-6 {
511 return None;
512 }
513 if pen < best_pen {
514 best_pen = pen;
515 best_local_n = if dist > 0.0 {
516 face_n.scale(-1.0)
517 } else {
518 face_n
519 };
520 }
521 }
522 let edges: [Vec3; 3] = [e0, e1, e2];
523 let unit_axes: [Vec3; 3] = [
524 Vec3::new(1.0, 0.0, 0.0),
525 Vec3::new(0.0, 1.0, 0.0),
526 Vec3::new(0.0, 0.0, 1.0),
527 ];
528 for edge in edges {
529 for u_axis in unit_axes {
530 let raw_a: Vec3 = edge.cross(u_axis);
531 let len_sq: f32 = raw_a.length_sq();
532 if len_sq <= 1e-10 {
533 continue;
534 }
535 let axis: Vec3 = raw_a.scale(1.0 / len_sq.sqrt());
536 let p0: f32 = v0.dot(axis);
537 let p1: f32 = v1.dot(axis);
538 let p2: f32 = v2.dot(axis);
539 let t_min: f32 = p0.min(p1).min(p2);
540 let t_max: f32 = p0.max(p1).max(p2);
541 let radius_val: f32 = height_val.get_x() * axis.get_x().abs()
542 + height_val.get_y() * axis.get_y().abs()
543 + height_val.get_z() * axis.get_z().abs();
544 if t_min >= radius_val || t_max <= -radius_val {
545 return None;
546 }
547 let pen: f32 = (radius_val - t_min).min(t_max + radius_val);
548 if pen <= 1e-6 {
549 return None;
550 }
551 if pen < best_pen {
552 best_pen = pen;
553 best_local_n = if t_min + t_max > 0.0 {
554 axis.scale(-1.0)
555 } else {
556 axis
557 };
558 }
559 }
560 }
561 let tri_center: Vec3 = v0.add(v1).add(v2).scale(1.0 / 3.0);
562 let local_contact: Vec3 = Vec3::new(
563 tri_center
564 .get_x()
565 .clamp(-height_val.get_x(), height_val.get_x()),
566 tri_center
567 .get_y()
568 .clamp(-height_val.get_y(), height_val.get_y()),
569 tri_center
570 .get_z()
571 .clamp(-height_val.get_z(), height_val.get_z()),
572 );
573 let world_n: Vec3 = axes[0]
574 .scale(best_local_n.get_x())
575 .add(axes[1].scale(best_local_n.get_y()))
576 .add(axes[2].scale(best_local_n.get_z()))
577 .normalize();
578 let world_contact: Vec3 = vec_value
579 .add(axes[0].scale(local_contact.get_x()))
580 .add(axes[1].scale(local_contact.get_y()))
581 .add(axes[2].scale(local_contact.get_z()));
582 Some((world_n, best_pen, world_contact))
583 }
584
585 #[must_use]
596 pub fn intersects_oriented_box(&self, other: &Self) -> bool {
597 let a_axes: [Vec3; 3] = self.get_axes();
598 let b_axes: [Vec3; 3] = other.get_axes();
599 let a_ext: [f32; 3] = [
600 self.get_half_extents().get_x(),
601 self.get_half_extents().get_y(),
602 self.get_half_extents().get_z(),
603 ];
604 let b_ext: [f32; 3] = [
605 other.get_half_extents().get_x(),
606 other.get_half_extents().get_y(),
607 other.get_half_extents().get_z(),
608 ];
609 let mut rot: [[f32; 3]; 3] = [[0.0; 3]; 3];
610 let mut abs_rot: [[f32; 3]; 3] = [[0.0; 3]; 3];
611 for row_idx in 0..3_usize {
612 for col_idx in 0..3_usize {
613 let dot_val: f32 = a_axes[row_idx].dot(b_axes[col_idx]);
614 rot[row_idx][col_idx] = dot_val;
615 abs_rot[row_idx][col_idx] = dot_val.abs() + 1.0e-5;
616 }
617 }
618 let delta_world: Vec3 = other.get_center().sub(self.get_center());
619 let trans: [f32; 3] = [
620 delta_world.dot(a_axes[0]),
621 delta_world.dot(a_axes[1]),
622 delta_world.dot(a_axes[2]),
623 ];
624 for row_idx in 0..3_usize {
625 let ra: f32 = a_ext[row_idx];
626 let rb: f32 = b_ext[0] * abs_rot[row_idx][0]
627 + b_ext[1] * abs_rot[row_idx][1]
628 + b_ext[2] * abs_rot[row_idx][2];
629 if trans[row_idx].abs() > ra + rb {
630 return false;
631 }
632 }
633 for col_idx in 0..3_usize {
634 let ra: f32 = a_ext[0] * abs_rot[0][col_idx]
635 + a_ext[1] * abs_rot[1][col_idx]
636 + a_ext[2] * abs_rot[2][col_idx];
637 let rb: f32 = b_ext[col_idx];
638 let proj: f32 = trans[0] * rot[0][col_idx]
639 + trans[1] * rot[1][col_idx]
640 + trans[2] * rot[2][col_idx];
641 if proj.abs() > ra + rb {
642 return false;
643 }
644 }
645 for row_idx in 0..3_usize {
646 let r1: usize = (row_idx + 1) % 3;
647 let r2: usize = (row_idx + 2) % 3;
648 for col_idx in 0..3_usize {
649 let c1: usize = (col_idx + 1) % 3;
650 let c2: usize = (col_idx + 2) % 3;
651 let ra: f32 = a_ext[r1] * abs_rot[r2][col_idx] + a_ext[r2] * abs_rot[r1][col_idx];
652 let rb: f32 = b_ext[c1] * abs_rot[row_idx][c2] + b_ext[c2] * abs_rot[row_idx][c1];
653 let proj: f32 = trans[r2] * rot[r1][col_idx] - trans[r1] * rot[r2][col_idx];
654 if proj.abs() > ra + rb {
655 return false;
656 }
657 }
658 }
659 true
660 }
661
662 #[inline]
675 #[must_use]
676 fn xz_corners(
677 center: Vec3,
678 u_vec: (f32, f32),
679 v_vec: (f32, f32),
680 half_xz: (f32, f32),
681 ) -> [(f32, f32); 4] {
682 let cx: f32 = center.get_x();
683 let cz: f32 = center.get_z();
684 let (hx, hz): (f32, f32) = half_xz;
685 [
686 (
687 cx + u_vec.0 * hx + v_vec.0 * hz,
688 cz + u_vec.1 * hx + v_vec.1 * hz,
689 ),
690 (
691 cx + u_vec.0 * hx - v_vec.0 * hz,
692 cz + u_vec.1 * hx - v_vec.1 * hz,
693 ),
694 (
695 cx - u_vec.0 * hx + v_vec.0 * hz,
696 cz - u_vec.1 * hx + v_vec.1 * hz,
697 ),
698 (
699 cx - u_vec.0 * hx - v_vec.0 * hz,
700 cz - u_vec.1 * hx - v_vec.1 * hz,
701 ),
702 ]
703 }
704
705 #[must_use]
715 pub fn intersect_oriented_box_xz(&self, other: &Self) -> Option<(Vec3, f32, Vec3)> {
716 let a_bounds: AxisAlignedBox3D = self.to_world_bounds();
717 let b_bounds: AxisAlignedBox3D = other.to_world_bounds();
718 if a_bounds.get_max().get_y() <= b_bounds.get_min().get_y()
719 || b_bounds.get_max().get_y() <= a_bounds.get_min().get_y()
720 {
721 return None;
722 }
723 let norm_xz: fn(Vec3, (f32, f32)) -> (f32, f32) =
724 |axis: Vec3, fallback: (f32, f32)| -> (f32, f32) {
725 let len: f32 = (axis.get_x() * axis.get_x() + axis.get_z() * axis.get_z()).sqrt();
726 if len > 1.0e-5 {
727 (axis.get_x() / len, axis.get_z() / len)
728 } else {
729 fallback
730 }
731 };
732 let a_axes: [Vec3; 3] = self.get_axes();
733 let b_axes: [Vec3; 3] = other.get_axes();
734 let ua: (f32, f32) = norm_xz(a_axes[0], (1.0, 0.0));
735 let va: (f32, f32) = norm_xz(a_axes[2], (0.0, 1.0));
736 let ub: (f32, f32) = norm_xz(b_axes[0], (1.0, 0.0));
737 let vb: (f32, f32) = norm_xz(b_axes[2], (0.0, 1.0));
738 let hxa: f32 = self.get_half_extents().get_x();
739 let hza: f32 = self.get_half_extents().get_z();
740 let hxb: f32 = other.get_half_extents().get_x();
741 let hzb: f32 = other.get_half_extents().get_z();
742 let ca: Vec3 = self.get_center();
743 let cb: Vec3 = other.get_center();
744 let dx: f32 = ca.get_x() - cb.get_x();
745 let dz: f32 = ca.get_z() - cb.get_z();
746 let sat_axes: [(f32, f32); 4] = [ua, va, ub, vb];
747 let mut best_pen: f32 = f32::INFINITY;
748 let mut best_nx: f32 = 1.0;
749 let mut best_nz: f32 = 0.0;
750 let mut best_idx: usize = 0;
751 for (axis_idx, &(ax, az)) in sat_axes.iter().enumerate() {
752 let ra: f32 = hxa * (ua.0 * ax + ua.1 * az).abs() + hza * (va.0 * ax + va.1 * az).abs();
753 let rb: f32 = hxb * (ub.0 * ax + ub.1 * az).abs() + hzb * (vb.0 * ax + vb.1 * az).abs();
754 let center_proj: f32 = dx * ax + dz * az;
755 let overlap: f32 = (ra + rb) - center_proj.abs();
756 if overlap <= 1.0e-5 {
757 return None;
758 }
759 if overlap < best_pen {
760 best_pen = overlap;
761 let sign: f32 = if center_proj >= 0.0 { 1.0 } else { -1.0 };
762 best_nx = ax * sign;
763 best_nz = az * sign;
764 best_idx = axis_idx;
765 }
766 }
767 let (inc_corners, dir_x, dir_z): ([(f32, f32); 4], f32, f32) = if best_idx < 2 {
768 (Self::xz_corners(cb, ub, vb, (hxb, hzb)), best_nx, best_nz)
769 } else {
770 (Self::xz_corners(ca, ua, va, (hxa, hza)), -best_nx, -best_nz)
771 };
772 let mut max_proj: f32 = f32::NEG_INFINITY;
773 for &(px, pz) in inc_corners.iter() {
774 let proj: f32 = px * dir_x + pz * dir_z;
775 if proj > max_proj {
776 max_proj = proj;
777 }
778 }
779 let mut sum_x: f32 = 0.0;
780 let mut sum_z: f32 = 0.0;
781 let mut count: f32 = 0.0;
782 for &(px, pz) in inc_corners.iter() {
783 let proj: f32 = px * dir_x + pz * dir_z;
784 if proj >= max_proj - 0.08 {
785 sum_x += px;
786 sum_z += pz;
787 count += 1.0;
788 }
789 }
790 let inv_cnt: f32 = if count > 0.0 { 1.0 / count } else { 1.0 };
791 let contact_y: f32 = (ca.get_y() + cb.get_y()) * 0.5;
792 let contact: Vec3 = Vec3::new(sum_x * inv_cnt, contact_y, sum_z * inv_cnt);
793 Some((Vec3::new(best_nx, 0.0, best_nz), best_pen, contact))
794 }
795}
796
797impl Default for PlayerVehiclePhysics3D {
799 fn default() -> Self {
805 Self {
806 vel: Vec3::zero(),
807 yaw_rate: 0.0,
808 body_roll_rad: 0.0,
809 body_pitch_rad: 0.0,
810 boost_active: false,
811 boost_charge: 1.0,
812 drift_active: false,
813 drift_slip_angle: 0.0,
814 drift_duration: 0.0,
815 drift_peak_slip: 0.0,
816 camera_fov_boost: 0.0,
817 camera_shake: 0.0,
818 }
819 }
820}
821
822impl NpcVehicle3D {
824 #[must_use]
838 pub(crate) fn new_boulevard(
839 object_index: usize,
840 start_s: f32,
841 lane_u: f32,
842 signed_speed_mps: f32,
843 face_yaw: f32,
844 ) -> Self {
845 let dir: f32 = if signed_speed_mps >= 0.0 { 1.0 } else { -1.0 };
846 let speed: f32 = signed_speed_mps.abs();
847 let fwd: Vec3 = Vec3::new(-face_yaw.sin(), 0.0, -face_yaw.cos());
848 let (target_pos, _): (Vec3, f32) = World3D::loop_pose_at(start_s + dir * 10.0, lane_u);
849 Self {
850 object_index,
851 vel: fwd.scale(speed),
852 yaw_rate: 0.0,
853 mass: VEHICLE_NPC_MASS_KG,
854 cruise_speed: speed,
855 recovery_timer: 0.0,
856 free_roam_mode: false,
857 loop_arc_s: start_s,
858 loop_lane_u: lane_u,
859 loop_dir: dir,
860 nav_target: target_pos,
861 waypoint_idx: 0,
862 route_id: 0,
863 }
864 }
865
866 #[must_use]
880 pub(crate) fn new_free_roam(
881 object_index: usize,
882 route_id: u8,
883 waypoint_idx: usize,
884 cruise_speed: f32,
885 face_yaw: f32,
886 ) -> Self {
887 let waypoints: &[(f32, f32)] = Self::route_waypoints(route_id);
888 let safe_idx: usize = waypoint_idx % waypoints.len();
889 let (tx, tz): (f32, f32) = waypoints[safe_idx];
890 let fwd: Vec3 = Vec3::new(-face_yaw.sin(), 0.0, -face_yaw.cos());
891 Self {
892 object_index,
893 vel: fwd.scale(cruise_speed),
894 yaw_rate: 0.0,
895 mass: VEHICLE_NPC_MASS_KG,
896 cruise_speed,
897 recovery_timer: 0.0,
898 free_roam_mode: true,
899 loop_arc_s: 0.0,
900 loop_lane_u: 0.0,
901 loop_dir: 1.0,
902 nav_target: Vec3::new(tx, 0.0, tz),
903 waypoint_idx: safe_idx,
904 route_id,
905 }
906 }
907
908 #[must_use]
918 pub(crate) fn route_waypoints(route_id: u8) -> &'static [(f32, f32)] {
919 match route_id {
920 1 => &NPC_OUTER_PLAZA_WAYPOINTS,
921 2 => &NPC_COURTYARD_CROSS_WAYPOINTS,
922 _ => &NPC_INNER_PLAZA_WAYPOINTS,
923 }
924 }
925
926 #[must_use]
936 pub(crate) fn nearest_open_waypoint(pos: Vec3) -> (u8, usize, Vec3) {
937 let mut best_route: u8 = 0;
938 let mut best_idx: usize = 0;
939 let mut best_pos: Vec3 = Vec3::new(
940 NPC_INNER_PLAZA_WAYPOINTS[0].0,
941 0.0,
942 NPC_INNER_PLAZA_WAYPOINTS[0].1,
943 );
944 let mut best_dist_sq: f32 = f32::INFINITY;
945 for route_id in 0..3_u8 {
946 let pts: &[(f32, f32)] = Self::route_waypoints(route_id);
947 for (idx, &(wx, wz)) in pts.iter().enumerate() {
948 let dx: f32 = wx - pos.get_x();
949 let dz: f32 = wz - pos.get_z();
950 let dist_sq: f32 = dx * dx + dz * dz;
951 if dist_sq > 25.0 && dist_sq < best_dist_sq {
952 best_dist_sq = dist_sq;
953 best_route = route_id;
954 best_idx = idx;
955 best_pos = Vec3::new(wx, 0.0, wz);
956 }
957 }
958 }
959 (best_route, best_idx, best_pos)
960 }
961}
962
963impl CameraMode3D {
965 #[must_use]
975 pub const fn from_u8(index: u8) -> Self {
976 match index {
977 1 => Self::Hood,
978 2 => Self::Orbit,
979 3 => Self::Aerial,
980 4 => Self::FreeFly,
981 5 => Self::CinematicDolly,
982 _ => Self::Chase,
983 }
984 }
985
986 #[must_use]
996 pub const fn as_u8(self) -> u8 {
997 match self {
998 Self::Chase => 0,
999 Self::Hood => 1,
1000 Self::Orbit => 2,
1001 Self::Aerial => 3,
1002 Self::FreeFly => 4,
1003 Self::CinematicDolly => 5,
1004 }
1005 }
1006}
1007
1008impl SpawnObjectDesc {
1010 #[must_use]
1021 pub fn new(name: &str, mesh_id: usize) -> Self {
1022 Self {
1023 name: name.to_string(),
1024 mesh_id,
1025 transform: Transform3D::default(),
1026 material: PbrMaterial::default(),
1027 ray_trace_caster: true,
1028 solid_collider: true,
1029 spin_speed: 0.0,
1030 is_dynamic: false,
1031 }
1032 }
1033
1034 #[must_use]
1045 pub fn with_transform(mut self, transform: Transform3D) -> Self {
1046 self.set_transform(transform);
1047 self
1048 }
1049
1050 #[must_use]
1061 pub fn with_material(mut self, material: PbrMaterial) -> Self {
1062 self.set_material(material);
1063 self
1064 }
1065
1066 #[must_use]
1077 pub fn with_ray_trace(mut self, ray_trace_caster: bool) -> Self {
1078 self.set_ray_trace_caster(ray_trace_caster);
1079 self
1080 }
1081
1082 #[must_use]
1093 pub fn with_solid_collider(mut self, solid_collider: bool) -> Self {
1094 self.set_solid_collider(solid_collider);
1095 self
1096 }
1097
1098 #[must_use]
1109 pub fn with_spin(mut self, spin_speed: f32) -> Self {
1110 self.set_spin_speed(spin_speed);
1111 if spin_speed.abs() > 0.001 {
1112 self.set_is_dynamic(true);
1113 }
1114 self
1115 }
1116
1117 #[must_use]
1128 pub fn with_dynamic(mut self, is_dynamic: bool) -> Self {
1129 self.set_is_dynamic(is_dynamic);
1130 self
1131 }
1132}
1133
1134impl ImportModelDesc {
1136 #[must_use]
1147 pub fn new(format: ModelFormat, source: &str) -> Self {
1148 Self {
1149 format,
1150 source: source.to_string(),
1151 transform: Transform3D::default(),
1152 fallback_material: PbrMaterial::default(),
1153 spin_speed: 0.0,
1154 }
1155 }
1156
1157 #[must_use]
1168 pub fn with_transform(mut self, transform: Transform3D) -> Self {
1169 self.set_transform(transform);
1170 self
1171 }
1172
1173 #[must_use]
1184 pub fn with_material(mut self, fallback_material: PbrMaterial) -> Self {
1185 self.set_fallback_material(fallback_material);
1186 self
1187 }
1188
1189 #[must_use]
1200 pub fn with_spin(mut self, spin_speed: f32) -> Self {
1201 self.set_spin_speed(spin_speed);
1202 self
1203 }
1204}
1205
1206impl DirectionalLight3D {
1208 #[must_use]
1218 pub fn from_time_of_day(hour: f32) -> Self {
1219 let height_val: f32 = hour.rem_euclid(24.0);
1220 let elev_angle: f32 = ((height_val - 6.0) / 12.0 * PI).clamp(-0.35, 3.49);
1221 let sun_y: f32 = elev_angle.sin();
1222 let sun_x: f32 = elev_angle.cos();
1223 let dir: Vec3 = Vec3::new(-sun_x * 0.62, sun_y.max(0.22), -0.78).normalize();
1224 if (7.5..=16.5).contains(&height_val) {
1225 Self {
1226 direction: dir,
1227 color: Vec3::new(2.35, 2.18, 1.96),
1228 sky_zenith: Vec3::new(0.08, 0.24, 0.64),
1229 sky_horizon: Vec3::new(0.46, 0.66, 0.88),
1230 time_of_day: height_val,
1231 }
1232 } else if (5.5..7.5).contains(&height_val) || (16.5..19.5).contains(&height_val) {
1233 Self {
1234 direction: Vec3::new(-0.14, 0.165, -0.976).normalize(),
1235 color: Vec3::new(2.85, 1.42, 0.66),
1236 sky_zenith: Vec3::new(0.028, 0.038, 0.155),
1237 sky_horizon: Vec3::new(0.62, 0.24, 0.22),
1238 time_of_day: height_val,
1239 }
1240 } else {
1241 Self {
1242 direction: Vec3::new(-0.36, 0.56, -0.74).normalize(),
1243 color: Vec3::new(0.52, 0.68, 1.22),
1244 sky_zenith: Vec3::new(0.012, 0.022, 0.068),
1245 sky_horizon: Vec3::new(0.068, 0.115, 0.235),
1246 time_of_day: height_val,
1247 }
1248 }
1249 }
1250}
1251
1252impl Default for DirectionalLight3D {
1254 fn default() -> Self {
1260 Self::from_time_of_day(17.2)
1261 }
1262}
1263
1264impl Default for World3D {
1266 fn default() -> Self {
1272 Self {
1273 mesh_library: Vec::new(),
1274 objects: Vec::new(),
1275 camera: Camera3D::default(),
1276 sun: DirectionalLight3D::default(),
1277 bvh: Bvh3D::default(),
1278 dynamic_bvh: Bvh3D::default(),
1279 mesh_local_bvhs: Vec::new(),
1280 dynamic_instances: Vec::new(),
1281 bvh_dirty: true,
1282 dynamic_bvh_dirty: true,
1283 dynamic_topology_dirty: true,
1284 static_bvh_rebuilds: 0,
1285 dynamic_bvh_refits: 0,
1286 dynamic_bvh_rebuilds: 0,
1287 world_revision: 1,
1288 sim_tick: 0,
1289 dynamic_tris_scratch: Vec::new(),
1290 chunk_size: 64.0,
1291 player_vehicle_index: None,
1292 hero_vehicle_style: HeroVehicleStyle::AventadorV12,
1293 hero_vehicle_meshes: [None, None],
1294 imported_model_count: 0,
1295 camera_mode: 0,
1296 camera_orbit_rad: 0.4,
1297 point_lights: Vec::new(),
1298 spot_lights: Vec::new(),
1299 niagara: NiagaraSystem3D::default(),
1300 atmosphere_preset: 0,
1301 traffic_vehicles: Vec::new(),
1302 player_physics: PlayerVehiclePhysics3D::default(),
1303 world_time_secs: 0.0,
1304 scene_graph: SceneGraph3D::default(),
1305 principled_materials: Vec::new(),
1306 textures: Vec::new(),
1307 skins: Vec::new(),
1308 animation_mixer: AnimationMixer3D::default(),
1309 environment_ibl: None,
1310 area_lights: Vec::new(),
1311 scene_cameras: Vec::new(),
1312 active_scene_camera: None,
1313 node_object_map: Vec::new(),
1314 skin_scratch: SkinPaletteScratch3D::default(),
1315 deformed_meshes: Vec::new(),
1316 use_agx_tonemap: false,
1317 gpu_pass_scratch: World3dGpuPassScratch::default(),
1318 pbr_pass_scratch: World3dPbrPassScratch::default(),
1319 }
1320 }
1321}
1322
1323impl World3D {
1325 pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
1336 let id: usize = self.get_mesh_library().len();
1337 self.get_mut_mesh_library().push(chain);
1338 id
1339 }
1340
1341 pub fn spawn_object(
1356 &mut self,
1357 name: &str,
1358 mesh_id: usize,
1359 transform: Transform3D,
1360 material: PbrMaterial,
1361 ray_trace_caster: bool,
1362 ) -> usize {
1363 let local_bounds: AxisAlignedBox3D = self
1364 .get_mesh_library()
1365 .get(mesh_id)
1366 .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1367 .map(Mesh3D::get_bounds)
1368 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1369 let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1370 let cs: f32 = self.get_chunk_size().max(8.0);
1371 let pos: Vec3 = transform.get_position();
1372 let chunk_coord: (i32, i32) = (
1373 (pos.get_x() / cs).floor() as i32,
1374 (pos.get_z() / cs).floor() as i32,
1375 );
1376 let idx: usize = self.get_objects().len();
1377 self.get_mut_objects().push(SceneObject3D {
1378 name: name.to_string(),
1379 mesh_id,
1380 transform,
1381 material,
1382 world_bounds,
1383 chunk_coord,
1384 ray_trace_caster,
1385 solid_collider: ray_trace_caster,
1386 spin_speed: 0.0,
1387 is_dynamic: false,
1388 teleport_epoch: 0,
1389 node_id: None,
1390 principled_material_id: None,
1391 skin_id: None,
1392 });
1393 let Self {
1394 deformed_meshes, ..
1395 } = self;
1396 deformed_meshes.push(None);
1397 if ray_trace_caster {
1398 self.set_bvh_dirty(true);
1399 }
1400 self.bump_world_revision();
1401 idx
1402 }
1403
1404 pub fn bump_world_revision(&mut self) {
1410 let next: u64 = self.get_world_revision().wrapping_add(1);
1411 self.set_world_revision(next);
1412 }
1413
1414 pub fn set_object_dynamic(&mut self, obj_idx: usize, is_dynamic: bool) -> bool {
1426 let Some(obj) = self.get_mut_objects().get_mut(obj_idx) else {
1427 return false;
1428 };
1429 if obj.get_is_dynamic() != is_dynamic {
1430 obj.set_is_dynamic(is_dynamic);
1431 if obj.get_ray_trace_caster() {
1432 self.set_bvh_dirty(true);
1433 self.set_dynamic_bvh_dirty(true);
1434 self.set_dynamic_topology_dirty(true);
1435 }
1436 self.bump_world_revision();
1437 }
1438 true
1439 }
1440
1441 pub fn teleport_object(&mut self, obj_idx: usize, transform: Transform3D) -> bool {
1453 let Some((mesh_id, ray_caster, is_dynamic)) =
1454 self.get_objects().get(obj_idx).map(|obj: &SceneObject3D| {
1455 (
1456 obj.get_mesh_id(),
1457 obj.get_ray_trace_caster(),
1458 obj.get_is_dynamic(),
1459 )
1460 })
1461 else {
1462 return false;
1463 };
1464 let local_bounds: AxisAlignedBox3D = self
1465 .get_mesh_library()
1466 .get(mesh_id)
1467 .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1468 .map(Mesh3D::get_bounds)
1469 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1470 let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1471 if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1472 obj.set_transform(transform);
1473 obj.set_world_bounds(world_bounds);
1474 let next_epoch: u32 = obj.get_teleport_epoch().wrapping_add(1);
1475 obj.set_teleport_epoch(next_epoch);
1476 }
1477 if self.vehicle_index() == Some(obj_idx) {
1478 let Self { player_physics, .. } = self;
1479 let saved_charge: f32 = player_physics.get_boost_charge();
1480 *player_physics = PlayerVehiclePhysics3D::default();
1481 player_physics.set_boost_charge(saved_charge);
1482 } else {
1483 let Self {
1484 traffic_vehicles, ..
1485 } = self;
1486 for npc in traffic_vehicles.iter_mut() {
1487 if npc.get_object_index() == obj_idx {
1488 npc.set_vel(Vec3::zero());
1489 npc.set_yaw_rate(0.0);
1490 npc.set_recovery_timer(0.0);
1491 break;
1492 }
1493 }
1494 }
1495 if ray_caster {
1496 if is_dynamic {
1497 self.set_dynamic_bvh_dirty(true);
1498 } else {
1499 self.set_bvh_dirty(true);
1500 }
1501 }
1502 self.bump_world_revision();
1503 true
1504 }
1505
1506 pub fn import_model(
1521 &mut self,
1522 format: ModelFormat,
1523 source: &str,
1524 transform: Transform3D,
1525 fallback_material: PbrMaterial,
1526 spin_speed: f32,
1527 ) -> Result<ImportedModel3D, String> {
1528 let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
1529 let model_name: String = imported.get_name().clone();
1530 for (item_index, chain) in imported.get_meshes().iter().cloned().enumerate() {
1531 let mat: PbrMaterial = chain
1532 .get_levels()
1533 .first()
1534 .map(Mesh3D::get_material)
1535 .unwrap_or(fallback_material);
1536 let mid: usize = self.register_mesh(chain);
1537 let obj_idx: usize = self.spawn_object(
1538 &format!("{model_name}_{item_index}"),
1539 mid,
1540 transform,
1541 mat,
1542 true,
1543 );
1544 if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1545 obj.set_spin_speed(spin_speed);
1546 }
1547 if spin_speed.abs() > 0.001 {
1548 let _: bool = self.set_object_dynamic(obj_idx, true);
1549 }
1550 }
1551 let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
1552 self.set_imported_model_count(next_cnt);
1553 Ok(imported)
1554 }
1555
1556 pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
1567 let idx: usize = self.spawn_object(
1568 desc.get_name(),
1569 desc.get_mesh_id(),
1570 desc.get_transform(),
1571 desc.get_material(),
1572 desc.get_ray_trace_caster(),
1573 );
1574 if let Some(obj) = self.get_mut_objects().get_mut(idx) {
1575 obj.set_solid_collider(desc.get_solid_collider());
1576 obj.set_spin_speed(desc.get_spin_speed());
1577 }
1578 if desc.get_is_dynamic() || desc.get_spin_speed().abs() > 0.001 {
1579 let _: bool = self.set_object_dynamic(idx, true);
1580 }
1581 idx
1582 }
1583
1584 pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
1595 self.import_model(
1596 desc.get_format(),
1597 desc.get_source(),
1598 desc.get_transform(),
1599 desc.get_fallback_material(),
1600 desc.get_spin_speed(),
1601 )
1602 }
1603
1604 #[must_use]
1614 pub fn active_camera_mode(&self) -> CameraMode3D {
1615 CameraMode3D::from_u8(self.get_camera_mode())
1616 }
1617
1618 pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
1625 self.set_camera_mode(mode.as_u8());
1626 }
1627
1628 fn collect_caster_triangles(
1637 objects: &[SceneObject3D],
1638 mesh_library: &[MeshLodChain],
1639 dynamic_filter: bool,
1640 out_tris: &mut Vec<BvhTriangle>,
1641 ) {
1642 out_tris.clear();
1643 for obj in objects.iter() {
1644 if !obj.get_ray_trace_caster() || obj.get_is_dynamic() != dynamic_filter {
1645 continue;
1646 }
1647 let Some(chain) = mesh_library.get(obj.get_mesh_id()) else {
1648 continue;
1649 };
1650 let Some(mesh) = chain.get_levels().first() else {
1651 continue;
1652 };
1653 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1654 let model_m: Mat4 = obj.get_transform().to_mat4();
1655 let mat: PbrMaterial = obj.get_material();
1656 for (tri_idx, tri) in mesh.get_indices().iter().enumerate() {
1657 let (i0, i1, i2): (usize, usize, usize) =
1658 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1659 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1660 let p0: Vec3 = model_m.mul_point3(verts[i0].get_position());
1661 let p1: Vec3 = model_m.mul_point3(verts[i1].get_position());
1662 let p2: Vec3 = model_m.mul_point3(verts[i2].get_position());
1663 let (tri_mat, mat_slot): (PbrMaterial, u16) =
1664 mesh.resolve_triangle_material(tri_idx, mat);
1665 out_tris.push(BvhTriangle::from_points_with_slot(
1666 p0, p1, p2, tri_mat, mat_slot,
1667 ));
1668 }
1669 }
1670 }
1671 }
1672
1673 pub fn ensure_bvh(&mut self) {
1679 if self.get_bvh_dirty() {
1680 let mut static_tris: Vec<BvhTriangle> = Vec::new();
1681 Self::collect_caster_triangles(
1682 self.get_objects().as_slice(),
1683 self.get_mesh_library().as_slice(),
1684 false,
1685 &mut static_tris,
1686 );
1687 self.set_bvh(Bvh3D::build(static_tris));
1688 self.set_bvh_dirty(false);
1689 let next_static: u64 = self.get_static_bvh_rebuilds().saturating_add(1);
1690 self.set_static_bvh_rebuilds(next_static);
1691 }
1692 if self.get_dynamic_bvh_dirty() {
1693 let topology_dirty: bool = self.get_dynamic_topology_dirty();
1694 let Self {
1695 objects,
1696 mesh_library,
1697 dynamic_bvh,
1698 dynamic_tris_scratch,
1699 dynamic_bvh_dirty,
1700 dynamic_topology_dirty,
1701 dynamic_bvh_refits,
1702 dynamic_bvh_rebuilds,
1703 ..
1704 } = self;
1705 Self::collect_caster_triangles(
1706 objects.as_slice(),
1707 mesh_library.as_slice(),
1708 true,
1709 dynamic_tris_scratch,
1710 );
1711 if dynamic_tris_scratch.is_empty() {
1712 dynamic_bvh.rebuild_in_place(&[]);
1713 } else if !topology_dirty
1714 && dynamic_bvh.refit_from_source(dynamic_tris_scratch.as_slice())
1715 {
1716 let check_degraded: bool = ((*dynamic_bvh_refits + 1) & 15) == 0;
1717 if check_degraded && dynamic_bvh.needs_rebuild_after_refit(3.5) {
1718 dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1719 *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1720 } else {
1721 *dynamic_bvh_refits = dynamic_bvh_refits.saturating_add(1);
1722 }
1723 } else {
1724 dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1725 *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1726 }
1727 *dynamic_bvh_dirty = false;
1728 *dynamic_topology_dirty = false;
1729 }
1730 self.sync_dynamic_ray_instances();
1731 }
1732
1733 pub fn sync_dynamic_ray_instances(&mut self) {
1739 let Self {
1740 mesh_library,
1741 objects,
1742 mesh_local_bvhs,
1743 dynamic_instances,
1744 ..
1745 } = self;
1746 if mesh_local_bvhs.len() < mesh_library.len() {
1747 mesh_local_bvhs.resize_with(mesh_library.len(), || None);
1748 }
1749 dynamic_instances.clear();
1750 for (obj_idx, obj) in objects.iter().enumerate() {
1751 if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
1752 continue;
1753 }
1754 let mesh_id: usize = obj.get_mesh_id();
1755 let Some(chain) = mesh_library.get(mesh_id) else {
1756 continue;
1757 };
1758 let Some(mesh) = chain.get_levels().first() else {
1759 continue;
1760 };
1761 if mesh_local_bvhs[mesh_id].is_none() {
1762 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1763 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
1764 let mut local_tris: Vec<BvhTriangle> = Vec::with_capacity(indices.len());
1765 let neutral: PbrMaterial = PbrMaterial::default();
1766 for (tri_idx, tri) in indices.iter().enumerate() {
1767 let (i0, i1, i2): (usize, usize, usize) =
1768 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1769 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1770 let (tri_mat, mat_slot): (PbrMaterial, u16) =
1771 mesh.resolve_triangle_material(tri_idx, neutral);
1772 local_tris.push(BvhTriangle::from_points_with_slot(
1773 verts[i0].get_position(),
1774 verts[i1].get_position(),
1775 verts[i2].get_position(),
1776 tri_mat,
1777 mat_slot,
1778 ));
1779 }
1780 }
1781 mesh_local_bvhs[mesh_id] = Some(Bvh3D::build(local_tris));
1782 }
1783 let transform_val: Transform3D = obj.get_transform();
1784 dynamic_instances.push(DynamicRayInstance {
1785 obj_idx,
1786 mesh_id,
1787 world_bounds: obj.get_world_bounds(),
1788 inv_model: transform_val.to_inv_mat4(),
1789 normal_basis: transform_val.normal_mat3(),
1790 material: obj.get_material(),
1791 });
1792 }
1793 }
1794
1795 pub(crate) fn override_dynamic_instance_pose(
1804 &mut self,
1805 obj_idx: usize,
1806 transform: Transform3D,
1807 world_bounds: AxisAlignedBox3D,
1808 ) {
1809 let Self {
1810 dynamic_instances, ..
1811 } = self;
1812 for inst in dynamic_instances.iter_mut() {
1813 if inst.obj_idx == obj_idx {
1814 inst.world_bounds = world_bounds;
1815 inst.inv_model = transform.to_inv_mat4();
1816 inst.normal_basis = transform.normal_mat3();
1817 return;
1818 }
1819 }
1820 }
1821
1822 #[inline(always)]
1836 #[must_use]
1837 pub(crate) fn trace_any_shadow_dynamic_instances(
1838 instances: &[DynamicRayInstance],
1839 local_bvhs: &[Option<Bvh3D>],
1840 ray: (Vec3, Vec3, Vec3),
1841 bounds: (f32, f32),
1842 dyn_cache: &mut u32,
1843 ) -> bool {
1844 let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1845 let (t_min, t_max): (f32, f32) = bounds;
1846 for inst in instances.iter() {
1847 if !inst
1848 .world_bounds
1849 .intersect_ray_near(origin, inv_dir, t_min, t_max)
1850 .is_finite()
1851 {
1852 continue;
1853 }
1854 let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1855 continue;
1856 };
1857 let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1858 let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1859 let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1860 if local_bvh
1861 .trace_any_shadow_cached(local_orig, local_dir, local_inv, t_min, t_max, dyn_cache)
1862 {
1863 return true;
1864 }
1865 }
1866 false
1867 }
1868
1869 #[inline(always)]
1885 #[must_use]
1886 pub(crate) fn trace_any_shadow_packet4_with_instances(
1887 static_bvh: &Bvh3D,
1888 instances: &[DynamicRayInstance],
1889 local_bvhs: &[Option<Bvh3D>],
1890 pkt: &RayPacket4,
1891 active_mask: u8,
1892 bounds: (f32, f32),
1893 caches: (&mut u32, &mut u32),
1894 ) -> u8 {
1895 let (t_min, t_max): (f32, f32) = bounds;
1896 let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1897 let mut occluded: u8 =
1898 static_bvh.trace_any_shadow_packet4(pkt, active_mask, t_min, t_max, static_cache);
1899 let mut rem: u8 = active_mask & !occluded;
1900 if rem == 0 || instances.is_empty() {
1901 return occluded;
1902 }
1903 for inst in instances.iter() {
1904 let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1905 continue;
1906 };
1907 let mut hit_box_mask: u8 = 0;
1908 let mut check: u8 = rem;
1909 while check != 0 {
1910 let red_val: usize = check.trailing_zeros() as usize;
1911 check &= check - 1;
1912 let orig_r: Vec3 = Vec3::new(pkt.ox[red_val], pkt.oy[red_val], pkt.oz[red_val]);
1913 let inv_r: Vec3 = Vec3::new(pkt.ix[red_val], pkt.iy[red_val], pkt.iz[red_val]);
1914 if inst
1915 .world_bounds
1916 .intersect_ray_near(orig_r, inv_r, t_min, t_max)
1917 .is_finite()
1918 {
1919 hit_box_mask |= 1_u8 << red_val;
1920 }
1921 }
1922 if hit_box_mask == 0 {
1923 continue;
1924 }
1925 let mut local_pkt: RayPacket4 = *pkt;
1926 let mut tr_mask: u8 = hit_box_mask;
1927 while tr_mask != 0 {
1928 let radius_val: usize = tr_mask.trailing_zeros() as usize;
1929 tr_mask &= tr_mask - 1;
1930 let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1931 pkt.ox[radius_val],
1932 pkt.oy[radius_val],
1933 pkt.oz[radius_val],
1934 ));
1935 let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1936 pkt.dx[radius_val],
1937 pkt.dy[radius_val],
1938 pkt.dz[radius_val],
1939 ));
1940 let li: Vec3 = Ray3D::safe_inv_vec(ld);
1941 local_pkt.ox[radius_val] = lo.get_x();
1942 local_pkt.oy[radius_val] = lo.get_y();
1943 local_pkt.oz[radius_val] = lo.get_z();
1944 local_pkt.dx[radius_val] = ld.get_x();
1945 local_pkt.dy[radius_val] = ld.get_y();
1946 local_pkt.dz[radius_val] = ld.get_z();
1947 local_pkt.ix[radius_val] = li.get_x();
1948 local_pkt.iy[radius_val] = li.get_y();
1949 local_pkt.iz[radius_val] = li.get_z();
1950 }
1951 let dyn_occ: u8 = local_bvh.trace_any_shadow_packet4(
1952 &local_pkt,
1953 hit_box_mask,
1954 t_min,
1955 t_max,
1956 dyn_cache,
1957 );
1958 occluded |= dyn_occ;
1959 rem &= !dyn_occ;
1960 if rem == 0 {
1961 break;
1962 }
1963 }
1964 occluded
1965 }
1966
1967 #[inline(always)]
1982 #[must_use]
1983 pub(crate) fn trace_any_shadow_with_instances(
1984 static_bvh: &Bvh3D,
1985 instances: &[DynamicRayInstance],
1986 local_bvhs: &[Option<Bvh3D>],
1987 ray: (Vec3, Vec3, Vec3),
1988 bounds: (f32, f32),
1989 caches: (&mut u32, &mut u32),
1990 ) -> bool {
1991 let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1992 let (t_min, t_max): (f32, f32) = bounds;
1993 let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1994 if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
1995 return true;
1996 }
1997 if !instances.is_empty() {
1998 return Self::trace_any_shadow_dynamic_instances(
1999 instances, local_bvhs, ray, bounds, dyn_cache,
2000 );
2001 }
2002 false
2003 }
2004
2005 #[inline(always)]
2019 #[must_use]
2020 pub(crate) fn trace_closest_with_instances(
2021 static_bvh: &Bvh3D,
2022 instances: &[DynamicRayInstance],
2023 local_bvhs: &[Option<Bvh3D>],
2024 ray: (Vec3, Vec3, Vec3),
2025 bounds: (f32, f32),
2026 ) -> Option<(f32, Vec3, PbrMaterial)> {
2027 let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2028 let (t_min, t_max): (f32, f32) = bounds;
2029 let mut best_t: f32 = t_max;
2030 let mut best_hit: Option<(f32, Vec3, PbrMaterial)> = static_bvh
2031 .trace_closest_raw(origin, dir, inv_dir, t_min, t_max)
2032 .map(|(node_style, si): (f32, usize)| {
2033 let tri: &BvhTriangle = &static_bvh.get_triangles()[si];
2034 best_t = node_style;
2035 (node_style, tri.get_normal(), tri.get_material())
2036 });
2037 for inst in instances.iter() {
2038 if !inst
2039 .world_bounds
2040 .intersect_ray_near(origin, inv_dir, t_min, best_t)
2041 .is_finite()
2042 {
2043 continue;
2044 }
2045 let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
2046 continue;
2047 };
2048 let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
2049 let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
2050 let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
2051 if let Some((dt, di)) =
2052 local_bvh.trace_closest_raw(local_orig, local_dir, local_inv, t_min, best_t)
2053 {
2054 best_t = dt;
2055 let hit_tri: &BvhTriangle = &local_bvh.get_triangles()[di];
2056 let local_n: Vec3 = hit_tri.get_normal();
2057 let world_n: Vec3 = Mat4::transform_normal_with_basis(local_n, inst.normal_basis);
2058 let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
2059 inst.material
2060 } else {
2061 hit_tri.get_material()
2062 };
2063 best_hit = Some((dt, world_n, hit_mat));
2064 }
2065 }
2066 best_hit
2067 }
2068
2069 #[inline(always)]
2084 #[must_use]
2085 pub(crate) fn trace_closest_packet4_with_instances(
2086 static_bvh: &Bvh3D,
2087 instances: &[DynamicRayInstance],
2088 local_bvhs: &[Option<Bvh3D>],
2089 pkt: &RayPacket4,
2090 active_mask: u8,
2091 bounds: (f32, f32),
2092 ) -> [Option<(f32, Vec3, PbrMaterial)>; 4] {
2093 let (t_min, t_max): (f32, f32) = bounds;
2094 let mut best_t: [f32; 4] = [t_max; 4];
2095 let mut best_static_idx: [usize; 4] = [usize::MAX; 4];
2096 static_bvh.trace_closest_packet4(
2097 pkt,
2098 active_mask,
2099 t_min,
2100 &mut best_t,
2101 &mut best_static_idx,
2102 );
2103 let static_tris: &[BvhTriangle] = static_bvh.get_triangles().as_slice();
2104 let mut out: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
2105 let mut matrix_elems: u8 = active_mask;
2106 while matrix_elems != 0 {
2107 let red_val: usize = matrix_elems.trailing_zeros() as usize;
2108 matrix_elems &= matrix_elems - 1;
2109 let sidx: usize = best_static_idx[red_val];
2110 if sidx != usize::MAX {
2111 let tri: &BvhTriangle = &static_tris[sidx];
2112 out[red_val] = Some((best_t[red_val], tri.get_normal(), tri.get_material()));
2113 }
2114 }
2115 for inst in instances.iter() {
2116 let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
2117 continue;
2118 };
2119 let mut hit_box_mask: u8 = 0;
2120 let mut check: u8 = active_mask;
2121 while check != 0 {
2122 let radius_val: usize = check.trailing_zeros() as usize;
2123 check &= check - 1;
2124 if inst
2125 .world_bounds
2126 .intersect_ray_near(
2127 Vec3::new(pkt.ox[radius_val], pkt.oy[radius_val], pkt.oz[radius_val]),
2128 Vec3::new(pkt.ix[radius_val], pkt.iy[radius_val], pkt.iz[radius_val]),
2129 t_min,
2130 best_t[radius_val],
2131 )
2132 .is_finite()
2133 {
2134 hit_box_mask |= 1_u8 << radius_val;
2135 }
2136 }
2137 if hit_box_mask == 0 {
2138 continue;
2139 }
2140 let mut local_pkt: RayPacket4 = *pkt;
2141 let mut tr_mask: u8 = hit_box_mask;
2142 while tr_mask != 0 {
2143 let rect_val: usize = tr_mask.trailing_zeros() as usize;
2144 tr_mask &= tr_mask - 1;
2145 let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
2146 pkt.ox[rect_val],
2147 pkt.oy[rect_val],
2148 pkt.oz[rect_val],
2149 ));
2150 let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
2151 pkt.dx[rect_val],
2152 pkt.dy[rect_val],
2153 pkt.dz[rect_val],
2154 ));
2155 let li: Vec3 = Ray3D::safe_inv_vec(ld);
2156 local_pkt.ox[rect_val] = lo.get_x();
2157 local_pkt.oy[rect_val] = lo.get_y();
2158 local_pkt.oz[rect_val] = lo.get_z();
2159 local_pkt.dx[rect_val] = ld.get_x();
2160 local_pkt.dy[rect_val] = ld.get_y();
2161 local_pkt.dz[rect_val] = ld.get_z();
2162 local_pkt.ix[rect_val] = li.get_x();
2163 local_pkt.iy[rect_val] = li.get_y();
2164 local_pkt.iz[rect_val] = li.get_z();
2165 }
2166 let mut dyn_idx: [usize; 4] = [usize::MAX; 4];
2167 local_bvh.trace_closest_packet4(
2168 &local_pkt,
2169 hit_box_mask,
2170 t_min,
2171 &mut best_t,
2172 &mut dyn_idx,
2173 );
2174 let local_tris: &[BvhTriangle] = local_bvh.get_triangles().as_slice();
2175 let mut upd: u8 = hit_box_mask;
2176 while upd != 0 {
2177 let row_val: usize = upd.trailing_zeros() as usize;
2178 upd &= upd - 1;
2179 let di: usize = dyn_idx[row_val];
2180 if di != usize::MAX {
2181 let hit_tri: &BvhTriangle = &local_tris[di];
2182 let wn: Vec3 =
2183 Mat4::transform_normal_with_basis(hit_tri.get_normal(), inst.normal_basis);
2184 let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
2185 inst.material
2186 } else {
2187 hit_tri.get_material()
2188 };
2189 out[row_val] = Some((best_t[row_val], wn, hit_mat));
2190 }
2191 }
2192 }
2193 out
2194 }
2195
2196 #[must_use]
2209 pub fn trace_any_shadow_object_space(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
2210 let Self {
2211 bvh,
2212 dynamic_instances,
2213 mesh_local_bvhs,
2214 ..
2215 } = self;
2216 let mut scale_factor: u32 = u32::MAX;
2217 let mut dc: u32 = u32::MAX;
2218 Self::trace_any_shadow_with_instances(
2219 bvh,
2220 dynamic_instances.as_slice(),
2221 mesh_local_bvhs.as_slice(),
2222 (
2223 ray.get_origin(),
2224 ray.get_direction(),
2225 ray.get_inv_direction(),
2226 ),
2227 (t_min, t_max),
2228 (&mut scale_factor, &mut dc),
2229 )
2230 }
2231
2232 #[must_use]
2246 pub fn trace_closest_packet4(
2247 &self,
2248 pkt: &RayPacket4,
2249 active_mask: u8,
2250 t_min: f32,
2251 t_max: f32,
2252 ) -> [Option<RayHit3D>; 4] {
2253 let Self {
2254 bvh,
2255 dynamic_instances,
2256 mesh_local_bvhs,
2257 ..
2258 } = self;
2259 let raw: [Option<(f32, Vec3, PbrMaterial)>; 4] = Self::trace_closest_packet4_with_instances(
2260 bvh,
2261 dynamic_instances.as_slice(),
2262 mesh_local_bvhs.as_slice(),
2263 pkt,
2264 active_mask,
2265 (t_min, t_max),
2266 );
2267 let mut out: [Option<RayHit3D>; 4] = [None; 4];
2268 for lane in 0..4 {
2269 if let Some((blend_factor, normal, material)) = raw[lane] {
2270 let point: Vec3 = Vec3::new(
2271 pkt.ox[lane] + pkt.dx[lane] * blend_factor,
2272 pkt.oy[lane] + pkt.dy[lane] * blend_factor,
2273 pkt.oz[lane] + pkt.dz[lane] * blend_factor,
2274 );
2275 out[lane] = Some(RayHit3D {
2276 distance: blend_factor,
2277 point,
2278 normal,
2279 material,
2280 });
2281 }
2282 }
2283 out
2284 }
2285
2286 #[must_use]
2299 pub fn trace_closest_object_space(
2300 &self,
2301 ray: &Ray3D,
2302 t_min: f32,
2303 t_max: f32,
2304 ) -> Option<RayHit3D> {
2305 let Self {
2306 bvh,
2307 dynamic_instances,
2308 mesh_local_bvhs,
2309 ..
2310 } = self;
2311 let (blend_factor, normal, material): (f32, Vec3, PbrMaterial) =
2312 Self::trace_closest_with_instances(
2313 bvh,
2314 dynamic_instances.as_slice(),
2315 mesh_local_bvhs.as_slice(),
2316 (
2317 ray.get_origin(),
2318 ray.get_direction(),
2319 ray.get_inv_direction(),
2320 ),
2321 (t_min, t_max),
2322 )?;
2323 Some(RayHit3D {
2324 distance: blend_factor,
2325 point: ray
2326 .get_origin()
2327 .add(ray.get_direction().scale(blend_factor)),
2328 normal,
2329 material,
2330 })
2331 }
2332
2333 #[must_use]
2343 pub fn total_bvh_nodes(&self) -> usize {
2344 self.get_bvh()
2345 .get_nodes()
2346 .len()
2347 .saturating_add(self.get_dynamic_bvh().get_nodes().len())
2348 }
2349
2350 #[must_use]
2363 pub fn trace_any_shadow_split(
2364 bvhs: (&Bvh3D, &Bvh3D),
2365 ray: (Vec3, Vec3, Vec3),
2366 bounds: (f32, f32),
2367 caches: (&mut u32, &mut u32),
2368 ) -> bool {
2369 let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2370 let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2371 let (t_min, t_max): (f32, f32) = bounds;
2372 let (static_cache, dynamic_cache): (&mut u32, &mut u32) = caches;
2373 if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
2374 return true;
2375 }
2376 if !dynamic_bvh.is_empty() {
2377 return dynamic_bvh.trace_any_shadow_cached(
2378 origin,
2379 dir,
2380 inv_dir,
2381 t_min,
2382 t_max,
2383 dynamic_cache,
2384 );
2385 }
2386 false
2387 }
2388
2389 #[must_use]
2401 pub fn trace_closest_split(
2402 bvhs: (&Bvh3D, &Bvh3D),
2403 ray: (Vec3, Vec3, Vec3),
2404 bounds: (f32, f32),
2405 ) -> Option<(f32, bool, usize)> {
2406 let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2407 let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2408 let (t_min, t_max): (f32, f32) = bounds;
2409 let static_hit: Option<(f32, usize)> =
2410 static_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, t_max);
2411 let dyn_limit: f32 =
2412 static_hit.map_or(t_max, |(blend_factor, _): (f32, usize)| blend_factor);
2413 let dynamic_hit: Option<(f32, usize)> = if !dynamic_bvh.is_empty() {
2414 dynamic_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, dyn_limit)
2415 } else {
2416 None
2417 };
2418 match (static_hit, dynamic_hit) {
2419 (_, Some((dt, di))) => Some((dt, true, di)),
2420 (Some((node_style, si)), None) => Some((node_style, false, si)),
2421 (None, None) => None,
2422 }
2423 }
2424
2425 #[must_use]
2435 pub fn vehicle_index(&self) -> Option<usize> {
2436 let Self {
2437 player_vehicle_index,
2438 ..
2439 } = self;
2440 *player_vehicle_index
2441 }
2442
2443 #[must_use]
2454 pub fn loop_lateral_offset(world_x: f32, world_z: f32) -> (f32, f32) {
2455 let spine_z: f32 = world_z.clamp(-CITY_LOOP_STRAIGHT_HALF_Z, CITY_LOOP_STRAIGHT_HALF_Z);
2456 let dx: f32 = world_x - CITY_LOOP_CENTER_X;
2457 let dz: f32 = world_z - spine_z;
2458 let d_spine: f32 = dx.hypot(dz);
2459 (d_spine, d_spine - CITY_LOOP_RADIUS)
2460 }
2461
2462 #[must_use]
2473 pub fn loop_pose_at(arc_s: f32, lateral_u: f32) -> (Vec3, f32) {
2474 let straight_len: f32 = 2.0 * CITY_LOOP_STRAIGHT_HALF_Z;
2475 let arc_len: f32 = PI * CITY_LOOP_RADIUS;
2476 let s: f32 = arc_s.rem_euclid(CITY_LOOP_TOTAL_LENGTH);
2477 if s < straight_len {
2478 let world_x: f32 = -lateral_u;
2479 let world_z: f32 = CITY_LOOP_STRAIGHT_HALF_Z - s;
2480 (Vec3::new(world_x, 0.0, world_z), 0.0)
2481 } else if s < straight_len + arc_len {
2482 let alpha: f32 = (s - straight_len) / CITY_LOOP_RADIUS;
2483 let radius: f32 = CITY_LOOP_RADIUS + lateral_u;
2484 let (sin_a, cos_a): (f32, f32) = alpha.sin_cos();
2485 let world_x: f32 = CITY_LOOP_CENTER_X - radius * cos_a;
2486 let world_z: f32 = -CITY_LOOP_STRAIGHT_HALF_Z - radius * sin_a;
2487 (Vec3::new(world_x, 0.0, world_z), -alpha)
2488 } else if s < 2.0 * straight_len + arc_len {
2489 let east_s: f32 = s - (straight_len + arc_len);
2490 let world_x: f32 = CITY_LOOP_CENTER_X * 2.0 + lateral_u;
2491 let world_z: f32 = -CITY_LOOP_STRAIGHT_HALF_Z + east_s;
2492 (Vec3::new(world_x, 0.0, world_z), PI)
2493 } else {
2494 let beta: f32 = (s - (2.0 * straight_len + arc_len)) / CITY_LOOP_RADIUS;
2495 let radius: f32 = CITY_LOOP_RADIUS + lateral_u;
2496 let (sin_b, cos_b): (f32, f32) = beta.sin_cos();
2497 let world_x: f32 = CITY_LOOP_CENTER_X + radius * cos_b;
2498 let world_z: f32 = CITY_LOOP_STRAIGHT_HALF_Z + radius * sin_b;
2499 (Vec3::new(world_x, 0.0, world_z), PI - beta)
2500 }
2501 }
2502
2503 #[must_use]
2509 fn curated_skyline_palettes() -> [PbrMaterial; 6] {
2510 [
2511 PbrMaterial::pbr(Color::hex(0x9E8C73), 0.24, 0.36, 0.38)
2512 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2513 PbrMaterial::pbr(Color::hex(0x163C6B), 0.78, 0.12, 0.76)
2514 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2515 PbrMaterial::pbr(Color::hex(0x141D2D), 0.86, 0.10, 0.82)
2516 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2517 PbrMaterial::pbr(Color::hex(0x7B4232), 0.20, 0.42, 0.32)
2518 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2519 PbrMaterial::pbr(Color::hex(0x0E4B47), 0.74, 0.14, 0.72)
2520 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2521 PbrMaterial::pbr(Color::hex(0x64748B), 0.82, 0.18, 0.70)
2522 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2523 ]
2524 }
2525
2526 fn register_building_archetypes(&mut self) -> [usize; 6] {
2532 let base_mat: PbrMaterial = PbrMaterial::default();
2533 let art_deco: usize = self.register_mesh(MeshLodChain::from_mesh(
2534 Mesh3D::building_art_deco_tower(CITY_MESH_ART_DECO, base_mat),
2535 ));
2536 let chamfered: usize = self.register_mesh(MeshLodChain::from_mesh(
2537 Mesh3D::building_chamfered_glass_tower(CITY_MESH_CHAMFERED, base_mat),
2538 ));
2539 let twisted: usize = self.register_mesh(MeshLodChain::from_mesh(
2540 Mesh3D::building_twisted_spire_tower(CITY_MESH_TWISTED, base_mat),
2541 ));
2542 let cantilever: usize = self.register_mesh(MeshLodChain::from_mesh(
2543 Mesh3D::building_cantilever_tech_tower(CITY_MESH_CANTILEVER, base_mat),
2544 ));
2545 let cylinder: usize = self.register_mesh(MeshLodChain::from_mesh(
2546 Mesh3D::building_cylindrical_landmark(CITY_MESH_CYLINDER, base_mat),
2547 ));
2548 let boutique: usize = self.register_mesh(MeshLodChain::from_mesh(
2549 Mesh3D::building_boutique_podium_block(CITY_MESH_BOUTIQUE, base_mat),
2550 ));
2551 [art_deco, chamfered, twisted, cantilever, cylinder, boutique]
2552 }
2553
2554 #[must_use]
2564 pub fn hero_vehicle_material(style: HeroVehicleStyle) -> PbrMaterial {
2565 match style {
2566 HeroVehicleStyle::AventadorV12 => {
2567 PbrMaterial::pbr(Color::hex(0xFF4500), 0.30, 0.12, 0.42)
2568 }
2569 HeroVehicleStyle::ShelbyCobra => {
2570 PbrMaterial::pbr(Color::hex(0x0A3EC2), 0.30, 0.12, 0.40)
2571 }
2572 }
2573 }
2574
2575 pub fn set_hero_vehicle_style(&mut self, style: HeroVehicleStyle) -> bool {
2586 let Some(car_idx) = self.vehicle_index() else {
2587 self.set_hero_vehicle_style_raw(style);
2588 return false;
2589 };
2590 let slot_idx: usize = match style {
2591 HeroVehicleStyle::AventadorV12 => 0,
2592 HeroVehicleStyle::ShelbyCobra => 1,
2593 };
2594 let cached_entry: Option<(usize, PbrMaterial)> = {
2595 let Self {
2596 hero_vehicle_meshes,
2597 ..
2598 } = self;
2599 hero_vehicle_meshes[slot_idx]
2600 };
2601 let (target_mesh_id, target_mat): (usize, PbrMaterial) = if let Some(pair) = cached_entry {
2602 pair
2603 } else {
2604 let sig_mat: PbrMaterial = Self::hero_vehicle_material(style);
2605 let built_mesh: Mesh3D = match style {
2606 HeroVehicleStyle::AventadorV12 => {
2607 Mesh3D::aventador_svj(CITY_MESH_AVENTADOR, sig_mat)
2608 }
2609 HeroVehicleStyle::ShelbyCobra => Mesh3D::shelby_cobra(CITY_MESH_SHELBY, sig_mat),
2610 };
2611 let new_mesh_id: usize = self.register_mesh(MeshLodChain::single_level(built_mesh));
2612 let Self {
2613 hero_vehicle_meshes,
2614 ..
2615 } = self;
2616 hero_vehicle_meshes[slot_idx] = Some((new_mesh_id, sig_mat));
2617 (new_mesh_id, sig_mat)
2618 };
2619 let already_active: bool = self.get_hero_vehicle_style() == style
2620 && self
2621 .get_objects()
2622 .get(car_idx)
2623 .is_some_and(|obj: &SceneObject3D| obj.get_mesh_id() == target_mesh_id);
2624 if already_active {
2625 return false;
2626 }
2627 let new_local_bounds: AxisAlignedBox3D = self
2628 .get_mesh_library()
2629 .get(target_mesh_id)
2630 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
2631 .map(Mesh3D::get_bounds)
2632 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.2), Vec3::splat(1.2)));
2633 if let Some(car_obj) = self.get_mut_objects().get_mut(car_idx) {
2634 let live_tr: Transform3D = car_obj.get_transform();
2635 car_obj.set_mesh_id(target_mesh_id);
2636 car_obj.set_material(target_mat);
2637 car_obj.set_world_bounds(live_tr.transform_bounds(new_local_bounds));
2638 }
2639 self.set_hero_vehicle_style_raw(style);
2640 self.set_dynamic_topology_dirty(true);
2641 self.set_dynamic_bvh_dirty(true);
2642 self.sync_dynamic_ray_instances();
2643 self.bump_world_revision();
2644 true
2645 }
2646
2647 fn set_hero_vehicle_style_raw(&mut self, style: HeroVehicleStyle) {
2654 let Self {
2655 hero_vehicle_style, ..
2656 } = self;
2657 *hero_vehicle_style = style;
2658 }
2659
2660 #[must_use]
2666 fn build_open_world_city_template() -> OpenWorldCityTemplate3D {
2667 let world: Self = Self::build_open_world_city_uncached();
2668 let rev: u64 = Self::allocate_gpu_mesh_revision();
2669 let (gpu_mesh_buffer, gpu_mesh_ranges): (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) =
2670 world.build_gpu_mesh_buffer(rev);
2671 OpenWorldCityTemplate3D {
2672 world,
2673 gpu_mesh_buffer,
2674 gpu_mesh_ranges,
2675 }
2676 }
2677
2678 fn with_open_world_city_template<F, R>(visitor: F) -> R
2688 where
2689 F: FnOnce(&OpenWorldCityTemplate3D) -> R,
2690 {
2691 #[cfg(not(target_arch = "wasm32"))]
2692 {
2693 let tpl: &OpenWorldCityTemplate3D =
2694 OPEN_WORLD_CITY_TEMPLATE.get_or_init(Self::build_open_world_city_template);
2695 visitor(tpl)
2696 }
2697 #[cfg(target_arch = "wasm32")]
2698 {
2699 OPEN_WORLD_CITY_TEMPLATE_WASM.with(
2700 |slot: &RefCell<Option<OpenWorldCityTemplate3D>>| -> R {
2701 if let Ok(mut guard) = slot.try_borrow_mut() {
2702 if guard.is_none() {
2703 *guard = Some(Self::build_open_world_city_template());
2704 }
2705 if let Some(tpl) = guard.as_ref() {
2706 return visitor(tpl);
2707 }
2708 }
2709 let fallback: OpenWorldCityTemplate3D = Self::build_open_world_city_template();
2710 visitor(&fallback)
2711 },
2712 )
2713 }
2714 }
2715
2716 #[must_use]
2722 pub fn create_open_world_city() -> Self {
2723 Self::with_open_world_city_template(|tpl: &OpenWorldCityTemplate3D| tpl.world.clone())
2724 }
2725
2726 #[must_use]
2732 pub fn create_open_world_city_with_gpu_cache()
2733 -> (Self, Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) {
2734 Self::with_open_world_city_template(|tpl: &OpenWorldCityTemplate3D| {
2735 (
2736 tpl.world.clone(),
2737 Arc::clone(&tpl.gpu_mesh_buffer),
2738 tpl.gpu_mesh_ranges.clone(),
2739 )
2740 })
2741 }
2742
2743 #[must_use]
2749 fn build_open_world_city_uncached() -> Self {
2750 let mut world: Self = Self::default();
2751 world.get_mut_mesh_library().reserve(16);
2752 world.get_mut_objects().reserve(144);
2753 world.get_mut_point_lights().reserve(16);
2754 world.get_mut_spot_lights().reserve(4);
2755 {
2756 let Self {
2757 traffic_vehicles, ..
2758 } = &mut world;
2759 traffic_vehicles.reserve(8);
2760 }
2761 let ground_w: f32 = CITY_GROUND_X_MAX - CITY_GROUND_X_MIN;
2762 let ground_d: f32 = CITY_GROUND_Z_MAX - CITY_GROUND_Z_MIN;
2763 let ground_cx: f32 = (CITY_GROUND_X_MIN + CITY_GROUND_X_MAX) * 0.5;
2764 let ground_cz: f32 = (CITY_GROUND_Z_MIN + CITY_GROUND_Z_MAX) * 0.5;
2765 let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0E131C), 0.08, 0.24, 0.62)
2766 .with_surface_detail(SurfaceDetailMode::RoadSurface);
2767 let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
2768 CITY_GROUND_MESH_NAME,
2769 ground_w,
2770 ground_d,
2771 24,
2772 asphalt_mat,
2773 )));
2774 let _: usize = world.spawn_object(
2775 CITY_GROUND_OBJ_NAME,
2776 road_mesh,
2777 Transform3D::new(Vec3::new(ground_cx, 0.0, ground_cz), 0.0, Vec3::splat(1.0)),
2778 asphalt_mat,
2779 false,
2780 );
2781 let ocean_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x063846), 0.05, 0.06, 0.86)
2782 .with_surface_detail(SurfaceDetailMode::OceanWater);
2783 let ocean_mesh: usize =
2784 world.register_mesh(MeshLodChain::from_mesh(Mesh3D::coastal_ocean_ring(
2785 CITY_OCEAN_MESH_NAME,
2786 CITY_OCEAN_SPAN_M,
2787 ground_w * 0.5,
2788 ground_d * 0.5,
2789 24,
2790 ocean_mat,
2791 )));
2792 let _: usize = world.spawn_object(
2793 CITY_OCEAN_MESH_NAME,
2794 ocean_mesh,
2795 Transform3D::new(
2796 Vec3::new(ground_cx, CITY_OCEAN_SURFACE_Y, ground_cz),
2797 0.0,
2798 Vec3::splat(1.0),
2799 ),
2800 ocean_mat,
2801 false,
2802 );
2803 let stud_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFBBF24), 0.90);
2804 let stud_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2805 CITY_LANE_STUD_MESH_NAME,
2806 0.10,
2807 0.018,
2808 0.16,
2809 true,
2810 stud_mat,
2811 )));
2812 for iz in -7..=0 {
2813 let _: usize = world.spawn_object(
2814 &format!("stripe_{iz}"),
2815 stud_mesh,
2816 Transform3D::new(
2817 Vec3::new(0.0, 0.008, (iz as f32) * 14.0),
2818 0.0,
2819 Vec3::splat(1.0),
2820 ),
2821 stud_mat,
2822 false,
2823 );
2824 }
2825 let unit_box: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2826 CITY_UNIT_BOX_MESH_NAME,
2827 1.0,
2828 1.0,
2829 1.0,
2830 true,
2831 PbrMaterial::default(),
2832 )));
2833 let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2834 CITY_NEON_SIGN_MESH_NAME,
2835 1.0,
2836 1.0,
2837 1.0,
2838 true,
2839 PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
2840 )));
2841 let archetypes: [usize; 6] = world.register_building_archetypes();
2842 let palettes: [PbrMaterial; 6] = Self::curated_skyline_palettes();
2843 let neon_colors: [Color; 4] = [
2844 Color::hex(0x38BDF8),
2845 Color::hex(0xF43F5E),
2846 Color::hex(0xA855F7),
2847 Color::hex(0x34D399),
2848 ];
2849 let west_pattern: [(usize, f32, f32, f32); 9] = [
2850 (0, 46.0, 11.2, 12.0),
2851 (5, 20.0, 11.6, 12.4),
2852 (1, 38.0, 11.0, 11.8),
2853 (3, 34.0, 10.6, 11.8),
2854 (4, 48.0, 11.4, 11.4),
2855 (5, 22.0, 11.4, 12.2),
2856 (2, 54.0, 11.2, 11.2),
2857 (1, 40.0, 10.8, 12.0),
2858 (0, 44.0, 11.0, 11.6),
2859 ];
2860 let mut idx_counter: usize = 0;
2861 for side in [-1.0_f32, 1.0_f32] {
2862 for (row_i, row_z_idx) in (-4..=4_i32).enumerate() {
2863 let (base_arch, base_h, width_val, depth_val): (usize, f32, f32, f32) =
2864 west_pattern[(row_i + if side > 0.0 { 2 } else { 0 }) % west_pattern.len()];
2865 let pos_z: f32 = (row_z_idx as f32) * 28.0 - 4.0;
2866 let pos_x: f32 = side * (22.0 + ((idx_counter % 3) as f32) * 1.1);
2867 let height_val: f32 = if side > 0.0 && base_arch != 5 {
2868 base_h + 4.0
2869 } else {
2870 base_h
2871 };
2872 let mat: PbrMaterial = palettes[(idx_counter * 5 + row_i) % palettes.len()];
2873 let _: usize = world.spawn_object(
2874 &format!("tower_{idx_counter}"),
2875 archetypes[base_arch],
2876 Transform3D::new(
2877 Vec3::new(pos_x, 0.0, pos_z),
2878 0.0,
2879 Vec3::new(width_val, height_val, depth_val),
2880 ),
2881 mat,
2882 true,
2883 );
2884 idx_counter += 1;
2885 }
2886 }
2887 let inner_spine_specs: [(f32, f32, f32, f32, f32, usize, usize); 19] = [
2888 (64.0, -158.0, 14.0, 56.0, 14.0, 4, 1),
2889 (64.0, -116.0, 14.5, 68.0, 14.5, 0, 0),
2890 (54.0, -76.0, 13.0, 62.0, 13.0, 2, 2),
2891 (76.0, -76.0, 13.0, 52.0, 13.0, 1, 4),
2892 (64.0, -34.0, 15.0, 74.0, 15.0, 2, 5),
2893 (52.0, 10.0, 13.5, 58.0, 13.5, 3, 3),
2894 (78.0, 12.0, 13.5, 64.0, 13.5, 4, 1),
2895 (64.0, 56.0, 14.5, 70.0, 14.5, 0, 0),
2896 (54.0, 98.0, 13.0, 54.0, 13.0, 1, 2),
2897 (76.0, 100.0, 13.0, 48.0, 13.0, 3, 4),
2898 (64.0, 156.0, 14.0, 58.0, 14.0, 4, 5),
2899 (103.5, -112.0, 11.4, 34.0, 12.4, 5, 0),
2900 (103.5, -78.0, 11.6, 48.0, 11.6, 4, 4),
2901 (103.5, -44.0, 11.4, 24.0, 12.2, 5, 3),
2902 (103.5, -10.0, 11.8, 44.0, 12.0, 1, 1),
2903 (103.5, 24.0, 11.4, 38.0, 12.0, 3, 5),
2904 (103.5, 58.0, 11.6, 22.0, 12.2, 5, 0),
2905 (103.5, 92.0, 11.8, 46.0, 11.8, 0, 2),
2906 (103.5, 124.0, 11.4, 40.0, 11.4, 2, 4),
2907 ];
2908 for (l_idx, &(lx, lz, lw, lh, ld, l_arch, l_pal)) in inner_spine_specs.iter().enumerate() {
2909 let _: usize = world.spawn_object(
2910 &format!("landmark_tower_{l_idx}"),
2911 archetypes[l_arch],
2912 Transform3D::new(Vec3::new(lx, 0.0, lz), 0.0, Vec3::new(lw, lh, ld)),
2913 palettes[l_pal],
2914 true,
2915 );
2916 }
2917 let skyline_specs: [(f32, f32, f32, f32, usize, usize); 6] = [
2918 (-46.0, -96.0, 13.0, 56.0, 0, 2),
2919 (-46.0, -64.0, 12.5, 66.0, 2, 1),
2920 (-46.0, -32.0, 13.0, 52.0, 4, 4),
2921 (-46.0, 4.0, 12.5, 62.0, 1, 5),
2922 (-46.0, 40.0, 12.5, 50.0, 3, 3),
2923 (-46.0, 76.0, 13.0, 58.0, 0, 0),
2924 ];
2925 for (sky_idx, &(sx, sz, sw, sh, s_arch, s_pal)) in skyline_specs.iter().enumerate() {
2926 let _: usize = world.spawn_object(
2927 &format!("{CITY_SKYLINE_MESH_NAME}_{sky_idx}"),
2928 archetypes[s_arch],
2929 Transform3D::new(Vec3::new(sx, 0.0, sz), 0.0, Vec3::new(sw, sh, 13.0)),
2930 palettes[s_pal],
2931 true,
2932 );
2933 }
2934 let mut rim_serial: usize = 0;
2935 let rim_angles_deg: [f32; 7] = [44.0, 64.0, 84.0, 104.0, 124.0, 144.0, 164.0];
2936 for (turn_idx, &turn_sign_z) in [-1.0_f32, 1.0_f32].iter().enumerate() {
2937 let center_z: f32 = turn_sign_z * CITY_LOOP_STRAIGHT_HALF_Z;
2938 for (ang_i, °) in rim_angles_deg.iter().enumerate() {
2939 let rad: f32 = deg.to_radians();
2940 let (sin_a, cos_a): (f32, f32) = rad.sin_cos();
2941 let ring_r: f32 = 94.0 + ((ang_i % 2) as f32) * 3.5;
2942 let rx: f32 = CITY_LOOP_CENTER_X + ring_r * cos_a;
2943 let rz: f32 = center_z + turn_sign_z * ring_r * sin_a;
2944 let yaw_rim: f32 = if turn_sign_z < 0.0 {
2945 rad - FRAC_PI_2
2946 } else {
2947 FRAC_PI_2 - rad
2948 };
2949 let arch_i: usize = (rim_serial + turn_idx * 2) % archetypes.len();
2950 let height_m: f32 = if arch_i == 5 {
2951 24.0
2952 } else {
2953 36.0 + ((rim_serial * 7) % 4) as f32 * 8.0
2954 };
2955 let _: usize = world.spawn_object(
2956 &format!("rim_tower_{rim_serial}"),
2957 archetypes[arch_i],
2958 Transform3D::new(
2959 Vec3::new(rx, 0.0, rz),
2960 yaw_rim,
2961 Vec3::new(11.5, height_m, 11.5),
2962 ),
2963 palettes[(rim_serial + 1) % palettes.len()],
2964 true,
2965 );
2966 rim_serial += 1;
2967 }
2968 }
2969 let seawall_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x475569), 0.14, 0.56, 0.22);
2970 let mut wall_serial: usize = 0;
2971 let _: usize = world.spawn_object(
2972 &format!("{CITY_SEAWALL_MESH_NAME}_{wall_serial}"),
2973 unit_box,
2974 Transform3D::new(
2975 Vec3::new(142.8, 0.0, 0.0),
2976 0.0,
2977 Vec3::new(2.4, 1.15, CITY_LOOP_STRAIGHT_HALF_Z * 2.0 + 4.0),
2978 ),
2979 seawall_mat,
2980 true,
2981 );
2982 wall_serial += 1;
2983 for &turn_sign_z in [-1.0_f32, 1.0_f32].iter() {
2984 let center_z: f32 = turn_sign_z * CITY_LOOP_STRAIGHT_HALF_Z;
2985 let seg_count: usize = 10;
2986 for seg_i in 0..seg_count {
2987 let deg: f32 = 3.0 + (seg_i as f32) * 6.0;
2988 let rad: f32 = deg.to_radians();
2989 let (sin_a, cos_a): (f32, f32) = rad.sin_cos();
2990 let wall_r: f32 = 79.0;
2991 let wx: f32 = CITY_LOOP_CENTER_X + wall_r * cos_a;
2992 let wz: f32 = center_z + turn_sign_z * wall_r * sin_a;
2993 let wall_yaw: f32 = if turn_sign_z < 0.0 { rad } else { -rad };
2994 let _: usize = world.spawn_object(
2995 &format!("{CITY_SEAWALL_MESH_NAME}_{wall_serial}"),
2996 unit_box,
2997 Transform3D::new(Vec3::new(wx, 0.0, wz), wall_yaw, Vec3::new(2.2, 1.15, 10.6)),
2998 seawall_mat,
2999 true,
3000 );
3001 wall_serial += 1;
3002 }
3003 }
3004 let palm_mesh: usize = world.register_mesh(MeshLodChain::single_level(Mesh3D::palm_tree(
3005 CITY_PALM_MESH_NAME,
3006 )));
3007 let palm_bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
3008 let palm_z_positions: [f32; 6] = [-102.0, -74.0, -46.0, -18.0, 10.0, 38.0];
3009 for (palm_row, &palm_z) in palm_z_positions.iter().enumerate() {
3010 for side_idx in 0..2usize {
3011 let side_sign: f32 = if side_idx == 0 { -1.0 } else { 1.0 };
3012 let yaw_palm: f32 = (palm_row as f32) * 0.95
3013 + (side_idx as f32) * 2.1
3014 + if side_idx == 0 { 0.35 } else { -0.35 };
3015 let scale_palm: f32 = 0.94 + ((palm_row + side_idx) % 3) as f32 * 0.08;
3016 let _: usize = world.spawn_object(
3017 &format!("palm_{palm_row}_{side_idx}"),
3018 palm_mesh,
3019 Transform3D::new(
3020 Vec3::new(side_sign * 12.0, 0.0, palm_z),
3021 yaw_palm,
3022 Vec3::splat(scale_palm),
3023 ),
3024 palm_bark_mat,
3025 true,
3026 );
3027 }
3028 }
3029 for coast_i in 0..10usize {
3030 let cz: f32 = -124.0 + (coast_i as f32) * 27.5;
3031 let yaw_p: f32 = (coast_i as f32) * 0.72 + 1.2;
3032 let scale_p: f32 = 0.96 + (coast_i % 3) as f32 * 0.07;
3033 let _: usize = world.spawn_object(
3034 &format!("waterfront_palm_{coast_i}"),
3035 palm_mesh,
3036 Transform3D::new(Vec3::new(139.8, 0.0, cz), yaw_p, Vec3::splat(scale_p)),
3037 palm_bark_mat,
3038 true,
3039 );
3040 }
3041 let arch_frame_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0F172A), 0.82, 0.18, 0.60);
3042 for (arch_idx, &arch_z) in [-36.0_f32, -80.0_f32, 48.0_f32].iter().enumerate() {
3043 let arch_neon: PbrMaterial =
3044 PbrMaterial::neon(neon_colors[arch_idx % neon_colors.len()], 2.1);
3045 let _: usize = world.spawn_object(
3046 &format!("arch_beam_{arch_idx}"),
3047 unit_box,
3048 Transform3D::new(
3049 Vec3::new(0.0, 13.4, arch_z),
3050 0.0,
3051 Vec3::new(23.0, 0.58, 0.72),
3052 ),
3053 arch_frame_mat,
3054 true,
3055 );
3056 let _: usize = world.spawn_object(
3057 &format!("arch_glow_{arch_idx}"),
3058 neon_unit,
3059 Transform3D::new(
3060 Vec3::new(0.0, 13.08, arch_z),
3061 0.0,
3062 Vec3::new(21.2, 0.24, 0.34),
3063 ),
3064 arch_neon,
3065 true,
3066 );
3067 for side in [-1.0_f32, 1.0_f32] {
3068 let _: usize = world.spawn_object(
3069 &format!("arch_pillar_{arch_idx}_{}", if side < 0.0 { 0 } else { 1 }),
3070 unit_box,
3071 Transform3D::new(
3072 Vec3::new(side * 11.2, 0.0, arch_z),
3073 0.0,
3074 Vec3::new(0.58, 13.4, 0.68),
3075 ),
3076 arch_frame_mat,
3077 true,
3078 );
3079 }
3080 }
3081 let aventador_mat: PbrMaterial =
3082 Self::hero_vehicle_material(HeroVehicleStyle::AventadorV12);
3083 let shelby_mat: PbrMaterial = Self::hero_vehicle_material(HeroVehicleStyle::ShelbyCobra);
3084 let aventador_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3085 Mesh3D::aventador_svj(CITY_MESH_AVENTADOR, aventador_mat),
3086 ));
3087 let shelby_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3088 Mesh3D::shelby_cobra(CITY_MESH_SHELBY, shelby_mat),
3089 ));
3090 {
3091 let Self {
3092 hero_vehicle_meshes,
3093 ..
3094 } = &mut world;
3095 hero_vehicle_meshes[0] = Some((aventador_mesh, aventador_mat));
3096 hero_vehicle_meshes[1] = Some((shelby_mesh, shelby_mat));
3097 }
3098 let car_idx: usize = world.spawn_object(
3099 CITY_OBJ_PLAYER_CAR,
3100 aventador_mesh,
3101 Transform3D::new(Vec3::new(0.0, 0.0, 0.0), 0.0, Vec3::splat(1.1)),
3102 aventador_mat,
3103 true,
3104 );
3105 let _: bool = world.set_object_dynamic(car_idx, true);
3106 world.set_player_vehicle_index(Some(car_idx));
3107 let _: usize = world.add_point_light(PointLight3D::new(
3108 Vec3::new(0.0, 0.95, 2.9),
3109 Color::hex(0xFF1744),
3110 1.85,
3111 8.5,
3112 ));
3113 let traffic_specs: [(f32, f32, f32, usize, Color); 4] = [
3114 (156.0, 5.6, -11.5, shelby_mesh, Color::hex(0x38BDF8)),
3115 (620.0, 5.6, -11.5, aventador_mesh, Color::hex(0xA855F7)),
3116 (164.0, -5.6, 13.0, aventador_mesh, Color::hex(0x22C55E)),
3117 (645.0, -5.6, 13.0, shelby_mesh, Color::hex(0xF59E0B)),
3118 ];
3119 for (t_idx, &(start_s, lane_u, speed_mps, t_mesh, t_col)) in
3120 traffic_specs.iter().enumerate()
3121 {
3122 let (t_pos, base_yaw): (Vec3, f32) = Self::loop_pose_at(start_s, lane_u);
3123 let face_yaw: f32 = if speed_mps >= 0.0 {
3124 base_yaw
3125 } else {
3126 base_yaw + PI
3127 };
3128 let tmat: PbrMaterial = PbrMaterial::pbr(t_col, 0.84, 0.13, 0.76);
3129 let obj_id: usize = world.spawn_object(
3130 &format!("ai_traffic_{t_idx}"),
3131 t_mesh,
3132 Transform3D::new(t_pos, face_yaw, Vec3::splat(1.04)),
3133 tmat,
3134 true,
3135 );
3136 let _: bool = world.set_object_dynamic(obj_id, true);
3137 let Self {
3138 traffic_vehicles, ..
3139 } = &mut world;
3140 traffic_vehicles.push(NpcVehicle3D::new_boulevard(
3141 obj_id, start_s, lane_u, speed_mps, face_yaw,
3142 ));
3143 }
3144 let offroad_specs: [(Vec3, f32, u8, usize, f32, usize, Color); 4] = [
3145 (
3146 Vec3::new(38.0, 0.0, -40.0),
3147 0.0,
3148 0,
3149 0,
3150 10.5,
3151 aventador_mesh,
3152 Color::hex(0x14B8A6),
3153 ),
3154 (
3155 Vec3::new(91.0, 0.0, 40.0),
3156 PI,
3157 0,
3158 3,
3159 10.0,
3160 shelby_mesh,
3161 Color::hex(0xFB7185),
3162 ),
3163 (
3164 Vec3::new(-72.0, 0.0, -30.0),
3165 PI,
3166 1,
3167 1,
3168 11.0,
3169 aventador_mesh,
3170 Color::hex(0xEAB308),
3171 ),
3172 (
3173 Vec3::new(38.0, 0.0, 78.0),
3174 -FRAC_PI_2,
3175 2,
3176 1,
3177 9.5,
3178 shelby_mesh,
3179 Color::hex(0x6366F1),
3180 ),
3181 ];
3182 for (o_idx, &(o_pos, o_yaw, route_id, wp_idx, o_speed, o_mesh, o_col)) in
3183 offroad_specs.iter().enumerate()
3184 {
3185 let traffic_serial: usize = traffic_specs.len() + o_idx;
3186 let omat: PbrMaterial = PbrMaterial::pbr(o_col, 0.84, 0.13, 0.76);
3187 let obj_id: usize = world.spawn_object(
3188 &format!("ai_traffic_{traffic_serial}"),
3189 o_mesh,
3190 Transform3D::new(o_pos, o_yaw, Vec3::splat(1.04)),
3191 omat,
3192 true,
3193 );
3194 let _: bool = world.set_object_dynamic(obj_id, true);
3195 let Self {
3196 traffic_vehicles, ..
3197 } = &mut world;
3198 traffic_vehicles.push(NpcVehicle3D::new_free_roam(
3199 obj_id, route_id, wp_idx, o_speed, o_yaw,
3200 ));
3201 }
3202 let lamp_palette: [Color; 4] = [
3203 Color::hex(0x38BDF8),
3204 Color::hex(0xF43F5E),
3205 Color::hex(0xA855F7),
3206 Color::hex(0x34D399),
3207 ];
3208 let lamp_z_rows: [f32; 4] = [-62.0, -26.0, 18.0, 66.0];
3209 for lamp_idx in 0..8usize {
3210 let side: f32 = if lamp_idx % 2 == 0 { -1.0 } else { 1.0 };
3211 let z_pos: f32 = lamp_z_rows[lamp_idx / 2];
3212 let lamp_color: Color = lamp_palette[lamp_idx % lamp_palette.len()];
3213 let _: usize = world.spawn_object(
3214 &format!("lamp_pole_{lamp_idx}"),
3215 unit_box,
3216 Transform3D::new(
3217 Vec3::new(side * 10.65, 0.0, z_pos),
3218 0.0,
3219 Vec3::new(0.20, 6.2, 0.20),
3220 ),
3221 arch_frame_mat,
3222 true,
3223 );
3224 let _: usize = world.spawn_object(
3225 &format!("lamp_head_{lamp_idx}"),
3226 neon_unit,
3227 Transform3D::new(
3228 Vec3::new(side * 10.15, 6.2, z_pos),
3229 0.0,
3230 Vec3::new(1.1, 0.18, 0.28),
3231 ),
3232 PbrMaterial::neon(lamp_color, 2.2),
3233 true,
3234 );
3235 let _: usize = world.add_point_light(PointLight3D::new(
3236 Vec3::new(side * 9.8, 6.2, z_pos),
3237 lamp_color,
3238 2.35,
3239 16.5,
3240 ));
3241 }
3242 let _: usize = world.add_spot_light(SpotLight3D::new(
3243 Vec3::new(-0.85, 0.95, -2.2),
3244 Vec3::new(0.0, -0.14, -1.0),
3245 Color::hex(0xFEF3C7),
3246 2.8,
3247 24.0,
3248 (14.0, 26.0),
3249 ));
3250 let _: usize = world.add_spot_light(SpotLight3D::new(
3251 Vec3::new(0.85, 0.95, -2.2),
3252 Vec3::new(0.0, -0.14, -1.0),
3253 Color::hex(0xFEF3C7),
3254 2.8,
3255 24.0,
3256 (14.0, 26.0),
3257 ));
3258 world.set_camera(Camera3D {
3259 position: Vec3::new(0.0, 4.15, 9.2),
3260 yaw: -FRAC_PI_2,
3261 pitch: -0.145,
3262 fov_deg: 60.0,
3263 near: 0.3,
3264 far: 560.0,
3265 });
3266 world.ensure_bvh();
3267 world
3268 }
3269
3270 #[must_use]
3276 pub fn traffic_vehicle_count(&self) -> usize {
3277 let Self {
3278 traffic_vehicles, ..
3279 } = self;
3280 traffic_vehicles.len()
3281 }
3282
3283 #[must_use]
3293 pub fn traffic_vehicle_object_index(&self, slot: usize) -> Option<usize> {
3294 let Self {
3295 traffic_vehicles, ..
3296 } = self;
3297 traffic_vehicles
3298 .get(slot)
3299 .map(NpcVehicle3D::get_object_index)
3300 }
3301
3302 #[must_use]
3312 pub fn traffic_vehicle_velocity(&self, slot: usize) -> Option<Vec3> {
3313 let Self {
3314 traffic_vehicles, ..
3315 } = self;
3316 traffic_vehicles.get(slot).map(NpcVehicle3D::get_vel)
3317 }
3318
3319 #[must_use]
3329 pub fn traffic_vehicle_yaw_rate(&self, slot: usize) -> Option<f32> {
3330 let Self {
3331 traffic_vehicles, ..
3332 } = self;
3333 traffic_vehicles.get(slot).map(NpcVehicle3D::get_yaw_rate)
3334 }
3335
3336 #[must_use]
3346 pub fn traffic_vehicle_is_free_roam(&self, slot: usize) -> Option<bool> {
3347 let Self {
3348 traffic_vehicles, ..
3349 } = self;
3350 traffic_vehicles
3351 .get(slot)
3352 .map(NpcVehicle3D::get_free_roam_mode)
3353 }
3354
3355 #[must_use]
3361 pub fn player_velocity(&self) -> Vec3 {
3362 let Self { player_physics, .. } = self;
3363 player_physics.get_vel()
3364 }
3365
3366 #[must_use]
3372 pub fn player_forward_speed_mps(&self) -> f32 {
3373 let Some(car_idx) = self.vehicle_index() else {
3374 return 0.0;
3375 };
3376 let Some(car_obj) = self.get_objects().get(car_idx) else {
3377 return 0.0;
3378 };
3379 let yaw_rad: f32 = car_obj.get_transform().get_yaw_rad();
3380 let forward_dir: Vec3 = Vec3::new(-yaw_rad.sin(), 0.0, -yaw_rad.cos());
3381 self.player_velocity().dot(forward_dir)
3382 }
3383
3384 pub fn reset_player_vehicle(&mut self) -> bool {
3390 let Some(car_idx) = self.vehicle_index() else {
3391 return false;
3392 };
3393 let spawn_transform: Transform3D =
3394 Transform3D::new(Vec3::new(0.0, 0.0, 0.0), 0.0, Vec3::splat(1.1));
3395 if !self.teleport_object(car_idx, spawn_transform) {
3396 return false;
3397 }
3398 {
3399 let Self { player_physics, .. } = self;
3400 player_physics.set_boost_charge(1.0);
3401 }
3402 self.get_mut_niagara().clear();
3403 let mut reset_cam: Camera3D = self.get_camera();
3404 let eye_pos: Vec3 = Vec3::new(0.0, 4.25, 9.8);
3405 let look_target: Vec3 = Vec3::new(0.0, 2.40, -16.0);
3406 let look_dir: Vec3 = look_target.sub(eye_pos).normalize();
3407 reset_cam.set_position(eye_pos);
3408 reset_cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
3409 reset_cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
3410 reset_cam.set_fov_deg(CAMERA_BASE_FOV_DEG);
3411 self.set_camera(reset_cam);
3412 self.bump_world_revision();
3413 true
3414 }
3415
3416 #[must_use]
3422 pub fn player_speed_mps(&self) -> f32 {
3423 let v: Vec3 = self.player_velocity();
3424 (v.get_x() * v.get_x() + v.get_z() * v.get_z()).sqrt()
3425 }
3426
3427 #[must_use]
3433 pub fn player_speed_kmh(&self) -> f32 {
3434 self.player_speed_mps() * 3.6
3435 }
3436
3437 #[must_use]
3443 pub fn player_yaw_rate(&self) -> f32 {
3444 let Self { player_physics, .. } = self;
3445 player_physics.get_yaw_rate()
3446 }
3447
3448 #[must_use]
3454 pub fn player_boost_active(&self) -> bool {
3455 let Self { player_physics, .. } = self;
3456 player_physics.get_boost_active()
3457 }
3458
3459 #[must_use]
3465 pub fn player_boost_charge(&self) -> f32 {
3466 let Self { player_physics, .. } = self;
3467 player_physics.get_boost_charge()
3468 }
3469
3470 #[must_use]
3476 pub fn player_drift_active(&self) -> bool {
3477 let Self { player_physics, .. } = self;
3478 player_physics.get_drift_active()
3479 }
3480
3481 #[must_use]
3487 pub fn player_drift_slip_angle_rad(&self) -> f32 {
3488 let Self { player_physics, .. } = self;
3489 player_physics.get_drift_slip_angle()
3490 }
3491
3492 #[must_use]
3498 pub fn player_body_roll_rad(&self) -> f32 {
3499 let Self { player_physics, .. } = self;
3500 player_physics.get_body_roll_rad()
3501 }
3502
3503 #[must_use]
3509 pub fn player_body_pitch_rad(&self) -> f32 {
3510 let Self { player_physics, .. } = self;
3511 player_physics.get_body_pitch_rad()
3512 }
3513
3514 #[must_use]
3520 pub fn player_camera_fov_boost(&self) -> f32 {
3521 let Self { player_physics, .. } = self;
3522 player_physics.get_camera_fov_boost()
3523 }
3524
3525 #[must_use]
3531 pub fn player_camera_shake(&self) -> f32 {
3532 let Self { player_physics, .. } = self;
3533 player_physics.get_camera_shake()
3534 }
3535
3536 pub fn apply_atmosphere_preset(&mut self, preset: u8) -> f32 {
3546 let clamped: u8 = preset.min(3);
3547 let hour: f32 = match clamped {
3548 1 => ATMOSPHERE_HOUR_RAINY_NIGHT,
3549 2 => ATMOSPHERE_HOUR_NOON,
3550 3 => ATMOSPHERE_HOUR_MIDNIGHT,
3551 _ => ATMOSPHERE_HOUR_SUNSET,
3552 };
3553 self.set_atmosphere_preset(clamped);
3554 let sun_light: DirectionalLight3D = match clamped {
3555 1 => DirectionalLight3D {
3556 direction: Vec3::new(-0.32, 0.48, -0.82).normalize(),
3557 color: Vec3::new(0.56, 0.78, 1.24),
3558 sky_zenith: Vec3::new(0.015, 0.038, 0.105),
3559 sky_horizon: Vec3::new(0.078, 0.155, 0.275),
3560 time_of_day: hour,
3561 },
3562 3 => DirectionalLight3D {
3563 direction: Vec3::new(-0.42, 0.62, -0.66).normalize(),
3564 color: Vec3::new(0.36, 0.34, 0.88),
3565 sky_zenith: Vec3::new(0.007, 0.005, 0.024),
3566 sky_horizon: Vec3::new(0.135, 0.036, 0.215),
3567 time_of_day: hour,
3568 },
3569 _ => DirectionalLight3D::from_time_of_day(hour),
3570 };
3571 self.set_sun(sun_light);
3572 if clamped == 1 && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES {
3573 let cam_pos: Vec3 = self.get_camera().get_position();
3574 let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
3575 rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 4.5, -14.0)));
3576 rain_cfg.set_base_velocity(Vec3::new(-0.4, -17.0, 0.3));
3577 rain_cfg.set_velocity_spread(2.4);
3578 rain_cfg.set_start_color(Color::rgba(175, 222, 255, 165));
3579 rain_cfg.set_end_color(Color::rgba(92, 162, 235, 42));
3580 rain_cfg.set_start_size_m(0.042);
3581 rain_cfg.set_end_size_m(0.016);
3582 rain_cfg.set_min_lifetime(0.55);
3583 rain_cfg.set_max_lifetime(0.95);
3584 rain_cfg.set_emissive_boost(0.85);
3585 self.get_mut_niagara().emit_burst(8, &rain_cfg);
3586 }
3587 self.bump_world_revision();
3588 hour
3589 }
3590
3591 pub fn add_point_light(&mut self, light: PointLight3D) -> usize {
3601 let light_idx: usize = self.get_point_lights().len();
3602 self.get_mut_point_lights().push(light);
3603 self.bump_world_revision();
3604 light_idx
3605 }
3606
3607 pub fn add_spot_light(&mut self, light: SpotLight3D) -> usize {
3617 let light_idx: usize = self.get_spot_lights().len();
3618 self.get_mut_spot_lights().push(light);
3619 self.bump_world_revision();
3620 light_idx
3621 }
3622
3623 pub fn clear_local_lights(&mut self) {
3625 self.get_mut_point_lights().clear();
3626 self.get_mut_spot_lights().clear();
3627 self.bump_world_revision();
3628 }
3629
3630 pub fn emit_particles_3d(&mut self, config: &NiagaraEmitterConfig3D, count: usize) -> usize {
3641 self.get_mut_niagara().emit_burst(count, config);
3642 let active: usize = self.get_niagara().get_active_count();
3643 if count > 0 {
3644 self.bump_world_revision();
3645 }
3646 active
3647 }
3648
3649 #[must_use]
3659 pub fn create_dense_open_world_city(blocks_radius: i32) -> Self {
3660 let radius: i32 = blocks_radius.clamp(1, 5);
3661 let mut world: Self = Self::create_open_world_city();
3662 let dense_occluder: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
3663 DENSE_TOWER_MESH_NAME,
3664 1.0,
3665 1.0,
3666 1.0,
3667 true,
3668 PbrMaterial::default(),
3669 )));
3670 let archetypes: [usize; 6] = world.register_building_archetypes();
3671 let facades: [PbrMaterial; 6] = Self::curated_skyline_palettes();
3672 let neon_palette: [Color; 4] = [
3673 Color::hex(0x38BDF8),
3674 Color::hex(0xF43F5E),
3675 Color::hex(0xA855F7),
3676 Color::hex(0x34D399),
3677 ];
3678 let mut serial: usize = 0;
3679 for bx in -radius..=radius {
3680 for bz in -radius..=radius {
3681 if bx == 0 && (-3..=3).contains(&bz) {
3682 continue;
3683 }
3684 let center_x: f32 = (bx as f32) * 26.0;
3685 let center_z: f32 = (bz as f32) * 24.0 - 16.0;
3686 for sub in 0..4usize {
3687 let off_x: f32 = if (sub & 1) == 0 { -5.5 } else { 5.5 };
3688 let off_z: f32 = if (sub & 2) == 0 { -5.5 } else { 5.5 };
3689 let px: f32 = center_x + off_x;
3690 let pz: f32 = center_z + off_z;
3691 let (d_spine, _): (f32, f32) = Self::loop_lateral_offset(px, pz);
3692 if (49.0..=79.0).contains(&d_spine) || px > 134.0 {
3693 continue;
3694 }
3695 let height_m: f32 = 16.0 + (((serial * 11 + sub * 7) % 6) as f32) * 8.0;
3696 let width_m: f32 = 8.0 + ((serial % 3) as f32) * 1.4;
3697 let mat: PbrMaterial = facades[serial % facades.len()];
3698 let mesh_id: usize = if sub % 2 == 0 {
3699 dense_occluder
3700 } else {
3701 archetypes[(serial + sub) % archetypes.len()]
3702 };
3703 let _: usize = world.spawn_object(
3704 &format!("dense_bldg_{serial}"),
3705 mesh_id,
3706 Transform3D::new(
3707 Vec3::new(px, 0.0, pz),
3708 0.0,
3709 Vec3::new(width_m, height_m, 9.0),
3710 ),
3711 mat,
3712 true,
3713 );
3714 serial += 1;
3715 }
3716 if (bx + bz).abs() <= 2 && world.get_point_lights().len() < 32 {
3717 let _: usize = world.add_point_light(PointLight3D::new(
3718 Vec3::new(center_x, 7.0, center_z),
3719 neon_palette[serial % neon_palette.len()],
3720 4.5,
3721 22.0,
3722 ));
3723 }
3724 }
3725 }
3726 world.ensure_bvh();
3727 world
3728 }
3729
3730 pub fn cycle_camera_mode(&mut self) -> u8 {
3740 let next: u8 = (self.get_camera_mode() + 1) % 4;
3741 self.set_camera_mode(next);
3742 next
3743 }
3744
3745 #[must_use]
3755 pub fn ground_play_bounds(&self) -> Option<(f32, f32, f32, f32)> {
3756 let mut found: bool = false;
3757 let mut min_x: f32 = f32::INFINITY;
3758 let mut max_x: f32 = f32::NEG_INFINITY;
3759 let mut min_z: f32 = f32::INFINITY;
3760 let mut max_z: f32 = f32::NEG_INFINITY;
3761 for obj in self.get_objects().iter() {
3762 if obj.get_ray_trace_caster()
3763 || obj.get_material().get_surface_detail() == SurfaceDetailMode::OceanWater
3764 {
3765 continue;
3766 }
3767 let blue_val: AxisAlignedBox3D = obj.get_world_bounds();
3768 let span_x: f32 = blue_val.get_max().get_x() - blue_val.get_min().get_x();
3769 let span_z: f32 = blue_val.get_max().get_z() - blue_val.get_min().get_z();
3770 if span_x >= 16.0 && span_z >= 16.0 {
3771 min_x = min_x.min(blue_val.get_min().get_x());
3772 max_x = max_x.max(blue_val.get_max().get_x());
3773 min_z = min_z.min(blue_val.get_min().get_z());
3774 max_z = max_z.max(blue_val.get_max().get_z());
3775 found = true;
3776 }
3777 }
3778 if found {
3779 Some((min_x, max_x, min_z, max_z))
3780 } else {
3781 None
3782 }
3783 }
3784
3785 #[must_use]
3797 pub fn mesh_oriented_box_collision(
3798 &self,
3799 candidate: OrientedBox3D,
3800 ignore_idx: Option<usize>,
3801 ) -> Option<MeshCollisionHit3D> {
3802 let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
3803 let mut deepest: Option<MeshCollisionHit3D> = None;
3804 let objects: &[SceneObject3D] = self.get_objects().as_slice();
3805 let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
3806 for (idx, obj) in objects.iter().enumerate() {
3807 if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
3808 {
3809 continue;
3810 }
3811 let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
3812 if !Self::boxes_overlap(query_bounds, obj_bounds) {
3813 continue;
3814 }
3815 let Some(mesh) = mesh_lib
3816 .get(obj.get_mesh_id())
3817 .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
3818 else {
3819 continue;
3820 };
3821 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
3822 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
3823 let obj_tr: Transform3D = obj.get_transform();
3824 let model_mat: Mat4 = obj_tr.to_mat4();
3825 let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
3826 let mut hit_this_obj: bool = false;
3827 if meshlets.is_empty() {
3828 for tri in indices.iter() {
3829 let (i0, i1, i2): (usize, usize, usize) =
3830 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3831 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3832 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3833 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3834 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3835 if let Some((normal, pen, contact)) =
3836 candidate.intersect_triangle_world(w0, w1, w2)
3837 {
3838 hit_this_obj = true;
3839 let replace: bool = deepest
3840 .map(|delta_val: MeshCollisionHit3D| {
3841 pen > delta_val.get_penetration()
3842 })
3843 .unwrap_or(true);
3844 if replace {
3845 deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
3846 }
3847 }
3848 }
3849 }
3850 } else {
3851 for ml in meshlets.iter() {
3852 let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
3853 if !Self::boxes_overlap(query_bounds, ml_bounds) {
3854 continue;
3855 }
3856 let start: usize = ml.get_first_tri() as usize;
3857 let end: usize = start
3858 .saturating_add(ml.get_tri_count() as usize)
3859 .min(indices.len());
3860 for tri in indices[start..end].iter() {
3861 let (i0, i1, i2): (usize, usize, usize) =
3862 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3863 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3864 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3865 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3866 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3867 if let Some((normal, pen, contact)) =
3868 candidate.intersect_triangle_world(w0, w1, w2)
3869 {
3870 hit_this_obj = true;
3871 let replace: bool = deepest
3872 .map(|distance_val: MeshCollisionHit3D| {
3873 pen > distance_val.get_penetration()
3874 })
3875 .unwrap_or(true);
3876 if replace {
3877 deepest =
3878 Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
3879 }
3880 }
3881 }
3882 }
3883 }
3884 }
3885 if !hit_this_obj
3886 && mesh.get_is_closed()
3887 && Self::point_in_bounds(candidate.get_center(), obj_bounds)
3888 && let Some(inside_hit) =
3889 Self::point_inside_closed_mesh_mtv(idx, candidate, verts, indices, model_mat)
3890 {
3891 let replace: bool = deepest
3892 .map(|prev_hit: MeshCollisionHit3D| {
3893 inside_hit.get_penetration() > prev_hit.get_penetration()
3894 })
3895 .unwrap_or(true);
3896 if replace {
3897 deepest = Some(inside_hit);
3898 }
3899 }
3900 }
3901 deepest
3902 }
3903
3904 #[inline]
3915 #[must_use]
3916 fn point_in_bounds(point: Vec3, bounds: AxisAlignedBox3D) -> bool {
3917 let bmin: Vec3 = bounds.get_min();
3918 let bmax: Vec3 = bounds.get_max();
3919 point.get_x() >= bmin.get_x()
3920 && point.get_x() <= bmax.get_x()
3921 && point.get_y() >= bmin.get_y()
3922 && point.get_y() <= bmax.get_y()
3923 && point.get_z() >= bmin.get_z()
3924 && point.get_z() <= bmax.get_z()
3925 }
3926
3927 #[inline]
3940 #[must_use]
3941 fn closest_point_on_triangle(point: Vec3, v0: Vec3, v1: Vec3, v2: Vec3) -> Vec3 {
3942 let ab: Vec3 = v1.sub(v0);
3943 let ac: Vec3 = v2.sub(v0);
3944 let ap: Vec3 = point.sub(v0);
3945 let d1: f32 = ab.dot(ap);
3946 let d2: f32 = ac.dot(ap);
3947 if d1 <= 0.0 && d2 <= 0.0 {
3948 return v0;
3949 }
3950 let bp: Vec3 = point.sub(v1);
3951 let d3: f32 = ab.dot(bp);
3952 let d4: f32 = ac.dot(bp);
3953 if d3 >= 0.0 && d4 <= d3 {
3954 return v1;
3955 }
3956 let vc: f32 = d1 * d4 - d3 * d2;
3957 if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
3958 let weight_v: f32 = d1 / (d1 - d3).max(1.0e-7);
3959 return v0.add(ab.scale(weight_v));
3960 }
3961 let cp: Vec3 = point.sub(v2);
3962 let d5: f32 = ab.dot(cp);
3963 let d6: f32 = ac.dot(cp);
3964 if d6 >= 0.0 && d5 <= d6 {
3965 return v2;
3966 }
3967 let vb: f32 = d5 * d2 - d1 * d6;
3968 if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
3969 let weight_w: f32 = d2 / (d2 - d6).max(1.0e-7);
3970 return v0.add(ac.scale(weight_w));
3971 }
3972 let va: f32 = d3 * d6 - d5 * d4;
3973 if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
3974 let denom_bc: f32 = ((d4 - d3) + (d5 - d6)).max(1.0e-7);
3975 let weight_w: f32 = (d4 - d3) / denom_bc;
3976 return v1.add(v2.sub(v1).scale(weight_w));
3977 }
3978 let denom: f32 = (va + vb + vc).max(1.0e-7);
3979 let weight_v: f32 = vb / denom;
3980 let weight_w: f32 = vc / denom;
3981 v0.add(ab.scale(weight_v)).add(ac.scale(weight_w))
3982 }
3983
3984 #[must_use]
3998 fn point_inside_closed_mesh_mtv(
3999 obj_idx: usize,
4000 candidate: OrientedBox3D,
4001 verts: &[Vertex3D],
4002 indices: &[[u32; 3]],
4003 model_mat: Mat4,
4004 ) -> Option<MeshCollisionHit3D> {
4005 let center: Vec3 = candidate.get_center();
4006 let parity_dir: Vec3 = Vec3::new(1.0, 1.37e-4, 2.71e-4).normalize();
4007 let mut crossings: u32 = 0;
4008 let mut best_horiz_dist_sq: f32 = f32::INFINITY;
4009 let mut best_horiz_cp: Vec3 = center;
4010 let mut best_horiz_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
4011 let mut best_any_dist_sq: f32 = f32::INFINITY;
4012 let mut best_any_cp: Vec3 = center;
4013 let mut best_any_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
4014 for tri in indices.iter() {
4015 let (i0, i1, i2): (usize, usize, usize) =
4016 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4017 if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
4018 continue;
4019 }
4020 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4021 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4022 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4023 if Self::ray_intersect_triangle(center, parity_dir, w0, w1, w2, 1.0e-5, f32::INFINITY)
4024 .is_some()
4025 {
4026 crossings = crossings.wrapping_add(1);
4027 }
4028 let cp: Vec3 = Self::closest_point_on_triangle(center, w0, w1, w2);
4029 let delta: Vec3 = cp.sub(center);
4030 let dist_sq: f32 = delta.length_sq();
4031 let raw_face_n: Vec3 = w1.sub(w0).cross(w2.sub(w0));
4032 let face_n: Vec3 = if raw_face_n.length_sq() > 1.0e-10 {
4033 raw_face_n.normalize()
4034 } else {
4035 Vec3::new(1.0, 0.0, 0.0)
4036 };
4037 if dist_sq < best_any_dist_sq {
4038 best_any_dist_sq = dist_sq;
4039 best_any_cp = cp;
4040 best_any_n = face_n;
4041 }
4042 let horiz_mag_sq: f32 =
4043 face_n.get_x() * face_n.get_x() + face_n.get_z() * face_n.get_z();
4044 if horiz_mag_sq > 0.25 && dist_sq < best_horiz_dist_sq {
4045 best_horiz_dist_sq = dist_sq;
4046 best_horiz_cp = cp;
4047 best_horiz_n = Vec3::new(face_n.get_x(), 0.0, face_n.get_z()).normalize();
4048 }
4049 }
4050 if (crossings & 1) == 0 {
4051 return None;
4052 }
4053 let (target_cp, fallback_n, target_dist_sq): (Vec3, Vec3, f32) =
4054 if best_horiz_dist_sq.is_finite() {
4055 (best_horiz_cp, best_horiz_n, best_horiz_dist_sq)
4056 } else if best_any_dist_sq.is_finite() {
4057 (best_any_cp, best_any_n, best_any_dist_sq)
4058 } else {
4059 return None;
4060 };
4061 let push_raw: Vec3 = target_cp.sub(center);
4062 let push_n: Vec3 = if push_raw.length_sq() > 1.0e-8 {
4063 push_raw.normalize()
4064 } else {
4065 fallback_n
4066 };
4067 let axes: [Vec3; 3] = candidate.get_axes();
4068 let half_extents: Vec3 = candidate.get_half_extents();
4069 let obb_proj: f32 = axes[0].dot(push_n).abs() * half_extents.get_x()
4070 + axes[1].dot(push_n).abs() * half_extents.get_y()
4071 + axes[2].dot(push_n).abs() * half_extents.get_z();
4072 let total_pen: f32 = target_dist_sq.sqrt() + obb_proj;
4073 Some(MeshCollisionHit3D::new(
4074 obj_idx, push_n, total_pen, target_cp,
4075 ))
4076 }
4077
4078 #[must_use]
4090 fn horizontal_collision_normal(&self, candidate: OrientedBox3D, obj_idx: usize) -> Vec3 {
4091 let Some(obj) = self.get_objects().get(obj_idx) else {
4092 return Vec3::zero();
4093 };
4094 if let Some(mesh) = self
4095 .get_mesh_library()
4096 .get(obj.get_mesh_id())
4097 .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
4098 {
4099 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
4100 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
4101 let model_mat: Mat4 = obj.get_transform().to_mat4();
4102 let mut best_pen: f32 = f32::INFINITY;
4103 let mut best_hn: Vec3 = Vec3::zero();
4104 for tri in indices.iter() {
4105 let (i0, i1, i2): (usize, usize, usize) =
4106 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4107 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4108 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4109 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4110 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4111 if let Some((normal, pen, _)) = candidate.intersect_triangle_world(w0, w1, w2) {
4112 let hn: Vec3 = Vec3::new(normal.get_x(), 0.0, normal.get_z());
4113 if hn.length_sq() > 0.25 && pen < best_pen {
4114 best_pen = pen;
4115 best_hn = hn.normalize();
4116 }
4117 }
4118 }
4119 }
4120 if best_hn.length_sq() > 1.0e-6 {
4121 return best_hn;
4122 }
4123 }
4124 let bounds: AxisAlignedBox3D = obj.get_world_bounds();
4125 let bcenter: Vec3 = bounds.get_min().add(bounds.get_max()).scale(0.5);
4126 let diff: Vec3 = candidate.get_center().sub(bcenter);
4127 let horiz: Vec3 = Vec3::new(diff.get_x(), 0.0, diff.get_z());
4128 if horiz.length_sq() > 1.0e-6 {
4129 horiz.normalize()
4130 } else {
4131 Vec3::new(1.0, 0.0, 0.0)
4132 }
4133 }
4134
4135 #[inline]
4147 #[must_use]
4148 fn clamp_horizontal_to_ground(
4149 mut pos: Vec3,
4150 ground_limits: Option<(f32, f32, f32, f32)>,
4151 ground_margin: f32,
4152 ) -> Vec3 {
4153 if let Some((gx0, gx1, gz0, gz1)) = ground_limits {
4154 let lo_x: f32 = (gx0 + ground_margin).min(gx1);
4155 let hi_x: f32 = (gx1 - ground_margin).max(lo_x);
4156 let lo_z: f32 = (gz0 + ground_margin).min(gz1);
4157 let hi_z: f32 = (gz1 - ground_margin).max(lo_z);
4158 pos.set_x(pos.get_x().clamp(lo_x, hi_x));
4159 pos.set_z(pos.get_z().clamp(lo_z, hi_z));
4160 }
4161 pos
4162 }
4163
4164 fn depenetrate_vehicle_horizontally(
4179 &self,
4180 transform_val: &mut Transform3D,
4181 mesh_bounds: AxisAlignedBox3D,
4182 vehicle_idx: usize,
4183 ground_limits: Option<(f32, f32, f32, f32)>,
4184 ground_margin: f32,
4185 ) -> bool {
4186 let mut adjusted: bool = false;
4187 for _ in 0..COLLISION_MTV_MAX_ITERS {
4188 let Some(hit) = self.collides_with_obstacles(*transform_val, mesh_bounds, vehicle_idx)
4189 else {
4190 break;
4191 };
4192 let raw_hn: Vec3 = Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
4193 let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
4194 raw_hn.normalize()
4195 } else {
4196 self.horizontal_collision_normal(
4197 transform_val.to_oriented_box(mesh_bounds),
4198 hit.get_object_index(),
4199 )
4200 };
4201 if hn.length_sq() <= 1.0e-6 {
4202 break;
4203 }
4204 let push_dist: f32 = hit.get_penetration() + COLLISION_MTV_PUSH_EPS;
4205 let cur_pos: Vec3 = transform_val.get_position();
4206 let pushed_pos: Vec3 = Self::clamp_horizontal_to_ground(
4207 Vec3::new(
4208 cur_pos.get_x() + hn.get_x() * push_dist,
4209 cur_pos.get_y(),
4210 cur_pos.get_z() + hn.get_z() * push_dist,
4211 ),
4212 ground_limits,
4213 ground_margin,
4214 );
4215 transform_val.set_position(pushed_pos);
4216 adjusted = true;
4217 }
4218 adjusted
4219 }
4220
4221 #[must_use]
4235 pub fn raycast_solid_meshes(
4236 &self,
4237 origin: Vec3,
4238 direction: Vec3,
4239 max_dist: f32,
4240 ignore_idx: Option<usize>,
4241 ) -> Option<RayHit3D> {
4242 let dir: Vec3 = direction.normalize();
4243 let inv_dir: Vec3 = Ray3D::safe_inv_vec(dir);
4244 let t_min: f32 = 1e-4;
4245 let mut best_t: f32 = max_dist;
4246 let mut best_hit: Option<RayHit3D> = None;
4247 let objects: &[SceneObject3D] = self.get_objects().as_slice();
4248 let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
4249 let ignore_is_static_caster: bool = ignore_idx
4250 .and_then(|idx: usize| objects.get(idx))
4251 .is_some_and(|obj: &SceneObject3D| obj.get_ray_trace_caster() && !obj.get_is_dynamic());
4252 let use_static_bvh: bool =
4253 !self.get_bvh_dirty() && !self.get_bvh().is_empty() && !ignore_is_static_caster;
4254 if use_static_bvh
4255 && let Some((hit_dist, tri_idx)) = self
4256 .get_bvh()
4257 .trace_closest_raw(origin, dir, inv_dir, t_min, best_t)
4258 {
4259 let bvh_tris: &[BvhTriangle] = self.get_bvh().get_triangles().as_slice();
4260 if let Some(hit_tri) = bvh_tris.get(tri_idx) {
4261 let raw_normal: Vec3 = hit_tri.get_normal();
4262 let oriented_normal: Vec3 = if raw_normal.dot(dir) > 0.0 {
4263 raw_normal.scale(-1.0)
4264 } else {
4265 raw_normal
4266 };
4267 best_t = hit_dist;
4268 best_hit = Some(RayHit3D {
4269 distance: hit_dist,
4270 point: origin.add(dir.scale(hit_dist)),
4271 normal: oriented_normal,
4272 material: hit_tri.get_material(),
4273 });
4274 }
4275 }
4276 for (idx, obj) in objects.iter().enumerate() {
4277 if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
4278 {
4279 continue;
4280 }
4281 if use_static_bvh && obj.get_ray_trace_caster() && !obj.get_is_dynamic() {
4282 continue;
4283 }
4284 if !obj
4285 .get_world_bounds()
4286 .intersect_ray_near(origin, inv_dir, t_min, best_t)
4287 .is_finite()
4288 {
4289 continue;
4290 }
4291 let Some(mesh) = mesh_lib
4292 .get(obj.get_mesh_id())
4293 .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
4294 else {
4295 continue;
4296 };
4297 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
4298 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
4299 let model_mat: Mat4 = obj.get_transform().to_mat4();
4300 let mat: PbrMaterial = obj.get_material();
4301 for tri in indices.iter() {
4302 let (i0, i1, i2): (usize, usize, usize) =
4303 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4304 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4305 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4306 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4307 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4308 if let Some((blend_factor, normal)) =
4309 Self::ray_intersect_triangle(origin, dir, w0, w1, w2, t_min, best_t)
4310 {
4311 best_t = blend_factor;
4312 best_hit = Some(RayHit3D {
4313 distance: blend_factor,
4314 point: origin.add(dir.scale(blend_factor)),
4315 normal,
4316 material: mat,
4317 });
4318 }
4319 }
4320 }
4321 }
4322 best_hit
4323 }
4324
4325 #[inline]
4336 #[must_use]
4337 fn boxes_overlap(alpha_val: AxisAlignedBox3D, blue_val: AxisAlignedBox3D) -> bool {
4338 let ox: bool = alpha_val.get_min().get_x() < blue_val.get_max().get_x()
4339 && alpha_val.get_max().get_x() > blue_val.get_min().get_x();
4340 let oy: bool = alpha_val.get_min().get_y() < blue_val.get_max().get_y()
4341 && alpha_val.get_max().get_y() > blue_val.get_min().get_y();
4342 let oz: bool = alpha_val.get_min().get_z() < blue_val.get_max().get_z()
4343 && alpha_val.get_max().get_z() > blue_val.get_min().get_z();
4344 ox && oy && oz
4345 }
4346
4347 #[inline]
4363 #[must_use]
4364 fn ray_intersect_triangle(
4365 origin: Vec3,
4366 dir: Vec3,
4367 v0: Vec3,
4368 v1: Vec3,
4369 v2: Vec3,
4370 t_min: f32,
4371 t_max: f32,
4372 ) -> Option<(f32, Vec3)> {
4373 let e1: Vec3 = v1.sub(v0);
4374 let e2: Vec3 = v2.sub(v0);
4375 let pvec: Vec3 = dir.cross(e2);
4376 let det: f32 = e1.dot(pvec);
4377 if det.abs() < 1e-7 {
4378 return None;
4379 }
4380 let inv_det: f32 = 1.0 / det;
4381 let tvec: Vec3 = origin.sub(v0);
4382 let tex_u: f32 = tvec.dot(pvec) * inv_det;
4383 if !(0.0..=1.0).contains(&tex_u) {
4384 return None;
4385 }
4386 let qvec: Vec3 = tvec.cross(e1);
4387 let item_val: f32 = dir.dot(qvec) * inv_det;
4388 if item_val < 0.0 || tex_u + item_val > 1.0 {
4389 return None;
4390 }
4391 let blend_factor: f32 = e2.dot(qvec) * inv_det;
4392 if blend_factor <= t_min || blend_factor > t_max {
4393 return None;
4394 }
4395 let raw_n: Vec3 = e1.cross(e2).normalize();
4396 let normal: Vec3 = if raw_n.dot(dir) > 0.0 {
4397 raw_n.scale(-1.0)
4398 } else {
4399 raw_n
4400 };
4401 Some((blend_factor, normal))
4402 }
4403
4404 #[must_use]
4417 fn collides_with_obstacles(
4418 &self,
4419 candidate_tr: Transform3D,
4420 local_bounds: AxisAlignedBox3D,
4421 ignore_idx: usize,
4422 ) -> Option<MeshCollisionHit3D> {
4423 let oriented_box: OrientedBox3D = candidate_tr.to_oriented_box(local_bounds);
4424 self.mesh_oriented_box_collision(oriented_box, Some(ignore_idx))
4425 }
4426
4427 #[must_use]
4438 fn mesh_oriented_box_static_collision(
4439 &self,
4440 candidate: OrientedBox3D,
4441 ignore_idx: Option<usize>,
4442 ) -> Option<MeshCollisionHit3D> {
4443 let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
4444 let mut deepest: Option<MeshCollisionHit3D> = None;
4445 let objects: &[SceneObject3D] = self.get_objects().as_slice();
4446 let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
4447 for (idx, obj) in objects.iter().enumerate() {
4448 let is_solid: bool = obj.get_solid_collider() || obj.get_ray_trace_caster();
4449 if ignore_idx == Some(idx) || obj.get_is_dynamic() || !is_solid {
4450 continue;
4451 }
4452 let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
4453 if !Self::boxes_overlap(query_bounds, obj_bounds) {
4454 continue;
4455 }
4456 let Some(mesh) = mesh_lib
4457 .get(obj.get_mesh_id())
4458 .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
4459 else {
4460 continue;
4461 };
4462 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
4463 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
4464 let model_mat: Mat4 = obj.get_transform().to_mat4();
4465 let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
4466 let mut hit_this_obj: bool = false;
4467 if meshlets.is_empty() {
4468 for tri in indices.iter() {
4469 let (i0, i1, i2): (usize, usize, usize) =
4470 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4471 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4472 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4473 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4474 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4475 if let Some((normal, pen, contact)) =
4476 candidate.intersect_triangle_world(w0, w1, w2)
4477 {
4478 hit_this_obj = true;
4479 let replace: bool = deepest
4480 .map(|prev: MeshCollisionHit3D| pen > prev.get_penetration())
4481 .unwrap_or(true);
4482 if replace {
4483 deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
4484 }
4485 }
4486 }
4487 }
4488 } else {
4489 for ml in meshlets.iter() {
4490 let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
4491 if !Self::boxes_overlap(query_bounds, ml_bounds) {
4492 continue;
4493 }
4494 let start: usize = ml.get_first_tri() as usize;
4495 let end: usize = start
4496 .saturating_add(ml.get_tri_count() as usize)
4497 .min(indices.len());
4498 for tri in indices[start..end].iter() {
4499 let (i0, i1, i2): (usize, usize, usize) =
4500 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4501 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4502 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4503 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4504 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4505 if let Some((normal, pen, contact)) =
4506 candidate.intersect_triangle_world(w0, w1, w2)
4507 {
4508 hit_this_obj = true;
4509 let replace: bool = deepest
4510 .map(|prev: MeshCollisionHit3D| pen > prev.get_penetration())
4511 .unwrap_or(true);
4512 if replace {
4513 deepest =
4514 Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
4515 }
4516 }
4517 }
4518 }
4519 }
4520 }
4521 if !hit_this_obj
4522 && mesh.get_is_closed()
4523 && Self::point_in_bounds(candidate.get_center(), obj_bounds)
4524 && let Some(inside_hit) =
4525 Self::point_inside_closed_mesh_mtv(idx, candidate, verts, indices, model_mat)
4526 {
4527 let replace: bool = deepest
4528 .map(|prev: MeshCollisionHit3D| {
4529 inside_hit.get_penetration() > prev.get_penetration()
4530 })
4531 .unwrap_or(true);
4532 if replace {
4533 deepest = Some(inside_hit);
4534 }
4535 }
4536 }
4537 deepest
4538 }
4539
4540 fn depenetrate_vehicle_static_horizontally(
4554 &self,
4555 transform_val: &mut Transform3D,
4556 mesh_bounds: AxisAlignedBox3D,
4557 vehicle_idx: usize,
4558 ground_limits: Option<(f32, f32, f32, f32)>,
4559 ground_margin: f32,
4560 ) -> bool {
4561 let mut adjusted: bool = false;
4562 for _ in 0..COLLISION_MTV_MAX_ITERS {
4563 let Some(hit) = self.mesh_oriented_box_static_collision(
4564 transform_val.to_oriented_box(mesh_bounds),
4565 Some(vehicle_idx),
4566 ) else {
4567 break;
4568 };
4569 let raw_hn: Vec3 = Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
4570 let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
4571 raw_hn.normalize()
4572 } else {
4573 self.horizontal_collision_normal(
4574 transform_val.to_oriented_box(mesh_bounds),
4575 hit.get_object_index(),
4576 )
4577 };
4578 if hn.length_sq() <= 1.0e-6 {
4579 break;
4580 }
4581 let push_dist: f32 = hit.get_penetration() + COLLISION_MTV_PUSH_EPS;
4582 let cur_pos: Vec3 = transform_val.get_position();
4583 let pushed_pos: Vec3 = Self::clamp_horizontal_to_ground(
4584 Vec3::new(
4585 cur_pos.get_x() + hn.get_x() * push_dist,
4586 cur_pos.get_y(),
4587 cur_pos.get_z() + hn.get_z() * push_dist,
4588 ),
4589 ground_limits,
4590 ground_margin,
4591 );
4592 transform_val.set_position(pushed_pos);
4593 adjusted = true;
4594 }
4595 adjusted
4596 }
4597
4598 #[inline]
4608 #[must_use]
4609 fn wrap_angle_rad(angle: f32) -> f32 {
4610 let two_pi: f32 = 2.0 * PI;
4611 let wrapped: f32 = (angle + PI).rem_euclid(two_pi) - PI;
4612 if wrapped <= -PI {
4613 wrapped + two_pi
4614 } else {
4615 wrapped
4616 }
4617 }
4618
4619 #[must_use]
4629 fn local_bounds_for_mesh(&self, mesh_id: usize) -> AxisAlignedBox3D {
4630 self.get_mesh_library()
4631 .get(mesh_id)
4632 .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
4633 .map(Mesh3D::get_bounds)
4634 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)))
4635 }
4636
4637 #[must_use]
4650 fn compute_static_contact_point(
4651 obb: OrientedBox3D,
4652 hn: Vec3,
4653 obstacle_bounds: AxisAlignedBox3D,
4654 fallback_contact: Vec3,
4655 ) -> Vec3 {
4656 let axes: [Vec3; 3] = obb.get_axes();
4657 let half: Vec3 = obb.get_half_extents();
4658 let center: Vec3 = obb.get_center();
4659 let ux: f32 = axes[0].get_x() * half.get_x();
4660 let uz: f32 = axes[0].get_z() * half.get_x();
4661 let vx: f32 = axes[2].get_x() * half.get_z();
4662 let vz: f32 = axes[2].get_z() * half.get_z();
4663 let cx: f32 = center.get_x();
4664 let cz: f32 = center.get_z();
4665 let corners: [(f32, f32); 4] = [
4666 (cx + ux + vx, cz + uz + vz),
4667 (cx + ux - vx, cz + uz - vz),
4668 (cx - ux + vx, cz - uz + vz),
4669 (cx - ux - vx, cz - uz - vz),
4670 ];
4671 let bmin: Vec3 = obstacle_bounds.get_min();
4672 let bmax: Vec3 = obstacle_bounds.get_max();
4673 let pad: f32 = 0.15;
4674 let in_obstacle: fn(f32, f32, Vec3, Vec3, f32) -> bool =
4675 |px: f32, pz: f32, lo: Vec3, hi: Vec3, margin: f32| -> bool {
4676 px >= lo.get_x() - margin
4677 && px <= hi.get_x() + margin
4678 && pz >= lo.get_z() - margin
4679 && pz <= hi.get_z() + margin
4680 };
4681 let mut best_in_proj: f32 = f32::NEG_INFINITY;
4682 let mut any_in: bool = false;
4683 let mut best_all_proj: f32 = f32::NEG_INFINITY;
4684 for &(px, pz) in corners.iter() {
4685 let proj: f32 = -(px * hn.get_x() + pz * hn.get_z());
4686 if proj > best_all_proj {
4687 best_all_proj = proj;
4688 }
4689 if in_obstacle(px, pz, bmin, bmax, pad) {
4690 any_in = true;
4691 if proj > best_in_proj {
4692 best_in_proj = proj;
4693 }
4694 }
4695 }
4696 let target_proj: f32 = if any_in { best_in_proj } else { best_all_proj };
4697 let mut sum_x: f32 = 0.0;
4698 let mut sum_z: f32 = 0.0;
4699 let mut cnt: f32 = 0.0;
4700 for &(px, pz) in corners.iter() {
4701 if any_in && !in_obstacle(px, pz, bmin, bmax, pad) {
4702 continue;
4703 }
4704 let proj: f32 = -(px * hn.get_x() + pz * hn.get_z());
4705 if proj >= target_proj - 0.16 {
4706 sum_x += px;
4707 sum_z += pz;
4708 cnt += 1.0;
4709 }
4710 }
4711 if cnt > 0.0 {
4712 Vec3::new(sum_x / cnt, fallback_contact.get_y().max(0.45), sum_z / cnt)
4713 } else {
4714 fallback_contact
4715 }
4716 }
4717
4718 fn apply_static_wall_impulse(
4733 car_pos: Vec3,
4734 vel: &mut Vec3,
4735 yaw_rate: &mut f32,
4736 inertia_pair: (f32, f32),
4737 hn: Vec3,
4738 contact_point: Vec3,
4739 ) -> f32 {
4740 let (inv_m, inv_i): (f32, f32) = inertia_pair;
4741 let raw_rx: f32 = contact_point.get_x() - car_pos.get_x();
4742 let raw_rz: f32 = contact_point.get_z() - car_pos.get_z();
4743 let r_len: f32 = (raw_rx * raw_rx + raw_rz * raw_rz).sqrt();
4744 let (rx, rz): (f32, f32) = if r_len > 2.6 {
4745 let scale_r: f32 = 2.6 / r_len;
4746 (raw_rx * scale_r, raw_rz * scale_r)
4747 } else {
4748 (raw_rx, raw_rz)
4749 };
4750 let v_pt_x: f32 = vel.get_x() + (*yaw_rate) * rz;
4751 let v_pt_z: f32 = vel.get_z() - (*yaw_rate) * rx;
4752 let v_n: f32 = v_pt_x * hn.get_x() + v_pt_z * hn.get_z();
4753 if v_n >= 0.0 {
4754 return 0.0;
4755 }
4756 let approach_speed: f32 = -v_n;
4757 let restitution: f32 = if approach_speed > 1.2 {
4758 COLLISION_WALL_RESTITUTION
4759 } else {
4760 0.0
4761 };
4762 let r_cross_n: f32 = rz * hn.get_x() - rx * hn.get_z();
4763 let denom_n: f32 = inv_m + (r_cross_n * r_cross_n) * inv_i;
4764 let j_n: f32 = (-(1.0 + restitution) * v_n / denom_n.max(1.0e-6)).max(0.0);
4765 vel.set_x(vel.get_x() + hn.get_x() * j_n * inv_m);
4766 vel.set_z(vel.get_z() + hn.get_z() * j_n * inv_m);
4767 *yaw_rate = (*yaw_rate + r_cross_n * j_n * inv_i)
4768 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
4769 let vt_x: f32 = v_pt_x - hn.get_x() * v_n;
4770 let vt_z: f32 = v_pt_z - hn.get_z() * v_n;
4771 let vt_len: f32 = (vt_x * vt_x + vt_z * vt_z).sqrt();
4772 if vt_len > 1.0e-4 && j_n > 0.0 {
4773 let tx: f32 = vt_x / vt_len;
4774 let tz: f32 = vt_z / vt_len;
4775 let r_cross_t: f32 = rz * tx - rx * tz;
4776 let denom_t: f32 = inv_m + (r_cross_t * r_cross_t) * inv_i;
4777 let max_jt: f32 = COLLISION_WALL_FRICTION * j_n;
4778 let j_t: f32 = (-vt_len / denom_t.max(1.0e-6)).clamp(-max_jt, max_jt);
4779 vel.set_x(vel.get_x() + tx * j_t * inv_m);
4780 vel.set_z(vel.get_z() + tz * j_t * inv_m);
4781 *yaw_rate = (*yaw_rate + r_cross_t * j_t * inv_i)
4782 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
4783 }
4784 approach_speed
4785 }
4786
4787 fn step_rigid_vehicle_static_ccd(
4802 &self,
4803 tr: &mut Transform3D,
4804 vel: &mut Vec3,
4805 yaw_rate: &mut f32,
4806 inertia_pair: (f32, f32),
4807 vehicle_spec: (usize, AxisAlignedBox3D),
4808 step_ctx: VehicleCcdStepCtx3D,
4809 ) -> (bool, f32, Vec3, Vec3) {
4810 let (vehicle_idx, mesh_bounds): (usize, AxisAlignedBox3D) = vehicle_spec;
4811 let VehicleCcdStepCtx3D {
4812 sub_dt,
4813 ground_limits,
4814 ground_margin,
4815 } = step_ctx;
4816 let mut moved: bool = self.depenetrate_vehicle_static_horizontally(
4817 tr,
4818 mesh_bounds,
4819 vehicle_idx,
4820 ground_limits,
4821 ground_margin,
4822 );
4823 let mut peak_impact: f32 = 0.0;
4824 let mut peak_contact: Vec3 = tr.get_position();
4825 let mut peak_normal: Vec3 = Vec3::new(0.0, 0.0, 1.0);
4826 let speed: f32 = (vel.get_x() * vel.get_x() + vel.get_z() * vel.get_z()).sqrt();
4827 let linear_dist: f32 = speed * sub_dt;
4828 let angular_dist: f32 = yaw_rate.abs() * sub_dt;
4829 if linear_dist <= 1.0e-6 && angular_dist <= 1.0e-6 {
4830 return (moved, peak_impact, peak_contact, peak_normal);
4831 }
4832 let obb_now: OrientedBox3D = tr.to_oriented_box(mesh_bounds);
4833 let min_half: f32 = obb_now
4834 .get_half_extents()
4835 .get_x()
4836 .min(obb_now.get_half_extents().get_z())
4837 .max(0.25);
4838 let max_lin_step: f32 = (min_half * 0.25).min(COLLISION_CCD_MAX_STEP_M);
4839 let lin_steps: usize =
4840 ((linear_dist / max_lin_step).ceil() as usize).clamp(1, COLLISION_CCD_MAX_SUBSTEPS);
4841 let rot_steps: usize = ((angular_dist / COLLISION_ROT_MAX_STEP_RAD).ceil() as usize)
4842 .clamp(1, COLLISION_ROT_MAX_SUBSTEPS);
4843 let substeps: usize = lin_steps.max(rot_steps);
4844 let step_dt: f32 = sub_dt / (substeps as f32);
4845 for _ in 0..substeps {
4846 let d_yaw: f32 = (*yaw_rate) * step_dt;
4847 if d_yaw.abs() > 1.0e-6 {
4848 let mut rotated: Transform3D = *tr;
4849 rotated.set_yaw_rad(tr.get_yaw_rad() + d_yaw);
4850 if let Some(rot_hit) = self.mesh_oriented_box_static_collision(
4851 rotated.to_oriented_box(mesh_bounds),
4852 Some(vehicle_idx),
4853 ) {
4854 if rot_hit.get_penetration() <= COLLISION_ROT_MAX_PUSH_M {
4855 let mut pushed_rot: Transform3D = rotated;
4856 let _: bool = self.depenetrate_vehicle_static_horizontally(
4857 &mut pushed_rot,
4858 mesh_bounds,
4859 vehicle_idx,
4860 ground_limits,
4861 ground_margin,
4862 );
4863 let shift_m: f32 = pushed_rot
4864 .get_position()
4865 .sub(rotated.get_position())
4866 .length();
4867 if shift_m <= COLLISION_ROT_MAX_PUSH_M
4868 && self
4869 .mesh_oriented_box_static_collision(
4870 pushed_rot.to_oriented_box(mesh_bounds),
4871 Some(vehicle_idx),
4872 )
4873 .is_none()
4874 {
4875 *tr = pushed_rot;
4876 moved = true;
4877 } else {
4878 *yaw_rate *= -0.2;
4879 }
4880 } else {
4881 *yaw_rate *= -0.2;
4882 }
4883 } else {
4884 *tr = rotated;
4885 moved = true;
4886 }
4887 }
4888 let step_dx: f32 = vel.get_x() * step_dt;
4889 let step_dz: f32 = vel.get_z() * step_dt;
4890 if step_dx * step_dx + step_dz * step_dz <= 1.0e-12 {
4891 continue;
4892 }
4893 let cur_pos: Vec3 = tr.get_position();
4894 let raw_next: Vec3 = Vec3::new(
4895 cur_pos.get_x() + step_dx,
4896 cur_pos.get_y(),
4897 cur_pos.get_z() + step_dz,
4898 );
4899 let next_pos: Vec3 =
4900 Self::clamp_horizontal_to_ground(raw_next, ground_limits, ground_margin);
4901 if (next_pos.get_x() - raw_next.get_x()).abs() > 1.0e-4 {
4902 vel.set_x(-vel.get_x() * COLLISION_WALL_RESTITUTION);
4903 }
4904 if (next_pos.get_z() - raw_next.get_z()).abs() > 1.0e-4 {
4905 vel.set_z(-vel.get_z() * COLLISION_WALL_RESTITUTION);
4906 }
4907 let mut cand: Transform3D = *tr;
4908 cand.set_position(next_pos);
4909 if let Some(hit) = self.mesh_oriented_box_static_collision(
4910 cand.to_oriented_box(mesh_bounds),
4911 Some(vehicle_idx),
4912 ) {
4913 let raw_hn: Vec3 =
4914 Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
4915 let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
4916 raw_hn.normalize()
4917 } else {
4918 self.horizontal_collision_normal(
4919 cand.to_oriented_box(mesh_bounds),
4920 hit.get_object_index(),
4921 )
4922 };
4923 if hn.length_sq() > 1.0e-6 {
4924 let obs_bounds: AxisAlignedBox3D = self
4925 .get_objects()
4926 .get(hit.get_object_index())
4927 .map(SceneObject3D::get_world_bounds)
4928 .unwrap_or_else(|| {
4929 AxisAlignedBox3D::new(
4930 hit.get_contact_point().sub(Vec3::splat(0.5)),
4931 hit.get_contact_point().add(Vec3::splat(0.5)),
4932 )
4933 });
4934 let phys_contact: Vec3 = Self::compute_static_contact_point(
4935 cand.to_oriented_box(mesh_bounds),
4936 hn,
4937 obs_bounds,
4938 hit.get_contact_point(),
4939 );
4940 let impact_v: f32 = Self::apply_static_wall_impulse(
4941 cur_pos,
4942 vel,
4943 yaw_rate,
4944 inertia_pair,
4945 hn,
4946 phys_contact,
4947 );
4948 if impact_v > peak_impact {
4949 peak_impact = impact_v;
4950 peak_contact = phys_contact;
4951 peak_normal = hn;
4952 }
4953 let slide_dx: f32 = vel.get_x() * step_dt;
4954 let slide_dz: f32 = vel.get_z() * step_dt;
4955 let push_eps: f32 = COLLISION_MTV_PUSH_EPS;
4956 let slide_pos: Vec3 = Self::clamp_horizontal_to_ground(
4957 Vec3::new(
4958 cur_pos.get_x() + slide_dx + hn.get_x() * push_eps,
4959 cur_pos.get_y(),
4960 cur_pos.get_z() + slide_dz + hn.get_z() * push_eps,
4961 ),
4962 ground_limits,
4963 ground_margin,
4964 );
4965 let mut slide_tr: Transform3D = *tr;
4966 slide_tr.set_position(slide_pos);
4967 if self
4968 .mesh_oriented_box_static_collision(
4969 slide_tr.to_oriented_box(mesh_bounds),
4970 Some(vehicle_idx),
4971 )
4972 .is_none()
4973 {
4974 *tr = slide_tr;
4975 moved = true;
4976 continue;
4977 }
4978 }
4979 break;
4980 }
4981 *tr = cand;
4982 moved = true;
4983 }
4984 if self.depenetrate_vehicle_static_horizontally(
4985 tr,
4986 mesh_bounds,
4987 vehicle_idx,
4988 ground_limits,
4989 ground_margin,
4990 ) {
4991 moved = true;
4992 }
4993 (moved, peak_impact, peak_contact, peak_normal)
4994 }
4995
4996 fn emit_collision_sparks(&mut self, contact: Vec3, normal: Vec3, intensity: f32) {
5004 if self.get_niagara().get_active_count() >= 56 {
5005 return;
5006 }
5007 let burst: usize = ((3.0 + intensity * 6.0).round() as usize).clamp(2, 9);
5008 let mut cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
5009 cfg.set_origin(Vec3::new(
5010 contact.get_x(),
5011 contact.get_y().max(0.45),
5012 contact.get_z(),
5013 ));
5014 cfg.set_base_velocity(normal.scale(4.5 + intensity * 7.5).add(Vec3::new(
5015 0.0,
5016 2.8 + intensity * 2.5,
5017 0.0,
5018 )));
5019 cfg.set_velocity_spread(3.8 + intensity * 2.5);
5020 cfg.set_start_color(Color::rgba(255, 196, 36, 255));
5021 cfg.set_end_color(Color::rgba(255, 72, 0, 80));
5022 cfg.set_start_size_m(0.12);
5023 cfg.set_end_size_m(0.03);
5024 cfg.set_min_lifetime(0.22);
5025 cfg.set_max_lifetime(0.55);
5026 cfg.set_emissive_boost(1.75);
5027 self.get_mut_niagara().emit_burst(burst, &cfg);
5028 }
5029
5030 fn emit_drift_smoke(
5039 &mut self,
5040 car_origin: Vec3,
5041 car_fwd: Vec3,
5042 car_right: Vec3,
5043 slip_abs: f32,
5044 ) {
5045 if self.get_niagara().get_active_count() >= 48 {
5046 return;
5047 }
5048 let intensity: f32 = ((slip_abs - 0.10) / 0.50).clamp(0.25, 1.0);
5049 let rear_center: Vec3 = car_origin
5050 .sub(car_fwd.scale(1.85))
5051 .add(Vec3::new(0.0, 0.22, 0.0));
5052 for side in [-0.88_f32, 0.88_f32] {
5053 let wheel_pos: Vec3 = rear_center.add(car_right.scale(side));
5054 let mut smoke_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
5055 smoke_cfg.set_origin(wheel_pos);
5056 smoke_cfg.set_base_velocity(car_fwd.scale(-2.4).add(Vec3::new(
5057 0.0,
5058 0.85 + intensity * 0.5,
5059 0.0,
5060 )));
5061 smoke_cfg.set_velocity_spread(1.25);
5062 smoke_cfg.set_start_color(Color::rgba(226, 232, 240, 175));
5063 smoke_cfg.set_end_color(Color::rgba(148, 163, 184, 30));
5064 smoke_cfg.set_start_size_m(0.22 + intensity * 0.12);
5065 smoke_cfg.set_end_size_m(0.52 + intensity * 0.18);
5066 smoke_cfg.set_min_lifetime(0.35);
5067 smoke_cfg.set_max_lifetime(0.75);
5068 smoke_cfg.set_emissive_boost(0.35);
5069 self.get_mut_niagara().emit_burst(1, &smoke_cfg);
5070 }
5071 }
5072
5073 fn emit_boost_flame(
5082 &mut self,
5083 car_origin: Vec3,
5084 car_fwd: Vec3,
5085 car_right: Vec3,
5086 car_vel: Vec3,
5087 ) {
5088 if self.get_niagara().get_active_count() >= 64 {
5089 return;
5090 }
5091 let exhaust_center: Vec3 = car_origin
5092 .sub(car_fwd.scale(2.35))
5093 .add(Vec3::new(0.0, 0.44, 0.0));
5094 let base_jet_vel: Vec3 = car_vel
5095 .scale(0.65)
5096 .add(car_fwd.scale(-8.5))
5097 .add(Vec3::new(0.0, 0.35, 0.0));
5098 for side in [-0.46_f32, 0.46_f32] {
5099 let pipe_pos: Vec3 = exhaust_center.add(car_right.scale(side));
5100 let mut flame_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
5101 flame_cfg.set_origin(pipe_pos);
5102 flame_cfg.set_base_velocity(base_jet_vel);
5103 flame_cfg.set_velocity_spread(0.85);
5104 flame_cfg.set_start_color(Color::rgba(0, 178, 255, 245));
5105 flame_cfg.set_end_color(Color::rgba(255, 88, 0, 75));
5106 flame_cfg.set_start_size_m(0.17);
5107 flame_cfg.set_end_size_m(0.05);
5108 flame_cfg.set_min_lifetime(0.10);
5109 flame_cfg.set_max_lifetime(0.22);
5110 flame_cfg.set_emissive_boost(1.65);
5111 self.get_mut_niagara().emit_burst(2, &flame_cfg);
5112 }
5113 }
5114
5115 #[must_use]
5129 fn npc_forward_blocking_gap(
5130 &self,
5131 npc_idx: usize,
5132 pos: Vec3,
5133 fwd: Vec3,
5134 right: Vec3,
5135 npc_fwd_speed: f32,
5136 ) -> Option<f32> {
5137 let mut closest: Option<f32> = None;
5138 let objects: &[SceneObject3D] = self.get_objects().as_slice();
5139 let player_opt: Option<usize> = self.vehicle_index();
5140 let player_vel: Vec3 = self.player_velocity();
5141 let Self {
5142 traffic_vehicles, ..
5143 } = self;
5144 for (other_idx, other_obj) in objects.iter().enumerate() {
5145 let other_solid: bool =
5146 other_obj.get_solid_collider() || other_obj.get_ray_trace_caster();
5147 if other_idx == npc_idx || !other_obj.get_is_dynamic() || !other_solid {
5148 continue;
5149 }
5150 let other_pos: Vec3 = other_obj.get_transform().get_position();
5151 let diff: Vec3 = Vec3::new(
5152 other_pos.get_x() - pos.get_x(),
5153 0.0,
5154 other_pos.get_z() - pos.get_z(),
5155 );
5156 let fwd_d: f32 = diff.dot(fwd);
5157 if fwd_d <= 0.5 || fwd_d >= 16.0 {
5158 continue;
5159 }
5160 let lat_d: f32 = diff.dot(right).abs();
5161 if lat_d > 2.75 {
5162 continue;
5163 }
5164 let other_vel: Vec3 = if player_opt == Some(other_idx) {
5165 player_vel
5166 } else {
5167 traffic_vehicles
5168 .iter()
5169 .find(|n: &&NpcVehicle3D| n.get_object_index() == other_idx)
5170 .map(NpcVehicle3D::get_vel)
5171 .unwrap_or_else(Vec3::zero)
5172 };
5173 let other_fwd_speed: f32 = other_vel.dot(fwd);
5174 if other_fwd_speed < npc_fwd_speed - 0.5 || other_fwd_speed.abs() < 1.5 {
5175 closest = Some(closest.map(|prev: f32| prev.min(fwd_d)).unwrap_or(fwd_d));
5176 }
5177 }
5178 closest
5179 }
5180
5181 fn resolve_dynamic_vehicle_collisions(
5191 &mut self,
5192 ground_limits: Option<(f32, f32, f32, f32)>,
5193 ) -> (bool, f32, Vec3, Vec3) {
5194 let player_opt: Option<usize> = self.vehicle_index();
5195 let npc_count: usize = self.traffic_vehicle_count();
5196 let total_bodies: usize = npc_count + usize::from(player_opt.is_some());
5197 if total_bodies < 2 {
5198 return (false, 0.0, Vec3::zero(), Vec3::new(0.0, 0.0, 1.0));
5199 }
5200 let mut any_moved: bool = false;
5201 let mut player_peak_impact: f32 = 0.0;
5202 let mut player_peak_contact: Vec3 = Vec3::zero();
5203 let mut player_peak_normal: Vec3 = Vec3::new(0.0, 0.0, 1.0);
5204 let player_offset: usize = usize::from(player_opt.is_some());
5205 for _ in 0..2_usize {
5206 for idx_a in 0..total_bodies {
5207 for idx_b in (idx_a + 1)..total_bodies {
5208 let is_a_player: bool = player_opt.is_some() && idx_a == 0;
5209 let obj_a: usize = if is_a_player {
5210 match player_opt {
5211 Some(p_idx) => p_idx,
5212 None => continue,
5213 }
5214 } else {
5215 match self.traffic_vehicle_object_index(idx_a - player_offset) {
5216 Some(n_idx) => n_idx,
5217 None => continue,
5218 }
5219 };
5220 let npc_slot_b: usize = idx_b - player_offset;
5221 let Some(obj_b) = self.traffic_vehicle_object_index(npc_slot_b) else {
5222 continue;
5223 };
5224 let Some((mut tr_a, mesh_a)) = self
5225 .get_objects()
5226 .get(obj_a)
5227 .map(|o: &SceneObject3D| (o.get_transform(), o.get_mesh_id()))
5228 else {
5229 continue;
5230 };
5231 let Some((mut tr_b, mesh_b)) = self
5232 .get_objects()
5233 .get(obj_b)
5234 .map(|o: &SceneObject3D| (o.get_transform(), o.get_mesh_id()))
5235 else {
5236 continue;
5237 };
5238 let bounds_a: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_a);
5239 let bounds_b: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_b);
5240 let obb_a: OrientedBox3D = tr_a.to_oriented_box(bounds_a);
5241 let obb_b: OrientedBox3D = tr_b.to_oriented_box(bounds_b);
5242 let Some((normal_ba, pen, contact)) = obb_a.intersect_oriented_box_xz(&obb_b)
5243 else {
5244 continue;
5245 };
5246 let (mut vel_a, mut omega_a, mass_a, inv_i_a): (Vec3, f32, f32, f32) =
5247 if is_a_player {
5248 (
5249 self.player_velocity(),
5250 self.player_yaw_rate(),
5251 VEHICLE_PLAYER_MASS_KG,
5252 1.0 / VEHICLE_PLAYER_INERTIA_YAW,
5253 )
5254 } else {
5255 let Self {
5256 traffic_vehicles, ..
5257 } = self;
5258 let npc_a: NpcVehicle3D = traffic_vehicles[idx_a - player_offset];
5259 (
5260 npc_a.get_vel(),
5261 npc_a.get_yaw_rate(),
5262 npc_a.get_mass(),
5263 1.0 / VEHICLE_NPC_INERTIA_YAW,
5264 )
5265 };
5266 let (mut vel_b, mut omega_b, mass_b, inv_i_b): (Vec3, f32, f32, f32) = {
5267 let Self {
5268 traffic_vehicles, ..
5269 } = self;
5270 let npc_b: NpcVehicle3D = traffic_vehicles[npc_slot_b];
5271 (
5272 npc_b.get_vel(),
5273 npc_b.get_yaw_rate(),
5274 npc_b.get_mass(),
5275 1.0 / VEHICLE_NPC_INERTIA_YAW,
5276 )
5277 };
5278 let inv_m_a: f32 = 1.0 / mass_a.max(100.0);
5279 let inv_m_b: f32 = 1.0 / mass_b.max(100.0);
5280 let inv_m_sum: f32 = inv_m_a + inv_m_b;
5281 let total_push: f32 = pen + COLLISION_MTV_PUSH_EPS;
5282 let share_a: f32 = total_push * (inv_m_a / inv_m_sum);
5283 let share_b: f32 = total_push * (inv_m_b / inv_m_sum);
5284 let margin_a: f32 = obb_a
5285 .get_half_extents()
5286 .get_x()
5287 .max(obb_a.get_half_extents().get_z());
5288 let margin_b: f32 = obb_b
5289 .get_half_extents()
5290 .get_x()
5291 .max(obb_b.get_half_extents().get_z());
5292 let cand_pos_a: Vec3 = Self::clamp_horizontal_to_ground(
5293 tr_a.get_position().add(normal_ba.scale(share_a)),
5294 ground_limits,
5295 margin_a,
5296 );
5297 let cand_pos_b: Vec3 = Self::clamp_horizontal_to_ground(
5298 tr_b.get_position().sub(normal_ba.scale(share_b)),
5299 ground_limits,
5300 margin_b,
5301 );
5302 let mut cand_tr_a: Transform3D = tr_a;
5303 cand_tr_a.set_position(cand_pos_a);
5304 let mut cand_tr_b: Transform3D = tr_b;
5305 cand_tr_b.set_position(cand_pos_b);
5306 let a_static_ok: bool = self
5307 .mesh_oriented_box_static_collision(
5308 cand_tr_a.to_oriented_box(bounds_a),
5309 Some(obj_a),
5310 )
5311 .is_none();
5312 let b_static_ok: bool = self
5313 .mesh_oriented_box_static_collision(
5314 cand_tr_b.to_oriented_box(bounds_b),
5315 Some(obj_b),
5316 )
5317 .is_none();
5318 if a_static_ok && b_static_ok {
5319 tr_a = cand_tr_a;
5320 tr_b = cand_tr_b;
5321 } else if b_static_ok {
5322 let full_b: Vec3 = Self::clamp_horizontal_to_ground(
5323 tr_b.get_position().sub(normal_ba.scale(total_push)),
5324 ground_limits,
5325 margin_b,
5326 );
5327 tr_b.set_position(full_b);
5328 } else if a_static_ok {
5329 let full_a: Vec3 = Self::clamp_horizontal_to_ground(
5330 tr_a.get_position().add(normal_ba.scale(total_push)),
5331 ground_limits,
5332 margin_a,
5333 );
5334 tr_a.set_position(full_a);
5335 } else {
5336 tr_a = cand_tr_a;
5337 tr_b = cand_tr_b;
5338 let _: bool = self.depenetrate_vehicle_static_horizontally(
5339 &mut tr_a,
5340 bounds_a,
5341 obj_a,
5342 ground_limits,
5343 margin_a,
5344 );
5345 let _: bool = self.depenetrate_vehicle_static_horizontally(
5346 &mut tr_b,
5347 bounds_b,
5348 obj_b,
5349 ground_limits,
5350 margin_b,
5351 );
5352 }
5353 let pos_a: Vec3 = tr_a.get_position();
5354 let pos_b: Vec3 = tr_b.get_position();
5355 let ra_x: f32 = (contact.get_x() - pos_a.get_x()).clamp(-2.6, 2.6);
5356 let ra_z: f32 = (contact.get_z() - pos_a.get_z()).clamp(-2.6, 2.6);
5357 let rb_x: f32 = (contact.get_x() - pos_b.get_x()).clamp(-2.6, 2.6);
5358 let rb_z: f32 = (contact.get_z() - pos_b.get_z()).clamp(-2.6, 2.6);
5359 let va_pt_x: f32 = vel_a.get_x() + omega_a * ra_z;
5360 let va_pt_z: f32 = vel_a.get_z() - omega_a * ra_x;
5361 let vb_pt_x: f32 = vel_b.get_x() + omega_b * rb_z;
5362 let vb_pt_z: f32 = vel_b.get_z() - omega_b * rb_x;
5363 let vrel_x: f32 = va_pt_x - vb_pt_x;
5364 let vrel_z: f32 = va_pt_z - vb_pt_z;
5365 let vrel_n: f32 = vrel_x * normal_ba.get_x() + vrel_z * normal_ba.get_z();
5366 let mut impact_dv_a: f32 = 0.0;
5367 let mut impact_dv_b: f32 = 0.0;
5368 if vrel_n < 0.0 {
5369 let ra_cross_n: f32 = ra_z * normal_ba.get_x() - ra_x * normal_ba.get_z();
5370 let rb_cross_n: f32 = rb_z * normal_ba.get_x() - rb_x * normal_ba.get_z();
5371 let denom_n: f32 = inv_m_a
5372 + inv_m_b
5373 + (ra_cross_n * ra_cross_n) * inv_i_a
5374 + (rb_cross_n * rb_cross_n) * inv_i_b;
5375 let restitution: f32 = if -vrel_n > 1.5 {
5376 COLLISION_CAR_RESTITUTION
5377 } else {
5378 0.05
5379 };
5380 let j_n: f32 =
5381 (-(1.0 + restitution) * vrel_n / denom_n.max(1.0e-6)).max(0.0);
5382 vel_a.set_x(vel_a.get_x() + normal_ba.get_x() * j_n * inv_m_a);
5383 vel_a.set_z(vel_a.get_z() + normal_ba.get_z() * j_n * inv_m_a);
5384 omega_a = (omega_a + ra_cross_n * j_n * inv_i_a)
5385 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5386 vel_b.set_x(vel_b.get_x() - normal_ba.get_x() * j_n * inv_m_b);
5387 vel_b.set_z(vel_b.get_z() - normal_ba.get_z() * j_n * inv_m_b);
5388 omega_b = (omega_b - rb_cross_n * j_n * inv_i_b)
5389 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5390 impact_dv_a = j_n * inv_m_a;
5391 impact_dv_b = j_n * inv_m_b;
5392 let vt_x: f32 = vrel_x - normal_ba.get_x() * vrel_n;
5393 let vt_z: f32 = vrel_z - normal_ba.get_z() * vrel_n;
5394 let vt_len: f32 = (vt_x * vt_x + vt_z * vt_z).sqrt();
5395 if vt_len > 1.0e-4 && j_n > 0.0 {
5396 let tx: f32 = vt_x / vt_len;
5397 let tz: f32 = vt_z / vt_len;
5398 let ra_cross_t: f32 = ra_z * tx - ra_x * tz;
5399 let rb_cross_t: f32 = rb_z * tx - rb_x * tz;
5400 let denom_t: f32 = inv_m_a
5401 + inv_m_b
5402 + (ra_cross_t * ra_cross_t) * inv_i_a
5403 + (rb_cross_t * rb_cross_t) * inv_i_b;
5404 let max_jt: f32 = COLLISION_CAR_FRICTION * j_n;
5405 let j_t: f32 = (-vt_len / denom_t.max(1.0e-6)).clamp(-max_jt, max_jt);
5406 vel_a.set_x(vel_a.get_x() + tx * j_t * inv_m_a);
5407 vel_a.set_z(vel_a.get_z() + tz * j_t * inv_m_a);
5408 omega_a = (omega_a + ra_cross_t * j_t * inv_i_a)
5409 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5410 vel_b.set_x(vel_b.get_x() - tx * j_t * inv_m_b);
5411 vel_b.set_z(vel_b.get_z() - tz * j_t * inv_m_b);
5412 omega_b = (omega_b - rb_cross_t * j_t * inv_i_b)
5413 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5414 }
5415 let closing: f32 = -vrel_n;
5416 if is_a_player && closing > player_peak_impact {
5417 player_peak_impact = closing;
5418 player_peak_contact = contact;
5419 player_peak_normal = normal_ba;
5420 }
5421 if closing > 2.5 {
5422 let spark_int: f32 = ((closing - 2.0) / 24.0).clamp(0.15, 1.0);
5423 self.emit_collision_sparks(contact, normal_ba, spark_int);
5424 }
5425 }
5426 let wb_a: AxisAlignedBox3D = tr_a.transform_bounds(bounds_a);
5427 let wb_b: AxisAlignedBox3D = tr_b.transform_bounds(bounds_b);
5428 if let Some(o_a) = self.get_mut_objects().get_mut(obj_a) {
5429 o_a.set_transform(tr_a);
5430 o_a.set_world_bounds(wb_a);
5431 }
5432 if let Some(o_b) = self.get_mut_objects().get_mut(obj_b) {
5433 o_b.set_transform(tr_b);
5434 o_b.set_world_bounds(wb_b);
5435 }
5436 if is_a_player {
5437 let Self { player_physics, .. } = self;
5438 player_physics.set_vel(vel_a);
5439 player_physics.set_yaw_rate(omega_a);
5440 } else {
5441 let slot_a: usize = idx_a - player_offset;
5442 let Self {
5443 traffic_vehicles, ..
5444 } = self;
5445 let npc_a: &mut NpcVehicle3D = &mut traffic_vehicles[slot_a];
5446 npc_a.set_vel(vel_a);
5447 npc_a.set_yaw_rate(omega_a);
5448 if impact_dv_a > 1.5 {
5449 let rec_s: f32 = (1.4 + impact_dv_a * 0.08).clamp(1.2, 2.8);
5450 npc_a.set_recovery_timer(npc_a.get_recovery_timer().max(rec_s));
5451 npc_a.set_free_roam_mode(true);
5452 }
5453 }
5454 {
5455 let Self {
5456 traffic_vehicles, ..
5457 } = self;
5458 let npc_b: &mut NpcVehicle3D = &mut traffic_vehicles[npc_slot_b];
5459 npc_b.set_vel(vel_b);
5460 npc_b.set_yaw_rate(omega_b);
5461 if impact_dv_b > 1.5 {
5462 let rec_s: f32 = (1.4 + impact_dv_b * 0.08).clamp(1.2, 2.8);
5463 npc_b.set_recovery_timer(npc_b.get_recovery_timer().max(rec_s));
5464 npc_b.set_free_roam_mode(true);
5465 }
5466 }
5467 any_moved = true;
5468 }
5469 }
5470 }
5471 (
5472 any_moved,
5473 player_peak_impact,
5474 player_peak_contact,
5475 player_peak_normal,
5476 )
5477 }
5478
5479 pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
5487 if dt <= 0.0 || !dt.is_finite() {
5488 return;
5489 }
5490 self.set_world_time_secs(self.get_world_time_secs() + dt);
5491 let sim_tick: u64 = self.get_sim_tick().wrapping_add(1);
5492 self.set_sim_tick(sim_tick);
5493 let kb_steer: f32 = if actions.is_active(GameAction::MoveRight, input) {
5494 1.0
5495 } else {
5496 0.0
5497 } - if actions.is_active(GameAction::MoveLeft, input) {
5498 1.0
5499 } else {
5500 0.0
5501 };
5502 let kb_throttle: f32 = if actions.is_active(GameAction::MoveUp, input) {
5503 1.0
5504 } else {
5505 0.0
5506 } - if actions.is_active(GameAction::MoveDown, input) {
5507 1.0
5508 } else {
5509 0.0
5510 };
5511 let v_stick: Point = input.get_virtual_axis();
5512 let steer: f32 = (kb_steer + v_stick.get_x()).clamp(-1.0, 1.0);
5513 let throttle: f32 = (kb_throttle - v_stick.get_y()).clamp(-1.0, 1.0);
5514 let boost_pressed: bool = actions.is_active(GameAction::Boost, input)
5515 || input.get_modifiers().get_shift()
5516 || input.get_virtual_boost();
5517 let drift_pressed: bool = actions.is_active(GameAction::Drift, input)
5518 || input.is_key_down(KeyCode::Space)
5519 || input.get_virtual_drift();
5520 let mut any_dynamic_moved: bool = false;
5521 let mut any_static_moved: bool = false;
5522 let ground_limits: Option<(f32, f32, f32, f32)> = self.ground_play_bounds();
5523 let car_opt: Option<usize> = self.vehicle_index();
5524 let sim_substeps: usize = ((dt / 0.02).ceil() as usize).clamp(1, 6);
5525 let sub_dt: f32 = dt / (sim_substeps as f32);
5526 let mut player_moved_any: bool = false;
5527 for _ in 0..sim_substeps {
5528 if let Some(car_idx) = car_opt
5529 && let Some((cur_tr, mesh_id, car_is_dynamic)) =
5530 self.get_objects().get(car_idx).map(|car: &SceneObject3D| {
5531 (car.get_transform(), car.get_mesh_id(), car.get_is_dynamic())
5532 })
5533 {
5534 let mesh_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
5535 let mut phys: PlayerVehiclePhysics3D = {
5536 let Self { player_physics, .. } = self;
5537 *player_physics
5538 };
5539 let mut flat_tr: Transform3D = Transform3D::new(
5540 Vec3::new(
5541 cur_tr.get_position().get_x(),
5542 0.0,
5543 cur_tr.get_position().get_z(),
5544 ),
5545 cur_tr.get_yaw_rad(),
5546 cur_tr.get_scale(),
5547 );
5548 let flat_obb: OrientedBox3D = flat_tr.to_oriented_box(mesh_bounds);
5549 let ground_margin: f32 = flat_obb
5550 .get_half_extents()
5551 .get_x()
5552 .max(flat_obb.get_half_extents().get_z());
5553 let yaw_now: f32 = flat_tr.get_yaw_rad();
5554 let fwd: Vec3 = Vec3::new(-yaw_now.sin(), 0.0, -yaw_now.cos());
5555 let right: Vec3 = Vec3::new(yaw_now.cos(), 0.0, -yaw_now.sin());
5556 let mut vel: Vec3 = phys.get_vel();
5557 let mut v_fwd: f32 = vel.dot(fwd);
5558 let mut v_lat: f32 = vel.dot(right);
5559 let speed_now: f32 = (v_fwd * v_fwd + v_lat * v_lat).sqrt();
5560 let was_boosting: bool = phys.get_boost_active();
5561 let mut boost_charge: f32 = phys.get_boost_charge();
5562 let can_boost: bool = if was_boosting {
5563 boost_charge > 0.0
5564 } else {
5565 boost_charge >= VEHICLE_BOOST_MIN_REIGNITE
5566 };
5567 let boost_active: bool = boost_pressed && can_boost && throttle >= -0.05;
5568 let was_drifting: bool = phys.get_drift_active();
5569 let drift_active: bool = drift_pressed
5570 && speed_now > VEHICLE_DRIFT_MIN_SPEED_MPS
5571 && v_fwd > VEHICLE_DRIFT_MIN_FWD_MPS;
5572 if boost_active {
5573 boost_charge = (boost_charge - VEHICLE_BOOST_DRAIN_PER_SEC * sub_dt).max(0.0);
5574 } else {
5575 let regen_rate: f32 = if drift_active {
5576 VEHICLE_BOOST_DRIFT_REGEN_PER_SEC
5577 } else {
5578 VEHICLE_BOOST_REGEN_PER_SEC
5579 };
5580 boost_charge = (boost_charge + regen_rate * sub_dt).min(1.0);
5581 }
5582 let mut drift_duration: f32 = phys.get_drift_duration();
5583 let mut drift_peak_slip: f32 = phys.get_drift_peak_slip();
5584 let mut exit_kick_triggered: bool = false;
5585 if drift_active {
5586 drift_duration += sub_dt;
5587 } else if was_drifting {
5588 if drift_duration >= VEHICLE_DRIFT_EXIT_MIN_SECS
5589 && drift_peak_slip >= VEHICLE_DRIFT_EXIT_MIN_SLIP_RAD
5590 && v_fwd > 4.0
5591 {
5592 let slip_snap: f32 = v_lat.abs() * 0.45;
5593 v_fwd = (v_fwd + VEHICLE_DRIFT_EXIT_KICK_MPS + slip_snap)
5594 .min(VEHICLE_BOOST_TOP_SPEED_MPS);
5595 exit_kick_triggered = true;
5596 }
5597 drift_duration = 0.0;
5598 drift_peak_slip = 0.0;
5599 } else {
5600 drift_duration = 0.0;
5601 drift_peak_slip = 0.0;
5602 }
5603 let eff_throttle: f32 = if boost_active && throttle >= 0.0 {
5604 throttle.max(1.0)
5605 } else {
5606 throttle
5607 };
5608 let top_fwd: f32 = if boost_active {
5609 VEHICLE_BOOST_TOP_SPEED_MPS
5610 } else {
5611 VEHICLE_NORMAL_TOP_SPEED_MPS
5612 };
5613 let long_accel: f32 = if eff_throttle > 0.05 {
5614 if v_fwd < -0.5 {
5615 VEHICLE_BRAKE_DECEL_MPS2
5616 } else {
5617 let launch: f32 = VEHICLE_NORMAL_ACCEL_MPS2
5618 + VEHICLE_LAUNCH_BONUS_MPS2
5619 * (-(v_fwd.abs()) / VEHICLE_LAUNCH_TAPER_MPS).exp();
5620 let mult: f32 = if boost_active {
5621 VEHICLE_BOOST_THRUST_MULT
5622 } else {
5623 1.0
5624 };
5625 let speed_ratio: f32 = (v_fwd / top_fwd).clamp(0.0, 1.0);
5626 let taper: f32 = (1.0 - speed_ratio * speed_ratio * 0.65).max(0.18);
5627 eff_throttle * launch * mult * taper
5628 }
5629 } else if eff_throttle < -0.05 {
5630 if v_fwd > 0.5 {
5631 -VEHICLE_BRAKE_DECEL_MPS2
5632 } else {
5633 let launch: f32 = VEHICLE_NORMAL_ACCEL_MPS2
5634 + VEHICLE_LAUNCH_BONUS_MPS2
5635 * (-(v_fwd.abs()) / VEHICLE_LAUNCH_TAPER_MPS).exp();
5636 let speed_ratio: f32 =
5637 ((-v_fwd) / VEHICLE_REVERSE_TOP_SPEED_MPS).clamp(0.0, 1.0);
5638 let taper: f32 = (1.0 - speed_ratio * speed_ratio * 0.65).max(0.2);
5639 eff_throttle * launch * taper
5640 }
5641 } else {
5642 let handbrake_drag: f32 = if drift_pressed { 4.5 } else { 0.0 };
5643 let drag: f32 = (VEHICLE_ROLLING_DRAG + handbrake_drag) * v_fwd
5644 + VEHICLE_AERO_DRAG * v_fwd * v_fwd.abs();
5645 -drag
5646 };
5647 v_fwd += long_accel * sub_dt;
5648 if eff_throttle.abs() <= 0.05 && v_fwd.abs() < 0.08 && v_lat.abs() < 0.08 {
5649 v_fwd = 0.0;
5650 v_lat = 0.0;
5651 } else {
5652 let max_allowed_fwd: f32 = if boost_active || exit_kick_triggered {
5653 VEHICLE_BOOST_TOP_SPEED_MPS
5654 } else if v_fwd > VEHICLE_NORMAL_TOP_SPEED_MPS {
5655 (v_fwd - 10.0 * sub_dt).max(VEHICLE_NORMAL_TOP_SPEED_MPS)
5656 } else {
5657 VEHICLE_NORMAL_TOP_SPEED_MPS
5658 };
5659 v_fwd = v_fwd.clamp(-VEHICLE_REVERSE_TOP_SPEED_MPS, max_allowed_fwd);
5660 }
5661 let slip_before: f32 = v_lat.atan2(v_fwd.abs().max(1.0));
5662 let lat_grip: f32 = if drift_active {
5663 let extra_scrub: f32 = ((slip_before.abs() - 0.66).max(0.0)) * 5.2;
5664 VEHICLE_DRIFT_LAT_GRIP + extra_scrub
5665 } else {
5666 VEHICLE_NORMAL_LAT_GRIP
5667 };
5668 v_lat *= (-lat_grip * sub_dt).exp();
5669 let mut yaw_rate: f32 = phys.get_yaw_rate();
5670 let steer_sign: f32 =
5671 if v_fwd < -0.35 || (v_fwd.abs() <= 0.35 && eff_throttle < -0.05) {
5672 -1.0
5673 } else {
5674 1.0
5675 };
5676 let active_speed: f32 = (v_fwd * v_fwd + v_lat * v_lat).sqrt();
5677 let base_auth: f32 = (0.90 + 0.10 * (active_speed / 8.0).min(1.0)).min(1.0);
5678 let high_speed_calm: f32 = if drift_active {
5679 1.0
5680 } else {
5681 (1.0 - ((active_speed - 28.0).max(0.0) / 60.0)).clamp(0.72, 1.0)
5682 };
5683 let steer_authority: f32 = base_auth * high_speed_calm;
5684 let yaw_gain: f32 = if drift_active {
5685 VEHICLE_DRIFT_YAW_GAIN
5686 } else {
5687 VEHICLE_NORMAL_YAW_GAIN
5688 };
5689 let target_yaw_rate: f32 = if steer.abs() > 0.05 {
5690 -steer * steer_sign * yaw_gain * steer_authority
5691 } else {
5692 0.0
5693 };
5694 let yaw_resp: f32 = if drift_active { 12.0 } else { 32.0 };
5695 let yaw_blend: f32 = 1.0 - (-yaw_resp * sub_dt).exp();
5696 yaw_rate += (target_yaw_rate - yaw_rate) * yaw_blend;
5697 if drift_active {
5698 let slip_excess: f32 = (slip_before.abs() - 0.56).max(0.0);
5699 if slip_excess > 0.0 {
5700 let align_torque: f32 = -slip_before.signum() * slip_excess * 5.8;
5701 yaw_rate += align_torque * sub_dt;
5702 }
5703 if steer.abs() > 0.05 && slip_before.abs() < 0.28 {
5704 let kick_dir: f32 = -steer.signum();
5705 v_lat += -kick_dir * 6.5 * sub_dt;
5706 }
5707 }
5708 if steer.abs() <= 0.05 && yaw_rate.abs() < 0.01 && active_speed < 0.1 {
5709 yaw_rate = 0.0;
5710 }
5711 yaw_rate = yaw_rate.clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5712 vel = fwd.scale(v_fwd).add(right.scale(v_lat));
5713 let (ccd_moved, wall_impact, wall_contact, wall_normal): (bool, f32, Vec3, Vec3) =
5714 self.step_rigid_vehicle_static_ccd(
5715 &mut flat_tr,
5716 &mut vel,
5717 &mut yaw_rate,
5718 (
5719 1.0 / VEHICLE_PLAYER_MASS_KG,
5720 1.0 / VEHICLE_PLAYER_INERTIA_YAW,
5721 ),
5722 (car_idx, mesh_bounds),
5723 VehicleCcdStepCtx3D {
5724 sub_dt,
5725 ground_limits,
5726 ground_margin,
5727 },
5728 );
5729 let final_yaw: f32 = flat_tr.get_yaw_rad();
5730 let final_fwd: Vec3 = Vec3::new(-final_yaw.sin(), 0.0, -final_yaw.cos());
5731 let final_right: Vec3 = Vec3::new(final_yaw.cos(), 0.0, -final_yaw.sin());
5732 let post_vfwd: f32 = vel.dot(final_fwd);
5733 let post_vlat: f32 = vel.dot(final_right);
5734 let post_slip: f32 = if post_vfwd.abs() + post_vlat.abs() > 1.0 {
5735 post_vlat.atan2(post_vfwd.abs().max(1.0))
5736 } else {
5737 0.0
5738 };
5739 if drift_active {
5740 drift_peak_slip = drift_peak_slip.max(post_slip.abs());
5741 }
5742 let mut cam_shake: f32 = phys.get_camera_shake() * (-7.5 * sub_dt).exp();
5743 if cam_shake < 0.004 {
5744 cam_shake = 0.0;
5745 }
5746 let mut body_pitch: f32 = phys.get_body_pitch_rad();
5747 if wall_impact > 2.8 {
5748 let imp_norm: f32 = ((wall_impact - 2.0) / 26.0).clamp(0.0, 1.0);
5749 cam_shake = cam_shake.max(imp_norm * 0.65);
5750 if wall_normal.dot(final_fwd) < -0.35 {
5751 body_pitch = (body_pitch - imp_norm * 0.055).clamp(-0.08, 0.06);
5752 }
5753 self.emit_collision_sparks(wall_contact, wall_normal, imp_norm);
5754 }
5755 let target_roll: f32 = if post_vlat.abs() > 0.25 {
5756 (-post_vlat * 0.011).clamp(-0.085, 0.085)
5757 } else {
5758 0.0
5759 };
5760 let target_pitch: f32 = if boost_active {
5761 0.036
5762 } else if long_accel > 8.0 {
5763 0.018
5764 } else if long_accel < -15.0 {
5765 -0.028
5766 } else {
5767 0.0
5768 };
5769 let susp_blend: f32 = 1.0 - (-10.0 * sub_dt).exp();
5770 let mut body_roll: f32 = phys.get_body_roll_rad()
5771 + (target_roll - phys.get_body_roll_rad()) * susp_blend;
5772 body_pitch += (target_pitch - body_pitch) * susp_blend;
5773 if body_roll.abs() < 0.0005 && target_roll == 0.0 {
5774 body_roll = 0.0;
5775 }
5776 if body_pitch.abs() < 0.0005 && target_pitch == 0.0 {
5777 body_pitch = 0.0;
5778 }
5779 let target_fov_boost: f32 = if boost_active {
5780 CAMERA_BOOST_FOV_MAX_DEG
5781 } else if exit_kick_triggered {
5782 CAMERA_BOOST_FOV_MAX_DEG * 0.6
5783 } else if drift_active && post_slip.abs() > 0.18 {
5784 3.2
5785 } else {
5786 0.0
5787 };
5788 let fov_blend: f32 = 1.0 - (-5.5 * sub_dt).exp();
5789 let mut cam_fov_boost: f32 = phys.get_camera_fov_boost()
5790 + (target_fov_boost - phys.get_camera_fov_boost()) * fov_blend;
5791 if cam_fov_boost < 0.02 && target_fov_boost == 0.0 {
5792 cam_fov_boost = 0.0;
5793 }
5794 phys.set_vel(vel);
5795 phys.set_yaw_rate(yaw_rate);
5796 phys.set_body_roll_rad(body_roll);
5797 phys.set_body_pitch_rad(body_pitch);
5798 phys.set_boost_active(boost_active);
5799 phys.set_boost_charge(boost_charge);
5800 phys.set_drift_active(drift_active);
5801 phys.set_drift_slip_angle(post_slip);
5802 phys.set_drift_duration(drift_duration);
5803 phys.set_drift_peak_slip(drift_peak_slip);
5804 phys.set_camera_fov_boost(cam_fov_boost);
5805 phys.set_camera_shake(cam_shake);
5806 {
5807 let Self { player_physics, .. } = self;
5808 *player_physics = phys;
5809 }
5810 let lift_y: f32 = (body_roll.abs() * 0.55 + body_pitch.abs() * 0.95).min(0.06);
5811 let mut visual_tr: Transform3D = Transform3D {
5812 position: Vec3::new(
5813 flat_tr.get_position().get_x(),
5814 lift_y,
5815 flat_tr.get_position().get_z(),
5816 ),
5817 rotation: Quat::from_euler_yxz(final_yaw, body_pitch, body_roll),
5818 scale: flat_tr.get_scale(),
5819 };
5820 if (body_roll != 0.0 || body_pitch != 0.0)
5821 && self
5822 .mesh_oriented_box_static_collision(
5823 visual_tr.to_oriented_box(mesh_bounds),
5824 Some(car_idx),
5825 )
5826 .is_some()
5827 {
5828 visual_tr = flat_tr;
5829 }
5830 let tr_changed: bool = ccd_moved || visual_tr != cur_tr;
5831 if tr_changed {
5832 let world_b: AxisAlignedBox3D = visual_tr.transform_bounds(mesh_bounds);
5833 if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
5834 car_mut.set_transform(visual_tr);
5835 car_mut.set_world_bounds(world_b);
5836 }
5837 player_moved_any = true;
5838 if car_is_dynamic {
5839 any_dynamic_moved = true;
5840 } else {
5841 any_static_moved = true;
5842 }
5843 }
5844 }
5845 let traffic_count: usize = self.traffic_vehicle_count();
5846 for slot_idx in 0..traffic_count {
5847 let mut npc: NpcVehicle3D = {
5848 let Self {
5849 traffic_vehicles, ..
5850 } = self;
5851 traffic_vehicles[slot_idx]
5852 };
5853 let npc_idx: usize = npc.get_object_index();
5854 let Some((cur_tr, mesh_id, is_dynamic)) =
5855 self.get_objects().get(npc_idx).map(|obj: &SceneObject3D| {
5856 (obj.get_transform(), obj.get_mesh_id(), obj.get_is_dynamic())
5857 })
5858 else {
5859 continue;
5860 };
5861 let local_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
5862 let mut tr: Transform3D = Transform3D::new(
5863 Vec3::new(
5864 cur_tr.get_position().get_x(),
5865 0.0,
5866 cur_tr.get_position().get_z(),
5867 ),
5868 cur_tr.get_yaw_rad(),
5869 cur_tr.get_scale(),
5870 );
5871 let obb_npc: OrientedBox3D = tr.to_oriented_box(local_bounds);
5872 let margin: f32 = obb_npc
5873 .get_half_extents()
5874 .get_x()
5875 .max(obb_npc.get_half_extents().get_z());
5876 let pos: Vec3 = tr.get_position();
5877 let yaw: f32 = tr.get_yaw_rad();
5878 let fwd: Vec3 = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
5879 let right: Vec3 = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
5880 let mut vel: Vec3 = npc.get_vel();
5881 let mut yaw_rate: f32 = npc.get_yaw_rate();
5882 let mut recovery: f32 = npc.get_recovery_timer();
5883 if recovery > 0.0 {
5884 recovery = (recovery - sub_dt).max(0.0);
5885 let mut v_fwd: f32 = vel.dot(fwd);
5886 let mut v_lat: f32 = vel.dot(right);
5887 v_fwd *= (-1.15 * sub_dt).exp();
5888 v_lat *= (-2.85 * sub_dt).exp();
5889 vel = fwd.scale(v_fwd).add(right.scale(v_lat));
5890 yaw_rate *= (-2.3 * sub_dt).exp();
5891 if recovery <= 0.0 && yaw_rate.abs() < 0.8 {
5892 let (route_id, wp_idx, wp_pos): (u8, usize, Vec3) =
5893 NpcVehicle3D::nearest_open_waypoint(pos);
5894 npc.set_route_id(route_id);
5895 npc.set_waypoint_idx(wp_idx);
5896 npc.set_nav_target(wp_pos);
5897 }
5898 } else {
5899 let mut v_fwd: f32 = vel.dot(fwd);
5900 let mut v_lat: f32 = vel.dot(right);
5901 let target_pt: Vec3 = if npc.get_free_roam_mode() {
5902 let cur_tgt: Vec3 = npc.get_nav_target();
5903 let to_t: Vec3 = Vec3::new(
5904 cur_tgt.get_x() - pos.get_x(),
5905 0.0,
5906 cur_tgt.get_z() - pos.get_z(),
5907 );
5908 if to_t.length_sq() < 49.0 {
5909 let wps: &[(f32, f32)] =
5910 NpcVehicle3D::route_waypoints(npc.get_route_id());
5911 let next_wp: usize = (npc.get_waypoint_idx() + 1) % wps.len();
5912 let next_pt: Vec3 = Vec3::new(wps[next_wp].0, 0.0, wps[next_wp].1);
5913 npc.set_waypoint_idx(next_wp);
5914 npc.set_nav_target(next_pt);
5915 next_pt
5916 } else {
5917 cur_tgt
5918 }
5919 } else {
5920 let cur_s: f32 = npc.get_loop_arc_s();
5921 let lane_u: f32 = npc.get_loop_lane_u();
5922 let dir: f32 = npc.get_loop_dir();
5923 let (_, base_yaw_at_s): (Vec3, f32) = Self::loop_pose_at(cur_s, lane_u);
5924 let tan_yaw: f32 = if dir >= 0.0 {
5925 base_yaw_at_s
5926 } else {
5927 base_yaw_at_s + PI
5928 };
5929 let tan_dir: Vec3 = Vec3::new(-tan_yaw.sin(), 0.0, -tan_yaw.cos());
5930 let prog: f32 = vel.dot(tan_dir).max(0.0) * sub_dt;
5931 let next_s: f32 = (cur_s + dir * prog).rem_euclid(CITY_LOOP_TOTAL_LENGTH);
5932 npc.set_loop_arc_s(next_s);
5933 let look_s: f32 = (next_s + dir * 11.0).rem_euclid(CITY_LOOP_TOTAL_LENGTH);
5934 let (look_pt, _): (Vec3, f32) = Self::loop_pose_at(look_s, lane_u);
5935 npc.set_nav_target(look_pt);
5936 look_pt
5937 };
5938 let to_target: Vec3 = Vec3::new(
5939 target_pt.get_x() - pos.get_x(),
5940 0.0,
5941 target_pt.get_z() - pos.get_z(),
5942 );
5943 let desired_yaw: f32 = if to_target.length_sq() > 1.0e-4 {
5944 (-to_target.get_x()).atan2(-to_target.get_z())
5945 } else {
5946 yaw
5947 };
5948 let mut yaw_err: f32 = Self::wrap_angle_rad(desired_yaw - yaw);
5949 let mut obstacle_slow: f32 = 1.0;
5950 if npc.get_free_roam_mode() {
5951 let probe_dist: f32 = (v_fwd.abs() * 0.55 + 5.5).clamp(5.0, 11.0);
5952 let probe_tr: Transform3D =
5953 Transform3D::new(pos.add(fwd.scale(probe_dist)), yaw, tr.get_scale());
5954 if self
5955 .mesh_oriented_box_static_collision(
5956 probe_tr.to_oriented_box(local_bounds),
5957 Some(npc_idx),
5958 )
5959 .is_some()
5960 {
5961 let left_yaw: f32 = yaw + 0.55;
5962 let right_yaw: f32 = yaw - 0.55;
5963 let left_fwd: Vec3 = Vec3::new(-left_yaw.sin(), 0.0, -left_yaw.cos());
5964 let right_fwd: Vec3 =
5965 Vec3::new(-right_yaw.sin(), 0.0, -right_yaw.cos());
5966 let left_clear: bool = self
5967 .mesh_oriented_box_static_collision(
5968 Transform3D::new(
5969 pos.add(left_fwd.scale(probe_dist)),
5970 left_yaw,
5971 tr.get_scale(),
5972 )
5973 .to_oriented_box(local_bounds),
5974 Some(npc_idx),
5975 )
5976 .is_none();
5977 let right_clear: bool = self
5978 .mesh_oriented_box_static_collision(
5979 Transform3D::new(
5980 pos.add(right_fwd.scale(probe_dist)),
5981 right_yaw,
5982 tr.get_scale(),
5983 )
5984 .to_oriented_box(local_bounds),
5985 Some(npc_idx),
5986 )
5987 .is_none();
5988 if left_clear && !right_clear {
5989 yaw_err = 0.85;
5990 obstacle_slow = 0.65;
5991 } else if right_clear && !left_clear {
5992 yaw_err = -0.85;
5993 obstacle_slow = 0.65;
5994 } else if left_clear {
5995 yaw_err = if yaw_err >= 0.0 { 0.85 } else { -0.85 };
5996 obstacle_slow = 0.7;
5997 } else {
5998 yaw_err = 1.1;
5999 obstacle_slow = 0.25;
6000 }
6001 }
6002 }
6003 let mut target_speed: f32 = npc.get_cruise_speed() * obstacle_slow;
6004 if let Some(gap_m) =
6005 self.npc_forward_blocking_gap(npc_idx, pos, fwd, right, v_fwd)
6006 {
6007 if gap_m < 9.5 {
6008 target_speed = 0.0;
6009 } else if gap_m < 14.5 {
6010 target_speed *= ((gap_m - 9.5) / 5.0).clamp(0.0, 1.0);
6011 }
6012 }
6013 let speed_diff: f32 = target_speed - v_fwd;
6014 let accel_rate: f32 = if speed_diff < 0.0 { 36.0 } else { 18.0 };
6015 v_fwd += speed_diff.clamp(-accel_rate * sub_dt, accel_rate * sub_dt);
6016 if target_speed <= 0.05 && v_fwd.abs() < 0.15 {
6017 v_fwd = 0.0;
6018 }
6019 v_lat *= (-8.5 * sub_dt).exp();
6020 let target_omega: f32 = (yaw_err * 3.8).clamp(-2.6, 2.6);
6021 let omega_blend: f32 = 1.0 - (-12.0 * sub_dt).exp();
6022 yaw_rate += (target_omega - yaw_rate) * omega_blend;
6023 if v_fwd.abs() < 0.1 {
6024 yaw_rate *= (-8.0 * sub_dt).exp();
6025 }
6026 vel = fwd.scale(v_fwd).add(right.scale(v_lat));
6027 }
6028 let (npc_moved, npc_wall_imp, npc_wall_cp, npc_wall_n): (bool, f32, Vec3, Vec3) =
6029 self.step_rigid_vehicle_static_ccd(
6030 &mut tr,
6031 &mut vel,
6032 &mut yaw_rate,
6033 (
6034 1.0 / npc.get_mass().max(100.0),
6035 1.0 / VEHICLE_NPC_INERTIA_YAW,
6036 ),
6037 (npc_idx, local_bounds),
6038 VehicleCcdStepCtx3D {
6039 sub_dt,
6040 ground_limits,
6041 ground_margin: margin,
6042 },
6043 );
6044 if npc_wall_imp > 3.5 {
6045 let spark_int: f32 = ((npc_wall_imp - 2.5) / 22.0).clamp(0.15, 0.9);
6046 self.emit_collision_sparks(npc_wall_cp, npc_wall_n, spark_int);
6047 if npc.get_free_roam_mode() && recovery <= 0.0 {
6048 let wps: &[(f32, f32)] = NpcVehicle3D::route_waypoints(npc.get_route_id());
6049 let next_wp: usize = (npc.get_waypoint_idx() + 1) % wps.len();
6050 npc.set_waypoint_idx(next_wp);
6051 npc.set_nav_target(Vec3::new(wps[next_wp].0, 0.0, wps[next_wp].1));
6052 }
6053 }
6054 npc.set_vel(vel);
6055 npc.set_yaw_rate(yaw_rate);
6056 npc.set_recovery_timer(recovery);
6057 {
6058 let Self {
6059 traffic_vehicles, ..
6060 } = self;
6061 traffic_vehicles[slot_idx] = npc;
6062 }
6063 if npc_moved {
6064 let world_b: AxisAlignedBox3D = tr.transform_bounds(local_bounds);
6065 if let Some(obj) = self.get_mut_objects().get_mut(npc_idx) {
6066 obj.set_transform(tr);
6067 obj.set_world_bounds(world_b);
6068 }
6069 if is_dynamic {
6070 any_dynamic_moved = true;
6071 } else {
6072 any_static_moved = true;
6073 }
6074 }
6075 }
6076 let (dyn_moved, dyn_imp, _dyn_cp, _dyn_n): (bool, f32, Vec3, Vec3) =
6077 self.resolve_dynamic_vehicle_collisions(ground_limits);
6078 if dyn_moved {
6079 any_dynamic_moved = true;
6080 player_moved_any = true;
6081 }
6082 if dyn_imp > 2.5 {
6083 let imp_norm: f32 = ((dyn_imp - 2.0) / 24.0).clamp(0.0, 1.0);
6084 let Self { player_physics, .. } = self;
6085 let next_shake: f32 = player_physics.get_camera_shake().max(imp_norm * 0.70);
6086 player_physics.set_camera_shake(next_shake);
6087 }
6088 }
6089 if let Some(car_idx) = car_opt
6090 && let Some((car_tr, mesh_id)) = self
6091 .get_objects()
6092 .get(car_idx)
6093 .map(|car: &SceneObject3D| (car.get_transform(), car.get_mesh_id()))
6094 {
6095 let car_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
6096 let mut safe_tr: Transform3D = car_tr;
6097 let car_obb: OrientedBox3D = safe_tr.to_oriented_box(car_bounds);
6098 let car_margin: f32 = car_obb
6099 .get_half_extents()
6100 .get_x()
6101 .max(car_obb.get_half_extents().get_z());
6102 if self.depenetrate_vehicle_horizontally(
6103 &mut safe_tr,
6104 car_bounds,
6105 car_idx,
6106 ground_limits,
6107 car_margin,
6108 ) {
6109 let wb: AxisAlignedBox3D = safe_tr.transform_bounds(car_bounds);
6110 if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
6111 car_mut.set_transform(safe_tr);
6112 car_mut.set_world_bounds(wb);
6113 }
6114 player_moved_any = true;
6115 any_dynamic_moved = true;
6116 }
6117 let final_car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
6118 let car_pos: Vec3 = final_car_tr.get_position();
6119 let yaw: f32 = final_car_tr.get_yaw_rad();
6120 let car_fwd: Vec3 = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
6121 let car_right: Vec3 = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
6122 let phys: PlayerVehiclePhysics3D = {
6123 let Self { player_physics, .. } = self;
6124 *player_physics
6125 };
6126 if player_moved_any || phys.get_boost_active() || phys.get_drift_active() {
6127 let beam_dir: Vec3 = Vec3::new(car_fwd.get_x(), -0.14, car_fwd.get_z()).normalize();
6128 if self.get_spot_lights().len() >= 2 {
6129 let front_center: Vec3 = car_pos
6130 .add(car_fwd.scale(2.2))
6131 .add(Vec3::new(0.0, 0.95, 0.0));
6132 let left_pos: Vec3 = front_center.sub(car_right.scale(0.85));
6133 let right_pos: Vec3 = front_center.add(car_right.scale(0.85));
6134 let spots: &mut Vec<SpotLight3D> = self.get_mut_spot_lights();
6135 spots[0].set_position(left_pos);
6136 spots[0].set_direction(beam_dir);
6137 spots[1].set_position(right_pos);
6138 spots[1].set_direction(beam_dir);
6139 }
6140 if let Some(tail_light) = self.get_mut_point_lights().first_mut()
6141 && tail_light.get_color().get_x() > 0.90
6142 && tail_light.get_color().get_y() < 0.15
6143 {
6144 let rear_pos: Vec3 = car_pos
6145 .sub(car_fwd.scale(2.9))
6146 .add(Vec3::new(0.0, 0.95, 0.0));
6147 tail_light.set_position(rear_pos);
6148 if phys.get_boost_active() {
6149 tail_light.set_color(Vec3::new(1.0, 0.14, 0.06));
6150 tail_light.set_intensity(4.5);
6151 tail_light.set_radius(10.5);
6152 } else if phys.get_drift_active() || throttle < -0.15 {
6153 tail_light.set_color(Vec3::new(1.0, 0.06, 0.18));
6154 tail_light.set_intensity(3.85);
6155 tail_light.set_radius(9.6);
6156 } else {
6157 tail_light.set_color(Vec3::new(1.0, 0.09, 0.27));
6158 tail_light.set_intensity(1.85);
6159 tail_light.set_radius(8.5);
6160 }
6161 }
6162 if phys.get_boost_active() && (sim_tick & 1) == 0 {
6163 self.emit_boost_flame(car_pos, car_fwd, car_right, phys.get_vel());
6164 }
6165 if phys.get_drift_active()
6166 && phys.get_drift_slip_angle().abs() > 0.12
6167 && (sim_tick & 1) == 0
6168 {
6169 self.emit_drift_smoke(
6170 car_pos,
6171 car_fwd,
6172 car_right,
6173 phys.get_drift_slip_angle().abs(),
6174 );
6175 } else if throttle.abs() > 0.25
6176 && !phys.get_boost_active()
6177 && (sim_tick & 3) == 0
6178 && self.get_niagara().get_active_count() < 24
6179 {
6180 let exhaust_pos: Vec3 = car_pos
6181 .sub(car_fwd.scale(2.3))
6182 .add(Vec3::new(0.0, 0.42, 0.0));
6183 let mut spark_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6184 spark_cfg.set_origin(exhaust_pos);
6185 spark_cfg.set_base_velocity(car_fwd.scale(-4.5).add(Vec3::new(0.0, 1.1, 0.0)));
6186 spark_cfg.set_start_size_m(0.11);
6187 spark_cfg.set_end_size_m(0.03);
6188 self.get_mut_niagara().emit_burst(1, &spark_cfg);
6189 }
6190 }
6191 let cam_mode: u8 = self.get_camera_mode();
6192 let fov_boost: f32 = phys.get_camera_fov_boost();
6193 let chase_pullback: f32 = fov_boost * 0.14;
6194 let reverse_speed_mps: f32 = -phys.get_vel().dot(car_fwd);
6195 let reverse_blend: f32 = ((reverse_speed_mps - 0.5) / 8.0).clamp(0.0, 1.0);
6196 let (mut desired_eye, look_target): (Vec3, Vec3) = match cam_mode {
6197 1 => {
6198 let eye: Vec3 = Vec3::new(
6199 car_pos.get_x() - yaw.sin() * 1.4,
6200 2.15,
6201 car_pos.get_z() - yaw.cos() * 1.4,
6202 );
6203 let tgt: Vec3 = Vec3::new(
6204 car_pos.get_x() - yaw.sin() * 18.0,
6205 1.8,
6206 car_pos.get_z() - yaw.cos() * 18.0,
6207 );
6208 (eye, tgt)
6209 }
6210 2 => {
6211 let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.45;
6212 self.set_camera_orbit_rad(orbit);
6213 let eye: Vec3 = Vec3::new(
6214 car_pos.get_x() + orbit.sin() * 10.5,
6215 5.2,
6216 car_pos.get_z() + orbit.cos() * 10.5,
6217 );
6218 (eye, Vec3::new(car_pos.get_x(), 1.6, car_pos.get_z()))
6219 }
6220 3 => {
6221 let eye: Vec3 = Vec3::new(
6222 car_pos.get_x() + yaw.sin() * 18.0,
6223 18.5,
6224 car_pos.get_z() + yaw.cos() * 18.0,
6225 );
6226 (eye, Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()))
6227 }
6228 4 => {
6229 let cur_cam: Camera3D = self.get_camera();
6230 let fwd_c: Vec3 = cur_cam.forward();
6231 let right_c: Vec3 = cur_cam.right();
6232 let moved: Vec3 = cur_cam
6233 .get_position()
6234 .add(fwd_c.scale(throttle * 18.0 * dt))
6235 .add(right_c.scale(steer * 14.0 * dt));
6236 let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
6237 (eye, eye.add(fwd_c.scale(16.0)))
6238 }
6239 5 => {
6240 let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
6241 self.set_camera_orbit_rad(orbit);
6242 let eye: Vec3 = Vec3::new(
6243 car_pos.get_x() + orbit.sin() * 7.8,
6244 3.6 + (orbit * 1.5).sin() * 1.4,
6245 car_pos.get_z() + orbit.cos() * 13.5,
6246 );
6247 (eye, Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0))
6248 }
6249 _ => {
6250 let chase_dist: f32 = 9.8 + chase_pullback + reverse_blend * 2.4;
6251 let eye: Vec3 = Vec3::new(
6252 car_pos.get_x() + yaw.sin() * chase_dist,
6253 4.25 + chase_pullback * 0.12 + reverse_blend * 0.55,
6254 car_pos.get_z() + yaw.cos() * chase_dist,
6255 );
6256 let tgt: Vec3 = Vec3::new(
6257 car_pos.get_x() - yaw.sin() * 16.0,
6258 2.40 - reverse_blend * 0.65,
6259 car_pos.get_z() - yaw.cos() * 16.0,
6260 );
6261 (eye, tgt)
6262 }
6263 };
6264 let shake_amp: f32 = phys.get_camera_shake();
6265 if shake_amp > 0.005 {
6266 let phase: f32 = self.get_world_time_secs() * 54.0;
6267 let sx: f32 = phase.sin() * shake_amp * 0.34;
6268 let sy: f32 = (phase * 1.37).cos() * shake_amp * 0.22;
6269 desired_eye = desired_eye
6270 .add(car_right.scale(sx))
6271 .add(Vec3::new(0.0, sy, 0.0));
6272 }
6273 let boom_anchor: Vec3 =
6274 Vec3::new(car_pos.get_x(), car_pos.get_y() + 1.8, car_pos.get_z());
6275 let boom_vec: Vec3 = desired_eye.sub(boom_anchor);
6276 let boom_len: f32 = boom_vec.length();
6277 if boom_len > 0.25 {
6278 let boom_dir: Vec3 = boom_vec.scale(1.0 / boom_len);
6279 if let Some(hit) =
6280 self.raycast_solid_meshes(boom_anchor, boom_dir, boom_len, Some(car_idx))
6281 {
6282 let safe_dist: f32 = (hit.get_distance() - 0.55).max(0.8);
6283 desired_eye = boom_anchor.add(boom_dir.scale(safe_dist));
6284 }
6285 }
6286 let cam_probe: OrientedBox3D = OrientedBox3D::from_bounds(AxisAlignedBox3D::new(
6287 desired_eye.sub(Vec3::splat(0.45)),
6288 desired_eye.add(Vec3::splat(0.45)),
6289 ));
6290 if let Some(hit) = self.mesh_oriented_box_collision(cam_probe, Some(car_idx)) {
6291 desired_eye = desired_eye.add(hit.get_normal().scale(hit.get_penetration() + 0.1));
6292 }
6293 let prev_cam: Camera3D = self.get_camera();
6294 let mut cam: Camera3D = prev_cam;
6295 let follow_rate: f32 = 7.0 + reverse_blend * 5.0;
6296 let smooth: f32 = (dt * follow_rate).clamp(0.05, 1.0);
6297 cam.set_position(cam.get_position().lerp(desired_eye, smooth));
6298 let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
6299 cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
6300 cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
6301 cam.set_fov_deg(CAMERA_BASE_FOV_DEG + fov_boost);
6302 self.set_camera(cam);
6303 if cam != prev_cam {
6304 self.bump_world_revision();
6305 }
6306 }
6307 let Self {
6308 objects,
6309 mesh_library,
6310 ..
6311 } = self;
6312 for obj in objects.iter_mut() {
6313 let spin: f32 = obj.get_spin_speed();
6314 if spin.abs() > 0.001 {
6315 let mut object_transform: Transform3D = obj.get_transform();
6316 object_transform.set_yaw_rad(object_transform.get_yaw_rad() + spin * dt);
6317 obj.set_transform(object_transform);
6318 let local_bounds: AxisAlignedBox3D = mesh_library
6319 .get(obj.get_mesh_id())
6320 .and_then(|color_item: &MeshLodChain| color_item.get_levels().first())
6321 .map(Mesh3D::get_bounds)
6322 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
6323 obj.set_world_bounds(object_transform.transform_bounds(local_bounds));
6324 if obj.get_is_dynamic() {
6325 any_dynamic_moved = true;
6326 } else {
6327 any_static_moved = true;
6328 }
6329 }
6330 }
6331 if self.get_atmosphere_preset() == 1
6332 && (sim_tick & 1) == 0
6333 && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES
6334 {
6335 let cam_pos: Vec3 = self.get_camera().get_position();
6336 let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6337 rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 5.0, -14.0)));
6338 rain_cfg.set_base_velocity(Vec3::new(-0.5, -15.5, 0.3));
6339 rain_cfg.set_velocity_spread(3.6);
6340 rain_cfg.set_start_color(Color::rgba(150, 218, 255, 210));
6341 rain_cfg.set_end_color(Color::rgba(68, 152, 240, 60));
6342 rain_cfg.set_start_size_m(0.07);
6343 rain_cfg.set_end_size_m(0.03);
6344 rain_cfg.set_min_lifetime(0.6);
6345 rain_cfg.set_max_lifetime(0.95);
6346 rain_cfg.set_emissive_boost(1.4);
6347 self.get_mut_niagara().emit_burst(2, &rain_cfg);
6348 }
6349 if self.get_niagara().get_active_count() > 0 {
6350 let _: usize = self.get_mut_niagara().update(dt, 0.0);
6351 }
6352 if !self.get_animation_mixer().get_layers().is_empty() {
6353 let anim_updates: usize = self.tick_animations(dt);
6354 if anim_updates > 0 {
6355 any_dynamic_moved = true;
6356 }
6357 }
6358 if any_static_moved {
6359 self.set_bvh_dirty(true);
6360 }
6361 if any_dynamic_moved {
6362 self.set_dynamic_bvh_dirty(true);
6363 }
6364 if any_static_moved || any_dynamic_moved {
6365 self.bump_world_revision();
6366 }
6367 }
6368
6369 #[must_use]
6375 pub fn environment_ibl(&self) -> Option<&EnvironmentIbl3D> {
6376 let Self {
6377 environment_ibl, ..
6378 } = self;
6379 environment_ibl.as_ref()
6380 }
6381
6382 pub fn set_environment_ibl(&mut self, ibl: Option<EnvironmentIbl3D>) {
6389 let Self {
6390 environment_ibl, ..
6391 } = self;
6392 *environment_ibl = ibl;
6393 self.bump_world_revision();
6394 }
6395
6396 #[must_use]
6402 pub fn active_scene_camera_index(&self) -> Option<usize> {
6403 let Self {
6404 active_scene_camera,
6405 ..
6406 } = self;
6407 *active_scene_camera
6408 }
6409
6410 pub fn set_active_scene_camera(&mut self, camera_index: Option<usize>) -> bool {
6421 let cam_count: usize = self.get_scene_cameras().len();
6422 if let Some(target_idx) = camera_index
6423 && target_idx >= cam_count
6424 {
6425 return false;
6426 }
6427 let Self {
6428 active_scene_camera,
6429 ..
6430 } = self;
6431 *active_scene_camera = camera_index;
6432 if let Some(target_idx) = camera_index
6433 && let Some(scene_cam) = self.get_scene_cameras().get(target_idx).cloned()
6434 {
6435 self.set_camera(scene_cam.to_camera3d());
6436 }
6437 self.bump_world_revision();
6438 true
6439 }
6440
6441 #[must_use]
6452 pub fn active_view_projection(&self, viewport_aspect: f32) -> Mat4 {
6453 if let Some(cam_idx) = self.active_scene_camera_index()
6454 && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
6455 {
6456 return scene_cam.view_projection(viewport_aspect);
6457 }
6458 self.get_camera().view_projection(viewport_aspect)
6459 }
6460
6461 #[must_use]
6472 pub fn deformed_mesh_for_object(&self, obj_idx: usize) -> Option<&Mesh3D> {
6473 let Self {
6474 deformed_meshes, ..
6475 } = self;
6476 deformed_meshes.get(obj_idx).and_then(Option::as_ref)
6477 }
6478
6479 #[must_use]
6490 pub fn is_object_visible(&self, obj_idx: usize) -> bool {
6491 let Some(obj) = self.get_objects().get(obj_idx) else {
6492 return false;
6493 };
6494 if let Some(node_id) = obj.try_get_node_id() {
6495 return self.get_scene_graph().is_node_effectively_visible(node_id);
6496 }
6497 true
6498 }
6499
6500 pub fn set_skinning_mode(&mut self, skin_idx: usize, mode: SkinningMode) -> bool {
6512 let Some(skin) = self.get_mut_skins().get_mut(skin_idx) else {
6513 return false;
6514 };
6515 skin.set_skinning_mode(mode);
6516 let _: usize = self.update_deformed_meshes();
6517 self.bump_world_revision();
6518 true
6519 }
6520
6521 pub fn set_collection_visible(&mut self, collection_name: &str, visible: bool) -> bool {
6533 let updated: bool = self
6534 .get_mut_scene_graph()
6535 .get_mut_collections()
6536 .set_collection_visible(collection_name, visible);
6537 if updated {
6538 self.bump_world_revision();
6539 }
6540 updated
6541 }
6542
6543 pub fn load_imported_scene(&mut self, scene: &ImportedScene3D) -> Vec<usize> {
6554 let texture_base: u32 = self.get_textures().len() as u32;
6555 self.get_mut_textures()
6556 .extend(scene.get_textures().iter().cloned());
6557 let material_base: u32 = self.get_principled_materials().len() as u32;
6558 for raw_mat in scene.get_materials().iter() {
6559 let mut rebased: PrincipledMaterial3D = raw_mat.clone();
6560 Self::rebase_material_textures(&mut rebased, texture_base);
6561 self.get_mut_principled_materials().push(rebased);
6562 }
6563 let mesh_base: usize = self.get_mesh_library().len();
6564 for raw_mesh in scene.get_meshes().iter() {
6565 let mut mesh_copy: Mesh3D = raw_mesh.clone();
6566 if let Some(local_mat_id) = mesh_copy.try_get_material_index() {
6567 mesh_copy.set_material_index(Some(local_mat_id.saturating_add(material_base)));
6568 }
6569 let lod_chain: MeshLodChain = if mesh_copy.get_indices().len() > 24 {
6570 build_qem_lod_chain(&mesh_copy, 3)
6571 } else {
6572 MeshLodChain::from_mesh(mesh_copy)
6573 };
6574 let _: usize = self.register_mesh(lod_chain);
6575 }
6576 let node_base: u32 = self.get_scene_graph().get_nodes().len() as u32;
6577 let skin_base: u32 = self.get_skins().len() as u32;
6578 let mut collection_bit_remap: Vec<u64> = Vec::new();
6579 for coll_entry in scene
6580 .get_scene_graph()
6581 .get_collections()
6582 .get_entries()
6583 .iter()
6584 {
6585 let mask_val: u64 = self
6586 .get_mut_scene_graph()
6587 .get_mut_collections()
6588 .register_collection(coll_entry.get_name());
6589 if !coll_entry.get_visible_viewport() {
6590 let _: bool = self
6591 .get_mut_scene_graph()
6592 .get_mut_collections()
6593 .set_collection_visible(coll_entry.get_name(), false);
6594 }
6595 collection_bit_remap.push(mask_val);
6596 }
6597 let src_graph: &SceneGraph3D = scene.get_scene_graph();
6598 let src_nodes: &[SceneNode3D] = src_graph.get_nodes().as_slice();
6599 for (src_idx, src_node) in src_nodes.iter().enumerate() {
6600 let rebased_parent: Option<u32> = src_node
6601 .try_get_parent()
6602 .map(|parent_idx: u32| parent_idx.saturating_add(node_base));
6603 let node_label: &str = if src_node.get_name().is_empty() {
6604 BLENDER_IMPORTED_NODE_FALLBACK
6605 } else {
6606 src_node.get_name().as_str()
6607 };
6608 let mut dst_node: SceneNode3D = SceneNode3D::from_name(node_label, rebased_parent);
6609 dst_node.set_local_translation(src_node.get_local_translation());
6610 dst_node.set_local_rotation(src_node.get_local_rotation());
6611 dst_node.set_local_scale(src_node.get_local_scale());
6612 dst_node.set_visible(src_node.get_visible());
6613 dst_node.set_extras(src_node.get_extras().clone());
6614 let mut mapped_mask: u64 = 0;
6615 let raw_mask: u64 = src_node.get_collection_mask();
6616 for (bit_pos, &dst_bit) in collection_bit_remap.iter().enumerate() {
6617 if (raw_mask & (1_u64 << (bit_pos as u32))) != 0 {
6618 mapped_mask |= dst_bit;
6619 }
6620 }
6621 dst_node.set_collection_mask(if mapped_mask == 0 { 1 } else { mapped_mask });
6622 if let Some(src_mesh_id) = src_node.try_get_mesh_id() {
6623 dst_node.set_mesh_id(Some((mesh_base as u32).saturating_add(src_mesh_id)));
6624 }
6625 if let Some(src_skin_id) = src_node.try_get_skin_id() {
6626 dst_node.set_skin_id(Some(skin_base.saturating_add(src_skin_id)));
6627 }
6628 dst_node.set_camera_id(src_node.try_get_camera_id());
6629 dst_node.set_light_id(src_node.try_get_light_id());
6630 let dst_node_id: u32 = self.get_mut_scene_graph().add_node(dst_node);
6631 let src_weights: &[f32] = src_graph.morph_weights_for_node(src_idx as u32);
6632 if !src_weights.is_empty() {
6633 self.get_mut_scene_graph()
6634 .attach_morph_weights(dst_node_id, src_weights);
6635 }
6636 let Self {
6637 node_object_map, ..
6638 } = self;
6639 node_object_map.push(None);
6640 }
6641 let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
6642 for src_skin in scene.get_skins().iter() {
6643 let mut runtime_skin: Skin3D = Skin3D::from_imported(src_skin);
6644 for joint_node in runtime_skin.get_mut_joints().iter_mut() {
6645 *joint_node = joint_node.saturating_add(node_base);
6646 }
6647 if let Some(root_idx) = runtime_skin.try_get_skeleton_root() {
6648 runtime_skin.set_skeleton_root(Some(root_idx.saturating_add(node_base)));
6649 }
6650 self.get_mut_skins().push(runtime_skin);
6651 }
6652 let mut first_clip_added: Option<usize> = None;
6653 for src_clip in scene.get_animations().iter() {
6654 let mut rebased_clip: ImportedAnimationClip3D = src_clip.clone();
6655 for chan in rebased_clip.get_mut_channels().iter_mut() {
6656 chan.set_target_node(chan.get_target_node().saturating_add(node_base));
6657 }
6658 let clip_idx: usize = self.get_mut_animation_mixer().add_clip(rebased_clip);
6659 if first_clip_added.is_none() {
6660 first_clip_added = Some(clip_idx);
6661 }
6662 }
6663 let graph_snapshot: SceneGraph3D = self.get_scene_graph().clone();
6664 self.get_mut_animation_mixer()
6665 .capture_rest_pose(&graph_snapshot);
6666 if let Some(clip_idx) = first_clip_added
6667 && self.get_animation_mixer().get_layers().is_empty()
6668 {
6669 let _: usize = self
6670 .get_mut_animation_mixer()
6671 .push_layer(NlaLayer3D::new(clip_idx));
6672 }
6673 let mut spawned_objects: Vec<usize> = Vec::new();
6674 let total_nodes: usize = self.get_scene_graph().get_nodes().len();
6675 for node_idx in (node_base as usize)..total_nodes {
6676 let node_copy: SceneNode3D = self.get_scene_graph().get_nodes()[node_idx].clone();
6677 let world_mat: Mat4 = node_copy.get_world_matrix();
6678 let world_tr: Transform3D = Transform3D::from_matrix(world_mat);
6679 if let Some(global_mesh_id) = node_copy.try_get_mesh_id() {
6680 let mesh_usize: usize = global_mesh_id as usize;
6681 let principled_id: Option<u32> = self
6682 .get_mesh_library()
6683 .get(mesh_usize)
6684 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
6685 .and_then(|mesh_ref: &Mesh3D| mesh_ref.try_get_material_index());
6686 let legacy_mat: PbrMaterial = principled_id
6687 .and_then(|mat_idx: u32| self.get_principled_materials().get(mat_idx as usize))
6688 .map_or_else(
6689 || {
6690 self.get_mesh_library()
6691 .get(mesh_usize)
6692 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
6693 .map_or_else(PbrMaterial::default, Mesh3D::get_material)
6694 },
6695 PrincipledMaterial3D::to_legacy_pbr,
6696 );
6697 let cast_shadows: bool = node_copy.get_extras().get_cast_shadows();
6698 let obj_idx: usize = self.spawn_object(
6699 node_copy.get_name(),
6700 mesh_usize,
6701 world_tr,
6702 legacy_mat,
6703 cast_shadows,
6704 );
6705 let skin_opt: Option<u32> = node_copy.try_get_skin_id();
6706 let is_deformable: bool =
6707 skin_opt.is_some() || node_copy.get_morph_weight_count() > 0;
6708 if let Some(obj_mut) = self.get_mut_objects().get_mut(obj_idx) {
6709 obj_mut.set_node_id(Some(node_idx as u32));
6710 obj_mut.set_principled_material_id(principled_id);
6711 obj_mut.set_skin_id(skin_opt);
6712 }
6713 if is_deformable {
6714 let _: bool = self.set_object_dynamic(obj_idx, true);
6715 }
6716 let Self {
6717 node_object_map, ..
6718 } = self;
6719 if let Some(slot) = node_object_map.get_mut(node_idx) {
6720 *slot = Some(obj_idx);
6721 }
6722 spawned_objects.push(obj_idx);
6723 }
6724 if let Some(src_cam_id) = node_copy.try_get_camera_id()
6725 && let Some(imp_cam) = scene.get_cameras().get(src_cam_id as usize)
6726 {
6727 self.get_mut_scene_cameras()
6728 .push(SceneCamera3D::from_imported(
6729 imp_cam,
6730 Some(node_idx as u32),
6731 world_tr.get_position(),
6732 world_tr.get_rotation(),
6733 ));
6734 }
6735 if let Some(src_light_id) = node_copy.try_get_light_id()
6736 && let Some(imp_light) = scene.get_lights().get(src_light_id as usize)
6737 {
6738 let emit_dir: Vec3 = world_tr
6739 .get_rotation()
6740 .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
6741 .normalize();
6742 let light_color: Vec3 = imp_light.get_color();
6743 let light_intensity: f32 = imp_light.get_intensity();
6744 match imp_light.get_kind() {
6745 GltfLightKind::Directional => {
6746 let mut sun_val: DirectionalLight3D = self.get_sun();
6747 sun_val.set_direction(emit_dir.scale(-1.0).normalize());
6748 sun_val.set_color(light_color.scale(light_intensity.max(0.05)));
6749 self.set_sun(sun_val);
6750 }
6751 GltfLightKind::Point { range } => {
6752 let resolved_range: f32 = range.unwrap_or(24.0).max(0.5);
6753 self.get_mut_point_lights().push(PointLight3D::from_linear(
6754 world_tr.get_position(),
6755 light_color,
6756 light_intensity,
6757 resolved_range,
6758 ));
6759 }
6760 GltfLightKind::Spot {
6761 range,
6762 inner_cone_angle,
6763 outer_cone_angle,
6764 } => {
6765 let resolved_range: f32 = range.unwrap_or(32.0).max(0.5);
6766 self.get_mut_spot_lights().push(SpotLight3D::from_linear(
6767 world_tr.get_position(),
6768 emit_dir,
6769 light_color,
6770 light_intensity,
6771 resolved_range,
6772 (inner_cone_angle, outer_cone_angle),
6773 ));
6774 }
6775 GltfLightKind::Area { width, height } => {
6776 self.get_mut_area_lights().push(AreaLight3D::new_rect(
6777 world_tr.get_position(),
6778 emit_dir,
6779 light_color,
6780 light_intensity,
6781 (width, height),
6782 28.0,
6783 ));
6784 }
6785 }
6786 }
6787 }
6788 let _: usize = self.update_deformed_meshes();
6789 if self.environment_ibl().is_none() {
6790 let sun_ref: DirectionalLight3D = self.get_sun();
6791 let baked_ibl: EnvironmentIbl3D = EnvironmentIbl3D::from_procedural_sky(
6792 &sun_ref,
6793 WORLD_DEFAULT_IBL_OCT_SIZE,
6794 WORLD_DEFAULT_IBL_LUT_SIZE,
6795 );
6796 self.set_environment_ibl(Some(baked_ibl));
6797 }
6798 self.set_use_agx_tonemap(true);
6799 self.set_imported_model_count(self.get_imported_model_count().saturating_add(1));
6800 self.set_bvh_dirty(true);
6801 self.set_dynamic_bvh_dirty(true);
6802 self.set_dynamic_topology_dirty(true);
6803 self.bump_world_revision();
6804 spawned_objects
6805 }
6806
6807 pub fn load_glb_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
6818 let imported: ImportedScene3D = parse_gltf_or_glb_bytes(bytes, None)?;
6819 Ok(self.load_imported_scene(&imported))
6820 }
6821
6822 pub fn load_blend_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
6832 let imported: ImportedScene3D = parse_blend_bytes(bytes)?;
6833 Ok(self.load_imported_scene(&imported))
6834 }
6835
6836 pub fn load_euv3d_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
6846 let bundle: BakedAssetBundle3D = Euv3dPackage::decode_any_bytes(bytes)?;
6847 Ok(self.load_imported_scene(bundle.get_scene()))
6848 }
6849
6850 #[must_use]
6865 fn intersect_mesh_triangles_local(
6866 mesh: &Mesh3D,
6867 local_origin: Vec3,
6868 local_dir: Vec3,
6869 local_inv_dir: Vec3,
6870 t_min: f32,
6871 best_t: f32,
6872 ) -> Option<(f32, Vec3)> {
6873 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
6874 let tris: &[[u32; 3]] = mesh.get_indices().as_slice();
6875 if verts.is_empty() || tris.is_empty() {
6876 return None;
6877 }
6878 let mut closest_t: f32 = best_t;
6879 let mut closest_normal: Vec3 = Vec3::zero();
6880 let mut hit_any: bool = false;
6881 let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
6882 if !meshlets.is_empty() {
6883 for meshlet in meshlets.iter() {
6884 let mbox: AxisAlignedBox3D = meshlet.get_bounds();
6885 let box_t: f32 =
6886 mbox.intersect_ray_near(local_origin, local_inv_dir, t_min, closest_t);
6887 if box_t >= closest_t {
6888 continue;
6889 }
6890 let start: usize = meshlet.get_first_tri() as usize;
6891 let end: usize = start
6892 .saturating_add(meshlet.get_tri_count() as usize)
6893 .min(tris.len());
6894 for tri in &tris[start..end] {
6895 let (i0, i1, i2): (usize, usize, usize) =
6896 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
6897 if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
6898 continue;
6899 }
6900 let v0: Vec3 = verts[i0].get_position();
6901 let e1: Vec3 = verts[i1].get_position().sub(v0);
6902 let e2: Vec3 = verts[i2].get_position().sub(v0);
6903 let h: Vec3 = local_dir.cross(e2);
6904 let a: f32 = e1.dot(h);
6905 if a.abs() < 1e-7 {
6906 continue;
6907 }
6908 let inv_a: f32 = 1.0 / a;
6909 let s: Vec3 = local_origin.sub(v0);
6910 let u: f32 = inv_a * s.dot(h);
6911 if !(0.0..=1.0).contains(&u) {
6912 continue;
6913 }
6914 let q: Vec3 = s.cross(e1);
6915 let v: f32 = inv_a * local_dir.dot(q);
6916 if v < 0.0 || (u + v) > 1.0 {
6917 continue;
6918 }
6919 let t: f32 = inv_a * e2.dot(q);
6920 if t >= t_min && t < closest_t {
6921 closest_t = t;
6922 closest_normal = e1.cross(e2).normalize();
6923 hit_any = true;
6924 }
6925 }
6926 }
6927 } else {
6928 for tri in tris.iter() {
6929 let (i0, i1, i2): (usize, usize, usize) =
6930 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
6931 if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
6932 continue;
6933 }
6934 let v0: Vec3 = verts[i0].get_position();
6935 let e1: Vec3 = verts[i1].get_position().sub(v0);
6936 let e2: Vec3 = verts[i2].get_position().sub(v0);
6937 let h: Vec3 = local_dir.cross(e2);
6938 let a: f32 = e1.dot(h);
6939 if a.abs() < 1e-7 {
6940 continue;
6941 }
6942 let inv_a: f32 = 1.0 / a;
6943 let s: Vec3 = local_origin.sub(v0);
6944 let u: f32 = inv_a * s.dot(h);
6945 if !(0.0..=1.0).contains(&u) {
6946 continue;
6947 }
6948 let q: Vec3 = s.cross(e1);
6949 let v: f32 = inv_a * local_dir.dot(q);
6950 if v < 0.0 || (u + v) > 1.0 {
6951 continue;
6952 }
6953 let t: f32 = inv_a * e2.dot(q);
6954 if t >= t_min && t < closest_t {
6955 closest_t = t;
6956 closest_normal = e1.cross(e2).normalize();
6957 hit_any = true;
6958 }
6959 }
6960 }
6961 if hit_any {
6962 Some((closest_t, closest_normal))
6963 } else {
6964 None
6965 }
6966 }
6967
6968 #[must_use]
6980 pub fn pick_object_ray(
6981 &self,
6982 screen_u: f32,
6983 screen_v: f32,
6984 aspect: f32,
6985 ) -> Option<ScenePickHit3D> {
6986 let safe_aspect: f32 = if aspect.is_finite() && aspect > 0.05 {
6987 aspect
6988 } else {
6989 1.0
6990 };
6991 let ndc_x: f32 = screen_u.clamp(0.0, 1.0) * 2.0 - 1.0;
6992 let ndc_y: f32 = 1.0 - screen_v.clamp(0.0, 1.0) * 2.0;
6993 let (origin, ray_dir, t_min, mut best_t): (Vec3, Vec3, f32, f32) = if let Some(cam_idx) =
6994 self.active_scene_camera_index()
6995 && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
6996 {
6997 let fwd: Vec3 = scene_cam.forward();
6998 let right: Vec3 = scene_cam.right();
6999 let up: Vec3 = scene_cam.up();
7000 match scene_cam.get_projection() {
7001 GltfCameraProjection::Orthographic {
7002 xmag,
7003 ymag,
7004 znear,
7005 zfar,
7006 } => {
7007 let o: Vec3 = scene_cam
7008 .get_position()
7009 .add(right.scale(ndc_x * xmag))
7010 .add(up.scale(ndc_y * ymag));
7011 (o, fwd, znear.max(0.01), zfar.max(znear + 1.0))
7012 }
7013 GltfCameraProjection::Perspective {
7014 yfov_rad,
7015 aspect_ratio,
7016 znear,
7017 zfar,
7018 } => {
7019 let cam_aspect: f32 = aspect_ratio.unwrap_or(safe_aspect).max(0.05);
7020 let half_tan_y: f32 = (yfov_rad.clamp(0.15, 2.6) * 0.5).tan();
7021 let dir: Vec3 = fwd
7022 .add(right.scale(ndc_x * half_tan_y * cam_aspect))
7023 .add(up.scale(ndc_y * half_tan_y))
7024 .normalize();
7025 (
7026 scene_cam.get_position(),
7027 dir,
7028 znear.max(0.01),
7029 zfar.unwrap_or(480.0).max(znear + 1.0),
7030 )
7031 }
7032 }
7033 } else {
7034 let cam: Camera3D = self.get_camera();
7035 let half_tan_y: f32 = (cam.get_fov_deg().clamp(12.0, 120.0).to_radians() * 0.5).tan();
7036 let half_tan_x: f32 = half_tan_y * safe_aspect;
7037 let forward: Vec3 = cam.forward();
7038 let right: Vec3 = cam.right();
7039 let up: Vec3 = right.cross(forward).normalize();
7040 let dir: Vec3 = forward
7041 .add(right.scale(ndc_x * half_tan_x))
7042 .add(up.scale(ndc_y * half_tan_y))
7043 .normalize();
7044 let near_v: f32 = cam.get_near().max(0.01);
7045 (
7046 cam.get_position(),
7047 dir,
7048 near_v,
7049 cam.get_far().max(near_v + 1.0),
7050 )
7051 };
7052 let inv_dir: Vec3 = Vec3::new(
7053 if ray_dir.get_x().abs() > 1e-6 {
7054 1.0 / ray_dir.get_x()
7055 } else {
7056 f32::INFINITY
7057 },
7058 if ray_dir.get_y().abs() > 1e-6 {
7059 1.0 / ray_dir.get_y()
7060 } else {
7061 f32::INFINITY
7062 },
7063 if ray_dir.get_z().abs() > 1e-6 {
7064 1.0 / ray_dir.get_z()
7065 } else {
7066 f32::INFINITY
7067 },
7068 );
7069 let Self {
7070 objects,
7071 mesh_library,
7072 deformed_meshes,
7073 ..
7074 } = self;
7075 let mut best_hit: Option<ScenePickHit3D> = None;
7076 for (obj_idx, obj) in objects.iter().enumerate() {
7077 if !self.is_object_visible(obj_idx) {
7078 continue;
7079 }
7080 let bounds: AxisAlignedBox3D = obj.get_world_bounds();
7081 let aabb_t: f32 = bounds.intersect_ray_near(origin, inv_dir, t_min, best_t);
7082 if aabb_t >= best_t {
7083 continue;
7084 }
7085 let mesh_ref: Option<&Mesh3D> = deformed_meshes
7086 .get(obj_idx)
7087 .and_then(|slot: &Option<Mesh3D>| slot.as_ref())
7088 .or_else(|| {
7089 mesh_library
7090 .get(obj.get_mesh_id())
7091 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
7092 });
7093 let Some(mesh) = mesh_ref else {
7094 best_t = aabb_t;
7095 let world_pos: Vec3 = origin.add(ray_dir.scale(aabb_t));
7096 best_hit = Some(ScenePickHit3D::new(
7097 obj_idx,
7098 obj.get_mesh_id(),
7099 aabb_t,
7100 world_pos,
7101 ray_dir.scale(-1.0),
7102 ));
7103 continue;
7104 };
7105 if mesh.get_indices().is_empty() {
7106 best_t = aabb_t;
7107 let world_pos: Vec3 = origin.add(ray_dir.scale(aabb_t));
7108 best_hit = Some(ScenePickHit3D::new(
7109 obj_idx,
7110 obj.get_mesh_id(),
7111 aabb_t,
7112 world_pos,
7113 ray_dir.scale(-1.0),
7114 ));
7115 continue;
7116 }
7117 let xform: Transform3D = obj.get_transform();
7118 let inv_elems: [f32; 16] = xform.to_inv_mat4().get_elements();
7119 let local_origin: Vec3 = Vec3::new(
7120 inv_elems[0] * origin.get_x()
7121 + inv_elems[4] * origin.get_y()
7122 + inv_elems[8] * origin.get_z()
7123 + inv_elems[12],
7124 inv_elems[1] * origin.get_x()
7125 + inv_elems[5] * origin.get_y()
7126 + inv_elems[9] * origin.get_z()
7127 + inv_elems[13],
7128 inv_elems[2] * origin.get_x()
7129 + inv_elems[6] * origin.get_y()
7130 + inv_elems[10] * origin.get_z()
7131 + inv_elems[14],
7132 );
7133 let local_dir: Vec3 = Vec3::new(
7134 inv_elems[0] * ray_dir.get_x()
7135 + inv_elems[4] * ray_dir.get_y()
7136 + inv_elems[8] * ray_dir.get_z(),
7137 inv_elems[1] * ray_dir.get_x()
7138 + inv_elems[5] * ray_dir.get_y()
7139 + inv_elems[9] * ray_dir.get_z(),
7140 inv_elems[2] * ray_dir.get_x()
7141 + inv_elems[6] * ray_dir.get_y()
7142 + inv_elems[10] * ray_dir.get_z(),
7143 );
7144 let local_inv_dir: Vec3 = Vec3::new(
7145 if local_dir.get_x().abs() > 1e-6 {
7146 1.0 / local_dir.get_x()
7147 } else {
7148 f32::INFINITY
7149 },
7150 if local_dir.get_y().abs() > 1e-6 {
7151 1.0 / local_dir.get_y()
7152 } else {
7153 f32::INFINITY
7154 },
7155 if local_dir.get_z().abs() > 1e-6 {
7156 1.0 / local_dir.get_z()
7157 } else {
7158 f32::INFINITY
7159 },
7160 );
7161 if let Some((hit_t, local_n)) = Self::intersect_mesh_triangles_local(
7162 mesh,
7163 local_origin,
7164 local_dir,
7165 local_inv_dir,
7166 t_min,
7167 best_t,
7168 ) {
7169 best_t = hit_t;
7170 let nmat: [Vec3; 3] = xform.normal_mat3();
7171 let mut world_n: Vec3 = nmat[0]
7172 .scale(local_n.get_x())
7173 .add(nmat[1].scale(local_n.get_y()))
7174 .add(nmat[2].scale(local_n.get_z()))
7175 .normalize();
7176 if world_n.dot(ray_dir) > 0.0 {
7177 world_n = world_n.scale(-1.0);
7178 }
7179 let world_pos: Vec3 = origin.add(ray_dir.scale(hit_t));
7180 best_hit = Some(ScenePickHit3D::new(
7181 obj_idx,
7182 obj.get_mesh_id(),
7183 hit_t,
7184 world_pos,
7185 world_n,
7186 ));
7187 }
7188 }
7189 best_hit
7190 }
7191
7192 pub fn tick_animations(&mut self, dt_secs: f32) -> usize {
7203 let anim_updates: usize = {
7204 let Self {
7205 scene_graph,
7206 animation_mixer,
7207 ..
7208 } = self;
7209 animation_mixer.advance_and_apply(dt_secs, scene_graph)
7210 };
7211 let propagated: usize = self.get_mut_scene_graph().propagate_world_matrices();
7212 let synced: usize = self.sync_objects_from_scene_graph();
7213 let deformed: usize = self.update_deformed_meshes();
7214 let total: usize = anim_updates + propagated + synced + deformed;
7215 if total > 0 {
7216 self.set_dynamic_bvh_dirty(true);
7217 self.bump_world_revision();
7218 }
7219 total
7220 }
7221
7222 pub fn update_deformed_meshes(&mut self) -> usize {
7228 let obj_count: usize = self.get_objects().len();
7229 let Self {
7230 mesh_library,
7231 objects,
7232 scene_graph,
7233 skins,
7234 skin_scratch,
7235 deformed_meshes,
7236 ..
7237 } = self;
7238 if deformed_meshes.len() < obj_count {
7239 deformed_meshes.resize(obj_count, None);
7240 }
7241 let mut updated_count: usize = 0;
7242 for obj_idx in 0..obj_count {
7243 let obj_ref: &SceneObject3D = &objects[obj_idx];
7244 let Some(node_id) = obj_ref.try_get_node_id() else {
7245 continue;
7246 };
7247 let morph_weights: &[f32] = scene_graph.morph_weights_for_node(node_id);
7248 let skin_opt: Option<u32> = obj_ref.try_get_skin_id();
7249 if skin_opt.is_none() && morph_weights.is_empty() {
7250 continue;
7251 }
7252 let Some(base_mesh) = mesh_library
7253 .get(obj_ref.get_mesh_id())
7254 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
7255 else {
7256 continue;
7257 };
7258 let mesh_world: Mat4 = scene_graph.get_nodes().get(node_id as usize).map_or_else(
7259 || obj_ref.get_transform().to_mat4(),
7260 SceneNode3D::get_world_matrix,
7261 );
7262 let did_deform: bool = if let Some(skin_id) = skin_opt
7263 && let Some(skin_ref) = skins.get(skin_id as usize)
7264 {
7265 skin_ref.deform_mesh_into(
7266 base_mesh,
7267 morph_weights,
7268 mesh_world,
7269 scene_graph,
7270 skin_scratch,
7271 )
7272 } else {
7273 let morphed: bool = apply_morph_targets_into(
7274 base_mesh.get_vertices().as_slice(),
7275 base_mesh.get_morph_targets().as_slice(),
7276 morph_weights,
7277 skin_scratch.get_mut_skinned_vertices(),
7278 );
7279 morphed
7280 };
7281 if did_deform {
7282 let deformed_verts: &[Vertex3D] = skin_scratch.get_skinned_vertices().as_slice();
7283 let mut local_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
7284 for vert_item in deformed_verts.iter() {
7285 local_bounds.expand_point(vert_item.get_position());
7286 }
7287 let target_slot: &mut Option<Mesh3D> = &mut deformed_meshes[obj_idx];
7288 if let Some(existing_mesh) = target_slot.as_mut() {
7289 let dst_verts: &mut Vec<Vertex3D> = existing_mesh.get_mut_vertices();
7290 dst_verts.clear();
7291 dst_verts.extend_from_slice(deformed_verts);
7292 existing_mesh.set_bounds(local_bounds);
7293 } else {
7294 let mut cloned_mesh: Mesh3D = base_mesh.clone();
7295 let dst_verts: &mut Vec<Vertex3D> = cloned_mesh.get_mut_vertices();
7296 dst_verts.clear();
7297 dst_verts.extend_from_slice(deformed_verts);
7298 cloned_mesh.set_bounds(local_bounds);
7299 *target_slot = Some(cloned_mesh);
7300 }
7301 if let Some(deformed_ref) = target_slot.as_ref() {
7302 let world_tr: Transform3D = objects[obj_idx].get_transform();
7303 objects[obj_idx]
7304 .set_world_bounds(world_tr.transform_bounds(deformed_ref.get_bounds()));
7305 }
7306 updated_count += 1;
7307 }
7308 }
7309 updated_count
7310 }
7311
7312 pub fn apply_live_delta(&mut self, delta: &BlenderLiveDelta3D) -> bool {
7323 match delta {
7324 BlenderLiveDelta3D::NodeTransform {
7325 node_name,
7326 translation,
7327 rotation,
7328 scale,
7329 blender_z_up,
7330 } => {
7331 let found_id: Option<u32> = self
7332 .get_scene_graph()
7333 .get_nodes()
7334 .iter()
7335 .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
7336 .map(|idx: usize| idx as u32);
7337 let Some(node_id) = found_id else {
7338 return false;
7339 };
7340 let raw_t: Vec3 = Vec3::from_array(*translation);
7341 let raw_r: Quat = Quat::from_array(*rotation).normalize();
7342 let raw_s: Vec3 = Vec3::from_array(*scale);
7343 let (dst_t, dst_r, dst_s): (Vec3, Quat, Vec3) = if *blender_z_up {
7344 (
7345 raw_t.blender_z_up_to_y_up(),
7346 raw_r.blender_z_up_to_y_up(),
7347 Vec3::new(raw_s.get_x(), raw_s.get_z(), raw_s.get_y()),
7348 )
7349 } else {
7350 (raw_t, raw_r, raw_s)
7351 };
7352 self.get_mut_scene_graph()
7353 .set_local_trs(node_id, dst_t, dst_r, dst_s);
7354 let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
7355 let _: usize = self.sync_objects_from_scene_graph();
7356 let _: usize = self.update_deformed_meshes();
7357 self.set_dynamic_bvh_dirty(true);
7358 self.bump_world_revision();
7359 true
7360 }
7361 BlenderLiveDelta3D::MaterialParams {
7362 material_name,
7363 base_color_factor,
7364 metallic_factor,
7365 roughness_factor,
7366 clearcoat_factor,
7367 clearcoat_roughness_factor,
7368 sheen_color_factor,
7369 sheen_roughness_factor,
7370 emissive_factor,
7371 emissive_strength,
7372 transmission_factor,
7373 ior,
7374 } => {
7375 let found_idx: Option<usize> = self
7376 .get_principled_materials()
7377 .iter()
7378 .position(|mat_ref: &PrincipledMaterial3D| mat_ref.get_name() == material_name);
7379 let Some(mat_idx) = found_idx else {
7380 return false;
7381 };
7382 let updated_legacy: PbrMaterial = {
7383 let mat_mut: &mut PrincipledMaterial3D =
7384 &mut self.get_mut_principled_materials()[mat_idx];
7385 if let Some(val) = *base_color_factor {
7386 mat_mut.set_base_color_factor(val);
7387 }
7388 if let Some(val) = *metallic_factor {
7389 mat_mut.set_metallic_factor(val.clamp(0.0, 1.0));
7390 }
7391 if let Some(val) = *roughness_factor {
7392 mat_mut.set_roughness_factor(val.clamp(0.04, 1.0));
7393 }
7394 if let Some(val) = *clearcoat_factor {
7395 mat_mut.set_clearcoat_factor(val.clamp(0.0, 1.0));
7396 }
7397 if let Some(val) = *clearcoat_roughness_factor {
7398 mat_mut.set_clearcoat_roughness_factor(val.clamp(0.0, 1.0));
7399 }
7400 if let Some(val) = *sheen_color_factor {
7401 mat_mut.set_sheen_color_factor(val);
7402 }
7403 if let Some(val) = *sheen_roughness_factor {
7404 mat_mut.set_sheen_roughness_factor(val.clamp(0.0, 1.0));
7405 }
7406 if let Some(val) = *emissive_factor {
7407 mat_mut.set_emissive_factor(val);
7408 }
7409 if let Some(val) = *emissive_strength {
7410 mat_mut.set_emissive_strength(val.max(0.0));
7411 }
7412 if let Some(val) = *transmission_factor {
7413 mat_mut.set_transmission_factor(val.clamp(0.0, 1.0));
7414 }
7415 if let Some(val) = *ior {
7416 mat_mut.set_ior(val.clamp(1.0, 3.0));
7417 }
7418 mat_mut.to_legacy_pbr()
7419 };
7420 let mat_u32: u32 = mat_idx as u32;
7421 for obj_mut in self.get_mut_objects().iter_mut() {
7422 if obj_mut.try_get_principled_material_id() == Some(mat_u32) {
7423 obj_mut.set_material(updated_legacy);
7424 }
7425 }
7426 self.bump_world_revision();
7427 true
7428 }
7429 BlenderLiveDelta3D::MorphWeights { node_name, weights } => {
7430 let found_id: Option<u32> = self
7431 .get_scene_graph()
7432 .get_nodes()
7433 .iter()
7434 .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
7435 .map(|idx: usize| idx as u32);
7436 let Some(node_id) = found_id else {
7437 return false;
7438 };
7439 self.get_mut_scene_graph()
7440 .update_morph_weights(node_id, weights.as_slice());
7441 let _: usize = self.update_deformed_meshes();
7442 self.set_dynamic_bvh_dirty(true);
7443 self.bump_world_revision();
7444 true
7445 }
7446 BlenderLiveDelta3D::LightUpdate {
7447 light_index,
7448 color,
7449 intensity,
7450 position,
7451 direction,
7452 } => {
7453 let mut changed: bool = false;
7454 if let Some(point_mut) = self.get_mut_point_lights().get_mut(*light_index) {
7455 if let Some(col_arr) = *color {
7456 point_mut.set_color(Vec3::from_array(col_arr));
7457 }
7458 if let Some(int_val) = *intensity {
7459 point_mut.set_intensity(int_val.max(0.0));
7460 }
7461 if let Some(pos_arr) = *position {
7462 point_mut.set_position(Vec3::from_array(pos_arr));
7463 }
7464 changed = true;
7465 } else if let Some(area_mut) = self.get_mut_area_lights().get_mut(*light_index) {
7466 if let Some(col_arr) = *color {
7467 area_mut.set_color(Vec3::from_array(col_arr));
7468 }
7469 if let Some(int_val) = *intensity {
7470 area_mut.set_intensity(int_val.max(0.0));
7471 }
7472 if let Some(pos_arr) = *position {
7473 area_mut.set_position(Vec3::from_array(pos_arr));
7474 }
7475 if let Some(dir_arr) = *direction {
7476 area_mut.set_direction(Vec3::from_array(dir_arr).normalize());
7477 }
7478 changed = true;
7479 }
7480 if changed {
7481 self.bump_world_revision();
7482 }
7483 changed
7484 }
7485 BlenderLiveDelta3D::CameraUpdate {
7486 position,
7487 yaw,
7488 pitch,
7489 fov_deg,
7490 } => {
7491 let mut cam: Camera3D = self.get_camera();
7492 cam.set_position(Vec3::from_array(*position));
7493 cam.set_yaw(*yaw);
7494 cam.set_pitch(pitch.clamp(-1.4, 1.4));
7495 cam.set_fov_deg(fov_deg.clamp(12.0, 120.0));
7496 self.set_camera(cam);
7497 self.bump_world_revision();
7498 true
7499 }
7500 BlenderLiveDelta3D::CollectionVisibility {
7501 collection_name,
7502 visible,
7503 } => self.set_collection_visible(collection_name, *visible),
7504 BlenderLiveDelta3D::EnvironmentUpdate {
7505 rotation_y_rad,
7506 intensity,
7507 } => {
7508 let Self {
7509 environment_ibl, ..
7510 } = self;
7511 if let Some(ibl_mut) = environment_ibl.as_mut() {
7512 ibl_mut.set_rotation_y_rad(*rotation_y_rad);
7513 ibl_mut.set_intensity(intensity.max(0.0));
7514 self.bump_world_revision();
7515 true
7516 } else {
7517 false
7518 }
7519 }
7520 }
7521 }
7522
7523 pub fn apply_live_delta_json(&mut self, json_payload: &str) -> Result<bool, String> {
7534 let root: Value =
7535 from_str::<Value>(json_payload).map_err(|_| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
7536 let kind_str: &str = root
7537 .get(LIVE_KEY_KIND)
7538 .and_then(Value::as_str)
7539 .ok_or_else(|| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
7540 let delta: BlenderLiveDelta3D = match kind_str {
7541 LIVE_DELTA_KIND_TRANSFORM => BlenderLiveDelta3D::NodeTransform {
7542 node_name: root
7543 .get(LIVE_KEY_NODE_NAME)
7544 .and_then(Value::as_str)
7545 .unwrap_or_default()
7546 .to_string(),
7547 translation: Self::json_f32_array3(root.get(LIVE_KEY_TRANSLATION))
7548 .unwrap_or([0.0, 0.0, 0.0]),
7549 rotation: Self::json_f32_array4(root.get(LIVE_KEY_ROTATION))
7550 .unwrap_or([0.0, 0.0, 0.0, 1.0]),
7551 scale: Self::json_f32_array3(root.get(LIVE_KEY_SCALE)).unwrap_or([1.0, 1.0, 1.0]),
7552 blender_z_up: root
7553 .get(LIVE_KEY_BLENDER_Z_UP)
7554 .and_then(Value::as_bool)
7555 .unwrap_or(false),
7556 },
7557 LIVE_DELTA_KIND_MATERIAL => BlenderLiveDelta3D::MaterialParams {
7558 material_name: root
7559 .get(LIVE_KEY_MATERIAL_NAME)
7560 .and_then(Value::as_str)
7561 .unwrap_or_default()
7562 .to_string(),
7563 base_color_factor: Self::json_f32_array4(root.get(LIVE_KEY_BASE_COLOR)),
7564 metallic_factor: root
7565 .get(LIVE_KEY_METALLIC)
7566 .and_then(Value::as_f64)
7567 .map(|val: f64| val as f32),
7568 roughness_factor: root
7569 .get(LIVE_KEY_ROUGHNESS)
7570 .and_then(Value::as_f64)
7571 .map(|val: f64| val as f32),
7572 clearcoat_factor: root
7573 .get(LIVE_KEY_CLEARCOAT)
7574 .and_then(Value::as_f64)
7575 .map(|val: f64| val as f32),
7576 clearcoat_roughness_factor: root
7577 .get(LIVE_KEY_CLEARCOAT_ROUGHNESS)
7578 .and_then(Value::as_f64)
7579 .map(|val: f64| val as f32),
7580 sheen_color_factor: Self::json_f32_array3(root.get(LIVE_KEY_SHEEN_COLOR)),
7581 sheen_roughness_factor: root
7582 .get(LIVE_KEY_SHEEN_ROUGHNESS)
7583 .and_then(Value::as_f64)
7584 .map(|val: f64| val as f32),
7585 emissive_factor: Self::json_f32_array3(root.get(LIVE_KEY_EMISSIVE)),
7586 emissive_strength: root
7587 .get(LIVE_KEY_EMISSIVE_STRENGTH)
7588 .and_then(Value::as_f64)
7589 .map(|val: f64| val as f32),
7590 transmission_factor: root
7591 .get(LIVE_KEY_TRANSMISSION)
7592 .and_then(Value::as_f64)
7593 .map(|val: f64| val as f32),
7594 ior: root
7595 .get("ior")
7596 .and_then(Value::as_f64)
7597 .map(|val: f64| val as f32),
7598 },
7599 LIVE_DELTA_KIND_MORPH => {
7600 let parsed_weights: Vec<f32> = root
7601 .get(LIVE_KEY_WEIGHTS)
7602 .and_then(Value::as_array)
7603 .map(|items: &Vec<Value>| {
7604 items
7605 .iter()
7606 .filter_map(|elem: &Value| elem.as_f64().map(|val: f64| val as f32))
7607 .collect()
7608 })
7609 .unwrap_or_default();
7610 BlenderLiveDelta3D::MorphWeights {
7611 node_name: root
7612 .get(LIVE_KEY_NODE_NAME)
7613 .and_then(Value::as_str)
7614 .unwrap_or_default()
7615 .to_string(),
7616 weights: parsed_weights,
7617 }
7618 }
7619 LIVE_DELTA_KIND_LIGHT => BlenderLiveDelta3D::LightUpdate {
7620 light_index: root
7621 .get(LIVE_KEY_LIGHT_INDEX)
7622 .and_then(Value::as_u64)
7623 .unwrap_or(0) as usize,
7624 color: Self::json_f32_array3(root.get(LIVE_KEY_COLOR)),
7625 intensity: root
7626 .get(LIVE_KEY_INTENSITY)
7627 .and_then(Value::as_f64)
7628 .map(|val: f64| val as f32),
7629 position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION)),
7630 direction: Self::json_f32_array3(root.get(LIVE_KEY_DIRECTION)),
7631 },
7632 LIVE_DELTA_KIND_CAMERA => BlenderLiveDelta3D::CameraUpdate {
7633 position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION))
7634 .unwrap_or([0.0, 2.0, 6.0]),
7635 yaw: root
7636 .get("yaw")
7637 .and_then(Value::as_f64)
7638 .map_or(0.0, |val: f64| val as f32),
7639 pitch: root
7640 .get(LIVE_KEY_PITCH)
7641 .and_then(Value::as_f64)
7642 .map_or(0.0, |val: f64| val as f32),
7643 fov_deg: root
7644 .get(LIVE_KEY_FOV_DEG)
7645 .and_then(Value::as_f64)
7646 .map_or(60.0, |val: f64| val as f32),
7647 },
7648 LIVE_DELTA_KIND_COLLECTION => BlenderLiveDelta3D::CollectionVisibility {
7649 collection_name: root
7650 .get(LIVE_KEY_COLLECTION_NAME)
7651 .and_then(Value::as_str)
7652 .unwrap_or_default()
7653 .to_string(),
7654 visible: root
7655 .get(LIVE_KEY_VISIBLE)
7656 .and_then(Value::as_bool)
7657 .unwrap_or(true),
7658 },
7659 LIVE_DELTA_KIND_ENVIRONMENT => BlenderLiveDelta3D::EnvironmentUpdate {
7660 rotation_y_rad: root
7661 .get(LIVE_KEY_ROTATION_Y_RAD)
7662 .and_then(Value::as_f64)
7663 .map_or(0.0, |val: f64| val as f32),
7664 intensity: root
7665 .get(LIVE_KEY_INTENSITY)
7666 .and_then(Value::as_f64)
7667 .map_or(1.0, |val: f64| val as f32),
7668 },
7669 _ => return Err(ERR_LIVE_DELTA_UNKNOWN_KIND.to_string()),
7670 };
7671 Ok(self.apply_live_delta(&delta))
7672 }
7673
7674 fn sync_objects_from_scene_graph(&mut self) -> usize {
7680 let Self {
7681 mesh_library,
7682 objects,
7683 scene_graph,
7684 scene_cameras,
7685 node_object_map,
7686 deformed_meshes,
7687 ..
7688 } = self;
7689 let nodes: &[SceneNode3D] = scene_graph.get_nodes().as_slice();
7690 let mut synced_count: usize = 0;
7691 for (node_idx, obj_slot) in node_object_map.iter().enumerate() {
7692 let Some(obj_idx) = *obj_slot else {
7693 continue;
7694 };
7695 if node_idx >= nodes.len() || obj_idx >= objects.len() {
7696 continue;
7697 }
7698 let world_tr: Transform3D =
7699 Transform3D::from_matrix(nodes[node_idx].get_world_matrix());
7700 if objects[obj_idx].get_transform() != world_tr {
7701 objects[obj_idx].set_transform(world_tr);
7702 let local_bounds: AxisAlignedBox3D = deformed_meshes
7703 .get(obj_idx)
7704 .and_then(Option::as_ref)
7705 .map(Mesh3D::get_bounds)
7706 .or_else(|| {
7707 mesh_library
7708 .get(objects[obj_idx].get_mesh_id())
7709 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
7710 .map(Mesh3D::get_bounds)
7711 })
7712 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
7713 objects[obj_idx].set_world_bounds(world_tr.transform_bounds(local_bounds));
7714 synced_count += 1;
7715 }
7716 }
7717 for cam_mut in scene_cameras.iter_mut() {
7718 if let Some(node_id) = cam_mut.try_get_node_id()
7719 && let Some(node_ref) = nodes.get(node_id as usize)
7720 {
7721 let (pos_val, rot_val, _scale_val): (Vec3, Quat, Vec3) =
7722 node_ref.get_world_matrix().decompose_trs();
7723 cam_mut.set_position(pos_val);
7724 cam_mut.set_rotation(rot_val);
7725 synced_count += 1;
7726 }
7727 }
7728 synced_count
7729 }
7730
7731 fn rebase_material_textures(material: &mut PrincipledMaterial3D, texture_base: u32) {
7738 if texture_base == 0 {
7739 return;
7740 }
7741 let shift_slot: fn(Option<TextureSlot3D>, u32) -> Option<TextureSlot3D> =
7742 |slot_opt: Option<TextureSlot3D>, base_val: u32| -> Option<TextureSlot3D> {
7743 slot_opt.map(|mut slot: TextureSlot3D| {
7744 slot.set_texture_index(slot.get_texture_index().saturating_add(base_val));
7745 slot
7746 })
7747 };
7748 material.set_base_color_texture(shift_slot(
7749 material.try_get_base_color_texture(),
7750 texture_base,
7751 ));
7752 material.set_metallic_roughness_texture(shift_slot(
7753 material.try_get_metallic_roughness_texture(),
7754 texture_base,
7755 ));
7756 material.set_normal_texture(shift_slot(material.try_get_normal_texture(), texture_base));
7757 material.set_occlusion_texture(shift_slot(
7758 material.try_get_occlusion_texture(),
7759 texture_base,
7760 ));
7761 material.set_emissive_texture(shift_slot(
7762 material.try_get_emissive_texture(),
7763 texture_base,
7764 ));
7765 material.set_specular_texture(shift_slot(
7766 material.try_get_specular_texture(),
7767 texture_base,
7768 ));
7769 material.set_specular_color_texture(shift_slot(
7770 material.try_get_specular_color_texture(),
7771 texture_base,
7772 ));
7773 material.set_clearcoat_texture(shift_slot(
7774 material.try_get_clearcoat_texture(),
7775 texture_base,
7776 ));
7777 material.set_clearcoat_roughness_texture(shift_slot(
7778 material.try_get_clearcoat_roughness_texture(),
7779 texture_base,
7780 ));
7781 material.set_clearcoat_normal_texture(shift_slot(
7782 material.try_get_clearcoat_normal_texture(),
7783 texture_base,
7784 ));
7785 material.set_transmission_texture(shift_slot(
7786 material.try_get_transmission_texture(),
7787 texture_base,
7788 ));
7789 material.set_sheen_color_texture(shift_slot(
7790 material.try_get_sheen_color_texture(),
7791 texture_base,
7792 ));
7793 material.set_sheen_roughness_texture(shift_slot(
7794 material.try_get_sheen_roughness_texture(),
7795 texture_base,
7796 ));
7797 }
7798
7799 #[must_use]
7809 fn json_f32_array3(val: Option<&Value>) -> Option<[f32; 3]> {
7810 let arr: &Vec<Value> = val?.as_array()?;
7811 if arr.len() < 3 {
7812 return None;
7813 }
7814 Some([
7815 arr[0].as_f64()? as f32,
7816 arr[1].as_f64()? as f32,
7817 arr[2].as_f64()? as f32,
7818 ])
7819 }
7820
7821 #[must_use]
7831 fn json_f32_array4(val: Option<&Value>) -> Option<[f32; 4]> {
7832 let arr: &Vec<Value> = val?.as_array()?;
7833 if arr.len() < 4 {
7834 return None;
7835 }
7836 Some([
7837 arr[0].as_f64()? as f32,
7838 arr[1].as_f64()? as f32,
7839 arr[2].as_f64()? as f32,
7840 arr[3].as_f64()? as f32,
7841 ])
7842 }
7843
7844 #[must_use]
7850 pub fn allocate_gpu_mesh_revision() -> u64 {
7851 NEXT_GPU_WORLD3D_MESH_REVISION
7852 .fetch_add(1, Ordering::Relaxed)
7853 .max(1)
7854 }
7855
7856 fn append_unit_particle_octahedron(vertices: &mut Vec<GpuWorld3dVertex>) -> (u32, u32) {
7866 let start_idx: u32 = vertices.len() as u32;
7867 let top: [f32; 3] = [0.0, 1.0, 0.0];
7868 let bot: [f32; 3] = [0.0, -1.0, 0.0];
7869 let pos_x: [f32; 3] = [1.0, 0.0, 0.0];
7870 let neg_x: [f32; 3] = [-1.0, 0.0, 0.0];
7871 let pos_z: [f32; 3] = [0.0, 0.0, 1.0];
7872 let neg_z: [f32; 3] = [0.0, 0.0, -1.0];
7873 let faces: [[[f32; 3]; 3]; 8] = [
7874 [top, pos_z, pos_x],
7875 [top, pos_x, neg_z],
7876 [top, neg_z, neg_x],
7877 [top, neg_x, pos_z],
7878 [bot, pos_x, pos_z],
7879 [bot, neg_z, pos_x],
7880 [bot, neg_x, neg_z],
7881 [bot, pos_z, neg_x],
7882 ];
7883 vertices.reserve(24);
7884 for tri in faces.iter() {
7885 for corner in tri.iter() {
7886 vertices.push(GpuWorld3dVertex::new(
7887 [corner[0], corner[1], corner[2], 1.0],
7888 [corner[0], corner[1], corner[2], 0.0],
7889 [1.0, 1.0, 1.0, 0.0],
7890 ));
7891 }
7892 }
7893 let vert_count: u32 = (vertices.len() as u32).saturating_sub(start_idx);
7894 (start_idx, vert_count)
7895 }
7896
7897 #[must_use]
7908 pub fn build_gpu_mesh_buffer(
7909 &self,
7910 revision: u64,
7911 ) -> (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) {
7912 let mut vertices: Vec<GpuWorld3dVertex> = Vec::new();
7913 let mut ranges: Vec<(u32, u32)> = Vec::with_capacity(self.get_mesh_library().len() + 1);
7914 for chain in self.get_mesh_library() {
7915 let start_idx: u32 = vertices.len() as u32;
7916 if let Some(mesh) = chain.get_levels().first() {
7917 let mesh_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
7918 let tri_mats: &[u16] = mesh.get_tri_materials().as_slice();
7919 let sub_mats: &[PbrMaterial] = mesh.get_sub_materials().as_slice();
7920 vertices.reserve(mesh.get_indices().len() * 3);
7921 for (tri_idx, &[i0, i1, i2]) in mesh.get_indices().iter().enumerate() {
7922 let (Some(v0), Some(v1), Some(v2)) = (
7923 mesh_verts.get(i0 as usize),
7924 mesh_verts.get(i1 as usize),
7925 mesh_verts.get(i2 as usize),
7926 ) else {
7927 continue;
7928 };
7929 let mat_slot: usize = tri_mats.get(tri_idx).copied().unwrap_or(0) as usize;
7930 let color_submat: [f32; 4] = if mat_slot > 0
7931 && let Some(sub_mat) = sub_mats.get(mat_slot - 1)
7932 {
7933 let base_c: Vec3 = sub_mat.get_base_color();
7934 let em_c: Vec3 = sub_mat.get_emissive();
7935 if em_c.length_sq() > 0.01 {
7936 [
7937 base_c.get_x() + em_c.get_x() * 1.4,
7938 base_c.get_y() + em_c.get_y() * 1.4,
7939 base_c.get_z() + em_c.get_z() * 1.4,
7940 2.0,
7941 ]
7942 } else {
7943 [base_c.get_x(), base_c.get_y(), base_c.get_z(), 1.0]
7944 }
7945 } else {
7946 [1.0, 1.0, 1.0, 0.0]
7947 };
7948 for vert in [v0, v1, v2] {
7949 let pos: Vec3 = vert.get_position();
7950 let nrm: Vec3 = vert.get_normal();
7951 vertices.push(GpuWorld3dVertex::new(
7952 [pos.get_x(), pos.get_y(), pos.get_z(), 1.0],
7953 [nrm.get_x(), nrm.get_y(), nrm.get_z(), 0.0],
7954 color_submat,
7955 ));
7956 }
7957 }
7958 }
7959 let vert_count: u32 = (vertices.len() as u32).saturating_sub(start_idx);
7960 ranges.push((start_idx, vert_count));
7961 }
7962 let particle_range: (u32, u32) = Self::append_unit_particle_octahedron(&mut vertices);
7963 ranges.push(particle_range);
7964 (
7965 Arc::new(GpuWorld3dMeshBuffer { revision, vertices }),
7966 ranges,
7967 )
7968 }
7969
7970 fn populate_gpu_scene_pass_with_scratch(
7982 &self,
7983 snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
7984 alpha: f32,
7985 viewport: (u32, u32),
7986 quality: &RenderQualityConfig,
7987 mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
7988 buffers: (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass),
7989 ) {
7990 let (scratch, out): (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass) = buffers;
7991 let (target_width, target_height): (u32, u32) = viewport;
7992 let (mesh_buffer, mesh_ranges): (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]) = mesh_cache;
7993 let blend_alpha: f32 = alpha.clamp(0.0, 1.0);
7994 let prev_snap: &World3DSnapshot = snapshots.get_prev_state();
7995 let curr_snap: &World3DSnapshot = snapshots.get_curr_state();
7996 let mut interp_cam: Camera3D = if curr_snap.get_camera_cut() {
7997 curr_snap.get_camera()
7998 } else {
7999 prev_snap
8000 .get_camera()
8001 .lerp(curr_snap.get_camera(), blend_alpha)
8002 };
8003 let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
8004 if aspect > 3.5 {
8005 let pull_back: f32 = ((aspect - 3.5) * 0.42).min(1.6);
8006 let shifted_pos: Vec3 = interp_cam
8007 .get_position()
8008 .sub(interp_cam.forward().scale(pull_back));
8009 interp_cam.set_position(shifted_pos);
8010 }
8011 let view_proj_mat: Mat4 = if let Some(cam_idx) = self.active_scene_camera_index()
8012 && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
8013 {
8014 scene_cam.view_projection(aspect)
8015 } else {
8016 interp_cam.view_projection(aspect)
8017 };
8018 let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
8019 let cam_pos: Vec3 = interp_cam.get_position();
8020 let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
8021 let frustum_on: bool = quality.get_frustum_culling();
8022 let obj_len: usize = self.get_objects().len();
8023 if scratch.dynamic_pose_epochs.len() < obj_len {
8024 scratch.dynamic_pose_epochs.resize(obj_len, 0);
8025 scratch
8026 .dynamic_pose_transforms
8027 .resize(obj_len, Transform3D::default());
8028 }
8029 let next_epoch: u32 = scratch.current_epoch.wrapping_add(1);
8030 let active_epoch: u32 = if next_epoch == 0 {
8031 scratch.dynamic_pose_epochs.fill(0);
8032 1
8033 } else {
8034 next_epoch
8035 };
8036 scratch.current_epoch = active_epoch;
8037 let prev_objs: &[ObjectPose3D] = prev_snap.get_objects().as_slice();
8038 let next_objs: &[ObjectPose3D] = curr_snap.get_objects().as_slice();
8039 for (slot_idx, curr) in next_objs.iter().copied().enumerate() {
8040 let obj_idx: usize = curr.get_object_index();
8041 if obj_idx >= obj_len {
8042 continue;
8043 }
8044 let mut blended_tr: Transform3D = curr.get_transform();
8045 if curr.get_visible()
8046 && let Some(prev) = prev_objs.get(slot_idx).copied()
8047 {
8048 let continuous: bool = prev.get_visible()
8049 && prev.get_object_index() == obj_idx
8050 && prev.get_teleport_epoch() == curr.get_teleport_epoch();
8051 if continuous {
8052 blended_tr = prev
8053 .get_transform()
8054 .lerp_shortest_angle(curr.get_transform(), blend_alpha);
8055 }
8056 }
8057 scratch.dynamic_pose_epochs[obj_idx] = active_epoch;
8058 scratch.dynamic_pose_transforms[obj_idx] = blended_tr;
8059 }
8060 let mesh_len: usize = mesh_ranges.len();
8061 if scratch.mesh_counts.len() < mesh_len {
8062 scratch.mesh_counts.resize(mesh_len, 0);
8063 scratch.mesh_cursors.resize(mesh_len, 0);
8064 }
8065 scratch.mesh_counts[..mesh_len].fill(0);
8066 scratch.visible_scratch.clear();
8067 let principled_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
8068 let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
8069 for (obj_idx, obj) in self.get_objects().iter().enumerate() {
8070 if !self.is_object_visible(obj_idx) {
8071 continue;
8072 }
8073 let mesh_id: usize = obj.get_mesh_id();
8074 let Some(&(_, vert_count)) = mesh_ranges.get(mesh_id) else {
8075 continue;
8076 };
8077 if vert_count == 0 {
8078 continue;
8079 }
8080 let mut tr: Transform3D = obj.get_transform();
8081 let mut world_bounds: AxisAlignedBox3D = obj.get_world_bounds();
8082 if scratch.dynamic_pose_epochs[obj_idx] == active_epoch {
8083 tr = scratch.dynamic_pose_transforms[obj_idx];
8084 if let Some(chain) = mesh_lib.get(mesh_id)
8085 && let Some(mesh0) = chain.get_levels().first()
8086 {
8087 world_bounds = tr.transform_bounds(mesh0.get_bounds());
8088 }
8089 }
8090 let dist_sq: f32 = world_bounds.center().sub(cam_pos).length_sq();
8091 let radius: f32 = world_bounds.get_max().sub(world_bounds.get_min()).length() * 0.5;
8092 if dist_sq > draw_dist_sq + radius * radius * 4.0 {
8093 continue;
8094 }
8095 if frustum_on && !frustum.intersects_bounds(&world_bounds) {
8096 continue;
8097 }
8098 let mat: PbrMaterial = obj.get_material();
8099 let (albedo, metallic, roughness, emissive): (Vec3, f32, f32, Vec3) = if let Some(pm_id) =
8100 obj.try_get_principled_material_id()
8101 && let Some(pm) = principled_mats.get(pm_id as usize)
8102 {
8103 let bc: [f32; 4] = pm.get_base_color_factor();
8104 let em: [f32; 3] = pm.get_emissive_factor();
8105 let em_str: f32 = pm.get_emissive_strength();
8106 (
8107 Vec3::new(bc[0], bc[1], bc[2]),
8108 pm.get_metallic_factor(),
8109 pm.get_roughness_factor(),
8110 Vec3::new(em[0] * em_str, em[1] * em_str, em[2] * em_str),
8111 )
8112 } else {
8113 (
8114 mat.get_base_color(),
8115 mat.get_metallic(),
8116 mat.get_roughness(),
8117 mat.get_emissive(),
8118 )
8119 };
8120 let mut model_elems: [f32; 16] = tr.to_mat4().get_elements();
8121 model_elems[15] = match mat.get_surface_detail() {
8122 SurfaceDetailMode::None => 0.0,
8123 SurfaceDetailMode::RoadSurface => 1.0,
8124 SurfaceDetailMode::ArchitecturalFacade => 2.0,
8125 SurfaceDetailMode::OceanWater => 3.0,
8126 };
8127 scratch.mesh_counts[mesh_id] = scratch.mesh_counts[mesh_id].saturating_add(1);
8128 scratch.visible_scratch.push((
8129 mesh_id as u32,
8130 GpuWorld3dInstance::new(
8131 model_elems,
8132 [
8133 albedo.get_x(),
8134 albedo.get_y(),
8135 albedo.get_z(),
8136 metallic.clamp(0.0, 1.0),
8137 ],
8138 [
8139 emissive.get_x(),
8140 emissive.get_y(),
8141 emissive.get_z(),
8142 roughness.clamp(0.05, 1.0),
8143 ],
8144 ),
8145 ));
8146 }
8147 let total_instances: usize = scratch.visible_scratch.len();
8148 out.draw_batches.clear();
8149 let mut cursor: u32 = 0;
8150 for (mesh_id, &(vertex_start, vertex_count)) in mesh_ranges.iter().enumerate() {
8151 let count: u32 = scratch.mesh_counts[mesh_id];
8152 scratch.mesh_cursors[mesh_id] = cursor;
8153 if count == 0 {
8154 continue;
8155 }
8156 out.draw_batches.push(GpuWorld3dMeshRange::new(
8157 vertex_start,
8158 vertex_count,
8159 cursor,
8160 count,
8161 ));
8162 cursor = cursor.saturating_add(count);
8163 }
8164 out.instances
8165 .resize(total_instances, GpuWorld3dInstance::default());
8166 for &(mesh_id_u32, inst) in scratch.visible_scratch.iter() {
8167 let mesh_id: usize = mesh_id_u32 as usize;
8168 let dst_idx: usize = scratch.mesh_cursors[mesh_id] as usize;
8169 scratch.mesh_cursors[mesh_id] = scratch.mesh_cursors[mesh_id].saturating_add(1);
8170 out.instances[dst_idx] = inst;
8171 }
8172 let particle_mesh_idx: usize = mesh_lib.len();
8173 if self.get_niagara().get_active_count() > 0
8174 && let Some(&(particle_vert_start, particle_vert_count)) =
8175 mesh_ranges.get(particle_mesh_idx)
8176 && particle_vert_count > 0
8177 {
8178 let particle_inst_start: u32 = out.instances.len() as u32;
8179 let active_frustum: Option<&Frustum3D> = if frustum_on { Some(&frustum) } else { None };
8180 let particle_inst_count: u32 = self.get_niagara().append_gpu_world3d_instances(
8181 cam_pos,
8182 draw_dist_sq,
8183 active_frustum,
8184 &mut out.instances,
8185 );
8186 if particle_inst_count > 0 {
8187 out.draw_batches.push(GpuWorld3dMeshRange::new(
8188 particle_vert_start,
8189 particle_vert_count,
8190 particle_inst_start,
8191 particle_inst_count,
8192 ));
8193 }
8194 }
8195 let sun: DirectionalLight3D = self.get_sun();
8196 let sun_dir: Vec3 = sun.get_direction().normalize();
8197 let sun_col: Vec3 = sun.get_color();
8198 let sky_hor: Vec3 = sun.get_sky_horizon();
8199 let sky_zen: Vec3 = sun.get_sky_zenith();
8200 let fog_density: f32 = if quality.get_volumetric_fog() {
8201 0.0028
8202 } else {
8203 0.0008
8204 };
8205 out.target_width = target_width;
8206 out.target_height = target_height;
8207 out.view_proj = view_proj_mat.get_elements();
8208 out.camera_pos = [cam_pos.get_x(), cam_pos.get_y(), cam_pos.get_z(), 1.15];
8209 out.sun_dir_fog = [
8210 sun_dir.get_x(),
8211 sun_dir.get_y(),
8212 sun_dir.get_z(),
8213 fog_density,
8214 ];
8215 out.sun_color_ambient = [sun_col.get_x(), sun_col.get_y(), sun_col.get_z(), 0.34];
8216 let anim_time: f32 =
8217 (sun.get_time_of_day() + self.get_world_time_secs()).rem_euclid(3600.0);
8218 out.sky_horizon_tod = [sky_hor.get_x(), sky_hor.get_y(), sky_hor.get_z(), anim_time];
8219 out.sky_zenith_aspect = [sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), aspect];
8220 out.mesh_buffer = Arc::clone(mesh_buffer);
8221 }
8222
8223 pub fn build_gpu_scene_pass_into(
8235 &mut self,
8236 snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
8237 alpha: f32,
8238 viewport: (u32, u32),
8239 quality: &RenderQualityConfig,
8240 mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
8241 out: &mut GpuWorld3dScenePass,
8242 ) {
8243 let mut scratch: World3dGpuPassScratch = {
8244 let Self {
8245 gpu_pass_scratch, ..
8246 } = self;
8247 take(gpu_pass_scratch)
8248 };
8249 self.populate_gpu_scene_pass_with_scratch(
8250 snapshots,
8251 alpha,
8252 viewport,
8253 quality,
8254 mesh_cache,
8255 (&mut scratch, out),
8256 );
8257 let Self {
8258 gpu_pass_scratch, ..
8259 } = self;
8260 *gpu_pass_scratch = scratch;
8261 }
8262
8263 fn sync_pbr_quantized_mesh_cache(
8270 mesh_library: &[MeshLodChain],
8271 scratch: &mut World3dPbrPassScratch,
8272 ) {
8273 let mut total_verts: usize = 0;
8274 let mut total_indices: usize = 0;
8275 let mut any_skinned: bool = false;
8276 let mut any_morphed: bool = false;
8277 for chain in mesh_library.iter() {
8278 for mesh in chain.get_levels().iter().take(4) {
8279 total_verts = total_verts.saturating_add(mesh.get_vertices().len());
8280 total_indices =
8281 total_indices.saturating_add(mesh.get_indices().len().saturating_mul(3));
8282 if !mesh.get_skin_influences().is_empty() {
8283 any_skinned = true;
8284 }
8285 if !mesh.get_morph_targets().is_empty() {
8286 any_morphed = true;
8287 }
8288 }
8289 }
8290 let signature: (usize, usize, usize) = (mesh_library.len(), total_verts, total_indices);
8291 if scratch.cached_signature == signature && scratch.cached_mesh_buffer.get_revision() > 0 {
8292 return;
8293 }
8294 let next_rev: u64 = NEXT_GPU_PBR_MESH_REVISION
8295 .fetch_add(1, Ordering::Relaxed)
8296 .max(1);
8297 let mut vertices: Vec<QuantizedVertex3D> = Vec::with_capacity(total_verts);
8298 let mut indices: Vec<u32> = Vec::with_capacity(total_indices);
8299 let mut skin_vertices: Vec<QuantizedSkinVertex3D> = if any_skinned {
8300 Vec::with_capacity(total_verts)
8301 } else {
8302 Vec::new()
8303 };
8304 let mut uv1_f16: Vec<[u16; 2]> = Vec::with_capacity(total_verts);
8305 let mut mesh_bounds_min: Vec<[f32; 4]> = Vec::with_capacity(mesh_library.len());
8306 let mut mesh_bounds_extent: Vec<[f32; 4]> = Vec::with_capacity(mesh_library.len());
8307 let mut morph_deltas: Vec<[f32; 4]> = if any_morphed && total_verts > 0 {
8308 vec![[0.0; 4]; total_verts.saturating_mul(4)]
8309 } else {
8310 Vec::new()
8311 };
8312 scratch.cached_lod_ranges.clear();
8313 scratch.cached_lod_ranges.reserve(mesh_library.len());
8314 let mut vert_tags: Vec<u8> = Vec::new();
8315 for chain in mesh_library.iter() {
8316 let levels: &[Mesh3D] = chain.get_levels().as_slice();
8317 let mut lod_ranges: [CachedPbrLodRange; 4] = [CachedPbrLodRange::default(); 4];
8318 let mut base_min: [f32; 4] = [0.0; 4];
8319 let mut base_ext: [f32; 4] = [1.0, 1.0, 1.0, 0.0];
8320 for (lod_idx, mesh) in levels.iter().take(4).enumerate() {
8321 let m_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
8322 let m_tris: &[[u32; 3]] = mesh.get_indices().as_slice();
8323 let mb: AxisAlignedBox3D = mesh.get_bounds();
8324 let bmin: Vec3 = mb.get_min();
8325 let bext_raw: Vec3 = mb.get_max().sub(bmin);
8326 let bext: Vec3 = Vec3::new(
8327 bext_raw.get_x().max(1e-4),
8328 bext_raw.get_y().max(1e-4),
8329 bext_raw.get_z().max(1e-4),
8330 );
8331 let min_arr: [f32; 4] = [bmin.get_x(), bmin.get_y(), bmin.get_z(), 0.0];
8332 let ext_arr: [f32; 4] = [bext.get_x(), bext.get_y(), bext.get_z(), 0.0];
8333 if lod_idx == 0 {
8334 base_min = min_arr;
8335 base_ext = ext_arr;
8336 }
8337 vert_tags.clear();
8338 vert_tags.resize(m_verts.len(), 0);
8339 for (cluster_idx, meshlet) in mesh.get_meshlets().iter().enumerate() {
8340 let tag: u8 = ((cluster_idx % 255) + 1) as u8;
8341 let t_start: usize = meshlet.get_first_tri() as usize;
8342 let t_end: usize = t_start
8343 .saturating_add(meshlet.get_tri_count() as usize)
8344 .min(m_tris.len());
8345 for tri in &m_tris[t_start..t_end] {
8346 for &vi in tri.iter() {
8347 if let Some(slot) = vert_tags.get_mut(vi as usize) {
8348 *slot = tag;
8349 }
8350 }
8351 }
8352 }
8353 let base_vertex: u32 = vertices.len() as u32;
8354 let index_start: u32 = indices.len() as u32;
8355 let skins: &[MeshSkinInfluence3D] = mesh.get_skin_influences().as_slice();
8356 for (vi, vert) in m_verts.iter().enumerate() {
8357 let tag: u8 = vert_tags.get(vi).copied().unwrap_or(0);
8358 vertices.push(quantize_vertex_3d(vert, bmin, bext, tag));
8359 let uv1: [f32; 2] = vert.get_uv1();
8360 uv1_f16.push([encode_f32_to_f16(uv1[0]), encode_f32_to_f16(uv1[1])]);
8361 if any_skinned {
8362 let qskin: QuantizedSkinVertex3D = skins
8363 .get(vi)
8364 .map_or_else(QuantizedSkinVertex3D::default, quantize_skin_vertex_3d);
8365 skin_vertices.push(qskin);
8366 }
8367 }
8368 let has_morphs: bool = !mesh.get_morph_targets().is_empty();
8369 if any_morphed && has_morphs && total_verts > 0 {
8370 for (t_idx, target) in mesh.get_morph_targets().iter().take(4).enumerate() {
8371 let dpos: &[[f32; 3]] = target.get_delta_positions().as_slice();
8372 let target_base: usize = t_idx
8373 .saturating_mul(total_verts)
8374 .saturating_add(base_vertex as usize);
8375 for (vi, delta) in dpos.iter().take(m_verts.len()).enumerate() {
8376 if let Some(dst) = morph_deltas.get_mut(target_base + vi) {
8377 *dst = [delta[0], delta[1], delta[2], 0.0];
8378 }
8379 }
8380 }
8381 }
8382 for tri in m_tris.iter() {
8383 indices.push(base_vertex.saturating_add(tri[0]));
8384 indices.push(base_vertex.saturating_add(tri[1]));
8385 indices.push(base_vertex.saturating_add(tri[2]));
8386 }
8387 let index_count: u32 = (indices.len() as u32).saturating_sub(index_start);
8388 lod_ranges[lod_idx] = CachedPbrLodRange {
8389 index_start,
8390 index_count,
8391 bounds_min: min_arr,
8392 bounds_extent: ext_arr,
8393 has_morphs,
8394 };
8395 }
8396 let avail: usize = levels.len().min(4);
8397 if avail > 0 && avail < 4 {
8398 let fallback_lod: CachedPbrLodRange = lod_ranges[avail - 1];
8399 for fill_slot in lod_ranges.iter_mut().skip(avail) {
8400 *fill_slot = fallback_lod;
8401 }
8402 }
8403 mesh_bounds_min.push(base_min);
8404 mesh_bounds_extent.push(base_ext);
8405 scratch.cached_lod_ranges.push(lod_ranges);
8406 }
8407 scratch.cached_signature = signature;
8408 scratch.cached_mesh_buffer = Arc::new(GpuPbrMeshBuffer {
8409 revision: next_rev,
8410 vertices,
8411 indices,
8412 skin_vertices,
8413 morph_deltas,
8414 uv1_f16,
8415 mesh_bounds_min,
8416 mesh_bounds_extent,
8417 });
8418 }
8419
8420 fn resolve_fallback_gpu_material(
8432 mat: PbrMaterial,
8433 fallback_base: usize,
8434 materials: &mut Vec<GpuMaterialData3D>,
8435 ) -> u32 {
8436 let albedo: Vec3 = mat.get_base_color();
8437 let emissive: Vec3 = mat.get_emissive();
8438 let candidate: GpuMaterialData3D = GpuMaterialData3D {
8439 base_color_factor: [albedo.get_x(), albedo.get_y(), albedo.get_z(), 1.0],
8440 emissive_alpha_cutoff: [emissive.get_x(), emissive.get_y(), emissive.get_z(), 0.5],
8441 pbr_ior_specular: [
8442 mat.get_metallic().clamp(0.0, 1.0),
8443 mat.get_roughness().clamp(0.04, 1.0),
8444 PRINCIPLED_DEFAULT_IOR,
8445 1.0,
8446 ],
8447 specular_color_clearcoat: [1.0, 1.0, 1.0, 0.0],
8448 clearcoat_normal_occ_trans: [0.1, 1.0, 1.0, 0.0],
8449 volume_attenuation: [1.0, 1.0, 1.0, 0.0],
8450 sheen_color_roughness: [0.0, 0.0, 0.0, 0.5],
8451 tex_indices_a: [GPU_MATERIAL_NO_TEXTURE; 4],
8452 tex_indices_b: [GPU_MATERIAL_NO_TEXTURE; 4],
8453 flags_volume: [
8454 0,
8455 f32::INFINITY.to_bits(),
8456 GPU_MATERIAL_NO_TEXTURE,
8457 GPU_MATERIAL_NO_TEXTURE,
8458 ],
8459 };
8460 if let Some(rel_idx) = materials[fallback_base..]
8461 .iter()
8462 .position(|existing: &GpuMaterialData3D| *existing == candidate)
8463 {
8464 return (fallback_base + rel_idx) as u32;
8465 }
8466 let slot: u32 = materials.len() as u32;
8467 materials.push(candidate);
8468 slot
8469 }
8470
8471 fn populate_gpu_pbr_scene_pass_with_scratch(
8483 &self,
8484 viewport: (u32, u32),
8485 quality: &RenderQualityConfig,
8486 belt: &mut GpuUploadBelt,
8487 scratch: &mut World3dPbrPassScratch,
8488 skin_scratch: &mut SkinPaletteScratch3D,
8489 out: &mut GpuPbrScenePass,
8490 ) {
8491 belt.begin_frame();
8492 let prev_vp: [f32; 16] = out.get_view_proj();
8493 out.clear_frame_payloads();
8494 let (target_width, target_height): (u32, u32) = viewport;
8495 let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
8496 let (view_proj_mat, cam_pos, cam_fov_deg, cam_far): (Mat4, Vec3, f32, f32) =
8497 if let Some(cam_idx) = self.active_scene_camera_index()
8498 && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
8499 {
8500 let proj_cam: Camera3D = scene_cam.to_camera3d();
8501 (
8502 scene_cam.view_projection(aspect),
8503 scene_cam.get_position(),
8504 proj_cam.get_fov_deg(),
8505 proj_cam.get_far(),
8506 )
8507 } else {
8508 let cam: Camera3D = self.get_camera();
8509 (
8510 cam.view_projection(aspect),
8511 cam.get_position(),
8512 cam.get_fov_deg(),
8513 cam.get_far(),
8514 )
8515 };
8516 let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
8517 Self::sync_pbr_quantized_mesh_cache(mesh_lib, scratch);
8518 let src_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
8519 let dst_mats: &mut Vec<GpuMaterialData3D> = out.get_mut_materials();
8520 if dst_mats.capacity() < src_mats.len() {
8521 dst_mats.reserve(src_mats.len() - dst_mats.len());
8522 }
8523 for mat_ref in src_mats.iter() {
8524 dst_mats.push(mat_ref.to_gpu_data());
8525 }
8526 let fallback_mat_base: usize = dst_mats.len();
8527 let dst_lights: &mut Vec<GpuPackedLocalLight> = out.get_mut_local_lights();
8528 for pl in self.get_point_lights().iter() {
8529 if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
8530 break;
8531 }
8532 let p: Vec3 = pl.get_position();
8533 let c: Vec3 = pl.get_color();
8534 dst_lights.push(GpuPackedLocalLight::new(
8535 [p.get_x(), p.get_y(), p.get_z(), pl.get_radius().max(0.1)],
8536 [c.get_x(), c.get_y(), c.get_z(), pl.get_intensity().max(0.0)],
8537 [0.0, -1.0, 0.0, 0.0],
8538 [-1.0, -1.0, 0.0, 0.0],
8539 ));
8540 }
8541 for sl in self.get_spot_lights().iter() {
8542 if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
8543 break;
8544 }
8545 let p: Vec3 = sl.get_position();
8546 let c: Vec3 = sl.get_color();
8547 let d: Vec3 = sl.get_direction().normalize();
8548 dst_lights.push(GpuPackedLocalLight::new(
8549 [p.get_x(), p.get_y(), p.get_z(), sl.get_range().max(0.1)],
8550 [c.get_x(), c.get_y(), c.get_z(), sl.get_intensity().max(0.0)],
8551 [d.get_x(), d.get_y(), d.get_z(), 1.0],
8552 [sl.get_inner_cos(), sl.get_outer_cos(), 0.0, 0.0],
8553 ));
8554 }
8555 for al in self.get_area_lights().iter() {
8556 if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
8557 break;
8558 }
8559 let p: Vec3 = al.get_position();
8560 let c: Vec3 = al.get_color();
8561 let d: Vec3 = al.get_direction().normalize();
8562 dst_lights.push(GpuPackedLocalLight::new(
8563 [p.get_x(), p.get_y(), p.get_z(), al.get_range().max(0.1)],
8564 [c.get_x(), c.get_y(), c.get_z(), al.get_intensity().max(0.0)],
8565 [d.get_x(), d.get_y(), d.get_z(), 2.0],
8566 [0.0, -1.0, al.get_width(), al.get_height()],
8567 ));
8568 }
8569 let sun: DirectionalLight3D = self.get_sun();
8570 let sun_dir: Vec3 = sun.get_direction().normalize();
8571 let sun_col: Vec3 = sun.get_color();
8572 let sky_hor: Vec3 = sun.get_sky_horizon();
8573 let sky_zen: Vec3 = sun.get_sky_zenith();
8574 let ibl_sh: [[f32; 4]; 9] = if let Some(env) = self.environment_ibl() {
8575 let raw: [[f32; 3]; 9] = env.get_sh_irradiance();
8576 let mut packed: [[f32; 4]; 9] = [[0.0; 4]; 9];
8577 for (dst, src) in packed.iter_mut().zip(raw.iter()) {
8578 *dst = [src[0], src[1], src[2], 0.0];
8579 }
8580 packed
8581 } else {
8582 let mut packed: [[f32; 4]; 9] = [[0.0; 4]; 9];
8583 let avg_r: f32 = (sky_hor.get_x() + sky_zen.get_x()) * 0.5;
8584 let avg_g: f32 = (sky_hor.get_y() + sky_zen.get_y()) * 0.5;
8585 let avg_b: f32 = (sky_hor.get_z() + sky_zen.get_z()) * 0.5;
8586 packed[0] = [avg_r * 1.35, avg_g * 1.35, avg_b * 1.35, 0.0];
8587 packed[1] = [
8588 (sky_zen.get_x() - sky_hor.get_x()) * 0.35,
8589 (sky_zen.get_y() - sky_hor.get_y()) * 0.35,
8590 (sky_zen.get_z() - sky_hor.get_z()) * 0.35,
8591 0.0,
8592 ];
8593 packed
8594 };
8595 let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
8596 let frustum_planes: [[f32; 4]; 6] = frustum.get_planes();
8597 let half_h: f32 = (cam_fov_deg.clamp(12.0, 120.0).to_radians() * 0.5)
8598 .tan()
8599 .max(0.05);
8600 let focal_px: f32 = (target_height.max(1) as f32) * 0.5 / half_h;
8601 let draw_dist: f32 = quality.get_draw_distance().max(1.0);
8602 let draw_dist_sq: f32 = draw_dist * draw_dist;
8603 let frustum_on: bool = quality.get_frustum_culling();
8604 let chunk_on: bool = quality.get_chunk_streaming();
8605 let lod_bias: f32 = quality.get_lod_bias();
8606 let inv_far: f32 = 1.0 / cam_far.max(draw_dist).max(1.0);
8607 let objects: &[SceneObject3D] = self.get_objects().as_slice();
8608 let scene_graph: &SceneGraph3D = self.get_scene_graph();
8609 let skins: &[Skin3D] = self.get_skins().as_slice();
8610 let total_objs: usize = objects.len();
8611 scratch.batcher.get_mut_entries().clear();
8612 if scratch.batcher.get_entries().capacity() < total_objs {
8613 let need: usize = total_objs - scratch.batcher.get_entries().len();
8614 scratch.batcher.get_mut_entries().reserve(need);
8615 }
8616 let mut meshlets_tested: u32 = 0;
8617 let mut meshlets_culled: u32 = 0;
8618 let mut lod_counts: [u32; 4] = [0; 4];
8619 let mut base_idx: usize = 0;
8620 while base_idx < total_objs {
8621 let chunk: usize = (total_objs - base_idx).min(4);
8622 let mut min_x: [f32; 4] = [0.0; 4];
8623 let mut min_y: [f32; 4] = [0.0; 4];
8624 let mut min_z: [f32; 4] = [0.0; 4];
8625 let mut max_x: [f32; 4] = [0.0; 4];
8626 let mut max_y: [f32; 4] = [0.0; 4];
8627 let mut max_z: [f32; 4] = [0.0; 4];
8628 let mut vis_flags: u8 = 0;
8629 for lane in 0..chunk {
8630 let obj_idx: usize = base_idx + lane;
8631 if !self.is_object_visible(obj_idx) {
8632 continue;
8633 }
8634 let wb: AxisAlignedBox3D = objects[obj_idx].get_world_bounds();
8635 let dist_sq: f32 = wb.center().sub(cam_pos).length_sq();
8636 if chunk_on && dist_sq > draw_dist_sq {
8637 continue;
8638 }
8639 let bmin: Vec3 = wb.get_min();
8640 let bmax: Vec3 = wb.get_max();
8641 min_x[lane] = bmin.get_x();
8642 min_y[lane] = bmin.get_y();
8643 min_z[lane] = bmin.get_z();
8644 max_x[lane] = bmax.get_x();
8645 max_y[lane] = bmax.get_y();
8646 max_z[lane] = bmax.get_z();
8647 vis_flags |= 1u8 << lane;
8648 }
8649 let frustum_mask: u8 = if frustum_on && vis_flags != 0 {
8650 let aabb4: SimdAabbBatch4 =
8651 SimdAabbBatch4::new(min_x, min_y, min_z, max_x, max_y, max_z);
8652 cull_aabb_batch4_simd(&frustum_planes, &aabb4)
8653 } else {
8654 0x0F
8655 };
8656 let active_mask: u8 = vis_flags & frustum_mask;
8657 for lane in 0..chunk {
8658 let obj_idx: usize = base_idx + lane;
8659 let obj: &SceneObject3D = &objects[obj_idx];
8660 let mesh_id: usize = obj.get_mesh_id();
8661 let Some(chain) = mesh_lib.get(mesh_id) else {
8662 continue;
8663 };
8664 if ((active_mask >> lane) & 1) == 0 {
8665 if self.is_object_visible(obj_idx)
8666 && let Some(base_mesh) = chain.get_levels().first()
8667 {
8668 let mcount: u32 = base_mesh.get_meshlets().len().max(1) as u32;
8669 meshlets_tested = meshlets_tested.saturating_add(mcount);
8670 meshlets_culled = meshlets_culled.saturating_add(mcount);
8671 }
8672 continue;
8673 }
8674 let wb: AxisAlignedBox3D = obj.get_world_bounds();
8675 let dist: f32 = wb.center().sub(cam_pos).length();
8676 let (selected_mesh, raw_lod): (&Mesh3D, usize) =
8677 chain.select_screen_error(dist, wb.radius(), focal_px, lod_bias);
8678 let lod_idx: usize = raw_lod.min(3);
8679 let Some(lod_arr) = scratch.cached_lod_ranges.get(mesh_id) else {
8680 continue;
8681 };
8682 let lod_range: CachedPbrLodRange = lod_arr[lod_idx];
8683 if lod_range.index_count == 0 {
8684 continue;
8685 }
8686 let model_mat: Mat4 = obj.get_transform().to_mat4();
8687 let (m_tested, m_culled): (u32, u32) = if !selected_mesh.get_meshlets().is_empty() {
8688 cull_meshlets_simd(
8689 selected_mesh.get_meshlets().as_slice(),
8690 &model_mat,
8691 &frustum,
8692 cam_pos,
8693 selected_mesh.get_is_closed(),
8694 )
8695 } else {
8696 (1, 0)
8697 };
8698 meshlets_tested = meshlets_tested.saturating_add(m_tested);
8699 meshlets_culled = meshlets_culled.saturating_add(m_culled);
8700 if selected_mesh.get_is_closed() && m_tested > 0 && m_culled >= m_tested {
8701 continue;
8702 }
8703 lod_counts[lod_idx] = lod_counts[lod_idx].saturating_add(1);
8704 let mat_slot: u32 = if let Some(pid) = obj.try_get_principled_material_id()
8705 && (pid as usize) < fallback_mat_base
8706 {
8707 pid
8708 } else {
8709 Self::resolve_fallback_gpu_material(
8710 obj.get_material(),
8711 fallback_mat_base,
8712 out.get_mut_materials(),
8713 )
8714 };
8715 let mat_flags: u32 = out
8716 .get_materials()
8717 .get(mat_slot as usize)
8718 .map_or(0, |m: &GpuMaterialData3D| m.get_flags_volume()[0]);
8719 let is_alpha_blend: bool = (mat_flags & GPU_MATERIAL_FLAG_ALPHA_BLEND) != 0;
8720 let mut inst_flags: u32 = 0;
8721 let mut bone_off: u32 = 0;
8722 let mut pso_variant: u8 = PBR_PSO_VARIANT_OPAQUE;
8723 if let Some(skin_id) = obj.try_get_skin_id()
8724 && let Some(skin_ref) = skins.get(skin_id as usize)
8725 {
8726 bone_off = out.get_bone_matrices().len() as u32;
8727 skin_ref.compute_skin_matrices_into(model_mat, scene_graph, skin_scratch);
8728 let palette: &[Mat4] = skin_scratch.get_skin_matrices().as_slice();
8729 let dst_bones: &mut Vec<[f32; 16]> = out.get_mut_bone_matrices();
8730 if dst_bones.capacity() < dst_bones.len() + palette.len() {
8731 dst_bones.reserve(palette.len());
8732 }
8733 for bm in palette.iter() {
8734 dst_bones.push(bm.get_elements());
8735 }
8736 inst_flags |= PBR_INST_FLAG_SKINNED;
8737 if skin_ref.get_skinning_mode() == SkinningMode::DualQuaternion {
8738 inst_flags |= PBR_INST_FLAG_DQS;
8739 }
8740 pso_variant = PBR_PSO_VARIANT_SKINNED;
8741 }
8742 let mut morph_off: u32 = 0;
8743 if lod_range.has_morphs
8744 && let Some(node_id) = obj.try_get_node_id()
8745 {
8746 let mweights: &[f32] = scene_graph.morph_weights_for_node(node_id);
8747 if !mweights.is_empty() {
8748 morph_off = out.get_morph_weights().len() as u32;
8749 let dst_mw: &mut Vec<f32> = out.get_mut_morph_weights();
8750 for k in 0..4 {
8751 dst_mw.push(mweights.get(k).copied().unwrap_or(0.0));
8752 }
8753 inst_flags |= PBR_INST_FLAG_MORPHED;
8754 }
8755 }
8756 let alpha_pass: u8 = if is_alpha_blend {
8757 pso_variant = PBR_PSO_VARIANT_ALPHA_BLEND;
8758 inst_flags |= PBR_INST_FLAG_ALPHA_BLEND;
8759 1
8760 } else {
8761 0
8762 };
8763 let depth_q16: u16 = ((dist * inv_far).clamp(0.0, 1.0) * 65_535.0).round() as u16;
8764 let sort_key: u64 = pack_pbr_sort_key(
8765 alpha_pass,
8766 pso_variant,
8767 mat_slot,
8768 mesh_id as u32,
8769 lod_idx as u8,
8770 depth_q16,
8771 );
8772 let mut q_origin: [f32; 4] = lod_range.bounds_min;
8773 q_origin[3] = f32::from_bits(obj_idx as u32);
8774 let mut q_extent: [f32; 4] = lod_range.bounds_extent;
8775 q_extent[3] = lod_idx as f32;
8776 let instance: GpuPbrInstance3D = GpuPbrInstance3D::new(
8777 model_mat.get_elements(),
8778 q_origin,
8779 q_extent,
8780 [mat_slot, bone_off, morph_off, inst_flags],
8781 );
8782 scratch.batcher.get_mut_entries().push(PbrSortEntry3D {
8783 sort_key,
8784 index_start: lod_range.index_start,
8785 index_count: lod_range.index_count,
8786 base_vertex: 0,
8787 material_index: mat_slot,
8788 pso_variant,
8789 lod_level: lod_idx as u8,
8790 instance,
8791 });
8792 }
8793 base_idx += 4;
8794 }
8795 let draw_call_count: u32 = {
8796 let GpuPbrScenePass {
8797 instances,
8798 draw_batches,
8799 ..
8800 } = out;
8801 coalesce_pbr_batches_into(&mut scratch.batcher, instances, draw_batches)
8802 };
8803 let textures: &[Texture2D3D] = self.get_textures().as_slice();
8804 if scratch.uploaded_texture_min_mip.len() < textures.len() {
8805 scratch
8806 .uploaded_texture_min_mip
8807 .resize(textures.len(), u8::MAX);
8808 }
8809 for (slot_idx, tex) in textures.iter().enumerate() {
8810 let mips: &[TextureMipLevel3D] = tex.get_mips().as_slice();
8811 if mips.is_empty() {
8812 continue;
8813 }
8814 let current_min: u8 = scratch.uploaded_texture_min_mip[slot_idx];
8815 if current_min == 0 {
8816 continue;
8817 }
8818 let total_mips: u8 = mips.len().min(16) as u8;
8819 let (target_mip, priority): (u8, StreamPriority) = if current_min == u8::MAX {
8820 (total_mips.saturating_sub(1), StreamPriority::Critical)
8821 } else {
8822 let next_mip: u8 = current_min.saturating_sub(1);
8823 let prio: StreamPriority = if next_mip > 0 {
8824 StreamPriority::VisibleHigh
8825 } else {
8826 StreamPriority::PrefetchMedium
8827 };
8828 (next_mip, prio)
8829 };
8830 if let Some(mip_data) = mips.get(target_mip as usize) {
8831 let upload: GpuTextureMipUpload = GpuTextureMipUpload {
8832 texture_slot: slot_idx as u32,
8833 mip_level: target_mip,
8834 total_mip_levels: total_mips,
8835 is_srgb: tex.get_color_space() == TextureColorSpace::Srgb,
8836 min_lod_clamp: target_mip,
8837 width: mip_data.get_width(),
8838 height: mip_data.get_height(),
8839 rgba8: mip_data.get_pixels().clone(),
8840 };
8841 let _: GpuUploadTicket = belt.enqueue_mip_upload(priority, upload);
8842 }
8843 }
8844 let _: usize = belt.drain_mip_uploads_into(out.get_mut_texture_uploads());
8845 for uploaded in out.get_texture_uploads().iter() {
8846 let slot_idx: usize = uploaded.get_texture_slot() as usize;
8847 if let Some(watermark) = scratch.uploaded_texture_min_mip.get_mut(slot_idx) {
8848 *watermark = (*watermark).min(uploaded.get_mip_level());
8849 }
8850 }
8851 let fog_density: f32 = if quality.get_volumetric_fog() {
8852 0.0028
8853 } else {
8854 0.0008
8855 };
8856 let agx_flag: f32 = if self.get_use_agx_tonemap() { 1.0 } else { 0.0 };
8857 out.set_target_width(target_width);
8858 out.set_target_height(target_height);
8859 out.set_prev_view_proj(prev_vp);
8860 out.set_view_proj(view_proj_mat.get_elements());
8861 out.set_camera_pos_exposure([cam_pos.get_x(), cam_pos.get_y(), cam_pos.get_z(), 1.15]);
8862 out.set_sun_dir_fog([
8863 sun_dir.get_x(),
8864 sun_dir.get_y(),
8865 sun_dir.get_z(),
8866 fog_density,
8867 ]);
8868 out.set_sun_color_ambient([sun_col.get_x(), sun_col.get_y(), sun_col.get_z(), 0.34]);
8869 out.set_sky_horizon_tod([
8870 sky_hor.get_x(),
8871 sky_hor.get_y(),
8872 sky_hor.get_z(),
8873 sun.get_time_of_day(),
8874 ]);
8875 out.set_sky_zenith_agx([sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), agx_flag]);
8876 out.set_ibl_sh(ibl_sh);
8877 out.set_mesh_buffer(Arc::clone(&scratch.cached_mesh_buffer));
8878 let stats: GpuPbrCullStats = GpuPbrCullStats::new(
8879 meshlets_tested,
8880 meshlets_culled,
8881 lod_counts,
8882 draw_call_count,
8883 belt.get_frame_bytes_used(),
8884 belt.get_frame_time_us_used(),
8885 );
8886 out.set_stats(stats);
8887 }
8888
8889 pub fn build_gpu_pbr_scene_pass_into(
8898 &mut self,
8899 viewport: (u32, u32),
8900 quality: &RenderQualityConfig,
8901 belt: &mut GpuUploadBelt,
8902 out: &mut GpuPbrScenePass,
8903 ) {
8904 let (mut pbr_work, mut skin_work): (World3dPbrPassScratch, SkinPaletteScratch3D) = {
8905 let Self {
8906 pbr_pass_scratch,
8907 skin_scratch,
8908 ..
8909 } = self;
8910 (take(pbr_pass_scratch), take(skin_scratch))
8911 };
8912 self.populate_gpu_pbr_scene_pass_with_scratch(
8913 viewport,
8914 quality,
8915 belt,
8916 &mut pbr_work,
8917 &mut skin_work,
8918 out,
8919 );
8920 let Self {
8921 pbr_pass_scratch,
8922 skin_scratch,
8923 ..
8924 } = self;
8925 *pbr_pass_scratch = pbr_work;
8926 *skin_scratch = skin_work;
8927 }
8928
8929 #[must_use]
8944 pub fn build_gpu_scene_pass(
8945 &self,
8946 snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
8947 alpha: f32,
8948 viewport: (u32, u32),
8949 quality: &RenderQualityConfig,
8950 mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
8951 ) -> GpuWorld3dScenePass {
8952 let mut out: GpuWorld3dScenePass = GpuWorld3dScenePass::default();
8953 let used_tls: bool = WORLD3D_GPU_PASS_SCRATCH
8954 .try_with(|cell: &RefCell<World3dGpuPassScratch>| -> bool {
8955 if let Ok(mut scratch) = cell.try_borrow_mut() {
8956 self.populate_gpu_scene_pass_with_scratch(
8957 snapshots,
8958 alpha,
8959 viewport,
8960 quality,
8961 mesh_cache,
8962 (&mut scratch, &mut out),
8963 );
8964 true
8965 } else {
8966 false
8967 }
8968 })
8969 .unwrap_or(false);
8970 if !used_tls {
8971 let mut local_scratch: World3dGpuPassScratch = World3dGpuPassScratch::default();
8972 self.populate_gpu_scene_pass_with_scratch(
8973 snapshots,
8974 alpha,
8975 viewport,
8976 quality,
8977 mesh_cache,
8978 (&mut local_scratch, &mut out),
8979 );
8980 }
8981 out
8982 }
8983}
8984
8985impl SceneCamera3D {
8987 #[must_use]
9000 pub fn from_imported(
9001 imported: &ImportedCamera3D,
9002 node_id: Option<u32>,
9003 position: Vec3,
9004 rotation: Quat,
9005 ) -> Self {
9006 Self {
9007 name: imported.get_name().clone(),
9008 node_id,
9009 position,
9010 rotation: rotation.normalize(),
9011 projection: imported.get_projection(),
9012 }
9013 }
9014
9015 #[must_use]
9021 pub fn forward(&self) -> Vec3 {
9022 self.get_rotation()
9023 .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
9024 .normalize()
9025 }
9026
9027 #[must_use]
9033 pub fn right(&self) -> Vec3 {
9034 self.get_rotation()
9035 .rotate_vec3(Vec3::new(1.0, 0.0, 0.0))
9036 .normalize()
9037 }
9038
9039 #[must_use]
9045 pub fn up(&self) -> Vec3 {
9046 self.get_rotation()
9047 .rotate_vec3(Vec3::new(0.0, 1.0, 0.0))
9048 .normalize()
9049 }
9050
9051 #[must_use]
9057 pub fn is_orthographic(&self) -> bool {
9058 matches!(
9059 self.get_projection(),
9060 GltfCameraProjection::Orthographic { .. }
9061 )
9062 }
9063
9064 #[must_use]
9075 pub fn view_projection(&self, viewport_aspect: f32) -> Mat4 {
9076 let pos: Vec3 = self.get_position();
9077 let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), self.up());
9078 let proj: Mat4 = match self.get_projection() {
9079 GltfCameraProjection::Perspective {
9080 yfov_rad,
9081 aspect_ratio,
9082 znear,
9083 zfar,
9084 } => Mat4::perspective(
9085 yfov_rad.clamp(0.15, 2.6),
9086 aspect_ratio.unwrap_or(viewport_aspect).max(0.1),
9087 znear.max(0.02),
9088 zfar.unwrap_or(480.0).max(znear + 1.0),
9089 ),
9090 GltfCameraProjection::Orthographic {
9091 xmag,
9092 ymag,
9093 znear,
9094 zfar,
9095 } => Mat4::orthographic_mag(xmag, ymag, znear.max(0.01), zfar.max(znear + 1.0)),
9096 };
9097 proj.mul(view)
9098 }
9099
9100 #[must_use]
9106 pub fn to_camera3d(&self) -> Camera3D {
9107 let fwd: Vec3 = self.forward();
9108 let yaw_val: f32 = fwd.get_z().atan2(fwd.get_x());
9109 let pitch_val: f32 = fwd.get_y().clamp(-0.98, 0.98).asin();
9110 let (fov_deg, near_val, far_val): (f32, f32, f32) = match self.get_projection() {
9111 GltfCameraProjection::Perspective {
9112 yfov_rad,
9113 znear,
9114 zfar,
9115 ..
9116 } => (
9117 yfov_rad.to_degrees().clamp(12.0, 120.0),
9118 znear.max(0.05),
9119 zfar.unwrap_or(480.0).max(10.0),
9120 ),
9121 GltfCameraProjection::Orthographic { znear, zfar, .. } => {
9122 (45.0, znear.max(0.05), zfar.max(10.0))
9123 }
9124 };
9125 let mut cam: Camera3D = Camera3D::default();
9126 cam.set_position(self.get_position());
9127 cam.set_yaw(yaw_val);
9128 cam.set_pitch(pitch_val);
9129 cam.set_fov_deg(fov_deg);
9130 cam.set_near(near_val);
9131 cam.set_far(far_val);
9132 cam
9133 }
9134}