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 meshlets,
430 is_closed: false,
431 }
432 }
433
434 #[must_use]
449 pub fn box_mesh(
450 name: &str,
451 width_val: f32,
452 height_val: f32,
453 delta_val: f32,
454 ground_pivot: bool,
455 material: PbrMaterial,
456 ) -> Self {
457 let hx: f32 = width_val * 0.5;
458 let hz: f32 = delta_val * 0.5;
459 let y0: f32 = if ground_pivot { 0.0 } else { -height_val * 0.5 };
460 let y1: f32 = if ground_pivot {
461 height_val
462 } else {
463 height_val * 0.5
464 };
465 let faces: [([Vec3; 4], Vec3); 6] = [
466 (
467 [
468 Vec3::new(-hx, y0, hz),
469 Vec3::new(hx, y0, hz),
470 Vec3::new(hx, y1, hz),
471 Vec3::new(-hx, y1, hz),
472 ],
473 Vec3::new(0.0, 0.0, 1.0),
474 ),
475 (
476 [
477 Vec3::new(hx, y0, -hz),
478 Vec3::new(-hx, y0, -hz),
479 Vec3::new(-hx, y1, -hz),
480 Vec3::new(hx, y1, -hz),
481 ],
482 Vec3::new(0.0, 0.0, -1.0),
483 ),
484 (
485 [
486 Vec3::new(hx, y0, hz),
487 Vec3::new(hx, y0, -hz),
488 Vec3::new(hx, y1, -hz),
489 Vec3::new(hx, y1, hz),
490 ],
491 Vec3::new(1.0, 0.0, 0.0),
492 ),
493 (
494 [
495 Vec3::new(-hx, y0, -hz),
496 Vec3::new(-hx, y0, hz),
497 Vec3::new(-hx, y1, hz),
498 Vec3::new(-hx, y1, -hz),
499 ],
500 Vec3::new(-1.0, 0.0, 0.0),
501 ),
502 (
503 [
504 Vec3::new(-hx, y1, hz),
505 Vec3::new(hx, y1, hz),
506 Vec3::new(hx, y1, -hz),
507 Vec3::new(-hx, y1, -hz),
508 ],
509 Vec3::new(0.0, 1.0, 0.0),
510 ),
511 (
512 [
513 Vec3::new(-hx, y0, -hz),
514 Vec3::new(hx, y0, -hz),
515 Vec3::new(hx, y0, hz),
516 Vec3::new(-hx, y0, hz),
517 ],
518 Vec3::new(0.0, -1.0, 0.0),
519 ),
520 ];
521 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(24);
522 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(12);
523 for (quad, item_count) in faces.into_iter() {
524 let base: u32 = vertices.len() as u32;
525 for point_val in quad.into_iter() {
526 vertices.push(Vertex3D::new(point_val, item_count));
527 }
528 indices.push([base, base + 1, base + 2]);
529 indices.push([base, base + 2, base + 3]);
530 }
531 let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
532 mesh.set_is_closed(true);
533 mesh
534 }
535
536 #[must_use]
550 pub fn ground_plane(
551 name: &str,
552 width_val: f32,
553 delta_val: f32,
554 subdivisions: usize,
555 material: PbrMaterial,
556 ) -> Self {
557 let segs: usize = subdivisions.clamp(1, 16);
558 let mut vertices: Vec<Vertex3D> = Vec::with_capacity((segs + 1) * (segs + 1));
559 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(segs * segs * 2);
560 let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
561 for iz in 0..=segs {
562 let vz: f32 = ((iz as f32) / (segs as f32) - 0.5) * delta_val;
563 for ix in 0..=segs {
564 let vx: f32 = ((ix as f32) / (segs as f32) - 0.5) * width_val;
565 vertices.push(Vertex3D::new(Vec3::new(vx, 0.0, vz), up));
566 }
567 }
568 let stride: u32 = (segs + 1) as u32;
569 for iz in 0..segs {
570 for ix in 0..segs {
571 let i0: u32 = (iz as u32) * stride + (ix as u32);
572 let i1: u32 = i0 + 1;
573 let i2: u32 = i0 + stride;
574 let i3: u32 = i2 + 1;
575 indices.push([i0, i2, i1]);
576 indices.push([i1, i2, i3]);
577 }
578 }
579 Self::from_parts(name.to_string(), vertices, indices, material)
580 }
581
582 #[must_use]
593 pub fn sports_car(name: &str, material: PbrMaterial) -> Self {
594 let lower: Self = Self::box_mesh(MESH_CAR_LOWER, 2.2, 0.80, 4.6, true, material);
595 let cabin: Self = Self::box_mesh(MESH_CAR_CABIN, 1.82, 0.72, 2.2, true, material);
596 let wheel: Self = Self::box_mesh(MESH_CAR_WHEEL, 0.34, 0.56, 0.62, true, material);
597 let wing: Self = Self::box_mesh(MESH_CAR_WING, 2.04, 0.11, 0.42, true, material);
598 let strut: Self = Self::box_mesh(MESH_CAR_STRUT, 0.10, 0.30, 0.18, true, material);
599 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(216);
600 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(108);
601 let lower_offset: u32 = vertices.len() as u32;
602 for item_val in lower.get_vertices().iter() {
603 let vec_value: Vec3 = item_val.get_position();
604 let mut px: f32 = vec_value.get_x();
605 let mut py: f32 = vec_value.get_y();
606 let pz: f32 = vec_value.get_z();
607 let mut norm: Vec3 = item_val.get_normal();
608 if py > 0.4 {
609 if pz < 0.0 {
610 px *= 0.86;
611 py *= 0.66;
612 norm = norm.add(Vec3::new(0.0, 0.35, -0.45)).normalize();
613 } else {
614 px *= 0.98;
615 py *= 1.04;
616 norm = norm.add(Vec3::new(0.0, 0.20, 0.15)).normalize();
617 }
618 }
619 vertices.push(Vertex3D::new(Vec3::new(px, py + 0.24, pz), norm));
620 }
621 for tri in lower.get_indices().iter() {
622 indices.push([
623 tri[0] + lower_offset,
624 tri[1] + lower_offset,
625 tri[2] + lower_offset,
626 ]);
627 }
628 let cabin_offset: u32 = vertices.len() as u32;
629 for tex_v in cabin.get_vertices().iter() {
630 let direction_vec: Vec3 = tex_v.get_position();
631 let mut px: f32 = direction_vec.get_x();
632 let py: f32 = direction_vec.get_y();
633 let mut pz: f32 = direction_vec.get_z();
634 let mut norm: Vec3 = tex_v.get_normal();
635 if py > 0.35 {
636 px *= 0.76;
637 if pz < 0.0 {
638 pz += 0.46;
639 norm = norm.add(Vec3::new(0.0, 0.55, -0.50)).normalize();
640 } else {
641 pz -= 0.18;
642 norm = norm.add(Vec3::new(0.0, 0.45, 0.35)).normalize();
643 }
644 } else if pz > 0.0 {
645 pz += 0.26;
646 }
647 vertices.push(Vertex3D::new(Vec3::new(px, py + 0.98, pz + 0.06), norm));
648 }
649 for tri in cabin.get_indices().iter() {
650 indices.push([
651 tri[0] + cabin_offset,
652 tri[1] + cabin_offset,
653 tri[2] + cabin_offset,
654 ]);
655 }
656 let wing_offset: u32 = vertices.len() as u32;
657 for wing_v in wing.get_vertices().iter() {
658 let wp: Vec3 = wing_v.get_position();
659 vertices.push(Vertex3D::new(
660 Vec3::new(wp.get_x(), wp.get_y() + 1.24, wp.get_z() + 1.98),
661 wing_v.get_normal(),
662 ));
663 }
664 for tri in wing.get_indices().iter() {
665 indices.push([
666 tri[0] + wing_offset,
667 tri[1] + wing_offset,
668 tri[2] + wing_offset,
669 ]);
670 }
671 for strut_x in [-0.66_f32, 0.66_f32] {
672 let strut_off: u32 = vertices.len() as u32;
673 for sv in strut.get_vertices().iter() {
674 let sp: Vec3 = sv.get_position();
675 vertices.push(Vertex3D::new(
676 Vec3::new(sp.get_x() + strut_x, sp.get_y() + 0.98, sp.get_z() + 1.94),
677 sv.get_normal(),
678 ));
679 }
680 for tri in strut.get_indices().iter() {
681 indices.push([tri[0] + strut_off, tri[1] + strut_off, tri[2] + strut_off]);
682 }
683 }
684 let wheel_offsets: [(f32, f32); 4] =
685 [(-1.12, -1.45), (1.12, -1.45), (-1.12, 1.45), (1.12, 1.45)];
686 for (wx, wz) in wheel_offsets.into_iter() {
687 let base: u32 = vertices.len() as u32;
688 for bary_v in wheel.get_vertices().iter() {
689 let position_vec: Vec3 = bary_v.get_position();
690 vertices.push(Vertex3D::new(
691 Vec3::new(
692 position_vec.get_x() + wx,
693 position_vec.get_y() + 0.02,
694 position_vec.get_z() + wz,
695 ),
696 bary_v.get_normal(),
697 ));
698 }
699 for tri in wheel.get_indices().iter() {
700 indices.push([tri[0] + base, tri[1] + base, tri[2] + base]);
701 }
702 }
703 let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
704 mesh.set_is_closed(true);
705 mesh
706 }
707
708 #[must_use]
718 pub fn from_box_desc(desc: &BoxMeshDesc) -> Self {
719 let size: Vec3 = desc.get_size();
720 Self::box_mesh(
721 desc.get_name(),
722 size.get_x(),
723 size.get_y(),
724 size.get_z(),
725 desc.get_ground_pivot(),
726 desc.get_material(),
727 )
728 }
729
730 #[must_use]
740 pub fn from_ground_desc(desc: &GroundPlaneDesc) -> Self {
741 Self::ground_plane(
742 desc.get_name(),
743 desc.get_width(),
744 desc.get_depth(),
745 desc.get_subdivisions(),
746 desc.get_material(),
747 )
748 }
749
750 #[must_use]
761 pub fn build_lod_proxy(&self, suffix: &str) -> Self {
762 let blue_val: AxisAlignedBox3D = self.get_bounds();
763 let size: Vec3 = blue_val.get_max().sub(blue_val.get_min());
764 let center: Vec3 = blue_val.center();
765 let mut proxy: Self = Self::box_mesh(
766 &format!("{}_{suffix}", self.get_name()),
767 size.get_x().max(0.2),
768 size.get_y().max(0.2),
769 size.get_z().max(0.2),
770 false,
771 self.get_material(),
772 );
773 for item_val in proxy.get_mut_vertices().iter_mut() {
774 item_val.set_position(item_val.get_position().add(center));
775 }
776 proxy.set_bounds(blue_val);
777 let meshlets: Vec<Meshlet3D> =
778 Self::build_meshlets_from_parts(proxy.get_vertices(), proxy.get_indices());
779 proxy.set_meshlets(meshlets);
780 proxy
781 }
782
783 #[must_use]
794 pub fn build_mid_lod(&self, suffix: &str) -> Self {
795 let verts: &[Vertex3D] = self.get_vertices().as_slice();
796 let tris: &[[u32; 3]] = self.get_indices().as_slice();
797 if tris.len() <= 24 {
798 return self.build_lod_proxy(suffix);
799 }
800 let mut scored: Vec<(f32, [u32; 3])> = Vec::with_capacity(tris.len());
801 for tri in tris.iter().copied() {
802 let (i0, i1, i2): (usize, usize, usize) =
803 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
804 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
805 let p0: Vec3 = verts[i0].get_position();
806 let p1: Vec3 = verts[i1].get_position();
807 let p2: Vec3 = verts[i2].get_position();
808 let area2: f32 = p1.sub(p0).cross(p2.sub(p0)).length_sq();
809 scored.push((area2, tri));
810 }
811 }
812 scored.sort_unstable_by(|alpha_val: &(f32, [u32; 3]), blue_val: &(f32, [u32; 3])| {
813 blue_val.0.total_cmp(&alpha_val.0)
814 });
815 let keep: usize = (scored.len() / 2).max(12);
816 let reduced: Vec<[u32; 3]> = scored
817 .into_iter()
818 .take(keep)
819 .map(|(_, blend_factor): (f32, [u32; 3])| blend_factor)
820 .collect();
821 Self::from_parts(
822 format!("{}_{suffix}", self.get_name()),
823 self.get_vertices().clone(),
824 reduced,
825 self.get_material(),
826 )
827 }
828}
829
830impl MeshLodChain {
832 #[must_use]
842 pub fn from_mesh(mesh: Mesh3D) -> Self {
843 let tri_count: usize = mesh.get_indices().len();
844 if tri_count > 32 {
845 let lod1: Mesh3D = mesh.build_mid_lod(MESH_LOD1_SUFFIX);
846 let lod2: Mesh3D = mesh.build_lod_proxy(MESH_LOD2_SUFFIX);
847 Self {
848 levels: vec![mesh, lod1, lod2],
849 }
850 } else if tri_count > 16 {
851 let lod1: Mesh3D = mesh.build_lod_proxy(MESH_LOD1_SUFFIX);
852 Self {
853 levels: vec![mesh, lod1],
854 }
855 } else {
856 let clone_lod1: Mesh3D = mesh.clone();
857 Self {
858 levels: vec![mesh, clone_lod1],
859 }
860 }
861 }
862
863 #[must_use]
875 pub fn select(&self, distance: f32, lod_bias: f32) -> (&Mesh3D, usize) {
876 let levels: &[Mesh3D] = self.get_levels().as_slice();
877 let effective_dist: f32 = distance * lod_bias.max(0.25);
878 if levels.len() > 2 && effective_dist > 135.0 {
879 (&levels[2], 2)
880 } else if levels.len() > 1 && effective_dist > 78.0 {
881 (&levels[1], 1)
882 } else {
883 (&levels[0], 0)
884 }
885 }
886
887 #[must_use]
901 pub fn select_screen_error(
902 &self,
903 distance: f32,
904 bounds_radius: f32,
905 focal_px: f32,
906 lod_bias: f32,
907 ) -> (&Mesh3D, usize) {
908 let levels: &[Mesh3D] = self.get_levels().as_slice();
909 let safe_dist: f32 = distance.max(0.5);
910 let projected_px: f32 =
911 (bounds_radius.max(0.2) * focal_px) / (safe_dist * lod_bias.max(0.25));
912 if levels.len() > 2 && projected_px < 22.0 {
913 (&levels[2], 2)
914 } else if levels.len() > 1 && projected_px < 58.0 {
915 (&levels[1], 1)
916 } else {
917 (&levels[0], 0)
918 }
919 }
920}
921
922impl ModelImporter3D {
924 pub fn import(
936 format: ModelFormat,
937 source: &str,
938 fallback_material: PbrMaterial,
939 ) -> Result<ImportedModel3D, String> {
940 match format {
941 ModelFormat::Obj => Self::parse_obj(source, fallback_material),
942 ModelFormat::GltfJson => Self::parse_gltf_json(source, fallback_material),
943 }
944 }
945
946 pub fn parse_obj(source: &str, material: PbrMaterial) -> Result<ImportedModel3D, String> {
957 let mut positions: Vec<Vec3> = Vec::new();
958 let mut normals: Vec<Vec3> = Vec::new();
959 let mut vertices: Vec<Vertex3D> = Vec::new();
960 let mut indices: Vec<[u32; 3]> = Vec::new();
961 let mut model_name: String = MESH_OBJ_DEFAULT_NAME.to_string();
962 for raw_line in source.lines() {
963 let line: &str = raw_line.trim();
964 if line.is_empty() || line.starts_with('#') {
965 continue;
966 }
967 let parts: Vec<&str> = line.split_whitespace().collect();
968 if parts.is_empty() {
969 continue;
970 }
971 match parts[0] {
972 "o" | "g" if parts.len() >= 2 => {
973 model_name = parts[1].to_string();
974 }
975 "v" if parts.len() >= 4 => {
976 let pos_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
977 let pos_y: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
978 let pos_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
979 positions.push(Vec3::new(pos_x, pos_y, pos_z));
980 }
981 "vn" if parts.len() >= 4 => {
982 let coord_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
983 let coord_y: f32 = parts[2].parse::<f32>().unwrap_or(1.0);
984 let coord_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
985 normals.push(Vec3::new(coord_x, coord_y, coord_z).normalize());
986 }
987 "f" if parts.len() >= 4 => {
988 let mut face_verts: Vec<(Vec3, Option<Vec3>)> =
989 Vec::with_capacity(parts.len() - 1);
990 for token in parts.iter().skip(1) {
991 let comps: Vec<&str> = token.split('/').collect();
992 let v_idx_raw: i32 = comps
993 .first()
994 .and_then(|source_val: &&str| source_val.parse::<i32>().ok())
995 .unwrap_or(0);
996 let p_opt: Option<Vec3> = if v_idx_raw > 0 {
997 positions.get((v_idx_raw - 1) as usize).copied()
998 } else if v_idx_raw < 0 {
999 let idx: isize = (positions.len() as isize) + (v_idx_raw as isize);
1000 if idx >= 0 {
1001 positions.get(idx as usize).copied()
1002 } else {
1003 None
1004 }
1005 } else {
1006 None
1007 };
1008 let n_opt: Option<Vec3> = comps
1009 .get(2)
1010 .and_then(|scale_val: &&str| scale_val.parse::<i32>().ok())
1011 .and_then(|n_raw: i32| {
1012 if n_raw > 0 {
1013 normals.get((n_raw - 1) as usize).copied()
1014 } else {
1015 None
1016 }
1017 });
1018 if let Some(pos) = p_opt {
1019 face_verts.push((pos, n_opt));
1020 }
1021 }
1022 if face_verts.len() >= 3 {
1023 for entry_index in 1..(face_verts.len() - 1) {
1024 let (p0, n0): (Vec3, Option<Vec3>) = face_verts[0];
1025 let (p1, n1): (Vec3, Option<Vec3>) = face_verts[entry_index];
1026 let (p2, n2): (Vec3, Option<Vec3>) = face_verts[entry_index + 1];
1027 let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
1028 let base: u32 = vertices.len() as u32;
1029 vertices.push(Vertex3D::new(p0, n0.unwrap_or(face_n)));
1030 vertices.push(Vertex3D::new(p1, n1.unwrap_or(face_n)));
1031 vertices.push(Vertex3D::new(p2, n2.unwrap_or(face_n)));
1032 indices.push([base, base + 1, base + 2]);
1033 }
1034 }
1035 }
1036 _ => {}
1037 }
1038 }
1039 if indices.is_empty() {
1040 return Err(ERR_OBJ_EMPTY.to_string());
1041 }
1042 let total_vertices: usize = vertices.len();
1043 let total_triangles: usize = indices.len();
1044 let mesh: Mesh3D = Mesh3D::from_parts(model_name.clone(), vertices, indices, material);
1045 Ok(ImportedModel3D {
1046 name: model_name,
1047 format: ModelFormat::Obj,
1048 meshes: vec![MeshLodChain::from_mesh(mesh)],
1049 total_vertices,
1050 total_triangles,
1051 })
1052 }
1053
1054 pub fn parse_gltf_json(
1065 source: &str,
1066 fallback_material: PbrMaterial,
1067 ) -> Result<ImportedModel3D, String> {
1068 let root: Value = from_str::<Value>(source)
1069 .ok()
1070 .ok_or_else(|| ERR_GLTF_JSON.to_string())?;
1071 let name: String = root
1072 .get(GLTF_KEY_ASSET)
1073 .and_then(|alpha_val: &Value| alpha_val.get(GLTF_KEY_GENERATOR))
1074 .and_then(Value::as_str)
1075 .unwrap_or(MESH_GLTF_DEFAULT_NAME)
1076 .to_string();
1077 let mut mat: PbrMaterial = fallback_material;
1078 if let Some(pbr) = root
1079 .get(GLTF_KEY_MATERIALS)
1080 .and_then(Value::as_array)
1081 .and_then(|arr: &Vec<Value>| arr.first())
1082 .and_then(|matrix_elems: &Value| matrix_elems.get(GLTF_KEY_PBR))
1083 {
1084 if let Some(bc) = pbr.get(GLTF_KEY_BASE_COLOR).and_then(Value::as_array)
1085 && bc.len() >= 3
1086 {
1087 let red_val: f32 = bc[0].as_f64().unwrap_or(0.8) as f32;
1088 let green_val: f32 = bc[1].as_f64().unwrap_or(0.8) as f32;
1089 let blue_val: f32 = bc[2].as_f64().unwrap_or(0.8) as f32;
1090 mat.set_base_color(Vec3::new(red_val, green_val, blue_val));
1091 }
1092 if let Some(met) = pbr.get(GLTF_KEY_METALLIC).and_then(Value::as_f64) {
1093 mat.set_metallic((met as f32).clamp(0.0, 1.0));
1094 }
1095 if let Some(rough) = pbr.get(GLTF_KEY_ROUGHNESS).and_then(Value::as_f64) {
1096 mat.set_roughness((rough as f32).clamp(0.04, 1.0));
1097 mat.set_reflectivity((1.0 - (rough as f32)).clamp(0.05, 0.95));
1098 }
1099 }
1100 let mut chains: Vec<MeshLodChain> = Vec::new();
1101 let mut total_vertices: usize = 0;
1102 let mut total_triangles: usize = 0;
1103 if let Some(meshes_arr) = root.get(GLTF_KEY_MESHES).and_then(Value::as_array) {
1104 for (m_idx, m_val) in meshes_arr.iter().enumerate() {
1105 let mesh_name: String = m_val
1106 .get(GLTF_KEY_NAME)
1107 .and_then(Value::as_str)
1108 .map(str::to_string)
1109 .unwrap_or_else(|| format!("{name}_mesh_{m_idx}"));
1110 let Some(prims) = m_val.get(GLTF_KEY_PRIMITIVES).and_then(Value::as_array) else {
1111 continue;
1112 };
1113 for prim in prims.iter() {
1114 let extras: &Value = prim.get(GLTF_KEY_EXTRAS).unwrap_or(prim);
1115 let pos_vals: Vec<f32> = extras
1116 .get(GLTF_KEY_POSITIONS)
1117 .and_then(Value::as_array)
1118 .map(|first_val: &Vec<Value>| {
1119 first_val
1120 .iter()
1121 .filter_map(|item_val: &Value| {
1122 item_val.as_f64().map(|item_count: f64| item_count as f32)
1123 })
1124 .collect()
1125 })
1126 .unwrap_or_default();
1127 let idx_vals: Vec<u32> = extras
1128 .get(GLTF_KEY_INDICES)
1129 .and_then(Value::as_array)
1130 .map(|area_val: &Vec<Value>| {
1131 area_val
1132 .iter()
1133 .filter_map(|tex_v: &Value| {
1134 tex_v.as_u64().map(|node_entry: u64| node_entry as u32)
1135 })
1136 .collect()
1137 })
1138 .unwrap_or_default();
1139 let mut raw_pts: Vec<Vec3> = Vec::new();
1140 for chunk in pos_vals.as_chunks::<3>().0 {
1141 raw_pts.push(Vec3::new(chunk[0], chunk[1], chunk[2]));
1142 }
1143 let mut verts: Vec<Vertex3D> = Vec::new();
1144 let mut tris: Vec<[u32; 3]> = Vec::new();
1145 for tri in idx_vals.as_chunks::<3>().0 {
1146 let (i0, i1, i2): (usize, usize, usize) =
1147 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1148 if i0 < raw_pts.len() && i1 < raw_pts.len() && i2 < raw_pts.len() {
1149 let p0: Vec3 = raw_pts[i0];
1150 let p1: Vec3 = raw_pts[i1];
1151 let p2: Vec3 = raw_pts[i2];
1152 let vec_value: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
1153 let base: u32 = verts.len() as u32;
1154 verts.push(Vertex3D::new(p0, vec_value));
1155 verts.push(Vertex3D::new(p1, vec_value));
1156 verts.push(Vertex3D::new(p2, vec_value));
1157 tris.push([base, base + 1, base + 2]);
1158 }
1159 }
1160 if !tris.is_empty() {
1161 total_vertices += verts.len();
1162 total_triangles += tris.len();
1163 let mesh: Mesh3D = Mesh3D::from_parts(mesh_name.clone(), verts, tris, mat);
1164 chains.push(MeshLodChain::from_mesh(mesh));
1165 }
1166 }
1167 }
1168 }
1169 if chains.is_empty() {
1170 return Err(ERR_GLTF_EMPTY.to_string());
1171 }
1172 Ok(ImportedModel3D {
1173 name,
1174 format: ModelFormat::GltfJson,
1175 meshes: chains,
1176 total_vertices,
1177 total_triangles,
1178 })
1179 }
1180}