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 boost_spool: 0.0,
813 engine_rpm_norm: 0.14,
814 active_gear: 1,
815 prev_throttle: 0.0,
816 backfire_timer: 0.0,
817 drift_active: false,
818 drift_slip_angle: 0.0,
819 drift_duration: 0.0,
820 drift_peak_slip: 0.0,
821 camera_fov_boost: 0.0,
822 camera_shake: 0.0,
823 wheel_spin_rad: 0.0,
824 front_steer_rad: 0.0,
825 }
826 }
827}
828
829impl NpcVehicle3D {
831 #[must_use]
845 pub(crate) fn new_boulevard(
846 object_index: usize,
847 start_s: f32,
848 lane_u: f32,
849 signed_speed_mps: f32,
850 face_yaw: f32,
851 ) -> Self {
852 let dir: f32 = if signed_speed_mps >= 0.0 { 1.0 } else { -1.0 };
853 let speed: f32 = signed_speed_mps.abs();
854 let fwd: Vec3 = Vec3::new(-face_yaw.sin(), 0.0, -face_yaw.cos());
855 let (target_pos, _): (Vec3, f32) = World3D::loop_pose_at(start_s + dir * 10.0, lane_u);
856 Self {
857 object_index,
858 vel: fwd.scale(speed),
859 yaw_rate: 0.0,
860 mass: VEHICLE_NPC_MASS_KG,
861 cruise_speed: speed,
862 recovery_timer: 0.0,
863 free_roam_mode: false,
864 loop_arc_s: start_s,
865 loop_lane_u: lane_u,
866 loop_dir: dir,
867 nav_target: target_pos,
868 waypoint_idx: 0,
869 route_id: 0,
870 stuck_timer: 0.0,
871 unstick_timer: 0.0,
872 unstick_steer: 1.0,
873 escape_heading: face_yaw,
874 escape_timer: 0.0,
875 lane_avoid_offset: 0.0,
876 last_wall_normal_x: 0.0,
877 last_wall_normal_z: 0.0,
878 wheel_spin_rad: 0.0,
879 front_steer_rad: 0.0,
880 wheel_object_indices: [None; 4],
881 vehicle_kind: SculptedVehicleKind::NpcSedan,
882 }
883 }
884
885 #[must_use]
899 pub(crate) fn new_free_roam(
900 object_index: usize,
901 route_id: u8,
902 waypoint_idx: usize,
903 cruise_speed: f32,
904 face_yaw: f32,
905 ) -> Self {
906 let waypoints: &[(f32, f32)] = Self::route_waypoints(route_id);
907 let safe_idx: usize = waypoint_idx % waypoints.len();
908 let (tx, tz): (f32, f32) = waypoints[safe_idx];
909 let fwd: Vec3 = Vec3::new(-face_yaw.sin(), 0.0, -face_yaw.cos());
910 Self {
911 object_index,
912 vel: fwd.scale(cruise_speed),
913 yaw_rate: 0.0,
914 mass: VEHICLE_NPC_MASS_KG,
915 cruise_speed,
916 recovery_timer: 0.0,
917 free_roam_mode: true,
918 loop_arc_s: 0.0,
919 loop_lane_u: 0.0,
920 loop_dir: 1.0,
921 nav_target: Vec3::new(tx, 0.0, tz),
922 waypoint_idx: safe_idx,
923 route_id,
924 stuck_timer: 0.0,
925 unstick_timer: 0.0,
926 unstick_steer: 1.0,
927 escape_heading: face_yaw,
928 escape_timer: 0.0,
929 lane_avoid_offset: 0.0,
930 last_wall_normal_x: 0.0,
931 last_wall_normal_z: 0.0,
932 wheel_spin_rad: 0.0,
933 front_steer_rad: 0.0,
934 wheel_object_indices: [None; 4],
935 vehicle_kind: SculptedVehicleKind::NpcSedan,
936 }
937 }
938
939 #[must_use]
949 pub(crate) fn route_waypoints(route_id: u8) -> &'static [(f32, f32)] {
950 match route_id {
951 1 => &NPC_OUTER_PLAZA_WAYPOINTS,
952 2 => &NPC_COURTYARD_CROSS_WAYPOINTS,
953 _ => &NPC_INNER_PLAZA_WAYPOINTS,
954 }
955 }
956
957 #[must_use]
967 pub(crate) fn nearest_open_waypoint(pos: Vec3) -> (u8, usize, Vec3) {
968 let mut best_route: u8 = 0;
969 let mut best_idx: usize = 0;
970 let mut best_pos: Vec3 = Vec3::new(
971 NPC_INNER_PLAZA_WAYPOINTS[0].0,
972 0.0,
973 NPC_INNER_PLAZA_WAYPOINTS[0].1,
974 );
975 let mut best_dist_sq: f32 = f32::INFINITY;
976 for route_id in 0..3_u8 {
977 let pts: &[(f32, f32)] = Self::route_waypoints(route_id);
978 for (idx, &(wx, wz)) in pts.iter().enumerate() {
979 let dx: f32 = wx - pos.get_x();
980 let dz: f32 = wz - pos.get_z();
981 let dist_sq: f32 = dx * dx + dz * dz;
982 if dist_sq > 25.0 && dist_sq < best_dist_sq {
983 best_dist_sq = dist_sq;
984 best_route = route_id;
985 best_idx = idx;
986 best_pos = Vec3::new(wx, 0.0, wz);
987 }
988 }
989 }
990 (best_route, best_idx, best_pos)
991 }
992}
993
994impl CameraMode3D {
996 #[must_use]
1006 pub const fn from_u8(index: u8) -> Self {
1007 match index {
1008 1 => Self::Hood,
1009 2 => Self::Orbit,
1010 3 => Self::Aerial,
1011 4 => Self::FreeFly,
1012 5 => Self::CinematicDolly,
1013 6 => Self::Cockpit,
1014 7 => Self::CitySkylinePanorama,
1015 8 => Self::CityRiverfrontBridge,
1016 9 => Self::CityDowntownIntersection,
1017 10 => Self::CityAerialDroneOrbit,
1018 _ => Self::Chase,
1019 }
1020 }
1021
1022 #[must_use]
1032 pub const fn as_u8(self) -> u8 {
1033 match self {
1034 Self::Chase => 0,
1035 Self::Hood => 1,
1036 Self::Orbit => 2,
1037 Self::Aerial => 3,
1038 Self::FreeFly => 4,
1039 Self::CinematicDolly => 5,
1040 Self::Cockpit => 6,
1041 Self::CitySkylinePanorama => 7,
1042 Self::CityRiverfrontBridge => 8,
1043 Self::CityDowntownIntersection => 9,
1044 Self::CityAerialDroneOrbit => 10,
1045 }
1046 }
1047
1048 #[must_use]
1058 pub const fn is_city_camera(self) -> bool {
1059 matches!(
1060 self,
1061 Self::CitySkylinePanorama
1062 | Self::CityRiverfrontBridge
1063 | Self::CityDowntownIntersection
1064 | Self::CityAerialDroneOrbit
1065 )
1066 }
1067
1068 #[must_use]
1078 pub const fn label(self) -> &'static str {
1079 match self {
1080 Self::Chase => CAMERA_LABEL_CHASE,
1081 Self::Hood => CAMERA_LABEL_HOOD,
1082 Self::Cockpit => CAMERA_LABEL_COCKPIT,
1083 Self::Orbit => CAMERA_LABEL_ORBIT,
1084 Self::Aerial => CAMERA_LABEL_AERIAL,
1085 Self::FreeFly => CAMERA_LABEL_FREE_FLY,
1086 Self::CinematicDolly => CAMERA_LABEL_CINEMATIC_DOLLY,
1087 Self::CitySkylinePanorama => CAMERA_LABEL_CITY_SKYLINE,
1088 Self::CityRiverfrontBridge => CAMERA_LABEL_CITY_RIVERFRONT,
1089 Self::CityDowntownIntersection => CAMERA_LABEL_CITY_DOWNTOWN,
1090 Self::CityAerialDroneOrbit => CAMERA_LABEL_CITY_DRONE,
1091 }
1092 }
1093}
1094
1095impl TimeOfDayPreset3D {
1097 #[must_use]
1107 pub const fn from_u8(index: u8) -> Self {
1108 match index {
1109 0 => Self::MorningSunrise,
1110 1 => Self::BrightNoon,
1111 3 => Self::NeonMidnight,
1112 _ => Self::GoldenSunset,
1113 }
1114 }
1115
1116 #[must_use]
1126 pub const fn as_u8(self) -> u8 {
1127 match self {
1128 Self::MorningSunrise => 0,
1129 Self::BrightNoon => 1,
1130 Self::GoldenSunset => 2,
1131 Self::NeonMidnight => 3,
1132 }
1133 }
1134
1135 #[must_use]
1145 pub const fn next(self) -> Self {
1146 match self {
1147 Self::MorningSunrise => Self::BrightNoon,
1148 Self::BrightNoon => Self::GoldenSunset,
1149 Self::GoldenSunset => Self::NeonMidnight,
1150 Self::NeonMidnight => Self::MorningSunrise,
1151 }
1152 }
1153
1154 #[must_use]
1164 pub const fn hour(self) -> f32 {
1165 match self {
1166 Self::MorningSunrise => ATMOSPHERE_HOUR_SUNRISE,
1167 Self::BrightNoon => ATMOSPHERE_HOUR_NOON,
1168 Self::GoldenSunset => ATMOSPHERE_HOUR_SUNSET,
1169 Self::NeonMidnight => ATMOSPHERE_HOUR_MIDNIGHT,
1170 }
1171 }
1172
1173 #[must_use]
1183 pub const fn label(self) -> &'static str {
1184 match self {
1185 Self::MorningSunrise => TIME_LABEL_MORNING_SUNRISE,
1186 Self::BrightNoon => TIME_LABEL_BRIGHT_NOON,
1187 Self::GoldenSunset => TIME_LABEL_GOLDEN_SUNSET,
1188 Self::NeonMidnight => TIME_LABEL_NEON_MIDNIGHT,
1189 }
1190 }
1191}
1192
1193impl WeatherPreset3D {
1195 #[must_use]
1205 pub const fn from_u8(index: u8) -> Self {
1206 match index {
1207 1 => Self::PartlyCloudy,
1208 2 => Self::MistyFog,
1209 3 => Self::Rainstorm,
1210 _ => Self::ClearSunny,
1211 }
1212 }
1213
1214 #[must_use]
1224 pub const fn as_u8(self) -> u8 {
1225 match self {
1226 Self::ClearSunny => 0,
1227 Self::PartlyCloudy => 1,
1228 Self::MistyFog => 2,
1229 Self::Rainstorm => 3,
1230 }
1231 }
1232
1233 #[must_use]
1243 pub const fn next(self) -> Self {
1244 match self {
1245 Self::ClearSunny => Self::PartlyCloudy,
1246 Self::PartlyCloudy => Self::MistyFog,
1247 Self::MistyFog => Self::Rainstorm,
1248 Self::Rainstorm => Self::ClearSunny,
1249 }
1250 }
1251
1252 #[must_use]
1262 pub const fn is_wet_asphalt(self) -> bool {
1263 matches!(self, Self::MistyFog | Self::Rainstorm)
1264 }
1265
1266 #[must_use]
1276 pub const fn base_fog_density(self) -> f32 {
1277 match self {
1278 Self::ClearSunny => 0.0022,
1279 Self::PartlyCloudy => 0.0038,
1280 Self::MistyFog => 0.0145,
1281 Self::Rainstorm => 0.0086,
1282 }
1283 }
1284
1285 #[must_use]
1295 pub const fn label(self) -> &'static str {
1296 match self {
1297 Self::ClearSunny => WEATHER_LABEL_CLEAR_SUNNY,
1298 Self::PartlyCloudy => WEATHER_LABEL_PARTLY_CLOUDY,
1299 Self::MistyFog => WEATHER_LABEL_MISTY_FOG,
1300 Self::Rainstorm => WEATHER_LABEL_RAINSTORM,
1301 }
1302 }
1303}
1304
1305impl SpawnObjectDesc {
1307 #[must_use]
1318 pub fn new(name: &str, mesh_id: usize) -> Self {
1319 Self {
1320 name: name.to_string(),
1321 mesh_id,
1322 transform: Transform3D::default(),
1323 material: PbrMaterial::default(),
1324 ray_trace_caster: true,
1325 solid_collider: true,
1326 spin_speed: 0.0,
1327 is_dynamic: false,
1328 }
1329 }
1330
1331 #[must_use]
1342 pub fn with_transform(mut self, transform: Transform3D) -> Self {
1343 self.set_transform(transform);
1344 self
1345 }
1346
1347 #[must_use]
1358 pub fn with_material(mut self, material: PbrMaterial) -> Self {
1359 self.set_material(material);
1360 self
1361 }
1362
1363 #[must_use]
1374 pub fn with_ray_trace(mut self, ray_trace_caster: bool) -> Self {
1375 self.set_ray_trace_caster(ray_trace_caster);
1376 self
1377 }
1378
1379 #[must_use]
1390 pub fn with_solid_collider(mut self, solid_collider: bool) -> Self {
1391 self.set_solid_collider(solid_collider);
1392 self
1393 }
1394
1395 #[must_use]
1406 pub fn with_spin(mut self, spin_speed: f32) -> Self {
1407 self.set_spin_speed(spin_speed);
1408 if spin_speed.abs() > 0.001 {
1409 self.set_is_dynamic(true);
1410 }
1411 self
1412 }
1413
1414 #[must_use]
1425 pub fn with_dynamic(mut self, is_dynamic: bool) -> Self {
1426 self.set_is_dynamic(is_dynamic);
1427 self
1428 }
1429}
1430
1431impl ImportModelDesc {
1433 #[must_use]
1444 pub fn new(format: ModelFormat, source: &str) -> Self {
1445 Self {
1446 format,
1447 source: source.to_string(),
1448 transform: Transform3D::default(),
1449 fallback_material: PbrMaterial::default(),
1450 spin_speed: 0.0,
1451 }
1452 }
1453
1454 #[must_use]
1465 pub fn with_transform(mut self, transform: Transform3D) -> Self {
1466 self.set_transform(transform);
1467 self
1468 }
1469
1470 #[must_use]
1481 pub fn with_material(mut self, fallback_material: PbrMaterial) -> Self {
1482 self.set_fallback_material(fallback_material);
1483 self
1484 }
1485
1486 #[must_use]
1497 pub fn with_spin(mut self, spin_speed: f32) -> Self {
1498 self.set_spin_speed(spin_speed);
1499 self
1500 }
1501}
1502
1503impl DirectionalLight3D {
1505 #[must_use]
1515 pub fn from_time_of_day(hour: f32) -> Self {
1516 let height_val: f32 = hour.rem_euclid(24.0);
1517 let elev_angle: f32 = ((height_val - 6.0) / 12.0 * PI).clamp(-0.35, 3.49);
1518 let sun_y: f32 = elev_angle.sin();
1519 let sun_x: f32 = elev_angle.cos();
1520 let dir: Vec3 = Vec3::new(-sun_x * 0.62, sun_y.max(0.22), -0.78).normalize();
1521 if (7.5..=16.5).contains(&height_val) {
1522 Self {
1523 direction: dir,
1524 color: Vec3::new(2.35, 2.18, 1.96),
1525 sky_zenith: Vec3::new(0.08, 0.24, 0.64),
1526 sky_horizon: Vec3::new(0.46, 0.66, 0.88),
1527 time_of_day: height_val,
1528 }
1529 } else if (5.5..7.5).contains(&height_val) || (16.5..19.5).contains(&height_val) {
1530 Self {
1531 direction: Vec3::new(-0.14, 0.165, -0.976).normalize(),
1532 color: Vec3::new(2.85, 1.42, 0.66),
1533 sky_zenith: Vec3::new(0.028, 0.038, 0.155),
1534 sky_horizon: Vec3::new(0.62, 0.24, 0.22),
1535 time_of_day: height_val,
1536 }
1537 } else {
1538 Self {
1539 direction: Vec3::new(-0.36, 0.56, -0.74).normalize(),
1540 color: Vec3::new(0.52, 0.68, 1.22),
1541 sky_zenith: Vec3::new(0.012, 0.022, 0.068),
1542 sky_horizon: Vec3::new(0.068, 0.115, 0.235),
1543 time_of_day: height_val,
1544 }
1545 }
1546 }
1547}
1548
1549impl Default for DirectionalLight3D {
1551 fn default() -> Self {
1557 Self::from_time_of_day(17.2)
1558 }
1559}
1560
1561impl Default for World3D {
1563 fn default() -> Self {
1569 Self {
1570 mesh_library: Arc::new(Vec::new()),
1571 objects: Vec::new(),
1572 camera: Camera3D::default(),
1573 sun: DirectionalLight3D::default(),
1574 bvh: Arc::new(Bvh3D::default()),
1575 dynamic_bvh: Arc::new(Bvh3D::default()),
1576 mesh_local_bvhs: Arc::new(Vec::new()),
1577 dynamic_instances: Vec::new(),
1578 bvh_dirty: true,
1579 dynamic_bvh_dirty: true,
1580 dynamic_topology_dirty: true,
1581 static_bvh_rebuilds: 0,
1582 dynamic_bvh_refits: 0,
1583 dynamic_bvh_rebuilds: 0,
1584 world_revision: 1,
1585 sim_tick: 0,
1586 dynamic_tris_scratch: Vec::new(),
1587 chunk_size: 64.0,
1588 player_vehicle_index: None,
1589 hero_vehicle_style: HeroVehicleStyle::AventadorV12,
1590 hero_vehicle_meshes: [None, None],
1591 hero_wheel_meshes: [None, None],
1592 player_wheel_objects: [None; 4],
1593 imported_model_count: 0,
1594 camera_mode: 0,
1595 last_car_camera_mode: CameraMode3D::Chase,
1596 camera_orbit_rad: 0.4,
1597 point_lights: Vec::new(),
1598 spot_lights: Vec::new(),
1599 niagara: NiagaraSystem3D::default(),
1600 atmosphere_preset: 0,
1601 time_of_day_preset: TimeOfDayPreset3D::GoldenSunset,
1602 weather_preset: WeatherPreset3D::ClearSunny,
1603 wet_asphalt: false,
1604 weather_fog_density: WeatherPreset3D::ClearSunny.base_fog_density(),
1605 weather_ambient_strength: 0.34,
1606 weather_exposure: 1.15,
1607 exhaust_flame_objects: [None; EXHAUST_TOTAL_FLAME_OBJECTS],
1608 exhaust_flame_visible: [false; EXHAUST_TOTAL_FLAME_OBJECTS],
1609 exhaust_light_index: None,
1610 road_ground_object_index: None,
1611 traffic_vehicles: Vec::new(),
1612 player_physics: PlayerVehiclePhysics3D::default(),
1613 world_time_secs: 0.0,
1614 scene_graph: SceneGraph3D::default(),
1615 principled_materials: Vec::new(),
1616 textures: Vec::new(),
1617 skins: Vec::new(),
1618 animation_mixer: AnimationMixer3D::default(),
1619 environment_ibl: None,
1620 area_lights: Vec::new(),
1621 scene_cameras: Vec::new(),
1622 active_scene_camera: None,
1623 node_object_map: Vec::new(),
1624 skin_scratch: SkinPaletteScratch3D::default(),
1625 deformed_meshes: Vec::new(),
1626 use_agx_tonemap: false,
1627 gpu_pass_scratch: World3dGpuPassScratch::default(),
1628 pbr_pass_scratch: World3dPbrPassScratch::default(),
1629 city_ecosystem: CityEcosystemState3D::default(),
1630 }
1631 }
1632}
1633
1634impl World3D {
1636 #[inline]
1646 #[must_use]
1647 pub fn get_mesh_library(&self) -> &Vec<MeshLodChain> {
1648 let Self { mesh_library, .. } = self;
1649 mesh_library.as_ref()
1650 }
1651
1652 #[inline]
1662 pub fn get_mut_mesh_library(&mut self) -> &mut Vec<MeshLodChain> {
1663 let Self { mesh_library, .. } = self;
1664 Arc::make_mut(mesh_library)
1665 }
1666
1667 #[inline]
1678 pub fn set_mesh_library(&mut self, next_mesh_library: Vec<MeshLodChain>) -> &mut Self {
1679 let Self { mesh_library, .. } = self;
1680 *mesh_library = Arc::new(next_mesh_library);
1681 self
1682 }
1683
1684 #[inline]
1694 #[must_use]
1695 pub fn get_bvh(&self) -> &Bvh3D {
1696 let Self { bvh, .. } = self;
1697 bvh.as_ref()
1698 }
1699
1700 #[inline]
1710 pub fn get_mut_bvh(&mut self) -> &mut Bvh3D {
1711 let Self { bvh, .. } = self;
1712 Arc::make_mut(bvh)
1713 }
1714
1715 #[inline]
1726 pub fn set_bvh(&mut self, next_bvh: Bvh3D) -> &mut Self {
1727 let Self { bvh, .. } = self;
1728 *bvh = Arc::new(next_bvh);
1729 self
1730 }
1731
1732 #[inline]
1742 #[must_use]
1743 pub fn get_dynamic_bvh(&self) -> &Bvh3D {
1744 let Self { dynamic_bvh, .. } = self;
1745 dynamic_bvh.as_ref()
1746 }
1747
1748 #[inline]
1758 pub fn get_mut_dynamic_bvh(&mut self) -> &mut Bvh3D {
1759 let Self { dynamic_bvh, .. } = self;
1760 Arc::make_mut(dynamic_bvh)
1761 }
1762
1763 #[inline]
1774 pub fn set_dynamic_bvh(&mut self, next_bvh: Bvh3D) -> &mut Self {
1775 let Self { dynamic_bvh, .. } = self;
1776 *dynamic_bvh = Arc::new(next_bvh);
1777 self
1778 }
1779
1780 pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
1791 let id: usize = self.get_mesh_library().len();
1792 self.get_mut_mesh_library().push(chain);
1793 id
1794 }
1795
1796 pub fn spawn_object(
1811 &mut self,
1812 name: &str,
1813 mesh_id: usize,
1814 transform: Transform3D,
1815 material: PbrMaterial,
1816 ray_trace_caster: bool,
1817 ) -> usize {
1818 let local_bounds: AxisAlignedBox3D = self
1819 .get_mesh_library()
1820 .get(mesh_id)
1821 .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1822 .map(Mesh3D::get_bounds)
1823 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1824 let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1825 let cs: f32 = self.get_chunk_size().max(8.0);
1826 let pos: Vec3 = transform.get_position();
1827 let chunk_coord: (i32, i32) = (
1828 (pos.get_x() / cs).floor() as i32,
1829 (pos.get_z() / cs).floor() as i32,
1830 );
1831 let idx: usize = self.get_objects().len();
1832 self.get_mut_objects().push(SceneObject3D {
1833 name: name.to_string(),
1834 mesh_id,
1835 transform,
1836 material,
1837 world_bounds,
1838 chunk_coord,
1839 ray_trace_caster,
1840 solid_collider: ray_trace_caster,
1841 spin_speed: 0.0,
1842 is_dynamic: false,
1843 teleport_epoch: 0,
1844 node_id: None,
1845 principled_material_id: None,
1846 skin_id: None,
1847 });
1848 let Self {
1849 deformed_meshes, ..
1850 } = self;
1851 deformed_meshes.push(None);
1852 if ray_trace_caster {
1853 self.set_bvh_dirty(true);
1854 }
1855 self.bump_world_revision();
1856 idx
1857 }
1858
1859 pub fn bump_world_revision(&mut self) {
1865 let next: u64 = self.get_world_revision().wrapping_add(1);
1866 self.set_world_revision(next);
1867 }
1868
1869 pub fn set_object_collidable(&mut self, obj_idx: usize, solid_collider: bool) -> bool {
1881 if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1882 obj.set_solid_collider(solid_collider);
1883 true
1884 } else {
1885 false
1886 }
1887 }
1888
1889 pub fn set_object_dynamic(&mut self, obj_idx: usize, is_dynamic: bool) -> bool {
1901 let Some(obj) = self.get_mut_objects().get_mut(obj_idx) else {
1902 return false;
1903 };
1904 if obj.get_is_dynamic() != is_dynamic {
1905 obj.set_is_dynamic(is_dynamic);
1906 if obj.get_ray_trace_caster() {
1907 self.set_bvh_dirty(true);
1908 self.set_dynamic_bvh_dirty(true);
1909 self.set_dynamic_topology_dirty(true);
1910 }
1911 self.bump_world_revision();
1912 }
1913 true
1914 }
1915
1916 pub fn teleport_object(&mut self, obj_idx: usize, transform: Transform3D) -> bool {
1928 let Some((mesh_id, ray_caster, is_dynamic)) =
1929 self.get_objects().get(obj_idx).map(|obj: &SceneObject3D| {
1930 (
1931 obj.get_mesh_id(),
1932 obj.get_ray_trace_caster(),
1933 obj.get_is_dynamic(),
1934 )
1935 })
1936 else {
1937 return false;
1938 };
1939 let local_bounds: AxisAlignedBox3D = self
1940 .get_mesh_library()
1941 .get(mesh_id)
1942 .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1943 .map(Mesh3D::get_bounds)
1944 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1945 let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1946 if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1947 obj.set_transform(transform);
1948 obj.set_world_bounds(world_bounds);
1949 let next_epoch: u32 = obj.get_teleport_epoch().wrapping_add(1);
1950 obj.set_teleport_epoch(next_epoch);
1951 }
1952 if self.vehicle_index() == Some(obj_idx) {
1953 let Self { player_physics, .. } = self;
1954 let saved_charge: f32 = player_physics.get_boost_charge();
1955 *player_physics = PlayerVehiclePhysics3D::default();
1956 player_physics.set_boost_charge(saved_charge);
1957 } else {
1958 let Self {
1959 traffic_vehicles, ..
1960 } = self;
1961 for npc in traffic_vehicles.iter_mut() {
1962 if npc.get_object_index() == obj_idx {
1963 npc.set_vel(Vec3::zero());
1964 npc.set_yaw_rate(0.0);
1965 npc.set_recovery_timer(0.0);
1966 break;
1967 }
1968 }
1969 }
1970 if ray_caster {
1971 if is_dynamic {
1972 self.set_dynamic_bvh_dirty(true);
1973 } else {
1974 self.set_bvh_dirty(true);
1975 }
1976 }
1977 self.bump_world_revision();
1978 true
1979 }
1980
1981 pub fn import_model(
1996 &mut self,
1997 format: ModelFormat,
1998 source: &str,
1999 transform: Transform3D,
2000 fallback_material: PbrMaterial,
2001 spin_speed: f32,
2002 ) -> Result<ImportedModel3D, String> {
2003 let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
2004 let model_name: String = imported.get_name().clone();
2005 for (item_index, chain) in imported.get_meshes().iter().cloned().enumerate() {
2006 let mat: PbrMaterial = chain
2007 .get_levels()
2008 .first()
2009 .map(Mesh3D::get_material)
2010 .unwrap_or(fallback_material);
2011 let mid: usize = self.register_mesh(chain);
2012 let obj_idx: usize = self.spawn_object(
2013 &format!("{model_name}_{item_index}"),
2014 mid,
2015 transform,
2016 mat,
2017 true,
2018 );
2019 if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
2020 obj.set_spin_speed(spin_speed);
2021 }
2022 if spin_speed.abs() > 0.001 {
2023 let _: bool = self.set_object_dynamic(obj_idx, true);
2024 }
2025 }
2026 let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
2027 self.set_imported_model_count(next_cnt);
2028 Ok(imported)
2029 }
2030
2031 pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
2042 let idx: usize = self.spawn_object(
2043 desc.get_name(),
2044 desc.get_mesh_id(),
2045 desc.get_transform(),
2046 desc.get_material(),
2047 desc.get_ray_trace_caster(),
2048 );
2049 if let Some(obj) = self.get_mut_objects().get_mut(idx) {
2050 obj.set_solid_collider(desc.get_solid_collider());
2051 obj.set_spin_speed(desc.get_spin_speed());
2052 }
2053 if desc.get_is_dynamic() || desc.get_spin_speed().abs() > 0.001 {
2054 let _: bool = self.set_object_dynamic(idx, true);
2055 }
2056 idx
2057 }
2058
2059 pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
2070 self.import_model(
2071 desc.get_format(),
2072 desc.get_source(),
2073 desc.get_transform(),
2074 desc.get_fallback_material(),
2075 desc.get_spin_speed(),
2076 )
2077 }
2078
2079 #[must_use]
2089 pub fn active_camera_mode(&self) -> CameraMode3D {
2090 CameraMode3D::from_u8(self.get_camera_mode())
2091 }
2092
2093 pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
2100 self.set_camera_mode(mode.as_u8());
2101 }
2102
2103 fn collect_caster_triangles(
2112 objects: &[SceneObject3D],
2113 mesh_library: &[MeshLodChain],
2114 dynamic_filter: bool,
2115 out_tris: &mut Vec<BvhTriangle>,
2116 ) {
2117 out_tris.clear();
2118 for obj in objects.iter() {
2119 if !obj.get_ray_trace_caster() || obj.get_is_dynamic() != dynamic_filter {
2120 continue;
2121 }
2122 let Some(chain) = mesh_library.get(obj.get_mesh_id()) else {
2123 continue;
2124 };
2125 let Some(mesh) = chain.get_levels().first() else {
2126 continue;
2127 };
2128 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
2129 let model_m: Mat4 = obj.get_transform().to_mat4();
2130 let mat: PbrMaterial = obj.get_material();
2131 for (tri_idx, tri) in mesh.get_indices().iter().enumerate() {
2132 let (i0, i1, i2): (usize, usize, usize) =
2133 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2134 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
2135 let p0: Vec3 = model_m.mul_point3(verts[i0].get_position());
2136 let p1: Vec3 = model_m.mul_point3(verts[i1].get_position());
2137 let p2: Vec3 = model_m.mul_point3(verts[i2].get_position());
2138 let (tri_mat, mat_slot): (PbrMaterial, u16) =
2139 mesh.resolve_triangle_material(tri_idx, mat);
2140 out_tris.push(BvhTriangle::from_points_with_slot(
2141 p0, p1, p2, tri_mat, mat_slot,
2142 ));
2143 }
2144 }
2145 }
2146 }
2147
2148 pub fn ensure_bvh(&mut self) {
2154 if self.get_bvh_dirty() {
2155 let mut static_tris: Vec<BvhTriangle> = Vec::new();
2156 Self::collect_caster_triangles(
2157 self.get_objects().as_slice(),
2158 self.get_mesh_library().as_slice(),
2159 false,
2160 &mut static_tris,
2161 );
2162 self.set_bvh(Bvh3D::build(static_tris));
2163 self.set_bvh_dirty(false);
2164 let next_static: u64 = self.get_static_bvh_rebuilds().saturating_add(1);
2165 self.set_static_bvh_rebuilds(next_static);
2166 }
2167 if self.get_dynamic_bvh_dirty() {
2168 let topology_dirty: bool = self.get_dynamic_topology_dirty();
2169 let Self {
2170 objects,
2171 mesh_library,
2172 dynamic_bvh,
2173 dynamic_tris_scratch,
2174 dynamic_bvh_dirty,
2175 dynamic_topology_dirty,
2176 dynamic_bvh_refits,
2177 dynamic_bvh_rebuilds,
2178 ..
2179 } = self;
2180 Self::collect_caster_triangles(
2181 objects.as_slice(),
2182 mesh_library.as_slice(),
2183 true,
2184 dynamic_tris_scratch,
2185 );
2186 let dyn_bvh: &mut Bvh3D = Arc::make_mut(dynamic_bvh);
2187 if dynamic_tris_scratch.is_empty() {
2188 dyn_bvh.rebuild_in_place(&[]);
2189 } else if !topology_dirty && dyn_bvh.refit_from_source(dynamic_tris_scratch.as_slice())
2190 {
2191 let check_degraded: bool = ((*dynamic_bvh_refits + 1) & 15) == 0;
2192 if check_degraded && dyn_bvh.needs_rebuild_after_refit(3.5) {
2193 dyn_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
2194 *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
2195 } else {
2196 *dynamic_bvh_refits = dynamic_bvh_refits.saturating_add(1);
2197 }
2198 } else {
2199 dyn_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
2200 *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
2201 }
2202 *dynamic_bvh_dirty = false;
2203 *dynamic_topology_dirty = false;
2204 }
2205 self.sync_dynamic_ray_instances();
2206 }
2207
2208 pub fn sync_dynamic_ray_instances(&mut self) {
2214 let Self {
2215 mesh_library,
2216 objects,
2217 mesh_local_bvhs,
2218 dynamic_instances,
2219 ..
2220 } = self;
2221 if mesh_local_bvhs.len() < mesh_library.len() {
2222 Arc::make_mut(mesh_local_bvhs).resize_with(mesh_library.len(), || None);
2223 }
2224 dynamic_instances.clear();
2225 for (obj_idx, obj) in objects.iter().enumerate() {
2226 if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
2227 continue;
2228 }
2229 let mesh_id: usize = obj.get_mesh_id();
2230 let Some(chain) = mesh_library.get(mesh_id) else {
2231 continue;
2232 };
2233 let Some(mesh) = chain.get_levels().first() else {
2234 continue;
2235 };
2236 if mesh_local_bvhs[mesh_id].is_none() {
2237 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
2238 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
2239 let mut local_tris: Vec<BvhTriangle> = Vec::with_capacity(indices.len());
2240 let neutral: PbrMaterial = PbrMaterial::default();
2241 for (tri_idx, tri) in indices.iter().enumerate() {
2242 let (i0, i1, i2): (usize, usize, usize) =
2243 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2244 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
2245 let (tri_mat, mat_slot): (PbrMaterial, u16) =
2246 mesh.resolve_triangle_material(tri_idx, neutral);
2247 local_tris.push(BvhTriangle::from_points_with_slot(
2248 verts[i0].get_position(),
2249 verts[i1].get_position(),
2250 verts[i2].get_position(),
2251 tri_mat,
2252 mat_slot,
2253 ));
2254 }
2255 }
2256 Arc::make_mut(mesh_local_bvhs)[mesh_id] = Some(Bvh3D::build(local_tris));
2257 }
2258 let transform_val: Transform3D = obj.get_transform();
2259 dynamic_instances.push(DynamicRayInstance {
2260 obj_idx,
2261 mesh_id,
2262 world_bounds: obj.get_world_bounds(),
2263 inv_model: transform_val.to_inv_mat4(),
2264 normal_basis: transform_val.normal_mat3(),
2265 material: obj.get_material(),
2266 });
2267 }
2268 }
2269
2270 pub(crate) fn override_dynamic_instance_pose(
2279 &mut self,
2280 obj_idx: usize,
2281 transform: Transform3D,
2282 world_bounds: AxisAlignedBox3D,
2283 ) {
2284 let Self {
2285 dynamic_instances, ..
2286 } = self;
2287 for inst in dynamic_instances.iter_mut() {
2288 if inst.obj_idx == obj_idx {
2289 inst.world_bounds = world_bounds;
2290 inst.inv_model = transform.to_inv_mat4();
2291 inst.normal_basis = transform.normal_mat3();
2292 return;
2293 }
2294 }
2295 }
2296
2297 #[inline(always)]
2311 #[must_use]
2312 pub(crate) fn trace_any_shadow_dynamic_instances(
2313 instances: &[DynamicRayInstance],
2314 local_bvhs: &[Option<Bvh3D>],
2315 ray: (Vec3, Vec3, Vec3),
2316 bounds: (f32, f32),
2317 dyn_cache: &mut u32,
2318 ) -> bool {
2319 let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2320 let (t_min, t_max): (f32, f32) = bounds;
2321 for inst in instances.iter() {
2322 if !inst
2323 .world_bounds
2324 .intersect_ray_near(origin, inv_dir, t_min, t_max)
2325 .is_finite()
2326 {
2327 continue;
2328 }
2329 let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
2330 continue;
2331 };
2332 let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
2333 let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
2334 let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
2335 if local_bvh
2336 .trace_any_shadow_cached(local_orig, local_dir, local_inv, t_min, t_max, dyn_cache)
2337 {
2338 return true;
2339 }
2340 }
2341 false
2342 }
2343
2344 #[inline(always)]
2360 #[must_use]
2361 pub(crate) fn trace_any_shadow_packet4_with_instances(
2362 static_bvh: &Bvh3D,
2363 instances: &[DynamicRayInstance],
2364 local_bvhs: &[Option<Bvh3D>],
2365 pkt: &RayPacket4,
2366 active_mask: u8,
2367 bounds: (f32, f32),
2368 caches: (&mut u32, &mut u32),
2369 ) -> u8 {
2370 let (t_min, t_max): (f32, f32) = bounds;
2371 let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
2372 let mut occluded: u8 =
2373 static_bvh.trace_any_shadow_packet4(pkt, active_mask, t_min, t_max, static_cache);
2374 let mut rem: u8 = active_mask & !occluded;
2375 if rem == 0 || instances.is_empty() {
2376 return occluded;
2377 }
2378 for inst in instances.iter() {
2379 let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
2380 continue;
2381 };
2382 let mut hit_box_mask: u8 = 0;
2383 let mut check: u8 = rem;
2384 while check != 0 {
2385 let red_val: usize = check.trailing_zeros() as usize;
2386 check &= check - 1;
2387 let orig_r: Vec3 = Vec3::new(pkt.ox[red_val], pkt.oy[red_val], pkt.oz[red_val]);
2388 let inv_r: Vec3 = Vec3::new(pkt.ix[red_val], pkt.iy[red_val], pkt.iz[red_val]);
2389 if inst
2390 .world_bounds
2391 .intersect_ray_near(orig_r, inv_r, t_min, t_max)
2392 .is_finite()
2393 {
2394 hit_box_mask |= 1_u8 << red_val;
2395 }
2396 }
2397 if hit_box_mask == 0 {
2398 continue;
2399 }
2400 let mut local_pkt: RayPacket4 = *pkt;
2401 let mut tr_mask: u8 = hit_box_mask;
2402 while tr_mask != 0 {
2403 let radius_val: usize = tr_mask.trailing_zeros() as usize;
2404 tr_mask &= tr_mask - 1;
2405 let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
2406 pkt.ox[radius_val],
2407 pkt.oy[radius_val],
2408 pkt.oz[radius_val],
2409 ));
2410 let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
2411 pkt.dx[radius_val],
2412 pkt.dy[radius_val],
2413 pkt.dz[radius_val],
2414 ));
2415 let li: Vec3 = Ray3D::safe_inv_vec(ld);
2416 local_pkt.ox[radius_val] = lo.get_x();
2417 local_pkt.oy[radius_val] = lo.get_y();
2418 local_pkt.oz[radius_val] = lo.get_z();
2419 local_pkt.dx[radius_val] = ld.get_x();
2420 local_pkt.dy[radius_val] = ld.get_y();
2421 local_pkt.dz[radius_val] = ld.get_z();
2422 local_pkt.ix[radius_val] = li.get_x();
2423 local_pkt.iy[radius_val] = li.get_y();
2424 local_pkt.iz[radius_val] = li.get_z();
2425 }
2426 let dyn_occ: u8 = local_bvh.trace_any_shadow_packet4(
2427 &local_pkt,
2428 hit_box_mask,
2429 t_min,
2430 t_max,
2431 dyn_cache,
2432 );
2433 occluded |= dyn_occ;
2434 rem &= !dyn_occ;
2435 if rem == 0 {
2436 break;
2437 }
2438 }
2439 occluded
2440 }
2441
2442 #[inline(always)]
2457 #[must_use]
2458 pub(crate) fn trace_any_shadow_with_instances(
2459 static_bvh: &Bvh3D,
2460 instances: &[DynamicRayInstance],
2461 local_bvhs: &[Option<Bvh3D>],
2462 ray: (Vec3, Vec3, Vec3),
2463 bounds: (f32, f32),
2464 caches: (&mut u32, &mut u32),
2465 ) -> bool {
2466 let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2467 let (t_min, t_max): (f32, f32) = bounds;
2468 let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
2469 if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
2470 return true;
2471 }
2472 if !instances.is_empty() {
2473 return Self::trace_any_shadow_dynamic_instances(
2474 instances, local_bvhs, ray, bounds, dyn_cache,
2475 );
2476 }
2477 false
2478 }
2479
2480 #[inline(always)]
2494 #[must_use]
2495 pub(crate) fn trace_closest_with_instances(
2496 static_bvh: &Bvh3D,
2497 instances: &[DynamicRayInstance],
2498 local_bvhs: &[Option<Bvh3D>],
2499 ray: (Vec3, Vec3, Vec3),
2500 bounds: (f32, f32),
2501 ) -> Option<(f32, Vec3, PbrMaterial)> {
2502 let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2503 let (t_min, t_max): (f32, f32) = bounds;
2504 let mut best_t: f32 = t_max;
2505 let mut best_hit: Option<(f32, Vec3, PbrMaterial)> = static_bvh
2506 .trace_closest_raw(origin, dir, inv_dir, t_min, t_max)
2507 .map(|(node_style, si): (f32, usize)| {
2508 let tri: &BvhTriangle = &static_bvh.get_triangles()[si];
2509 best_t = node_style;
2510 (node_style, tri.get_normal(), tri.get_material())
2511 });
2512 for inst in instances.iter() {
2513 if !inst
2514 .world_bounds
2515 .intersect_ray_near(origin, inv_dir, t_min, best_t)
2516 .is_finite()
2517 {
2518 continue;
2519 }
2520 let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
2521 continue;
2522 };
2523 let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
2524 let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
2525 let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
2526 if let Some((dt, di)) =
2527 local_bvh.trace_closest_raw(local_orig, local_dir, local_inv, t_min, best_t)
2528 {
2529 best_t = dt;
2530 let hit_tri: &BvhTriangle = &local_bvh.get_triangles()[di];
2531 let local_n: Vec3 = hit_tri.get_normal();
2532 let world_n: Vec3 = Mat4::transform_normal_with_basis(local_n, inst.normal_basis);
2533 let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
2534 inst.material
2535 } else {
2536 hit_tri.get_material()
2537 };
2538 best_hit = Some((dt, world_n, hit_mat));
2539 }
2540 }
2541 best_hit
2542 }
2543
2544 #[inline(always)]
2559 #[must_use]
2560 pub(crate) fn trace_closest_packet4_with_instances(
2561 static_bvh: &Bvh3D,
2562 instances: &[DynamicRayInstance],
2563 local_bvhs: &[Option<Bvh3D>],
2564 pkt: &RayPacket4,
2565 active_mask: u8,
2566 bounds: (f32, f32),
2567 ) -> [Option<(f32, Vec3, PbrMaterial)>; 4] {
2568 let (t_min, t_max): (f32, f32) = bounds;
2569 let mut best_t: [f32; 4] = [t_max; 4];
2570 let mut best_static_idx: [usize; 4] = [usize::MAX; 4];
2571 static_bvh.trace_closest_packet4(
2572 pkt,
2573 active_mask,
2574 t_min,
2575 &mut best_t,
2576 &mut best_static_idx,
2577 );
2578 let static_tris: &[BvhTriangle] = static_bvh.get_triangles().as_slice();
2579 let mut out: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
2580 let mut matrix_elems: u8 = active_mask;
2581 while matrix_elems != 0 {
2582 let red_val: usize = matrix_elems.trailing_zeros() as usize;
2583 matrix_elems &= matrix_elems - 1;
2584 let sidx: usize = best_static_idx[red_val];
2585 if sidx != usize::MAX {
2586 let tri: &BvhTriangle = &static_tris[sidx];
2587 out[red_val] = Some((best_t[red_val], tri.get_normal(), tri.get_material()));
2588 }
2589 }
2590 for inst in instances.iter() {
2591 let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
2592 continue;
2593 };
2594 let mut hit_box_mask: u8 = 0;
2595 let mut check: u8 = active_mask;
2596 while check != 0 {
2597 let radius_val: usize = check.trailing_zeros() as usize;
2598 check &= check - 1;
2599 if inst
2600 .world_bounds
2601 .intersect_ray_near(
2602 Vec3::new(pkt.ox[radius_val], pkt.oy[radius_val], pkt.oz[radius_val]),
2603 Vec3::new(pkt.ix[radius_val], pkt.iy[radius_val], pkt.iz[radius_val]),
2604 t_min,
2605 best_t[radius_val],
2606 )
2607 .is_finite()
2608 {
2609 hit_box_mask |= 1_u8 << radius_val;
2610 }
2611 }
2612 if hit_box_mask == 0 {
2613 continue;
2614 }
2615 let mut local_pkt: RayPacket4 = *pkt;
2616 let mut tr_mask: u8 = hit_box_mask;
2617 while tr_mask != 0 {
2618 let rect_val: usize = tr_mask.trailing_zeros() as usize;
2619 tr_mask &= tr_mask - 1;
2620 let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
2621 pkt.ox[rect_val],
2622 pkt.oy[rect_val],
2623 pkt.oz[rect_val],
2624 ));
2625 let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
2626 pkt.dx[rect_val],
2627 pkt.dy[rect_val],
2628 pkt.dz[rect_val],
2629 ));
2630 let li: Vec3 = Ray3D::safe_inv_vec(ld);
2631 local_pkt.ox[rect_val] = lo.get_x();
2632 local_pkt.oy[rect_val] = lo.get_y();
2633 local_pkt.oz[rect_val] = lo.get_z();
2634 local_pkt.dx[rect_val] = ld.get_x();
2635 local_pkt.dy[rect_val] = ld.get_y();
2636 local_pkt.dz[rect_val] = ld.get_z();
2637 local_pkt.ix[rect_val] = li.get_x();
2638 local_pkt.iy[rect_val] = li.get_y();
2639 local_pkt.iz[rect_val] = li.get_z();
2640 }
2641 let mut dyn_idx: [usize; 4] = [usize::MAX; 4];
2642 local_bvh.trace_closest_packet4(
2643 &local_pkt,
2644 hit_box_mask,
2645 t_min,
2646 &mut best_t,
2647 &mut dyn_idx,
2648 );
2649 let local_tris: &[BvhTriangle] = local_bvh.get_triangles().as_slice();
2650 let mut upd: u8 = hit_box_mask;
2651 while upd != 0 {
2652 let row_val: usize = upd.trailing_zeros() as usize;
2653 upd &= upd - 1;
2654 let di: usize = dyn_idx[row_val];
2655 if di != usize::MAX {
2656 let hit_tri: &BvhTriangle = &local_tris[di];
2657 let wn: Vec3 =
2658 Mat4::transform_normal_with_basis(hit_tri.get_normal(), inst.normal_basis);
2659 let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
2660 inst.material
2661 } else {
2662 hit_tri.get_material()
2663 };
2664 out[row_val] = Some((best_t[row_val], wn, hit_mat));
2665 }
2666 }
2667 }
2668 out
2669 }
2670
2671 #[must_use]
2684 pub fn trace_any_shadow_object_space(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
2685 let Self {
2686 bvh,
2687 dynamic_instances,
2688 mesh_local_bvhs,
2689 ..
2690 } = self;
2691 let mut scale_factor: u32 = u32::MAX;
2692 let mut dc: u32 = u32::MAX;
2693 Self::trace_any_shadow_with_instances(
2694 bvh.as_ref(),
2695 dynamic_instances.as_slice(),
2696 mesh_local_bvhs.as_slice(),
2697 (
2698 ray.get_origin(),
2699 ray.get_direction(),
2700 ray.get_inv_direction(),
2701 ),
2702 (t_min, t_max),
2703 (&mut scale_factor, &mut dc),
2704 )
2705 }
2706
2707 #[must_use]
2721 pub fn trace_closest_packet4(
2722 &self,
2723 pkt: &RayPacket4,
2724 active_mask: u8,
2725 t_min: f32,
2726 t_max: f32,
2727 ) -> [Option<RayHit3D>; 4] {
2728 let Self {
2729 bvh,
2730 dynamic_instances,
2731 mesh_local_bvhs,
2732 ..
2733 } = self;
2734 let raw: [Option<(f32, Vec3, PbrMaterial)>; 4] = Self::trace_closest_packet4_with_instances(
2735 bvh.as_ref(),
2736 dynamic_instances.as_slice(),
2737 mesh_local_bvhs.as_slice(),
2738 pkt,
2739 active_mask,
2740 (t_min, t_max),
2741 );
2742 let mut out: [Option<RayHit3D>; 4] = [None; 4];
2743 for lane in 0..4 {
2744 if let Some((blend_factor, normal, material)) = raw[lane] {
2745 let point: Vec3 = Vec3::new(
2746 pkt.ox[lane] + pkt.dx[lane] * blend_factor,
2747 pkt.oy[lane] + pkt.dy[lane] * blend_factor,
2748 pkt.oz[lane] + pkt.dz[lane] * blend_factor,
2749 );
2750 out[lane] = Some(RayHit3D {
2751 distance: blend_factor,
2752 point,
2753 normal,
2754 material,
2755 });
2756 }
2757 }
2758 out
2759 }
2760
2761 #[must_use]
2774 pub fn trace_closest_object_space(
2775 &self,
2776 ray: &Ray3D,
2777 t_min: f32,
2778 t_max: f32,
2779 ) -> Option<RayHit3D> {
2780 let Self {
2781 bvh,
2782 dynamic_instances,
2783 mesh_local_bvhs,
2784 ..
2785 } = self;
2786 let (blend_factor, normal, material): (f32, Vec3, PbrMaterial) =
2787 Self::trace_closest_with_instances(
2788 bvh.as_ref(),
2789 dynamic_instances.as_slice(),
2790 mesh_local_bvhs.as_slice(),
2791 (
2792 ray.get_origin(),
2793 ray.get_direction(),
2794 ray.get_inv_direction(),
2795 ),
2796 (t_min, t_max),
2797 )?;
2798 Some(RayHit3D {
2799 distance: blend_factor,
2800 point: ray
2801 .get_origin()
2802 .add(ray.get_direction().scale(blend_factor)),
2803 normal,
2804 material,
2805 })
2806 }
2807
2808 #[must_use]
2818 pub fn total_bvh_nodes(&self) -> usize {
2819 self.get_bvh()
2820 .get_nodes()
2821 .len()
2822 .saturating_add(self.get_dynamic_bvh().get_nodes().len())
2823 }
2824
2825 #[must_use]
2838 pub fn trace_any_shadow_split(
2839 bvhs: (&Bvh3D, &Bvh3D),
2840 ray: (Vec3, Vec3, Vec3),
2841 bounds: (f32, f32),
2842 caches: (&mut u32, &mut u32),
2843 ) -> bool {
2844 let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2845 let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2846 let (t_min, t_max): (f32, f32) = bounds;
2847 let (static_cache, dynamic_cache): (&mut u32, &mut u32) = caches;
2848 if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
2849 return true;
2850 }
2851 if !dynamic_bvh.is_empty() {
2852 return dynamic_bvh.trace_any_shadow_cached(
2853 origin,
2854 dir,
2855 inv_dir,
2856 t_min,
2857 t_max,
2858 dynamic_cache,
2859 );
2860 }
2861 false
2862 }
2863
2864 #[must_use]
2876 pub fn trace_closest_split(
2877 bvhs: (&Bvh3D, &Bvh3D),
2878 ray: (Vec3, Vec3, Vec3),
2879 bounds: (f32, f32),
2880 ) -> Option<(f32, bool, usize)> {
2881 let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2882 let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2883 let (t_min, t_max): (f32, f32) = bounds;
2884 let static_hit: Option<(f32, usize)> =
2885 static_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, t_max);
2886 let dyn_limit: f32 =
2887 static_hit.map_or(t_max, |(blend_factor, _): (f32, usize)| blend_factor);
2888 let dynamic_hit: Option<(f32, usize)> = if !dynamic_bvh.is_empty() {
2889 dynamic_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, dyn_limit)
2890 } else {
2891 None
2892 };
2893 match (static_hit, dynamic_hit) {
2894 (_, Some((dt, di))) => Some((dt, true, di)),
2895 (Some((node_style, si)), None) => Some((node_style, false, si)),
2896 (None, None) => None,
2897 }
2898 }
2899
2900 #[must_use]
2910 pub fn vehicle_index(&self) -> Option<usize> {
2911 let Self {
2912 player_vehicle_index,
2913 ..
2914 } = self;
2915 *player_vehicle_index
2916 }
2917
2918 #[must_use]
2929 pub fn loop_lateral_offset(world_x: f32, world_z: f32) -> (f32, f32) {
2930 let spine_z: f32 = world_z.clamp(-CITY_LOOP_STRAIGHT_HALF_Z, CITY_LOOP_STRAIGHT_HALF_Z);
2931 let dx: f32 = world_x - CITY_LOOP_CENTER_X;
2932 let dz: f32 = world_z - spine_z;
2933 let d_spine: f32 = dx.hypot(dz);
2934 (d_spine, d_spine - CITY_LOOP_RADIUS)
2935 }
2936
2937 #[must_use]
2948 pub fn loop_pose_at(arc_s: f32, lateral_u: f32) -> (Vec3, f32) {
2949 let straight_len: f32 = 2.0 * CITY_LOOP_STRAIGHT_HALF_Z;
2950 let arc_len: f32 = PI * CITY_LOOP_RADIUS;
2951 let s: f32 = arc_s.rem_euclid(CITY_LOOP_TOTAL_LENGTH);
2952 if s < straight_len {
2953 let world_x: f32 = -lateral_u;
2954 let world_z: f32 = CITY_LOOP_STRAIGHT_HALF_Z - s;
2955 (Vec3::new(world_x, 0.0, world_z), 0.0)
2956 } else if s < straight_len + arc_len {
2957 let alpha: f32 = (s - straight_len) / CITY_LOOP_RADIUS;
2958 let radius: f32 = CITY_LOOP_RADIUS + lateral_u;
2959 let (sin_a, cos_a): (f32, f32) = alpha.sin_cos();
2960 let world_x: f32 = CITY_LOOP_CENTER_X - radius * cos_a;
2961 let world_z: f32 = -CITY_LOOP_STRAIGHT_HALF_Z - radius * sin_a;
2962 (Vec3::new(world_x, 0.0, world_z), -alpha)
2963 } else if s < 2.0 * straight_len + arc_len {
2964 let east_s: f32 = s - (straight_len + arc_len);
2965 let world_x: f32 = CITY_LOOP_CENTER_X * 2.0 + lateral_u;
2966 let world_z: f32 = -CITY_LOOP_STRAIGHT_HALF_Z + east_s;
2967 (Vec3::new(world_x, 0.0, world_z), PI)
2968 } else {
2969 let beta: f32 = (s - (2.0 * straight_len + arc_len)) / CITY_LOOP_RADIUS;
2970 let radius: f32 = CITY_LOOP_RADIUS + lateral_u;
2971 let (sin_b, cos_b): (f32, f32) = beta.sin_cos();
2972 let world_x: f32 = CITY_LOOP_CENTER_X + radius * cos_b;
2973 let world_z: f32 = CITY_LOOP_STRAIGHT_HALF_Z + radius * sin_b;
2974 (Vec3::new(world_x, 0.0, world_z), PI - beta)
2975 }
2976 }
2977
2978 #[must_use]
2984 fn curated_skyline_palettes() -> [PbrMaterial; 6] {
2985 [
2986 PbrMaterial::pbr(Color::hex(0x9E8C73), 0.24, 0.36, 0.38)
2987 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2988 PbrMaterial::pbr(Color::hex(0x163C6B), 0.78, 0.12, 0.76)
2989 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2990 PbrMaterial::pbr(Color::hex(0x141D2D), 0.86, 0.10, 0.82)
2991 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2992 PbrMaterial::pbr(Color::hex(0x7B4232), 0.20, 0.42, 0.32)
2993 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2994 PbrMaterial::pbr(Color::hex(0x0E4B47), 0.74, 0.14, 0.72)
2995 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2996 PbrMaterial::pbr(Color::hex(0x64748B), 0.82, 0.18, 0.70)
2997 .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2998 ]
2999 }
3000
3001 fn register_building_archetypes(&mut self) -> [usize; 6] {
3007 let base_mat: PbrMaterial = PbrMaterial::default();
3008 let art_deco: usize = self.register_mesh(MeshLodChain::from_mesh(
3009 Mesh3D::building_art_deco_tower(CITY_MESH_ART_DECO, base_mat),
3010 ));
3011 let chamfered: usize = self.register_mesh(MeshLodChain::from_mesh(
3012 Mesh3D::building_chamfered_glass_tower(CITY_MESH_CHAMFERED, base_mat),
3013 ));
3014 let twisted: usize = self.register_mesh(MeshLodChain::from_mesh(
3015 Mesh3D::building_twisted_spire_tower(CITY_MESH_TWISTED, base_mat),
3016 ));
3017 let cantilever: usize = self.register_mesh(MeshLodChain::from_mesh(
3018 Mesh3D::building_cantilever_tech_tower(CITY_MESH_CANTILEVER, base_mat),
3019 ));
3020 let cylinder: usize = self.register_mesh(MeshLodChain::from_mesh(
3021 Mesh3D::building_cylindrical_landmark(CITY_MESH_CYLINDER, base_mat),
3022 ));
3023 let boutique: usize = self.register_mesh(MeshLodChain::from_mesh(
3024 Mesh3D::building_boutique_podium_block(CITY_MESH_BOUTIQUE, base_mat),
3025 ));
3026 [art_deco, chamfered, twisted, cantilever, cylinder, boutique]
3027 }
3028
3029 #[must_use]
3039 pub fn hero_vehicle_material(style: HeroVehicleStyle) -> PbrMaterial {
3040 match style {
3041 HeroVehicleStyle::AventadorV12 => {
3042 PbrMaterial::pbr(Color::hex(0xFF4500), 0.30, 0.12, 0.42)
3043 }
3044 HeroVehicleStyle::ShelbyCobra => {
3045 PbrMaterial::pbr(Color::hex(0x0A3EC2), 0.30, 0.12, 0.40)
3046 }
3047 }
3048 }
3049
3050 pub fn set_hero_vehicle_style(&mut self, style: HeroVehicleStyle) -> bool {
3061 let Some(car_idx) = self.vehicle_index() else {
3062 self.set_hero_vehicle_style_raw(style);
3063 return false;
3064 };
3065 let slot_idx: usize = match style {
3066 HeroVehicleStyle::AventadorV12 => 0,
3067 HeroVehicleStyle::ShelbyCobra => 1,
3068 };
3069 let cached_entry: Option<(usize, PbrMaterial)> = {
3070 let Self {
3071 hero_vehicle_meshes,
3072 ..
3073 } = self;
3074 hero_vehicle_meshes[slot_idx]
3075 };
3076 let (target_mesh_id, target_mat): (usize, PbrMaterial) = if let Some(pair) = cached_entry {
3077 pair
3078 } else {
3079 let sig_mat: PbrMaterial = Self::hero_vehicle_material(style);
3080 let built_mesh: Mesh3D = match style {
3081 HeroVehicleStyle::AventadorV12 => {
3082 build_lamborghini_chassis_mesh(CITY_MESH_AVENTADOR, sig_mat)
3083 }
3084 HeroVehicleStyle::ShelbyCobra => {
3085 build_mustang_s650_chassis_mesh(CITY_MESH_SHELBY, sig_mat)
3086 }
3087 };
3088 let new_mesh_id: usize = self.register_mesh(MeshLodChain::single_level(built_mesh));
3089 let Self {
3090 hero_vehicle_meshes,
3091 ..
3092 } = self;
3093 hero_vehicle_meshes[slot_idx] = Some((new_mesh_id, sig_mat));
3094 (new_mesh_id, sig_mat)
3095 };
3096 let already_active: bool = self.get_hero_vehicle_style() == style
3097 && self
3098 .get_objects()
3099 .get(car_idx)
3100 .is_some_and(|obj: &SceneObject3D| obj.get_mesh_id() == target_mesh_id);
3101 if already_active {
3102 return false;
3103 }
3104 let new_local_bounds: AxisAlignedBox3D = self
3105 .get_mesh_library()
3106 .get(target_mesh_id)
3107 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
3108 .map(Mesh3D::get_bounds)
3109 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.2), Vec3::splat(1.2)));
3110 let mut live_car_tr: Transform3D = Transform3D::default();
3111 if let Some(car_obj) = self.get_mut_objects().get_mut(car_idx) {
3112 let live_tr: Transform3D = car_obj.get_transform();
3113 live_car_tr = live_tr;
3114 car_obj.set_mesh_id(target_mesh_id);
3115 car_obj.set_material(target_mat);
3116 car_obj.set_world_bounds(live_tr.transform_bounds(new_local_bounds));
3117 }
3118 let cached_wheel_pair: Option<(usize, PbrMaterial)> = {
3119 let Self {
3120 hero_wheel_meshes, ..
3121 } = self;
3122 hero_wheel_meshes[slot_idx]
3123 };
3124 let target_wheel_pair: (usize, PbrMaterial) = if let Some(pair) = cached_wheel_pair {
3125 pair
3126 } else {
3127 let built_wheel: Mesh3D = match style {
3128 HeroVehicleStyle::AventadorV12 => {
3129 build_lamborghini_wheel_mesh(WHEEL_MESH_LAMBORGHINI)
3130 }
3131 HeroVehicleStyle::ShelbyCobra => build_mustang_s650_wheel_mesh(WHEEL_MESH_MUSTANG),
3132 };
3133 let wheel_mat: PbrMaterial = built_wheel.get_material();
3134 let new_wheel_id: usize = self.register_mesh(MeshLodChain::single_level(built_wheel));
3135 let Self {
3136 hero_wheel_meshes, ..
3137 } = self;
3138 hero_wheel_meshes[slot_idx] = Some((new_wheel_id, wheel_mat));
3139 (new_wheel_id, wheel_mat)
3140 };
3141 let player_wheels: [Option<usize>; 4] = {
3142 let Self {
3143 player_wheel_objects,
3144 ..
3145 } = self;
3146 *player_wheel_objects
3147 };
3148 let (w_mesh_id, w_mat): (usize, PbrMaterial) = target_wheel_pair;
3149 for wheel_opt in player_wheels.into_iter().flatten() {
3150 if let Some(wheel_obj) = self.get_mut_objects().get_mut(wheel_opt) {
3151 wheel_obj.set_mesh_id(w_mesh_id);
3152 wheel_obj.set_material(w_mat);
3153 }
3154 }
3155 self.set_hero_vehicle_style_raw(style);
3156 let (spin_now, steer_now): (f32, f32) =
3157 (self.player_wheel_spin_rad(), self.player_front_steer_rad());
3158 let layout: VehicleWheelLayout3D = Self::hero_wheel_layout(style);
3159 let _: bool = self.sync_vehicle_wheel_transforms(
3160 player_wheels,
3161 (
3162 live_car_tr.get_position(),
3163 live_car_tr.get_yaw_rad(),
3164 live_car_tr.get_scale().get_x().max(0.5),
3165 ),
3166 layout,
3167 (spin_now, steer_now),
3168 true,
3169 );
3170 self.set_dynamic_topology_dirty(true);
3171 self.set_dynamic_bvh_dirty(true);
3172 self.sync_dynamic_ray_instances();
3173 self.bump_world_revision();
3174 true
3175 }
3176
3177 fn set_hero_vehicle_style_raw(&mut self, style: HeroVehicleStyle) {
3184 let Self {
3185 hero_vehicle_style, ..
3186 } = self;
3187 *hero_vehicle_style = style;
3188 }
3189
3190 #[must_use]
3196 fn build_open_world_city_template() -> OpenWorldCityTemplate3D {
3197 let world: Self = Self::build_open_world_city_uncached();
3198 let rev: u64 = Self::allocate_gpu_mesh_revision();
3199 let (gpu_mesh_buffer, gpu_mesh_ranges): (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) =
3200 world.build_gpu_mesh_buffer(rev);
3201 OpenWorldCityTemplate3D {
3202 world,
3203 gpu_mesh_buffer,
3204 gpu_mesh_ranges,
3205 }
3206 }
3207
3208 fn with_open_world_city_template<F, R>(visitor: F) -> R
3218 where
3219 F: FnOnce(&OpenWorldCityTemplate3D) -> R,
3220 {
3221 #[cfg(not(target_arch = "wasm32"))]
3222 {
3223 let tpl: &OpenWorldCityTemplate3D =
3224 OPEN_WORLD_CITY_TEMPLATE.get_or_init(Self::build_open_world_city_template);
3225 visitor(tpl)
3226 }
3227 #[cfg(target_arch = "wasm32")]
3228 {
3229 OPEN_WORLD_CITY_TEMPLATE_WASM.with(
3230 |slot: &RefCell<Option<OpenWorldCityTemplate3D>>| -> R {
3231 if let Ok(mut guard) = slot.try_borrow_mut() {
3232 if guard.is_none() {
3233 *guard = Some(Self::build_open_world_city_template());
3234 }
3235 if let Some(tpl) = guard.as_ref() {
3236 return visitor(tpl);
3237 }
3238 }
3239 let fallback: OpenWorldCityTemplate3D = Self::build_open_world_city_template();
3240 visitor(&fallback)
3241 },
3242 )
3243 }
3244 }
3245
3246 #[must_use]
3252 pub fn create_open_world_city() -> Self {
3253 Self::with_open_world_city_template(|tpl: &OpenWorldCityTemplate3D| tpl.world.clone())
3254 }
3255
3256 #[must_use]
3262 pub fn create_open_world_city_with_gpu_cache()
3263 -> (Self, Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) {
3264 Self::with_open_world_city_template(|tpl: &OpenWorldCityTemplate3D| {
3265 (
3266 tpl.world.clone(),
3267 Arc::clone(&tpl.gpu_mesh_buffer),
3268 tpl.gpu_mesh_ranges.clone(),
3269 )
3270 })
3271 }
3272
3273 #[must_use]
3279 fn build_open_world_city_uncached() -> Self {
3280 let mut world: Self = Self::default();
3281 world.get_mut_mesh_library().reserve(16);
3282 world.get_mut_objects().reserve(144);
3283 world.get_mut_point_lights().reserve(16);
3284 world.get_mut_spot_lights().reserve(4);
3285 {
3286 let Self {
3287 traffic_vehicles, ..
3288 } = &mut world;
3289 traffic_vehicles.reserve(8);
3290 }
3291 let ground_w: f32 = CITY_GROUND_X_MAX - CITY_GROUND_X_MIN;
3292 let ground_d: f32 = CITY_GROUND_Z_MAX - CITY_GROUND_Z_MIN;
3293 let ground_cx: f32 = (CITY_GROUND_X_MIN + CITY_GROUND_X_MAX) * 0.5;
3294 let ground_cz: f32 = (CITY_GROUND_Z_MIN + CITY_GROUND_Z_MAX) * 0.5;
3295 let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0E131C), 0.08, 0.24, 0.62)
3296 .with_surface_detail(SurfaceDetailMode::RoadSurface);
3297 let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
3298 CITY_GROUND_MESH_NAME,
3299 ground_w,
3300 ground_d,
3301 24,
3302 asphalt_mat,
3303 )));
3304 let road_ground_idx: usize = world.spawn_object(
3305 CITY_GROUND_OBJ_NAME,
3306 road_mesh,
3307 Transform3D::new(Vec3::new(ground_cx, 0.0, ground_cz), 0.0, Vec3::splat(1.0)),
3308 asphalt_mat,
3309 false,
3310 );
3311 {
3312 let Self {
3313 road_ground_object_index,
3314 ..
3315 } = &mut world;
3316 *road_ground_object_index = Some(road_ground_idx);
3317 }
3318 let ocean_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x063846), 0.05, 0.06, 0.86)
3319 .with_surface_detail(SurfaceDetailMode::OceanWater);
3320 let ocean_mesh: usize =
3321 world.register_mesh(MeshLodChain::from_mesh(Mesh3D::coastal_ocean_ring(
3322 CITY_OCEAN_MESH_NAME,
3323 CITY_OCEAN_SPAN_M,
3324 ground_w * 0.5,
3325 ground_d * 0.5,
3326 24,
3327 ocean_mat,
3328 )));
3329 let _: usize = world.spawn_object(
3330 CITY_OCEAN_MESH_NAME,
3331 ocean_mesh,
3332 Transform3D::new(
3333 Vec3::new(ground_cx, CITY_OCEAN_SURFACE_Y, ground_cz),
3334 0.0,
3335 Vec3::splat(1.0),
3336 ),
3337 ocean_mat,
3338 false,
3339 );
3340 let stud_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFBBF24), 0.90);
3341 let stud_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
3342 CITY_LANE_STUD_MESH_NAME,
3343 0.10,
3344 0.018,
3345 0.16,
3346 true,
3347 stud_mat,
3348 )));
3349 for iz in -7..=0 {
3350 let _: usize = world.spawn_object(
3351 &format!("stripe_{iz}"),
3352 stud_mesh,
3353 Transform3D::new(
3354 Vec3::new(0.0, 0.008, (iz as f32) * 14.0),
3355 0.0,
3356 Vec3::splat(1.0),
3357 ),
3358 stud_mat,
3359 false,
3360 );
3361 }
3362 let unit_box: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
3363 CITY_UNIT_BOX_MESH_NAME,
3364 1.0,
3365 1.0,
3366 1.0,
3367 true,
3368 PbrMaterial::default(),
3369 )));
3370 let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
3371 CITY_NEON_SIGN_MESH_NAME,
3372 1.0,
3373 1.0,
3374 1.0,
3375 true,
3376 PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
3377 )));
3378 let archetypes: [usize; 6] = world.register_building_archetypes();
3379 let palettes: [PbrMaterial; 6] = Self::curated_skyline_palettes();
3380 let neon_colors: [Color; 4] = [
3381 Color::hex(0x38BDF8),
3382 Color::hex(0xF43F5E),
3383 Color::hex(0xA855F7),
3384 Color::hex(0x34D399),
3385 ];
3386 let west_pattern: [(usize, f32, f32, f32); 9] = [
3387 (0, 46.0, 11.2, 12.0),
3388 (5, 20.0, 11.6, 12.4),
3389 (1, 38.0, 11.0, 11.8),
3390 (3, 34.0, 10.6, 11.8),
3391 (4, 48.0, 11.4, 11.4),
3392 (5, 22.0, 11.4, 12.2),
3393 (2, 54.0, 11.2, 11.2),
3394 (1, 40.0, 10.8, 12.0),
3395 (0, 44.0, 11.0, 11.6),
3396 ];
3397 let mut idx_counter: usize = 0;
3398 for side in [-1.0_f32, 1.0_f32] {
3399 for (row_i, row_z_idx) in (-4..=4_i32).enumerate() {
3400 let (base_arch, base_h, width_val, depth_val): (usize, f32, f32, f32) =
3401 west_pattern[(row_i + if side > 0.0 { 2 } else { 0 }) % west_pattern.len()];
3402 let pos_z: f32 = (row_z_idx as f32) * 28.0 - 4.0;
3403 let pos_x: f32 = side * (22.0 + ((idx_counter % 3) as f32) * 1.1);
3404 let height_val: f32 = if side > 0.0 && base_arch != 5 {
3405 base_h + 4.0
3406 } else {
3407 base_h
3408 };
3409 let mat: PbrMaterial = palettes[(idx_counter * 5 + row_i) % palettes.len()];
3410 let _: usize = world.spawn_object(
3411 &format!("tower_{idx_counter}"),
3412 archetypes[base_arch],
3413 Transform3D::new(
3414 Vec3::new(pos_x, 0.0, pos_z),
3415 0.0,
3416 Vec3::new(width_val, height_val, depth_val),
3417 ),
3418 mat,
3419 true,
3420 );
3421 idx_counter += 1;
3422 }
3423 }
3424 let inner_spine_specs: [(f32, f32, f32, f32, f32, usize, usize); 19] = [
3425 (64.0, -158.0, 14.0, 56.0, 14.0, 4, 1),
3426 (64.0, -116.0, 14.5, 68.0, 14.5, 0, 0),
3427 (54.0, -76.0, 13.0, 62.0, 13.0, 2, 2),
3428 (76.0, -76.0, 13.0, 52.0, 13.0, 1, 4),
3429 (64.0, -34.0, 15.0, 74.0, 15.0, 2, 5),
3430 (52.0, 10.0, 13.5, 58.0, 13.5, 3, 3),
3431 (78.0, 12.0, 13.5, 64.0, 13.5, 4, 1),
3432 (64.0, 56.0, 14.5, 70.0, 14.5, 0, 0),
3433 (54.0, 98.0, 13.0, 54.0, 13.0, 1, 2),
3434 (76.0, 100.0, 13.0, 48.0, 13.0, 3, 4),
3435 (64.0, 156.0, 14.0, 58.0, 14.0, 4, 5),
3436 (103.5, -112.0, 11.4, 34.0, 12.4, 5, 0),
3437 (103.5, -78.0, 11.6, 48.0, 11.6, 4, 4),
3438 (103.5, -44.0, 11.4, 24.0, 12.2, 5, 3),
3439 (103.5, -10.0, 11.8, 44.0, 12.0, 1, 1),
3440 (103.5, 24.0, 11.4, 38.0, 12.0, 3, 5),
3441 (103.5, 58.0, 11.6, 22.0, 12.2, 5, 0),
3442 (103.5, 92.0, 11.8, 46.0, 11.8, 0, 2),
3443 (103.5, 124.0, 11.4, 40.0, 11.4, 2, 4),
3444 ];
3445 for (l_idx, &(lx, lz, lw, lh, ld, l_arch, l_pal)) in inner_spine_specs.iter().enumerate() {
3446 let _: usize = world.spawn_object(
3447 &format!("landmark_tower_{l_idx}"),
3448 archetypes[l_arch],
3449 Transform3D::new(Vec3::new(lx, 0.0, lz), 0.0, Vec3::new(lw, lh, ld)),
3450 palettes[l_pal],
3451 true,
3452 );
3453 }
3454 let skyline_specs: [(f32, f32, f32, f32, usize, usize); 6] = [
3455 (-46.0, -96.0, 13.0, 56.0, 0, 2),
3456 (-46.0, -64.0, 12.5, 66.0, 2, 1),
3457 (-46.0, -32.0, 13.0, 52.0, 4, 4),
3458 (-46.0, 4.0, 12.5, 62.0, 1, 5),
3459 (-46.0, 40.0, 12.5, 50.0, 3, 3),
3460 (-46.0, 76.0, 13.0, 58.0, 0, 0),
3461 ];
3462 for (sky_idx, &(sx, sz, sw, sh, s_arch, s_pal)) in skyline_specs.iter().enumerate() {
3463 let _: usize = world.spawn_object(
3464 &format!("{CITY_SKYLINE_MESH_NAME}_{sky_idx}"),
3465 archetypes[s_arch],
3466 Transform3D::new(Vec3::new(sx, 0.0, sz), 0.0, Vec3::new(sw, sh, 13.0)),
3467 palettes[s_pal],
3468 true,
3469 );
3470 }
3471 let mut rim_serial: usize = 0;
3472 let rim_angles_deg: [f32; 7] = [44.0, 64.0, 84.0, 104.0, 124.0, 144.0, 164.0];
3473 for (turn_idx, &turn_sign_z) in [-1.0_f32, 1.0_f32].iter().enumerate() {
3474 let center_z: f32 = turn_sign_z * CITY_LOOP_STRAIGHT_HALF_Z;
3475 for (ang_i, °) in rim_angles_deg.iter().enumerate() {
3476 let rad: f32 = deg.to_radians();
3477 let (sin_a, cos_a): (f32, f32) = rad.sin_cos();
3478 let ring_r: f32 = 99.0 + ((ang_i % 2) as f32) * 3.5;
3479 let rx: f32 = CITY_LOOP_CENTER_X + ring_r * cos_a;
3480 let rz: f32 = center_z + turn_sign_z * ring_r * sin_a;
3481 let yaw_rim: f32 = if turn_sign_z < 0.0 {
3482 rad - FRAC_PI_2
3483 } else {
3484 FRAC_PI_2 - rad
3485 };
3486 let arch_i: usize = (rim_serial + turn_idx * 2) % archetypes.len();
3487 let height_m: f32 = if arch_i == 5 {
3488 24.0
3489 } else {
3490 36.0 + ((rim_serial * 7) % 4) as f32 * 8.0
3491 };
3492 let _: usize = world.spawn_object(
3493 &format!("rim_tower_{rim_serial}"),
3494 archetypes[arch_i],
3495 Transform3D::new(
3496 Vec3::new(rx, 0.0, rz),
3497 yaw_rim,
3498 Vec3::new(11.5, height_m, 11.5),
3499 ),
3500 palettes[(rim_serial + 1) % palettes.len()],
3501 true,
3502 );
3503 rim_serial += 1;
3504 }
3505 }
3506 let seawall_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x475569), 0.14, 0.56, 0.22);
3507 let mut wall_serial: usize = 0;
3508 let _: usize = world.spawn_object(
3509 &format!("{CITY_SEAWALL_MESH_NAME}_{wall_serial}"),
3510 unit_box,
3511 Transform3D::new(
3512 Vec3::new(146.0, 0.0, 0.0),
3513 0.0,
3514 Vec3::new(2.4, 1.15, CITY_LOOP_STRAIGHT_HALF_Z * 2.0 + 4.0),
3515 ),
3516 seawall_mat,
3517 true,
3518 );
3519 wall_serial += 1;
3520 for &turn_sign_z in [-1.0_f32, 1.0_f32].iter() {
3521 let center_z: f32 = turn_sign_z * CITY_LOOP_STRAIGHT_HALF_Z;
3522 let seg_count: usize = 10;
3523 for seg_i in 0..seg_count {
3524 let deg: f32 = 3.0 + (seg_i as f32) * 6.0;
3525 let rad: f32 = deg.to_radians();
3526 let (sin_a, cos_a): (f32, f32) = rad.sin_cos();
3527 let wall_r: f32 = 79.0;
3528 let wx: f32 = CITY_LOOP_CENTER_X + wall_r * cos_a;
3529 let wz: f32 = center_z + turn_sign_z * wall_r * sin_a;
3530 let wall_yaw: f32 = if turn_sign_z < 0.0 { rad } else { -rad };
3531 let _: usize = world.spawn_object(
3532 &format!("{CITY_SEAWALL_MESH_NAME}_{wall_serial}"),
3533 unit_box,
3534 Transform3D::new(Vec3::new(wx, 0.0, wz), wall_yaw, Vec3::new(2.2, 1.15, 10.6)),
3535 seawall_mat,
3536 true,
3537 );
3538 wall_serial += 1;
3539 }
3540 }
3541 let palm_mesh: usize = world.register_mesh(MeshLodChain::single_level(Mesh3D::palm_tree(
3542 CITY_PALM_MESH_NAME,
3543 )));
3544 let palm_bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
3545 let palm_z_positions: [f32; 6] = [-102.0, -74.0, -46.0, -18.0, 10.0, 38.0];
3546 for (palm_row, &palm_z) in palm_z_positions.iter().enumerate() {
3547 for side_idx in 0..2usize {
3548 let side_sign: f32 = if side_idx == 0 { -1.0 } else { 1.0 };
3549 let yaw_palm: f32 = (palm_row as f32) * 0.95
3550 + (side_idx as f32) * 2.1
3551 + if side_idx == 0 { 0.35 } else { -0.35 };
3552 let scale_palm: f32 = 0.94 + ((palm_row + side_idx) % 3) as f32 * 0.08;
3553 let _: usize = world.spawn_object(
3554 &format!("palm_{palm_row}_{side_idx}"),
3555 palm_mesh,
3556 Transform3D::new(
3557 Vec3::new(side_sign * 12.0, 0.0, palm_z),
3558 yaw_palm,
3559 Vec3::splat(scale_palm),
3560 ),
3561 palm_bark_mat,
3562 true,
3563 );
3564 }
3565 }
3566 for coast_i in 0..10usize {
3567 let cz: f32 = -124.0 + (coast_i as f32) * 27.5;
3568 let yaw_p: f32 = (coast_i as f32) * 0.72 + 1.2;
3569 let scale_p: f32 = 0.96 + (coast_i % 3) as f32 * 0.07;
3570 let _: usize = world.spawn_object(
3571 &format!("waterfront_palm_{coast_i}"),
3572 palm_mesh,
3573 Transform3D::new(Vec3::new(139.8, 0.0, cz), yaw_p, Vec3::splat(scale_p)),
3574 palm_bark_mat,
3575 true,
3576 );
3577 }
3578 let arch_frame_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0F172A), 0.82, 0.18, 0.60);
3579 for (arch_idx, &arch_z) in [-36.0_f32, -80.0_f32, 48.0_f32].iter().enumerate() {
3580 let arch_neon: PbrMaterial =
3581 PbrMaterial::neon(neon_colors[arch_idx % neon_colors.len()], 2.1);
3582 let _: usize = world.spawn_object(
3583 &format!("arch_beam_{arch_idx}"),
3584 unit_box,
3585 Transform3D::new(
3586 Vec3::new(0.0, 13.4, arch_z),
3587 0.0,
3588 Vec3::new(23.0, 0.58, 0.72),
3589 ),
3590 arch_frame_mat,
3591 true,
3592 );
3593 let _: usize = world.spawn_object(
3594 &format!("arch_glow_{arch_idx}"),
3595 neon_unit,
3596 Transform3D::new(
3597 Vec3::new(0.0, 13.08, arch_z),
3598 0.0,
3599 Vec3::new(21.2, 0.24, 0.34),
3600 ),
3601 arch_neon,
3602 true,
3603 );
3604 for side in [-1.0_f32, 1.0_f32] {
3605 let _: usize = world.spawn_object(
3606 &format!("arch_pillar_{arch_idx}_{}", if side < 0.0 { 0 } else { 1 }),
3607 unit_box,
3608 Transform3D::new(
3609 Vec3::new(side * 11.2, 0.0, arch_z),
3610 0.0,
3611 Vec3::new(0.58, 13.4, 0.68),
3612 ),
3613 arch_frame_mat,
3614 true,
3615 );
3616 }
3617 }
3618 let aventador_mat: PbrMaterial =
3619 Self::hero_vehicle_material(HeroVehicleStyle::AventadorV12);
3620 let shelby_mat: PbrMaterial = Self::hero_vehicle_material(HeroVehicleStyle::ShelbyCobra);
3621 let aventador_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3622 build_lamborghini_chassis_mesh(CITY_MESH_AVENTADOR, aventador_mat),
3623 ));
3624 let shelby_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3625 build_mustang_s650_chassis_mesh(CITY_MESH_SHELBY, shelby_mat),
3626 ));
3627 let npc_default_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x38BDF8), 0.84, 0.13, 0.76);
3628 let npc_sedan_mesh: usize =
3629 world.register_mesh(MeshLodChain::single_level(build_npc_chassis_mesh(
3630 SculptedVehicleKind::NpcSedan,
3631 CITY_MESH_NPC_SEDAN,
3632 npc_default_mat,
3633 )));
3634 let npc_coupe_mesh: usize =
3635 world.register_mesh(MeshLodChain::single_level(build_npc_chassis_mesh(
3636 SculptedVehicleKind::NpcCoupe,
3637 CITY_MESH_NPC_COUPE,
3638 npc_default_mat,
3639 )));
3640 let npc_suv_mesh: usize =
3641 world.register_mesh(MeshLodChain::single_level(build_npc_chassis_mesh(
3642 SculptedVehicleKind::NpcSuv,
3643 CITY_MESH_NPC_SUV,
3644 npc_default_mat,
3645 )));
3646 let lambo_wheel_proto: Mesh3D = build_lamborghini_wheel_mesh(WHEEL_MESH_LAMBORGHINI);
3647 let lambo_wheel_mat: PbrMaterial = lambo_wheel_proto.get_material();
3648 let lambo_wheel_mesh: usize =
3649 world.register_mesh(MeshLodChain::single_level(lambo_wheel_proto));
3650 let mustang_wheel_proto: Mesh3D = build_mustang_s650_wheel_mesh(WHEEL_MESH_MUSTANG);
3651 let mustang_wheel_mat: PbrMaterial = mustang_wheel_proto.get_material();
3652 let mustang_wheel_mesh: usize =
3653 world.register_mesh(MeshLodChain::single_level(mustang_wheel_proto));
3654 let npc_sedan_wheel_proto: Mesh3D =
3655 build_npc_wheel_mesh(SculptedVehicleKind::NpcSedan, WHEEL_MESH_NPC_SEDAN);
3656 let npc_wheel_mat: PbrMaterial = npc_sedan_wheel_proto.get_material();
3657 let npc_sedan_wheel_mesh: usize =
3658 world.register_mesh(MeshLodChain::single_level(npc_sedan_wheel_proto));
3659 let npc_coupe_wheel_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3660 build_npc_wheel_mesh(SculptedVehicleKind::NpcCoupe, WHEEL_MESH_NPC_COUPE),
3661 ));
3662 let npc_suv_wheel_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3663 build_npc_wheel_mesh(SculptedVehicleKind::NpcSuv, WHEEL_MESH_NPC_SUV),
3664 ));
3665 {
3666 let Self {
3667 hero_vehicle_meshes,
3668 hero_wheel_meshes,
3669 ..
3670 } = &mut world;
3671 hero_vehicle_meshes[0] = Some((aventador_mesh, aventador_mat));
3672 hero_vehicle_meshes[1] = Some((shelby_mesh, shelby_mat));
3673 hero_wheel_meshes[0] = Some((lambo_wheel_mesh, lambo_wheel_mat));
3674 hero_wheel_meshes[1] = Some((mustang_wheel_mesh, mustang_wheel_mat));
3675 }
3676 let car_idx: usize = world.spawn_object(
3677 CITY_OBJ_PLAYER_CAR,
3678 aventador_mesh,
3679 Transform3D::new(Vec3::new(0.0, 0.0, 0.0), 0.0, Vec3::splat(1.1)),
3680 aventador_mat,
3681 true,
3682 );
3683 let _: bool = world.set_object_dynamic(car_idx, true);
3684 world.set_player_vehicle_index(Some(car_idx));
3685 let mut p_wheels: [Option<usize>; 4] = [None; 4];
3686 for (w_idx, slot_out) in p_wheels.iter_mut().enumerate() {
3687 let w_obj_id: usize = world.spawn_object(
3688 &format!("{PLAYER_WHEEL_OBJ_PREFIX}{w_idx}"),
3689 lambo_wheel_mesh,
3690 Transform3D::default(),
3691 lambo_wheel_mat,
3692 false,
3693 );
3694 let _: bool = world.set_object_dynamic(w_obj_id, true);
3695 *slot_out = Some(w_obj_id);
3696 }
3697 {
3698 let Self {
3699 player_wheel_objects,
3700 ..
3701 } = &mut world;
3702 *player_wheel_objects = p_wheels;
3703 }
3704 let _: bool = world.sync_vehicle_wheel_transforms(
3705 p_wheels,
3706 (Vec3::zero(), 0.0, 1.1),
3707 Self::hero_wheel_layout(HeroVehicleStyle::AventadorV12),
3708 (0.0, 0.0),
3709 true,
3710 );
3711 let _: usize = world.add_point_light(PointLight3D::new(
3712 Vec3::new(0.0, 0.95, 2.9),
3713 Color::hex(0xFF1744),
3714 1.85,
3715 8.5,
3716 ));
3717 let flame_cone_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3718 Self::build_volumetric_flame_cone_mesh(),
3719 ));
3720 let flame_init_mat: PbrMaterial = PbrMaterial::neon(Color::rgb(205, 244, 255), 4.2);
3721 let mut flame_slots: [Option<usize>; EXHAUST_TOTAL_FLAME_OBJECTS] =
3722 [None; EXHAUST_TOTAL_FLAME_OBJECTS];
3723 for (slot_idx, slot_entry) in flame_slots.iter_mut().enumerate() {
3724 let flame_obj_idx: usize = world.spawn_object(
3725 &format!("{EXHAUST_FLAME_OBJ_PREFIX}{slot_idx}"),
3726 flame_cone_mesh,
3727 Transform3D::new(Vec3::new(0.0, 0.5, 2.4), 0.0, Vec3::splat(0.01)),
3728 flame_init_mat,
3729 false,
3730 );
3731 let _: bool = world.set_object_dynamic(flame_obj_idx, true);
3732 *slot_entry = Some(flame_obj_idx);
3733 }
3734 {
3735 let Self {
3736 exhaust_flame_objects,
3737 exhaust_flame_visible,
3738 ..
3739 } = &mut world;
3740 *exhaust_flame_objects = flame_slots;
3741 *exhaust_flame_visible = [false; EXHAUST_TOTAL_FLAME_OBJECTS];
3742 }
3743 let traffic_specs: [(f32, f32, f32, SculptedVehicleKind, Color); 4] = [
3744 (
3745 156.0,
3746 5.6,
3747 -11.5,
3748 SculptedVehicleKind::NpcSedan,
3749 Color::hex(0x38BDF8),
3750 ),
3751 (
3752 620.0,
3753 5.6,
3754 -11.5,
3755 SculptedVehicleKind::NpcCoupe,
3756 Color::hex(0xA855F7),
3757 ),
3758 (
3759 164.0,
3760 -5.6,
3761 13.0,
3762 SculptedVehicleKind::NpcSuv,
3763 Color::hex(0x22C55E),
3764 ),
3765 (
3766 645.0,
3767 -5.6,
3768 13.0,
3769 SculptedVehicleKind::MustangS650,
3770 Color::hex(0xF59E0B),
3771 ),
3772 ];
3773 for (t_idx, &(start_s, lane_u, speed_mps, npc_kind, t_col)) in
3774 traffic_specs.iter().enumerate()
3775 {
3776 let (t_pos, base_yaw): (Vec3, f32) = Self::loop_pose_at(start_s, lane_u);
3777 let face_yaw: f32 = if speed_mps >= 0.0 {
3778 base_yaw
3779 } else {
3780 base_yaw + PI
3781 };
3782 let (t_mesh, npc_wheel_mesh, npc_w_mat): (usize, usize, PbrMaterial) = match npc_kind {
3783 SculptedVehicleKind::LamborghiniRevuelto => {
3784 (aventador_mesh, lambo_wheel_mesh, lambo_wheel_mat)
3785 }
3786 SculptedVehicleKind::MustangS650 => {
3787 (shelby_mesh, mustang_wheel_mesh, mustang_wheel_mat)
3788 }
3789 SculptedVehicleKind::NpcSedan => {
3790 (npc_sedan_mesh, npc_sedan_wheel_mesh, npc_wheel_mat)
3791 }
3792 SculptedVehicleKind::NpcCoupe => {
3793 (npc_coupe_mesh, npc_coupe_wheel_mesh, npc_wheel_mat)
3794 }
3795 SculptedVehicleKind::NpcSuv => (npc_suv_mesh, npc_suv_wheel_mesh, npc_wheel_mat),
3796 };
3797 let tmat: PbrMaterial = PbrMaterial::pbr(t_col, 0.84, 0.13, 0.76);
3798 let obj_id: usize = world.spawn_object(
3799 &format!("ai_traffic_{t_idx}"),
3800 t_mesh,
3801 Transform3D::new(t_pos, face_yaw, Vec3::splat(1.04)),
3802 tmat,
3803 true,
3804 );
3805 let _: bool = world.set_object_dynamic(obj_id, true);
3806 let mut npc_wheels: [Option<usize>; 4] = [None; 4];
3807 for (w_idx, slot_out) in npc_wheels.iter_mut().enumerate() {
3808 let w_obj_id: usize = world.spawn_object(
3809 &format!("{NPC_WHEEL_OBJ_PREFIX}{t_idx}_{w_idx}"),
3810 npc_wheel_mesh,
3811 Transform3D::default(),
3812 npc_w_mat,
3813 false,
3814 );
3815 let _: bool = world.set_object_dynamic(w_obj_id, true);
3816 *slot_out = Some(w_obj_id);
3817 }
3818 let _: bool = world.sync_vehicle_wheel_transforms(
3819 npc_wheels,
3820 (t_pos, face_yaw, 1.04),
3821 npc_wheel_layout(npc_kind),
3822 (0.0, 0.0),
3823 true,
3824 );
3825 let mut npc_entry: NpcVehicle3D =
3826 NpcVehicle3D::new_boulevard(obj_id, start_s, lane_u, speed_mps, face_yaw);
3827 npc_entry.set_wheel_object_indices(npc_wheels);
3828 npc_entry.set_vehicle_kind(npc_kind);
3829 let Self {
3830 traffic_vehicles, ..
3831 } = &mut world;
3832 traffic_vehicles.push(npc_entry);
3833 }
3834 let offroad_specs: [(Vec3, f32, u8, usize, f32, SculptedVehicleKind, Color); 4] = [
3835 (
3836 Vec3::new(38.0, 0.0, -40.0),
3837 0.0,
3838 0,
3839 0,
3840 10.5,
3841 SculptedVehicleKind::NpcCoupe,
3842 Color::hex(0x14B8A6),
3843 ),
3844 (
3845 Vec3::new(91.0, 0.0, 40.0),
3846 PI,
3847 0,
3848 3,
3849 10.0,
3850 SculptedVehicleKind::NpcSedan,
3851 Color::hex(0xFB7185),
3852 ),
3853 (
3854 Vec3::new(-72.0, 0.0, -30.0),
3855 PI,
3856 1,
3857 1,
3858 11.0,
3859 SculptedVehicleKind::NpcSuv,
3860 Color::hex(0xEAB308),
3861 ),
3862 (
3863 Vec3::new(38.0, 0.0, 78.0),
3864 -FRAC_PI_2,
3865 2,
3866 1,
3867 9.5,
3868 SculptedVehicleKind::LamborghiniRevuelto,
3869 Color::hex(0x6366F1),
3870 ),
3871 ];
3872 for (o_idx, &(o_pos, o_yaw, route_id, wp_idx, o_speed, npc_kind, o_col)) in
3873 offroad_specs.iter().enumerate()
3874 {
3875 let traffic_serial: usize = traffic_specs.len() + o_idx;
3876 let (o_mesh, npc_wheel_mesh, npc_w_mat): (usize, usize, PbrMaterial) = match npc_kind {
3877 SculptedVehicleKind::LamborghiniRevuelto => {
3878 (aventador_mesh, lambo_wheel_mesh, lambo_wheel_mat)
3879 }
3880 SculptedVehicleKind::MustangS650 => {
3881 (shelby_mesh, mustang_wheel_mesh, mustang_wheel_mat)
3882 }
3883 SculptedVehicleKind::NpcSedan => {
3884 (npc_sedan_mesh, npc_sedan_wheel_mesh, npc_wheel_mat)
3885 }
3886 SculptedVehicleKind::NpcCoupe => {
3887 (npc_coupe_mesh, npc_coupe_wheel_mesh, npc_wheel_mat)
3888 }
3889 SculptedVehicleKind::NpcSuv => (npc_suv_mesh, npc_suv_wheel_mesh, npc_wheel_mat),
3890 };
3891 let omat: PbrMaterial = PbrMaterial::pbr(o_col, 0.84, 0.13, 0.76);
3892 let obj_id: usize = world.spawn_object(
3893 &format!("ai_traffic_{traffic_serial}"),
3894 o_mesh,
3895 Transform3D::new(o_pos, o_yaw, Vec3::splat(1.04)),
3896 omat,
3897 true,
3898 );
3899 let _: bool = world.set_object_dynamic(obj_id, true);
3900 let mut npc_wheels: [Option<usize>; 4] = [None; 4];
3901 for (w_idx, slot_out) in npc_wheels.iter_mut().enumerate() {
3902 let w_obj_id: usize = world.spawn_object(
3903 &format!("{NPC_WHEEL_OBJ_PREFIX}{traffic_serial}_{w_idx}"),
3904 npc_wheel_mesh,
3905 Transform3D::default(),
3906 npc_w_mat,
3907 false,
3908 );
3909 let _: bool = world.set_object_dynamic(w_obj_id, true);
3910 *slot_out = Some(w_obj_id);
3911 }
3912 let _: bool = world.sync_vehicle_wheel_transforms(
3913 npc_wheels,
3914 (o_pos, o_yaw, 1.04),
3915 npc_wheel_layout(npc_kind),
3916 (0.0, 0.0),
3917 true,
3918 );
3919 let mut npc_entry: NpcVehicle3D =
3920 NpcVehicle3D::new_free_roam(obj_id, route_id, wp_idx, o_speed, o_yaw);
3921 npc_entry.set_wheel_object_indices(npc_wheels);
3922 npc_entry.set_vehicle_kind(npc_kind);
3923 let Self {
3924 traffic_vehicles, ..
3925 } = &mut world;
3926 traffic_vehicles.push(npc_entry);
3927 }
3928 let lamp_palette: [Color; 4] = [
3929 Color::hex(0x38BDF8),
3930 Color::hex(0xF43F5E),
3931 Color::hex(0xA855F7),
3932 Color::hex(0x34D399),
3933 ];
3934 let lamp_z_rows: [f32; 4] = [-62.0, -26.0, 18.0, 66.0];
3935 for lamp_idx in 0..8usize {
3936 let side: f32 = if lamp_idx % 2 == 0 { -1.0 } else { 1.0 };
3937 let z_pos: f32 = lamp_z_rows[lamp_idx / 2];
3938 let lamp_color: Color = lamp_palette[lamp_idx % lamp_palette.len()];
3939 let _: usize = world.spawn_object(
3940 &format!("lamp_pole_{lamp_idx}"),
3941 unit_box,
3942 Transform3D::new(
3943 Vec3::new(side * 10.65, 0.0, z_pos),
3944 0.0,
3945 Vec3::new(0.20, 6.2, 0.20),
3946 ),
3947 arch_frame_mat,
3948 true,
3949 );
3950 let _: usize = world.spawn_object(
3951 &format!("lamp_head_{lamp_idx}"),
3952 neon_unit,
3953 Transform3D::new(
3954 Vec3::new(side * 10.15, 6.2, z_pos),
3955 0.0,
3956 Vec3::new(1.1, 0.18, 0.28),
3957 ),
3958 PbrMaterial::neon(lamp_color, 2.2),
3959 true,
3960 );
3961 let _: usize = world.add_point_light(PointLight3D::new(
3962 Vec3::new(side * 9.8, 6.2, z_pos),
3963 lamp_color,
3964 2.35,
3965 16.5,
3966 ));
3967 }
3968 let _: usize = world.add_spot_light(SpotLight3D::new(
3969 Vec3::new(-0.85, 0.95, -2.2),
3970 Vec3::new(0.0, -0.14, -1.0),
3971 Color::hex(0xFEF3C7),
3972 2.8,
3973 24.0,
3974 (14.0, 26.0),
3975 ));
3976 let _: usize = world.add_spot_light(SpotLight3D::new(
3977 Vec3::new(0.85, 0.95, -2.2),
3978 Vec3::new(0.0, -0.14, -1.0),
3979 Color::hex(0xFEF3C7),
3980 2.8,
3981 24.0,
3982 (14.0, 26.0),
3983 ));
3984 let exhaust_glow_idx: usize = world.add_point_light(PointLight3D::new(
3985 Vec3::new(0.0, 0.56, 2.9),
3986 Color::rgb(64, 210, 255),
3987 0.0,
3988 9.5,
3989 ));
3990 {
3991 let Self {
3992 exhaust_light_index,
3993 ..
3994 } = &mut world;
3995 *exhaust_light_index = Some(exhaust_glow_idx);
3996 }
3997 world.set_camera(Camera3D {
3998 position: Vec3::new(0.0, 4.15, 9.2),
3999 yaw: -FRAC_PI_2,
4000 pitch: -0.145,
4001 fov_deg: 60.0,
4002 near: 0.3,
4003 far: 560.0,
4004 });
4005 populate_city_ecosystem_and_furniture(&mut world);
4006 world.sync_environment_lighting();
4007 world.ensure_bvh();
4008 {
4009 let Self {
4010 dynamic_tris_scratch,
4011 ..
4012 } = &mut world;
4013 dynamic_tris_scratch.clear();
4014 dynamic_tris_scratch.shrink_to_fit();
4015 }
4016 world
4017 }
4018
4019 #[must_use]
4025 pub fn traffic_vehicle_count(&self) -> usize {
4026 let Self {
4027 traffic_vehicles, ..
4028 } = self;
4029 traffic_vehicles.len()
4030 }
4031
4032 #[must_use]
4042 pub fn traffic_vehicle_object_index(&self, slot: usize) -> Option<usize> {
4043 let Self {
4044 traffic_vehicles, ..
4045 } = self;
4046 traffic_vehicles
4047 .get(slot)
4048 .map(NpcVehicle3D::get_object_index)
4049 }
4050
4051 #[must_use]
4061 pub fn traffic_vehicle_velocity(&self, slot: usize) -> Option<Vec3> {
4062 let Self {
4063 traffic_vehicles, ..
4064 } = self;
4065 traffic_vehicles.get(slot).map(NpcVehicle3D::get_vel)
4066 }
4067
4068 #[must_use]
4078 pub fn traffic_vehicle_yaw_rate(&self, slot: usize) -> Option<f32> {
4079 let Self {
4080 traffic_vehicles, ..
4081 } = self;
4082 traffic_vehicles.get(slot).map(NpcVehicle3D::get_yaw_rate)
4083 }
4084
4085 #[must_use]
4095 pub fn traffic_vehicle_is_free_roam(&self, slot: usize) -> Option<bool> {
4096 let Self {
4097 traffic_vehicles, ..
4098 } = self;
4099 traffic_vehicles
4100 .get(slot)
4101 .map(NpcVehicle3D::get_free_roam_mode)
4102 }
4103
4104 #[must_use]
4110 pub fn player_velocity(&self) -> Vec3 {
4111 let Self { player_physics, .. } = self;
4112 player_physics.get_vel()
4113 }
4114
4115 #[must_use]
4121 pub fn player_forward_speed_mps(&self) -> f32 {
4122 let Some(car_idx) = self.vehicle_index() else {
4123 return 0.0;
4124 };
4125 let Some(car_obj) = self.get_objects().get(car_idx) else {
4126 return 0.0;
4127 };
4128 let yaw_rad: f32 = car_obj.get_transform().get_yaw_rad();
4129 let forward_dir: Vec3 = Vec3::new(-yaw_rad.sin(), 0.0, -yaw_rad.cos());
4130 self.player_velocity().dot(forward_dir)
4131 }
4132
4133 #[must_use]
4143 pub(crate) fn hero_wheel_layout(style: HeroVehicleStyle) -> VehicleWheelLayout3D {
4144 match style {
4145 HeroVehicleStyle::AventadorV12 => lamborghini_wheel_layout(),
4146 HeroVehicleStyle::ShelbyCobra => mustang_s650_wheel_layout(),
4147 }
4148 }
4149
4150 fn sync_vehicle_wheel_transforms(
4164 &mut self,
4165 wheel_slots: [Option<usize>; 4],
4166 car_pose: (Vec3, f32, f32),
4167 layout: VehicleWheelLayout3D,
4168 wheel_angles: (f32, f32),
4169 bump_teleport: bool,
4170 ) -> bool {
4171 let (car_pos, car_yaw, car_scale): (Vec3, f32, f32) = car_pose;
4172 let (wheel_spin_rad, front_steer_rad): (f32, f32) = wheel_angles;
4173 let right: Vec3 = Vec3::new(car_yaw.cos(), 0.0, -car_yaw.sin());
4174 let rear: Vec3 = Vec3::new(car_yaw.sin(), 0.0, car_yaw.cos());
4175 let corners: [Vec3; 4] = [
4176 layout.get_front_left(),
4177 layout.get_front_right(),
4178 layout.get_rear_left(),
4179 layout.get_rear_right(),
4180 ];
4181 let mut updated_any: bool = false;
4182 for (w_idx, obj_opt) in wheel_slots.into_iter().enumerate() {
4183 let Some(obj_idx) = obj_opt else {
4184 continue;
4185 };
4186 let is_front: bool = w_idx < 2;
4187 let corner: Vec3 = corners[w_idx];
4188 let world_pos: Vec3 = Vec3::new(car_pos.get_x(), car_pos.get_y(), car_pos.get_z())
4189 .add(right.scale(corner.get_x() * car_scale))
4190 .add(rear.scale(corner.get_z() * car_scale))
4191 .add(Vec3::new(0.0, corner.get_y() * car_scale, 0.0));
4192 let wheel_yaw: f32 = car_yaw + if is_front { front_steer_rad } else { 0.0 };
4193 let wheel_rot: Quat = Quat::from_euler_yxz(wheel_yaw, wheel_spin_rad, 0.0);
4194 let wheel_tr: Transform3D =
4195 Transform3D::from_trs(world_pos, wheel_rot, Vec3::splat(car_scale));
4196 let mesh_id_opt: Option<usize> = self
4197 .get_objects()
4198 .get(obj_idx)
4199 .map(SceneObject3D::get_mesh_id);
4200 if let Some(m_id) = mesh_id_opt {
4201 let local_b: AxisAlignedBox3D = self.local_bounds_for_mesh(m_id);
4202 let world_b: AxisAlignedBox3D = wheel_tr.transform_bounds(local_b);
4203 if let Some(obj_mut) = self.get_mut_objects().get_mut(obj_idx) {
4204 obj_mut.set_transform(wheel_tr);
4205 obj_mut.set_world_bounds(world_b);
4206 if bump_teleport {
4207 let next_ep: u32 = obj_mut.get_teleport_epoch().wrapping_add(1);
4208 obj_mut.set_teleport_epoch(next_ep);
4209 }
4210 updated_any = true;
4211 }
4212 }
4213 }
4214 updated_any
4215 }
4216
4217 #[must_use]
4223 pub fn player_wheel_spin_rad(&self) -> f32 {
4224 let Self { player_physics, .. } = self;
4225 player_physics.get_wheel_spin_rad()
4226 }
4227
4228 #[must_use]
4234 pub fn player_front_steer_rad(&self) -> f32 {
4235 let Self { player_physics, .. } = self;
4236 player_physics.get_front_steer_rad()
4237 }
4238
4239 #[must_use]
4245 pub fn player_wheel_object_indices(&self) -> [Option<usize>; 4] {
4246 let Self {
4247 player_wheel_objects,
4248 ..
4249 } = self;
4250 *player_wheel_objects
4251 }
4252
4253 #[must_use]
4263 pub fn traffic_vehicle_wheel_spin_rad(&self, slot: usize) -> Option<f32> {
4264 let Self {
4265 traffic_vehicles, ..
4266 } = self;
4267 traffic_vehicles
4268 .get(slot)
4269 .map(NpcVehicle3D::get_wheel_spin_rad)
4270 }
4271
4272 #[must_use]
4282 pub fn traffic_vehicle_front_steer_rad(&self, slot: usize) -> Option<f32> {
4283 let Self {
4284 traffic_vehicles, ..
4285 } = self;
4286 traffic_vehicles
4287 .get(slot)
4288 .map(NpcVehicle3D::get_front_steer_rad)
4289 }
4290
4291 #[must_use]
4301 pub fn traffic_vehicle_wheel_object_indices(&self, slot: usize) -> Option<[Option<usize>; 4]> {
4302 let Self {
4303 traffic_vehicles, ..
4304 } = self;
4305 traffic_vehicles
4306 .get(slot)
4307 .map(NpcVehicle3D::get_wheel_object_indices)
4308 }
4309
4310 #[must_use]
4320 pub fn hero_exhaust_tips_local(style: HeroVehicleStyle) -> &'static [[f32; 3]] {
4321 match style {
4322 HeroVehicleStyle::AventadorV12 => &LAMBORGHINI_EXHAUST_TIPS_LOCAL,
4323 HeroVehicleStyle::ShelbyCobra => &MUSTANG_S650_EXHAUST_TIPS_LOCAL,
4324 }
4325 }
4326
4327 #[must_use]
4333 fn build_volumetric_flame_cone_mesh() -> Mesh3D {
4334 let radial_segs: usize = 12;
4335 let profile: [(f32, f32); 6] = [
4336 (-0.05, 0.72),
4337 (0.08, 1.00),
4338 (0.28, 0.66),
4339 (0.48, 0.84),
4340 (0.74, 0.42),
4341 (1.00, 0.02),
4342 ];
4343 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(profile.len() * radial_segs + 2);
4344 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(profile.len() * radial_segs * 2);
4345 for (ring_idx, &(z_pos, rad)) in profile.iter().enumerate() {
4346 let dr_dz: f32 = if ring_idx == 0 {
4347 (profile[1].1 - rad) / (profile[1].0 - z_pos)
4348 } else if ring_idx + 1 == profile.len() {
4349 (rad - profile[ring_idx - 1].1) / (z_pos - profile[ring_idx - 1].0)
4350 } else {
4351 (profile[ring_idx + 1].1 - profile[ring_idx - 1].1)
4352 / (profile[ring_idx + 1].0 - profile[ring_idx - 1].0)
4353 };
4354 for seg in 0..radial_segs {
4355 let theta: f32 = ((seg as f32) / (radial_segs as f32)) * (2.0 * PI);
4356 let (sin_t, cos_t): (f32, f32) = theta.sin_cos();
4357 let pos: Vec3 = Vec3::new(rad * cos_t, rad * sin_t, z_pos);
4358 let nrm: Vec3 = Vec3::new(cos_t, sin_t, -dr_dz).normalize();
4359 vertices.push(Vertex3D::new(pos, nrm));
4360 }
4361 }
4362 let ring_count: usize = profile.len();
4363 for r in 0..(ring_count - 1) {
4364 let base0: u32 = (r * radial_segs) as u32;
4365 let base1: u32 = ((r + 1) * radial_segs) as u32;
4366 for seg in 0..radial_segs {
4367 let next_seg: usize = (seg + 1) % radial_segs;
4368 let a: u32 = base0 + (seg as u32);
4369 let b: u32 = base0 + (next_seg as u32);
4370 let c: u32 = base1 + (next_seg as u32);
4371 let d: u32 = base1 + (seg as u32);
4372 indices.push([a, b, d]);
4373 indices.push([b, c, d]);
4374 }
4375 }
4376 let base_cap_center: u32 = vertices.len() as u32;
4377 vertices.push(Vertex3D::new(
4378 Vec3::new(0.0, 0.0, profile[0].0),
4379 Vec3::new(0.0, 0.0, -1.0),
4380 ));
4381 let tip_cap_center: u32 = vertices.len() as u32;
4382 vertices.push(Vertex3D::new(
4383 Vec3::new(0.0, 0.0, profile[ring_count - 1].0),
4384 Vec3::new(0.0, 0.0, 1.0),
4385 ));
4386 let last_ring_base: u32 = ((ring_count - 1) * radial_segs) as u32;
4387 for seg in 0..radial_segs {
4388 let next_seg: usize = (seg + 1) % radial_segs;
4389 indices.push([base_cap_center, next_seg as u32, seg as u32]);
4390 indices.push([
4391 tip_cap_center,
4392 last_ring_base + (seg as u32),
4393 last_ring_base + (next_seg as u32),
4394 ]);
4395 }
4396 let mut mesh: Mesh3D = Mesh3D::from_parts(
4397 EXHAUST_FLAME_CONE_MESH_NAME.to_string(),
4398 vertices,
4399 indices,
4400 PbrMaterial::neon(Color::rgb(205, 244, 255), 4.2),
4401 );
4402 mesh.set_is_closed(true);
4403 mesh
4404 }
4405
4406 pub fn reset_player_vehicle(&mut self) -> bool {
4412 let Some(car_idx) = self.vehicle_index() else {
4413 return false;
4414 };
4415 let spawn_transform: Transform3D =
4416 Transform3D::new(Vec3::new(0.0, 0.0, 0.0), 0.0, Vec3::splat(1.1));
4417 if !self.teleport_object(car_idx, spawn_transform) {
4418 return false;
4419 }
4420 {
4421 let Self {
4422 player_physics,
4423 exhaust_flame_visible,
4424 exhaust_light_index,
4425 point_lights,
4426 ..
4427 } = self;
4428 *player_physics = PlayerVehiclePhysics3D::default();
4429 *exhaust_flame_visible = [false; EXHAUST_TOTAL_FLAME_OBJECTS];
4430 if let Some(light_idx) = *exhaust_light_index
4431 && let Some(light) = point_lights.get_mut(light_idx)
4432 {
4433 light.set_intensity(0.0);
4434 }
4435 }
4436 let player_wheels: [Option<usize>; 4] = self.player_wheel_object_indices();
4437 let layout: VehicleWheelLayout3D = Self::hero_wheel_layout(self.get_hero_vehicle_style());
4438 let _: bool = self.sync_vehicle_wheel_transforms(
4439 player_wheels,
4440 (Vec3::zero(), 0.0, 1.1),
4441 layout,
4442 (0.0, 0.0),
4443 true,
4444 );
4445 self.get_mut_niagara().clear();
4446 let mut reset_cam: Camera3D = self.get_camera();
4447 let eye_pos: Vec3 = Vec3::new(0.0, 4.25, 9.8);
4448 let look_target: Vec3 = Vec3::new(0.0, 2.40, -16.0);
4449 let look_dir: Vec3 = look_target.sub(eye_pos).normalize();
4450 reset_cam.set_position(eye_pos);
4451 reset_cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
4452 reset_cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
4453 reset_cam.set_fov_deg(CAMERA_BASE_FOV_DEG);
4454 self.set_camera(reset_cam);
4455 self.bump_world_revision();
4456 true
4457 }
4458
4459 #[must_use]
4465 pub fn player_speed_mps(&self) -> f32 {
4466 let v: Vec3 = self.player_velocity();
4467 (v.get_x() * v.get_x() + v.get_z() * v.get_z()).sqrt()
4468 }
4469
4470 #[must_use]
4476 pub fn player_speed_kmh(&self) -> f32 {
4477 self.player_speed_mps() * 3.6
4478 }
4479
4480 #[must_use]
4486 pub fn player_yaw_rate(&self) -> f32 {
4487 let Self { player_physics, .. } = self;
4488 player_physics.get_yaw_rate()
4489 }
4490
4491 #[must_use]
4497 pub fn player_boost_active(&self) -> bool {
4498 let Self { player_physics, .. } = self;
4499 player_physics.get_boost_active()
4500 }
4501
4502 #[must_use]
4508 pub fn player_boost_charge(&self) -> f32 {
4509 let Self { player_physics, .. } = self;
4510 player_physics.get_boost_charge()
4511 }
4512
4513 #[must_use]
4519 pub fn player_boost_spool(&self) -> f32 {
4520 let Self { player_physics, .. } = self;
4521 player_physics.get_boost_spool()
4522 }
4523
4524 #[must_use]
4530 pub fn player_backfire_active(&self) -> bool {
4531 let Self { player_physics, .. } = self;
4532 player_physics.get_backfire_timer() > 0.0
4533 }
4534
4535 #[must_use]
4541 pub fn player_active_gear(&self) -> u8 {
4542 let Self { player_physics, .. } = self;
4543 player_physics.get_active_gear()
4544 }
4545
4546 #[must_use]
4552 pub fn active_exhaust_flame_count(&self) -> usize {
4553 let Self {
4554 exhaust_flame_visible,
4555 ..
4556 } = self;
4557 exhaust_flame_visible
4558 .iter()
4559 .filter(|visible: &&bool| **visible)
4560 .count()
4561 }
4562
4563 #[must_use]
4569 pub fn exhaust_glow_light_intensity(&self) -> f32 {
4570 let Self {
4571 exhaust_light_index,
4572 point_lights,
4573 ..
4574 } = self;
4575 exhaust_light_index
4576 .and_then(|idx: usize| point_lights.get(idx))
4577 .map_or(0.0, PointLight3D::get_intensity)
4578 }
4579
4580 #[must_use]
4586 pub fn player_drift_active(&self) -> bool {
4587 let Self { player_physics, .. } = self;
4588 player_physics.get_drift_active()
4589 }
4590
4591 #[must_use]
4597 pub fn player_drift_slip_angle_rad(&self) -> f32 {
4598 let Self { player_physics, .. } = self;
4599 player_physics.get_drift_slip_angle()
4600 }
4601
4602 #[must_use]
4608 pub fn player_body_roll_rad(&self) -> f32 {
4609 let Self { player_physics, .. } = self;
4610 player_physics.get_body_roll_rad()
4611 }
4612
4613 #[must_use]
4619 pub fn player_body_pitch_rad(&self) -> f32 {
4620 let Self { player_physics, .. } = self;
4621 player_physics.get_body_pitch_rad()
4622 }
4623
4624 #[must_use]
4630 pub fn player_camera_fov_boost(&self) -> f32 {
4631 let Self { player_physics, .. } = self;
4632 player_physics.get_camera_fov_boost()
4633 }
4634
4635 #[must_use]
4641 pub fn player_camera_shake(&self) -> f32 {
4642 let Self { player_physics, .. } = self;
4643 player_physics.get_camera_shake()
4644 }
4645
4646 #[must_use]
4652 pub fn time_of_day_preset(&self) -> TimeOfDayPreset3D {
4653 let Self {
4654 time_of_day_preset, ..
4655 } = self;
4656 *time_of_day_preset
4657 }
4658
4659 #[must_use]
4665 pub fn weather_preset(&self) -> WeatherPreset3D {
4666 let Self { weather_preset, .. } = self;
4667 *weather_preset
4668 }
4669
4670 #[must_use]
4676 pub fn is_wet_asphalt(&self) -> bool {
4677 let Self { wet_asphalt, .. } = self;
4678 *wet_asphalt
4679 }
4680
4681 #[must_use]
4691 pub fn effective_fog_density(&self, volumetric_fog: bool) -> f32 {
4692 let Self {
4693 weather_fog_density,
4694 ..
4695 } = self;
4696 if volumetric_fog {
4697 *weather_fog_density
4698 } else {
4699 (*weather_fog_density * 0.35).max(0.0008)
4700 }
4701 }
4702
4703 #[must_use]
4709 pub fn camera_mode_label(&self) -> &'static str {
4710 self.active_camera_mode().label()
4711 }
4712
4713 #[must_use]
4719 pub fn time_of_day_label(&self) -> &'static str {
4720 self.time_of_day_preset().label()
4721 }
4722
4723 #[must_use]
4729 pub fn weather_label(&self) -> &'static str {
4730 self.weather_preset().label()
4731 }
4732
4733 fn sync_environment_lighting(&mut self) {
4735 let tod: TimeOfDayPreset3D = self.time_of_day_preset();
4736 let weather: WeatherPreset3D = self.weather_preset();
4737 let (
4738 sun_dir,
4739 base_sun_col,
4740 base_zenith,
4741 base_horizon,
4742 hour,
4743 base_ambient,
4744 base_exposure,
4745 mut lamp_scale,
4746 mut headlight_scale,
4747 headlight_range,
4748 mut neon_scale,
4749 ): (Vec3, Vec3, Vec3, Vec3, f32, f32, f32, f32, f32, f32, f32) = match tod {
4750 TimeOfDayPreset3D::MorningSunrise => (
4751 Vec3::new(0.68, 0.24, -0.69).normalize(),
4752 Vec3::new(2.48, 1.58, 0.96),
4753 Vec3::new(0.085, 0.165, 0.46),
4754 Vec3::new(0.80, 0.49, 0.36),
4755 ATMOSPHERE_HOUR_SUNRISE,
4756 0.36,
4757 1.12,
4758 0.45,
4759 0.65,
4760 20.0,
4761 0.55,
4762 ),
4763 TimeOfDayPreset3D::BrightNoon => (
4764 Vec3::new(-0.18, 0.88, -0.44).normalize(),
4765 Vec3::new(2.60, 2.48, 2.28),
4766 Vec3::new(0.075, 0.26, 0.72),
4767 Vec3::new(0.50, 0.72, 0.94),
4768 ATMOSPHERE_HOUR_NOON,
4769 0.44,
4770 1.04,
4771 0.12,
4772 0.30,
4773 14.0,
4774 0.25,
4775 ),
4776 TimeOfDayPreset3D::GoldenSunset => (
4777 Vec3::new(-0.16, 0.17, -0.97).normalize(),
4778 Vec3::new(2.85, 1.42, 0.66),
4779 Vec3::new(0.028, 0.038, 0.155),
4780 Vec3::new(0.62, 0.24, 0.22),
4781 ATMOSPHERE_HOUR_SUNSET,
4782 0.34,
4783 1.15,
4784 1.00,
4785 1.00,
4786 24.0,
4787 1.00,
4788 ),
4789 TimeOfDayPreset3D::NeonMidnight => (
4790 Vec3::new(-0.40, 0.60, -0.69).normalize(),
4791 Vec3::new(0.40, 0.44, 0.98),
4792 Vec3::new(0.008, 0.008, 0.032),
4793 Vec3::new(0.115, 0.048, 0.215),
4794 ATMOSPHERE_HOUR_MIDNIGHT,
4795 0.26,
4796 1.24,
4797 1.90,
4798 2.25,
4799 38.0,
4800 1.85,
4801 ),
4802 };
4803 let sky_luma: f32 = (base_horizon.get_x() * 0.30
4804 + base_horizon.get_y() * 0.55
4805 + base_horizon.get_z() * 0.15)
4806 .clamp(0.16, 0.88);
4807 let (sun_col, sky_zenith, sky_horizon, ambient, exposure): (Vec3, Vec3, Vec3, f32, f32) =
4808 match weather {
4809 WeatherPreset3D::ClearSunny => (
4810 base_sun_col,
4811 base_zenith,
4812 base_horizon,
4813 base_ambient,
4814 base_exposure,
4815 ),
4816 WeatherPreset3D::PartlyCloudy => (
4817 base_sun_col.scale(0.76),
4818 base_zenith.lerp(Vec3::new(0.32, 0.38, 0.46).scale(sky_luma * 0.85), 0.32),
4819 base_horizon.lerp(Vec3::new(0.62, 0.68, 0.76).scale(sky_luma), 0.26),
4820 base_ambient * 1.08,
4821 base_exposure * 1.02,
4822 ),
4823 WeatherPreset3D::MistyFog => (
4824 base_sun_col.scale(0.48),
4825 base_zenith.lerp(Vec3::new(0.56, 0.64, 0.72).scale(sky_luma), 0.56),
4826 base_horizon.lerp(Vec3::new(0.74, 0.80, 0.86).scale(sky_luma), 0.62),
4827 base_ambient * 1.18,
4828 base_exposure * 1.04,
4829 ),
4830 WeatherPreset3D::Rainstorm => {
4831 lamp_scale *= 1.35;
4832 headlight_scale *= 1.30;
4833 neon_scale *= 1.30;
4834 (
4835 base_sun_col.scale(0.32),
4836 base_zenith.lerp(Vec3::new(0.035, 0.062, 0.115), 0.64),
4837 base_horizon.lerp(Vec3::new(0.125, 0.195, 0.295), 0.62),
4838 base_ambient * 0.92,
4839 base_exposure * 1.08,
4840 )
4841 }
4842 };
4843 let wet_now: bool = weather.is_wet_asphalt();
4844 let fog_now: f32 = weather.base_fog_density();
4845 let effective_hour: f32 =
4846 if tod == TimeOfDayPreset3D::NeonMidnight && weather == WeatherPreset3D::Rainstorm {
4847 ATMOSPHERE_HOUR_RAINY_NIGHT
4848 } else {
4849 hour
4850 };
4851 self.set_sun(DirectionalLight3D {
4852 direction: sun_dir,
4853 color: sun_col,
4854 sky_zenith,
4855 sky_horizon,
4856 time_of_day: effective_hour,
4857 });
4858 {
4859 let Self {
4860 wet_asphalt,
4861 weather_fog_density,
4862 weather_ambient_strength,
4863 weather_exposure,
4864 ..
4865 } = self;
4866 *wet_asphalt = wet_now;
4867 *weather_fog_density = fog_now;
4868 *weather_ambient_strength = ambient;
4869 *weather_exposure = exposure;
4870 }
4871 let exhaust_light_opt: Option<usize> = {
4872 let Self {
4873 exhaust_light_index,
4874 ..
4875 } = self;
4876 *exhaust_light_index
4877 };
4878 for (l_idx, light_mut) in self.get_mut_point_lights().iter_mut().enumerate() {
4879 if Some(l_idx) == exhaust_light_opt {
4880 continue;
4881 }
4882 if l_idx == 0 {
4883 light_mut.set_intensity((1.85 * lamp_scale).clamp(0.75, 3.6));
4884 } else {
4885 light_mut.set_intensity((2.35 * lamp_scale).clamp(0.25, 5.2));
4886 }
4887 }
4888 for spot_mut in self.get_mut_spot_lights().iter_mut() {
4889 spot_mut.set_intensity((2.8 * headlight_scale).clamp(0.75, 7.2));
4890 spot_mut.set_range(headlight_range);
4891 }
4892 let road_idx_opt: Option<usize> = {
4893 let Self {
4894 road_ground_object_index,
4895 ..
4896 } = self;
4897 *road_ground_object_index
4898 };
4899 if let Some(road_idx) = road_idx_opt
4900 && let Some(road_obj) = self.get_mut_objects().get_mut(road_idx)
4901 {
4902 let road_mat: PbrMaterial = match weather {
4903 WeatherPreset3D::Rainstorm => {
4904 PbrMaterial::pbr(Color::hex(0x070B12), 0.24, 0.08, 0.88)
4905 .with_surface_detail(SurfaceDetailMode::RoadSurface)
4906 }
4907 WeatherPreset3D::MistyFog => {
4908 PbrMaterial::pbr(Color::hex(0x0B1018), 0.14, 0.16, 0.74)
4909 .with_surface_detail(SurfaceDetailMode::RoadSurface)
4910 }
4911 _ => PbrMaterial::pbr(Color::hex(0x0E131C), 0.08, 0.24, 0.62)
4912 .with_surface_detail(SurfaceDetailMode::RoadSurface),
4913 };
4914 road_obj.set_material(road_mat);
4915 }
4916 for obj_mut in self.get_mut_objects().iter_mut() {
4917 let name_str: &str = obj_mut.get_name().as_str();
4918 if name_str.starts_with(CITY_OBJ_ARCH_GLOW_PREFIX)
4919 || name_str.starts_with(CITY_OBJ_LAMP_HEAD_PREFIX)
4920 {
4921 let mut mat: PbrMaterial = obj_mut.get_material();
4922 let base_c: Vec3 = mat.get_base_color();
4923 let base_gain: f32 = if name_str.starts_with(CITY_OBJ_ARCH_GLOW_PREFIX) {
4924 2.1
4925 } else {
4926 2.2
4927 };
4928 mat.set_emissive(base_c.scale(base_gain * neon_scale));
4929 obj_mut.set_material(mat);
4930 }
4931 }
4932 let (base_cloud_rgb, base_cloud_em, base_river_rgb): (Vec3, Vec3, Vec3) = match tod {
4933 TimeOfDayPreset3D::MorningSunrise => (
4934 Vec3::new(0.99, 0.89, 0.82),
4935 Vec3::new(0.18, 0.11, 0.07),
4936 Vec3::new(0.10, 0.42, 0.56),
4937 ),
4938 TimeOfDayPreset3D::BrightNoon => (
4939 Vec3::new(0.97, 0.98, 0.99),
4940 Vec3::new(0.14, 0.15, 0.17),
4941 Vec3::new(0.06, 0.46, 0.57),
4942 ),
4943 TimeOfDayPreset3D::GoldenSunset => (
4944 Vec3::new(0.97, 0.77, 0.63),
4945 Vec3::new(0.22, 0.10, 0.06),
4946 Vec3::new(0.16, 0.34, 0.45),
4947 ),
4948 TimeOfDayPreset3D::NeonMidnight => (
4949 Vec3::new(0.20, 0.25, 0.36),
4950 Vec3::new(0.03, 0.04, 0.09),
4951 Vec3::new(0.04, 0.14, 0.26),
4952 ),
4953 };
4954 let (cloud_rgb, cloud_em, river_rgb, river_rough): (Vec3, Vec3, Vec3, f32) = match weather {
4955 WeatherPreset3D::ClearSunny => (base_cloud_rgb, base_cloud_em, base_river_rgb, 0.08),
4956 WeatherPreset3D::PartlyCloudy => (
4957 base_cloud_rgb.lerp(Vec3::new(0.76, 0.81, 0.87), 0.28),
4958 base_cloud_em.scale(0.72),
4959 base_river_rgb.lerp(Vec3::new(0.10, 0.36, 0.48), 0.22),
4960 0.10,
4961 ),
4962 WeatherPreset3D::MistyFog => (
4963 base_cloud_rgb.lerp(Vec3::new(0.72, 0.78, 0.84), 0.48),
4964 base_cloud_em.scale(0.45),
4965 base_river_rgb.lerp(Vec3::new(0.14, 0.32, 0.40), 0.38),
4966 0.07,
4967 ),
4968 WeatherPreset3D::Rainstorm => (
4969 base_cloud_rgb.lerp(Vec3::new(0.16, 0.21, 0.29), 0.66),
4970 base_cloud_em.scale(0.22),
4971 base_river_rgb.lerp(Vec3::new(0.04, 0.14, 0.22), 0.58),
4972 0.045,
4973 ),
4974 };
4975 let cloud_color: Color = Color::rgb(
4976 (cloud_rgb.get_x().clamp(0.0, 1.0) * 255.0) as u8,
4977 (cloud_rgb.get_y().clamp(0.0, 1.0) * 255.0) as u8,
4978 (cloud_rgb.get_z().clamp(0.0, 1.0) * 255.0) as u8,
4979 );
4980 let mut cloud_mat: PbrMaterial = PbrMaterial::dielectric(cloud_color, 0.92)
4981 .with_surface_detail(SurfaceDetailMode::VolumetricCloud);
4982 cloud_mat.set_emissive(cloud_em);
4983 let river_color: Color = Color::rgb(
4984 (river_rgb.get_x().clamp(0.0, 1.0) * 255.0) as u8,
4985 (river_rgb.get_y().clamp(0.0, 1.0) * 255.0) as u8,
4986 (river_rgb.get_z().clamp(0.0, 1.0) * 255.0) as u8,
4987 );
4988 let river_mat: PbrMaterial = PbrMaterial::pbr(river_color, 0.08, river_rough, 0.86)
4989 .with_surface_detail(SurfaceDetailMode::RiverWater);
4990 {
4991 let Self {
4992 city_ecosystem,
4993 objects,
4994 ..
4995 } = self;
4996 for cloud in city_ecosystem.get_clouds().iter() {
4997 if let Some(cloud_obj) = objects.get_mut(cloud.get_object_index()) {
4998 cloud_obj.set_material(cloud_mat);
4999 }
5000 }
5001 for &river_idx in city_ecosystem.get_river_water_objects().iter() {
5002 if let Some(river_obj) = objects.get_mut(river_idx) {
5003 river_obj.set_material(river_mat);
5004 }
5005 }
5006 }
5007 if weather == WeatherPreset3D::Rainstorm
5008 && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES
5009 {
5010 let cam_pos: Vec3 = self.get_camera().get_position();
5011 let cam_fwd: Vec3 = self.get_camera().forward();
5012 let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
5013 rain_cfg.set_origin(
5014 cam_pos
5015 .add(cam_fwd.scale(14.0))
5016 .add(Vec3::new(0.0, 6.5, 0.0)),
5017 );
5018 rain_cfg.set_base_velocity(Vec3::new(-3.2, -21.0, 1.6));
5019 rain_cfg.set_velocity_spread(3.8);
5020 rain_cfg.set_start_color(Color::rgba(175, 224, 255, 195));
5021 rain_cfg.set_end_color(Color::rgba(92, 162, 235, 45));
5022 rain_cfg.set_start_size_m(0.055);
5023 rain_cfg.set_end_size_m(0.022);
5024 rain_cfg.set_min_lifetime(0.45);
5025 rain_cfg.set_max_lifetime(0.85);
5026 rain_cfg.set_emissive_boost(1.1);
5027 self.get_mut_niagara().emit_burst(12, &rain_cfg);
5028 }
5029 self.bump_world_revision();
5030 }
5031
5032 pub fn set_time_of_day_preset(&mut self, preset: TimeOfDayPreset3D) -> f32 {
5042 {
5043 let Self {
5044 time_of_day_preset, ..
5045 } = self;
5046 *time_of_day_preset = preset;
5047 }
5048 self.sync_environment_lighting();
5049 self.get_sun().get_time_of_day()
5050 }
5051
5052 pub fn cycle_time_of_day_preset(&mut self) -> TimeOfDayPreset3D {
5058 let next: TimeOfDayPreset3D = self.time_of_day_preset().next();
5059 let _: f32 = self.set_time_of_day_preset(next);
5060 next
5061 }
5062
5063 pub fn set_weather_preset(&mut self, preset: WeatherPreset3D) {
5069 {
5070 let Self { weather_preset, .. } = self;
5071 *weather_preset = preset;
5072 }
5073 self.sync_environment_lighting();
5074 }
5075
5076 pub fn cycle_weather_preset(&mut self) -> WeatherPreset3D {
5082 let next: WeatherPreset3D = self.weather_preset().next();
5083 self.set_weather_preset(next);
5084 next
5085 }
5086
5087 pub fn apply_atmosphere_preset(&mut self, preset: u8) -> f32 {
5097 let clamped: u8 = preset.min(3);
5098 self.set_atmosphere_preset(clamped);
5099 let (tod, weather): (TimeOfDayPreset3D, WeatherPreset3D) = match clamped {
5100 1 => (TimeOfDayPreset3D::NeonMidnight, WeatherPreset3D::Rainstorm),
5101 2 => (TimeOfDayPreset3D::BrightNoon, WeatherPreset3D::ClearSunny),
5102 3 => (TimeOfDayPreset3D::NeonMidnight, WeatherPreset3D::ClearSunny),
5103 _ => (TimeOfDayPreset3D::GoldenSunset, WeatherPreset3D::ClearSunny),
5104 };
5105 {
5106 let Self {
5107 time_of_day_preset,
5108 weather_preset,
5109 ..
5110 } = self;
5111 *time_of_day_preset = tod;
5112 *weather_preset = weather;
5113 }
5114 self.sync_environment_lighting();
5115 self.get_sun().get_time_of_day()
5116 }
5117
5118 pub fn add_point_light(&mut self, light: PointLight3D) -> usize {
5128 let light_idx: usize = self.get_point_lights().len();
5129 self.get_mut_point_lights().push(light);
5130 self.bump_world_revision();
5131 light_idx
5132 }
5133
5134 pub fn add_spot_light(&mut self, light: SpotLight3D) -> usize {
5144 let light_idx: usize = self.get_spot_lights().len();
5145 self.get_mut_spot_lights().push(light);
5146 self.bump_world_revision();
5147 light_idx
5148 }
5149
5150 pub fn clear_local_lights(&mut self) {
5152 self.get_mut_point_lights().clear();
5153 self.get_mut_spot_lights().clear();
5154 self.bump_world_revision();
5155 }
5156
5157 pub fn emit_particles_3d(&mut self, config: &NiagaraEmitterConfig3D, count: usize) -> usize {
5168 self.get_mut_niagara().emit_burst(count, config);
5169 let active: usize = self.get_niagara().get_active_count();
5170 if count > 0 {
5171 self.bump_world_revision();
5172 }
5173 active
5174 }
5175
5176 #[must_use]
5186 pub fn create_dense_open_world_city(blocks_radius: i32) -> Self {
5187 let radius: i32 = blocks_radius.clamp(1, 5);
5188 let mut world: Self = Self::create_open_world_city();
5189 let dense_occluder: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
5190 DENSE_TOWER_MESH_NAME,
5191 1.0,
5192 1.0,
5193 1.0,
5194 true,
5195 PbrMaterial::default(),
5196 )));
5197 let archetypes: [usize; 6] = world.register_building_archetypes();
5198 let facades: [PbrMaterial; 6] = Self::curated_skyline_palettes();
5199 let neon_palette: [Color; 4] = [
5200 Color::hex(0x38BDF8),
5201 Color::hex(0xF43F5E),
5202 Color::hex(0xA855F7),
5203 Color::hex(0x34D399),
5204 ];
5205 let mut serial: usize = 0;
5206 for bx in -radius..=radius {
5207 for bz in -radius..=radius {
5208 if bx == 0 && (-3..=3).contains(&bz) {
5209 continue;
5210 }
5211 let center_x: f32 = (bx as f32) * 26.0;
5212 let center_z: f32 = (bz as f32) * 24.0 - 16.0;
5213 for sub in 0..4usize {
5214 let off_x: f32 = if (sub & 1) == 0 { -5.5 } else { 5.5 };
5215 let off_z: f32 = if (sub & 2) == 0 { -5.5 } else { 5.5 };
5216 let px: f32 = center_x + off_x;
5217 let pz: f32 = center_z + off_z;
5218 let (d_spine, _): (f32, f32) = Self::loop_lateral_offset(px, pz);
5219 if (49.0..=79.0).contains(&d_spine) || px > 134.0 {
5220 continue;
5221 }
5222 let height_m: f32 = 16.0 + (((serial * 11 + sub * 7) % 6) as f32) * 8.0;
5223 let width_m: f32 = 8.0 + ((serial % 3) as f32) * 1.4;
5224 let mat: PbrMaterial = facades[serial % facades.len()];
5225 let mesh_id: usize = if sub % 2 == 0 {
5226 dense_occluder
5227 } else {
5228 archetypes[(serial + sub) % archetypes.len()]
5229 };
5230 let _: usize = world.spawn_object(
5231 &format!("dense_bldg_{serial}"),
5232 mesh_id,
5233 Transform3D::new(
5234 Vec3::new(px, 0.0, pz),
5235 0.0,
5236 Vec3::new(width_m, height_m, 9.0),
5237 ),
5238 mat,
5239 true,
5240 );
5241 serial += 1;
5242 }
5243 if (bx + bz).abs() <= 2 && world.get_point_lights().len() < 32 {
5244 let _: usize = world.add_point_light(PointLight3D::new(
5245 Vec3::new(center_x, 7.0, center_z),
5246 neon_palette[serial % neon_palette.len()],
5247 4.5,
5248 22.0,
5249 ));
5250 }
5251 }
5252 }
5253 world.ensure_bvh();
5254 world
5255 }
5256
5257 pub fn cycle_car_camera_mode(&mut self) -> CameraMode3D {
5263 let cur_mode: CameraMode3D = self.active_camera_mode();
5264 let next_mode: CameraMode3D = if cur_mode.is_city_camera() {
5265 let Self {
5266 last_car_camera_mode,
5267 ..
5268 } = self;
5269 *last_car_camera_mode
5270 } else {
5271 let cur_pos: Option<usize> = CAR_CAMERA_CYCLE
5272 .iter()
5273 .position(|m: &CameraMode3D| *m == cur_mode);
5274 let next_idx: usize =
5275 cur_pos.map_or(0, |idx: usize| (idx + 1) % CAR_CAMERA_CYCLE.len());
5276 CAR_CAMERA_CYCLE[next_idx]
5277 };
5278 {
5279 let Self {
5280 last_car_camera_mode,
5281 ..
5282 } = self;
5283 *last_car_camera_mode = next_mode;
5284 }
5285 self.set_camera_mode(next_mode.as_u8());
5286 self.bump_world_revision();
5287 next_mode
5288 }
5289
5290 pub fn cycle_city_camera_mode(&mut self) -> CameraMode3D {
5296 let cur_mode: CameraMode3D = self.active_camera_mode();
5297 let next_mode: CameraMode3D = if !cur_mode.is_city_camera() {
5298 {
5299 let Self {
5300 last_car_camera_mode,
5301 ..
5302 } = self;
5303 *last_car_camera_mode = cur_mode;
5304 }
5305 CITY_CAMERA_CYCLE[0]
5306 } else {
5307 let cur_pos: Option<usize> = CITY_CAMERA_CYCLE
5308 .iter()
5309 .position(|m: &CameraMode3D| *m == cur_mode);
5310 match cur_pos {
5311 Some(idx) if idx + 1 < CITY_CAMERA_CYCLE.len() => CITY_CAMERA_CYCLE[idx + 1],
5312 _ => {
5313 let Self {
5314 last_car_camera_mode,
5315 ..
5316 } = self;
5317 *last_car_camera_mode
5318 }
5319 }
5320 };
5321 self.set_camera_mode(next_mode.as_u8());
5322 self.bump_world_revision();
5323 next_mode
5324 }
5325
5326 pub fn cycle_camera_mode(&mut self) -> u8 {
5332 self.cycle_car_camera_mode().as_u8()
5333 }
5334
5335 #[must_use]
5345 pub fn ground_play_bounds(&self) -> Option<(f32, f32, f32, f32)> {
5346 let mut found: bool = false;
5347 let mut min_x: f32 = f32::INFINITY;
5348 let mut max_x: f32 = f32::NEG_INFINITY;
5349 let mut min_z: f32 = f32::INFINITY;
5350 let mut max_z: f32 = f32::NEG_INFINITY;
5351 for obj in self.get_objects().iter() {
5352 if obj.get_ray_trace_caster()
5353 || obj.get_material().get_surface_detail() == SurfaceDetailMode::OceanWater
5354 {
5355 continue;
5356 }
5357 let blue_val: AxisAlignedBox3D = obj.get_world_bounds();
5358 let span_x: f32 = blue_val.get_max().get_x() - blue_val.get_min().get_x();
5359 let span_z: f32 = blue_val.get_max().get_z() - blue_val.get_min().get_z();
5360 if span_x >= 16.0 && span_z >= 16.0 {
5361 min_x = min_x.min(blue_val.get_min().get_x());
5362 max_x = max_x.max(blue_val.get_max().get_x());
5363 min_z = min_z.min(blue_val.get_min().get_z());
5364 max_z = max_z.max(blue_val.get_max().get_z());
5365 found = true;
5366 }
5367 }
5368 if found {
5369 Some((min_x, max_x, min_z, max_z))
5370 } else {
5371 None
5372 }
5373 }
5374
5375 #[must_use]
5387 pub fn mesh_oriented_box_collision(
5388 &self,
5389 candidate: OrientedBox3D,
5390 ignore_idx: Option<usize>,
5391 ) -> Option<MeshCollisionHit3D> {
5392 let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
5393 let mut deepest: Option<MeshCollisionHit3D> = None;
5394 let objects: &[SceneObject3D] = self.get_objects().as_slice();
5395 let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
5396 for (idx, obj) in objects.iter().enumerate() {
5397 if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
5398 {
5399 continue;
5400 }
5401 let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
5402 if !Self::boxes_overlap(query_bounds, obj_bounds) {
5403 continue;
5404 }
5405 let Some(mesh) = mesh_lib
5406 .get(obj.get_mesh_id())
5407 .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
5408 else {
5409 continue;
5410 };
5411 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
5412 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
5413 let obj_tr: Transform3D = obj.get_transform();
5414 let model_mat: Mat4 = obj_tr.to_mat4();
5415 let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
5416 let mut hit_this_obj: bool = false;
5417 if meshlets.is_empty() {
5418 for tri in indices.iter() {
5419 let (i0, i1, i2): (usize, usize, usize) =
5420 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
5421 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
5422 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
5423 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
5424 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
5425 if let Some((normal, pen, contact)) =
5426 candidate.intersect_triangle_world(w0, w1, w2)
5427 {
5428 hit_this_obj = true;
5429 let replace: bool = deepest
5430 .map(|delta_val: MeshCollisionHit3D| {
5431 pen > delta_val.get_penetration()
5432 })
5433 .unwrap_or(true);
5434 if replace {
5435 deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
5436 }
5437 }
5438 }
5439 }
5440 } else {
5441 for ml in meshlets.iter() {
5442 let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
5443 if !Self::boxes_overlap(query_bounds, ml_bounds) {
5444 continue;
5445 }
5446 let start: usize = ml.get_first_tri() as usize;
5447 let end: usize = start
5448 .saturating_add(ml.get_tri_count() as usize)
5449 .min(indices.len());
5450 for tri in indices[start..end].iter() {
5451 let (i0, i1, i2): (usize, usize, usize) =
5452 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
5453 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
5454 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
5455 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
5456 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
5457 if let Some((normal, pen, contact)) =
5458 candidate.intersect_triangle_world(w0, w1, w2)
5459 {
5460 hit_this_obj = true;
5461 let replace: bool = deepest
5462 .map(|distance_val: MeshCollisionHit3D| {
5463 pen > distance_val.get_penetration()
5464 })
5465 .unwrap_or(true);
5466 if replace {
5467 deepest =
5468 Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
5469 }
5470 }
5471 }
5472 }
5473 }
5474 }
5475 if !hit_this_obj
5476 && mesh.get_is_closed()
5477 && Self::point_in_bounds(candidate.get_center(), obj_bounds)
5478 && let Some(inside_hit) =
5479 Self::point_inside_closed_mesh_mtv(idx, candidate, verts, indices, model_mat)
5480 {
5481 let replace: bool = deepest
5482 .map(|prev_hit: MeshCollisionHit3D| {
5483 inside_hit.get_penetration() > prev_hit.get_penetration()
5484 })
5485 .unwrap_or(true);
5486 if replace {
5487 deepest = Some(inside_hit);
5488 }
5489 }
5490 }
5491 deepest
5492 }
5493
5494 #[inline]
5505 #[must_use]
5506 fn point_in_bounds(point: Vec3, bounds: AxisAlignedBox3D) -> bool {
5507 let bmin: Vec3 = bounds.get_min();
5508 let bmax: Vec3 = bounds.get_max();
5509 point.get_x() >= bmin.get_x()
5510 && point.get_x() <= bmax.get_x()
5511 && point.get_y() >= bmin.get_y()
5512 && point.get_y() <= bmax.get_y()
5513 && point.get_z() >= bmin.get_z()
5514 && point.get_z() <= bmax.get_z()
5515 }
5516
5517 #[inline]
5530 #[must_use]
5531 fn closest_point_on_triangle(point: Vec3, v0: Vec3, v1: Vec3, v2: Vec3) -> Vec3 {
5532 let ab: Vec3 = v1.sub(v0);
5533 let ac: Vec3 = v2.sub(v0);
5534 let ap: Vec3 = point.sub(v0);
5535 let d1: f32 = ab.dot(ap);
5536 let d2: f32 = ac.dot(ap);
5537 if d1 <= 0.0 && d2 <= 0.0 {
5538 return v0;
5539 }
5540 let bp: Vec3 = point.sub(v1);
5541 let d3: f32 = ab.dot(bp);
5542 let d4: f32 = ac.dot(bp);
5543 if d3 >= 0.0 && d4 <= d3 {
5544 return v1;
5545 }
5546 let vc: f32 = d1 * d4 - d3 * d2;
5547 if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
5548 let weight_v: f32 = d1 / (d1 - d3).max(1.0e-7);
5549 return v0.add(ab.scale(weight_v));
5550 }
5551 let cp: Vec3 = point.sub(v2);
5552 let d5: f32 = ab.dot(cp);
5553 let d6: f32 = ac.dot(cp);
5554 if d6 >= 0.0 && d5 <= d6 {
5555 return v2;
5556 }
5557 let vb: f32 = d5 * d2 - d1 * d6;
5558 if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
5559 let weight_w: f32 = d2 / (d2 - d6).max(1.0e-7);
5560 return v0.add(ac.scale(weight_w));
5561 }
5562 let va: f32 = d3 * d6 - d5 * d4;
5563 if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
5564 let denom_bc: f32 = ((d4 - d3) + (d5 - d6)).max(1.0e-7);
5565 let weight_w: f32 = (d4 - d3) / denom_bc;
5566 return v1.add(v2.sub(v1).scale(weight_w));
5567 }
5568 let denom: f32 = (va + vb + vc).max(1.0e-7);
5569 let weight_v: f32 = vb / denom;
5570 let weight_w: f32 = vc / denom;
5571 v0.add(ab.scale(weight_v)).add(ac.scale(weight_w))
5572 }
5573
5574 #[must_use]
5588 fn point_inside_closed_mesh_mtv(
5589 obj_idx: usize,
5590 candidate: OrientedBox3D,
5591 verts: &[Vertex3D],
5592 indices: &[[u32; 3]],
5593 model_mat: Mat4,
5594 ) -> Option<MeshCollisionHit3D> {
5595 let center: Vec3 = candidate.get_center();
5596 let parity_dir: Vec3 = Vec3::new(1.0, 1.37e-4, 2.71e-4).normalize();
5597 let mut crossings: u32 = 0;
5598 let mut best_horiz_dist_sq: f32 = f32::INFINITY;
5599 let mut best_horiz_cp: Vec3 = center;
5600 let mut best_horiz_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
5601 let mut best_any_dist_sq: f32 = f32::INFINITY;
5602 let mut best_any_cp: Vec3 = center;
5603 let mut best_any_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
5604 for tri in indices.iter() {
5605 let (i0, i1, i2): (usize, usize, usize) =
5606 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
5607 if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
5608 continue;
5609 }
5610 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
5611 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
5612 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
5613 if Self::ray_intersect_triangle(center, parity_dir, w0, w1, w2, 1.0e-5, f32::INFINITY)
5614 .is_some()
5615 {
5616 crossings = crossings.wrapping_add(1);
5617 }
5618 let cp: Vec3 = Self::closest_point_on_triangle(center, w0, w1, w2);
5619 let delta: Vec3 = cp.sub(center);
5620 let dist_sq: f32 = delta.length_sq();
5621 let raw_face_n: Vec3 = w1.sub(w0).cross(w2.sub(w0));
5622 let face_n: Vec3 = if raw_face_n.length_sq() > 1.0e-10 {
5623 raw_face_n.normalize()
5624 } else {
5625 Vec3::new(1.0, 0.0, 0.0)
5626 };
5627 if dist_sq < best_any_dist_sq {
5628 best_any_dist_sq = dist_sq;
5629 best_any_cp = cp;
5630 best_any_n = face_n;
5631 }
5632 let horiz_mag_sq: f32 =
5633 face_n.get_x() * face_n.get_x() + face_n.get_z() * face_n.get_z();
5634 if horiz_mag_sq > 0.25 && dist_sq < best_horiz_dist_sq {
5635 best_horiz_dist_sq = dist_sq;
5636 best_horiz_cp = cp;
5637 best_horiz_n = Vec3::new(face_n.get_x(), 0.0, face_n.get_z()).normalize();
5638 }
5639 }
5640 if (crossings & 1) == 0 {
5641 return None;
5642 }
5643 let (target_cp, fallback_n, target_dist_sq): (Vec3, Vec3, f32) =
5644 if best_horiz_dist_sq.is_finite() {
5645 (best_horiz_cp, best_horiz_n, best_horiz_dist_sq)
5646 } else if best_any_dist_sq.is_finite() {
5647 (best_any_cp, best_any_n, best_any_dist_sq)
5648 } else {
5649 return None;
5650 };
5651 let push_raw: Vec3 = target_cp.sub(center);
5652 let push_n: Vec3 = if push_raw.length_sq() > 1.0e-8 {
5653 push_raw.normalize()
5654 } else {
5655 fallback_n
5656 };
5657 let axes: [Vec3; 3] = candidate.get_axes();
5658 let half_extents: Vec3 = candidate.get_half_extents();
5659 let obb_proj: f32 = axes[0].dot(push_n).abs() * half_extents.get_x()
5660 + axes[1].dot(push_n).abs() * half_extents.get_y()
5661 + axes[2].dot(push_n).abs() * half_extents.get_z();
5662 let total_pen: f32 = target_dist_sq.sqrt() + obb_proj;
5663 Some(MeshCollisionHit3D::new(
5664 obj_idx, push_n, total_pen, target_cp,
5665 ))
5666 }
5667
5668 #[must_use]
5680 fn horizontal_collision_normal(&self, candidate: OrientedBox3D, obj_idx: usize) -> Vec3 {
5681 let Some(obj) = self.get_objects().get(obj_idx) else {
5682 return Vec3::zero();
5683 };
5684 if let Some(mesh) = self
5685 .get_mesh_library()
5686 .get(obj.get_mesh_id())
5687 .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
5688 {
5689 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
5690 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
5691 let model_mat: Mat4 = obj.get_transform().to_mat4();
5692 let mut best_pen: f32 = f32::INFINITY;
5693 let mut best_hn: Vec3 = Vec3::zero();
5694 for tri in indices.iter() {
5695 let (i0, i1, i2): (usize, usize, usize) =
5696 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
5697 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
5698 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
5699 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
5700 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
5701 if let Some((normal, pen, _)) = candidate.intersect_triangle_world(w0, w1, w2) {
5702 let hn: Vec3 = Vec3::new(normal.get_x(), 0.0, normal.get_z());
5703 if hn.length_sq() > 0.25 && pen < best_pen {
5704 best_pen = pen;
5705 best_hn = hn.normalize();
5706 }
5707 }
5708 }
5709 }
5710 if best_hn.length_sq() > 1.0e-6 {
5711 return best_hn;
5712 }
5713 }
5714 let bounds: AxisAlignedBox3D = obj.get_world_bounds();
5715 let bcenter: Vec3 = bounds.get_min().add(bounds.get_max()).scale(0.5);
5716 let diff: Vec3 = candidate.get_center().sub(bcenter);
5717 let horiz: Vec3 = Vec3::new(diff.get_x(), 0.0, diff.get_z());
5718 if horiz.length_sq() > 1.0e-6 {
5719 horiz.normalize()
5720 } else {
5721 Vec3::new(1.0, 0.0, 0.0)
5722 }
5723 }
5724
5725 #[inline]
5737 #[must_use]
5738 fn clamp_horizontal_to_ground(
5739 mut pos: Vec3,
5740 ground_limits: Option<(f32, f32, f32, f32)>,
5741 ground_margin: f32,
5742 ) -> Vec3 {
5743 if let Some((gx0, gx1, gz0, gz1)) = ground_limits {
5744 let lo_x: f32 = (gx0 + ground_margin).min(gx1);
5745 let hi_x: f32 = (gx1 - ground_margin).max(lo_x);
5746 let lo_z: f32 = (gz0 + ground_margin).min(gz1);
5747 let hi_z: f32 = (gz1 - ground_margin).max(lo_z);
5748 pos.set_x(pos.get_x().clamp(lo_x, hi_x));
5749 pos.set_z(pos.get_z().clamp(lo_z, hi_z));
5750 }
5751 pos
5752 }
5753
5754 fn depenetrate_vehicle_horizontally(
5769 &self,
5770 transform_val: &mut Transform3D,
5771 mesh_bounds: AxisAlignedBox3D,
5772 vehicle_idx: usize,
5773 ground_limits: Option<(f32, f32, f32, f32)>,
5774 ground_margin: f32,
5775 ) -> bool {
5776 let mut adjusted: bool = false;
5777 for _ in 0..COLLISION_MTV_MAX_ITERS {
5778 let Some(hit) = self.collides_with_obstacles(*transform_val, mesh_bounds, vehicle_idx)
5779 else {
5780 break;
5781 };
5782 let raw_hn: Vec3 = Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
5783 let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
5784 raw_hn.normalize()
5785 } else {
5786 self.horizontal_collision_normal(
5787 transform_val.to_oriented_box(mesh_bounds),
5788 hit.get_object_index(),
5789 )
5790 };
5791 if hn.length_sq() <= 1.0e-6 {
5792 break;
5793 }
5794 let push_dist: f32 = hit.get_penetration() + COLLISION_MTV_PUSH_EPS;
5795 let cur_pos: Vec3 = transform_val.get_position();
5796 let pushed_pos: Vec3 = Self::clamp_horizontal_to_ground(
5797 Vec3::new(
5798 cur_pos.get_x() + hn.get_x() * push_dist,
5799 cur_pos.get_y(),
5800 cur_pos.get_z() + hn.get_z() * push_dist,
5801 ),
5802 ground_limits,
5803 ground_margin,
5804 );
5805 transform_val.set_position(pushed_pos);
5806 adjusted = true;
5807 }
5808 adjusted
5809 }
5810
5811 #[must_use]
5825 pub fn raycast_solid_meshes(
5826 &self,
5827 origin: Vec3,
5828 direction: Vec3,
5829 max_dist: f32,
5830 ignore_idx: Option<usize>,
5831 ) -> Option<RayHit3D> {
5832 let dir: Vec3 = direction.normalize();
5833 let inv_dir: Vec3 = Ray3D::safe_inv_vec(dir);
5834 let t_min: f32 = 1e-4;
5835 let mut best_t: f32 = max_dist;
5836 let mut best_hit: Option<RayHit3D> = None;
5837 let objects: &[SceneObject3D] = self.get_objects().as_slice();
5838 let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
5839 let ignore_is_static_caster: bool = ignore_idx
5840 .and_then(|idx: usize| objects.get(idx))
5841 .is_some_and(|obj: &SceneObject3D| obj.get_ray_trace_caster() && !obj.get_is_dynamic());
5842 let use_static_bvh: bool =
5843 !self.get_bvh_dirty() && !self.get_bvh().is_empty() && !ignore_is_static_caster;
5844 if use_static_bvh
5845 && let Some((hit_dist, tri_idx)) = self
5846 .get_bvh()
5847 .trace_closest_raw(origin, dir, inv_dir, t_min, best_t)
5848 {
5849 let bvh_tris: &[BvhTriangle] = self.get_bvh().get_triangles().as_slice();
5850 if let Some(hit_tri) = bvh_tris.get(tri_idx) {
5851 let raw_normal: Vec3 = hit_tri.get_normal();
5852 let oriented_normal: Vec3 = if raw_normal.dot(dir) > 0.0 {
5853 raw_normal.scale(-1.0)
5854 } else {
5855 raw_normal
5856 };
5857 best_t = hit_dist;
5858 best_hit = Some(RayHit3D {
5859 distance: hit_dist,
5860 point: origin.add(dir.scale(hit_dist)),
5861 normal: oriented_normal,
5862 material: hit_tri.get_material(),
5863 });
5864 }
5865 }
5866 for (idx, obj) in objects.iter().enumerate() {
5867 if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
5868 {
5869 continue;
5870 }
5871 if use_static_bvh && obj.get_ray_trace_caster() && !obj.get_is_dynamic() {
5872 continue;
5873 }
5874 if !obj
5875 .get_world_bounds()
5876 .intersect_ray_near(origin, inv_dir, t_min, best_t)
5877 .is_finite()
5878 {
5879 continue;
5880 }
5881 let Some(mesh) = mesh_lib
5882 .get(obj.get_mesh_id())
5883 .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
5884 else {
5885 continue;
5886 };
5887 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
5888 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
5889 let model_mat: Mat4 = obj.get_transform().to_mat4();
5890 let mat: PbrMaterial = obj.get_material();
5891 for tri in indices.iter() {
5892 let (i0, i1, i2): (usize, usize, usize) =
5893 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
5894 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
5895 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
5896 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
5897 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
5898 if let Some((blend_factor, normal)) =
5899 Self::ray_intersect_triangle(origin, dir, w0, w1, w2, t_min, best_t)
5900 {
5901 best_t = blend_factor;
5902 best_hit = Some(RayHit3D {
5903 distance: blend_factor,
5904 point: origin.add(dir.scale(blend_factor)),
5905 normal,
5906 material: mat,
5907 });
5908 }
5909 }
5910 }
5911 }
5912 best_hit
5913 }
5914
5915 #[inline]
5926 #[must_use]
5927 fn boxes_overlap(alpha_val: AxisAlignedBox3D, blue_val: AxisAlignedBox3D) -> bool {
5928 let ox: bool = alpha_val.get_min().get_x() < blue_val.get_max().get_x()
5929 && alpha_val.get_max().get_x() > blue_val.get_min().get_x();
5930 let oy: bool = alpha_val.get_min().get_y() < blue_val.get_max().get_y()
5931 && alpha_val.get_max().get_y() > blue_val.get_min().get_y();
5932 let oz: bool = alpha_val.get_min().get_z() < blue_val.get_max().get_z()
5933 && alpha_val.get_max().get_z() > blue_val.get_min().get_z();
5934 ox && oy && oz
5935 }
5936
5937 #[inline]
5953 #[must_use]
5954 fn ray_intersect_triangle(
5955 origin: Vec3,
5956 dir: Vec3,
5957 v0: Vec3,
5958 v1: Vec3,
5959 v2: Vec3,
5960 t_min: f32,
5961 t_max: f32,
5962 ) -> Option<(f32, Vec3)> {
5963 let e1: Vec3 = v1.sub(v0);
5964 let e2: Vec3 = v2.sub(v0);
5965 let pvec: Vec3 = dir.cross(e2);
5966 let det: f32 = e1.dot(pvec);
5967 if det.abs() < 1e-7 {
5968 return None;
5969 }
5970 let inv_det: f32 = 1.0 / det;
5971 let tvec: Vec3 = origin.sub(v0);
5972 let tex_u: f32 = tvec.dot(pvec) * inv_det;
5973 if !(0.0..=1.0).contains(&tex_u) {
5974 return None;
5975 }
5976 let qvec: Vec3 = tvec.cross(e1);
5977 let item_val: f32 = dir.dot(qvec) * inv_det;
5978 if item_val < 0.0 || tex_u + item_val > 1.0 {
5979 return None;
5980 }
5981 let blend_factor: f32 = e2.dot(qvec) * inv_det;
5982 if blend_factor <= t_min || blend_factor > t_max {
5983 return None;
5984 }
5985 let raw_n: Vec3 = e1.cross(e2).normalize();
5986 let normal: Vec3 = if raw_n.dot(dir) > 0.0 {
5987 raw_n.scale(-1.0)
5988 } else {
5989 raw_n
5990 };
5991 Some((blend_factor, normal))
5992 }
5993
5994 #[must_use]
6007 fn collides_with_obstacles(
6008 &self,
6009 candidate_tr: Transform3D,
6010 local_bounds: AxisAlignedBox3D,
6011 ignore_idx: usize,
6012 ) -> Option<MeshCollisionHit3D> {
6013 let oriented_box: OrientedBox3D = candidate_tr.to_oriented_box(local_bounds);
6014 self.mesh_oriented_box_collision(oriented_box, Some(ignore_idx))
6015 }
6016
6017 #[must_use]
6028 fn mesh_oriented_box_static_collision(
6029 &self,
6030 candidate: OrientedBox3D,
6031 ignore_idx: Option<usize>,
6032 ) -> Option<MeshCollisionHit3D> {
6033 let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
6034 let mut deepest: Option<MeshCollisionHit3D> = None;
6035 let objects: &[SceneObject3D] = self.get_objects().as_slice();
6036 let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
6037 for (idx, obj) in objects.iter().enumerate() {
6038 let is_solid: bool = obj.get_solid_collider() || obj.get_ray_trace_caster();
6039 if ignore_idx == Some(idx) || obj.get_is_dynamic() || !is_solid {
6040 continue;
6041 }
6042 let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
6043 if !Self::boxes_overlap(query_bounds, obj_bounds) {
6044 continue;
6045 }
6046 let Some(mesh) = mesh_lib
6047 .get(obj.get_mesh_id())
6048 .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
6049 else {
6050 continue;
6051 };
6052 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
6053 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
6054 let model_mat: Mat4 = obj.get_transform().to_mat4();
6055 let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
6056 let mut hit_this_obj: bool = false;
6057 if meshlets.is_empty() {
6058 for tri in indices.iter() {
6059 let (i0, i1, i2): (usize, usize, usize) =
6060 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
6061 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
6062 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
6063 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
6064 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
6065 if let Some((normal, pen, contact)) =
6066 candidate.intersect_triangle_world(w0, w1, w2)
6067 {
6068 hit_this_obj = true;
6069 let replace: bool = deepest
6070 .map(|prev: MeshCollisionHit3D| pen > prev.get_penetration())
6071 .unwrap_or(true);
6072 if replace {
6073 deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
6074 }
6075 }
6076 }
6077 }
6078 } else {
6079 for ml in meshlets.iter() {
6080 let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
6081 if !Self::boxes_overlap(query_bounds, ml_bounds) {
6082 continue;
6083 }
6084 let start: usize = ml.get_first_tri() as usize;
6085 let end: usize = start
6086 .saturating_add(ml.get_tri_count() as usize)
6087 .min(indices.len());
6088 for tri in indices[start..end].iter() {
6089 let (i0, i1, i2): (usize, usize, usize) =
6090 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
6091 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
6092 let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
6093 let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
6094 let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
6095 if let Some((normal, pen, contact)) =
6096 candidate.intersect_triangle_world(w0, w1, w2)
6097 {
6098 hit_this_obj = true;
6099 let replace: bool = deepest
6100 .map(|prev: MeshCollisionHit3D| pen > prev.get_penetration())
6101 .unwrap_or(true);
6102 if replace {
6103 deepest =
6104 Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
6105 }
6106 }
6107 }
6108 }
6109 }
6110 }
6111 if !hit_this_obj
6112 && mesh.get_is_closed()
6113 && Self::point_in_bounds(candidate.get_center(), obj_bounds)
6114 && let Some(inside_hit) =
6115 Self::point_inside_closed_mesh_mtv(idx, candidate, verts, indices, model_mat)
6116 {
6117 let replace: bool = deepest
6118 .map(|prev: MeshCollisionHit3D| {
6119 inside_hit.get_penetration() > prev.get_penetration()
6120 })
6121 .unwrap_or(true);
6122 if replace {
6123 deepest = Some(inside_hit);
6124 }
6125 }
6126 }
6127 deepest
6128 }
6129
6130 fn depenetrate_vehicle_static_horizontally(
6144 &self,
6145 transform_val: &mut Transform3D,
6146 mesh_bounds: AxisAlignedBox3D,
6147 vehicle_idx: usize,
6148 ground_limits: Option<(f32, f32, f32, f32)>,
6149 ground_margin: f32,
6150 ) -> bool {
6151 let mut adjusted: bool = false;
6152 for _ in 0..COLLISION_MTV_MAX_ITERS {
6153 let Some(hit) = self.mesh_oriented_box_static_collision(
6154 transform_val.to_oriented_box(mesh_bounds),
6155 Some(vehicle_idx),
6156 ) else {
6157 break;
6158 };
6159 let raw_hn: Vec3 = Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
6160 let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
6161 raw_hn.normalize()
6162 } else {
6163 self.horizontal_collision_normal(
6164 transform_val.to_oriented_box(mesh_bounds),
6165 hit.get_object_index(),
6166 )
6167 };
6168 if hn.length_sq() <= 1.0e-6 {
6169 break;
6170 }
6171 let push_dist: f32 = hit.get_penetration() + COLLISION_MTV_PUSH_EPS;
6172 let cur_pos: Vec3 = transform_val.get_position();
6173 let pushed_pos: Vec3 = Self::clamp_horizontal_to_ground(
6174 Vec3::new(
6175 cur_pos.get_x() + hn.get_x() * push_dist,
6176 cur_pos.get_y(),
6177 cur_pos.get_z() + hn.get_z() * push_dist,
6178 ),
6179 ground_limits,
6180 ground_margin,
6181 );
6182 transform_val.set_position(pushed_pos);
6183 adjusted = true;
6184 }
6185 adjusted
6186 }
6187
6188 #[inline]
6198 #[must_use]
6199 fn wrap_angle_rad(angle: f32) -> f32 {
6200 let two_pi: f32 = 2.0 * PI;
6201 let wrapped: f32 = (angle + PI).rem_euclid(two_pi) - PI;
6202 if wrapped <= -PI {
6203 wrapped + two_pi
6204 } else {
6205 wrapped
6206 }
6207 }
6208
6209 #[must_use]
6219 fn local_bounds_for_mesh(&self, mesh_id: usize) -> AxisAlignedBox3D {
6220 self.get_mesh_library()
6221 .get(mesh_id)
6222 .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
6223 .map(Mesh3D::get_bounds)
6224 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)))
6225 }
6226
6227 #[must_use]
6240 fn compute_static_contact_point(
6241 obb: OrientedBox3D,
6242 hn: Vec3,
6243 obstacle_bounds: AxisAlignedBox3D,
6244 fallback_contact: Vec3,
6245 ) -> Vec3 {
6246 let axes: [Vec3; 3] = obb.get_axes();
6247 let half: Vec3 = obb.get_half_extents();
6248 let center: Vec3 = obb.get_center();
6249 let ux: f32 = axes[0].get_x() * half.get_x();
6250 let uz: f32 = axes[0].get_z() * half.get_x();
6251 let vx: f32 = axes[2].get_x() * half.get_z();
6252 let vz: f32 = axes[2].get_z() * half.get_z();
6253 let cx: f32 = center.get_x();
6254 let cz: f32 = center.get_z();
6255 let corners: [(f32, f32); 4] = [
6256 (cx + ux + vx, cz + uz + vz),
6257 (cx + ux - vx, cz + uz - vz),
6258 (cx - ux + vx, cz - uz + vz),
6259 (cx - ux - vx, cz - uz - vz),
6260 ];
6261 let bmin: Vec3 = obstacle_bounds.get_min();
6262 let bmax: Vec3 = obstacle_bounds.get_max();
6263 let pad: f32 = 0.15;
6264 let in_obstacle: fn(f32, f32, Vec3, Vec3, f32) -> bool =
6265 |px: f32, pz: f32, lo: Vec3, hi: Vec3, margin: f32| -> bool {
6266 px >= lo.get_x() - margin
6267 && px <= hi.get_x() + margin
6268 && pz >= lo.get_z() - margin
6269 && pz <= hi.get_z() + margin
6270 };
6271 let mut best_in_proj: f32 = f32::NEG_INFINITY;
6272 let mut any_in: bool = false;
6273 let mut best_all_proj: f32 = f32::NEG_INFINITY;
6274 for &(px, pz) in corners.iter() {
6275 let proj: f32 = -(px * hn.get_x() + pz * hn.get_z());
6276 if proj > best_all_proj {
6277 best_all_proj = proj;
6278 }
6279 if in_obstacle(px, pz, bmin, bmax, pad) {
6280 any_in = true;
6281 if proj > best_in_proj {
6282 best_in_proj = proj;
6283 }
6284 }
6285 }
6286 let target_proj: f32 = if any_in { best_in_proj } else { best_all_proj };
6287 let mut sum_x: f32 = 0.0;
6288 let mut sum_z: f32 = 0.0;
6289 let mut cnt: f32 = 0.0;
6290 for &(px, pz) in corners.iter() {
6291 if any_in && !in_obstacle(px, pz, bmin, bmax, pad) {
6292 continue;
6293 }
6294 let proj: f32 = -(px * hn.get_x() + pz * hn.get_z());
6295 if proj >= target_proj - 0.16 {
6296 sum_x += px;
6297 sum_z += pz;
6298 cnt += 1.0;
6299 }
6300 }
6301 if cnt > 0.0 {
6302 Vec3::new(sum_x / cnt, fallback_contact.get_y().max(0.45), sum_z / cnt)
6303 } else {
6304 fallback_contact
6305 }
6306 }
6307
6308 fn apply_static_wall_impulse(
6323 car_pos: Vec3,
6324 vel: &mut Vec3,
6325 yaw_rate: &mut f32,
6326 inertia_pair: (f32, f32),
6327 hn: Vec3,
6328 contact_point: Vec3,
6329 ) -> f32 {
6330 let (inv_m, inv_i): (f32, f32) = inertia_pair;
6331 let raw_rx: f32 = contact_point.get_x() - car_pos.get_x();
6332 let raw_rz: f32 = contact_point.get_z() - car_pos.get_z();
6333 let r_len: f32 = (raw_rx * raw_rx + raw_rz * raw_rz).sqrt();
6334 let (rx, rz): (f32, f32) = if r_len > 2.6 {
6335 let scale_r: f32 = 2.6 / r_len;
6336 (raw_rx * scale_r, raw_rz * scale_r)
6337 } else {
6338 (raw_rx, raw_rz)
6339 };
6340 let v_pt_x: f32 = vel.get_x() + (*yaw_rate) * rz;
6341 let v_pt_z: f32 = vel.get_z() - (*yaw_rate) * rx;
6342 let v_n: f32 = v_pt_x * hn.get_x() + v_pt_z * hn.get_z();
6343 if v_n >= 0.0 {
6344 return 0.0;
6345 }
6346 let approach_speed: f32 = -v_n;
6347 let restitution: f32 = if approach_speed > 1.2 {
6348 COLLISION_WALL_RESTITUTION
6349 } else {
6350 0.0
6351 };
6352 let r_cross_n: f32 = rz * hn.get_x() - rx * hn.get_z();
6353 let denom_n: f32 = inv_m + (r_cross_n * r_cross_n) * inv_i;
6354 let j_n: f32 = (-(1.0 + restitution) * v_n / denom_n.max(1.0e-6)).max(0.0);
6355 vel.set_x(vel.get_x() + hn.get_x() * j_n * inv_m);
6356 vel.set_z(vel.get_z() + hn.get_z() * j_n * inv_m);
6357 *yaw_rate = (*yaw_rate + r_cross_n * j_n * inv_i)
6358 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
6359 let vt_x: f32 = v_pt_x - hn.get_x() * v_n;
6360 let vt_z: f32 = v_pt_z - hn.get_z() * v_n;
6361 let vt_len: f32 = (vt_x * vt_x + vt_z * vt_z).sqrt();
6362 if vt_len > 1.0e-4 && j_n > 0.0 {
6363 let tx: f32 = vt_x / vt_len;
6364 let tz: f32 = vt_z / vt_len;
6365 let r_cross_t: f32 = rz * tx - rx * tz;
6366 let denom_t: f32 = inv_m + (r_cross_t * r_cross_t) * inv_i;
6367 let max_jt: f32 = COLLISION_WALL_FRICTION * j_n;
6368 let j_t: f32 = (-vt_len / denom_t.max(1.0e-6)).clamp(-max_jt, max_jt);
6369 vel.set_x(vel.get_x() + tx * j_t * inv_m);
6370 vel.set_z(vel.get_z() + tz * j_t * inv_m);
6371 *yaw_rate = (*yaw_rate + r_cross_t * j_t * inv_i)
6372 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
6373 }
6374 approach_speed
6375 }
6376
6377 fn step_rigid_vehicle_static_ccd(
6392 &self,
6393 tr: &mut Transform3D,
6394 vel: &mut Vec3,
6395 yaw_rate: &mut f32,
6396 inertia_pair: (f32, f32),
6397 vehicle_spec: (usize, AxisAlignedBox3D),
6398 step_ctx: VehicleCcdStepCtx3D,
6399 ) -> (bool, f32, Vec3, Vec3) {
6400 let (vehicle_idx, mesh_bounds): (usize, AxisAlignedBox3D) = vehicle_spec;
6401 let VehicleCcdStepCtx3D {
6402 sub_dt,
6403 ground_limits,
6404 ground_margin,
6405 } = step_ctx;
6406 let mut moved: bool = self.depenetrate_vehicle_static_horizontally(
6407 tr,
6408 mesh_bounds,
6409 vehicle_idx,
6410 ground_limits,
6411 ground_margin,
6412 );
6413 let mut peak_impact: f32 = 0.0;
6414 let mut peak_contact: Vec3 = tr.get_position();
6415 let mut peak_normal: Vec3 = Vec3::new(0.0, 0.0, 1.0);
6416 let speed: f32 = (vel.get_x() * vel.get_x() + vel.get_z() * vel.get_z()).sqrt();
6417 let linear_dist: f32 = speed * sub_dt;
6418 let angular_dist: f32 = yaw_rate.abs() * sub_dt;
6419 if linear_dist <= 1.0e-6 && angular_dist <= 1.0e-6 {
6420 return (moved, peak_impact, peak_contact, peak_normal);
6421 }
6422 let obb_now: OrientedBox3D = tr.to_oriented_box(mesh_bounds);
6423 let min_half: f32 = obb_now
6424 .get_half_extents()
6425 .get_x()
6426 .min(obb_now.get_half_extents().get_z())
6427 .max(0.25);
6428 let max_lin_step: f32 = (min_half * 0.25).min(COLLISION_CCD_MAX_STEP_M);
6429 let lin_steps: usize =
6430 ((linear_dist / max_lin_step).ceil() as usize).clamp(1, COLLISION_CCD_MAX_SUBSTEPS);
6431 let rot_steps: usize = ((angular_dist / COLLISION_ROT_MAX_STEP_RAD).ceil() as usize)
6432 .clamp(1, COLLISION_ROT_MAX_SUBSTEPS);
6433 let substeps: usize = lin_steps.max(rot_steps);
6434 let step_dt: f32 = sub_dt / (substeps as f32);
6435 for _ in 0..substeps {
6436 let d_yaw: f32 = (*yaw_rate) * step_dt;
6437 if d_yaw.abs() > 1.0e-6 {
6438 let mut rotated: Transform3D = *tr;
6439 rotated.set_yaw_rad(tr.get_yaw_rad() + d_yaw);
6440 if let Some(rot_hit) = self.mesh_oriented_box_static_collision(
6441 rotated.to_oriented_box(mesh_bounds),
6442 Some(vehicle_idx),
6443 ) {
6444 if rot_hit.get_penetration() <= COLLISION_ROT_MAX_PUSH_M {
6445 let mut pushed_rot: Transform3D = rotated;
6446 let _: bool = self.depenetrate_vehicle_static_horizontally(
6447 &mut pushed_rot,
6448 mesh_bounds,
6449 vehicle_idx,
6450 ground_limits,
6451 ground_margin,
6452 );
6453 let shift_m: f32 = pushed_rot
6454 .get_position()
6455 .sub(rotated.get_position())
6456 .length();
6457 if shift_m <= COLLISION_ROT_MAX_PUSH_M
6458 && self
6459 .mesh_oriented_box_static_collision(
6460 pushed_rot.to_oriented_box(mesh_bounds),
6461 Some(vehicle_idx),
6462 )
6463 .is_none()
6464 {
6465 *tr = pushed_rot;
6466 moved = true;
6467 } else {
6468 *yaw_rate *= -0.2;
6469 }
6470 } else {
6471 *yaw_rate *= -0.2;
6472 }
6473 } else {
6474 *tr = rotated;
6475 moved = true;
6476 }
6477 }
6478 let step_dx: f32 = vel.get_x() * step_dt;
6479 let step_dz: f32 = vel.get_z() * step_dt;
6480 if step_dx * step_dx + step_dz * step_dz <= 1.0e-12 {
6481 continue;
6482 }
6483 let cur_pos: Vec3 = tr.get_position();
6484 let raw_next: Vec3 = Vec3::new(
6485 cur_pos.get_x() + step_dx,
6486 cur_pos.get_y(),
6487 cur_pos.get_z() + step_dz,
6488 );
6489 let next_pos: Vec3 =
6490 Self::clamp_horizontal_to_ground(raw_next, ground_limits, ground_margin);
6491 if (next_pos.get_x() - raw_next.get_x()).abs() > 1.0e-4 {
6492 vel.set_x(-vel.get_x() * COLLISION_WALL_RESTITUTION);
6493 }
6494 if (next_pos.get_z() - raw_next.get_z()).abs() > 1.0e-4 {
6495 vel.set_z(-vel.get_z() * COLLISION_WALL_RESTITUTION);
6496 }
6497 let mut cand: Transform3D = *tr;
6498 cand.set_position(next_pos);
6499 if let Some(hit) = self.mesh_oriented_box_static_collision(
6500 cand.to_oriented_box(mesh_bounds),
6501 Some(vehicle_idx),
6502 ) {
6503 let raw_hn: Vec3 =
6504 Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
6505 let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
6506 raw_hn.normalize()
6507 } else {
6508 self.horizontal_collision_normal(
6509 cand.to_oriented_box(mesh_bounds),
6510 hit.get_object_index(),
6511 )
6512 };
6513 if hn.length_sq() > 1.0e-6 {
6514 let obs_bounds: AxisAlignedBox3D = self
6515 .get_objects()
6516 .get(hit.get_object_index())
6517 .map(SceneObject3D::get_world_bounds)
6518 .unwrap_or_else(|| {
6519 AxisAlignedBox3D::new(
6520 hit.get_contact_point().sub(Vec3::splat(0.5)),
6521 hit.get_contact_point().add(Vec3::splat(0.5)),
6522 )
6523 });
6524 let phys_contact: Vec3 = Self::compute_static_contact_point(
6525 cand.to_oriented_box(mesh_bounds),
6526 hn,
6527 obs_bounds,
6528 hit.get_contact_point(),
6529 );
6530 let impact_v: f32 = Self::apply_static_wall_impulse(
6531 cur_pos,
6532 vel,
6533 yaw_rate,
6534 inertia_pair,
6535 hn,
6536 phys_contact,
6537 );
6538 if impact_v > peak_impact {
6539 peak_impact = impact_v;
6540 peak_contact = phys_contact;
6541 peak_normal = hn;
6542 }
6543 let slide_dx: f32 = vel.get_x() * step_dt;
6544 let slide_dz: f32 = vel.get_z() * step_dt;
6545 let push_eps: f32 = COLLISION_MTV_PUSH_EPS;
6546 let slide_pos: Vec3 = Self::clamp_horizontal_to_ground(
6547 Vec3::new(
6548 cur_pos.get_x() + slide_dx + hn.get_x() * push_eps,
6549 cur_pos.get_y(),
6550 cur_pos.get_z() + slide_dz + hn.get_z() * push_eps,
6551 ),
6552 ground_limits,
6553 ground_margin,
6554 );
6555 let mut slide_tr: Transform3D = *tr;
6556 slide_tr.set_position(slide_pos);
6557 if self
6558 .mesh_oriented_box_static_collision(
6559 slide_tr.to_oriented_box(mesh_bounds),
6560 Some(vehicle_idx),
6561 )
6562 .is_none()
6563 {
6564 *tr = slide_tr;
6565 moved = true;
6566 continue;
6567 }
6568 }
6569 break;
6570 }
6571 *tr = cand;
6572 moved = true;
6573 }
6574 if self.depenetrate_vehicle_static_horizontally(
6575 tr,
6576 mesh_bounds,
6577 vehicle_idx,
6578 ground_limits,
6579 ground_margin,
6580 ) {
6581 moved = true;
6582 }
6583 (moved, peak_impact, peak_contact, peak_normal)
6584 }
6585
6586 fn emit_collision_sparks(&mut self, contact: Vec3, normal: Vec3, intensity: f32) {
6594 if self.get_niagara().get_active_count() >= 56 {
6595 return;
6596 }
6597 let burst: usize = ((3.0 + intensity * 6.0).round() as usize).clamp(2, 9);
6598 let mut cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6599 cfg.set_origin(Vec3::new(
6600 contact.get_x(),
6601 contact.get_y().max(0.45),
6602 contact.get_z(),
6603 ));
6604 cfg.set_base_velocity(normal.scale(4.5 + intensity * 7.5).add(Vec3::new(
6605 0.0,
6606 2.8 + intensity * 2.5,
6607 0.0,
6608 )));
6609 cfg.set_velocity_spread(3.8 + intensity * 2.5);
6610 cfg.set_start_color(Color::rgba(255, 196, 36, 255));
6611 cfg.set_end_color(Color::rgba(255, 72, 0, 80));
6612 cfg.set_start_size_m(0.12);
6613 cfg.set_end_size_m(0.03);
6614 cfg.set_min_lifetime(0.22);
6615 cfg.set_max_lifetime(0.55);
6616 cfg.set_emissive_boost(1.75);
6617 self.get_mut_niagara().emit_burst(burst, &cfg);
6618 }
6619
6620 fn emit_drift_smoke(
6629 &mut self,
6630 car_origin: Vec3,
6631 car_fwd: Vec3,
6632 car_right: Vec3,
6633 slip_abs: f32,
6634 ) {
6635 if self.get_niagara().get_active_count() >= 48 {
6636 return;
6637 }
6638 let intensity: f32 = ((slip_abs - 0.10) / 0.50).clamp(0.25, 1.0);
6639 let rear_center: Vec3 = car_origin
6640 .sub(car_fwd.scale(1.85))
6641 .add(Vec3::new(0.0, 0.22, 0.0));
6642 for side in [-0.88_f32, 0.88_f32] {
6643 let wheel_pos: Vec3 = rear_center.add(car_right.scale(side));
6644 let mut smoke_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6645 smoke_cfg.set_origin(wheel_pos);
6646 smoke_cfg.set_base_velocity(car_fwd.scale(-2.4).add(Vec3::new(
6647 0.0,
6648 0.85 + intensity * 0.5,
6649 0.0,
6650 )));
6651 smoke_cfg.set_velocity_spread(1.25);
6652 smoke_cfg.set_start_color(Color::rgba(226, 232, 240, 175));
6653 smoke_cfg.set_end_color(Color::rgba(148, 163, 184, 30));
6654 smoke_cfg.set_start_size_m(0.22 + intensity * 0.12);
6655 smoke_cfg.set_end_size_m(0.52 + intensity * 0.18);
6656 smoke_cfg.set_min_lifetime(0.35);
6657 smoke_cfg.set_max_lifetime(0.75);
6658 smoke_cfg.set_emissive_boost(0.35);
6659 self.get_mut_niagara().emit_burst(1, &smoke_cfg);
6660 }
6661 }
6662
6663 fn update_volumetric_exhaust_fx(
6677 &mut self,
6678 car_tr: Transform3D,
6679 car_vel: Vec3,
6680 phys: PlayerVehiclePhysics3D,
6681 throttle: f32,
6682 sim_tick: u64,
6683 ) -> bool {
6684 let style: HeroVehicleStyle = self.get_hero_vehicle_style();
6685 let tips_local: &[[f32; 3]] = Self::hero_exhaust_tips_local(style);
6686 let pipe_count: usize = tips_local.len().min(EXHAUST_MAX_PIPES);
6687 let car_rot: Quat = car_tr.get_rotation();
6688 let car_scale: f32 = car_tr.get_scale().get_x().max(0.5);
6689 let exhaust_dir: Vec3 = car_tr.rotate_vec(Vec3::new(0.0, 0.0, 1.0)).normalize();
6690 let speed_mps: f32 =
6691 (car_vel.get_x() * car_vel.get_x() + car_vel.get_z() * car_vel.get_z()).sqrt();
6692 let speed_ratio: f32 = (speed_mps / VEHICLE_BOOST_TOP_SPEED_MPS).clamp(0.0, 1.0);
6693 let boost_active: bool = phys.get_boost_active();
6694 let spool: f32 = phys.get_boost_spool().clamp(0.0, 1.0);
6695 let backfire_t: f32 = phys.get_backfire_timer().max(0.0);
6696 let backfire_env: f32 = (backfire_t / VEHICLE_BACKFIRE_DURATION_SECS).clamp(0.0, 1.0);
6697 let rpm_norm: f32 = phys.get_engine_rpm_norm().clamp(0.0, 1.0);
6698 let t_secs: f32 = self.get_world_time_secs();
6699 let high_rpm_lick: f32 = if !boost_active && throttle > 0.72 && rpm_norm > 0.84 {
6700 ((rpm_norm - 0.84) / 0.16).clamp(0.0, 1.0) * 0.28
6701 } else {
6702 0.0
6703 };
6704 let boost_intensity: f32 = if boost_active {
6705 (0.46 + 0.54 * spool).clamp(0.0, 1.0)
6706 } else {
6707 spool * 0.40
6708 };
6709 let backfire_pulse: f32 = backfire_env * (0.62 + 0.38 * (t_secs * 62.0).sin().abs());
6710 let flame_intensity: f32 = boost_intensity.max(backfire_pulse).max(high_rpm_lick);
6711 let is_backfire_dominant: bool = !boost_active && backfire_pulse > 0.12;
6712 let show_cones: bool = flame_intensity > 0.04;
6713 let mut any_cone_updated: bool = false;
6714 let flame_slots: [Option<usize>; EXHAUST_TOTAL_FLAME_OBJECTS] = {
6715 let Self {
6716 exhaust_flame_objects,
6717 ..
6718 } = self;
6719 *exhaust_flame_objects
6720 };
6721 let mut prev_vis: [bool; EXHAUST_TOTAL_FLAME_OBJECTS] = {
6722 let Self {
6723 exhaust_flame_visible,
6724 ..
6725 } = self;
6726 *exhaust_flame_visible
6727 };
6728 let mut next_vis: [bool; EXHAUST_TOTAL_FLAME_OBJECTS] =
6729 [false; EXHAUST_TOTAL_FLAME_OBJECTS];
6730 for (slot_idx, obj_opt) in flame_slots.iter().enumerate() {
6731 let Some(obj_idx) = *obj_opt else {
6732 continue;
6733 };
6734 let pipe_idx: usize = slot_idx / EXHAUST_LAYERS_PER_PIPE;
6735 let layer_idx: usize = slot_idx % EXHAUST_LAYERS_PER_PIPE;
6736 let active_slot: bool = show_cones && pipe_idx < pipe_count;
6737 next_vis[slot_idx] = active_slot;
6738 if active_slot {
6739 let tip: [f32; 3] = tips_local[pipe_idx];
6740 let world_tip: Vec3 = car_tr.transform_point(Vec3::new(tip[0], tip[1], tip[2]));
6741 let phase_base: f32 =
6742 t_secs * 44.0 + (pipe_idx as f32) * 1.93 + (layer_idx as f32) * 1.31;
6743 let turb_a: f32 = (phase_base).sin();
6744 let turb_b: f32 = (phase_base * 1.63 + 0.7).cos();
6745 let turb_c: f32 = (phase_base * 2.41 - 0.5).sin();
6746 let (base_rad, base_len, mat): (f32, f32, PbrMaterial) = match layer_idx {
6747 0 => {
6748 let rad: f32 = 0.056 * car_scale * (0.90 + 0.14 * turb_a);
6749 let len: f32 = (0.44 + 0.40 * speed_ratio)
6750 * car_scale
6751 * flame_intensity
6752 * (0.90 + 0.16 * turb_b);
6753 let m: PbrMaterial = PbrMaterial::neon(Color::rgb(212, 246, 255), 4.8);
6754 (rad, len, m)
6755 }
6756 1 => {
6757 let rad: f32 = 0.092 * car_scale * (0.86 + 0.18 * turb_b);
6758 let len: f32 = (0.78 + 0.66 * speed_ratio)
6759 * car_scale
6760 * flame_intensity
6761 * (0.86 + 0.20 * turb_c);
6762 let m: PbrMaterial = if is_backfire_dominant {
6763 PbrMaterial::neon(Color::rgb(255, 174, 44), 4.0)
6764 } else {
6765 PbrMaterial::neon(Color::rgb(52, 214, 255), 3.7)
6766 };
6767 (rad, len, m)
6768 }
6769 _ => {
6770 let rad: f32 = 0.132 * car_scale * (0.82 + 0.24 * turb_c);
6771 let len: f32 = (1.12 + 0.96 * speed_ratio)
6772 * car_scale
6773 * flame_intensity
6774 * (0.82 + 0.26 * turb_a);
6775 let m: PbrMaterial = PbrMaterial::neon(Color::rgb(255, 118, 22), 3.2);
6776 (rad, len, m)
6777 }
6778 };
6779 let flick_yaw: f32 = turb_a * (0.045 + (layer_idx as f32) * 0.025);
6780 let flick_pitch: f32 = turb_b * (0.040 + (layer_idx as f32) * 0.022);
6781 let spin_roll: f32 = (t_secs * (12.0 + (layer_idx as f32) * 7.0)
6782 + (pipe_idx as f32) * 1.5)
6783 .rem_euclid(2.0 * PI);
6784 let flick_rot: Quat = Quat::from_euler_yxz(flick_yaw, flick_pitch, spin_roll);
6785 let cone_tr: Transform3D = Transform3D::from_trs(
6786 world_tip,
6787 car_rot.mul_quat(flick_rot),
6788 Vec3::new(base_rad, base_rad, base_len.max(0.08)),
6789 );
6790 let mesh_id_opt: Option<usize> = self
6791 .get_objects()
6792 .get(obj_idx)
6793 .map(SceneObject3D::get_mesh_id);
6794 if let Some(m_id) = mesh_id_opt {
6795 let local_b: AxisAlignedBox3D = self.local_bounds_for_mesh(m_id);
6796 let world_b: AxisAlignedBox3D = cone_tr.transform_bounds(local_b);
6797 if let Some(obj_mut) = self.get_mut_objects().get_mut(obj_idx) {
6798 obj_mut.set_transform(cone_tr);
6799 obj_mut.set_material(mat);
6800 obj_mut.set_world_bounds(world_b);
6801 if !prev_vis[slot_idx] {
6802 let next_ep: u32 = obj_mut.get_teleport_epoch().wrapping_add(1);
6803 obj_mut.set_teleport_epoch(next_ep);
6804 }
6805 }
6806 any_cone_updated = true;
6807 }
6808 } else if prev_vis[slot_idx] {
6809 any_cone_updated = true;
6810 }
6811 prev_vis[slot_idx] = active_slot;
6812 }
6813 {
6814 let Self {
6815 exhaust_flame_visible,
6816 ..
6817 } = self;
6818 *exhaust_flame_visible = next_vis;
6819 }
6820 let exhaust_light_opt: Option<usize> = {
6821 let Self {
6822 exhaust_light_index,
6823 ..
6824 } = self;
6825 *exhaust_light_index
6826 };
6827 if let Some(light_idx) = exhaust_light_opt {
6828 let avg_tip_y: f32 = tips_local[0][1];
6829 let avg_tip_z: f32 = tips_local[0][2];
6830 let glow_pos: Vec3 = car_tr
6831 .transform_point(Vec3::new(0.0, avg_tip_y, avg_tip_z))
6832 .add(exhaust_dir.scale(0.55));
6833 let flicker: f32 = 0.84 + 0.16 * (t_secs * 58.0).sin() * (t_secs * 37.0).cos();
6834 let (glow_color, glow_intensity, glow_radius): (Vec3, f32, f32) = if boost_active {
6835 let mix_amber: f32 = (0.35 + 0.30 * (t_secs * 29.0).sin().abs()).clamp(0.0, 1.0);
6836 let col: Vec3 =
6837 Vec3::new(0.38, 0.84, 1.0).lerp(Vec3::new(1.0, 0.56, 0.16), mix_amber);
6838 (col, (3.4 + 3.2 * spool) * flicker, 8.5 + 4.0 * spool)
6839 } else if backfire_pulse > 0.08 {
6840 (
6841 Vec3::new(1.0, 0.48, 0.14),
6842 4.8 * backfire_pulse * flicker,
6843 9.2,
6844 )
6845 } else if high_rpm_lick > 0.05 {
6846 (Vec3::new(1.0, 0.58, 0.22), 1.2 * high_rpm_lick, 5.5)
6847 } else {
6848 (Vec3::new(0.38, 0.84, 1.0), 0.0, 6.0)
6849 };
6850 if let Some(light_mut) = self.get_mut_point_lights().get_mut(light_idx) {
6851 light_mut.set_position(glow_pos);
6852 light_mut.set_color(glow_color);
6853 light_mut.set_intensity(glow_intensity);
6854 light_mut.set_radius(glow_radius);
6855 }
6856 }
6857 let active_particles: usize = self.get_niagara().get_active_count();
6858 if boost_active {
6859 if active_particles < EXHAUST_BOOST_MAX_PARTICLES {
6860 let core_jet_vel: Vec3 = car_vel
6861 .scale(0.84)
6862 .add(exhaust_dir.scale(10.5 + 4.5 * spool))
6863 .add(Vec3::new(0.0, 0.20, 0.0));
6864 let ember_vel: Vec3 = car_vel
6865 .scale(0.72)
6866 .add(exhaust_dir.scale(8.5 + 3.0 * spool))
6867 .add(Vec3::new(0.0, 0.45, 0.0));
6868 let smoke_vel: Vec3 = car_vel
6869 .scale(0.45)
6870 .add(exhaust_dir.scale(4.2))
6871 .add(Vec3::new(0.0, 0.72, 0.0));
6872 let core_per_pipe: usize = if pipe_count <= 2 { 2 } else { 1 };
6873 for (p_idx, tip) in tips_local.iter().take(pipe_count).enumerate() {
6874 let world_tip: Vec3 = car_tr.transform_point(Vec3::new(tip[0], tip[1], tip[2]));
6875 let mut core_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6876 core_cfg.set_origin(world_tip.add(exhaust_dir.scale(0.24)));
6877 core_cfg.set_base_velocity(core_jet_vel);
6878 core_cfg.set_velocity_spread(0.65);
6879 core_cfg.set_start_color(Color::rgba(198, 246, 255, 255));
6880 core_cfg.set_end_color(Color::rgba(48, 204, 255, 95));
6881 core_cfg.set_start_size_m(0.14);
6882 core_cfg.set_end_size_m(0.045);
6883 core_cfg.set_min_lifetime(0.08);
6884 core_cfg.set_max_lifetime(0.17);
6885 core_cfg.set_drag(1.6);
6886 core_cfg.set_turbulence(1.1);
6887 core_cfg.set_emissive_boost(3.15);
6888 self.get_mut_niagara().emit_burst(core_per_pipe, &core_cfg);
6889 if ((sim_tick as usize + p_idx) & 1) == 0 {
6890 let mut ember_cfg: NiagaraEmitterConfig3D =
6891 NiagaraEmitterConfig3D::default();
6892 ember_cfg.set_origin(world_tip.add(exhaust_dir.scale(0.55)));
6893 ember_cfg.set_base_velocity(ember_vel);
6894 ember_cfg.set_velocity_spread(1.65);
6895 ember_cfg.set_start_color(Color::rgba(255, 202, 64, 250));
6896 ember_cfg.set_end_color(Color::rgba(255, 68, 12, 30));
6897 ember_cfg.set_start_size_m(0.095);
6898 ember_cfg.set_end_size_m(0.025);
6899 ember_cfg.set_min_lifetime(0.18);
6900 ember_cfg.set_max_lifetime(0.42);
6901 ember_cfg.set_drag(2.2);
6902 ember_cfg.set_turbulence(2.6);
6903 ember_cfg.set_emissive_boost(2.65);
6904 self.get_mut_niagara().emit_burst(1, &ember_cfg);
6905 }
6906 if (sim_tick as usize + p_idx).is_multiple_of(3) {
6907 let mut shimmer_cfg: NiagaraEmitterConfig3D =
6908 NiagaraEmitterConfig3D::default();
6909 shimmer_cfg.set_origin(world_tip.add(exhaust_dir.scale(0.85)));
6910 shimmer_cfg.set_base_velocity(smoke_vel);
6911 shimmer_cfg.set_velocity_spread(1.15);
6912 shimmer_cfg.set_start_color(Color::rgba(232, 214, 196, 125));
6913 shimmer_cfg.set_end_color(Color::rgba(136, 146, 160, 0));
6914 shimmer_cfg.set_start_size_m(0.16);
6915 shimmer_cfg.set_end_size_m(0.52);
6916 shimmer_cfg.set_min_lifetime(0.32);
6917 shimmer_cfg.set_max_lifetime(0.65);
6918 shimmer_cfg.set_drag(2.4);
6919 shimmer_cfg.set_turbulence(2.8);
6920 shimmer_cfg.set_emissive_boost(0.24);
6921 self.get_mut_niagara().emit_burst(1, &shimmer_cfg);
6922 }
6923 }
6924 }
6925 } else if backfire_pulse > 0.12 {
6926 if active_particles < EXHAUST_BOOST_MAX_PARTICLES && (sim_tick & 1) == 0 {
6927 let pop_vel: Vec3 = car_vel
6928 .scale(0.65)
6929 .add(exhaust_dir.scale(11.0))
6930 .add(Vec3::new(0.0, 0.35, 0.0));
6931 for tip in tips_local.iter().take(pipe_count) {
6932 let world_tip: Vec3 = car_tr.transform_point(Vec3::new(tip[0], tip[1], tip[2]));
6933 let mut pop_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6934 pop_cfg.set_origin(world_tip.add(exhaust_dir.scale(0.18)));
6935 pop_cfg.set_base_velocity(pop_vel);
6936 pop_cfg.set_velocity_spread(2.1);
6937 pop_cfg.set_start_color(Color::rgba(110, 224, 255, 255));
6938 pop_cfg.set_end_color(Color::rgba(255, 112, 20, 40));
6939 pop_cfg.set_start_size_m(0.15);
6940 pop_cfg.set_end_size_m(0.04);
6941 pop_cfg.set_min_lifetime(0.10);
6942 pop_cfg.set_max_lifetime(0.24);
6943 pop_cfg.set_drag(2.6);
6944 pop_cfg.set_turbulence(2.2);
6945 pop_cfg.set_emissive_boost(3.0);
6946 self.get_mut_niagara().emit_burst(2, &pop_cfg);
6947 }
6948 }
6949 } else if active_particles < EXHAUST_VAPOR_MAX_PARTICLES {
6950 let vapor_cadence: u64 = if throttle.abs() > 0.25 { 4 } else { 10 };
6951 if sim_tick.is_multiple_of(vapor_cadence) {
6952 let pipe_pick: usize = ((sim_tick / vapor_cadence) as usize) % pipe_count.max(1);
6953 let tip: [f32; 3] = tips_local[pipe_pick];
6954 let world_tip: Vec3 = car_tr.transform_point(Vec3::new(tip[0], tip[1], tip[2]));
6955 let vapor_push: f32 = 1.6 + throttle.abs() * 2.8 + speed_ratio * 2.2;
6956 let mut vapor_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6957 vapor_cfg.set_origin(world_tip.add(exhaust_dir.scale(0.08)));
6958 vapor_cfg.set_base_velocity(
6959 car_vel
6960 .scale(0.35)
6961 .add(exhaust_dir.scale(vapor_push))
6962 .add(Vec3::new(0.0, 0.55, 0.0)),
6963 );
6964 vapor_cfg.set_velocity_spread(0.42);
6965 vapor_cfg.set_start_color(Color::rgba(220, 228, 238, 102));
6966 vapor_cfg.set_end_color(Color::rgba(176, 188, 202, 0));
6967 vapor_cfg.set_start_size_m(0.085);
6968 vapor_cfg.set_end_size_m(0.28);
6969 vapor_cfg.set_min_lifetime(0.42);
6970 vapor_cfg.set_max_lifetime(0.82);
6971 vapor_cfg.set_drag(2.2);
6972 vapor_cfg.set_turbulence(1.1);
6973 vapor_cfg.set_emissive_boost(0.12);
6974 self.get_mut_niagara().emit_burst(1, &vapor_cfg);
6975 }
6976 }
6977 any_cone_updated
6978 }
6979
6980 #[must_use]
6993 fn npc_probe_heading_clear(
6994 &self,
6995 npc_geo: (usize, Vec3, Vec3, AxisAlignedBox3D),
6996 heading_yaw: f32,
6997 probe_dist: f32,
6998 bounds_ctx: (Option<(f32, f32, f32, f32)>, f32),
6999 ) -> bool {
7000 let (npc_idx, pos, scale, local_bounds): (usize, Vec3, Vec3, AxisAlignedBox3D) = npc_geo;
7001 let (ground_limits, margin): (Option<(f32, f32, f32, f32)>, f32) = bounds_ctx;
7002 let dir: Vec3 = Vec3::new(-heading_yaw.sin(), 0.0, -heading_yaw.cos());
7003 let check_dists: [f32; 2] = if probe_dist > 5.0 {
7004 [probe_dist * 0.52, probe_dist]
7005 } else {
7006 [probe_dist, probe_dist]
7007 };
7008 let check_len: usize = if probe_dist > 5.0 { 2 } else { 1 };
7009 for dist_m in check_dists.into_iter().take(check_len) {
7010 let probe_pos: Vec3 = pos.add(dir.scale(dist_m));
7011 if let Some((min_x, max_x, min_z, max_z)) = ground_limits {
7012 let bound_pad: f32 = margin + 2.0;
7013 let east_limit: f32 = (max_x - bound_pad).min(CITY_EAST_OCEAN_MIN_X - 3.5);
7014 if probe_pos.get_x() < min_x + bound_pad
7015 || probe_pos.get_x() > east_limit
7016 || probe_pos.get_z() < min_z + bound_pad
7017 || probe_pos.get_z() > max_z - bound_pad
7018 {
7019 return false;
7020 }
7021 }
7022 let probe_tr: Transform3D = Transform3D::new(probe_pos, heading_yaw, scale);
7023 if self
7024 .mesh_oriented_box_static_collision(
7025 probe_tr.to_oriented_box(local_bounds),
7026 Some(npc_idx),
7027 )
7028 .is_some()
7029 {
7030 return false;
7031 }
7032 }
7033 true
7034 }
7035
7036 #[must_use]
7049 fn npc_evaluate_5ray_feelers(
7050 &self,
7051 npc_geo: (usize, Vec3, Vec3, AxisAlignedBox3D),
7052 yaw: f32,
7053 desired_yaw_err: f32,
7054 bounds_ctx: (Option<(f32, f32, f32, f32)>, f32),
7055 ) -> (Option<f32>, f32, bool, bool) {
7056 let center_near: bool =
7057 self.npc_probe_heading_clear(npc_geo, yaw, NPC_FEELER_NEAR_M, bounds_ctx);
7058 let center_far: bool =
7059 center_near && self.npc_probe_heading_clear(npc_geo, yaw, NPC_FEELER_FAR_M, bounds_ctx);
7060 let inner_right_near: bool = self.npc_probe_heading_clear(
7061 npc_geo,
7062 yaw + NPC_FEELER_ANGLES_RAD[1],
7063 NPC_FEELER_NEAR_M,
7064 bounds_ctx,
7065 );
7066 let inner_left_near: bool = self.npc_probe_heading_clear(
7067 npc_geo,
7068 yaw + NPC_FEELER_ANGLES_RAD[3],
7069 NPC_FEELER_NEAR_M,
7070 bounds_ctx,
7071 );
7072 if center_far {
7073 let left_open: bool = inner_left_near
7074 || self.npc_probe_heading_clear(
7075 npc_geo,
7076 yaw + NPC_FEELER_ANGLES_RAD[4],
7077 NPC_FEELER_NEAR_M,
7078 bounds_ctx,
7079 );
7080 let right_open: bool = inner_right_near
7081 || self.npc_probe_heading_clear(
7082 npc_geo,
7083 yaw + NPC_FEELER_ANGLES_RAD[0],
7084 NPC_FEELER_NEAR_M,
7085 bounds_ctx,
7086 );
7087 return (None, 1.0, left_open, right_open);
7088 }
7089 let mut best_angle: f32 = 0.0;
7090 let mut best_score: f32 = -1.0e6;
7091 let mut any_near_clear: bool = false;
7092 let mut left_open: bool = inner_left_near;
7093 let mut right_open: bool = inner_right_near;
7094 for (ray_idx, &ang_off) in NPC_FEELER_ANGLES_RAD.iter().enumerate() {
7095 let near_ok: bool = match ray_idx {
7096 1 => inner_right_near,
7097 2 => center_near,
7098 3 => inner_left_near,
7099 _ => self.npc_probe_heading_clear(
7100 npc_geo,
7101 yaw + ang_off,
7102 NPC_FEELER_NEAR_M,
7103 bounds_ctx,
7104 ),
7105 };
7106 let far_ok: bool = if !near_ok {
7107 false
7108 } else if ray_idx == 2 {
7109 center_far
7110 } else {
7111 self.npc_probe_heading_clear(npc_geo, yaw + ang_off, NPC_FEELER_FAR_M, bounds_ctx)
7112 };
7113 if ray_idx == 0 && near_ok {
7114 right_open = true;
7115 }
7116 if ray_idx == 4 && near_ok {
7117 left_open = true;
7118 }
7119 if near_ok {
7120 any_near_clear = true;
7121 let align_bonus: f32 = if ang_off * desired_yaw_err >= 0.0 {
7122 0.35
7123 } else {
7124 0.0
7125 };
7126 let score: f32 =
7127 2.0 + if far_ok { 3.0 } else { 0.0 } - ang_off.abs() * 0.55 + align_bonus;
7128 if score > best_score {
7129 best_score = score;
7130 best_angle = ang_off;
7131 }
7132 }
7133 }
7134 if !any_near_clear {
7135 let fallback_steer: f32 = if desired_yaw_err >= 0.0 { 1.15 } else { -1.15 };
7136 return (Some(fallback_steer), 0.22, left_open, right_open);
7137 }
7138 let speed_scale: f32 = if center_near { 0.72 } else { 0.48 };
7139 (Some(best_angle), speed_scale, left_open, right_open)
7140 }
7141
7142 #[must_use]
7155 fn npc_scan_escape_heading(
7156 &self,
7157 npc_geo: (usize, Vec3, Vec3, AxisAlignedBox3D),
7158 yaw: f32,
7159 last_wall_n: Vec3,
7160 bounds_ctx: (Option<(f32, f32, f32, f32)>, f32),
7161 ) -> f32 {
7162 let mut best_yaw: f32 = Self::wrap_angle_rad(yaw + PI);
7163 let mut best_score: f32 = -1.0e6;
7164 let has_wall_n: bool = last_wall_n.length_sq() > 0.1;
7165 let candidates: [f32; 10] = [
7166 0.0,
7167 NPC_ESCAPE_CANDIDATE_ANGLES_RAD[0],
7168 NPC_ESCAPE_CANDIDATE_ANGLES_RAD[1],
7169 NPC_ESCAPE_CANDIDATE_ANGLES_RAD[2],
7170 NPC_ESCAPE_CANDIDATE_ANGLES_RAD[3],
7171 NPC_ESCAPE_CANDIDATE_ANGLES_RAD[4],
7172 NPC_ESCAPE_CANDIDATE_ANGLES_RAD[5],
7173 NPC_ESCAPE_CANDIDATE_ANGLES_RAD[6],
7174 NPC_ESCAPE_CANDIDATE_ANGLES_RAD[7],
7175 PI,
7176 ];
7177 for &offset in candidates.iter() {
7178 let cand_yaw: f32 = Self::wrap_angle_rad(yaw + offset);
7179 let near_ok: bool =
7180 self.npc_probe_heading_clear(npc_geo, cand_yaw, NPC_FEELER_NEAR_M, bounds_ctx);
7181 if !near_ok {
7182 continue;
7183 }
7184 let far_ok: bool =
7185 self.npc_probe_heading_clear(npc_geo, cand_yaw, NPC_FEELER_FAR_M, bounds_ctx);
7186 let cand_fwd: Vec3 = Vec3::new(-cand_yaw.sin(), 0.0, -cand_yaw.cos());
7187 let away_wall: f32 = if has_wall_n {
7188 cand_fwd.dot(last_wall_n) * 1.4
7189 } else {
7190 0.0
7191 };
7192 let turn_cost: f32 = offset.abs() * 0.22;
7193 let score: f32 = 3.0 + if far_ok { 5.0 } else { 0.0 } + away_wall - turn_cost;
7194 if score > best_score {
7195 best_score = score;
7196 best_yaw = cand_yaw;
7197 }
7198 }
7199 best_yaw
7200 }
7201
7202 #[must_use]
7217 fn npc_sense_traffic(
7218 &self,
7219 npc_idx: usize,
7220 pos: Vec3,
7221 fwd: Vec3,
7222 right: Vec3,
7223 npc_fwd_speed: f32,
7224 side_open: (bool, bool),
7225 ) -> (Option<f32>, f32, f32) {
7226 let (left_open, right_open): (bool, bool) = side_open;
7227 let mut stationary_player_gap: Option<f32> = None;
7228 let mut steer_bias: f32 = 0.0;
7229 let mut speed_scale: f32 = 1.0;
7230 let objects: &[SceneObject3D] = self.get_objects().as_slice();
7231 let player_opt: Option<usize> = self.vehicle_index();
7232 let player_vel: Vec3 = self.player_velocity();
7233 let Self {
7234 traffic_vehicles, ..
7235 } = self;
7236 for (other_idx, other_obj) in objects.iter().enumerate() {
7237 let other_solid: bool =
7238 other_obj.get_solid_collider() || other_obj.get_ray_trace_caster();
7239 if other_idx == npc_idx || !other_obj.get_is_dynamic() || !other_solid {
7240 continue;
7241 }
7242 let other_tr: Transform3D = other_obj.get_transform();
7243 let other_pos: Vec3 = other_tr.get_position();
7244 let diff: Vec3 = Vec3::new(
7245 other_pos.get_x() - pos.get_x(),
7246 0.0,
7247 other_pos.get_z() - pos.get_z(),
7248 );
7249 let fwd_d: f32 = diff.dot(fwd);
7250 if fwd_d <= 0.35 || fwd_d >= 18.0 {
7251 continue;
7252 }
7253 let lat_signed: f32 = diff.dot(right);
7254 let lat_abs: f32 = lat_signed.abs();
7255 if lat_abs > 3.6 {
7256 continue;
7257 }
7258 let is_player: bool = player_opt == Some(other_idx);
7259 let other_vel: Vec3 = if is_player {
7260 player_vel
7261 } else {
7262 traffic_vehicles
7263 .iter()
7264 .find(|n: &&NpcVehicle3D| n.get_object_index() == other_idx)
7265 .map(NpcVehicle3D::get_vel)
7266 .unwrap_or_else(Vec3::zero)
7267 };
7268 let other_speed: f32 = (other_vel.get_x() * other_vel.get_x()
7269 + other_vel.get_z() * other_vel.get_z())
7270 .sqrt();
7271 if is_player && other_speed < 0.8 && fwd_d < 16.0 && lat_abs <= 2.75 {
7272 stationary_player_gap = Some(
7273 stationary_player_gap
7274 .map(|prev: f32| prev.min(fwd_d))
7275 .unwrap_or(fwd_d),
7276 );
7277 continue;
7278 }
7279 let other_yaw: f32 = other_tr.get_yaw_rad();
7280 let other_fwd: Vec3 = Vec3::new(-other_yaw.sin(), 0.0, -other_yaw.cos());
7281 let heading_dot: f32 = fwd.dot(other_fwd);
7282 let urgency: f32 = ((18.0 - fwd_d) / 14.0).clamp(0.25, 1.0);
7283 if heading_dot < -0.30 {
7284 let avoid_sign: f32 = if !right_open && left_open {
7285 1.0
7286 } else if !left_open && right_open {
7287 -1.0
7288 } else if lat_signed > 0.65 {
7289 1.0
7290 } else if lat_signed < -0.65 {
7291 -1.0
7292 } else {
7293 if right_open || npc_idx < other_idx {
7294 -1.0
7295 } else {
7296 1.0
7297 }
7298 };
7299 steer_bias += avoid_sign * (0.55 + 0.65 * urgency);
7300 speed_scale = speed_scale.min(0.76 - 0.16 * urgency);
7301 } else if fwd_d < 15.0 && lat_abs < 2.85 {
7302 let other_fwd_speed: f32 = other_vel.dot(fwd);
7303 if other_fwd_speed < npc_fwd_speed - 0.5 || other_speed < 1.8 {
7304 let pass_sign: f32 = if left_open && !right_open {
7305 1.0
7306 } else if right_open && !left_open {
7307 -1.0
7308 } else if left_open && right_open {
7309 if lat_signed >= 0.0 { 1.0 } else { -1.0 }
7310 } else {
7311 0.0
7312 };
7313 if pass_sign != 0.0 {
7314 steer_bias += pass_sign * (0.48 + 0.52 * urgency);
7315 speed_scale = speed_scale.min(0.84 - 0.18 * urgency);
7316 } else if fwd_d < 7.0 {
7317 speed_scale = speed_scale.min(((fwd_d - 4.0) / 3.0).clamp(0.18, 0.70));
7318 } else {
7319 speed_scale = speed_scale.min(0.65);
7320 }
7321 }
7322 }
7323 }
7324 (
7325 stationary_player_gap,
7326 steer_bias.clamp(-1.35, 1.35),
7327 speed_scale.clamp(0.18, 1.0),
7328 )
7329 }
7330
7331 fn resolve_dynamic_vehicle_collisions(
7341 &mut self,
7342 ground_limits: Option<(f32, f32, f32, f32)>,
7343 ) -> (bool, f32, Vec3, Vec3) {
7344 let player_opt: Option<usize> = self.vehicle_index();
7345 let npc_count: usize = self.traffic_vehicle_count();
7346 let total_bodies: usize = npc_count + usize::from(player_opt.is_some());
7347 if total_bodies < 2 {
7348 return (false, 0.0, Vec3::zero(), Vec3::new(0.0, 0.0, 1.0));
7349 }
7350 let mut any_moved: bool = false;
7351 let mut player_peak_impact: f32 = 0.0;
7352 let mut player_peak_contact: Vec3 = Vec3::zero();
7353 let mut player_peak_normal: Vec3 = Vec3::new(0.0, 0.0, 1.0);
7354 let player_offset: usize = usize::from(player_opt.is_some());
7355 for _ in 0..2_usize {
7356 for idx_a in 0..total_bodies {
7357 for idx_b in (idx_a + 1)..total_bodies {
7358 let is_a_player: bool = player_opt.is_some() && idx_a == 0;
7359 let obj_a: usize = if is_a_player {
7360 match player_opt {
7361 Some(p_idx) => p_idx,
7362 None => continue,
7363 }
7364 } else {
7365 match self.traffic_vehicle_object_index(idx_a - player_offset) {
7366 Some(n_idx) => n_idx,
7367 None => continue,
7368 }
7369 };
7370 let npc_slot_b: usize = idx_b - player_offset;
7371 let Some(obj_b) = self.traffic_vehicle_object_index(npc_slot_b) else {
7372 continue;
7373 };
7374 let Some((mut tr_a, mesh_a)) = self
7375 .get_objects()
7376 .get(obj_a)
7377 .map(|o: &SceneObject3D| (o.get_transform(), o.get_mesh_id()))
7378 else {
7379 continue;
7380 };
7381 let Some((mut tr_b, mesh_b)) = self
7382 .get_objects()
7383 .get(obj_b)
7384 .map(|o: &SceneObject3D| (o.get_transform(), o.get_mesh_id()))
7385 else {
7386 continue;
7387 };
7388 let bounds_a: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_a);
7389 let bounds_b: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_b);
7390 let obb_a: OrientedBox3D = tr_a.to_oriented_box(bounds_a);
7391 let obb_b: OrientedBox3D = tr_b.to_oriented_box(bounds_b);
7392 let Some((normal_ba, pen, contact)) = obb_a.intersect_oriented_box_xz(&obb_b)
7393 else {
7394 continue;
7395 };
7396 let (mut vel_a, mut omega_a, mass_a, inv_i_a): (Vec3, f32, f32, f32) =
7397 if is_a_player {
7398 (
7399 self.player_velocity(),
7400 self.player_yaw_rate(),
7401 VEHICLE_PLAYER_MASS_KG,
7402 1.0 / VEHICLE_PLAYER_INERTIA_YAW,
7403 )
7404 } else {
7405 let Self {
7406 traffic_vehicles, ..
7407 } = self;
7408 let npc_a: NpcVehicle3D = traffic_vehicles[idx_a - player_offset];
7409 (
7410 npc_a.get_vel(),
7411 npc_a.get_yaw_rate(),
7412 npc_a.get_mass(),
7413 1.0 / VEHICLE_NPC_INERTIA_YAW,
7414 )
7415 };
7416 let (mut vel_b, mut omega_b, mass_b, inv_i_b): (Vec3, f32, f32, f32) = {
7417 let Self {
7418 traffic_vehicles, ..
7419 } = self;
7420 let npc_b: NpcVehicle3D = traffic_vehicles[npc_slot_b];
7421 (
7422 npc_b.get_vel(),
7423 npc_b.get_yaw_rate(),
7424 npc_b.get_mass(),
7425 1.0 / VEHICLE_NPC_INERTIA_YAW,
7426 )
7427 };
7428 let inv_m_a: f32 = 1.0 / mass_a.max(100.0);
7429 let inv_m_b: f32 = 1.0 / mass_b.max(100.0);
7430 let inv_m_sum: f32 = inv_m_a + inv_m_b;
7431 let total_push: f32 = pen + COLLISION_MTV_PUSH_EPS;
7432 let share_a: f32 = total_push * (inv_m_a / inv_m_sum);
7433 let share_b: f32 = total_push * (inv_m_b / inv_m_sum);
7434 let margin_a: f32 = obb_a
7435 .get_half_extents()
7436 .get_x()
7437 .max(obb_a.get_half_extents().get_z());
7438 let margin_b: f32 = obb_b
7439 .get_half_extents()
7440 .get_x()
7441 .max(obb_b.get_half_extents().get_z());
7442 let cand_pos_a: Vec3 = Self::clamp_horizontal_to_ground(
7443 tr_a.get_position().add(normal_ba.scale(share_a)),
7444 ground_limits,
7445 margin_a,
7446 );
7447 let cand_pos_b: Vec3 = Self::clamp_horizontal_to_ground(
7448 tr_b.get_position().sub(normal_ba.scale(share_b)),
7449 ground_limits,
7450 margin_b,
7451 );
7452 let mut cand_tr_a: Transform3D = tr_a;
7453 cand_tr_a.set_position(cand_pos_a);
7454 let mut cand_tr_b: Transform3D = tr_b;
7455 cand_tr_b.set_position(cand_pos_b);
7456 let a_static_ok: bool = self
7457 .mesh_oriented_box_static_collision(
7458 cand_tr_a.to_oriented_box(bounds_a),
7459 Some(obj_a),
7460 )
7461 .is_none();
7462 let b_static_ok: bool = self
7463 .mesh_oriented_box_static_collision(
7464 cand_tr_b.to_oriented_box(bounds_b),
7465 Some(obj_b),
7466 )
7467 .is_none();
7468 if a_static_ok && b_static_ok {
7469 tr_a = cand_tr_a;
7470 tr_b = cand_tr_b;
7471 } else if b_static_ok {
7472 let full_b: Vec3 = Self::clamp_horizontal_to_ground(
7473 tr_b.get_position().sub(normal_ba.scale(total_push)),
7474 ground_limits,
7475 margin_b,
7476 );
7477 tr_b.set_position(full_b);
7478 } else if a_static_ok {
7479 let full_a: Vec3 = Self::clamp_horizontal_to_ground(
7480 tr_a.get_position().add(normal_ba.scale(total_push)),
7481 ground_limits,
7482 margin_a,
7483 );
7484 tr_a.set_position(full_a);
7485 } else {
7486 tr_a = cand_tr_a;
7487 tr_b = cand_tr_b;
7488 let _: bool = self.depenetrate_vehicle_static_horizontally(
7489 &mut tr_a,
7490 bounds_a,
7491 obj_a,
7492 ground_limits,
7493 margin_a,
7494 );
7495 let _: bool = self.depenetrate_vehicle_static_horizontally(
7496 &mut tr_b,
7497 bounds_b,
7498 obj_b,
7499 ground_limits,
7500 margin_b,
7501 );
7502 }
7503 let pos_a: Vec3 = tr_a.get_position();
7504 let pos_b: Vec3 = tr_b.get_position();
7505 let ra_x: f32 = (contact.get_x() - pos_a.get_x()).clamp(-2.6, 2.6);
7506 let ra_z: f32 = (contact.get_z() - pos_a.get_z()).clamp(-2.6, 2.6);
7507 let rb_x: f32 = (contact.get_x() - pos_b.get_x()).clamp(-2.6, 2.6);
7508 let rb_z: f32 = (contact.get_z() - pos_b.get_z()).clamp(-2.6, 2.6);
7509 let va_pt_x: f32 = vel_a.get_x() + omega_a * ra_z;
7510 let va_pt_z: f32 = vel_a.get_z() - omega_a * ra_x;
7511 let vb_pt_x: f32 = vel_b.get_x() + omega_b * rb_z;
7512 let vb_pt_z: f32 = vel_b.get_z() - omega_b * rb_x;
7513 let vrel_x: f32 = va_pt_x - vb_pt_x;
7514 let vrel_z: f32 = va_pt_z - vb_pt_z;
7515 let vrel_n: f32 = vrel_x * normal_ba.get_x() + vrel_z * normal_ba.get_z();
7516 let mut impact_dv_a: f32 = 0.0;
7517 let mut impact_dv_b: f32 = 0.0;
7518 if vrel_n < 0.0 {
7519 let ra_cross_n: f32 = ra_z * normal_ba.get_x() - ra_x * normal_ba.get_z();
7520 let rb_cross_n: f32 = rb_z * normal_ba.get_x() - rb_x * normal_ba.get_z();
7521 let denom_n: f32 = inv_m_a
7522 + inv_m_b
7523 + (ra_cross_n * ra_cross_n) * inv_i_a
7524 + (rb_cross_n * rb_cross_n) * inv_i_b;
7525 let restitution: f32 = if -vrel_n > 1.5 {
7526 COLLISION_CAR_RESTITUTION
7527 } else {
7528 0.05
7529 };
7530 let j_n: f32 =
7531 (-(1.0 + restitution) * vrel_n / denom_n.max(1.0e-6)).max(0.0);
7532 vel_a.set_x(vel_a.get_x() + normal_ba.get_x() * j_n * inv_m_a);
7533 vel_a.set_z(vel_a.get_z() + normal_ba.get_z() * j_n * inv_m_a);
7534 omega_a = (omega_a + ra_cross_n * j_n * inv_i_a)
7535 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
7536 vel_b.set_x(vel_b.get_x() - normal_ba.get_x() * j_n * inv_m_b);
7537 vel_b.set_z(vel_b.get_z() - normal_ba.get_z() * j_n * inv_m_b);
7538 omega_b = (omega_b - rb_cross_n * j_n * inv_i_b)
7539 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
7540 impact_dv_a = j_n * inv_m_a;
7541 impact_dv_b = j_n * inv_m_b;
7542 let vt_x: f32 = vrel_x - normal_ba.get_x() * vrel_n;
7543 let vt_z: f32 = vrel_z - normal_ba.get_z() * vrel_n;
7544 let vt_len: f32 = (vt_x * vt_x + vt_z * vt_z).sqrt();
7545 if vt_len > 1.0e-4 && j_n > 0.0 {
7546 let tx: f32 = vt_x / vt_len;
7547 let tz: f32 = vt_z / vt_len;
7548 let ra_cross_t: f32 = ra_z * tx - ra_x * tz;
7549 let rb_cross_t: f32 = rb_z * tx - rb_x * tz;
7550 let denom_t: f32 = inv_m_a
7551 + inv_m_b
7552 + (ra_cross_t * ra_cross_t) * inv_i_a
7553 + (rb_cross_t * rb_cross_t) * inv_i_b;
7554 let max_jt: f32 = COLLISION_CAR_FRICTION * j_n;
7555 let j_t: f32 = (-vt_len / denom_t.max(1.0e-6)).clamp(-max_jt, max_jt);
7556 vel_a.set_x(vel_a.get_x() + tx * j_t * inv_m_a);
7557 vel_a.set_z(vel_a.get_z() + tz * j_t * inv_m_a);
7558 omega_a = (omega_a + ra_cross_t * j_t * inv_i_a)
7559 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
7560 vel_b.set_x(vel_b.get_x() - tx * j_t * inv_m_b);
7561 vel_b.set_z(vel_b.get_z() - tz * j_t * inv_m_b);
7562 omega_b = (omega_b - rb_cross_t * j_t * inv_i_b)
7563 .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
7564 }
7565 let closing: f32 = -vrel_n;
7566 if is_a_player && closing > player_peak_impact {
7567 player_peak_impact = closing;
7568 player_peak_contact = contact;
7569 player_peak_normal = normal_ba;
7570 }
7571 if closing > 2.5 {
7572 let spark_int: f32 = ((closing - 2.0) / 24.0).clamp(0.15, 1.0);
7573 self.emit_collision_sparks(contact, normal_ba, spark_int);
7574 }
7575 }
7576 let wb_a: AxisAlignedBox3D = tr_a.transform_bounds(bounds_a);
7577 let wb_b: AxisAlignedBox3D = tr_b.transform_bounds(bounds_b);
7578 if let Some(o_a) = self.get_mut_objects().get_mut(obj_a) {
7579 o_a.set_transform(tr_a);
7580 o_a.set_world_bounds(wb_a);
7581 }
7582 if let Some(o_b) = self.get_mut_objects().get_mut(obj_b) {
7583 o_b.set_transform(tr_b);
7584 o_b.set_world_bounds(wb_b);
7585 }
7586 if is_a_player {
7587 let Self { player_physics, .. } = self;
7588 player_physics.set_vel(vel_a);
7589 player_physics.set_yaw_rate(omega_a);
7590 } else {
7591 let slot_a: usize = idx_a - player_offset;
7592 let Self {
7593 traffic_vehicles, ..
7594 } = self;
7595 let npc_a: &mut NpcVehicle3D = &mut traffic_vehicles[slot_a];
7596 npc_a.set_vel(vel_a);
7597 npc_a.set_yaw_rate(omega_a);
7598 if impact_dv_a > 1.5 {
7599 let rec_s: f32 = (1.4 + impact_dv_a * 0.08).clamp(1.2, 2.8);
7600 npc_a.set_recovery_timer(npc_a.get_recovery_timer().max(rec_s));
7601 npc_a.set_free_roam_mode(true);
7602 }
7603 }
7604 {
7605 let Self {
7606 traffic_vehicles, ..
7607 } = self;
7608 let npc_b: &mut NpcVehicle3D = &mut traffic_vehicles[npc_slot_b];
7609 npc_b.set_vel(vel_b);
7610 npc_b.set_yaw_rate(omega_b);
7611 if impact_dv_b > 1.5 {
7612 let rec_s: f32 = (1.4 + impact_dv_b * 0.08).clamp(1.2, 2.8);
7613 npc_b.set_recovery_timer(npc_b.get_recovery_timer().max(rec_s));
7614 npc_b.set_free_roam_mode(true);
7615 }
7616 }
7617 any_moved = true;
7618 }
7619 }
7620 }
7621 (
7622 any_moved,
7623 player_peak_impact,
7624 player_peak_contact,
7625 player_peak_normal,
7626 )
7627 }
7628
7629 pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
7637 if dt <= 0.0 || !dt.is_finite() {
7638 return;
7639 }
7640 self.set_world_time_secs(self.get_world_time_secs() + dt);
7641 let sim_tick: u64 = self.get_sim_tick().wrapping_add(1);
7642 self.set_sim_tick(sim_tick);
7643 let kb_steer: f32 = if actions.is_active(GameAction::MoveRight, input) {
7644 1.0
7645 } else {
7646 0.0
7647 } - if actions.is_active(GameAction::MoveLeft, input) {
7648 1.0
7649 } else {
7650 0.0
7651 };
7652 let kb_throttle: f32 = if actions.is_active(GameAction::MoveUp, input) {
7653 1.0
7654 } else {
7655 0.0
7656 } - if actions.is_active(GameAction::MoveDown, input) {
7657 1.0
7658 } else {
7659 0.0
7660 };
7661 let v_stick: Point = input.get_virtual_axis();
7662 let steer: f32 = (kb_steer + v_stick.get_x()).clamp(-1.0, 1.0);
7663 let throttle: f32 = (kb_throttle - v_stick.get_y()).clamp(-1.0, 1.0);
7664 let boost_pressed: bool = actions.is_active(GameAction::Boost, input)
7665 || input.get_modifiers().get_shift()
7666 || input.get_virtual_boost();
7667 let drift_pressed: bool = actions.is_active(GameAction::Drift, input)
7668 || input.is_key_down(KeyCode::Space)
7669 || input.get_virtual_drift();
7670 let mut any_dynamic_moved: bool = false;
7671 let mut any_static_moved: bool = false;
7672 let ground_limits: Option<(f32, f32, f32, f32)> = self.ground_play_bounds();
7673 let car_opt: Option<usize> = self.vehicle_index();
7674 let sim_substeps: usize = ((dt / 0.02).ceil() as usize).clamp(1, 6);
7675 let sub_dt: f32 = dt / (sim_substeps as f32);
7676 let mut player_moved_any: bool = false;
7677 for _ in 0..sim_substeps {
7678 if let Some(car_idx) = car_opt
7679 && let Some((cur_tr, mesh_id, car_is_dynamic)) =
7680 self.get_objects().get(car_idx).map(|car: &SceneObject3D| {
7681 (car.get_transform(), car.get_mesh_id(), car.get_is_dynamic())
7682 })
7683 {
7684 let mesh_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
7685 let mut phys: PlayerVehiclePhysics3D = {
7686 let Self { player_physics, .. } = self;
7687 *player_physics
7688 };
7689 let mut flat_tr: Transform3D = Transform3D::new(
7690 Vec3::new(
7691 cur_tr.get_position().get_x(),
7692 0.0,
7693 cur_tr.get_position().get_z(),
7694 ),
7695 cur_tr.get_yaw_rad(),
7696 cur_tr.get_scale(),
7697 );
7698 let flat_obb: OrientedBox3D = flat_tr.to_oriented_box(mesh_bounds);
7699 let ground_margin: f32 = flat_obb
7700 .get_half_extents()
7701 .get_x()
7702 .max(flat_obb.get_half_extents().get_z());
7703 let yaw_now: f32 = flat_tr.get_yaw_rad();
7704 let fwd: Vec3 = Vec3::new(-yaw_now.sin(), 0.0, -yaw_now.cos());
7705 let right: Vec3 = Vec3::new(yaw_now.cos(), 0.0, -yaw_now.sin());
7706 let mut vel: Vec3 = phys.get_vel();
7707 let mut v_fwd: f32 = vel.dot(fwd);
7708 let mut v_lat: f32 = vel.dot(right);
7709 let speed_now: f32 = (v_fwd * v_fwd + v_lat * v_lat).sqrt();
7710 let was_boosting: bool = phys.get_boost_active();
7711 let mut boost_charge: f32 = phys.get_boost_charge();
7712 let mut boost_spool: f32 = phys.get_boost_spool();
7713 let boost_active: bool = boost_pressed && throttle >= -0.05;
7714 let was_drifting: bool = phys.get_drift_active();
7715 let drift_active: bool = drift_pressed
7716 && speed_now > VEHICLE_DRIFT_MIN_SPEED_MPS
7717 && v_fwd > VEHICLE_DRIFT_MIN_FWD_MPS;
7718 if boost_active {
7719 let spool_blend: f32 = 1.0 - (-VEHICLE_BOOST_SPOOL_UP_RATE * sub_dt).exp();
7720 boost_spool += (1.0 - boost_spool) * spool_blend;
7721 let gauge_blend: f32 =
7722 1.0 - (-VEHICLE_BOOST_GAUGE_APPROACH_RATE * sub_dt).exp();
7723 boost_charge += (VEHICLE_BOOST_SUSTAIN_CHARGE - boost_charge) * gauge_blend;
7724 } else {
7725 boost_spool *= (-VEHICLE_BOOST_SPOOL_DOWN_RATE * sub_dt).exp();
7726 if boost_spool < 0.002 {
7727 boost_spool = 0.0;
7728 }
7729 let regen_rate: f32 = if drift_active {
7730 VEHICLE_BOOST_DRIFT_REGEN_PER_SEC
7731 } else {
7732 VEHICLE_BOOST_REGEN_PER_SEC
7733 };
7734 boost_charge = (boost_charge + regen_rate * sub_dt).min(1.0);
7735 }
7736 let mut drift_duration: f32 = phys.get_drift_duration();
7737 let mut drift_peak_slip: f32 = phys.get_drift_peak_slip();
7738 let mut exit_kick_triggered: bool = false;
7739 if drift_active {
7740 drift_duration += sub_dt;
7741 } else if was_drifting {
7742 if drift_duration >= VEHICLE_DRIFT_EXIT_MIN_SECS
7743 && drift_peak_slip >= VEHICLE_DRIFT_EXIT_MIN_SLIP_RAD
7744 && v_fwd > 4.0
7745 {
7746 let slip_snap: f32 = v_lat.abs() * 0.45;
7747 v_fwd = (v_fwd + VEHICLE_DRIFT_EXIT_KICK_MPS + slip_snap)
7748 .min(VEHICLE_BOOST_TOP_SPEED_MPS);
7749 exit_kick_triggered = true;
7750 }
7751 drift_duration = 0.0;
7752 drift_peak_slip = 0.0;
7753 } else {
7754 drift_duration = 0.0;
7755 drift_peak_slip = 0.0;
7756 }
7757 let eff_throttle: f32 = if boost_active && throttle >= 0.0 {
7758 throttle.max(1.0)
7759 } else {
7760 throttle
7761 };
7762 let spool_drive: f32 = 0.40 + 0.60 * boost_spool;
7763 let top_fwd: f32 = if boost_active {
7764 VEHICLE_NORMAL_TOP_SPEED_MPS
7765 + (VEHICLE_BOOST_TOP_SPEED_MPS - VEHICLE_NORMAL_TOP_SPEED_MPS) * spool_drive
7766 } else {
7767 VEHICLE_NORMAL_TOP_SPEED_MPS
7768 };
7769 let long_accel: f32 = if eff_throttle > 0.05 {
7770 if v_fwd < -0.5 {
7771 VEHICLE_BRAKE_DECEL_MPS2
7772 } else if !boost_active && v_fwd > VEHICLE_NORMAL_TOP_SPEED_MPS {
7773 let overspeed: f32 = v_fwd - VEHICLE_NORMAL_TOP_SPEED_MPS;
7774 -(overspeed * VEHICLE_OVERSPEED_AERO_BLEED
7775 + VEHICLE_AERO_DRAG * 0.35 * overspeed * overspeed)
7776 } else {
7777 let launch: f32 = VEHICLE_NORMAL_ACCEL_MPS2
7778 + VEHICLE_LAUNCH_BONUS_MPS2
7779 * (-(v_fwd.abs()) / VEHICLE_LAUNCH_TAPER_MPS).exp();
7780 let mult: f32 = if boost_active {
7781 1.0 + (VEHICLE_BOOST_THRUST_MULT - 1.0) * spool_drive
7782 } else {
7783 1.0
7784 };
7785 let speed_ratio: f32 = (v_fwd / top_fwd).clamp(0.0, 1.0);
7786 let taper: f32 = (1.0 - speed_ratio * speed_ratio * 0.65).max(0.18);
7787 eff_throttle * launch * mult * taper
7788 }
7789 } else if eff_throttle < -0.05 {
7790 if v_fwd > 0.5 {
7791 -VEHICLE_BRAKE_DECEL_MPS2
7792 } else {
7793 let launch: f32 = VEHICLE_NORMAL_ACCEL_MPS2
7794 + VEHICLE_LAUNCH_BONUS_MPS2
7795 * (-(v_fwd.abs()) / VEHICLE_LAUNCH_TAPER_MPS).exp();
7796 let speed_ratio: f32 =
7797 ((-v_fwd) / VEHICLE_REVERSE_TOP_SPEED_MPS).clamp(0.0, 1.0);
7798 let taper: f32 = (1.0 - speed_ratio * speed_ratio * 0.65).max(0.2);
7799 eff_throttle * launch * taper
7800 }
7801 } else {
7802 let handbrake_drag: f32 = if drift_pressed { 4.5 } else { 0.0 };
7803 let drag: f32 = (VEHICLE_ROLLING_DRAG + handbrake_drag) * v_fwd
7804 + VEHICLE_AERO_DRAG * v_fwd * v_fwd.abs();
7805 -drag
7806 };
7807 v_fwd += long_accel * sub_dt;
7808 if eff_throttle.abs() <= 0.05 && v_fwd.abs() < 0.08 && v_lat.abs() < 0.08 {
7809 v_fwd = 0.0;
7810 v_lat = 0.0;
7811 } else {
7812 v_fwd =
7813 v_fwd.clamp(-VEHICLE_REVERSE_TOP_SPEED_MPS, VEHICLE_BOOST_TOP_SPEED_MPS);
7814 }
7815 let prev_gear: u8 = phys.get_active_gear().clamp(1, 6);
7816 let fwd_abs: f32 = v_fwd.abs();
7817 let mut next_gear: u8 = 1;
7818 for (g_idx, &thresh) in VEHICLE_GEAR_THRESHOLDS_MPS.iter().enumerate() {
7819 if fwd_abs >= thresh {
7820 next_gear = (g_idx + 1) as u8;
7821 }
7822 }
7823 let gear_floor: f32 = VEHICLE_GEAR_THRESHOLDS_MPS[(next_gear - 1) as usize];
7824 let gear_ceil: f32 = if (next_gear as usize) < VEHICLE_GEAR_THRESHOLDS_MPS.len() {
7825 VEHICLE_GEAR_THRESHOLDS_MPS[next_gear as usize]
7826 } else {
7827 VEHICLE_BOOST_TOP_SPEED_MPS
7828 };
7829 let gear_span: f32 = (gear_ceil - gear_floor).max(4.0);
7830 let engine_rpm_norm: f32 = (0.16
7831 + 0.84 * ((fwd_abs - gear_floor) / gear_span).clamp(0.0, 1.0)
7832 + if boost_active {
7833 0.12 * boost_spool
7834 } else {
7835 0.0
7836 })
7837 .clamp(0.14, 1.0);
7838 let mut backfire_timer: f32 = (phys.get_backfire_timer() - sub_dt).max(0.0);
7839 let upshift_pop: bool =
7840 next_gear > prev_gear && eff_throttle > 0.45 && fwd_abs > 10.0;
7841 let lift_off_pop: bool =
7842 phys.get_prev_throttle() > 0.45 && eff_throttle <= 0.08 && fwd_abs > 13.0;
7843 let boost_release_pop: bool = was_boosting && !boost_active && fwd_abs > 16.0;
7844 let any_throttle_pop: bool = upshift_pop || lift_off_pop;
7845 if any_throttle_pop || boost_release_pop {
7846 backfire_timer = VEHICLE_BACKFIRE_DURATION_SECS;
7847 }
7848 let slip_before: f32 = v_lat.atan2(v_fwd.abs().max(1.0));
7849 let lat_grip: f32 = if drift_active {
7850 let extra_scrub: f32 = ((slip_before.abs() - 0.66).max(0.0)) * 5.2;
7851 VEHICLE_DRIFT_LAT_GRIP + extra_scrub
7852 } else {
7853 VEHICLE_NORMAL_LAT_GRIP
7854 };
7855 v_lat *= (-lat_grip * sub_dt).exp();
7856 let mut yaw_rate: f32 = phys.get_yaw_rate();
7857 let steer_sign: f32 =
7858 if v_fwd < -0.35 || (v_fwd.abs() <= 0.35 && eff_throttle < -0.05) {
7859 -1.0
7860 } else {
7861 1.0
7862 };
7863 let active_speed: f32 = (v_fwd * v_fwd + v_lat * v_lat).sqrt();
7864 let base_auth: f32 = (0.90 + 0.10 * (active_speed / 8.0).min(1.0)).min(1.0);
7865 let high_speed_calm: f32 = if drift_active {
7866 1.0
7867 } else {
7868 (1.0 - ((active_speed - 28.0).max(0.0) / 60.0)).clamp(0.72, 1.0)
7869 };
7870 let steer_authority: f32 = base_auth * high_speed_calm;
7871 let yaw_gain: f32 = if drift_active {
7872 VEHICLE_DRIFT_YAW_GAIN
7873 } else {
7874 VEHICLE_NORMAL_YAW_GAIN
7875 };
7876 let target_yaw_rate: f32 = if steer.abs() > 0.05 {
7877 -steer * steer_sign * yaw_gain * steer_authority
7878 } else {
7879 0.0
7880 };
7881 let yaw_resp: f32 = if drift_active { 12.0 } else { 32.0 };
7882 let yaw_blend: f32 = 1.0 - (-yaw_resp * sub_dt).exp();
7883 yaw_rate += (target_yaw_rate - yaw_rate) * yaw_blend;
7884 if drift_active {
7885 let slip_excess: f32 = (slip_before.abs() - 0.56).max(0.0);
7886 if slip_excess > 0.0 {
7887 let align_torque: f32 = -slip_before.signum() * slip_excess * 5.8;
7888 yaw_rate += align_torque * sub_dt;
7889 }
7890 if steer.abs() > 0.05 && slip_before.abs() < 0.28 {
7891 let kick_dir: f32 = -steer.signum();
7892 v_lat += -kick_dir * 6.5 * sub_dt;
7893 }
7894 }
7895 if steer.abs() <= 0.05 && yaw_rate.abs() < 0.01 && active_speed < 0.1 {
7896 yaw_rate = 0.0;
7897 }
7898 yaw_rate = yaw_rate.clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
7899 vel = fwd.scale(v_fwd).add(right.scale(v_lat));
7900 let (ccd_moved, wall_impact, wall_contact, wall_normal): (bool, f32, Vec3, Vec3) =
7901 self.step_rigid_vehicle_static_ccd(
7902 &mut flat_tr,
7903 &mut vel,
7904 &mut yaw_rate,
7905 (
7906 1.0 / VEHICLE_PLAYER_MASS_KG,
7907 1.0 / VEHICLE_PLAYER_INERTIA_YAW,
7908 ),
7909 (car_idx, mesh_bounds),
7910 VehicleCcdStepCtx3D {
7911 sub_dt,
7912 ground_limits,
7913 ground_margin,
7914 },
7915 );
7916 let final_yaw: f32 = flat_tr.get_yaw_rad();
7917 let final_fwd: Vec3 = Vec3::new(-final_yaw.sin(), 0.0, -final_yaw.cos());
7918 let final_right: Vec3 = Vec3::new(final_yaw.cos(), 0.0, -final_yaw.sin());
7919 let post_vfwd: f32 = vel.dot(final_fwd);
7920 let post_vlat: f32 = vel.dot(final_right);
7921 let post_slip: f32 = if post_vfwd.abs() + post_vlat.abs() > 1.0 {
7922 post_vlat.atan2(post_vfwd.abs().max(1.0))
7923 } else {
7924 0.0
7925 };
7926 if drift_active {
7927 drift_peak_slip = drift_peak_slip.max(post_slip.abs());
7928 }
7929 let mut cam_shake: f32 = phys.get_camera_shake() * (-7.5 * sub_dt).exp();
7930 if cam_shake < 0.004 {
7931 cam_shake = 0.0;
7932 }
7933 let mut body_pitch: f32 = phys.get_body_pitch_rad();
7934 if wall_impact > 2.8 {
7935 let imp_norm: f32 = ((wall_impact - 2.0) / 26.0).clamp(0.0, 1.0);
7936 cam_shake = cam_shake.max(imp_norm * 0.65);
7937 if wall_normal.dot(final_fwd) < -0.35 {
7938 body_pitch = (body_pitch - imp_norm * 0.055).clamp(-0.08, 0.06);
7939 }
7940 self.emit_collision_sparks(wall_contact, wall_normal, imp_norm);
7941 }
7942 let target_roll: f32 = if post_vlat.abs() > 0.25 {
7943 (-post_vlat * 0.011).clamp(-0.085, 0.085)
7944 } else {
7945 0.0
7946 };
7947 let target_pitch: f32 = if boost_active {
7948 0.020 + 0.022 * boost_spool
7949 } else if long_accel > 8.0 {
7950 0.018
7951 } else if long_accel < -15.0 {
7952 -0.028
7953 } else {
7954 0.0
7955 };
7956 let susp_blend: f32 = 1.0 - (-10.0 * sub_dt).exp();
7957 let mut body_roll: f32 = phys.get_body_roll_rad()
7958 + (target_roll - phys.get_body_roll_rad()) * susp_blend;
7959 body_pitch += (target_pitch - body_pitch) * susp_blend;
7960 if body_roll.abs() < 0.0005 && target_roll == 0.0 {
7961 body_roll = 0.0;
7962 }
7963 if body_pitch.abs() < 0.0005 && target_pitch == 0.0 {
7964 body_pitch = 0.0;
7965 }
7966 let target_fov_boost: f32 = if boost_active {
7967 CAMERA_BOOST_FOV_MAX_DEG * (0.45 + 0.55 * boost_spool)
7968 } else if exit_kick_triggered {
7969 CAMERA_BOOST_FOV_MAX_DEG * 0.6
7970 } else if drift_active && post_slip.abs() > 0.18 {
7971 3.2
7972 } else {
7973 0.0
7974 };
7975 let fov_blend: f32 = 1.0 - (-5.5 * sub_dt).exp();
7976 let mut cam_fov_boost: f32 = phys.get_camera_fov_boost()
7977 + (target_fov_boost - phys.get_camera_fov_boost()) * fov_blend;
7978 if cam_fov_boost < 0.02 && target_fov_boost == 0.0 {
7979 cam_fov_boost = 0.0;
7980 }
7981 let wheel_rad_world: f32 = Self::hero_wheel_layout(self.get_hero_vehicle_style())
7982 .get_wheel_radius_m()
7983 * flat_tr.get_scale().get_x().max(0.5);
7984 let mut wheel_spin_rad: f32 =
7985 phys.get_wheel_spin_rad() - (post_vfwd / wheel_rad_world.max(0.1)) * sub_dt;
7986 if wheel_spin_rad.abs() > 10_000.0 * PI {
7987 wheel_spin_rad = wheel_spin_rad.rem_euclid(2.0 * PI);
7988 }
7989 let drift_counter_steer: f32 = if drift_active {
7990 (post_slip * 0.35).clamp(-0.22, 0.22)
7991 } else {
7992 0.0
7993 };
7994 let target_front_steer: f32 = (-steer * VEHICLE_MAX_FRONT_STEER_RAD
7995 + drift_counter_steer)
7996 .clamp(-VEHICLE_MAX_FRONT_STEER_RAD, VEHICLE_MAX_FRONT_STEER_RAD);
7997 let steer_blend: f32 = 1.0 - (-VEHICLE_FRONT_STEER_RESP_RATE * sub_dt).exp();
7998 let mut front_steer_rad: f32 = phys.get_front_steer_rad()
7999 + (target_front_steer - phys.get_front_steer_rad()) * steer_blend;
8000 if front_steer_rad.abs() < 0.0005 && target_front_steer == 0.0 {
8001 front_steer_rad = 0.0;
8002 }
8003 phys.set_vel(vel);
8004 phys.set_yaw_rate(yaw_rate);
8005 phys.set_body_roll_rad(body_roll);
8006 phys.set_body_pitch_rad(body_pitch);
8007 phys.set_boost_active(boost_active);
8008 phys.set_boost_charge(boost_charge);
8009 phys.set_boost_spool(boost_spool);
8010 phys.set_engine_rpm_norm(engine_rpm_norm);
8011 phys.set_active_gear(next_gear);
8012 phys.set_prev_throttle(eff_throttle);
8013 phys.set_backfire_timer(backfire_timer);
8014 phys.set_drift_active(drift_active);
8015 phys.set_drift_slip_angle(post_slip);
8016 phys.set_drift_duration(drift_duration);
8017 phys.set_drift_peak_slip(drift_peak_slip);
8018 phys.set_camera_fov_boost(cam_fov_boost);
8019 phys.set_camera_shake(cam_shake);
8020 phys.set_wheel_spin_rad(wheel_spin_rad);
8021 phys.set_front_steer_rad(front_steer_rad);
8022 {
8023 let Self { player_physics, .. } = self;
8024 *player_physics = phys;
8025 }
8026 let lift_y: f32 = (body_roll.abs() * 0.55 + body_pitch.abs() * 0.95).min(0.06);
8027 let mut visual_tr: Transform3D = Transform3D {
8028 position: Vec3::new(
8029 flat_tr.get_position().get_x(),
8030 lift_y,
8031 flat_tr.get_position().get_z(),
8032 ),
8033 rotation: Quat::from_euler_yxz(final_yaw, body_pitch, body_roll),
8034 scale: flat_tr.get_scale(),
8035 };
8036 if (body_roll != 0.0 || body_pitch != 0.0)
8037 && self
8038 .mesh_oriented_box_static_collision(
8039 visual_tr.to_oriented_box(mesh_bounds),
8040 Some(car_idx),
8041 )
8042 .is_some()
8043 {
8044 visual_tr = flat_tr;
8045 }
8046 let tr_changed: bool = ccd_moved || visual_tr != cur_tr;
8047 if tr_changed {
8048 let world_b: AxisAlignedBox3D = visual_tr.transform_bounds(mesh_bounds);
8049 if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
8050 car_mut.set_transform(visual_tr);
8051 car_mut.set_world_bounds(world_b);
8052 }
8053 player_moved_any = true;
8054 if car_is_dynamic {
8055 any_dynamic_moved = true;
8056 } else {
8057 any_static_moved = true;
8058 }
8059 }
8060 }
8061 let traffic_count: usize = self.traffic_vehicle_count();
8062 for slot_idx in 0..traffic_count {
8063 let mut npc: NpcVehicle3D = {
8064 let Self {
8065 traffic_vehicles, ..
8066 } = self;
8067 traffic_vehicles[slot_idx]
8068 };
8069 let npc_idx: usize = npc.get_object_index();
8070 let Some((cur_tr, mesh_id, is_dynamic)) =
8071 self.get_objects().get(npc_idx).map(|obj: &SceneObject3D| {
8072 (obj.get_transform(), obj.get_mesh_id(), obj.get_is_dynamic())
8073 })
8074 else {
8075 continue;
8076 };
8077 let local_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
8078 let mut tr: Transform3D = Transform3D::new(
8079 Vec3::new(
8080 cur_tr.get_position().get_x(),
8081 0.0,
8082 cur_tr.get_position().get_z(),
8083 ),
8084 cur_tr.get_yaw_rad(),
8085 cur_tr.get_scale(),
8086 );
8087 let obb_npc: OrientedBox3D = tr.to_oriented_box(local_bounds);
8088 let margin: f32 = obb_npc
8089 .get_half_extents()
8090 .get_x()
8091 .max(obb_npc.get_half_extents().get_z());
8092 let pos: Vec3 = tr.get_position();
8093 let yaw: f32 = tr.get_yaw_rad();
8094 let fwd: Vec3 = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
8095 let right: Vec3 = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
8096 let mut vel: Vec3 = npc.get_vel();
8097 let mut yaw_rate: f32 = npc.get_yaw_rate();
8098 let mut recovery: f32 = npc.get_recovery_timer();
8099 let mut stuck_timer: f32 = npc.get_stuck_timer();
8100 let mut unstick_timer: f32 = npc.get_unstick_timer();
8101 let mut unstick_steer: f32 = npc.get_unstick_steer();
8102 let mut escape_heading: f32 = npc.get_escape_heading();
8103 let mut escape_timer: f32 = npc.get_escape_timer();
8104 let mut lane_avoid: f32 = npc.get_lane_avoid_offset();
8105 let mut waiting_stationary_player: bool = false;
8106 if recovery > 0.0 {
8107 recovery = (recovery - sub_dt).max(0.0);
8108 let mut v_fwd: f32 = vel.dot(fwd);
8109 let mut v_lat: f32 = vel.dot(right);
8110 v_fwd *= (-1.15 * sub_dt).exp();
8111 v_lat *= (-2.85 * sub_dt).exp();
8112 vel = fwd.scale(v_fwd).add(right.scale(v_lat));
8113 yaw_rate *= (-2.3 * sub_dt).exp();
8114 stuck_timer = 0.0;
8115 if recovery <= 0.0 && yaw_rate.abs() < 0.8 {
8116 let (route_id, wp_idx, wp_pos): (u8, usize, Vec3) =
8117 NpcVehicle3D::nearest_open_waypoint(pos);
8118 npc.set_route_id(route_id);
8119 npc.set_waypoint_idx(wp_idx);
8120 npc.set_nav_target(wp_pos);
8121 }
8122 } else if unstick_timer > 0.0 {
8123 unstick_timer = (unstick_timer - sub_dt).max(0.0);
8124 let rear_clear: bool = self.npc_probe_heading_clear(
8125 (npc_idx, pos, tr.get_scale(), local_bounds),
8126 Self::wrap_angle_rad(yaw + PI),
8127 2.3,
8128 (ground_limits, margin),
8129 );
8130 if !rear_clear && unstick_timer < NPC_UNSTICK_REVERSE_SECS - 0.25 {
8131 unstick_timer = 0.0;
8132 }
8133 let mut v_fwd: f32 = vel.dot(fwd);
8134 let mut v_lat: f32 = vel.dot(right);
8135 let target_rev: f32 = if rear_clear {
8136 NPC_UNSTICK_REVERSE_SPEED_MPS
8137 } else {
8138 -1.5
8139 };
8140 let speed_diff: f32 = target_rev - v_fwd;
8141 v_fwd += speed_diff.clamp(-24.0 * sub_dt, 24.0 * sub_dt);
8142 v_lat *= (-8.5 * sub_dt).exp();
8143 let target_omega: f32 = unstick_steer * NPC_UNSTICK_YAW_RATE_RAD_S;
8144 let omega_blend: f32 = 1.0 - (-14.0 * sub_dt).exp();
8145 yaw_rate += (target_omega - yaw_rate) * omega_blend;
8146 vel = fwd.scale(v_fwd).add(right.scale(v_lat));
8147 stuck_timer = 0.0;
8148 if unstick_timer <= 0.0 {
8149 let last_wn: Vec3 = Vec3::new(
8150 npc.get_last_wall_normal_x(),
8151 0.0,
8152 npc.get_last_wall_normal_z(),
8153 );
8154 escape_heading = self.npc_scan_escape_heading(
8155 (npc_idx, pos, tr.get_scale(), local_bounds),
8156 yaw,
8157 last_wn,
8158 (ground_limits, margin),
8159 );
8160 escape_timer = NPC_ESCAPE_HOLD_SECS;
8161 let (_, cur_road_u): (f32, f32) =
8162 Self::loop_lateral_offset(pos.get_x(), pos.get_z());
8163 if cur_road_u.abs() > CITY_LOOP_SIDEWALK_HALF_WIDTH + 1.0 {
8164 npc.set_free_roam_mode(true);
8165 }
8166 if npc.get_free_roam_mode() {
8167 let (route_id, wp_idx, wp_pos): (u8, usize, Vec3) =
8168 NpcVehicle3D::nearest_open_waypoint(pos.add(Vec3::new(
8169 -escape_heading.sin() * 14.0,
8170 0.0,
8171 -escape_heading.cos() * 14.0,
8172 )));
8173 npc.set_route_id(route_id);
8174 npc.set_waypoint_idx(wp_idx);
8175 npc.set_nav_target(wp_pos);
8176 }
8177 }
8178 } else {
8179 let mut v_fwd: f32 = vel.dot(fwd);
8180 let mut v_lat: f32 = vel.dot(right);
8181 let target_pt: Vec3 = if npc.get_free_roam_mode() {
8182 let cur_tgt: Vec3 = npc.get_nav_target();
8183 let to_t: Vec3 = Vec3::new(
8184 cur_tgt.get_x() - pos.get_x(),
8185 0.0,
8186 cur_tgt.get_z() - pos.get_z(),
8187 );
8188 if to_t.length_sq() < 49.0 {
8189 let wps: &[(f32, f32)] =
8190 NpcVehicle3D::route_waypoints(npc.get_route_id());
8191 let next_wp: usize = (npc.get_waypoint_idx() + 1) % wps.len();
8192 let next_pt: Vec3 = Vec3::new(wps[next_wp].0, 0.0, wps[next_wp].1);
8193 npc.set_waypoint_idx(next_wp);
8194 npc.set_nav_target(next_pt);
8195 next_pt
8196 } else {
8197 cur_tgt
8198 }
8199 } else {
8200 let cur_s: f32 = npc.get_loop_arc_s();
8201 let lane_u: f32 = (npc.get_loop_lane_u() + lane_avoid).clamp(-8.6, 8.6);
8202 let dir: f32 = npc.get_loop_dir();
8203 let (_, base_yaw_at_s): (Vec3, f32) = Self::loop_pose_at(cur_s, lane_u);
8204 let tan_yaw: f32 = if dir >= 0.0 {
8205 base_yaw_at_s
8206 } else {
8207 base_yaw_at_s + PI
8208 };
8209 let tan_dir: Vec3 = Vec3::new(-tan_yaw.sin(), 0.0, -tan_yaw.cos());
8210 let prog: f32 = vel.dot(tan_dir).max(0.0) * sub_dt;
8211 let next_s: f32 = (cur_s + dir * prog).rem_euclid(CITY_LOOP_TOTAL_LENGTH);
8212 npc.set_loop_arc_s(next_s);
8213 let look_s: f32 = (next_s + dir * 11.0).rem_euclid(CITY_LOOP_TOTAL_LENGTH);
8214 let (look_pt, _): (Vec3, f32) = Self::loop_pose_at(look_s, lane_u);
8215 npc.set_nav_target(look_pt);
8216 look_pt
8217 };
8218 let desired_yaw: f32 = if escape_timer > 0.0 {
8219 escape_timer = (escape_timer - sub_dt).max(0.0);
8220 escape_heading
8221 } else {
8222 let to_target: Vec3 = Vec3::new(
8223 target_pt.get_x() - pos.get_x(),
8224 0.0,
8225 target_pt.get_z() - pos.get_z(),
8226 );
8227 if to_target.length_sq() > 1.0e-4 {
8228 (-to_target.get_x()).atan2(-to_target.get_z())
8229 } else {
8230 yaw
8231 }
8232 };
8233 let mut yaw_err: f32 = Self::wrap_angle_rad(desired_yaw - yaw);
8234 let (feeler_override, feeler_slow, left_open, right_open): (
8235 Option<f32>,
8236 f32,
8237 bool,
8238 bool,
8239 ) = self.npc_evaluate_5ray_feelers(
8240 (npc_idx, pos, tr.get_scale(), local_bounds),
8241 yaw,
8242 yaw_err,
8243 (ground_limits, margin),
8244 );
8245 if let Some(avoid_ang) = feeler_override {
8246 yaw_err = avoid_ang;
8247 }
8248 let (player_gap, traffic_steer, traffic_slow): (Option<f32>, f32, f32) = self
8249 .npc_sense_traffic(
8250 npc_idx,
8251 pos,
8252 fwd,
8253 right,
8254 v_fwd,
8255 (left_open, right_open),
8256 );
8257 if traffic_steer.abs() > 0.01 {
8258 yaw_err = (yaw_err * 0.35 + traffic_steer).clamp(-1.35, 1.35);
8259 let lane_shift_delta: f32 = -traffic_steer * 2.4 * sub_dt;
8260 lane_avoid = (lane_avoid + lane_shift_delta).clamp(-3.4, 3.4);
8261 } else {
8262 lane_avoid *= (-1.8 * sub_dt).exp();
8263 if lane_avoid.abs() < 0.02 {
8264 lane_avoid = 0.0;
8265 }
8266 }
8267 let mut target_speed: f32 =
8268 npc.get_cruise_speed() * feeler_slow.min(traffic_slow);
8269 if let Some(gap_m) = player_gap {
8270 if gap_m < 9.5 {
8271 target_speed = 0.0;
8272 waiting_stationary_player = true;
8273 } else if gap_m < 14.5 {
8274 target_speed *= ((gap_m - 9.5) / 5.0).clamp(0.0, 1.0);
8275 waiting_stationary_player = true;
8276 }
8277 }
8278 let speed_diff: f32 = target_speed - v_fwd;
8279 let accel_rate: f32 = if speed_diff < 0.0 { 36.0 } else { 18.0 };
8280 v_fwd += speed_diff.clamp(-accel_rate * sub_dt, accel_rate * sub_dt);
8281 if target_speed <= 0.05 && v_fwd.abs() < 0.15 {
8282 v_fwd = 0.0;
8283 }
8284 v_lat *= (-8.5 * sub_dt).exp();
8285 let target_omega: f32 = (yaw_err * 3.8).clamp(-2.8, 2.8);
8286 let omega_blend: f32 = 1.0 - (-12.0 * sub_dt).exp();
8287 yaw_rate += (target_omega - yaw_rate) * omega_blend;
8288 if waiting_stationary_player && v_fwd.abs() < 0.1 {
8289 yaw_rate *= (-8.0 * sub_dt).exp();
8290 }
8291 vel = fwd.scale(v_fwd).add(right.scale(v_lat));
8292 }
8293 let (npc_moved, npc_wall_imp, npc_wall_cp, npc_wall_n): (bool, f32, Vec3, Vec3) =
8294 self.step_rigid_vehicle_static_ccd(
8295 &mut tr,
8296 &mut vel,
8297 &mut yaw_rate,
8298 (
8299 1.0 / npc.get_mass().max(100.0),
8300 1.0 / VEHICLE_NPC_INERTIA_YAW,
8301 ),
8302 (npc_idx, local_bounds),
8303 VehicleCcdStepCtx3D {
8304 sub_dt,
8305 ground_limits,
8306 ground_margin: margin,
8307 },
8308 );
8309 if npc_wall_imp > 3.5 {
8310 let spark_int: f32 = ((npc_wall_imp - 2.5) / 22.0).clamp(0.15, 0.9);
8311 self.emit_collision_sparks(npc_wall_cp, npc_wall_n, spark_int);
8312 }
8313 let post_speed_mps: f32 =
8314 (vel.get_x() * vel.get_x() + vel.get_z() * vel.get_z()).sqrt();
8315 let hit_wall_forward: bool =
8316 npc_wall_imp > 0.40 && npc_wall_n.dot(fwd) < -0.25 && recovery <= 0.0;
8317 if hit_wall_forward {
8318 npc.set_last_wall_normal_x(npc_wall_n.get_x());
8319 npc.set_last_wall_normal_z(npc_wall_n.get_z());
8320 }
8321 if !waiting_stationary_player && recovery <= 0.0 && unstick_timer <= 0.0 {
8322 if post_speed_mps < NPC_STUCK_SPEED_MPS {
8323 stuck_timer += sub_dt;
8324 } else if post_speed_mps > NPC_STUCK_SPEED_MPS + 0.6 {
8325 stuck_timer = (stuck_timer - sub_dt * 2.0).max(0.0);
8326 }
8327 if stuck_timer >= NPC_STUCK_TRIGGER_SECS || hit_wall_forward {
8328 let ref_wn: Vec3 = if hit_wall_forward {
8329 npc_wall_n
8330 } else {
8331 Vec3::new(
8332 npc.get_last_wall_normal_x(),
8333 0.0,
8334 npc.get_last_wall_normal_z(),
8335 )
8336 };
8337 let wn_right: f32 = ref_wn.dot(right);
8338 let chosen_steer: f32 = if wn_right > 0.12 {
8339 -1.0
8340 } else if wn_right < -0.12 {
8341 1.0
8342 } else {
8343 let rear_geo: (usize, Vec3, Vec3, AxisAlignedBox3D) =
8344 (npc_idx, tr.get_position(), tr.get_scale(), local_bounds);
8345 let rear_left_ok: bool = self.npc_probe_heading_clear(
8346 rear_geo,
8347 Self::wrap_angle_rad(tr.get_yaw_rad() + PI - 0.45),
8348 3.8,
8349 (ground_limits, margin),
8350 );
8351 let rear_right_ok: bool = self.npc_probe_heading_clear(
8352 rear_geo,
8353 Self::wrap_angle_rad(tr.get_yaw_rad() + PI + 0.45),
8354 3.8,
8355 (ground_limits, margin),
8356 );
8357 if rear_right_ok && !rear_left_ok {
8358 1.0
8359 } else if rear_left_ok && !rear_right_ok {
8360 -1.0
8361 } else if (npc_idx & 1) == 0 {
8362 1.0
8363 } else {
8364 -1.0
8365 }
8366 };
8367 unstick_steer = chosen_steer;
8368 unstick_timer = NPC_UNSTICK_REVERSE_SECS;
8369 stuck_timer = 0.0;
8370 escape_timer = 0.0;
8371 }
8372 } else if waiting_stationary_player {
8373 stuck_timer = 0.0;
8374 }
8375 let npc_yaw_post: f32 = tr.get_yaw_rad();
8376 let npc_fwd_post: Vec3 = Vec3::new(-npc_yaw_post.sin(), 0.0, -npc_yaw_post.cos());
8377 let npc_vfwd_post: f32 = vel.dot(npc_fwd_post);
8378 let npc_scale_val: f32 = tr.get_scale().get_x().max(0.5);
8379 let npc_layout: VehicleWheelLayout3D = npc_wheel_layout(npc.get_vehicle_kind());
8380 let npc_wheel_r: f32 = npc_layout.get_wheel_radius_m() * npc_scale_val;
8381 let mut npc_wheel_spin: f32 =
8382 npc.get_wheel_spin_rad() - (npc_vfwd_post / npc_wheel_r.max(0.1)) * sub_dt;
8383 if npc_wheel_spin.abs() > 10_000.0 * PI {
8384 npc_wheel_spin = npc_wheel_spin.rem_euclid(2.0 * PI);
8385 }
8386 let npc_steer_dir: f32 = if npc_vfwd_post < -0.35 { -1.0 } else { 1.0 };
8387 let npc_target_steer: f32 = (yaw_rate * 0.26 * npc_steer_dir)
8388 .clamp(-VEHICLE_MAX_FRONT_STEER_RAD, VEHICLE_MAX_FRONT_STEER_RAD);
8389 let npc_steer_blend: f32 = 1.0 - (-12.0 * sub_dt).exp();
8390 let npc_front_steer: f32 = npc.get_front_steer_rad()
8391 + (npc_target_steer - npc.get_front_steer_rad()) * npc_steer_blend;
8392 npc.set_vel(vel);
8393 npc.set_yaw_rate(yaw_rate);
8394 npc.set_recovery_timer(recovery);
8395 npc.set_stuck_timer(stuck_timer);
8396 npc.set_unstick_timer(unstick_timer);
8397 npc.set_unstick_steer(unstick_steer);
8398 npc.set_escape_heading(escape_heading);
8399 npc.set_escape_timer(escape_timer);
8400 npc.set_lane_avoid_offset(lane_avoid);
8401 npc.set_wheel_spin_rad(npc_wheel_spin);
8402 npc.set_front_steer_rad(npc_front_steer);
8403 let npc_wheels: [Option<usize>; 4] = npc.get_wheel_object_indices();
8404 {
8405 let Self {
8406 traffic_vehicles, ..
8407 } = self;
8408 traffic_vehicles[slot_idx] = npc;
8409 }
8410 if npc_moved {
8411 let world_b: AxisAlignedBox3D = tr.transform_bounds(local_bounds);
8412 if let Some(obj) = self.get_mut_objects().get_mut(npc_idx) {
8413 obj.set_transform(tr);
8414 obj.set_world_bounds(world_b);
8415 }
8416 if is_dynamic {
8417 any_dynamic_moved = true;
8418 } else {
8419 any_static_moved = true;
8420 }
8421 }
8422 if self.sync_vehicle_wheel_transforms(
8423 npc_wheels,
8424 (tr.get_position(), npc_yaw_post, npc_scale_val),
8425 npc_layout,
8426 (npc_wheel_spin, npc_front_steer),
8427 false,
8428 ) && (npc_moved || npc_vfwd_post.abs() > 0.05 || yaw_rate.abs() > 0.02)
8429 {
8430 any_dynamic_moved = true;
8431 }
8432 }
8433 let (dyn_moved, dyn_imp, _dyn_cp, _dyn_n): (bool, f32, Vec3, Vec3) =
8434 self.resolve_dynamic_vehicle_collisions(ground_limits);
8435 if dyn_moved {
8436 any_dynamic_moved = true;
8437 player_moved_any = true;
8438 }
8439 if dyn_imp > 2.5 {
8440 let imp_norm: f32 = ((dyn_imp - 2.0) / 24.0).clamp(0.0, 1.0);
8441 let Self { player_physics, .. } = self;
8442 let next_shake: f32 = player_physics.get_camera_shake().max(imp_norm * 0.70);
8443 player_physics.set_camera_shake(next_shake);
8444 }
8445 }
8446 if let Some(car_idx) = car_opt
8447 && let Some((car_tr, mesh_id)) = self
8448 .get_objects()
8449 .get(car_idx)
8450 .map(|car: &SceneObject3D| (car.get_transform(), car.get_mesh_id()))
8451 {
8452 let car_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
8453 let mut safe_tr: Transform3D = car_tr;
8454 let car_obb: OrientedBox3D = safe_tr.to_oriented_box(car_bounds);
8455 let car_margin: f32 = car_obb
8456 .get_half_extents()
8457 .get_x()
8458 .max(car_obb.get_half_extents().get_z());
8459 if self.depenetrate_vehicle_horizontally(
8460 &mut safe_tr,
8461 car_bounds,
8462 car_idx,
8463 ground_limits,
8464 car_margin,
8465 ) {
8466 let wb: AxisAlignedBox3D = safe_tr.transform_bounds(car_bounds);
8467 if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
8468 car_mut.set_transform(safe_tr);
8469 car_mut.set_world_bounds(wb);
8470 }
8471 player_moved_any = true;
8472 any_dynamic_moved = true;
8473 }
8474 let final_car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
8475 let car_pos: Vec3 = final_car_tr.get_position();
8476 let yaw: f32 = final_car_tr.get_yaw_rad();
8477 let car_fwd: Vec3 = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
8478 let car_right: Vec3 = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
8479 let phys: PlayerVehiclePhysics3D = {
8480 let Self { player_physics, .. } = self;
8481 *player_physics
8482 };
8483 let tod_tail_scale: f32 = match self.time_of_day_preset() {
8484 TimeOfDayPreset3D::BrightNoon => 0.45,
8485 TimeOfDayPreset3D::MorningSunrise => 0.80,
8486 TimeOfDayPreset3D::GoldenSunset => 1.05,
8487 TimeOfDayPreset3D::NeonMidnight => 1.65,
8488 };
8489 if player_moved_any
8490 || phys.get_boost_active()
8491 || phys.get_drift_active()
8492 || phys.get_backfire_timer() > 0.0
8493 {
8494 let beam_dir: Vec3 = Vec3::new(car_fwd.get_x(), -0.14, car_fwd.get_z()).normalize();
8495 if self.get_spot_lights().len() >= 2 {
8496 let front_center: Vec3 = car_pos
8497 .add(car_fwd.scale(2.2))
8498 .add(Vec3::new(0.0, 0.95, 0.0));
8499 let left_pos: Vec3 = front_center.sub(car_right.scale(0.85));
8500 let right_pos: Vec3 = front_center.add(car_right.scale(0.85));
8501 let spots: &mut Vec<SpotLight3D> = self.get_mut_spot_lights();
8502 spots[0].set_position(left_pos);
8503 spots[0].set_direction(beam_dir);
8504 spots[1].set_position(right_pos);
8505 spots[1].set_direction(beam_dir);
8506 }
8507 if let Some(tail_light) = self.get_mut_point_lights().first_mut()
8508 && tail_light.get_color().get_x() > 0.90
8509 && tail_light.get_color().get_y() < 0.20
8510 {
8511 let rear_pos: Vec3 = car_pos
8512 .sub(car_fwd.scale(2.9))
8513 .add(Vec3::new(0.0, 0.95, 0.0));
8514 tail_light.set_position(rear_pos);
8515 if phys.get_boost_active() {
8516 tail_light.set_color(Vec3::new(1.0, 0.14, 0.06));
8517 tail_light.set_intensity(4.5 * tod_tail_scale);
8518 tail_light.set_radius(10.5);
8519 } else if phys.get_drift_active() || throttle < -0.15 {
8520 tail_light.set_color(Vec3::new(1.0, 0.06, 0.18));
8521 tail_light.set_intensity(3.85 * tod_tail_scale);
8522 tail_light.set_radius(9.6);
8523 } else {
8524 tail_light.set_color(Vec3::new(1.0, 0.09, 0.27));
8525 tail_light.set_intensity(1.85 * tod_tail_scale);
8526 tail_light.set_radius(8.5);
8527 }
8528 }
8529 if phys.get_drift_active()
8530 && phys.get_drift_slip_angle().abs() > 0.12
8531 && (sim_tick & 1) == 0
8532 {
8533 self.emit_drift_smoke(
8534 car_pos,
8535 car_fwd,
8536 car_right,
8537 phys.get_drift_slip_angle().abs(),
8538 );
8539 }
8540 }
8541 let player_wheels: [Option<usize>; 4] = self.player_wheel_object_indices();
8542 let player_wheel_layout: VehicleWheelLayout3D =
8543 Self::hero_wheel_layout(self.get_hero_vehicle_style());
8544 if self.sync_vehicle_wheel_transforms(
8545 player_wheels,
8546 (car_pos, yaw, final_car_tr.get_scale().get_x().max(0.5)),
8547 player_wheel_layout,
8548 (phys.get_wheel_spin_rad(), phys.get_front_steer_rad()),
8549 false,
8550 ) && (player_moved_any || phys.get_front_steer_rad().abs() > 0.005)
8551 {
8552 any_dynamic_moved = true;
8553 }
8554 if self.update_volumetric_exhaust_fx(
8555 final_car_tr,
8556 phys.get_vel(),
8557 phys,
8558 throttle,
8559 sim_tick,
8560 ) {
8561 any_dynamic_moved = true;
8562 }
8563 if self.weather_preset() == WeatherPreset3D::Rainstorm {
8564 let speed_spray: f32 = phys.get_vel().length();
8565 if speed_spray > 4.5
8566 && (sim_tick & 1) == 0
8567 && self.get_niagara().get_active_count() < EXHAUST_BOOST_MAX_PARTICLES
8568 {
8569 let rear_center: Vec3 = car_pos
8570 .sub(car_fwd.scale(1.85))
8571 .add(Vec3::new(0.0, 0.18, 0.0));
8572 let spray_ratio: f32 = ((speed_spray - 4.0) / 36.0).clamp(0.2, 1.0);
8573 for side in [-0.92_f32, 0.92_f32] {
8574 let wheel_pos: Vec3 = rear_center.add(car_right.scale(side));
8575 let mut spray_cfg: NiagaraEmitterConfig3D =
8576 NiagaraEmitterConfig3D::default();
8577 spray_cfg.set_origin(wheel_pos);
8578 spray_cfg.set_base_velocity(
8579 phys.get_vel()
8580 .scale(0.25)
8581 .sub(car_fwd.scale(3.5 + 4.0 * spray_ratio))
8582 .add(Vec3::new(0.0, 1.4 + 1.5 * spray_ratio, 0.0)),
8583 );
8584 spray_cfg.set_velocity_spread(1.1);
8585 spray_cfg.set_start_color(Color::rgba(205, 226, 245, 160));
8586 spray_cfg.set_end_color(Color::rgba(148, 178, 210, 0));
8587 spray_cfg.set_start_size_m(0.14 + 0.10 * spray_ratio);
8588 spray_cfg.set_end_size_m(0.46 + 0.24 * spray_ratio);
8589 spray_cfg.set_min_lifetime(0.25);
8590 spray_cfg.set_max_lifetime(0.55);
8591 spray_cfg.set_drag(2.0);
8592 spray_cfg.set_turbulence(1.8);
8593 spray_cfg.set_emissive_boost(0.20);
8594 self.get_mut_niagara().emit_burst(1, &spray_cfg);
8595 }
8596 }
8597 }
8598 let cam_mode_enum: CameraMode3D = self.active_camera_mode();
8599 let fov_boost: f32 = phys.get_camera_fov_boost();
8600 let chase_pullback: f32 = fov_boost * 0.14;
8601 let reverse_speed_mps: f32 = -phys.get_vel().dot(car_fwd);
8602 let reverse_blend: f32 = ((reverse_speed_mps - 0.5) / 8.0).clamp(0.0, 1.0);
8603 let world_t: f32 = self.get_world_time_secs();
8604 let is_city_cam: bool = cam_mode_enum.is_city_camera();
8605 let is_interior_cam: bool =
8606 matches!(cam_mode_enum, CameraMode3D::Hood | CameraMode3D::Cockpit);
8607 let (mut desired_eye, look_target, desired_fov): (Vec3, Vec3, f32) = match cam_mode_enum
8608 {
8609 CameraMode3D::Hood => {
8610 let eye: Vec3 = Vec3::new(
8611 car_pos.get_x() - yaw.sin() * 1.55,
8612 1.28,
8613 car_pos.get_z() - yaw.cos() * 1.55,
8614 );
8615 let tgt: Vec3 = Vec3::new(
8616 car_pos.get_x() - yaw.sin() * 24.0,
8617 1.15,
8618 car_pos.get_z() - yaw.cos() * 24.0,
8619 );
8620 (eye, tgt, CAMERA_BASE_FOV_DEG + fov_boost * 1.15)
8621 }
8622 CameraMode3D::Cockpit => {
8623 let eye_h: f32 =
8624 if self.get_hero_vehicle_style() == HeroVehicleStyle::ShelbyCobra {
8625 1.28
8626 } else {
8627 1.16
8628 };
8629 let eye: Vec3 = Vec3::new(
8630 car_pos.get_x() - yaw.sin() * 0.25 - car_right.get_x() * 0.36,
8631 eye_h,
8632 car_pos.get_z() - yaw.cos() * 0.25 - car_right.get_z() * 0.36,
8633 );
8634 let tgt: Vec3 = Vec3::new(
8635 car_pos.get_x() - yaw.sin() * 28.0 - car_right.get_x() * 0.20,
8636 eye_h - 0.12,
8637 car_pos.get_z() - yaw.cos() * 28.0 - car_right.get_z() * 0.20,
8638 );
8639 (eye, tgt, CAMERA_BASE_FOV_DEG + 4.0 + fov_boost * 1.2)
8640 }
8641 CameraMode3D::Orbit => {
8642 let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.48;
8643 self.set_camera_orbit_rad(orbit);
8644 let eye: Vec3 = Vec3::new(
8645 car_pos.get_x() + orbit.sin() * 8.6,
8646 2.75 + (orbit * 1.3).sin() * 0.55,
8647 car_pos.get_z() + orbit.cos() * 8.6,
8648 );
8649 (
8650 eye,
8651 Vec3::new(car_pos.get_x(), 1.15, car_pos.get_z()),
8652 CAMERA_BASE_FOV_DEG + fov_boost * 0.5,
8653 )
8654 }
8655 CameraMode3D::Aerial => {
8656 let eye: Vec3 = Vec3::new(
8657 car_pos.get_x() + yaw.sin() * 16.5,
8658 22.0,
8659 car_pos.get_z() + yaw.cos() * 16.5,
8660 );
8661 (
8662 eye,
8663 Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()),
8664 CAMERA_BASE_FOV_DEG + fov_boost * 0.35,
8665 )
8666 }
8667 CameraMode3D::FreeFly => {
8668 let cur_cam: Camera3D = self.get_camera();
8669 let fwd_c: Vec3 = cur_cam.forward();
8670 let right_c: Vec3 = cur_cam.right();
8671 let moved: Vec3 = cur_cam
8672 .get_position()
8673 .add(fwd_c.scale(throttle * 18.0 * dt))
8674 .add(right_c.scale(steer * 14.0 * dt));
8675 let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
8676 (eye, eye.add(fwd_c.scale(16.0)), CAMERA_BASE_FOV_DEG)
8677 }
8678 CameraMode3D::CinematicDolly => {
8679 let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
8680 self.set_camera_orbit_rad(orbit);
8681 let eye: Vec3 = Vec3::new(
8682 car_pos.get_x() + orbit.sin() * 7.8,
8683 3.6 + (orbit * 1.5).sin() * 1.4,
8684 car_pos.get_z() + orbit.cos() * 13.5,
8685 );
8686 (
8687 eye,
8688 Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0),
8689 CAMERA_BASE_FOV_DEG + fov_boost * 0.4,
8690 )
8691 }
8692 CameraMode3D::CitySkylinePanorama => {
8693 let sway: f32 = (world_t * 0.16).sin() * 8.0;
8694 let eye: Vec3 = Vec3::new(-94.0 + sway * 0.35, 38.0, 96.0 + sway);
8695 let tgt: Vec3 = Vec3::new(42.0, 14.0, -24.0);
8696 (eye, tgt, 56.0)
8697 }
8698 CameraMode3D::CityRiverfrontBridge => {
8699 let glide: f32 = (world_t * 0.18).sin() * 12.0;
8700 let eye: Vec3 = Vec3::new(158.0, 14.5, 52.0 + glide);
8701 let tgt: Vec3 = Vec3::new(72.0, 8.5, -24.0);
8702 (eye, tgt, 58.0)
8703 }
8704 CameraMode3D::CityDowntownIntersection => {
8705 let pan: f32 = (world_t * 0.22).sin() * 1.4;
8706 let eye: Vec3 = Vec3::new(-9.0 + pan * 0.35, 6.2, 34.0);
8707 let tgt: Vec3 = Vec3::new(0.0, 4.2, -62.0);
8708 (eye, tgt, 60.0)
8709 }
8710 CameraMode3D::CityAerialDroneOrbit => {
8711 let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.16;
8712 self.set_camera_orbit_rad(orbit);
8713 let eye: Vec3 = Vec3::new(
8714 36.0 + orbit.sin() * 128.0,
8715 66.0 + (orbit * 0.7).sin() * 6.0,
8716 orbit.cos() * 128.0,
8717 );
8718 let tgt: Vec3 = Vec3::new(36.0, 10.0, -8.0);
8719 (eye, tgt, 56.0)
8720 }
8721 CameraMode3D::Chase => {
8722 let chase_dist: f32 = 9.4 + chase_pullback + reverse_blend * 2.4;
8723 let eye: Vec3 = Vec3::new(
8724 car_pos.get_x() + yaw.sin() * chase_dist,
8725 4.05 + chase_pullback * 0.12 + reverse_blend * 0.55,
8726 car_pos.get_z() + yaw.cos() * chase_dist,
8727 );
8728 let tgt: Vec3 = Vec3::new(
8729 car_pos.get_x() - yaw.sin() * 16.0,
8730 2.25 - reverse_blend * 0.65,
8731 car_pos.get_z() - yaw.cos() * 16.0,
8732 );
8733 (eye, tgt, CAMERA_BASE_FOV_DEG + fov_boost)
8734 }
8735 };
8736 let shake_amp: f32 = phys.get_camera_shake();
8737 if shake_amp > 0.005 && !is_city_cam {
8738 let phase: f32 = world_t * 54.0;
8739 let sx: f32 = phase.sin() * shake_amp * 0.34;
8740 let sy: f32 = (phase * 1.37).cos() * shake_amp * 0.22;
8741 desired_eye = desired_eye
8742 .add(car_right.scale(sx))
8743 .add(Vec3::new(0.0, sy, 0.0));
8744 }
8745 if !is_city_cam && !is_interior_cam {
8746 let boom_anchor: Vec3 =
8747 Vec3::new(car_pos.get_x(), car_pos.get_y() + 1.8, car_pos.get_z());
8748 let boom_vec: Vec3 = desired_eye.sub(boom_anchor);
8749 let boom_len: f32 = boom_vec.length();
8750 if boom_len > 0.25 {
8751 let boom_dir: Vec3 = boom_vec.scale(1.0 / boom_len);
8752 if let Some(hit) =
8753 self.raycast_solid_meshes(boom_anchor, boom_dir, boom_len, Some(car_idx))
8754 {
8755 let safe_dist: f32 = (hit.get_distance() - 0.55).max(0.8);
8756 desired_eye = boom_anchor.add(boom_dir.scale(safe_dist));
8757 }
8758 }
8759 }
8760 if !is_interior_cam {
8761 let cam_probe: OrientedBox3D = OrientedBox3D::from_bounds(AxisAlignedBox3D::new(
8762 desired_eye.sub(Vec3::splat(0.45)),
8763 desired_eye.add(Vec3::splat(0.45)),
8764 ));
8765 if let Some(hit) = self.mesh_oriented_box_collision(cam_probe, Some(car_idx)) {
8766 desired_eye =
8767 desired_eye.add(hit.get_normal().scale(hit.get_penetration() + 0.1));
8768 }
8769 }
8770 let prev_cam: Camera3D = self.get_camera();
8771 let mut cam: Camera3D = prev_cam;
8772 let smooth: f32 = if is_interior_cam {
8773 1.0
8774 } else if is_city_cam {
8775 let jump_dist_sq: f32 = prev_cam.get_position().sub(desired_eye).length_sq();
8776 if jump_dist_sq > 144.0 {
8777 1.0
8778 } else {
8779 (dt * 4.5).clamp(0.05, 1.0)
8780 }
8781 } else {
8782 let follow_rate: f32 = 7.0 + reverse_blend * 5.0;
8783 (dt * follow_rate).clamp(0.05, 1.0)
8784 };
8785 cam.set_position(cam.get_position().lerp(desired_eye, smooth));
8786 let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
8787 cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
8788 cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
8789 cam.set_fov_deg(desired_fov);
8790 self.set_camera(cam);
8791 if cam != prev_cam {
8792 self.bump_world_revision();
8793 }
8794 }
8795 let Self {
8796 objects,
8797 mesh_library,
8798 ..
8799 } = self;
8800 for obj in objects.iter_mut() {
8801 let spin: f32 = obj.get_spin_speed();
8802 if spin.abs() > 0.001 {
8803 let mut object_transform: Transform3D = obj.get_transform();
8804 object_transform.set_yaw_rad(object_transform.get_yaw_rad() + spin * dt);
8805 obj.set_transform(object_transform);
8806 let local_bounds: AxisAlignedBox3D = mesh_library
8807 .get(obj.get_mesh_id())
8808 .and_then(|color_item: &MeshLodChain| color_item.get_levels().first())
8809 .map(Mesh3D::get_bounds)
8810 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
8811 obj.set_world_bounds(object_transform.transform_bounds(local_bounds));
8812 if obj.get_is_dynamic() {
8813 any_dynamic_moved = true;
8814 } else {
8815 any_static_moved = true;
8816 }
8817 }
8818 }
8819 if self.weather_preset() == WeatherPreset3D::Rainstorm
8820 && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES
8821 {
8822 let cam_now: Camera3D = self.get_camera();
8823 let cam_pos: Vec3 = cam_now.get_position();
8824 let cam_fwd: Vec3 = cam_now.forward();
8825 let cam_right: Vec3 = cam_now.right();
8826 let phase: f32 = ((sim_tick % 11) as f32) - 5.0;
8827 let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
8828 rain_cfg.set_origin(
8829 cam_pos
8830 .add(cam_fwd.scale(14.0 + (phase.abs() * 1.4)))
8831 .add(cam_right.scale(phase * 1.8))
8832 .add(Vec3::new(0.0, 8.5, 0.0)),
8833 );
8834 rain_cfg.set_base_velocity(Vec3::new(-3.4, -22.5, 1.8));
8835 rain_cfg.set_velocity_spread(4.2);
8836 rain_cfg.set_start_color(Color::rgba(168, 224, 255, 210));
8837 rain_cfg.set_end_color(Color::rgba(76, 158, 240, 55));
8838 rain_cfg.set_start_size_m(0.058);
8839 rain_cfg.set_end_size_m(0.022);
8840 rain_cfg.set_min_lifetime(0.42);
8841 rain_cfg.set_max_lifetime(0.82);
8842 rain_cfg.set_emissive_boost(1.25);
8843 self.get_mut_niagara().emit_burst(4, &rain_cfg);
8844 }
8845 if self.get_niagara().get_active_count() > 0 {
8846 let _: usize = self.get_mut_niagara().update(dt, 0.0);
8847 }
8848 if !self.get_animation_mixer().get_layers().is_empty() {
8849 let anim_updates: usize = self.tick_animations(dt);
8850 if anim_updates > 0 {
8851 any_dynamic_moved = true;
8852 }
8853 }
8854 step_city_ecosystem(self, dt, self.get_world_time_secs());
8855 if any_static_moved {
8856 self.set_bvh_dirty(true);
8857 }
8858 if any_dynamic_moved {
8859 self.set_dynamic_bvh_dirty(true);
8860 }
8861 if any_static_moved || any_dynamic_moved {
8862 self.bump_world_revision();
8863 }
8864 }
8865
8866 #[must_use]
8872 pub fn environment_ibl(&self) -> Option<&EnvironmentIbl3D> {
8873 let Self {
8874 environment_ibl, ..
8875 } = self;
8876 environment_ibl.as_ref()
8877 }
8878
8879 pub fn set_environment_ibl(&mut self, ibl: Option<EnvironmentIbl3D>) {
8886 let Self {
8887 environment_ibl, ..
8888 } = self;
8889 *environment_ibl = ibl;
8890 self.bump_world_revision();
8891 }
8892
8893 #[must_use]
8899 pub fn active_scene_camera_index(&self) -> Option<usize> {
8900 let Self {
8901 active_scene_camera,
8902 ..
8903 } = self;
8904 *active_scene_camera
8905 }
8906
8907 pub fn set_active_scene_camera(&mut self, camera_index: Option<usize>) -> bool {
8918 let cam_count: usize = self.get_scene_cameras().len();
8919 if let Some(target_idx) = camera_index
8920 && target_idx >= cam_count
8921 {
8922 return false;
8923 }
8924 let Self {
8925 active_scene_camera,
8926 ..
8927 } = self;
8928 *active_scene_camera = camera_index;
8929 if let Some(target_idx) = camera_index
8930 && let Some(scene_cam) = self.get_scene_cameras().get(target_idx).cloned()
8931 {
8932 self.set_camera(scene_cam.to_camera3d());
8933 }
8934 self.bump_world_revision();
8935 true
8936 }
8937
8938 #[must_use]
8949 pub fn active_view_projection(&self, viewport_aspect: f32) -> Mat4 {
8950 if let Some(cam_idx) = self.active_scene_camera_index()
8951 && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
8952 {
8953 return scene_cam.view_projection(viewport_aspect);
8954 }
8955 self.get_camera().view_projection(viewport_aspect)
8956 }
8957
8958 #[must_use]
8969 pub fn deformed_mesh_for_object(&self, obj_idx: usize) -> Option<&Mesh3D> {
8970 let Self {
8971 deformed_meshes, ..
8972 } = self;
8973 deformed_meshes.get(obj_idx).and_then(Option::as_ref)
8974 }
8975
8976 #[must_use]
8987 pub fn is_object_visible(&self, obj_idx: usize) -> bool {
8988 let Some(obj) = self.get_objects().get(obj_idx) else {
8989 return false;
8990 };
8991 let Self {
8992 exhaust_flame_objects,
8993 exhaust_flame_visible,
8994 ..
8995 } = self;
8996 if let Some(first_idx) = exhaust_flame_objects[0]
8997 && obj_idx >= first_idx
8998 && obj_idx < first_idx + EXHAUST_TOTAL_FLAME_OBJECTS
8999 {
9000 let slot: usize = obj_idx - first_idx;
9001 if exhaust_flame_objects[slot] == Some(obj_idx) {
9002 return exhaust_flame_visible[slot];
9003 }
9004 }
9005 if let Some(node_id) = obj.try_get_node_id() {
9006 return self.get_scene_graph().is_node_effectively_visible(node_id);
9007 }
9008 true
9009 }
9010
9011 pub fn set_skinning_mode(&mut self, skin_idx: usize, mode: SkinningMode) -> bool {
9023 let Some(skin) = self.get_mut_skins().get_mut(skin_idx) else {
9024 return false;
9025 };
9026 skin.set_skinning_mode(mode);
9027 let _: usize = self.update_deformed_meshes();
9028 self.bump_world_revision();
9029 true
9030 }
9031
9032 pub fn set_collection_visible(&mut self, collection_name: &str, visible: bool) -> bool {
9044 let updated: bool = self
9045 .get_mut_scene_graph()
9046 .get_mut_collections()
9047 .set_collection_visible(collection_name, visible);
9048 if updated {
9049 self.bump_world_revision();
9050 }
9051 updated
9052 }
9053
9054 pub fn load_imported_scene(&mut self, scene: &ImportedScene3D) -> Vec<usize> {
9065 let texture_base: u32 = self.get_textures().len() as u32;
9066 self.get_mut_textures()
9067 .extend(scene.get_textures().iter().cloned());
9068 let material_base: u32 = self.get_principled_materials().len() as u32;
9069 for raw_mat in scene.get_materials().iter() {
9070 let mut rebased: PrincipledMaterial3D = raw_mat.clone();
9071 Self::rebase_material_textures(&mut rebased, texture_base);
9072 self.get_mut_principled_materials().push(rebased);
9073 }
9074 let mesh_base: usize = self.get_mesh_library().len();
9075 for raw_mesh in scene.get_meshes().iter() {
9076 let mut mesh_copy: Mesh3D = raw_mesh.clone();
9077 if let Some(local_mat_id) = mesh_copy.try_get_material_index() {
9078 mesh_copy.set_material_index(Some(local_mat_id.saturating_add(material_base)));
9079 }
9080 let lod_chain: MeshLodChain = if mesh_copy.get_indices().len() > 24 {
9081 build_qem_lod_chain(&mesh_copy, 3)
9082 } else {
9083 MeshLodChain::from_mesh(mesh_copy)
9084 };
9085 let _: usize = self.register_mesh(lod_chain);
9086 }
9087 let node_base: u32 = self.get_scene_graph().get_nodes().len() as u32;
9088 let skin_base: u32 = self.get_skins().len() as u32;
9089 let mut collection_bit_remap: Vec<u64> = Vec::new();
9090 for coll_entry in scene
9091 .get_scene_graph()
9092 .get_collections()
9093 .get_entries()
9094 .iter()
9095 {
9096 let mask_val: u64 = self
9097 .get_mut_scene_graph()
9098 .get_mut_collections()
9099 .register_collection(coll_entry.get_name());
9100 if !coll_entry.get_visible_viewport() {
9101 let _: bool = self
9102 .get_mut_scene_graph()
9103 .get_mut_collections()
9104 .set_collection_visible(coll_entry.get_name(), false);
9105 }
9106 collection_bit_remap.push(mask_val);
9107 }
9108 let src_graph: &SceneGraph3D = scene.get_scene_graph();
9109 let src_nodes: &[SceneNode3D] = src_graph.get_nodes().as_slice();
9110 for (src_idx, src_node) in src_nodes.iter().enumerate() {
9111 let rebased_parent: Option<u32> = src_node
9112 .try_get_parent()
9113 .map(|parent_idx: u32| parent_idx.saturating_add(node_base));
9114 let node_label: &str = if src_node.get_name().is_empty() {
9115 BLENDER_IMPORTED_NODE_FALLBACK
9116 } else {
9117 src_node.get_name().as_str()
9118 };
9119 let mut dst_node: SceneNode3D = SceneNode3D::from_name(node_label, rebased_parent);
9120 dst_node.set_local_translation(src_node.get_local_translation());
9121 dst_node.set_local_rotation(src_node.get_local_rotation());
9122 dst_node.set_local_scale(src_node.get_local_scale());
9123 dst_node.set_visible(src_node.get_visible());
9124 dst_node.set_extras(src_node.get_extras().clone());
9125 let mut mapped_mask: u64 = 0;
9126 let raw_mask: u64 = src_node.get_collection_mask();
9127 for (bit_pos, &dst_bit) in collection_bit_remap.iter().enumerate() {
9128 if (raw_mask & (1_u64 << (bit_pos as u32))) != 0 {
9129 mapped_mask |= dst_bit;
9130 }
9131 }
9132 dst_node.set_collection_mask(if mapped_mask == 0 { 1 } else { mapped_mask });
9133 if let Some(src_mesh_id) = src_node.try_get_mesh_id() {
9134 dst_node.set_mesh_id(Some((mesh_base as u32).saturating_add(src_mesh_id)));
9135 }
9136 if let Some(src_skin_id) = src_node.try_get_skin_id() {
9137 dst_node.set_skin_id(Some(skin_base.saturating_add(src_skin_id)));
9138 }
9139 dst_node.set_camera_id(src_node.try_get_camera_id());
9140 dst_node.set_light_id(src_node.try_get_light_id());
9141 let dst_node_id: u32 = self.get_mut_scene_graph().add_node(dst_node);
9142 let src_weights: &[f32] = src_graph.morph_weights_for_node(src_idx as u32);
9143 if !src_weights.is_empty() {
9144 self.get_mut_scene_graph()
9145 .attach_morph_weights(dst_node_id, src_weights);
9146 }
9147 let Self {
9148 node_object_map, ..
9149 } = self;
9150 node_object_map.push(None);
9151 }
9152 let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
9153 for src_skin in scene.get_skins().iter() {
9154 let mut runtime_skin: Skin3D = Skin3D::from_imported(src_skin);
9155 for joint_node in runtime_skin.get_mut_joints().iter_mut() {
9156 *joint_node = joint_node.saturating_add(node_base);
9157 }
9158 if let Some(root_idx) = runtime_skin.try_get_skeleton_root() {
9159 runtime_skin.set_skeleton_root(Some(root_idx.saturating_add(node_base)));
9160 }
9161 self.get_mut_skins().push(runtime_skin);
9162 }
9163 let mut first_clip_added: Option<usize> = None;
9164 for src_clip in scene.get_animations().iter() {
9165 let mut rebased_clip: ImportedAnimationClip3D = src_clip.clone();
9166 for chan in rebased_clip.get_mut_channels().iter_mut() {
9167 chan.set_target_node(chan.get_target_node().saturating_add(node_base));
9168 }
9169 let clip_idx: usize = self.get_mut_animation_mixer().add_clip(rebased_clip);
9170 if first_clip_added.is_none() {
9171 first_clip_added = Some(clip_idx);
9172 }
9173 }
9174 let graph_snapshot: SceneGraph3D = self.get_scene_graph().clone();
9175 self.get_mut_animation_mixer()
9176 .capture_rest_pose(&graph_snapshot);
9177 if let Some(clip_idx) = first_clip_added
9178 && self.get_animation_mixer().get_layers().is_empty()
9179 {
9180 let _: usize = self
9181 .get_mut_animation_mixer()
9182 .push_layer(NlaLayer3D::new(clip_idx));
9183 }
9184 let mut spawned_objects: Vec<usize> = Vec::new();
9185 let total_nodes: usize = self.get_scene_graph().get_nodes().len();
9186 for node_idx in (node_base as usize)..total_nodes {
9187 let node_copy: SceneNode3D = self.get_scene_graph().get_nodes()[node_idx].clone();
9188 let world_mat: Mat4 = node_copy.get_world_matrix();
9189 let world_tr: Transform3D = Transform3D::from_matrix(world_mat);
9190 if let Some(global_mesh_id) = node_copy.try_get_mesh_id() {
9191 let mesh_usize: usize = global_mesh_id as usize;
9192 let principled_id: Option<u32> = self
9193 .get_mesh_library()
9194 .get(mesh_usize)
9195 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
9196 .and_then(|mesh_ref: &Mesh3D| mesh_ref.try_get_material_index());
9197 let legacy_mat: PbrMaterial = principled_id
9198 .and_then(|mat_idx: u32| self.get_principled_materials().get(mat_idx as usize))
9199 .map_or_else(
9200 || {
9201 self.get_mesh_library()
9202 .get(mesh_usize)
9203 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
9204 .map_or_else(PbrMaterial::default, Mesh3D::get_material)
9205 },
9206 PrincipledMaterial3D::to_legacy_pbr,
9207 );
9208 let cast_shadows: bool = node_copy.get_extras().get_cast_shadows();
9209 let obj_idx: usize = self.spawn_object(
9210 node_copy.get_name(),
9211 mesh_usize,
9212 world_tr,
9213 legacy_mat,
9214 cast_shadows,
9215 );
9216 let skin_opt: Option<u32> = node_copy.try_get_skin_id();
9217 let is_deformable: bool =
9218 skin_opt.is_some() || node_copy.get_morph_weight_count() > 0;
9219 if let Some(obj_mut) = self.get_mut_objects().get_mut(obj_idx) {
9220 obj_mut.set_node_id(Some(node_idx as u32));
9221 obj_mut.set_principled_material_id(principled_id);
9222 obj_mut.set_skin_id(skin_opt);
9223 }
9224 if is_deformable {
9225 let _: bool = self.set_object_dynamic(obj_idx, true);
9226 }
9227 let Self {
9228 node_object_map, ..
9229 } = self;
9230 if let Some(slot) = node_object_map.get_mut(node_idx) {
9231 *slot = Some(obj_idx);
9232 }
9233 spawned_objects.push(obj_idx);
9234 }
9235 if let Some(src_cam_id) = node_copy.try_get_camera_id()
9236 && let Some(imp_cam) = scene.get_cameras().get(src_cam_id as usize)
9237 {
9238 self.get_mut_scene_cameras()
9239 .push(SceneCamera3D::from_imported(
9240 imp_cam,
9241 Some(node_idx as u32),
9242 world_tr.get_position(),
9243 world_tr.get_rotation(),
9244 ));
9245 }
9246 if let Some(src_light_id) = node_copy.try_get_light_id()
9247 && let Some(imp_light) = scene.get_lights().get(src_light_id as usize)
9248 {
9249 let emit_dir: Vec3 = world_tr
9250 .get_rotation()
9251 .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
9252 .normalize();
9253 let light_color: Vec3 = imp_light.get_color();
9254 let light_intensity: f32 = imp_light.get_intensity();
9255 match imp_light.get_kind() {
9256 GltfLightKind::Directional => {
9257 let mut sun_val: DirectionalLight3D = self.get_sun();
9258 sun_val.set_direction(emit_dir.scale(-1.0).normalize());
9259 sun_val.set_color(light_color.scale(light_intensity.max(0.05)));
9260 self.set_sun(sun_val);
9261 }
9262 GltfLightKind::Point { range } => {
9263 let resolved_range: f32 = range.unwrap_or(24.0).max(0.5);
9264 self.get_mut_point_lights().push(PointLight3D::from_linear(
9265 world_tr.get_position(),
9266 light_color,
9267 light_intensity,
9268 resolved_range,
9269 ));
9270 }
9271 GltfLightKind::Spot {
9272 range,
9273 inner_cone_angle,
9274 outer_cone_angle,
9275 } => {
9276 let resolved_range: f32 = range.unwrap_or(32.0).max(0.5);
9277 self.get_mut_spot_lights().push(SpotLight3D::from_linear(
9278 world_tr.get_position(),
9279 emit_dir,
9280 light_color,
9281 light_intensity,
9282 resolved_range,
9283 (inner_cone_angle, outer_cone_angle),
9284 ));
9285 }
9286 GltfLightKind::Area { width, height } => {
9287 self.get_mut_area_lights().push(AreaLight3D::new_rect(
9288 world_tr.get_position(),
9289 emit_dir,
9290 light_color,
9291 light_intensity,
9292 (width, height),
9293 28.0,
9294 ));
9295 }
9296 }
9297 }
9298 }
9299 let _: usize = self.update_deformed_meshes();
9300 if self.environment_ibl().is_none() {
9301 let sun_ref: DirectionalLight3D = self.get_sun();
9302 let baked_ibl: EnvironmentIbl3D = EnvironmentIbl3D::from_procedural_sky(
9303 &sun_ref,
9304 WORLD_DEFAULT_IBL_OCT_SIZE,
9305 WORLD_DEFAULT_IBL_LUT_SIZE,
9306 );
9307 self.set_environment_ibl(Some(baked_ibl));
9308 }
9309 self.set_use_agx_tonemap(true);
9310 self.set_imported_model_count(self.get_imported_model_count().saturating_add(1));
9311 self.set_bvh_dirty(true);
9312 self.set_dynamic_bvh_dirty(true);
9313 self.set_dynamic_topology_dirty(true);
9314 self.bump_world_revision();
9315 spawned_objects
9316 }
9317
9318 pub fn load_glb_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
9329 let imported: ImportedScene3D = parse_gltf_or_glb_bytes(bytes, None)?;
9330 Ok(self.load_imported_scene(&imported))
9331 }
9332
9333 pub fn load_blend_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
9343 let imported: ImportedScene3D = parse_blend_bytes(bytes)?;
9344 Ok(self.load_imported_scene(&imported))
9345 }
9346
9347 pub fn load_euv3d_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
9357 let bundle: BakedAssetBundle3D = Euv3dPackage::decode_any_bytes(bytes)?;
9358 Ok(self.load_imported_scene(bundle.get_scene()))
9359 }
9360
9361 #[must_use]
9376 fn intersect_mesh_triangles_local(
9377 mesh: &Mesh3D,
9378 local_origin: Vec3,
9379 local_dir: Vec3,
9380 local_inv_dir: Vec3,
9381 t_min: f32,
9382 best_t: f32,
9383 ) -> Option<(f32, Vec3)> {
9384 let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
9385 let tris: &[[u32; 3]] = mesh.get_indices().as_slice();
9386 if verts.is_empty() || tris.is_empty() {
9387 return None;
9388 }
9389 let mut closest_t: f32 = best_t;
9390 let mut closest_normal: Vec3 = Vec3::zero();
9391 let mut hit_any: bool = false;
9392 let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
9393 if !meshlets.is_empty() {
9394 for meshlet in meshlets.iter() {
9395 let mbox: AxisAlignedBox3D = meshlet.get_bounds();
9396 let box_t: f32 =
9397 mbox.intersect_ray_near(local_origin, local_inv_dir, t_min, closest_t);
9398 if box_t >= closest_t {
9399 continue;
9400 }
9401 let start: usize = meshlet.get_first_tri() as usize;
9402 let end: usize = start
9403 .saturating_add(meshlet.get_tri_count() as usize)
9404 .min(tris.len());
9405 for tri in &tris[start..end] {
9406 let (i0, i1, i2): (usize, usize, usize) =
9407 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
9408 if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
9409 continue;
9410 }
9411 let v0: Vec3 = verts[i0].get_position();
9412 let e1: Vec3 = verts[i1].get_position().sub(v0);
9413 let e2: Vec3 = verts[i2].get_position().sub(v0);
9414 let h: Vec3 = local_dir.cross(e2);
9415 let a: f32 = e1.dot(h);
9416 if a.abs() < 1e-7 {
9417 continue;
9418 }
9419 let inv_a: f32 = 1.0 / a;
9420 let s: Vec3 = local_origin.sub(v0);
9421 let u: f32 = inv_a * s.dot(h);
9422 if !(0.0..=1.0).contains(&u) {
9423 continue;
9424 }
9425 let q: Vec3 = s.cross(e1);
9426 let v: f32 = inv_a * local_dir.dot(q);
9427 if v < 0.0 || (u + v) > 1.0 {
9428 continue;
9429 }
9430 let t: f32 = inv_a * e2.dot(q);
9431 if t >= t_min && t < closest_t {
9432 closest_t = t;
9433 closest_normal = e1.cross(e2).normalize();
9434 hit_any = true;
9435 }
9436 }
9437 }
9438 } else {
9439 for tri in tris.iter() {
9440 let (i0, i1, i2): (usize, usize, usize) =
9441 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
9442 if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
9443 continue;
9444 }
9445 let v0: Vec3 = verts[i0].get_position();
9446 let e1: Vec3 = verts[i1].get_position().sub(v0);
9447 let e2: Vec3 = verts[i2].get_position().sub(v0);
9448 let h: Vec3 = local_dir.cross(e2);
9449 let a: f32 = e1.dot(h);
9450 if a.abs() < 1e-7 {
9451 continue;
9452 }
9453 let inv_a: f32 = 1.0 / a;
9454 let s: Vec3 = local_origin.sub(v0);
9455 let u: f32 = inv_a * s.dot(h);
9456 if !(0.0..=1.0).contains(&u) {
9457 continue;
9458 }
9459 let q: Vec3 = s.cross(e1);
9460 let v: f32 = inv_a * local_dir.dot(q);
9461 if v < 0.0 || (u + v) > 1.0 {
9462 continue;
9463 }
9464 let t: f32 = inv_a * e2.dot(q);
9465 if t >= t_min && t < closest_t {
9466 closest_t = t;
9467 closest_normal = e1.cross(e2).normalize();
9468 hit_any = true;
9469 }
9470 }
9471 }
9472 if hit_any {
9473 Some((closest_t, closest_normal))
9474 } else {
9475 None
9476 }
9477 }
9478
9479 #[must_use]
9491 pub fn pick_object_ray(
9492 &self,
9493 screen_u: f32,
9494 screen_v: f32,
9495 aspect: f32,
9496 ) -> Option<ScenePickHit3D> {
9497 let safe_aspect: f32 = if aspect.is_finite() && aspect > 0.05 {
9498 aspect
9499 } else {
9500 1.0
9501 };
9502 let ndc_x: f32 = screen_u.clamp(0.0, 1.0) * 2.0 - 1.0;
9503 let ndc_y: f32 = 1.0 - screen_v.clamp(0.0, 1.0) * 2.0;
9504 let (origin, ray_dir, t_min, mut best_t): (Vec3, Vec3, f32, f32) = if let Some(cam_idx) =
9505 self.active_scene_camera_index()
9506 && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
9507 {
9508 let fwd: Vec3 = scene_cam.forward();
9509 let right: Vec3 = scene_cam.right();
9510 let up: Vec3 = scene_cam.up();
9511 match scene_cam.get_projection() {
9512 GltfCameraProjection::Orthographic {
9513 xmag,
9514 ymag,
9515 znear,
9516 zfar,
9517 } => {
9518 let o: Vec3 = scene_cam
9519 .get_position()
9520 .add(right.scale(ndc_x * xmag))
9521 .add(up.scale(ndc_y * ymag));
9522 (o, fwd, znear.max(0.01), zfar.max(znear + 1.0))
9523 }
9524 GltfCameraProjection::Perspective {
9525 yfov_rad,
9526 aspect_ratio,
9527 znear,
9528 zfar,
9529 } => {
9530 let cam_aspect: f32 = aspect_ratio.unwrap_or(safe_aspect).max(0.05);
9531 let half_tan_y: f32 = (yfov_rad.clamp(0.15, 2.6) * 0.5).tan();
9532 let dir: Vec3 = fwd
9533 .add(right.scale(ndc_x * half_tan_y * cam_aspect))
9534 .add(up.scale(ndc_y * half_tan_y))
9535 .normalize();
9536 (
9537 scene_cam.get_position(),
9538 dir,
9539 znear.max(0.01),
9540 zfar.unwrap_or(480.0).max(znear + 1.0),
9541 )
9542 }
9543 }
9544 } else {
9545 let cam: Camera3D = self.get_camera();
9546 let half_tan_y: f32 = (cam.get_fov_deg().clamp(12.0, 120.0).to_radians() * 0.5).tan();
9547 let half_tan_x: f32 = half_tan_y * safe_aspect;
9548 let forward: Vec3 = cam.forward();
9549 let right: Vec3 = cam.right();
9550 let up: Vec3 = right.cross(forward).normalize();
9551 let dir: Vec3 = forward
9552 .add(right.scale(ndc_x * half_tan_x))
9553 .add(up.scale(ndc_y * half_tan_y))
9554 .normalize();
9555 let near_v: f32 = cam.get_near().max(0.01);
9556 (
9557 cam.get_position(),
9558 dir,
9559 near_v,
9560 cam.get_far().max(near_v + 1.0),
9561 )
9562 };
9563 let inv_dir: Vec3 = Vec3::new(
9564 if ray_dir.get_x().abs() > 1e-6 {
9565 1.0 / ray_dir.get_x()
9566 } else {
9567 f32::INFINITY
9568 },
9569 if ray_dir.get_y().abs() > 1e-6 {
9570 1.0 / ray_dir.get_y()
9571 } else {
9572 f32::INFINITY
9573 },
9574 if ray_dir.get_z().abs() > 1e-6 {
9575 1.0 / ray_dir.get_z()
9576 } else {
9577 f32::INFINITY
9578 },
9579 );
9580 let Self {
9581 objects,
9582 mesh_library,
9583 deformed_meshes,
9584 ..
9585 } = self;
9586 let mut best_hit: Option<ScenePickHit3D> = None;
9587 for (obj_idx, obj) in objects.iter().enumerate() {
9588 if !self.is_object_visible(obj_idx) {
9589 continue;
9590 }
9591 let bounds: AxisAlignedBox3D = obj.get_world_bounds();
9592 let aabb_t: f32 = bounds.intersect_ray_near(origin, inv_dir, t_min, best_t);
9593 if aabb_t >= best_t {
9594 continue;
9595 }
9596 let mesh_ref: Option<&Mesh3D> = deformed_meshes
9597 .get(obj_idx)
9598 .and_then(|slot: &Option<Mesh3D>| slot.as_ref())
9599 .or_else(|| {
9600 mesh_library
9601 .get(obj.get_mesh_id())
9602 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
9603 });
9604 let Some(mesh) = mesh_ref else {
9605 best_t = aabb_t;
9606 let world_pos: Vec3 = origin.add(ray_dir.scale(aabb_t));
9607 best_hit = Some(ScenePickHit3D::new(
9608 obj_idx,
9609 obj.get_mesh_id(),
9610 aabb_t,
9611 world_pos,
9612 ray_dir.scale(-1.0),
9613 ));
9614 continue;
9615 };
9616 if mesh.get_indices().is_empty() {
9617 best_t = aabb_t;
9618 let world_pos: Vec3 = origin.add(ray_dir.scale(aabb_t));
9619 best_hit = Some(ScenePickHit3D::new(
9620 obj_idx,
9621 obj.get_mesh_id(),
9622 aabb_t,
9623 world_pos,
9624 ray_dir.scale(-1.0),
9625 ));
9626 continue;
9627 }
9628 let xform: Transform3D = obj.get_transform();
9629 let inv_elems: [f32; 16] = xform.to_inv_mat4().get_elements();
9630 let local_origin: Vec3 = Vec3::new(
9631 inv_elems[0] * origin.get_x()
9632 + inv_elems[4] * origin.get_y()
9633 + inv_elems[8] * origin.get_z()
9634 + inv_elems[12],
9635 inv_elems[1] * origin.get_x()
9636 + inv_elems[5] * origin.get_y()
9637 + inv_elems[9] * origin.get_z()
9638 + inv_elems[13],
9639 inv_elems[2] * origin.get_x()
9640 + inv_elems[6] * origin.get_y()
9641 + inv_elems[10] * origin.get_z()
9642 + inv_elems[14],
9643 );
9644 let local_dir: Vec3 = Vec3::new(
9645 inv_elems[0] * ray_dir.get_x()
9646 + inv_elems[4] * ray_dir.get_y()
9647 + inv_elems[8] * ray_dir.get_z(),
9648 inv_elems[1] * ray_dir.get_x()
9649 + inv_elems[5] * ray_dir.get_y()
9650 + inv_elems[9] * ray_dir.get_z(),
9651 inv_elems[2] * ray_dir.get_x()
9652 + inv_elems[6] * ray_dir.get_y()
9653 + inv_elems[10] * ray_dir.get_z(),
9654 );
9655 let local_inv_dir: Vec3 = Vec3::new(
9656 if local_dir.get_x().abs() > 1e-6 {
9657 1.0 / local_dir.get_x()
9658 } else {
9659 f32::INFINITY
9660 },
9661 if local_dir.get_y().abs() > 1e-6 {
9662 1.0 / local_dir.get_y()
9663 } else {
9664 f32::INFINITY
9665 },
9666 if local_dir.get_z().abs() > 1e-6 {
9667 1.0 / local_dir.get_z()
9668 } else {
9669 f32::INFINITY
9670 },
9671 );
9672 if let Some((hit_t, local_n)) = Self::intersect_mesh_triangles_local(
9673 mesh,
9674 local_origin,
9675 local_dir,
9676 local_inv_dir,
9677 t_min,
9678 best_t,
9679 ) {
9680 best_t = hit_t;
9681 let nmat: [Vec3; 3] = xform.normal_mat3();
9682 let mut world_n: Vec3 = nmat[0]
9683 .scale(local_n.get_x())
9684 .add(nmat[1].scale(local_n.get_y()))
9685 .add(nmat[2].scale(local_n.get_z()))
9686 .normalize();
9687 if world_n.dot(ray_dir) > 0.0 {
9688 world_n = world_n.scale(-1.0);
9689 }
9690 let world_pos: Vec3 = origin.add(ray_dir.scale(hit_t));
9691 best_hit = Some(ScenePickHit3D::new(
9692 obj_idx,
9693 obj.get_mesh_id(),
9694 hit_t,
9695 world_pos,
9696 world_n,
9697 ));
9698 }
9699 }
9700 best_hit
9701 }
9702
9703 pub fn tick_animations(&mut self, dt_secs: f32) -> usize {
9714 let anim_updates: usize = {
9715 let Self {
9716 scene_graph,
9717 animation_mixer,
9718 ..
9719 } = self;
9720 animation_mixer.advance_and_apply(dt_secs, scene_graph)
9721 };
9722 let propagated: usize = self.get_mut_scene_graph().propagate_world_matrices();
9723 let synced: usize = self.sync_objects_from_scene_graph();
9724 let deformed: usize = self.update_deformed_meshes();
9725 let total: usize = anim_updates + propagated + synced + deformed;
9726 if total > 0 {
9727 self.set_dynamic_bvh_dirty(true);
9728 self.bump_world_revision();
9729 }
9730 total
9731 }
9732
9733 pub fn update_deformed_meshes(&mut self) -> usize {
9739 let obj_count: usize = self.get_objects().len();
9740 let Self {
9741 mesh_library,
9742 objects,
9743 scene_graph,
9744 skins,
9745 skin_scratch,
9746 deformed_meshes,
9747 ..
9748 } = self;
9749 if deformed_meshes.len() < obj_count {
9750 deformed_meshes.resize(obj_count, None);
9751 }
9752 let mut updated_count: usize = 0;
9753 for obj_idx in 0..obj_count {
9754 let obj_ref: &SceneObject3D = &objects[obj_idx];
9755 let Some(node_id) = obj_ref.try_get_node_id() else {
9756 continue;
9757 };
9758 let morph_weights: &[f32] = scene_graph.morph_weights_for_node(node_id);
9759 let skin_opt: Option<u32> = obj_ref.try_get_skin_id();
9760 if skin_opt.is_none() && morph_weights.is_empty() {
9761 continue;
9762 }
9763 let Some(base_mesh) = mesh_library
9764 .get(obj_ref.get_mesh_id())
9765 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
9766 else {
9767 continue;
9768 };
9769 let mesh_world: Mat4 = scene_graph.get_nodes().get(node_id as usize).map_or_else(
9770 || obj_ref.get_transform().to_mat4(),
9771 SceneNode3D::get_world_matrix,
9772 );
9773 let did_deform: bool = if let Some(skin_id) = skin_opt
9774 && let Some(skin_ref) = skins.get(skin_id as usize)
9775 {
9776 skin_ref.deform_mesh_into(
9777 base_mesh,
9778 morph_weights,
9779 mesh_world,
9780 scene_graph,
9781 skin_scratch,
9782 )
9783 } else {
9784 let morphed: bool = apply_morph_targets_into(
9785 base_mesh.get_vertices().as_slice(),
9786 base_mesh.get_morph_targets().as_slice(),
9787 morph_weights,
9788 skin_scratch.get_mut_skinned_vertices(),
9789 );
9790 morphed
9791 };
9792 if did_deform {
9793 let deformed_verts: &[Vertex3D] = skin_scratch.get_skinned_vertices().as_slice();
9794 let mut local_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
9795 for vert_item in deformed_verts.iter() {
9796 local_bounds.expand_point(vert_item.get_position());
9797 }
9798 let target_slot: &mut Option<Mesh3D> = &mut deformed_meshes[obj_idx];
9799 if let Some(existing_mesh) = target_slot.as_mut() {
9800 let dst_verts: &mut Vec<Vertex3D> = existing_mesh.get_mut_vertices();
9801 dst_verts.clear();
9802 dst_verts.extend_from_slice(deformed_verts);
9803 existing_mesh.set_bounds(local_bounds);
9804 } else {
9805 let mut cloned_mesh: Mesh3D = base_mesh.clone();
9806 let dst_verts: &mut Vec<Vertex3D> = cloned_mesh.get_mut_vertices();
9807 dst_verts.clear();
9808 dst_verts.extend_from_slice(deformed_verts);
9809 cloned_mesh.set_bounds(local_bounds);
9810 *target_slot = Some(cloned_mesh);
9811 }
9812 if let Some(deformed_ref) = target_slot.as_ref() {
9813 let world_tr: Transform3D = objects[obj_idx].get_transform();
9814 objects[obj_idx]
9815 .set_world_bounds(world_tr.transform_bounds(deformed_ref.get_bounds()));
9816 }
9817 updated_count += 1;
9818 }
9819 }
9820 updated_count
9821 }
9822
9823 pub fn apply_live_delta(&mut self, delta: &BlenderLiveDelta3D) -> bool {
9834 match delta {
9835 BlenderLiveDelta3D::NodeTransform {
9836 node_name,
9837 translation,
9838 rotation,
9839 scale,
9840 blender_z_up,
9841 } => {
9842 let found_id: Option<u32> = self
9843 .get_scene_graph()
9844 .get_nodes()
9845 .iter()
9846 .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
9847 .map(|idx: usize| idx as u32);
9848 let Some(node_id) = found_id else {
9849 return false;
9850 };
9851 let raw_t: Vec3 = Vec3::from_array(*translation);
9852 let raw_r: Quat = Quat::from_array(*rotation).normalize();
9853 let raw_s: Vec3 = Vec3::from_array(*scale);
9854 let (dst_t, dst_r, dst_s): (Vec3, Quat, Vec3) = if *blender_z_up {
9855 (
9856 raw_t.blender_z_up_to_y_up(),
9857 raw_r.blender_z_up_to_y_up(),
9858 Vec3::new(raw_s.get_x(), raw_s.get_z(), raw_s.get_y()),
9859 )
9860 } else {
9861 (raw_t, raw_r, raw_s)
9862 };
9863 self.get_mut_scene_graph()
9864 .set_local_trs(node_id, dst_t, dst_r, dst_s);
9865 let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
9866 let _: usize = self.sync_objects_from_scene_graph();
9867 let _: usize = self.update_deformed_meshes();
9868 self.set_dynamic_bvh_dirty(true);
9869 self.bump_world_revision();
9870 true
9871 }
9872 BlenderLiveDelta3D::MaterialParams {
9873 material_name,
9874 base_color_factor,
9875 metallic_factor,
9876 roughness_factor,
9877 clearcoat_factor,
9878 clearcoat_roughness_factor,
9879 sheen_color_factor,
9880 sheen_roughness_factor,
9881 emissive_factor,
9882 emissive_strength,
9883 transmission_factor,
9884 ior,
9885 } => {
9886 let found_idx: Option<usize> = self
9887 .get_principled_materials()
9888 .iter()
9889 .position(|mat_ref: &PrincipledMaterial3D| mat_ref.get_name() == material_name);
9890 let Some(mat_idx) = found_idx else {
9891 return false;
9892 };
9893 let updated_legacy: PbrMaterial = {
9894 let mat_mut: &mut PrincipledMaterial3D =
9895 &mut self.get_mut_principled_materials()[mat_idx];
9896 if let Some(val) = *base_color_factor {
9897 mat_mut.set_base_color_factor(val);
9898 }
9899 if let Some(val) = *metallic_factor {
9900 mat_mut.set_metallic_factor(val.clamp(0.0, 1.0));
9901 }
9902 if let Some(val) = *roughness_factor {
9903 mat_mut.set_roughness_factor(val.clamp(0.04, 1.0));
9904 }
9905 if let Some(val) = *clearcoat_factor {
9906 mat_mut.set_clearcoat_factor(val.clamp(0.0, 1.0));
9907 }
9908 if let Some(val) = *clearcoat_roughness_factor {
9909 mat_mut.set_clearcoat_roughness_factor(val.clamp(0.0, 1.0));
9910 }
9911 if let Some(val) = *sheen_color_factor {
9912 mat_mut.set_sheen_color_factor(val);
9913 }
9914 if let Some(val) = *sheen_roughness_factor {
9915 mat_mut.set_sheen_roughness_factor(val.clamp(0.0, 1.0));
9916 }
9917 if let Some(val) = *emissive_factor {
9918 mat_mut.set_emissive_factor(val);
9919 }
9920 if let Some(val) = *emissive_strength {
9921 mat_mut.set_emissive_strength(val.max(0.0));
9922 }
9923 if let Some(val) = *transmission_factor {
9924 mat_mut.set_transmission_factor(val.clamp(0.0, 1.0));
9925 }
9926 if let Some(val) = *ior {
9927 mat_mut.set_ior(val.clamp(1.0, 3.0));
9928 }
9929 mat_mut.to_legacy_pbr()
9930 };
9931 let mat_u32: u32 = mat_idx as u32;
9932 for obj_mut in self.get_mut_objects().iter_mut() {
9933 if obj_mut.try_get_principled_material_id() == Some(mat_u32) {
9934 obj_mut.set_material(updated_legacy);
9935 }
9936 }
9937 self.bump_world_revision();
9938 true
9939 }
9940 BlenderLiveDelta3D::MorphWeights { node_name, weights } => {
9941 let found_id: Option<u32> = self
9942 .get_scene_graph()
9943 .get_nodes()
9944 .iter()
9945 .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
9946 .map(|idx: usize| idx as u32);
9947 let Some(node_id) = found_id else {
9948 return false;
9949 };
9950 self.get_mut_scene_graph()
9951 .update_morph_weights(node_id, weights.as_slice());
9952 let _: usize = self.update_deformed_meshes();
9953 self.set_dynamic_bvh_dirty(true);
9954 self.bump_world_revision();
9955 true
9956 }
9957 BlenderLiveDelta3D::LightUpdate {
9958 light_index,
9959 color,
9960 intensity,
9961 position,
9962 direction,
9963 } => {
9964 let mut changed: bool = false;
9965 if let Some(point_mut) = self.get_mut_point_lights().get_mut(*light_index) {
9966 if let Some(col_arr) = *color {
9967 point_mut.set_color(Vec3::from_array(col_arr));
9968 }
9969 if let Some(int_val) = *intensity {
9970 point_mut.set_intensity(int_val.max(0.0));
9971 }
9972 if let Some(pos_arr) = *position {
9973 point_mut.set_position(Vec3::from_array(pos_arr));
9974 }
9975 changed = true;
9976 } else if let Some(area_mut) = self.get_mut_area_lights().get_mut(*light_index) {
9977 if let Some(col_arr) = *color {
9978 area_mut.set_color(Vec3::from_array(col_arr));
9979 }
9980 if let Some(int_val) = *intensity {
9981 area_mut.set_intensity(int_val.max(0.0));
9982 }
9983 if let Some(pos_arr) = *position {
9984 area_mut.set_position(Vec3::from_array(pos_arr));
9985 }
9986 if let Some(dir_arr) = *direction {
9987 area_mut.set_direction(Vec3::from_array(dir_arr).normalize());
9988 }
9989 changed = true;
9990 }
9991 if changed {
9992 self.bump_world_revision();
9993 }
9994 changed
9995 }
9996 BlenderLiveDelta3D::CameraUpdate {
9997 position,
9998 yaw,
9999 pitch,
10000 fov_deg,
10001 } => {
10002 let mut cam: Camera3D = self.get_camera();
10003 cam.set_position(Vec3::from_array(*position));
10004 cam.set_yaw(*yaw);
10005 cam.set_pitch(pitch.clamp(-1.4, 1.4));
10006 cam.set_fov_deg(fov_deg.clamp(12.0, 120.0));
10007 self.set_camera(cam);
10008 self.bump_world_revision();
10009 true
10010 }
10011 BlenderLiveDelta3D::CollectionVisibility {
10012 collection_name,
10013 visible,
10014 } => self.set_collection_visible(collection_name, *visible),
10015 BlenderLiveDelta3D::EnvironmentUpdate {
10016 rotation_y_rad,
10017 intensity,
10018 } => {
10019 let Self {
10020 environment_ibl, ..
10021 } = self;
10022 if let Some(ibl_mut) = environment_ibl.as_mut() {
10023 ibl_mut.set_rotation_y_rad(*rotation_y_rad);
10024 ibl_mut.set_intensity(intensity.max(0.0));
10025 self.bump_world_revision();
10026 true
10027 } else {
10028 false
10029 }
10030 }
10031 }
10032 }
10033
10034 pub fn apply_live_delta_json(&mut self, json_payload: &str) -> Result<bool, String> {
10045 let root: Value =
10046 from_str::<Value>(json_payload).map_err(|_| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
10047 let kind_str: &str = root
10048 .get(LIVE_KEY_KIND)
10049 .and_then(Value::as_str)
10050 .ok_or_else(|| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
10051 let delta: BlenderLiveDelta3D = match kind_str {
10052 LIVE_DELTA_KIND_TRANSFORM => BlenderLiveDelta3D::NodeTransform {
10053 node_name: root
10054 .get(LIVE_KEY_NODE_NAME)
10055 .and_then(Value::as_str)
10056 .unwrap_or_default()
10057 .to_string(),
10058 translation: Self::json_f32_array3(root.get(LIVE_KEY_TRANSLATION))
10059 .unwrap_or([0.0, 0.0, 0.0]),
10060 rotation: Self::json_f32_array4(root.get(LIVE_KEY_ROTATION))
10061 .unwrap_or([0.0, 0.0, 0.0, 1.0]),
10062 scale: Self::json_f32_array3(root.get(LIVE_KEY_SCALE)).unwrap_or([1.0, 1.0, 1.0]),
10063 blender_z_up: root
10064 .get(LIVE_KEY_BLENDER_Z_UP)
10065 .and_then(Value::as_bool)
10066 .unwrap_or(false),
10067 },
10068 LIVE_DELTA_KIND_MATERIAL => BlenderLiveDelta3D::MaterialParams {
10069 material_name: root
10070 .get(LIVE_KEY_MATERIAL_NAME)
10071 .and_then(Value::as_str)
10072 .unwrap_or_default()
10073 .to_string(),
10074 base_color_factor: Self::json_f32_array4(root.get(LIVE_KEY_BASE_COLOR)),
10075 metallic_factor: root
10076 .get(LIVE_KEY_METALLIC)
10077 .and_then(Value::as_f64)
10078 .map(|val: f64| val as f32),
10079 roughness_factor: root
10080 .get(LIVE_KEY_ROUGHNESS)
10081 .and_then(Value::as_f64)
10082 .map(|val: f64| val as f32),
10083 clearcoat_factor: root
10084 .get(LIVE_KEY_CLEARCOAT)
10085 .and_then(Value::as_f64)
10086 .map(|val: f64| val as f32),
10087 clearcoat_roughness_factor: root
10088 .get(LIVE_KEY_CLEARCOAT_ROUGHNESS)
10089 .and_then(Value::as_f64)
10090 .map(|val: f64| val as f32),
10091 sheen_color_factor: Self::json_f32_array3(root.get(LIVE_KEY_SHEEN_COLOR)),
10092 sheen_roughness_factor: root
10093 .get(LIVE_KEY_SHEEN_ROUGHNESS)
10094 .and_then(Value::as_f64)
10095 .map(|val: f64| val as f32),
10096 emissive_factor: Self::json_f32_array3(root.get(LIVE_KEY_EMISSIVE)),
10097 emissive_strength: root
10098 .get(LIVE_KEY_EMISSIVE_STRENGTH)
10099 .and_then(Value::as_f64)
10100 .map(|val: f64| val as f32),
10101 transmission_factor: root
10102 .get(LIVE_KEY_TRANSMISSION)
10103 .and_then(Value::as_f64)
10104 .map(|val: f64| val as f32),
10105 ior: root
10106 .get("ior")
10107 .and_then(Value::as_f64)
10108 .map(|val: f64| val as f32),
10109 },
10110 LIVE_DELTA_KIND_MORPH => {
10111 let parsed_weights: Vec<f32> = root
10112 .get(LIVE_KEY_WEIGHTS)
10113 .and_then(Value::as_array)
10114 .map(|items: &Vec<Value>| {
10115 items
10116 .iter()
10117 .filter_map(|elem: &Value| elem.as_f64().map(|val: f64| val as f32))
10118 .collect()
10119 })
10120 .unwrap_or_default();
10121 BlenderLiveDelta3D::MorphWeights {
10122 node_name: root
10123 .get(LIVE_KEY_NODE_NAME)
10124 .and_then(Value::as_str)
10125 .unwrap_or_default()
10126 .to_string(),
10127 weights: parsed_weights,
10128 }
10129 }
10130 LIVE_DELTA_KIND_LIGHT => BlenderLiveDelta3D::LightUpdate {
10131 light_index: root
10132 .get(LIVE_KEY_LIGHT_INDEX)
10133 .and_then(Value::as_u64)
10134 .unwrap_or(0) as usize,
10135 color: Self::json_f32_array3(root.get(LIVE_KEY_COLOR)),
10136 intensity: root
10137 .get(LIVE_KEY_INTENSITY)
10138 .and_then(Value::as_f64)
10139 .map(|val: f64| val as f32),
10140 position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION)),
10141 direction: Self::json_f32_array3(root.get(LIVE_KEY_DIRECTION)),
10142 },
10143 LIVE_DELTA_KIND_CAMERA => BlenderLiveDelta3D::CameraUpdate {
10144 position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION))
10145 .unwrap_or([0.0, 2.0, 6.0]),
10146 yaw: root
10147 .get("yaw")
10148 .and_then(Value::as_f64)
10149 .map_or(0.0, |val: f64| val as f32),
10150 pitch: root
10151 .get(LIVE_KEY_PITCH)
10152 .and_then(Value::as_f64)
10153 .map_or(0.0, |val: f64| val as f32),
10154 fov_deg: root
10155 .get(LIVE_KEY_FOV_DEG)
10156 .and_then(Value::as_f64)
10157 .map_or(60.0, |val: f64| val as f32),
10158 },
10159 LIVE_DELTA_KIND_COLLECTION => BlenderLiveDelta3D::CollectionVisibility {
10160 collection_name: root
10161 .get(LIVE_KEY_COLLECTION_NAME)
10162 .and_then(Value::as_str)
10163 .unwrap_or_default()
10164 .to_string(),
10165 visible: root
10166 .get(LIVE_KEY_VISIBLE)
10167 .and_then(Value::as_bool)
10168 .unwrap_or(true),
10169 },
10170 LIVE_DELTA_KIND_ENVIRONMENT => BlenderLiveDelta3D::EnvironmentUpdate {
10171 rotation_y_rad: root
10172 .get(LIVE_KEY_ROTATION_Y_RAD)
10173 .and_then(Value::as_f64)
10174 .map_or(0.0, |val: f64| val as f32),
10175 intensity: root
10176 .get(LIVE_KEY_INTENSITY)
10177 .and_then(Value::as_f64)
10178 .map_or(1.0, |val: f64| val as f32),
10179 },
10180 _ => return Err(ERR_LIVE_DELTA_UNKNOWN_KIND.to_string()),
10181 };
10182 Ok(self.apply_live_delta(&delta))
10183 }
10184
10185 fn sync_objects_from_scene_graph(&mut self) -> usize {
10191 let Self {
10192 mesh_library,
10193 objects,
10194 scene_graph,
10195 scene_cameras,
10196 node_object_map,
10197 deformed_meshes,
10198 ..
10199 } = self;
10200 let nodes: &[SceneNode3D] = scene_graph.get_nodes().as_slice();
10201 let mut synced_count: usize = 0;
10202 for (node_idx, obj_slot) in node_object_map.iter().enumerate() {
10203 let Some(obj_idx) = *obj_slot else {
10204 continue;
10205 };
10206 if node_idx >= nodes.len() || obj_idx >= objects.len() {
10207 continue;
10208 }
10209 let world_tr: Transform3D =
10210 Transform3D::from_matrix(nodes[node_idx].get_world_matrix());
10211 if objects[obj_idx].get_transform() != world_tr {
10212 objects[obj_idx].set_transform(world_tr);
10213 let local_bounds: AxisAlignedBox3D = deformed_meshes
10214 .get(obj_idx)
10215 .and_then(Option::as_ref)
10216 .map(Mesh3D::get_bounds)
10217 .or_else(|| {
10218 mesh_library
10219 .get(objects[obj_idx].get_mesh_id())
10220 .and_then(|chain: &MeshLodChain| chain.get_levels().first())
10221 .map(Mesh3D::get_bounds)
10222 })
10223 .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
10224 objects[obj_idx].set_world_bounds(world_tr.transform_bounds(local_bounds));
10225 synced_count += 1;
10226 }
10227 }
10228 for cam_mut in scene_cameras.iter_mut() {
10229 if let Some(node_id) = cam_mut.try_get_node_id()
10230 && let Some(node_ref) = nodes.get(node_id as usize)
10231 {
10232 let (pos_val, rot_val, _scale_val): (Vec3, Quat, Vec3) =
10233 node_ref.get_world_matrix().decompose_trs();
10234 cam_mut.set_position(pos_val);
10235 cam_mut.set_rotation(rot_val);
10236 synced_count += 1;
10237 }
10238 }
10239 synced_count
10240 }
10241
10242 fn rebase_material_textures(material: &mut PrincipledMaterial3D, texture_base: u32) {
10249 if texture_base == 0 {
10250 return;
10251 }
10252 let shift_slot: fn(Option<TextureSlot3D>, u32) -> Option<TextureSlot3D> =
10253 |slot_opt: Option<TextureSlot3D>, base_val: u32| -> Option<TextureSlot3D> {
10254 slot_opt.map(|mut slot: TextureSlot3D| {
10255 slot.set_texture_index(slot.get_texture_index().saturating_add(base_val));
10256 slot
10257 })
10258 };
10259 material.set_base_color_texture(shift_slot(
10260 material.try_get_base_color_texture(),
10261 texture_base,
10262 ));
10263 material.set_metallic_roughness_texture(shift_slot(
10264 material.try_get_metallic_roughness_texture(),
10265 texture_base,
10266 ));
10267 material.set_normal_texture(shift_slot(material.try_get_normal_texture(), texture_base));
10268 material.set_occlusion_texture(shift_slot(
10269 material.try_get_occlusion_texture(),
10270 texture_base,
10271 ));
10272 material.set_emissive_texture(shift_slot(
10273 material.try_get_emissive_texture(),
10274 texture_base,
10275 ));
10276 material.set_specular_texture(shift_slot(
10277 material.try_get_specular_texture(),
10278 texture_base,
10279 ));
10280 material.set_specular_color_texture(shift_slot(
10281 material.try_get_specular_color_texture(),
10282 texture_base,
10283 ));
10284 material.set_clearcoat_texture(shift_slot(
10285 material.try_get_clearcoat_texture(),
10286 texture_base,
10287 ));
10288 material.set_clearcoat_roughness_texture(shift_slot(
10289 material.try_get_clearcoat_roughness_texture(),
10290 texture_base,
10291 ));
10292 material.set_clearcoat_normal_texture(shift_slot(
10293 material.try_get_clearcoat_normal_texture(),
10294 texture_base,
10295 ));
10296 material.set_transmission_texture(shift_slot(
10297 material.try_get_transmission_texture(),
10298 texture_base,
10299 ));
10300 material.set_sheen_color_texture(shift_slot(
10301 material.try_get_sheen_color_texture(),
10302 texture_base,
10303 ));
10304 material.set_sheen_roughness_texture(shift_slot(
10305 material.try_get_sheen_roughness_texture(),
10306 texture_base,
10307 ));
10308 }
10309
10310 #[must_use]
10320 fn json_f32_array3(val: Option<&Value>) -> Option<[f32; 3]> {
10321 let arr: &Vec<Value> = val?.as_array()?;
10322 if arr.len() < 3 {
10323 return None;
10324 }
10325 Some([
10326 arr[0].as_f64()? as f32,
10327 arr[1].as_f64()? as f32,
10328 arr[2].as_f64()? as f32,
10329 ])
10330 }
10331
10332 #[must_use]
10342 fn json_f32_array4(val: Option<&Value>) -> Option<[f32; 4]> {
10343 let arr: &Vec<Value> = val?.as_array()?;
10344 if arr.len() < 4 {
10345 return None;
10346 }
10347 Some([
10348 arr[0].as_f64()? as f32,
10349 arr[1].as_f64()? as f32,
10350 arr[2].as_f64()? as f32,
10351 arr[3].as_f64()? as f32,
10352 ])
10353 }
10354
10355 #[must_use]
10361 pub fn allocate_gpu_mesh_revision() -> u64 {
10362 NEXT_GPU_WORLD3D_MESH_REVISION
10363 .fetch_add(1, Ordering::Relaxed)
10364 .max(1)
10365 }
10366
10367 fn append_unit_particle_octahedron(vertices: &mut Vec<GpuWorld3dVertex>) -> (u32, u32) {
10377 let start_idx: u32 = vertices.len() as u32;
10378 let top: [f32; 3] = [0.0, 1.0, 0.0];
10379 let bot: [f32; 3] = [0.0, -1.0, 0.0];
10380 let pos_x: [f32; 3] = [1.0, 0.0, 0.0];
10381 let neg_x: [f32; 3] = [-1.0, 0.0, 0.0];
10382 let pos_z: [f32; 3] = [0.0, 0.0, 1.0];
10383 let neg_z: [f32; 3] = [0.0, 0.0, -1.0];
10384 let faces: [[[f32; 3]; 3]; 8] = [
10385 [top, pos_z, pos_x],
10386 [top, pos_x, neg_z],
10387 [top, neg_z, neg_x],
10388 [top, neg_x, pos_z],
10389 [bot, pos_x, pos_z],
10390 [bot, neg_z, pos_x],
10391 [bot, neg_x, neg_z],
10392 [bot, pos_z, neg_x],
10393 ];
10394 vertices.reserve(24);
10395 for tri in faces.iter() {
10396 for corner in tri.iter() {
10397 vertices.push(GpuWorld3dVertex::new(
10398 [corner[0], corner[1], corner[2], 1.0],
10399 [corner[0], corner[1], corner[2], 0.0],
10400 [1.0, 1.0, 1.0, 0.0],
10401 ));
10402 }
10403 }
10404 let vert_count: u32 = (vertices.len() as u32).saturating_sub(start_idx);
10405 (start_idx, vert_count)
10406 }
10407
10408 #[must_use]
10419 pub fn build_gpu_mesh_buffer(
10420 &self,
10421 revision: u64,
10422 ) -> (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) {
10423 let mut vertices: Vec<GpuWorld3dVertex> = Vec::new();
10424 let mut ranges: Vec<(u32, u32)> = Vec::with_capacity(self.get_mesh_library().len() + 1);
10425 for chain in self.get_mesh_library() {
10426 let start_idx: u32 = vertices.len() as u32;
10427 if let Some(mesh) = chain.get_levels().first() {
10428 let mesh_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
10429 let tri_mats: &[u16] = mesh.get_tri_materials().as_slice();
10430 let sub_mats: &[PbrMaterial] = mesh.get_sub_materials().as_slice();
10431 vertices.reserve(mesh.get_indices().len() * 3);
10432 for (tri_idx, &[i0, i1, i2]) in mesh.get_indices().iter().enumerate() {
10433 let (Some(v0), Some(v1), Some(v2)) = (
10434 mesh_verts.get(i0 as usize),
10435 mesh_verts.get(i1 as usize),
10436 mesh_verts.get(i2 as usize),
10437 ) else {
10438 continue;
10439 };
10440 let mat_slot: usize = tri_mats.get(tri_idx).copied().unwrap_or(0) as usize;
10441 let color_submat: [f32; 4] = if mat_slot > 0
10442 && let Some(sub_mat) = sub_mats.get(mat_slot - 1)
10443 {
10444 let base_c: Vec3 = sub_mat.get_base_color();
10445 let em_c: Vec3 = sub_mat.get_emissive();
10446 if em_c.length_sq() > 0.01 {
10447 [
10448 base_c.get_x() + em_c.get_x() * 1.4,
10449 base_c.get_y() + em_c.get_y() * 1.4,
10450 base_c.get_z() + em_c.get_z() * 1.4,
10451 2.0,
10452 ]
10453 } else {
10454 [base_c.get_x(), base_c.get_y(), base_c.get_z(), 1.0]
10455 }
10456 } else {
10457 [1.0, 1.0, 1.0, 0.0]
10458 };
10459 for vert in [v0, v1, v2] {
10460 let pos: Vec3 = vert.get_position();
10461 let nrm: Vec3 = vert.get_normal();
10462 vertices.push(GpuWorld3dVertex::new(
10463 [pos.get_x(), pos.get_y(), pos.get_z(), 1.0],
10464 [nrm.get_x(), nrm.get_y(), nrm.get_z(), 0.0],
10465 color_submat,
10466 ));
10467 }
10468 }
10469 }
10470 let vert_count: u32 = (vertices.len() as u32).saturating_sub(start_idx);
10471 ranges.push((start_idx, vert_count));
10472 }
10473 let particle_range: (u32, u32) = Self::append_unit_particle_octahedron(&mut vertices);
10474 ranges.push(particle_range);
10475 (
10476 Arc::new(GpuWorld3dMeshBuffer { revision, vertices }),
10477 ranges,
10478 )
10479 }
10480
10481 fn populate_gpu_scene_pass_with_scratch(
10493 &self,
10494 snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
10495 alpha: f32,
10496 viewport: (u32, u32),
10497 quality: &RenderQualityConfig,
10498 mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
10499 buffers: (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass),
10500 ) {
10501 let (scratch, out): (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass) = buffers;
10502 let (target_width, target_height): (u32, u32) = viewport;
10503 let (mesh_buffer, mesh_ranges): (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]) = mesh_cache;
10504 let blend_alpha: f32 = alpha.clamp(0.0, 1.0);
10505 let prev_snap: &World3DSnapshot = snapshots.get_prev_state();
10506 let curr_snap: &World3DSnapshot = snapshots.get_curr_state();
10507 let mut interp_cam: Camera3D = if curr_snap.get_camera_cut() {
10508 curr_snap.get_camera()
10509 } else {
10510 prev_snap
10511 .get_camera()
10512 .lerp(curr_snap.get_camera(), blend_alpha)
10513 };
10514 let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
10515 if aspect > 3.5 {
10516 let pull_back: f32 = ((aspect - 3.5) * 0.42).min(1.6);
10517 let shifted_pos: Vec3 = interp_cam
10518 .get_position()
10519 .sub(interp_cam.forward().scale(pull_back));
10520 interp_cam.set_position(shifted_pos);
10521 }
10522 let view_proj_mat: Mat4 = if let Some(cam_idx) = self.active_scene_camera_index()
10523 && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
10524 {
10525 scene_cam.view_projection(aspect)
10526 } else {
10527 interp_cam.view_projection(aspect)
10528 };
10529 let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
10530 let cam_pos: Vec3 = interp_cam.get_position();
10531 let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
10532 let frustum_on: bool = quality.get_frustum_culling();
10533 let obj_len: usize = self.get_objects().len();
10534 if scratch.dynamic_pose_epochs.len() < obj_len {
10535 scratch.dynamic_pose_epochs.resize(obj_len, 0);
10536 scratch
10537 .dynamic_pose_transforms
10538 .resize(obj_len, Transform3D::default());
10539 }
10540 let next_epoch: u32 = scratch.current_epoch.wrapping_add(1);
10541 let active_epoch: u32 = if next_epoch == 0 {
10542 scratch.dynamic_pose_epochs.fill(0);
10543 1
10544 } else {
10545 next_epoch
10546 };
10547 scratch.current_epoch = active_epoch;
10548 let prev_objs: &[ObjectPose3D] = prev_snap.get_objects().as_slice();
10549 let next_objs: &[ObjectPose3D] = curr_snap.get_objects().as_slice();
10550 for (slot_idx, curr) in next_objs.iter().copied().enumerate() {
10551 let obj_idx: usize = curr.get_object_index();
10552 if obj_idx >= obj_len {
10553 continue;
10554 }
10555 let mut blended_tr: Transform3D = curr.get_transform();
10556 if curr.get_visible()
10557 && let Some(prev) = prev_objs.get(slot_idx).copied()
10558 {
10559 let continuous: bool = prev.get_visible()
10560 && prev.get_object_index() == obj_idx
10561 && prev.get_teleport_epoch() == curr.get_teleport_epoch();
10562 if continuous {
10563 blended_tr = prev
10564 .get_transform()
10565 .lerp_shortest_angle(curr.get_transform(), blend_alpha);
10566 }
10567 }
10568 scratch.dynamic_pose_epochs[obj_idx] = active_epoch;
10569 scratch.dynamic_pose_transforms[obj_idx] = blended_tr;
10570 }
10571 let mesh_len: usize = mesh_ranges.len();
10572 if scratch.mesh_counts.len() < mesh_len {
10573 scratch.mesh_counts.resize(mesh_len, 0);
10574 scratch.mesh_cursors.resize(mesh_len, 0);
10575 }
10576 scratch.mesh_counts[..mesh_len].fill(0);
10577 scratch.visible_scratch.clear();
10578 let principled_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
10579 let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
10580 for (obj_idx, obj) in self.get_objects().iter().enumerate() {
10581 if !self.is_object_visible(obj_idx) {
10582 continue;
10583 }
10584 let mesh_id: usize = obj.get_mesh_id();
10585 let Some(&(_, vert_count)) = mesh_ranges.get(mesh_id) else {
10586 continue;
10587 };
10588 if vert_count == 0 {
10589 continue;
10590 }
10591 let mut tr: Transform3D = obj.get_transform();
10592 let mut world_bounds: AxisAlignedBox3D = obj.get_world_bounds();
10593 if scratch.dynamic_pose_epochs[obj_idx] == active_epoch {
10594 tr = scratch.dynamic_pose_transforms[obj_idx];
10595 if let Some(chain) = mesh_lib.get(mesh_id)
10596 && let Some(mesh0) = chain.get_levels().first()
10597 {
10598 world_bounds = tr.transform_bounds(mesh0.get_bounds());
10599 }
10600 }
10601 let dist_sq: f32 = world_bounds.center().sub(cam_pos).length_sq();
10602 let radius: f32 = world_bounds.get_max().sub(world_bounds.get_min()).length() * 0.5;
10603 if dist_sq > draw_dist_sq + radius * radius * 4.0 {
10604 continue;
10605 }
10606 if frustum_on && !frustum.intersects_bounds(&world_bounds) {
10607 continue;
10608 }
10609 let mat: PbrMaterial = obj.get_material();
10610 let (albedo, metallic, roughness, emissive): (Vec3, f32, f32, Vec3) = if let Some(pm_id) =
10611 obj.try_get_principled_material_id()
10612 && let Some(pm) = principled_mats.get(pm_id as usize)
10613 {
10614 let bc: [f32; 4] = pm.get_base_color_factor();
10615 let em: [f32; 3] = pm.get_emissive_factor();
10616 let em_str: f32 = pm.get_emissive_strength();
10617 (
10618 Vec3::new(bc[0], bc[1], bc[2]),
10619 pm.get_metallic_factor(),
10620 pm.get_roughness_factor(),
10621 Vec3::new(em[0] * em_str, em[1] * em_str, em[2] * em_str),
10622 )
10623 } else {
10624 (
10625 mat.get_base_color(),
10626 mat.get_metallic(),
10627 mat.get_roughness(),
10628 mat.get_emissive(),
10629 )
10630 };
10631 let mut model_elems: [f32; 16] = tr.to_mat4().get_elements();
10632 model_elems[15] = match mat.get_surface_detail() {
10633 SurfaceDetailMode::None => 0.0,
10634 SurfaceDetailMode::RoadSurface => 1.0,
10635 SurfaceDetailMode::ArchitecturalFacade => 2.0,
10636 SurfaceDetailMode::OceanWater => 3.0,
10637 SurfaceDetailMode::MasonryBrick => 4.0,
10638 SurfaceDetailMode::StoneCobble => 5.0,
10639 SurfaceDetailMode::OrganicFoliage => 6.0,
10640 SurfaceDetailMode::VolumetricCloud => 7.0,
10641 SurfaceDetailMode::RiverWater => 8.0,
10642 };
10643 scratch.mesh_counts[mesh_id] = scratch.mesh_counts[mesh_id].saturating_add(1);
10644 scratch.visible_scratch.push((
10645 mesh_id as u32,
10646 GpuWorld3dInstance::new(
10647 model_elems,
10648 [
10649 albedo.get_x(),
10650 albedo.get_y(),
10651 albedo.get_z(),
10652 metallic.clamp(0.0, 1.0),
10653 ],
10654 [
10655 emissive.get_x(),
10656 emissive.get_y(),
10657 emissive.get_z(),
10658 roughness.clamp(0.05, 1.0),
10659 ],
10660 ),
10661 ));
10662 }
10663 let total_instances: usize = scratch.visible_scratch.len();
10664 out.draw_batches.clear();
10665 let mut cursor: u32 = 0;
10666 for (mesh_id, &(vertex_start, vertex_count)) in mesh_ranges.iter().enumerate() {
10667 let count: u32 = scratch.mesh_counts[mesh_id];
10668 scratch.mesh_cursors[mesh_id] = cursor;
10669 if count == 0 {
10670 continue;
10671 }
10672 out.draw_batches.push(GpuWorld3dMeshRange::new(
10673 vertex_start,
10674 vertex_count,
10675 cursor,
10676 count,
10677 ));
10678 cursor = cursor.saturating_add(count);
10679 }
10680 out.instances
10681 .resize(total_instances, GpuWorld3dInstance::default());
10682 for &(mesh_id_u32, inst) in scratch.visible_scratch.iter() {
10683 let mesh_id: usize = mesh_id_u32 as usize;
10684 let dst_idx: usize = scratch.mesh_cursors[mesh_id] as usize;
10685 scratch.mesh_cursors[mesh_id] = scratch.mesh_cursors[mesh_id].saturating_add(1);
10686 out.instances[dst_idx] = inst;
10687 }
10688 let particle_mesh_idx: usize = mesh_lib.len();
10689 if self.get_niagara().get_active_count() > 0
10690 && let Some(&(particle_vert_start, particle_vert_count)) =
10691 mesh_ranges.get(particle_mesh_idx)
10692 && particle_vert_count > 0
10693 {
10694 let particle_inst_start: u32 = out.instances.len() as u32;
10695 let active_frustum: Option<&Frustum3D> = if frustum_on { Some(&frustum) } else { None };
10696 let particle_inst_count: u32 = self.get_niagara().append_gpu_world3d_instances(
10697 cam_pos,
10698 draw_dist_sq,
10699 active_frustum,
10700 &mut out.instances,
10701 );
10702 if particle_inst_count > 0 {
10703 out.draw_batches.push(GpuWorld3dMeshRange::new(
10704 particle_vert_start,
10705 particle_vert_count,
10706 particle_inst_start,
10707 particle_inst_count,
10708 ));
10709 }
10710 }
10711 let sun: DirectionalLight3D = self.get_sun();
10712 let sun_dir: Vec3 = sun.get_direction().normalize();
10713 let sun_col: Vec3 = sun.get_color();
10714 let sky_hor: Vec3 = sun.get_sky_horizon();
10715 let sky_zen: Vec3 = sun.get_sky_zenith();
10716 let fog_density: f32 = self.effective_fog_density(quality.get_volumetric_fog());
10717 let (ambient_strength, exposure_val): (f32, f32) = {
10718 let Self {
10719 weather_ambient_strength,
10720 weather_exposure,
10721 ..
10722 } = self;
10723 (*weather_ambient_strength, *weather_exposure)
10724 };
10725 out.target_width = target_width;
10726 out.target_height = target_height;
10727 out.view_proj = view_proj_mat.get_elements();
10728 out.camera_pos = [
10729 cam_pos.get_x(),
10730 cam_pos.get_y(),
10731 cam_pos.get_z(),
10732 exposure_val,
10733 ];
10734 out.sun_dir_fog = [
10735 sun_dir.get_x(),
10736 sun_dir.get_y(),
10737 sun_dir.get_z(),
10738 fog_density,
10739 ];
10740 out.sun_color_ambient = [
10741 sun_col.get_x(),
10742 sun_col.get_y(),
10743 sun_col.get_z(),
10744 ambient_strength,
10745 ];
10746 let anim_time: f32 =
10747 (sun.get_time_of_day() + self.get_world_time_secs()).rem_euclid(3600.0);
10748 out.sky_horizon_tod = [sky_hor.get_x(), sky_hor.get_y(), sky_hor.get_z(), anim_time];
10749 out.sky_zenith_aspect = [sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), aspect];
10750 out.mesh_buffer = Arc::clone(mesh_buffer);
10751 }
10752
10753 pub fn build_gpu_scene_pass_into(
10765 &mut self,
10766 snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
10767 alpha: f32,
10768 viewport: (u32, u32),
10769 quality: &RenderQualityConfig,
10770 mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
10771 out: &mut GpuWorld3dScenePass,
10772 ) {
10773 let mut scratch: World3dGpuPassScratch = {
10774 let Self {
10775 gpu_pass_scratch, ..
10776 } = self;
10777 take(gpu_pass_scratch)
10778 };
10779 self.populate_gpu_scene_pass_with_scratch(
10780 snapshots,
10781 alpha,
10782 viewport,
10783 quality,
10784 mesh_cache,
10785 (&mut scratch, out),
10786 );
10787 let Self {
10788 gpu_pass_scratch, ..
10789 } = self;
10790 *gpu_pass_scratch = scratch;
10791 }
10792
10793 fn sync_pbr_quantized_mesh_cache(
10800 mesh_library: &[MeshLodChain],
10801 scratch: &mut World3dPbrPassScratch,
10802 ) {
10803 let mut total_verts: usize = 0;
10804 let mut total_indices: usize = 0;
10805 let mut any_skinned: bool = false;
10806 let mut any_morphed: bool = false;
10807 for chain in mesh_library.iter() {
10808 for mesh in chain.get_levels().iter().take(4) {
10809 total_verts = total_verts.saturating_add(mesh.get_vertices().len());
10810 total_indices =
10811 total_indices.saturating_add(mesh.get_indices().len().saturating_mul(3));
10812 if !mesh.get_skin_influences().is_empty() {
10813 any_skinned = true;
10814 }
10815 if !mesh.get_morph_targets().is_empty() {
10816 any_morphed = true;
10817 }
10818 }
10819 }
10820 let signature: (usize, usize, usize) = (mesh_library.len(), total_verts, total_indices);
10821 if scratch.cached_signature == signature && scratch.cached_mesh_buffer.get_revision() > 0 {
10822 return;
10823 }
10824 let next_rev: u64 = NEXT_GPU_PBR_MESH_REVISION
10825 .fetch_add(1, Ordering::Relaxed)
10826 .max(1);
10827 let mut vertices: Vec<QuantizedVertex3D> = Vec::with_capacity(total_verts);
10828 let mut indices: Vec<u32> = Vec::with_capacity(total_indices);
10829 let mut skin_vertices: Vec<QuantizedSkinVertex3D> = if any_skinned {
10830 Vec::with_capacity(total_verts)
10831 } else {
10832 Vec::new()
10833 };
10834 let mut uv1_f16: Vec<[u16; 2]> = Vec::with_capacity(total_verts);
10835 let mut mesh_bounds_min: Vec<[f32; 4]> = Vec::with_capacity(mesh_library.len());
10836 let mut mesh_bounds_extent: Vec<[f32; 4]> = Vec::with_capacity(mesh_library.len());
10837 let mut morph_deltas: Vec<[f32; 4]> = if any_morphed && total_verts > 0 {
10838 vec![[0.0; 4]; total_verts.saturating_mul(4)]
10839 } else {
10840 Vec::new()
10841 };
10842 scratch.cached_lod_ranges.clear();
10843 scratch.cached_lod_ranges.reserve(mesh_library.len());
10844 let mut vert_tags: Vec<u8> = Vec::new();
10845 for chain in mesh_library.iter() {
10846 let levels: &[Mesh3D] = chain.get_levels().as_slice();
10847 let mut lod_ranges: [CachedPbrLodRange; 4] = [CachedPbrLodRange::default(); 4];
10848 let mut base_min: [f32; 4] = [0.0; 4];
10849 let mut base_ext: [f32; 4] = [1.0, 1.0, 1.0, 0.0];
10850 for (lod_idx, mesh) in levels.iter().take(4).enumerate() {
10851 let m_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
10852 let m_tris: &[[u32; 3]] = mesh.get_indices().as_slice();
10853 let mb: AxisAlignedBox3D = mesh.get_bounds();
10854 let bmin: Vec3 = mb.get_min();
10855 let bext_raw: Vec3 = mb.get_max().sub(bmin);
10856 let bext: Vec3 = Vec3::new(
10857 bext_raw.get_x().max(1e-4),
10858 bext_raw.get_y().max(1e-4),
10859 bext_raw.get_z().max(1e-4),
10860 );
10861 let min_arr: [f32; 4] = [bmin.get_x(), bmin.get_y(), bmin.get_z(), 0.0];
10862 let ext_arr: [f32; 4] = [bext.get_x(), bext.get_y(), bext.get_z(), 0.0];
10863 if lod_idx == 0 {
10864 base_min = min_arr;
10865 base_ext = ext_arr;
10866 }
10867 vert_tags.clear();
10868 vert_tags.resize(m_verts.len(), 0);
10869 for (cluster_idx, meshlet) in mesh.get_meshlets().iter().enumerate() {
10870 let tag: u8 = ((cluster_idx % 255) + 1) as u8;
10871 let t_start: usize = meshlet.get_first_tri() as usize;
10872 let t_end: usize = t_start
10873 .saturating_add(meshlet.get_tri_count() as usize)
10874 .min(m_tris.len());
10875 for tri in &m_tris[t_start..t_end] {
10876 for &vi in tri.iter() {
10877 if let Some(slot) = vert_tags.get_mut(vi as usize) {
10878 *slot = tag;
10879 }
10880 }
10881 }
10882 }
10883 let base_vertex: u32 = vertices.len() as u32;
10884 let index_start: u32 = indices.len() as u32;
10885 let skins: &[MeshSkinInfluence3D] = mesh.get_skin_influences().as_slice();
10886 for (vi, vert) in m_verts.iter().enumerate() {
10887 let tag: u8 = vert_tags.get(vi).copied().unwrap_or(0);
10888 vertices.push(quantize_vertex_3d(vert, bmin, bext, tag));
10889 let uv1: [f32; 2] = vert.get_uv1();
10890 uv1_f16.push([encode_f32_to_f16(uv1[0]), encode_f32_to_f16(uv1[1])]);
10891 if any_skinned {
10892 let qskin: QuantizedSkinVertex3D = skins
10893 .get(vi)
10894 .map_or_else(QuantizedSkinVertex3D::default, quantize_skin_vertex_3d);
10895 skin_vertices.push(qskin);
10896 }
10897 }
10898 let has_morphs: bool = !mesh.get_morph_targets().is_empty();
10899 if any_morphed && has_morphs && total_verts > 0 {
10900 for (t_idx, target) in mesh.get_morph_targets().iter().take(4).enumerate() {
10901 let dpos: &[[f32; 3]] = target.get_delta_positions().as_slice();
10902 let target_base: usize = t_idx
10903 .saturating_mul(total_verts)
10904 .saturating_add(base_vertex as usize);
10905 for (vi, delta) in dpos.iter().take(m_verts.len()).enumerate() {
10906 if let Some(dst) = morph_deltas.get_mut(target_base + vi) {
10907 *dst = [delta[0], delta[1], delta[2], 0.0];
10908 }
10909 }
10910 }
10911 }
10912 for tri in m_tris.iter() {
10913 indices.push(base_vertex.saturating_add(tri[0]));
10914 indices.push(base_vertex.saturating_add(tri[1]));
10915 indices.push(base_vertex.saturating_add(tri[2]));
10916 }
10917 let index_count: u32 = (indices.len() as u32).saturating_sub(index_start);
10918 lod_ranges[lod_idx] = CachedPbrLodRange {
10919 index_start,
10920 index_count,
10921 bounds_min: min_arr,
10922 bounds_extent: ext_arr,
10923 has_morphs,
10924 };
10925 }
10926 let avail: usize = levels.len().min(4);
10927 if avail > 0 && avail < 4 {
10928 let fallback_lod: CachedPbrLodRange = lod_ranges[avail - 1];
10929 for fill_slot in lod_ranges.iter_mut().skip(avail) {
10930 *fill_slot = fallback_lod;
10931 }
10932 }
10933 mesh_bounds_min.push(base_min);
10934 mesh_bounds_extent.push(base_ext);
10935 scratch.cached_lod_ranges.push(lod_ranges);
10936 }
10937 scratch.cached_signature = signature;
10938 scratch.cached_mesh_buffer = Arc::new(GpuPbrMeshBuffer {
10939 revision: next_rev,
10940 vertices,
10941 indices,
10942 skin_vertices,
10943 morph_deltas,
10944 uv1_f16,
10945 mesh_bounds_min,
10946 mesh_bounds_extent,
10947 });
10948 }
10949
10950 fn resolve_fallback_gpu_material(
10962 mat: PbrMaterial,
10963 fallback_base: usize,
10964 materials: &mut Vec<GpuMaterialData3D>,
10965 ) -> u32 {
10966 let albedo: Vec3 = mat.get_base_color();
10967 let emissive: Vec3 = mat.get_emissive();
10968 let candidate: GpuMaterialData3D = GpuMaterialData3D {
10969 base_color_factor: [albedo.get_x(), albedo.get_y(), albedo.get_z(), 1.0],
10970 emissive_alpha_cutoff: [emissive.get_x(), emissive.get_y(), emissive.get_z(), 0.5],
10971 pbr_ior_specular: [
10972 mat.get_metallic().clamp(0.0, 1.0),
10973 mat.get_roughness().clamp(0.04, 1.0),
10974 PRINCIPLED_DEFAULT_IOR,
10975 1.0,
10976 ],
10977 specular_color_clearcoat: [1.0, 1.0, 1.0, 0.0],
10978 clearcoat_normal_occ_trans: [0.1, 1.0, 1.0, 0.0],
10979 volume_attenuation: [1.0, 1.0, 1.0, 0.0],
10980 sheen_color_roughness: [0.0, 0.0, 0.0, 0.5],
10981 tex_indices_a: [GPU_MATERIAL_NO_TEXTURE; 4],
10982 tex_indices_b: [GPU_MATERIAL_NO_TEXTURE; 4],
10983 flags_volume: [
10984 0,
10985 f32::INFINITY.to_bits(),
10986 GPU_MATERIAL_NO_TEXTURE,
10987 GPU_MATERIAL_NO_TEXTURE,
10988 ],
10989 };
10990 if let Some(rel_idx) = materials[fallback_base..]
10991 .iter()
10992 .position(|existing: &GpuMaterialData3D| *existing == candidate)
10993 {
10994 return (fallback_base + rel_idx) as u32;
10995 }
10996 let slot: u32 = materials.len() as u32;
10997 materials.push(candidate);
10998 slot
10999 }
11000
11001 fn populate_gpu_pbr_scene_pass_with_scratch(
11013 &self,
11014 viewport: (u32, u32),
11015 quality: &RenderQualityConfig,
11016 belt: &mut GpuUploadBelt,
11017 scratch: &mut World3dPbrPassScratch,
11018 skin_scratch: &mut SkinPaletteScratch3D,
11019 out: &mut GpuPbrScenePass,
11020 ) {
11021 belt.begin_frame();
11022 let prev_vp: [f32; 16] = out.get_view_proj();
11023 out.clear_frame_payloads();
11024 let (target_width, target_height): (u32, u32) = viewport;
11025 let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
11026 let (view_proj_mat, cam_pos, cam_fov_deg, cam_far): (Mat4, Vec3, f32, f32) =
11027 if let Some(cam_idx) = self.active_scene_camera_index()
11028 && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
11029 {
11030 let proj_cam: Camera3D = scene_cam.to_camera3d();
11031 (
11032 scene_cam.view_projection(aspect),
11033 scene_cam.get_position(),
11034 proj_cam.get_fov_deg(),
11035 proj_cam.get_far(),
11036 )
11037 } else {
11038 let cam: Camera3D = self.get_camera();
11039 (
11040 cam.view_projection(aspect),
11041 cam.get_position(),
11042 cam.get_fov_deg(),
11043 cam.get_far(),
11044 )
11045 };
11046 let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
11047 Self::sync_pbr_quantized_mesh_cache(mesh_lib, scratch);
11048 let src_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
11049 let dst_mats: &mut Vec<GpuMaterialData3D> = out.get_mut_materials();
11050 if dst_mats.capacity() < src_mats.len() {
11051 dst_mats.reserve(src_mats.len() - dst_mats.len());
11052 }
11053 for mat_ref in src_mats.iter() {
11054 dst_mats.push(mat_ref.to_gpu_data());
11055 }
11056 let fallback_mat_base: usize = dst_mats.len();
11057 let dst_lights: &mut Vec<GpuPackedLocalLight> = out.get_mut_local_lights();
11058 for pl in self.get_point_lights().iter() {
11059 if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
11060 break;
11061 }
11062 let p: Vec3 = pl.get_position();
11063 let c: Vec3 = pl.get_color();
11064 dst_lights.push(GpuPackedLocalLight::new(
11065 [p.get_x(), p.get_y(), p.get_z(), pl.get_radius().max(0.1)],
11066 [c.get_x(), c.get_y(), c.get_z(), pl.get_intensity().max(0.0)],
11067 [0.0, -1.0, 0.0, 0.0],
11068 [-1.0, -1.0, 0.0, 0.0],
11069 ));
11070 }
11071 for sl in self.get_spot_lights().iter() {
11072 if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
11073 break;
11074 }
11075 let p: Vec3 = sl.get_position();
11076 let c: Vec3 = sl.get_color();
11077 let d: Vec3 = sl.get_direction().normalize();
11078 dst_lights.push(GpuPackedLocalLight::new(
11079 [p.get_x(), p.get_y(), p.get_z(), sl.get_range().max(0.1)],
11080 [c.get_x(), c.get_y(), c.get_z(), sl.get_intensity().max(0.0)],
11081 [d.get_x(), d.get_y(), d.get_z(), 1.0],
11082 [sl.get_inner_cos(), sl.get_outer_cos(), 0.0, 0.0],
11083 ));
11084 }
11085 for al in self.get_area_lights().iter() {
11086 if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
11087 break;
11088 }
11089 let p: Vec3 = al.get_position();
11090 let c: Vec3 = al.get_color();
11091 let d: Vec3 = al.get_direction().normalize();
11092 dst_lights.push(GpuPackedLocalLight::new(
11093 [p.get_x(), p.get_y(), p.get_z(), al.get_range().max(0.1)],
11094 [c.get_x(), c.get_y(), c.get_z(), al.get_intensity().max(0.0)],
11095 [d.get_x(), d.get_y(), d.get_z(), 2.0],
11096 [0.0, -1.0, al.get_width(), al.get_height()],
11097 ));
11098 }
11099 let sun: DirectionalLight3D = self.get_sun();
11100 let sun_dir: Vec3 = sun.get_direction().normalize();
11101 let sun_col: Vec3 = sun.get_color();
11102 let sky_hor: Vec3 = sun.get_sky_horizon();
11103 let sky_zen: Vec3 = sun.get_sky_zenith();
11104 let ibl_sh: [[f32; 4]; 9] = if let Some(env) = self.environment_ibl() {
11105 let raw: [[f32; 3]; 9] = env.get_sh_irradiance();
11106 let mut packed: [[f32; 4]; 9] = [[0.0; 4]; 9];
11107 for (dst, src) in packed.iter_mut().zip(raw.iter()) {
11108 *dst = [src[0], src[1], src[2], 0.0];
11109 }
11110 packed
11111 } else {
11112 let mut packed: [[f32; 4]; 9] = [[0.0; 4]; 9];
11113 let avg_r: f32 = (sky_hor.get_x() + sky_zen.get_x()) * 0.5;
11114 let avg_g: f32 = (sky_hor.get_y() + sky_zen.get_y()) * 0.5;
11115 let avg_b: f32 = (sky_hor.get_z() + sky_zen.get_z()) * 0.5;
11116 packed[0] = [avg_r * 1.35, avg_g * 1.35, avg_b * 1.35, 0.0];
11117 packed[1] = [
11118 (sky_zen.get_x() - sky_hor.get_x()) * 0.35,
11119 (sky_zen.get_y() - sky_hor.get_y()) * 0.35,
11120 (sky_zen.get_z() - sky_hor.get_z()) * 0.35,
11121 0.0,
11122 ];
11123 packed
11124 };
11125 let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
11126 let frustum_planes: [[f32; 4]; 6] = frustum.get_planes();
11127 let half_h: f32 = (cam_fov_deg.clamp(12.0, 120.0).to_radians() * 0.5)
11128 .tan()
11129 .max(0.05);
11130 let focal_px: f32 = (target_height.max(1) as f32) * 0.5 / half_h;
11131 let draw_dist: f32 = quality.get_draw_distance().max(1.0);
11132 let draw_dist_sq: f32 = draw_dist * draw_dist;
11133 let frustum_on: bool = quality.get_frustum_culling();
11134 let chunk_on: bool = quality.get_chunk_streaming();
11135 let lod_bias: f32 = quality.get_lod_bias();
11136 let inv_far: f32 = 1.0 / cam_far.max(draw_dist).max(1.0);
11137 let objects: &[SceneObject3D] = self.get_objects().as_slice();
11138 let scene_graph: &SceneGraph3D = self.get_scene_graph();
11139 let skins: &[Skin3D] = self.get_skins().as_slice();
11140 let total_objs: usize = objects.len();
11141 scratch.batcher.get_mut_entries().clear();
11142 if scratch.batcher.get_entries().capacity() < total_objs {
11143 let need: usize = total_objs - scratch.batcher.get_entries().len();
11144 scratch.batcher.get_mut_entries().reserve(need);
11145 }
11146 let mut meshlets_tested: u32 = 0;
11147 let mut meshlets_culled: u32 = 0;
11148 let mut lod_counts: [u32; 4] = [0; 4];
11149 let mut base_idx: usize = 0;
11150 while base_idx < total_objs {
11151 let chunk: usize = (total_objs - base_idx).min(4);
11152 let mut min_x: [f32; 4] = [0.0; 4];
11153 let mut min_y: [f32; 4] = [0.0; 4];
11154 let mut min_z: [f32; 4] = [0.0; 4];
11155 let mut max_x: [f32; 4] = [0.0; 4];
11156 let mut max_y: [f32; 4] = [0.0; 4];
11157 let mut max_z: [f32; 4] = [0.0; 4];
11158 let mut vis_flags: u8 = 0;
11159 for lane in 0..chunk {
11160 let obj_idx: usize = base_idx + lane;
11161 if !self.is_object_visible(obj_idx) {
11162 continue;
11163 }
11164 let wb: AxisAlignedBox3D = objects[obj_idx].get_world_bounds();
11165 let dist_sq: f32 = wb.center().sub(cam_pos).length_sq();
11166 if chunk_on && dist_sq > draw_dist_sq {
11167 continue;
11168 }
11169 let bmin: Vec3 = wb.get_min();
11170 let bmax: Vec3 = wb.get_max();
11171 min_x[lane] = bmin.get_x();
11172 min_y[lane] = bmin.get_y();
11173 min_z[lane] = bmin.get_z();
11174 max_x[lane] = bmax.get_x();
11175 max_y[lane] = bmax.get_y();
11176 max_z[lane] = bmax.get_z();
11177 vis_flags |= 1u8 << lane;
11178 }
11179 let frustum_mask: u8 = if frustum_on && vis_flags != 0 {
11180 let aabb4: SimdAabbBatch4 =
11181 SimdAabbBatch4::new(min_x, min_y, min_z, max_x, max_y, max_z);
11182 cull_aabb_batch4_simd(&frustum_planes, &aabb4)
11183 } else {
11184 0x0F
11185 };
11186 let active_mask: u8 = vis_flags & frustum_mask;
11187 for lane in 0..chunk {
11188 let obj_idx: usize = base_idx + lane;
11189 let obj: &SceneObject3D = &objects[obj_idx];
11190 let mesh_id: usize = obj.get_mesh_id();
11191 let Some(chain) = mesh_lib.get(mesh_id) else {
11192 continue;
11193 };
11194 if ((active_mask >> lane) & 1) == 0 {
11195 if self.is_object_visible(obj_idx)
11196 && let Some(base_mesh) = chain.get_levels().first()
11197 {
11198 let mcount: u32 = base_mesh.get_meshlets().len().max(1) as u32;
11199 meshlets_tested = meshlets_tested.saturating_add(mcount);
11200 meshlets_culled = meshlets_culled.saturating_add(mcount);
11201 }
11202 continue;
11203 }
11204 let wb: AxisAlignedBox3D = obj.get_world_bounds();
11205 let dist: f32 = wb.center().sub(cam_pos).length();
11206 let (selected_mesh, raw_lod): (&Mesh3D, usize) =
11207 chain.select_screen_error(dist, wb.radius(), focal_px, lod_bias);
11208 let lod_idx: usize = raw_lod.min(3);
11209 let Some(lod_arr) = scratch.cached_lod_ranges.get(mesh_id) else {
11210 continue;
11211 };
11212 let lod_range: CachedPbrLodRange = lod_arr[lod_idx];
11213 if lod_range.index_count == 0 {
11214 continue;
11215 }
11216 let model_mat: Mat4 = obj.get_transform().to_mat4();
11217 let (m_tested, m_culled): (u32, u32) = if !selected_mesh.get_meshlets().is_empty() {
11218 cull_meshlets_simd(
11219 selected_mesh.get_meshlets().as_slice(),
11220 &model_mat,
11221 &frustum,
11222 cam_pos,
11223 selected_mesh.get_is_closed(),
11224 )
11225 } else {
11226 (1, 0)
11227 };
11228 meshlets_tested = meshlets_tested.saturating_add(m_tested);
11229 meshlets_culled = meshlets_culled.saturating_add(m_culled);
11230 if selected_mesh.get_is_closed() && m_tested > 0 && m_culled >= m_tested {
11231 continue;
11232 }
11233 lod_counts[lod_idx] = lod_counts[lod_idx].saturating_add(1);
11234 let mat_slot: u32 = if let Some(pid) = obj.try_get_principled_material_id()
11235 && (pid as usize) < fallback_mat_base
11236 {
11237 pid
11238 } else {
11239 Self::resolve_fallback_gpu_material(
11240 obj.get_material(),
11241 fallback_mat_base,
11242 out.get_mut_materials(),
11243 )
11244 };
11245 let mat_flags: u32 = out
11246 .get_materials()
11247 .get(mat_slot as usize)
11248 .map_or(0, |m: &GpuMaterialData3D| m.get_flags_volume()[0]);
11249 let is_alpha_blend: bool = (mat_flags & GPU_MATERIAL_FLAG_ALPHA_BLEND) != 0;
11250 let mut inst_flags: u32 = 0;
11251 let mut bone_off: u32 = 0;
11252 let mut pso_variant: u8 = PBR_PSO_VARIANT_OPAQUE;
11253 if let Some(skin_id) = obj.try_get_skin_id()
11254 && let Some(skin_ref) = skins.get(skin_id as usize)
11255 {
11256 bone_off = out.get_bone_matrices().len() as u32;
11257 skin_ref.compute_skin_matrices_into(model_mat, scene_graph, skin_scratch);
11258 let palette: &[Mat4] = skin_scratch.get_skin_matrices().as_slice();
11259 let dst_bones: &mut Vec<[f32; 16]> = out.get_mut_bone_matrices();
11260 if dst_bones.capacity() < dst_bones.len() + palette.len() {
11261 dst_bones.reserve(palette.len());
11262 }
11263 for bm in palette.iter() {
11264 dst_bones.push(bm.get_elements());
11265 }
11266 inst_flags |= PBR_INST_FLAG_SKINNED;
11267 if skin_ref.get_skinning_mode() == SkinningMode::DualQuaternion {
11268 inst_flags |= PBR_INST_FLAG_DQS;
11269 }
11270 pso_variant = PBR_PSO_VARIANT_SKINNED;
11271 }
11272 let mut morph_off: u32 = 0;
11273 if lod_range.has_morphs
11274 && let Some(node_id) = obj.try_get_node_id()
11275 {
11276 let mweights: &[f32] = scene_graph.morph_weights_for_node(node_id);
11277 if !mweights.is_empty() {
11278 morph_off = out.get_morph_weights().len() as u32;
11279 let dst_mw: &mut Vec<f32> = out.get_mut_morph_weights();
11280 for k in 0..4 {
11281 dst_mw.push(mweights.get(k).copied().unwrap_or(0.0));
11282 }
11283 inst_flags |= PBR_INST_FLAG_MORPHED;
11284 }
11285 }
11286 let alpha_pass: u8 = if is_alpha_blend {
11287 pso_variant = PBR_PSO_VARIANT_ALPHA_BLEND;
11288 inst_flags |= PBR_INST_FLAG_ALPHA_BLEND;
11289 1
11290 } else {
11291 0
11292 };
11293 let depth_q16: u16 = ((dist * inv_far).clamp(0.0, 1.0) * 65_535.0).round() as u16;
11294 let sort_key: u64 = pack_pbr_sort_key(
11295 alpha_pass,
11296 pso_variant,
11297 mat_slot,
11298 mesh_id as u32,
11299 lod_idx as u8,
11300 depth_q16,
11301 );
11302 let mut q_origin: [f32; 4] = lod_range.bounds_min;
11303 q_origin[3] = f32::from_bits(obj_idx as u32);
11304 let mut q_extent: [f32; 4] = lod_range.bounds_extent;
11305 q_extent[3] = lod_idx as f32;
11306 let instance: GpuPbrInstance3D = GpuPbrInstance3D::new(
11307 model_mat.get_elements(),
11308 q_origin,
11309 q_extent,
11310 [mat_slot, bone_off, morph_off, inst_flags],
11311 );
11312 scratch.batcher.get_mut_entries().push(PbrSortEntry3D {
11313 sort_key,
11314 index_start: lod_range.index_start,
11315 index_count: lod_range.index_count,
11316 base_vertex: 0,
11317 material_index: mat_slot,
11318 pso_variant,
11319 lod_level: lod_idx as u8,
11320 instance,
11321 });
11322 }
11323 base_idx += 4;
11324 }
11325 let draw_call_count: u32 = {
11326 let GpuPbrScenePass {
11327 instances,
11328 draw_batches,
11329 ..
11330 } = out;
11331 coalesce_pbr_batches_into(&mut scratch.batcher, instances, draw_batches)
11332 };
11333 let textures: &[Texture2D3D] = self.get_textures().as_slice();
11334 if scratch.uploaded_texture_min_mip.len() < textures.len() {
11335 scratch
11336 .uploaded_texture_min_mip
11337 .resize(textures.len(), u8::MAX);
11338 }
11339 for (slot_idx, tex) in textures.iter().enumerate() {
11340 let mips: &[TextureMipLevel3D] = tex.get_mips().as_slice();
11341 if mips.is_empty() {
11342 continue;
11343 }
11344 let current_min: u8 = scratch.uploaded_texture_min_mip[slot_idx];
11345 if current_min == 0 {
11346 continue;
11347 }
11348 let total_mips: u8 = mips.len().min(16) as u8;
11349 let (target_mip, priority): (u8, StreamPriority) = if current_min == u8::MAX {
11350 (total_mips.saturating_sub(1), StreamPriority::Critical)
11351 } else {
11352 let next_mip: u8 = current_min.saturating_sub(1);
11353 let prio: StreamPriority = if next_mip > 0 {
11354 StreamPriority::VisibleHigh
11355 } else {
11356 StreamPriority::PrefetchMedium
11357 };
11358 (next_mip, prio)
11359 };
11360 if let Some(mip_data) = mips.get(target_mip as usize) {
11361 let upload: GpuTextureMipUpload = GpuTextureMipUpload {
11362 texture_slot: slot_idx as u32,
11363 mip_level: target_mip,
11364 total_mip_levels: total_mips,
11365 is_srgb: tex.get_color_space() == TextureColorSpace::Srgb,
11366 min_lod_clamp: target_mip,
11367 width: mip_data.get_width(),
11368 height: mip_data.get_height(),
11369 rgba8: mip_data.get_pixels().clone(),
11370 };
11371 let _: GpuUploadTicket = belt.enqueue_mip_upload(priority, upload);
11372 }
11373 }
11374 let _: usize = belt.drain_mip_uploads_into(out.get_mut_texture_uploads());
11375 for uploaded in out.get_texture_uploads().iter() {
11376 let slot_idx: usize = uploaded.get_texture_slot() as usize;
11377 if let Some(watermark) = scratch.uploaded_texture_min_mip.get_mut(slot_idx) {
11378 *watermark = (*watermark).min(uploaded.get_mip_level());
11379 }
11380 }
11381 let fog_density: f32 = self.effective_fog_density(quality.get_volumetric_fog());
11382 let (ambient_strength, exposure_val): (f32, f32) = {
11383 let Self {
11384 weather_ambient_strength,
11385 weather_exposure,
11386 ..
11387 } = self;
11388 (*weather_ambient_strength, *weather_exposure)
11389 };
11390 let agx_flag: f32 = if self.get_use_agx_tonemap() { 1.0 } else { 0.0 };
11391 out.set_target_width(target_width);
11392 out.set_target_height(target_height);
11393 out.set_prev_view_proj(prev_vp);
11394 out.set_view_proj(view_proj_mat.get_elements());
11395 out.set_camera_pos_exposure([
11396 cam_pos.get_x(),
11397 cam_pos.get_y(),
11398 cam_pos.get_z(),
11399 exposure_val,
11400 ]);
11401 out.set_sun_dir_fog([
11402 sun_dir.get_x(),
11403 sun_dir.get_y(),
11404 sun_dir.get_z(),
11405 fog_density,
11406 ]);
11407 out.set_sun_color_ambient([
11408 sun_col.get_x(),
11409 sun_col.get_y(),
11410 sun_col.get_z(),
11411 ambient_strength,
11412 ]);
11413 out.set_sky_horizon_tod([
11414 sky_hor.get_x(),
11415 sky_hor.get_y(),
11416 sky_hor.get_z(),
11417 sun.get_time_of_day(),
11418 ]);
11419 out.set_sky_zenith_agx([sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), agx_flag]);
11420 out.set_ibl_sh(ibl_sh);
11421 out.set_mesh_buffer(Arc::clone(&scratch.cached_mesh_buffer));
11422 let stats: GpuPbrCullStats = GpuPbrCullStats::new(
11423 meshlets_tested,
11424 meshlets_culled,
11425 lod_counts,
11426 draw_call_count,
11427 belt.get_frame_bytes_used(),
11428 belt.get_frame_time_us_used(),
11429 );
11430 out.set_stats(stats);
11431 }
11432
11433 pub fn build_gpu_pbr_scene_pass_into(
11442 &mut self,
11443 viewport: (u32, u32),
11444 quality: &RenderQualityConfig,
11445 belt: &mut GpuUploadBelt,
11446 out: &mut GpuPbrScenePass,
11447 ) {
11448 let (mut pbr_work, mut skin_work): (World3dPbrPassScratch, SkinPaletteScratch3D) = {
11449 let Self {
11450 pbr_pass_scratch,
11451 skin_scratch,
11452 ..
11453 } = self;
11454 (take(pbr_pass_scratch), take(skin_scratch))
11455 };
11456 self.populate_gpu_pbr_scene_pass_with_scratch(
11457 viewport,
11458 quality,
11459 belt,
11460 &mut pbr_work,
11461 &mut skin_work,
11462 out,
11463 );
11464 let Self {
11465 pbr_pass_scratch,
11466 skin_scratch,
11467 ..
11468 } = self;
11469 *pbr_pass_scratch = pbr_work;
11470 *skin_scratch = skin_work;
11471 }
11472
11473 #[must_use]
11488 pub fn build_gpu_scene_pass(
11489 &self,
11490 snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
11491 alpha: f32,
11492 viewport: (u32, u32),
11493 quality: &RenderQualityConfig,
11494 mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
11495 ) -> GpuWorld3dScenePass {
11496 let mut out: GpuWorld3dScenePass = GpuWorld3dScenePass::default();
11497 let used_tls: bool = WORLD3D_GPU_PASS_SCRATCH
11498 .try_with(|cell: &RefCell<World3dGpuPassScratch>| -> bool {
11499 if let Ok(mut scratch) = cell.try_borrow_mut() {
11500 self.populate_gpu_scene_pass_with_scratch(
11501 snapshots,
11502 alpha,
11503 viewport,
11504 quality,
11505 mesh_cache,
11506 (&mut scratch, &mut out),
11507 );
11508 true
11509 } else {
11510 false
11511 }
11512 })
11513 .unwrap_or(false);
11514 if !used_tls {
11515 let mut local_scratch: World3dGpuPassScratch = World3dGpuPassScratch::default();
11516 self.populate_gpu_scene_pass_with_scratch(
11517 snapshots,
11518 alpha,
11519 viewport,
11520 quality,
11521 mesh_cache,
11522 (&mut local_scratch, &mut out),
11523 );
11524 }
11525 out
11526 }
11527}
11528
11529impl SceneCamera3D {
11531 #[must_use]
11544 pub fn from_imported(
11545 imported: &ImportedCamera3D,
11546 node_id: Option<u32>,
11547 position: Vec3,
11548 rotation: Quat,
11549 ) -> Self {
11550 Self {
11551 name: imported.get_name().clone(),
11552 node_id,
11553 position,
11554 rotation: rotation.normalize(),
11555 projection: imported.get_projection(),
11556 }
11557 }
11558
11559 #[must_use]
11565 pub fn forward(&self) -> Vec3 {
11566 self.get_rotation()
11567 .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
11568 .normalize()
11569 }
11570
11571 #[must_use]
11577 pub fn right(&self) -> Vec3 {
11578 self.get_rotation()
11579 .rotate_vec3(Vec3::new(1.0, 0.0, 0.0))
11580 .normalize()
11581 }
11582
11583 #[must_use]
11589 pub fn up(&self) -> Vec3 {
11590 self.get_rotation()
11591 .rotate_vec3(Vec3::new(0.0, 1.0, 0.0))
11592 .normalize()
11593 }
11594
11595 #[must_use]
11601 pub fn is_orthographic(&self) -> bool {
11602 matches!(
11603 self.get_projection(),
11604 GltfCameraProjection::Orthographic { .. }
11605 )
11606 }
11607
11608 #[must_use]
11619 pub fn view_projection(&self, viewport_aspect: f32) -> Mat4 {
11620 let pos: Vec3 = self.get_position();
11621 let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), self.up());
11622 let proj: Mat4 = match self.get_projection() {
11623 GltfCameraProjection::Perspective {
11624 yfov_rad,
11625 aspect_ratio,
11626 znear,
11627 zfar,
11628 } => Mat4::perspective(
11629 yfov_rad.clamp(0.15, 2.6),
11630 aspect_ratio.unwrap_or(viewport_aspect).max(0.1),
11631 znear.max(0.02),
11632 zfar.unwrap_or(480.0).max(znear + 1.0),
11633 ),
11634 GltfCameraProjection::Orthographic {
11635 xmag,
11636 ymag,
11637 znear,
11638 zfar,
11639 } => Mat4::orthographic_mag(xmag, ymag, znear.max(0.01), zfar.max(znear + 1.0)),
11640 };
11641 proj.mul(view)
11642 }
11643
11644 #[must_use]
11650 pub fn to_camera3d(&self) -> Camera3D {
11651 let fwd: Vec3 = self.forward();
11652 let yaw_val: f32 = fwd.get_z().atan2(fwd.get_x());
11653 let pitch_val: f32 = fwd.get_y().clamp(-0.98, 0.98).asin();
11654 let (fov_deg, near_val, far_val): (f32, f32, f32) = match self.get_projection() {
11655 GltfCameraProjection::Perspective {
11656 yfov_rad,
11657 znear,
11658 zfar,
11659 ..
11660 } => (
11661 yfov_rad.to_degrees().clamp(12.0, 120.0),
11662 znear.max(0.05),
11663 zfar.unwrap_or(480.0).max(10.0),
11664 ),
11665 GltfCameraProjection::Orthographic { znear, zfar, .. } => {
11666 (45.0, znear.max(0.05), zfar.max(10.0))
11667 }
11668 };
11669 let mut cam: Camera3D = Camera3D::default();
11670 cam.set_position(self.get_position());
11671 cam.set_yaw(yaw_val);
11672 cam.set_pitch(pitch_val);
11673 cam.set_fov_deg(fov_deg);
11674 cam.set_near(near_val);
11675 cam.set_far(far_val);
11676 cam
11677 }
11678}