1use super::*;
2
3impl Default for PbrMaterial {
5 fn default() -> Self {
11 Self {
12 base_color: Vec3::new(0.72, 0.75, 0.80),
13 metallic: 0.1,
14 roughness: 0.55,
15 emissive: Vec3::zero(),
16 reflectivity: 0.12,
17 surface_detail: SurfaceDetailMode::None,
18 }
19 }
20}
21
22impl PbrMaterial {
24 #[must_use]
37 pub fn pbr(color: Color, metallic: f32, roughness: f32, reflectivity: f32) -> Self {
38 Self {
39 base_color: Vec3::from_color(color),
40 metallic: metallic.clamp(0.0, 1.0),
41 roughness: roughness.clamp(0.04, 1.0),
42 emissive: Vec3::zero(),
43 reflectivity: reflectivity.clamp(0.0, 1.0),
44 surface_detail: SurfaceDetailMode::None,
45 }
46 }
47
48 #[must_use]
59 pub fn metallic(color: Color, roughness: f32) -> Self {
60 let red_val: f32 = roughness.clamp(0.04, 1.0);
61 Self::pbr(
62 color,
63 0.92,
64 red_val,
65 (1.0 - red_val * 0.8).clamp(0.15, 0.96),
66 )
67 }
68
69 #[must_use]
80 pub fn dielectric(color: Color, roughness: f32) -> Self {
81 let red_val: f32 = roughness.clamp(0.04, 1.0);
82 Self::pbr(
83 color,
84 0.04,
85 red_val,
86 (0.35 * (1.0 - red_val)).clamp(0.04, 0.35),
87 )
88 }
89
90 #[must_use]
101 pub fn glass(color: Color, roughness: f32) -> Self {
102 let red_val: f32 = roughness.clamp(0.04, 0.4);
103 Self::pbr(color, 0.12, red_val, 0.88)
104 }
105
106 #[must_use]
117 pub fn neon(color: Color, intensity: f32) -> Self {
118 let rgb: Vec3 = Vec3::from_color(color);
119 Self {
120 base_color: rgb,
121 metallic: 0.2,
122 roughness: 0.2,
123 emissive: rgb.scale(intensity.max(0.2)),
124 reflectivity: 0.3,
125 surface_detail: SurfaceDetailMode::None,
126 }
127 }
128
129 #[must_use]
140 pub fn with_emissive(mut self, emissive: Vec3) -> Self {
141 self.set_emissive(emissive);
142 self
143 }
144
145 #[must_use]
156 pub fn with_roughness(mut self, roughness: f32) -> Self {
157 self.set_roughness(roughness.clamp(0.04, 1.0));
158 self
159 }
160
161 #[must_use]
172 pub fn with_metallic(mut self, metallic: f32) -> Self {
173 self.set_metallic(metallic.clamp(0.0, 1.0));
174 self
175 }
176
177 #[must_use]
188 pub fn with_reflectivity(mut self, reflectivity: f32) -> Self {
189 self.set_reflectivity(reflectivity.clamp(0.0, 1.0));
190 self
191 }
192
193 #[must_use]
204 pub fn with_surface_detail(mut self, mode: SurfaceDetailMode) -> Self {
205 self.set_surface_detail(mode);
206 self
207 }
208}
209
210impl BoxMeshDesc {
212 #[must_use]
223 pub fn new(name: &str, size: Vec3) -> Self {
224 Self {
225 name: name.to_string(),
226 size,
227 ground_pivot: true,
228 material: PbrMaterial::default(),
229 }
230 }
231
232 #[must_use]
243 pub fn with_ground_pivot(mut self, ground_pivot: bool) -> Self {
244 self.set_ground_pivot(ground_pivot);
245 self
246 }
247
248 #[must_use]
259 pub fn with_material(mut self, material: PbrMaterial) -> Self {
260 self.set_material(material);
261 self
262 }
263}
264
265impl GroundPlaneDesc {
267 #[must_use]
279 pub fn new(name: &str, width: f32, depth: f32) -> Self {
280 Self {
281 name: name.to_string(),
282 width,
283 depth,
284 subdivisions: 8,
285 material: PbrMaterial::default(),
286 }
287 }
288
289 #[must_use]
300 pub fn with_subdivisions(mut self, subdivisions: usize) -> Self {
301 self.set_subdivisions(subdivisions);
302 self
303 }
304
305 #[must_use]
316 pub fn with_material(mut self, material: PbrMaterial) -> Self {
317 self.set_material(material);
318 self
319 }
320}
321
322impl Mesh3D {
324 #[must_use]
335 pub fn build_meshlets_from_parts(
336 vertices: &[Vertex3D],
337 indices: &[[u32; 3]],
338 ) -> Vec<Meshlet3D> {
339 if indices.is_empty() {
340 return Vec::new();
341 }
342 let cluster_count: usize = indices.len().div_ceil(MESHLET_MAX_TRIS);
343 let mut out: Vec<Meshlet3D> = Vec::with_capacity(cluster_count);
344 let mut start: usize = 0;
345 while start < indices.len() {
346 let end: usize = (start + MESHLET_MAX_TRIS).min(indices.len());
347 let mut cluster_box: AxisAlignedBox3D = AxisAlignedBox3D::empty();
348 let mut avg_n: Vec3 = Vec3::zero();
349 let mut valid_tris: usize = 0;
350 for tri in &indices[start..end] {
351 let (i0, i1, i2): (usize, usize, usize) =
352 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
353 if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
354 let p0: Vec3 = vertices[i0].get_position();
355 let p1: Vec3 = vertices[i1].get_position();
356 let p2: Vec3 = vertices[i2].get_position();
357 cluster_box.expand_point(p0);
358 cluster_box.expand_point(p1);
359 cluster_box.expand_point(p2);
360 let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
361 avg_n = avg_n.add(fn_vec);
362 valid_tris += 1;
363 }
364 }
365 if valid_tris == 0 {
366 cluster_box = AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
367 }
368 let cone_axis: Vec3 = avg_n.normalize();
369 let mut min_dot: f32 = 1.0;
370 for tri in &indices[start..end] {
371 let (i0, i1, i2): (usize, usize, usize) =
372 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
373 if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
374 let p0: Vec3 = vertices[i0].get_position();
375 let p1: Vec3 = vertices[i1].get_position();
376 let p2: Vec3 = vertices[i2].get_position();
377 let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
378 min_dot = min_dot.min(fn_vec.dot(cone_axis));
379 }
380 }
381 let radius: f32 = cluster_box.radius().max(0.05);
382 let screen_error: f32 = radius / ((end - start).max(1) as f32).sqrt();
383 out.push(Meshlet3D::new(
384 start as u32,
385 (end - start) as u32,
386 cluster_box,
387 cone_axis,
388 min_dot,
389 screen_error,
390 ));
391 start = end;
392 }
393 out
394 }
395
396 #[must_use]
409 pub fn from_parts(
410 name: String,
411 vertices: Vec<Vertex3D>,
412 indices: Vec<[u32; 3]>,
413 material: PbrMaterial,
414 ) -> Self {
415 let mut bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
416 for item_val in vertices.iter() {
417 bounds.expand_point(item_val.get_position());
418 }
419 if vertices.is_empty() {
420 bounds = AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
421 }
422 let meshlets: Vec<Meshlet3D> = Self::build_meshlets_from_parts(&vertices, &indices);
423 Self {
424 name,
425 vertices,
426 indices,
427 bounds,
428 material,
429 sub_materials: Vec::new(),
430 tri_materials: Vec::new(),
431 meshlets,
432 is_closed: false,
433 }
434 }
435
436 #[cfg_attr(not(target_arch = "wasm32"), inline)]
447 #[must_use]
448 pub fn resolve_triangle_material(
449 &self,
450 tri_index: usize,
451 primary_material: PbrMaterial,
452 ) -> (PbrMaterial, u16) {
453 let Self {
454 sub_materials,
455 tri_materials,
456 ..
457 } = self;
458 if tri_materials.is_empty() {
459 return (primary_material, 0);
460 }
461 let slot: u16 = tri_materials.get(tri_index).copied().unwrap_or(0);
462 if slot == 0 {
463 (primary_material, 0)
464 } else if let Some(&sub_mat) = sub_materials.get((slot - 1) as usize) {
465 (sub_mat, slot)
466 } else {
467 (primary_material, 0)
468 }
469 }
470
471 fn push_flat_tri(
481 vertices: &mut Vec<Vertex3D>,
482 indices: &mut Vec<[u32; 3]>,
483 tri_materials: &mut Vec<u16>,
484 corners: (Vec3, Vec3, Vec3),
485 mat_slot: u16,
486 ) {
487 let (vert_a, vert_b, vert_c): (Vec3, Vec3, Vec3) = corners;
488 let face_normal: Vec3 = vert_b.sub(vert_a).cross(vert_c.sub(vert_a)).normalize();
489 let base_idx: u32 = vertices.len() as u32;
490 vertices.push(Vertex3D::new(vert_a, face_normal));
491 vertices.push(Vertex3D::new(vert_b, face_normal));
492 vertices.push(Vertex3D::new(vert_c, face_normal));
493 indices.push([base_idx, base_idx + 1, base_idx + 2]);
494 tri_materials.push(mat_slot);
495 }
496
497 fn push_flat_quad(
507 vertices: &mut Vec<Vertex3D>,
508 indices: &mut Vec<[u32; 3]>,
509 tri_materials: &mut Vec<u16>,
510 quad: [Vec3; 4],
511 mat_slot: u16,
512 ) {
513 let edge_u: Vec3 = quad[1].sub(quad[0]);
514 let edge_v: Vec3 = quad[2].sub(quad[0]);
515 let face_normal: Vec3 = edge_u.cross(edge_v).normalize();
516 let base_idx: u32 = vertices.len() as u32;
517 for corner in quad.into_iter() {
518 vertices.push(Vertex3D::new(corner, face_normal));
519 }
520 indices.push([base_idx, base_idx + 1, base_idx + 2]);
521 indices.push([base_idx, base_idx + 2, base_idx + 3]);
522 tri_materials.push(mat_slot);
523 tri_materials.push(mat_slot);
524 }
525
526 fn push_tapered_prism(
539 vertices: &mut Vec<Vertex3D>,
540 indices: &mut Vec<[u32; 3]>,
541 tri_materials: &mut Vec<u16>,
542 bottom: [Vec3; 4],
543 top: [Vec3; 4],
544 face_slots: [u16; 6],
545 ) {
546 Self::push_flat_quad(
547 vertices,
548 indices,
549 tri_materials,
550 [bottom[0], bottom[1], top[1], top[0]],
551 face_slots[0],
552 );
553 Self::push_flat_quad(
554 vertices,
555 indices,
556 tri_materials,
557 [bottom[2], bottom[3], top[3], top[2]],
558 face_slots[1],
559 );
560 Self::push_flat_quad(
561 vertices,
562 indices,
563 tri_materials,
564 [bottom[1], bottom[2], top[2], top[1]],
565 face_slots[2],
566 );
567 Self::push_flat_quad(
568 vertices,
569 indices,
570 tri_materials,
571 [bottom[3], bottom[0], top[0], top[3]],
572 face_slots[3],
573 );
574 Self::push_flat_quad(
575 vertices,
576 indices,
577 tri_materials,
578 [top[0], top[1], top[2], top[3]],
579 face_slots[4],
580 );
581 Self::push_flat_quad(
582 vertices,
583 indices,
584 tri_materials,
585 [bottom[3], bottom[2], bottom[1], bottom[0]],
586 face_slots[5],
587 );
588 }
589
590 fn push_box_part(
601 vertices: &mut Vec<Vertex3D>,
602 indices: &mut Vec<[u32; 3]>,
603 tri_materials: &mut Vec<u16>,
604 center: Vec3,
605 size: Vec3,
606 mat_slot: u16,
607 ) {
608 let half_x: f32 = size.get_x() * 0.5;
609 let half_y: f32 = size.get_y() * 0.5;
610 let half_z: f32 = size.get_z() * 0.5;
611 let cx: f32 = center.get_x();
612 let cy: f32 = center.get_y();
613 let cz: f32 = center.get_z();
614 let bottom: [Vec3; 4] = [
615 Vec3::new(cx - half_x, cy - half_y, cz + half_z),
616 Vec3::new(cx + half_x, cy - half_y, cz + half_z),
617 Vec3::new(cx + half_x, cy - half_y, cz - half_z),
618 Vec3::new(cx - half_x, cy - half_y, cz - half_z),
619 ];
620 let top: [Vec3; 4] = [
621 Vec3::new(cx - half_x, cy + half_y, cz + half_z),
622 Vec3::new(cx + half_x, cy + half_y, cz + half_z),
623 Vec3::new(cx + half_x, cy + half_y, cz - half_z),
624 Vec3::new(cx - half_x, cy + half_y, cz - half_z),
625 ];
626 Self::push_tapered_prism(vertices, indices, tri_materials, bottom, top, [mat_slot; 6]);
627 }
628
629 fn push_wheel_assembly(
640 vertices: &mut Vec<Vertex3D>,
641 indices: &mut Vec<[u32; 3]>,
642 tri_materials: &mut Vec<u16>,
643 center: Vec3,
644 dims: (f32, f32, f32),
645 slots: (u16, u16),
646 ) {
647 let (tire_radius, rim_radius, tire_width): (f32, f32, f32) = dims;
648 let (tire_slot, rim_slot): (u16, u16) = slots;
649 let half_w: f32 = tire_width * 0.5;
650 let cx: f32 = center.get_x();
651 let cy: f32 = center.get_y();
652 let cz: f32 = center.get_z();
653 let x_left: f32 = cx - half_w;
654 let x_right: f32 = cx + half_w;
655 let left_hub: Vec3 = Vec3::new(x_left, cy, cz);
656 let right_hub: Vec3 = Vec3::new(x_right, cy, cz);
657 let outer_sign: f32 = if cx >= 0.0 { 1.0 } else { -1.0 };
658 let rim_x: f32 = cx + outer_sign * (half_w + 0.014);
659 let brake_x: f32 = cx + outer_sign * (half_w + 0.006);
660 let rim_hub: Vec3 = Vec3::new(rim_x, cy, cz);
661 let brake_hub: Vec3 = Vec3::new(brake_x, cy, cz);
662 let step_rad: f32 = (2.0 * PI) / (MESH_CAR_WHEEL_SEGMENTS as f32);
663 for seg_idx in 0..MESH_CAR_WHEEL_SEGMENTS {
664 let a0: f32 = (seg_idx as f32) * step_rad;
665 let a1: f32 = ((seg_idx + 1) as f32) * step_rad;
666 let (s0, c0): (f32, f32) = a0.sin_cos();
667 let (s1, c1): (f32, f32) = a1.sin_cos();
668 let l0: Vec3 = Vec3::new(x_left, cy + s0 * tire_radius, cz + c0 * tire_radius);
669 let l1: Vec3 = Vec3::new(x_left, cy + s1 * tire_radius, cz + c1 * tire_radius);
670 let r0: Vec3 = Vec3::new(x_right, cy + s0 * tire_radius, cz + c0 * tire_radius);
671 let r1: Vec3 = Vec3::new(x_right, cy + s1 * tire_radius, cz + c1 * tire_radius);
672 Self::push_flat_quad(
673 vertices,
674 indices,
675 tri_materials,
676 [l0, r0, r1, l1],
677 tire_slot,
678 );
679 Self::push_flat_tri(
680 vertices,
681 indices,
682 tri_materials,
683 (right_hub, r1, r0),
684 tire_slot,
685 );
686 Self::push_flat_tri(
687 vertices,
688 indices,
689 tri_materials,
690 (left_hub, l0, l1),
691 tire_slot,
692 );
693 let bm0: Vec3 = Vec3::new(brake_x, cy + s0 * rim_radius, cz + c0 * rim_radius);
694 let bm1: Vec3 = Vec3::new(brake_x, cy + s1 * rim_radius, cz + c1 * rim_radius);
695 if outer_sign > 0.0 {
696 Self::push_flat_tri(
697 vertices,
698 indices,
699 tri_materials,
700 (brake_hub, bm1, bm0),
701 tire_slot,
702 );
703 } else {
704 Self::push_flat_tri(
705 vertices,
706 indices,
707 tri_materials,
708 (brake_hub, bm0, bm1),
709 tire_slot,
710 );
711 }
712 let lip_in: f32 = rim_radius * 0.78;
713 let rm0: Vec3 = Vec3::new(rim_x, cy + s0 * rim_radius, cz + c0 * rim_radius);
714 let rm1: Vec3 = Vec3::new(rim_x, cy + s1 * rim_radius, cz + c1 * rim_radius);
715 let ri0: Vec3 = Vec3::new(rim_x, cy + s0 * lip_in, cz + c0 * lip_in);
716 let ri1: Vec3 = Vec3::new(rim_x, cy + s1 * lip_in, cz + c1 * lip_in);
717 if outer_sign > 0.0 {
718 Self::push_flat_quad(
719 vertices,
720 indices,
721 tri_materials,
722 [ri0, rm0, rm1, ri1],
723 rim_slot,
724 );
725 } else {
726 Self::push_flat_quad(
727 vertices,
728 indices,
729 tri_materials,
730 [ri1, rm1, rm0, ri0],
731 rim_slot,
732 );
733 }
734 if seg_idx % 2 == 0 {
735 let spoke_rad: f32 = rim_radius * 0.84;
736 let a_mid: f32 = a0 + step_rad * 0.48;
737 let (sm, cm): (f32, f32) = a_mid.sin_cos();
738 let sp0: Vec3 = Vec3::new(rim_x, cy + s0 * spoke_rad, cz + c0 * spoke_rad);
739 let sp1: Vec3 = Vec3::new(rim_x, cy + sm * spoke_rad, cz + cm * spoke_rad);
740 if outer_sign > 0.0 {
741 Self::push_flat_tri(
742 vertices,
743 indices,
744 tri_materials,
745 (rim_hub, sp1, sp0),
746 rim_slot,
747 );
748 } else {
749 Self::push_flat_tri(
750 vertices,
751 indices,
752 tri_materials,
753 (rim_hub, sp0, sp1),
754 rim_slot,
755 );
756 }
757 }
758 }
759 }
760
761 #[must_use]
776 pub fn box_mesh(
777 name: &str,
778 width_val: f32,
779 height_val: f32,
780 delta_val: f32,
781 ground_pivot: bool,
782 material: PbrMaterial,
783 ) -> Self {
784 let hx: f32 = width_val * 0.5;
785 let hz: f32 = delta_val * 0.5;
786 let y0: f32 = if ground_pivot { 0.0 } else { -height_val * 0.5 };
787 let y1: f32 = if ground_pivot {
788 height_val
789 } else {
790 height_val * 0.5
791 };
792 let faces: [([Vec3; 4], Vec3); 6] = [
793 (
794 [
795 Vec3::new(-hx, y0, hz),
796 Vec3::new(hx, y0, hz),
797 Vec3::new(hx, y1, hz),
798 Vec3::new(-hx, y1, hz),
799 ],
800 Vec3::new(0.0, 0.0, 1.0),
801 ),
802 (
803 [
804 Vec3::new(hx, y0, -hz),
805 Vec3::new(-hx, y0, -hz),
806 Vec3::new(-hx, y1, -hz),
807 Vec3::new(hx, y1, -hz),
808 ],
809 Vec3::new(0.0, 0.0, -1.0),
810 ),
811 (
812 [
813 Vec3::new(hx, y0, hz),
814 Vec3::new(hx, y0, -hz),
815 Vec3::new(hx, y1, -hz),
816 Vec3::new(hx, y1, hz),
817 ],
818 Vec3::new(1.0, 0.0, 0.0),
819 ),
820 (
821 [
822 Vec3::new(-hx, y0, -hz),
823 Vec3::new(-hx, y0, hz),
824 Vec3::new(-hx, y1, hz),
825 Vec3::new(-hx, y1, -hz),
826 ],
827 Vec3::new(-1.0, 0.0, 0.0),
828 ),
829 (
830 [
831 Vec3::new(-hx, y1, hz),
832 Vec3::new(hx, y1, hz),
833 Vec3::new(hx, y1, -hz),
834 Vec3::new(-hx, y1, -hz),
835 ],
836 Vec3::new(0.0, 1.0, 0.0),
837 ),
838 (
839 [
840 Vec3::new(-hx, y0, -hz),
841 Vec3::new(hx, y0, -hz),
842 Vec3::new(hx, y0, hz),
843 Vec3::new(-hx, y0, hz),
844 ],
845 Vec3::new(0.0, -1.0, 0.0),
846 ),
847 ];
848 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(24);
849 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(12);
850 for (quad, item_count) in faces.into_iter() {
851 let base: u32 = vertices.len() as u32;
852 for point_val in quad.into_iter() {
853 vertices.push(Vertex3D::new(point_val, item_count));
854 }
855 indices.push([base, base + 1, base + 2]);
856 indices.push([base, base + 2, base + 3]);
857 }
858 let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
859 mesh.set_is_closed(true);
860 mesh
861 }
862
863 #[must_use]
877 pub fn ground_plane(
878 name: &str,
879 width_val: f32,
880 delta_val: f32,
881 subdivisions: usize,
882 material: PbrMaterial,
883 ) -> Self {
884 let segs: usize = subdivisions.clamp(1, 16);
885 let mut vertices: Vec<Vertex3D> = Vec::with_capacity((segs + 1) * (segs + 1));
886 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(segs * segs * 2);
887 let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
888 for iz in 0..=segs {
889 let vz: f32 = ((iz as f32) / (segs as f32) - 0.5) * delta_val;
890 for ix in 0..=segs {
891 let vx: f32 = ((ix as f32) / (segs as f32) - 0.5) * width_val;
892 vertices.push(Vertex3D::new(Vec3::new(vx, 0.0, vz), up));
893 }
894 }
895 let stride: u32 = (segs + 1) as u32;
896 for iz in 0..segs {
897 for ix in 0..segs {
898 let i0: u32 = (iz as u32) * stride + (ix as u32);
899 let i1: u32 = i0 + 1;
900 let i2: u32 = i0 + stride;
901 let i3: u32 = i2 + 1;
902 indices.push([i0, i2, i1]);
903 indices.push([i1, i2, i3]);
904 }
905 }
906 Self::from_parts(name.to_string(), vertices, indices, material)
907 }
908
909 #[must_use]
924 pub fn coastal_ocean_ring(
925 name: &str,
926 outer_span: f32,
927 inner_half_x: f32,
928 inner_half_z: f32,
929 subdivisions: usize,
930 material: PbrMaterial,
931 ) -> Self {
932 let seg_count: usize = subdivisions.clamp(8, 32);
933 let cut_half_x: f32 = (inner_half_x - 2.0).max(0.0);
934 let cut_half_z: f32 = (inner_half_z - 2.0).max(0.0);
935 let mut vertices: Vec<Vertex3D> = Vec::with_capacity((seg_count + 1) * (seg_count + 1));
936 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(seg_count * seg_count * 2);
937 let up_normal: Vec3 = Vec3::new(0.0, 1.0, 0.0);
938 let inv_segs: f32 = 1.0 / (seg_count as f32);
939 for grid_z in 0..=seg_count {
940 let pos_z: f32 = ((grid_z as f32) * inv_segs - 0.5) * outer_span;
941 for grid_x in 0..=seg_count {
942 let pos_x: f32 = ((grid_x as f32) * inv_segs - 0.5) * outer_span;
943 vertices.push(Vertex3D::new(Vec3::new(pos_x, 0.0, pos_z), up_normal));
944 }
945 }
946 let row_stride: u32 = (seg_count + 1) as u32;
947 let mut block_z: usize = 0;
948 while block_z < seg_count {
949 let end_z: usize = (block_z + 4).min(seg_count);
950 let mut block_x: usize = 0;
951 while block_x < seg_count {
952 let end_x: usize = (block_x + 4).min(seg_count);
953 for grid_z in block_z..end_z {
954 let quad_z0: f32 = ((grid_z as f32) * inv_segs - 0.5) * outer_span;
955 let quad_z1: f32 = (((grid_z + 1) as f32) * inv_segs - 0.5) * outer_span;
956 for grid_x in block_x..end_x {
957 let quad_x0: f32 = ((grid_x as f32) * inv_segs - 0.5) * outer_span;
958 let quad_x1: f32 = (((grid_x + 1) as f32) * inv_segs - 0.5) * outer_span;
959 let inside_x: bool = quad_x0 >= -cut_half_x && quad_x1 <= cut_half_x;
960 let inside_z: bool = quad_z0 >= -cut_half_z && quad_z1 <= cut_half_z;
961 if inside_x && inside_z {
962 continue;
963 }
964 let idx0: u32 = (grid_z as u32) * row_stride + (grid_x as u32);
965 let idx1: u32 = idx0 + 1;
966 let idx2: u32 = idx0 + row_stride;
967 let idx3: u32 = idx2 + 1;
968 indices.push([idx0, idx2, idx1]);
969 indices.push([idx1, idx2, idx3]);
970 }
971 }
972 block_x += 4;
973 }
974 block_z += 4;
975 }
976 Self::from_parts(name.to_string(), vertices, indices, material)
977 }
978
979 #[must_use]
990 pub fn sports_car(name: &str, material: PbrMaterial) -> Self {
991 let sub_materials: Vec<PbrMaterial> = vec![
992 PbrMaterial::glass(Color::hex(0x0A101E), 0.05),
993 PbrMaterial::dielectric(Color::hex(0x0D1015), 0.90),
994 PbrMaterial::metallic(Color::hex(0xDCE6F2), 0.12),
995 PbrMaterial::pbr(Color::hex(0x121722), 0.34, 0.32, 0.26),
996 PbrMaterial::neon(Color::hex(0xFF1744), 3.8),
997 PbrMaterial::neon(Color::hex(0xFFF6DC), 3.6),
998 PbrMaterial::dielectric(Color::hex(0x04060A), 0.96),
999 PbrMaterial::neon(Color::hex(0xFF9100), 2.2),
1000 ];
1001 let slot_body: u16 = 0;
1002 let slot_glass: u16 = 1;
1003 let slot_tire: u16 = 2;
1004 let slot_chrome: u16 = 3;
1005 let slot_carbon: u16 = 4;
1006 let slot_taillight: u16 = 5;
1007 let slot_headlight: u16 = 6;
1008 let slot_underbody: u16 = 7;
1009 let slot_amber: u16 = 8;
1010 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(960);
1011 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(340);
1012 let mut tri_materials: Vec<u16> = Vec::with_capacity(340);
1013 Self::push_box_part(
1014 &mut vertices,
1015 &mut indices,
1016 &mut tri_materials,
1017 Vec3::new(0.0, 0.14, 0.0),
1018 Vec3::new(2.06, 0.20, 4.46),
1019 slot_underbody,
1020 );
1021 Self::push_box_part(
1022 &mut vertices,
1023 &mut indices,
1024 &mut tri_materials,
1025 Vec3::new(0.0, 0.22, -2.28),
1026 Vec3::new(2.10, 0.09, 0.36),
1027 slot_carbon,
1028 );
1029 for skirt_side in [-1.0_f32, 1.0_f32] {
1030 Self::push_box_part(
1031 &mut vertices,
1032 &mut indices,
1033 &mut tri_materials,
1034 Vec3::new(skirt_side * 1.12, 0.24, 0.02),
1035 Vec3::new(0.14, 0.14, 2.04),
1036 slot_carbon,
1037 );
1038 }
1039 let front_bot: [Vec3; 4] = [
1040 Vec3::new(-1.14, 0.24, -0.78),
1041 Vec3::new(1.14, 0.24, -0.78),
1042 Vec3::new(0.98, 0.26, -2.38),
1043 Vec3::new(-0.98, 0.26, -2.38),
1044 ];
1045 let front_top: [Vec3; 4] = [
1046 Vec3::new(-1.04, 0.90, -0.78),
1047 Vec3::new(1.04, 0.90, -0.78),
1048 Vec3::new(0.84, 0.60, -2.32),
1049 Vec3::new(-0.84, 0.60, -2.32),
1050 ];
1051 Self::push_tapered_prism(
1052 &mut vertices,
1053 &mut indices,
1054 &mut tri_materials,
1055 front_bot,
1056 front_top,
1057 [
1058 slot_body,
1059 slot_body,
1060 slot_body,
1061 slot_body,
1062 slot_body,
1063 slot_underbody,
1064 ],
1065 );
1066 let mid_bot: [Vec3; 4] = [
1067 Vec3::new(-1.06, 0.24, 1.04),
1068 Vec3::new(1.06, 0.24, 1.04),
1069 Vec3::new(1.04, 0.24, -0.82),
1070 Vec3::new(-1.04, 0.24, -0.82),
1071 ];
1072 let mid_top: [Vec3; 4] = [
1073 Vec3::new(-1.04, 0.96, 1.04),
1074 Vec3::new(1.04, 0.96, 1.04),
1075 Vec3::new(1.00, 0.89, -0.82),
1076 Vec3::new(-1.00, 0.89, -0.82),
1077 ];
1078 Self::push_tapered_prism(
1079 &mut vertices,
1080 &mut indices,
1081 &mut tri_materials,
1082 mid_bot,
1083 mid_top,
1084 [
1085 slot_body,
1086 slot_body,
1087 slot_body,
1088 slot_body,
1089 slot_body,
1090 slot_underbody,
1091 ],
1092 );
1093 let rear_bot: [Vec3; 4] = [
1094 Vec3::new(-1.12, 0.36, 2.34),
1095 Vec3::new(1.12, 0.36, 2.34),
1096 Vec3::new(1.18, 0.26, 1.04),
1097 Vec3::new(-1.18, 0.26, 1.04),
1098 ];
1099 let rear_top: [Vec3; 4] = [
1100 Vec3::new(-1.06, 1.02, 2.24),
1101 Vec3::new(1.06, 1.02, 2.24),
1102 Vec3::new(1.14, 0.98, 1.04),
1103 Vec3::new(-1.14, 0.98, 1.04),
1104 ];
1105 Self::push_tapered_prism(
1106 &mut vertices,
1107 &mut indices,
1108 &mut tri_materials,
1109 rear_bot,
1110 rear_top,
1111 [
1112 slot_carbon,
1113 slot_body,
1114 slot_body,
1115 slot_body,
1116 slot_body,
1117 slot_underbody,
1118 ],
1119 );
1120 for fender_side in [-1.0_f32, 1.0_f32] {
1121 for (fender_z, flare_w) in [(-1.42_f32, 1.18_f32), (1.44_f32, 1.24_f32)] {
1122 let x_in: f32 = fender_side * 0.94;
1123 let x_out_lo: f32 = fender_side * flare_w;
1124 let x_out_hi: f32 = fender_side * (flare_w - 0.12);
1125 let (xa, xb): (f32, f32) = if fender_side > 0.0 {
1126 (x_in, x_out_lo)
1127 } else {
1128 (x_out_lo, x_in)
1129 };
1130 let (ta, tb): (f32, f32) = if fender_side > 0.0 {
1131 (x_in, x_out_hi)
1132 } else {
1133 (x_out_hi, x_in)
1134 };
1135 let arch_bot: [Vec3; 4] = [
1136 Vec3::new(xa, 0.62, fender_z + 0.56),
1137 Vec3::new(xb, 0.62, fender_z + 0.56),
1138 Vec3::new(xb, 0.62, fender_z - 0.56),
1139 Vec3::new(xa, 0.62, fender_z - 0.56),
1140 ];
1141 let arch_top: [Vec3; 4] = [
1142 Vec3::new(ta, 0.98, fender_z + 0.42),
1143 Vec3::new(tb, 0.98, fender_z + 0.42),
1144 Vec3::new(tb, 0.98, fender_z - 0.42),
1145 Vec3::new(ta, 0.98, fender_z - 0.42),
1146 ];
1147 Self::push_tapered_prism(
1148 &mut vertices,
1149 &mut indices,
1150 &mut tri_materials,
1151 arch_bot,
1152 arch_top,
1153 [
1154 slot_body,
1155 slot_body,
1156 slot_body,
1157 slot_body,
1158 slot_body,
1159 slot_underbody,
1160 ],
1161 );
1162 Self::push_box_part(
1163 &mut vertices,
1164 &mut indices,
1165 &mut tri_materials,
1166 Vec3::new(fender_side * 0.92, 0.44, fender_z),
1167 Vec3::new(0.28, 0.56, 0.88),
1168 slot_underbody,
1169 );
1170 }
1171 Self::push_box_part(
1172 &mut vertices,
1173 &mut indices,
1174 &mut tri_materials,
1175 Vec3::new(fender_side * 1.02, 1.02, -0.46),
1176 Vec3::new(0.20, 0.09, 0.16),
1177 slot_carbon,
1178 );
1179 }
1180 let cabin_bot: [Vec3; 4] = [
1181 Vec3::new(-0.92, 0.96, 1.56),
1182 Vec3::new(0.92, 0.96, 1.56),
1183 Vec3::new(0.90, 0.88, -0.82),
1184 Vec3::new(-0.90, 0.88, -0.82),
1185 ];
1186 let cabin_top: [Vec3; 4] = [
1187 Vec3::new(-0.68, 1.48, 0.74),
1188 Vec3::new(0.68, 1.48, 0.74),
1189 Vec3::new(0.68, 1.45, -0.14),
1190 Vec3::new(-0.68, 1.45, -0.14),
1191 ];
1192 Self::push_tapered_prism(
1193 &mut vertices,
1194 &mut indices,
1195 &mut tri_materials,
1196 cabin_bot,
1197 cabin_top,
1198 [
1199 slot_glass,
1200 slot_glass,
1201 slot_glass,
1202 slot_glass,
1203 slot_body,
1204 slot_underbody,
1205 ],
1206 );
1207 let roof_bot: [Vec3; 4] = [
1208 Vec3::new(-0.66, 1.488, 0.75),
1209 Vec3::new(0.66, 1.488, 0.75),
1210 Vec3::new(0.66, 1.458, -0.15),
1211 Vec3::new(-0.66, 1.458, -0.15),
1212 ];
1213 let roof_top: [Vec3; 4] = [
1214 Vec3::new(-0.56, 1.545, 0.65),
1215 Vec3::new(0.56, 1.545, 0.65),
1216 Vec3::new(0.56, 1.525, -0.05),
1217 Vec3::new(-0.56, 1.525, -0.05),
1218 ];
1219 Self::push_tapered_prism(
1220 &mut vertices,
1221 &mut indices,
1222 &mut tri_materials,
1223 roof_bot,
1224 roof_top,
1225 [slot_body; 6],
1226 );
1227 Self::push_box_part(
1228 &mut vertices,
1229 &mut indices,
1230 &mut tri_materials,
1231 Vec3::new(0.0, 0.78, 2.34),
1232 Vec3::new(1.94, 0.11, 0.08),
1233 slot_taillight,
1234 );
1235 for tail_side in [-1.0_f32, 1.0_f32] {
1236 Self::push_box_part(
1237 &mut vertices,
1238 &mut indices,
1239 &mut tri_materials,
1240 Vec3::new(tail_side * 0.76, 0.78, 2.36),
1241 Vec3::new(0.42, 0.17, 0.08),
1242 slot_taillight,
1243 );
1244 Self::push_box_part(
1245 &mut vertices,
1246 &mut indices,
1247 &mut tri_materials,
1248 Vec3::new(tail_side * 0.72, 0.56, -2.35),
1249 Vec3::new(0.42, 0.13, 0.10),
1250 slot_headlight,
1251 );
1252 }
1253 Self::push_box_part(
1254 &mut vertices,
1255 &mut indices,
1256 &mut tri_materials,
1257 Vec3::new(0.0, 0.42, -2.36),
1258 Vec3::new(1.26, 0.18, 0.08),
1259 slot_carbon,
1260 );
1261 Self::push_box_part(
1262 &mut vertices,
1263 &mut indices,
1264 &mut tri_materials,
1265 Vec3::new(0.0, 0.30, 2.32),
1266 Vec3::new(1.74, 0.24, 0.24),
1267 slot_carbon,
1268 );
1269 for fin_x in [-0.54_f32, -0.18_f32, 0.18_f32, 0.54_f32] {
1270 Self::push_box_part(
1271 &mut vertices,
1272 &mut indices,
1273 &mut tri_materials,
1274 Vec3::new(fin_x, 0.28, 2.40),
1275 Vec3::new(0.06, 0.22, 0.16),
1276 slot_carbon,
1277 );
1278 }
1279 for pipe_x in [-0.74_f32, -0.56_f32, 0.56_f32, 0.74_f32] {
1280 Self::push_box_part(
1281 &mut vertices,
1282 &mut indices,
1283 &mut tri_materials,
1284 Vec3::new(pipe_x, 0.32, 2.40),
1285 Vec3::new(0.11, 0.11, 0.14),
1286 slot_chrome,
1287 );
1288 Self::push_box_part(
1289 &mut vertices,
1290 &mut indices,
1291 &mut tri_materials,
1292 Vec3::new(pipe_x, 0.32, 2.46),
1293 Vec3::new(0.06, 0.06, 0.04),
1294 slot_amber,
1295 );
1296 }
1297 Self::push_box_part(
1298 &mut vertices,
1299 &mut indices,
1300 &mut tri_materials,
1301 Vec3::new(0.0, 1.29, 2.12),
1302 Vec3::new(2.04, 0.06, 0.38),
1303 slot_carbon,
1304 );
1305 for wing_side in [-1.0_f32, 1.0_f32] {
1306 Self::push_box_part(
1307 &mut vertices,
1308 &mut indices,
1309 &mut tri_materials,
1310 Vec3::new(wing_side * 1.02, 1.28, 2.12),
1311 Vec3::new(0.05, 0.14, 0.42),
1312 slot_carbon,
1313 );
1314 Self::push_box_part(
1315 &mut vertices,
1316 &mut indices,
1317 &mut tri_materials,
1318 Vec3::new(wing_side * 0.56, 1.14, 2.06),
1319 Vec3::new(0.05, 0.28, 0.18),
1320 slot_carbon,
1321 );
1322 }
1323 let wheel_specs: [(f32, f32, f32, f32, f32); 4] = [
1324 (-1.04, -1.42, 0.35, 0.24, 0.34),
1325 (1.04, -1.42, 0.35, 0.24, 0.34),
1326 (-1.06, 1.44, 0.37, 0.25, 0.44),
1327 (1.06, 1.44, 0.37, 0.25, 0.44),
1328 ];
1329 for (wheel_x, wheel_z, tire_r, rim_r, tire_w) in wheel_specs.into_iter() {
1330 Self::push_wheel_assembly(
1331 &mut vertices,
1332 &mut indices,
1333 &mut tri_materials,
1334 Vec3::new(wheel_x, tire_r, wheel_z),
1335 (tire_r, rim_r, tire_w),
1336 (slot_tire, slot_chrome),
1337 );
1338 }
1339 let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
1340 mesh.set_sub_materials(sub_materials);
1341 mesh.set_tri_materials(tri_materials);
1342 mesh.set_is_closed(true);
1343 mesh
1344 }
1345
1346 #[must_use]
1356 pub fn palm_tree(name: &str) -> Self {
1357 let bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
1358 let frond_top_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x227848), 0.05, 0.56, 0.08);
1359 let frond_under_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x134A2D), 0.04, 0.68, 0.05);
1360 let sub_materials: Vec<PbrMaterial> = vec![frond_top_mat, frond_under_mat];
1361 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(520);
1362 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(260);
1363 let mut tri_materials: Vec<u16> = Vec::with_capacity(260);
1364 let ring_specs: [(f32, f32, f32, f32); 5] = [
1365 (0.0, 0.0, 0.0, 0.30),
1366 (1.9, 0.14, 0.05, 0.25),
1367 (3.9, 0.32, 0.08, 0.21),
1368 (5.8, 0.44, 0.06, 0.17),
1369 (7.5, 0.48, 0.02, 0.14),
1370 ];
1371 let trunk_step: f32 = (2.0 * PI) / (MESH_PALM_TRUNK_SEGMENTS as f32);
1372 for seg_idx in 0..4usize {
1373 let (y0, ox0, oz0, r0): (f32, f32, f32, f32) = ring_specs[seg_idx];
1374 let (y1, ox1, oz1, r1): (f32, f32, f32, f32) = ring_specs[seg_idx + 1];
1375 for side_idx in 0..MESH_PALM_TRUNK_SEGMENTS {
1376 let a0: f32 = (side_idx as f32) * trunk_step;
1377 let a1: f32 = ((side_idx + 1) as f32) * trunk_step;
1378 let (s0, c0): (f32, f32) = a0.sin_cos();
1379 let (s1, c1): (f32, f32) = a1.sin_cos();
1380 let p0: Vec3 = Vec3::new(ox0 + c0 * r0, y0, oz0 + s0 * r0);
1381 let p1: Vec3 = Vec3::new(ox0 + c1 * r0, y0, oz0 + s1 * r0);
1382 let p2: Vec3 = Vec3::new(ox1 + c1 * r1, y1, oz1 + s1 * r1);
1383 let p3: Vec3 = Vec3::new(ox1 + c0 * r1, y1, oz1 + s0 * r1);
1384 Self::push_flat_quad(
1385 &mut vertices,
1386 &mut indices,
1387 &mut tri_materials,
1388 [p0, p1, p2, p3],
1389 0,
1390 );
1391 }
1392 }
1393 let crown: Vec3 = Vec3::new(0.48, 7.45, 0.02);
1394 let frond_step: f32 = (2.0 * PI) / (MESH_PALM_FROND_COUNT as f32);
1395 for tier_idx in 0..2usize {
1396 let tier_count: usize = if tier_idx == 0 {
1397 MESH_PALM_FROND_COUNT
1398 } else {
1399 5
1400 };
1401 let tier_step: f32 = if tier_idx == 0 {
1402 frond_step
1403 } else {
1404 (2.0 * PI) / 5.0
1405 };
1406 let tier_yaw_off: f32 = if tier_idx == 0 { 0.25 } else { 0.62 };
1407 let tier_origin: Vec3 = crown.add(Vec3::new(0.0, (tier_idx as f32) * 0.22, 0.0));
1408 for frond_idx in 0..tier_count {
1409 let yaw: f32 = (frond_idx as f32) * tier_step + tier_yaw_off;
1410 let (sy, cy): (f32, f32) = yaw.sin_cos();
1411 let dir: Vec3 = Vec3::new(cy, 0.0, sy);
1412 let right: Vec3 = Vec3::new(-sy, 0.0, cy);
1413 let reach: f32 = if tier_idx == 0 {
1414 if frond_idx % 2 == 0 { 2.85 } else { 2.45 }
1415 } else {
1416 1.85
1417 };
1418 let lift: f32 = if tier_idx == 0 { 0.48 } else { 0.92 };
1419 let drop_tip: f32 = if tier_idx == 0 { -1.18 } else { -0.18 };
1420 let p_mid: Vec3 = tier_origin
1421 .add(dir.scale(reach * 0.44))
1422 .add(Vec3::new(0.0, lift, 0.0));
1423 let p_arch: Vec3 = tier_origin.add(dir.scale(reach * 0.78)).add(Vec3::new(
1424 0.0,
1425 lift * 0.15 - 0.12,
1426 0.0,
1427 ));
1428 let p_tip: Vec3 = tier_origin
1429 .add(dir.scale(reach))
1430 .add(Vec3::new(0.0, drop_tip, 0.0));
1431 let w_mid: Vec3 = right.scale(if tier_idx == 0 { 0.34 } else { 0.26 });
1432 let w_arch: Vec3 = right.scale(if tier_idx == 0 { 0.24 } else { 0.18 });
1433 let sag_mid: Vec3 = Vec3::new(0.0, -0.16, 0.0);
1434 let sag_arch: Vec3 = Vec3::new(0.0, -0.20, 0.0);
1435 let mid_l: Vec3 = p_mid.sub(w_mid).add(sag_mid);
1436 let mid_r: Vec3 = p_mid.add(w_mid).add(sag_mid);
1437 let arch_l: Vec3 = p_arch.sub(w_arch).add(sag_arch);
1438 let arch_r: Vec3 = p_arch.add(w_arch).add(sag_arch);
1439 Self::push_flat_tri(
1440 &mut vertices,
1441 &mut indices,
1442 &mut tri_materials,
1443 (tier_origin, p_mid, mid_l),
1444 1,
1445 );
1446 Self::push_flat_tri(
1447 &mut vertices,
1448 &mut indices,
1449 &mut tri_materials,
1450 (tier_origin, mid_r, p_mid),
1451 1,
1452 );
1453 Self::push_flat_tri(
1454 &mut vertices,
1455 &mut indices,
1456 &mut tri_materials,
1457 (tier_origin, mid_l, p_mid),
1458 2,
1459 );
1460 Self::push_flat_tri(
1461 &mut vertices,
1462 &mut indices,
1463 &mut tri_materials,
1464 (tier_origin, p_mid, mid_r),
1465 2,
1466 );
1467 Self::push_flat_quad(
1468 &mut vertices,
1469 &mut indices,
1470 &mut tri_materials,
1471 [mid_l, p_mid, p_arch, arch_l],
1472 1,
1473 );
1474 Self::push_flat_quad(
1475 &mut vertices,
1476 &mut indices,
1477 &mut tri_materials,
1478 [p_mid, mid_r, arch_r, p_arch],
1479 1,
1480 );
1481 Self::push_flat_quad(
1482 &mut vertices,
1483 &mut indices,
1484 &mut tri_materials,
1485 [arch_l, p_arch, p_mid, mid_l],
1486 2,
1487 );
1488 Self::push_flat_quad(
1489 &mut vertices,
1490 &mut indices,
1491 &mut tri_materials,
1492 [p_arch, arch_r, mid_r, p_mid],
1493 2,
1494 );
1495 Self::push_flat_tri(
1496 &mut vertices,
1497 &mut indices,
1498 &mut tri_materials,
1499 (arch_l, p_arch, p_tip),
1500 1,
1501 );
1502 Self::push_flat_tri(
1503 &mut vertices,
1504 &mut indices,
1505 &mut tri_materials,
1506 (p_arch, arch_r, p_tip),
1507 1,
1508 );
1509 Self::push_flat_tri(
1510 &mut vertices,
1511 &mut indices,
1512 &mut tri_materials,
1513 (p_arch, arch_l, p_tip),
1514 2,
1515 );
1516 Self::push_flat_tri(
1517 &mut vertices,
1518 &mut indices,
1519 &mut tri_materials,
1520 (arch_r, p_arch, p_tip),
1521 2,
1522 );
1523 }
1524 }
1525 let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, bark_mat);
1526 mesh.set_sub_materials(sub_materials);
1527 mesh.set_tri_materials(tri_materials);
1528 mesh.set_is_closed(false);
1529 mesh
1530 }
1531
1532 #[must_use]
1542 pub fn from_box_desc(desc: &BoxMeshDesc) -> Self {
1543 let size: Vec3 = desc.get_size();
1544 Self::box_mesh(
1545 desc.get_name(),
1546 size.get_x(),
1547 size.get_y(),
1548 size.get_z(),
1549 desc.get_ground_pivot(),
1550 desc.get_material(),
1551 )
1552 }
1553
1554 #[must_use]
1564 pub fn from_ground_desc(desc: &GroundPlaneDesc) -> Self {
1565 Self::ground_plane(
1566 desc.get_name(),
1567 desc.get_width(),
1568 desc.get_depth(),
1569 desc.get_subdivisions(),
1570 desc.get_material(),
1571 )
1572 }
1573
1574 #[must_use]
1585 pub fn build_lod_proxy(&self, suffix: &str) -> Self {
1586 let blue_val: AxisAlignedBox3D = self.get_bounds();
1587 let size: Vec3 = blue_val.get_max().sub(blue_val.get_min());
1588 let center: Vec3 = blue_val.center();
1589 let mut proxy: Self = Self::box_mesh(
1590 &format!("{}_{suffix}", self.get_name()),
1591 size.get_x().max(0.2),
1592 size.get_y().max(0.2),
1593 size.get_z().max(0.2),
1594 false,
1595 self.get_material(),
1596 );
1597 for item_val in proxy.get_mut_vertices().iter_mut() {
1598 item_val.set_position(item_val.get_position().add(center));
1599 }
1600 proxy.set_bounds(blue_val);
1601 let meshlets: Vec<Meshlet3D> =
1602 Self::build_meshlets_from_parts(proxy.get_vertices(), proxy.get_indices());
1603 proxy.set_meshlets(meshlets);
1604 proxy
1605 }
1606
1607 #[must_use]
1618 pub fn build_mid_lod(&self, suffix: &str) -> Self {
1619 let verts: &[Vertex3D] = self.get_vertices().as_slice();
1620 let tris: &[[u32; 3]] = self.get_indices().as_slice();
1621 if tris.len() <= 24 {
1622 return self.build_lod_proxy(suffix);
1623 }
1624 let mut scored: Vec<(f32, [u32; 3], u16)> = Vec::with_capacity(tris.len());
1625 let default_mat: PbrMaterial = self.get_material();
1626 for (tri_idx, tri) in tris.iter().copied().enumerate() {
1627 let (i0, i1, i2): (usize, usize, usize) =
1628 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1629 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1630 let p0: Vec3 = verts[i0].get_position();
1631 let p1: Vec3 = verts[i1].get_position();
1632 let p2: Vec3 = verts[i2].get_position();
1633 let area2: f32 = p1.sub(p0).cross(p2.sub(p0)).length_sq();
1634 let (resolved_mat, slot): (PbrMaterial, u16) =
1635 self.resolve_triangle_material(tri_idx, default_mat);
1636 let emissive_boost: f32 = if resolved_mat.get_emissive().length_sq() > 0.25 {
1637 8.0
1638 } else {
1639 1.0
1640 };
1641 scored.push((area2 * emissive_boost, tri, slot));
1642 }
1643 }
1644 scored.sort_unstable_by(
1645 |alpha_val: &(f32, [u32; 3], u16), blue_val: &(f32, [u32; 3], u16)| {
1646 blue_val.0.total_cmp(&alpha_val.0)
1647 },
1648 );
1649 let keep: usize = (scored.len() / 2).max(12);
1650 let mut reduced: Vec<[u32; 3]> = Vec::with_capacity(keep);
1651 let mut reduced_slots: Vec<u16> = if self.get_tri_materials().is_empty() {
1652 Vec::new()
1653 } else {
1654 Vec::with_capacity(keep)
1655 };
1656 for (_, tri, slot) in scored.into_iter().take(keep) {
1657 reduced.push(tri);
1658 if !self.get_tri_materials().is_empty() {
1659 reduced_slots.push(slot);
1660 }
1661 }
1662 let mut mid_mesh: Self = Self::from_parts(
1663 format!("{}_{suffix}", self.get_name()),
1664 self.get_vertices().clone(),
1665 reduced,
1666 self.get_material(),
1667 );
1668 if !reduced_slots.is_empty() {
1669 mid_mesh.set_sub_materials(self.get_sub_materials().clone());
1670 mid_mesh.set_tri_materials(reduced_slots);
1671 }
1672 mid_mesh.set_is_closed(self.get_is_closed());
1673 mid_mesh
1674 }
1675}
1676
1677impl MeshLodChain {
1679 #[must_use]
1689 pub fn from_mesh(mesh: Mesh3D) -> Self {
1690 let tri_count: usize = mesh.get_indices().len();
1691 if tri_count > 32 {
1692 let lod1: Mesh3D = mesh.build_mid_lod(MESH_LOD1_SUFFIX);
1693 let lod2: Mesh3D = mesh.build_lod_proxy(MESH_LOD2_SUFFIX);
1694 Self {
1695 levels: vec![mesh, lod1, lod2],
1696 }
1697 } else if tri_count > 16 {
1698 let lod1: Mesh3D = mesh.build_lod_proxy(MESH_LOD1_SUFFIX);
1699 Self {
1700 levels: vec![mesh, lod1],
1701 }
1702 } else {
1703 let clone_lod1: Mesh3D = mesh.clone();
1704 Self {
1705 levels: vec![mesh, clone_lod1],
1706 }
1707 }
1708 }
1709
1710 #[must_use]
1722 pub fn select(&self, distance: f32, lod_bias: f32) -> (&Mesh3D, usize) {
1723 let levels: &[Mesh3D] = self.get_levels().as_slice();
1724 let effective_dist: f32 = distance * lod_bias.max(0.25);
1725 if levels.len() > 2 && effective_dist > 135.0 {
1726 (&levels[2], 2)
1727 } else if levels.len() > 1 && effective_dist > 78.0 {
1728 (&levels[1], 1)
1729 } else {
1730 (&levels[0], 0)
1731 }
1732 }
1733
1734 #[must_use]
1748 pub fn select_screen_error(
1749 &self,
1750 distance: f32,
1751 bounds_radius: f32,
1752 focal_px: f32,
1753 lod_bias: f32,
1754 ) -> (&Mesh3D, usize) {
1755 let levels: &[Mesh3D] = self.get_levels().as_slice();
1756 let safe_dist: f32 = distance.max(0.5);
1757 let projected_px: f32 =
1758 (bounds_radius.max(0.2) * focal_px) / (safe_dist * lod_bias.max(0.25));
1759 if levels.len() > 2 && projected_px < 22.0 {
1760 (&levels[2], 2)
1761 } else if levels.len() > 1 && projected_px < 58.0 {
1762 (&levels[1], 1)
1763 } else {
1764 (&levels[0], 0)
1765 }
1766 }
1767}
1768
1769impl ModelImporter3D {
1771 pub fn import(
1783 format: ModelFormat,
1784 source: &str,
1785 fallback_material: PbrMaterial,
1786 ) -> Result<ImportedModel3D, String> {
1787 match format {
1788 ModelFormat::Obj => Self::parse_obj(source, fallback_material),
1789 ModelFormat::GltfJson => Self::parse_gltf_json(source, fallback_material),
1790 }
1791 }
1792
1793 pub fn parse_obj(source: &str, material: PbrMaterial) -> Result<ImportedModel3D, String> {
1804 let mut positions: Vec<Vec3> = Vec::new();
1805 let mut normals: Vec<Vec3> = Vec::new();
1806 let mut vertices: Vec<Vertex3D> = Vec::new();
1807 let mut indices: Vec<[u32; 3]> = Vec::new();
1808 let mut model_name: String = MESH_OBJ_DEFAULT_NAME.to_string();
1809 for raw_line in source.lines() {
1810 let line: &str = raw_line.trim();
1811 if line.is_empty() || line.starts_with('#') {
1812 continue;
1813 }
1814 let parts: Vec<&str> = line.split_whitespace().collect();
1815 if parts.is_empty() {
1816 continue;
1817 }
1818 match parts[0] {
1819 "o" | "g" if parts.len() >= 2 => {
1820 model_name = parts[1].to_string();
1821 }
1822 "v" if parts.len() >= 4 => {
1823 let pos_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
1824 let pos_y: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
1825 let pos_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
1826 positions.push(Vec3::new(pos_x, pos_y, pos_z));
1827 }
1828 "vn" if parts.len() >= 4 => {
1829 let coord_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
1830 let coord_y: f32 = parts[2].parse::<f32>().unwrap_or(1.0);
1831 let coord_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
1832 normals.push(Vec3::new(coord_x, coord_y, coord_z).normalize());
1833 }
1834 "f" if parts.len() >= 4 => {
1835 let mut face_verts: Vec<(Vec3, Option<Vec3>)> =
1836 Vec::with_capacity(parts.len() - 1);
1837 for token in parts.iter().skip(1) {
1838 let comps: Vec<&str> = token.split('/').collect();
1839 let v_idx_raw: i32 = comps
1840 .first()
1841 .and_then(|source_val: &&str| source_val.parse::<i32>().ok())
1842 .unwrap_or(0);
1843 let p_opt: Option<Vec3> = if v_idx_raw > 0 {
1844 positions.get((v_idx_raw - 1) as usize).copied()
1845 } else if v_idx_raw < 0 {
1846 let idx: isize = (positions.len() as isize) + (v_idx_raw as isize);
1847 if idx >= 0 {
1848 positions.get(idx as usize).copied()
1849 } else {
1850 None
1851 }
1852 } else {
1853 None
1854 };
1855 let n_opt: Option<Vec3> = comps
1856 .get(2)
1857 .and_then(|scale_val: &&str| scale_val.parse::<i32>().ok())
1858 .and_then(|n_raw: i32| {
1859 if n_raw > 0 {
1860 normals.get((n_raw - 1) as usize).copied()
1861 } else {
1862 None
1863 }
1864 });
1865 if let Some(pos) = p_opt {
1866 face_verts.push((pos, n_opt));
1867 }
1868 }
1869 if face_verts.len() >= 3 {
1870 for entry_index in 1..(face_verts.len() - 1) {
1871 let (p0, n0): (Vec3, Option<Vec3>) = face_verts[0];
1872 let (p1, n1): (Vec3, Option<Vec3>) = face_verts[entry_index];
1873 let (p2, n2): (Vec3, Option<Vec3>) = face_verts[entry_index + 1];
1874 let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
1875 let base: u32 = vertices.len() as u32;
1876 vertices.push(Vertex3D::new(p0, n0.unwrap_or(face_n)));
1877 vertices.push(Vertex3D::new(p1, n1.unwrap_or(face_n)));
1878 vertices.push(Vertex3D::new(p2, n2.unwrap_or(face_n)));
1879 indices.push([base, base + 1, base + 2]);
1880 }
1881 }
1882 }
1883 _ => {}
1884 }
1885 }
1886 if indices.is_empty() {
1887 return Err(ERR_OBJ_EMPTY.to_string());
1888 }
1889 let total_vertices: usize = vertices.len();
1890 let total_triangles: usize = indices.len();
1891 let mesh: Mesh3D = Mesh3D::from_parts(model_name.clone(), vertices, indices, material);
1892 Ok(ImportedModel3D {
1893 name: model_name,
1894 format: ModelFormat::Obj,
1895 meshes: vec![MeshLodChain::from_mesh(mesh)],
1896 total_vertices,
1897 total_triangles,
1898 })
1899 }
1900
1901 pub fn parse_gltf_json(
1912 source: &str,
1913 fallback_material: PbrMaterial,
1914 ) -> Result<ImportedModel3D, String> {
1915 let root: Value = from_str::<Value>(source)
1916 .ok()
1917 .ok_or_else(|| ERR_GLTF_JSON.to_string())?;
1918 let name: String = root
1919 .get(GLTF_KEY_ASSET)
1920 .and_then(|alpha_val: &Value| alpha_val.get(GLTF_KEY_GENERATOR))
1921 .and_then(Value::as_str)
1922 .unwrap_or(MESH_GLTF_DEFAULT_NAME)
1923 .to_string();
1924 let mut mat: PbrMaterial = fallback_material;
1925 if let Some(pbr) = root
1926 .get(GLTF_KEY_MATERIALS)
1927 .and_then(Value::as_array)
1928 .and_then(|arr: &Vec<Value>| arr.first())
1929 .and_then(|matrix_elems: &Value| matrix_elems.get(GLTF_KEY_PBR))
1930 {
1931 if let Some(bc) = pbr.get(GLTF_KEY_BASE_COLOR).and_then(Value::as_array)
1932 && bc.len() >= 3
1933 {
1934 let red_val: f32 = bc[0].as_f64().unwrap_or(0.8) as f32;
1935 let green_val: f32 = bc[1].as_f64().unwrap_or(0.8) as f32;
1936 let blue_val: f32 = bc[2].as_f64().unwrap_or(0.8) as f32;
1937 mat.set_base_color(Vec3::new(red_val, green_val, blue_val));
1938 }
1939 if let Some(met) = pbr.get(GLTF_KEY_METALLIC).and_then(Value::as_f64) {
1940 mat.set_metallic((met as f32).clamp(0.0, 1.0));
1941 }
1942 if let Some(rough) = pbr.get(GLTF_KEY_ROUGHNESS).and_then(Value::as_f64) {
1943 mat.set_roughness((rough as f32).clamp(0.04, 1.0));
1944 mat.set_reflectivity((1.0 - (rough as f32)).clamp(0.05, 0.95));
1945 }
1946 }
1947 let mut chains: Vec<MeshLodChain> = Vec::new();
1948 let mut total_vertices: usize = 0;
1949 let mut total_triangles: usize = 0;
1950 if let Some(meshes_arr) = root.get(GLTF_KEY_MESHES).and_then(Value::as_array) {
1951 for (m_idx, m_val) in meshes_arr.iter().enumerate() {
1952 let mesh_name: String = m_val
1953 .get(GLTF_KEY_NAME)
1954 .and_then(Value::as_str)
1955 .map(str::to_string)
1956 .unwrap_or_else(|| format!("{name}_mesh_{m_idx}"));
1957 let Some(prims) = m_val.get(GLTF_KEY_PRIMITIVES).and_then(Value::as_array) else {
1958 continue;
1959 };
1960 for prim in prims.iter() {
1961 let extras: &Value = prim.get(GLTF_KEY_EXTRAS).unwrap_or(prim);
1962 let pos_vals: Vec<f32> = extras
1963 .get(GLTF_KEY_POSITIONS)
1964 .and_then(Value::as_array)
1965 .map(|first_val: &Vec<Value>| {
1966 first_val
1967 .iter()
1968 .filter_map(|item_val: &Value| {
1969 item_val.as_f64().map(|item_count: f64| item_count as f32)
1970 })
1971 .collect()
1972 })
1973 .unwrap_or_default();
1974 let idx_vals: Vec<u32> = extras
1975 .get(GLTF_KEY_INDICES)
1976 .and_then(Value::as_array)
1977 .map(|area_val: &Vec<Value>| {
1978 area_val
1979 .iter()
1980 .filter_map(|tex_v: &Value| {
1981 tex_v.as_u64().map(|node_entry: u64| node_entry as u32)
1982 })
1983 .collect()
1984 })
1985 .unwrap_or_default();
1986 let mut raw_pts: Vec<Vec3> = Vec::new();
1987 for chunk in pos_vals.as_chunks::<3>().0 {
1988 raw_pts.push(Vec3::new(chunk[0], chunk[1], chunk[2]));
1989 }
1990 let mut verts: Vec<Vertex3D> = Vec::new();
1991 let mut tris: Vec<[u32; 3]> = Vec::new();
1992 for tri in idx_vals.as_chunks::<3>().0 {
1993 let (i0, i1, i2): (usize, usize, usize) =
1994 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1995 if i0 < raw_pts.len() && i1 < raw_pts.len() && i2 < raw_pts.len() {
1996 let p0: Vec3 = raw_pts[i0];
1997 let p1: Vec3 = raw_pts[i1];
1998 let p2: Vec3 = raw_pts[i2];
1999 let vec_value: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
2000 let base: u32 = verts.len() as u32;
2001 verts.push(Vertex3D::new(p0, vec_value));
2002 verts.push(Vertex3D::new(p1, vec_value));
2003 verts.push(Vertex3D::new(p2, vec_value));
2004 tris.push([base, base + 1, base + 2]);
2005 }
2006 }
2007 if !tris.is_empty() {
2008 total_vertices += verts.len();
2009 total_triangles += tris.len();
2010 let mesh: Mesh3D = Mesh3D::from_parts(mesh_name.clone(), verts, tris, mat);
2011 chains.push(MeshLodChain::from_mesh(mesh));
2012 }
2013 }
2014 }
2015 }
2016 if chains.is_empty() {
2017 return Err(ERR_GLTF_EMPTY.to_string());
2018 }
2019 Ok(ImportedModel3D {
2020 name,
2021 format: ModelFormat::GltfJson,
2022 meshes: chains,
2023 total_vertices,
2024 total_triangles,
2025 })
2026 }
2027}