Skip to main content

euv_core/game/engine3d/mesh/
impl.rs

1use super::*;
2
3/// Default neutral vertex positioned at origin with `+Y` normal, `+X` tangent, and white vertex color.
4impl Default for Vertex3D {
5    /// Returns a default 64-byte `Vertex3D`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default `Vertex3D`.
10    fn default() -> Self {
11        Self::from_pos_normal(Vec3::zero(), Vec3::new(0.0, 1.0, 0.0))
12    }
13}
14
15/// Compact and full attribute constructors for `Vertex3D`.
16impl Vertex3D {
17    /// Constructs a `Vertex3D` from `position` and `normal` with identity tangent, zero UVs, and opaque white color.
18    ///
19    /// # Arguments
20    ///
21    /// - `Vec3` - Local-space 3D position.
22    /// - `Vec3` - Local-space unit surface normal.
23    ///
24    /// # Returns
25    ///
26    /// - `Self` - Constructed 64-byte vertex.
27    #[must_use]
28    pub const fn new(position: Vec3, normal: Vec3) -> Self {
29        Self::from_pos_normal(position, normal)
30    }
31
32    /// Constructs a `Vertex3D` from `position` and `normal` with default tangent, UV, and color attributes.
33    ///
34    /// # Arguments
35    ///
36    /// - `Vec3` - Local-space 3D position.
37    /// - `Vec3` - Local-space unit surface normal.
38    ///
39    /// # Returns
40    ///
41    /// - `Self` - Constructed 64-byte vertex.
42    #[must_use]
43    pub const fn from_pos_normal(position: Vec3, normal: Vec3) -> Self {
44        Self {
45            position,
46            normal,
47            tangent: [1.0, 0.0, 0.0, 1.0],
48            uv0: [0.0, 0.0],
49            uv1: [0.0, 0.0],
50            color0: [255, 255, 255, 255],
51            flags: 0,
52        }
53    }
54
55    /// Constructs a fully populated 64-byte `Vertex3D` with tangent, dual UVs, vertex color, and attribute flags.
56    ///
57    /// # Arguments
58    ///
59    /// - `Vec3` - Local-space 3D position.
60    /// - `Vec3` - Local-space unit surface normal.
61    /// - `[f32; 4]` - Tangent vector `(tx, ty, tz, handedness_sign)`.
62    /// - `[f32; 2]` - Primary UV coordinate (`TEXCOORD_0`).
63    /// - `[f32; 2]` - Secondary UV coordinate (`TEXCOORD_1`).
64    /// - `[u8; 4]` - Packed UNORM8 RGBA vertex color (`COLOR_0`).
65    /// - `u32` - Attribute bitmask flags.
66    ///
67    /// # Returns
68    ///
69    /// - `Self` - Fully populated 64-byte vertex.
70    #[must_use]
71    pub const fn from_full(
72        position: Vec3,
73        normal: Vec3,
74        tangent: [f32; 4],
75        uv0: [f32; 2],
76        uv1: [f32; 2],
77        color0: [u8; 4],
78        flags: u32,
79    ) -> Self {
80        Self {
81            position,
82            normal,
83            tangent,
84            uv0,
85            uv1,
86            color0,
87            flags,
88        }
89    }
90}
91
92/// Default neutral matte PBR material.
93impl Default for PbrMaterial {
94    /// Returns a mid-gray dielectric PBR material.
95    ///
96    /// # Returns
97    ///
98    /// - `Self` - Default `PbrMaterial`.
99    fn default() -> Self {
100        Self {
101            base_color: Vec3::new(0.72, 0.75, 0.80),
102            metallic: 0.1,
103            roughness: 0.55,
104            emissive: Vec3::zero(),
105            reflectivity: 0.12,
106            surface_detail: SurfaceDetailMode::None,
107        }
108    }
109}
110
111/// Material presets and fluent builders for metallic conductors, dielectrics, architectural glass, and neon signage.
112impl PbrMaterial {
113    /// Creates a PBR material from an sRGB `Color`, `metallic`, `roughness`, and `reflectivity`.
114    ///
115    /// # Arguments
116    ///
117    /// - `Color` - Base albedo color.
118    /// - `f32` - Metallic scalar `[0.0, 1.0]`.
119    /// - `f32` - Roughness scalar `[0.04, 1.0]`.
120    /// - `f32` - Ray-traced reflectivity weight `[0.0, 1.0]`.
121    ///
122    /// # Returns
123    ///
124    /// - `Self` - Configured PBR material.
125    #[must_use]
126    pub fn pbr(color: Color, metallic: f32, roughness: f32, reflectivity: f32) -> Self {
127        Self {
128            base_color: Vec3::from_color(color),
129            metallic: metallic.clamp(0.0, 1.0),
130            roughness: roughness.clamp(0.04, 1.0),
131            emissive: Vec3::zero(),
132            reflectivity: reflectivity.clamp(0.0, 1.0),
133            surface_detail: SurfaceDetailMode::None,
134        }
135    }
136
137    /// Creates a metallic conductor PBR material (chrome, painted car body, brushed steel).
138    ///
139    /// # Arguments
140    ///
141    /// - `Color` - Base metallic reflectance color.
142    /// - `f32` - Surface roughness in `[0.04, 1.0]`.
143    ///
144    /// # Returns
145    ///
146    /// - `Self` - Conductor PBR material.
147    #[must_use]
148    pub fn metallic(color: Color, roughness: f32) -> Self {
149        let red_val: f32 = roughness.clamp(0.04, 1.0);
150        Self::pbr(
151            color,
152            0.92,
153            red_val,
154            (1.0 - red_val * 0.8).clamp(0.15, 0.96),
155        )
156    }
157
158    /// Creates a non-metallic dielectric PBR material (asphalt, concrete, matte plastic, cloth).
159    ///
160    /// # Arguments
161    ///
162    /// - `Color` - Base diffuse albedo color.
163    /// - `f32` - Surface roughness in `[0.04, 1.0]`.
164    ///
165    /// # Returns
166    ///
167    /// - `Self` - Dielectric PBR material.
168    #[must_use]
169    pub fn dielectric(color: Color, roughness: f32) -> Self {
170        let red_val: f32 = roughness.clamp(0.04, 1.0);
171        Self::pbr(
172            color,
173            0.04,
174            red_val,
175            (0.35 * (1.0 - red_val)).clamp(0.04, 0.35),
176        )
177    }
178
179    /// Creates a highly reflective architectural glass PBR material.
180    ///
181    /// # Arguments
182    ///
183    /// - `Color` - Subtle glass tint color.
184    /// - `f32` - Surface roughness in `[0.04, 0.4]`.
185    ///
186    /// # Returns
187    ///
188    /// - `Self` - Reflective glass PBR material.
189    #[must_use]
190    pub fn glass(color: Color, roughness: f32) -> Self {
191        let red_val: f32 = roughness.clamp(0.04, 0.4);
192        Self::pbr(color, 0.12, red_val, 0.88)
193    }
194
195    /// Creates an emissive neon PBR material for city signage, vehicle tail-lights, and beacons.
196    ///
197    /// # Arguments
198    ///
199    /// - `Color` - Base and emissive neon color.
200    /// - `f32` - Emissive intensity multiplier.
201    ///
202    /// # Returns
203    ///
204    /// - `Self` - Emissive PBR material.
205    #[must_use]
206    pub fn neon(color: Color, intensity: f32) -> Self {
207        let rgb: Vec3 = Vec3::from_color(color);
208        Self {
209            base_color: rgb,
210            metallic: 0.2,
211            roughness: 0.2,
212            emissive: rgb.scale(intensity.max(0.2)),
213            reflectivity: 0.3,
214            surface_detail: SurfaceDetailMode::None,
215        }
216    }
217
218    /// Returns a copy of this material with custom linear HDR emissive radiance.
219    ///
220    /// # Arguments
221    ///
222    /// - `Self` - Base material.
223    /// - `Vec3` - Emissive HDR RGB radiance.
224    ///
225    /// # Returns
226    ///
227    /// - `Self` - Updated material.
228    #[must_use]
229    pub fn with_emissive(mut self, emissive: Vec3) -> Self {
230        self.set_emissive(emissive);
231        self
232    }
233
234    /// Returns a copy of this material with adjusted surface roughness.
235    ///
236    /// # Arguments
237    ///
238    /// - `Self` - Base material.
239    /// - `f32` - Surface roughness clamped to `[0.04, 1.0]`.
240    ///
241    /// # Returns
242    ///
243    /// - `Self` - Updated material.
244    #[must_use]
245    pub fn with_roughness(mut self, roughness: f32) -> Self {
246        self.set_roughness(roughness.clamp(0.04, 1.0));
247        self
248    }
249
250    /// Returns a copy of this material with adjusted metallic factor.
251    ///
252    /// # Arguments
253    ///
254    /// - `Self` - Base material.
255    /// - `f32` - Metallic factor clamped to `[0.0, 1.0]`.
256    ///
257    /// # Returns
258    ///
259    /// - `Self` - Updated material.
260    #[must_use]
261    pub fn with_metallic(mut self, metallic: f32) -> Self {
262        self.set_metallic(metallic.clamp(0.0, 1.0));
263        self
264    }
265
266    /// Returns a copy of this material with adjusted ray-traced reflectivity.
267    ///
268    /// # Arguments
269    ///
270    /// - `Self` - Base material.
271    /// - `f32` - Reflectivity weight clamped to `[0.0, 1.0]`.
272    ///
273    /// # Returns
274    ///
275    /// - `Self` - Updated material.
276    #[must_use]
277    pub fn with_reflectivity(mut self, reflectivity: f32) -> Self {
278        self.set_reflectivity(reflectivity.clamp(0.0, 1.0));
279        self
280    }
281
282    /// Returns a copy of this material with the requested procedural surface detail overlay.
283    ///
284    /// # Arguments
285    ///
286    /// - `Self` - Base material.
287    /// - `SurfaceDetailMode` - Procedural surface detail mode.
288    ///
289    /// # Returns
290    ///
291    /// - `Self` - Updated material.
292    #[must_use]
293    pub fn with_surface_detail(mut self, mode: SurfaceDetailMode) -> Self {
294        self.set_surface_detail(mode);
295        self
296    }
297}
298
299/// Fluent constructors for `BoxMeshDesc`.
300impl BoxMeshDesc {
301    /// Creates a box mesh descriptor with default ground pivot and neutral PBR material.
302    ///
303    /// # Arguments
304    ///
305    /// - `&str` - Asset name.
306    /// - `Vec3` - Box extents `(width, height, depth)`.
307    ///
308    /// # Returns
309    ///
310    /// - `Self` - Ready descriptor.
311    #[must_use]
312    pub fn new(name: &str, size: Vec3) -> Self {
313        Self {
314            name: name.to_string(),
315            size,
316            ground_pivot: true,
317            material: PbrMaterial::default(),
318        }
319    }
320
321    /// Sets whether the box rests on `y = 0` or is centered at the origin.
322    ///
323    /// # Arguments
324    ///
325    /// - `Self` - Base descriptor.
326    /// - `bool` - Ground pivot toggle.
327    ///
328    /// # Returns
329    ///
330    /// - `Self` - Updated descriptor.
331    #[must_use]
332    pub fn with_ground_pivot(mut self, ground_pivot: bool) -> Self {
333        self.set_ground_pivot(ground_pivot);
334        self
335    }
336
337    /// Assigns the PBR material for the generated box mesh.
338    ///
339    /// # Arguments
340    ///
341    /// - `Self` - Base descriptor.
342    /// - `PbrMaterial` - Surface material.
343    ///
344    /// # Returns
345    ///
346    /// - `Self` - Updated descriptor.
347    #[must_use]
348    pub fn with_material(mut self, material: PbrMaterial) -> Self {
349        self.set_material(material);
350        self
351    }
352}
353
354/// Fluent constructors for `GroundPlaneDesc`.
355impl GroundPlaneDesc {
356    /// Creates a ground plane descriptor with default subdivisions and neutral PBR material.
357    ///
358    /// # Arguments
359    ///
360    /// - `&str` - Asset name.
361    /// - `f32` - Width along X.
362    /// - `f32` - Depth along Z.
363    ///
364    /// # Returns
365    ///
366    /// - `Self` - Ready descriptor.
367    #[must_use]
368    pub fn new(name: &str, width: f32, depth: f32) -> Self {
369        Self {
370            name: name.to_string(),
371            width,
372            depth,
373            subdivisions: 8,
374            material: PbrMaterial::default(),
375        }
376    }
377
378    /// Sets the grid subdivision count along each axis.
379    ///
380    /// # Arguments
381    ///
382    /// - `Self` - Base descriptor.
383    /// - `usize` - Subdivision count.
384    ///
385    /// # Returns
386    ///
387    /// - `Self` - Updated descriptor.
388    #[must_use]
389    pub fn with_subdivisions(mut self, subdivisions: usize) -> Self {
390        self.set_subdivisions(subdivisions);
391        self
392    }
393
394    /// Assigns the PBR material for the generated ground plane.
395    ///
396    /// # Arguments
397    ///
398    /// - `Self` - Base descriptor.
399    /// - `PbrMaterial` - Surface material.
400    ///
401    /// # Returns
402    ///
403    /// - `Self` - Updated descriptor.
404    #[must_use]
405    pub fn with_material(mut self, material: PbrMaterial) -> Self {
406        self.set_material(material);
407        self
408    }
409}
410
411/// Mesh construction, Nanite-style meshlet clustering, decimation, and procedural asset generators for `Mesh3D`.
412impl Mesh3D {
413    /// Partitions indexed triangles into Nanite-style `Meshlet3D` clusters with tight axis-aligned bounding boxes and normal cones.
414    ///
415    /// # Arguments
416    ///
417    /// - `&[Vertex3D]` - Source vertex buffer.
418    /// - `&[[u32; 3]]` - Source triangle indices.
419    ///
420    /// # Returns
421    ///
422    /// - `Vec<Meshlet3D>` - Contiguous cluster descriptors covering all triangles.
423    #[must_use]
424    pub fn build_meshlets_from_parts(
425        vertices: &[Vertex3D],
426        indices: &[[u32; 3]],
427    ) -> Vec<Meshlet3D> {
428        if indices.is_empty() {
429            return Vec::new();
430        }
431        let cluster_count: usize = indices.len().div_ceil(MESHLET_MAX_TRIS);
432        let mut out: Vec<Meshlet3D> = Vec::with_capacity(cluster_count);
433        let mut start: usize = 0;
434        while start < indices.len() {
435            let end: usize = (start + MESHLET_MAX_TRIS).min(indices.len());
436            let mut cluster_box: AxisAlignedBox3D = AxisAlignedBox3D::empty();
437            let mut avg_n: Vec3 = Vec3::zero();
438            let mut valid_tris: usize = 0;
439            for tri in &indices[start..end] {
440                let (i0, i1, i2): (usize, usize, usize) =
441                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
442                if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
443                    let p0: Vec3 = vertices[i0].get_position();
444                    let p1: Vec3 = vertices[i1].get_position();
445                    let p2: Vec3 = vertices[i2].get_position();
446                    cluster_box.expand_point(p0);
447                    cluster_box.expand_point(p1);
448                    cluster_box.expand_point(p2);
449                    let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
450                    avg_n = avg_n.add(fn_vec);
451                    valid_tris += 1;
452                }
453            }
454            if valid_tris == 0 {
455                cluster_box = AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
456            }
457            let cone_axis: Vec3 = avg_n.normalize();
458            let mut min_dot: f32 = 1.0;
459            for tri in &indices[start..end] {
460                let (i0, i1, i2): (usize, usize, usize) =
461                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
462                if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
463                    let p0: Vec3 = vertices[i0].get_position();
464                    let p1: Vec3 = vertices[i1].get_position();
465                    let p2: Vec3 = vertices[i2].get_position();
466                    let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
467                    min_dot = min_dot.min(fn_vec.dot(cone_axis));
468                }
469            }
470            let radius: f32 = cluster_box.radius().max(0.05);
471            let screen_error: f32 = radius / ((end - start).max(1) as f32).sqrt();
472            out.push(Meshlet3D::new(
473                start as u32,
474                (end - start) as u32,
475                cluster_box,
476                cone_axis,
477                min_dot,
478                screen_error,
479            ));
480            start = end;
481        }
482        out
483    }
484
485    /// Constructs a `Mesh3D`, computes its local `AxisAlignedBox3D`, and partitions Nanite-style `Meshlet3D` clusters.
486    ///
487    /// # Arguments
488    ///
489    /// - `String` - Asset name.
490    /// - `Vec<Vertex3D>` - Vertex list.
491    /// - `Vec<[u32; 3]>` - Triangle indices.
492    /// - `PbrMaterial` - Default material.
493    ///
494    /// # Returns
495    ///
496    /// - `Self` - Ready indexed mesh with meshlets.
497    #[must_use]
498    pub fn from_parts(
499        name: String,
500        vertices: Vec<Vertex3D>,
501        indices: Vec<[u32; 3]>,
502        material: PbrMaterial,
503    ) -> Self {
504        let mut bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
505        for item_val in vertices.iter() {
506            bounds.expand_point(item_val.get_position());
507        }
508        if vertices.is_empty() {
509            bounds = AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
510        }
511        let meshlets: Vec<Meshlet3D> = Self::build_meshlets_from_parts(&vertices, &indices);
512        Self {
513            name,
514            vertices,
515            indices,
516            bounds,
517            material,
518            sub_materials: Vec::new(),
519            tri_materials: Vec::new(),
520            meshlets,
521            skin_influences: Vec::new(),
522            morph_targets: Vec::new(),
523            material_index: None,
524            is_closed: false,
525        }
526    }
527
528    /// Recomputes area-weighted smooth per-vertex normals across all indexed triangles.
529    ///
530    /// # Arguments
531    ///
532    /// - `&Self` - Mutable 3D mesh.
533    pub fn compute_smooth_normals(&mut self) {
534        let vert_count: usize = self.get_vertices().len();
535        if vert_count == 0 {
536            return;
537        }
538        let mut accum: Vec<Vec3> = vec![Vec3::zero(); vert_count];
539        let verts: &[Vertex3D] = self.get_vertices().as_slice();
540        for tri in self.get_indices().iter() {
541            let (i0, i1, i2): (usize, usize, usize) =
542                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
543            if i0 < vert_count && i1 < vert_count && i2 < vert_count {
544                let p0: Vec3 = verts[i0].get_position();
545                let p1: Vec3 = verts[i1].get_position();
546                let p2: Vec3 = verts[i2].get_position();
547                let weighted_n: Vec3 = p1.sub(p0).cross(p2.sub(p0));
548                accum[i0] = accum[i0].add(weighted_n);
549                accum[i1] = accum[i1].add(weighted_n);
550                accum[i2] = accum[i2].add(weighted_n);
551            }
552        }
553        for (idx, vert) in self.get_mut_vertices().iter_mut().enumerate() {
554            let sum_n: Vec3 = accum[idx];
555            if sum_n.length_sq() > 1e-10 {
556                vert.set_normal(sum_n.normalize());
557            }
558        }
559    }
560
561    /// Computes MikkTSpace-compatible Lengyel tangent-space vectors `(tx, ty, tz, handedness)` from positions, normals, and `uv0`.
562    ///
563    /// # Arguments
564    ///
565    /// - `&Self` - Mutable 3D mesh.
566    pub fn compute_lengyel_tangents(&mut self) {
567        let vert_count: usize = self.get_vertices().len();
568        if vert_count == 0 {
569            return;
570        }
571        let mut tan1: Vec<Vec3> = vec![Vec3::zero(); vert_count];
572        let mut tan2: Vec<Vec3> = vec![Vec3::zero(); vert_count];
573        let verts: &[Vertex3D] = self.get_vertices().as_slice();
574        for tri in self.get_indices().iter() {
575            let (i0, i1, i2): (usize, usize, usize) =
576                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
577            if i0 >= vert_count || i1 >= vert_count || i2 >= vert_count {
578                continue;
579            }
580            let p0: Vec3 = verts[i0].get_position();
581            let p1: Vec3 = verts[i1].get_position();
582            let p2: Vec3 = verts[i2].get_position();
583            let w0: [f32; 2] = verts[i0].get_uv0();
584            let w1: [f32; 2] = verts[i1].get_uv0();
585            let w2: [f32; 2] = verts[i2].get_uv0();
586            let e1: Vec3 = p1.sub(p0);
587            let e2: Vec3 = p2.sub(p0);
588            let s1: f32 = w1[0] - w0[0];
589            let s2: f32 = w2[0] - w0[0];
590            let t1: f32 = w1[1] - w0[1];
591            let t2: f32 = w2[1] - w0[1];
592            let det: f32 = s1 * t2 - s2 * t1;
593            if det.abs() < 1e-10 {
594                continue;
595            }
596            let inv_det: f32 = 1.0 / det;
597            let sdir: Vec3 = Vec3::new(
598                (t2 * e1.get_x() - t1 * e2.get_x()) * inv_det,
599                (t2 * e1.get_y() - t1 * e2.get_y()) * inv_det,
600                (t2 * e1.get_z() - t1 * e2.get_z()) * inv_det,
601            );
602            let tdir: Vec3 = Vec3::new(
603                (s1 * e2.get_x() - s2 * e1.get_x()) * inv_det,
604                (s1 * e2.get_y() - s2 * e1.get_y()) * inv_det,
605                (s1 * e2.get_z() - s2 * e1.get_z()) * inv_det,
606            );
607            tan1[i0] = tan1[i0].add(sdir);
608            tan1[i1] = tan1[i1].add(sdir);
609            tan1[i2] = tan1[i2].add(sdir);
610            tan2[i0] = tan2[i0].add(tdir);
611            tan2[i1] = tan2[i1].add(tdir);
612            tan2[i2] = tan2[i2].add(tdir);
613        }
614        for (idx, vert) in self.get_mut_vertices().iter_mut().enumerate() {
615            let n: Vec3 = vert.get_normal().normalize();
616            let t: Vec3 = tan1[idx];
617            let ortho: Vec3 = t.sub(n.scale(n.dot(t)));
618            let unit_t: Vec3 = if ortho.length_sq() > 1e-10 {
619                ortho.normalize()
620            } else {
621                let fallback_axis: Vec3 = if n.get_y().abs() < 0.99 {
622                    Vec3::new(0.0, 1.0, 0.0)
623                } else {
624                    Vec3::new(1.0, 0.0, 0.0)
625                };
626                fallback_axis.cross(n).normalize()
627            };
628            let handedness: f32 = if n.cross(t).dot(tan2[idx]) < 0.0 {
629                -1.0
630            } else {
631                1.0
632            };
633            vert.set_tangent([unit_t.get_x(), unit_t.get_y(), unit_t.get_z(), handedness]);
634            let next_flags: u32 = vert.get_flags() | 4;
635            vert.set_flags(next_flags);
636        }
637    }
638
639    /// Resolves the effective PBR material and sub-material slot for triangle `tri_index`.
640    ///
641    /// # Arguments
642    ///
643    /// - `usize` - Triangle index inside `indices`.
644    /// - `PbrMaterial` - Instance primary PBR material used when slot is `0`.
645    ///
646    /// # Returns
647    ///
648    /// - `(PbrMaterial, u16)` - Effective PBR material and resolved material slot.
649    #[cfg_attr(not(target_arch = "wasm32"), inline)]
650    #[must_use]
651    pub fn resolve_triangle_material(
652        &self,
653        tri_index: usize,
654        primary_material: PbrMaterial,
655    ) -> (PbrMaterial, u16) {
656        let Self {
657            sub_materials,
658            tri_materials,
659            ..
660        } = self;
661        if tri_materials.is_empty() {
662            return (primary_material, 0);
663        }
664        let slot: u16 = tri_materials.get(tri_index).copied().unwrap_or(0);
665        if slot == 0 {
666            (primary_material, 0)
667        } else if let Some(&sub_mat) = sub_materials.get((slot - 1) as usize) {
668            (sub_mat, slot)
669        } else {
670            (primary_material, 0)
671        }
672    }
673
674    /// Appends a single outward-oriented flat-shaded triangle tagged with `mat_slot`.
675    ///
676    /// # Arguments
677    ///
678    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
679    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
680    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
681    /// - `(Vec3, Vec3, Vec3)` - Triangle vertices `(vert_a, vert_b, vert_c)` in CCW outward order.
682    /// - `u16` - Sub-material slot index (`0` = primary material).
683    fn push_flat_tri(
684        vertices: &mut Vec<Vertex3D>,
685        indices: &mut Vec<[u32; 3]>,
686        tri_materials: &mut Vec<u16>,
687        corners: (Vec3, Vec3, Vec3),
688        mat_slot: u16,
689    ) {
690        let (vert_a, vert_b, vert_c): (Vec3, Vec3, Vec3) = corners;
691        let face_normal: Vec3 = vert_b.sub(vert_a).cross(vert_c.sub(vert_a)).normalize();
692        let base_idx: u32 = vertices.len() as u32;
693        vertices.push(Vertex3D::new(vert_a, face_normal));
694        vertices.push(Vertex3D::new(vert_b, face_normal));
695        vertices.push(Vertex3D::new(vert_c, face_normal));
696        indices.push([base_idx, base_idx + 1, base_idx + 2]);
697        tri_materials.push(mat_slot);
698    }
699
700    /// Appends a flat-shaded CCW quad split into two triangles tagged with `mat_slot`.
701    ///
702    /// # Arguments
703    ///
704    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
705    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
706    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
707    /// - `[Vec3; 4]` - Quad vertices in CCW outward order.
708    /// - `u16` - Sub-material slot index.
709    fn push_flat_quad(
710        vertices: &mut Vec<Vertex3D>,
711        indices: &mut Vec<[u32; 3]>,
712        tri_materials: &mut Vec<u16>,
713        quad: [Vec3; 4],
714        mat_slot: u16,
715    ) {
716        let edge_u: Vec3 = quad[1].sub(quad[0]);
717        let edge_v: Vec3 = quad[2].sub(quad[0]);
718        let face_normal: Vec3 = edge_u.cross(edge_v).normalize();
719        let base_idx: u32 = vertices.len() as u32;
720        for corner in quad.into_iter() {
721            vertices.push(Vertex3D::new(corner, face_normal));
722        }
723        indices.push([base_idx, base_idx + 1, base_idx + 2]);
724        indices.push([base_idx, base_idx + 2, base_idx + 3]);
725        tri_materials.push(mat_slot);
726        tri_materials.push(mat_slot);
727    }
728
729    /// Appends a closed 6-face tapered frustum/box prism with explicit bottom and top corner quads.
730    ///
731    /// Bottom corners are ordered `[(-x,+z), (+x,+z), (+x,-z), (-x,-z)]` and top corners match identically.
732    ///
733    /// # Arguments
734    ///
735    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
736    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
737    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
738    /// - `[Vec3; 4]` - Bottom loop corners `[bl_rear, br_rear, br_front, bl_front]`.
739    /// - `[Vec3; 4]` - Top loop corners `[tl_rear, tr_rear, tr_front, tl_front]`.
740    /// - `[u16; 6]` - Per-face material slots `[rear(+z), front(-z), right(+x), left(-x), top(+y), bottom(-y)]`.
741    fn push_tapered_prism(
742        vertices: &mut Vec<Vertex3D>,
743        indices: &mut Vec<[u32; 3]>,
744        tri_materials: &mut Vec<u16>,
745        bottom: [Vec3; 4],
746        top: [Vec3; 4],
747        face_slots: [u16; 6],
748    ) {
749        Self::push_flat_quad(
750            vertices,
751            indices,
752            tri_materials,
753            [bottom[0], bottom[1], top[1], top[0]],
754            face_slots[0],
755        );
756        Self::push_flat_quad(
757            vertices,
758            indices,
759            tri_materials,
760            [bottom[2], bottom[3], top[3], top[2]],
761            face_slots[1],
762        );
763        Self::push_flat_quad(
764            vertices,
765            indices,
766            tri_materials,
767            [bottom[1], bottom[2], top[2], top[1]],
768            face_slots[2],
769        );
770        Self::push_flat_quad(
771            vertices,
772            indices,
773            tri_materials,
774            [bottom[3], bottom[0], top[0], top[3]],
775            face_slots[3],
776        );
777        Self::push_flat_quad(
778            vertices,
779            indices,
780            tri_materials,
781            [top[0], top[1], top[2], top[3]],
782            face_slots[4],
783        );
784        Self::push_flat_quad(
785            vertices,
786            indices,
787            tri_materials,
788            [bottom[3], bottom[2], bottom[1], bottom[0]],
789            face_slots[5],
790        );
791    }
792
793    /// Appends an axis-aligned box prism centered at `center` with `(width, height, depth)` tagged uniformly with `mat_slot`.
794    ///
795    /// # Arguments
796    ///
797    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
798    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
799    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
800    /// - `Vec3` - Box center position.
801    /// - `Vec3` - Box extents `(width, height, depth)`.
802    /// - `u16` - Sub-material slot applied to all six faces.
803    fn push_box_part(
804        vertices: &mut Vec<Vertex3D>,
805        indices: &mut Vec<[u32; 3]>,
806        tri_materials: &mut Vec<u16>,
807        center: Vec3,
808        size: Vec3,
809        mat_slot: u16,
810    ) {
811        let half_x: f32 = size.get_x() * 0.5;
812        let half_y: f32 = size.get_y() * 0.5;
813        let half_z: f32 = size.get_z() * 0.5;
814        let cx: f32 = center.get_x();
815        let cy: f32 = center.get_y();
816        let cz: f32 = center.get_z();
817        let bottom: [Vec3; 4] = [
818            Vec3::new(cx - half_x, cy - half_y, cz + half_z),
819            Vec3::new(cx + half_x, cy - half_y, cz + half_z),
820            Vec3::new(cx + half_x, cy - half_y, cz - half_z),
821            Vec3::new(cx - half_x, cy - half_y, cz - half_z),
822        ];
823        let top: [Vec3; 4] = [
824            Vec3::new(cx - half_x, cy + half_y, cz + half_z),
825            Vec3::new(cx + half_x, cy + half_y, cz + half_z),
826            Vec3::new(cx + half_x, cy + half_y, cz - half_z),
827            Vec3::new(cx - half_x, cy + half_y, cz - half_z),
828        ];
829        Self::push_tapered_prism(vertices, indices, tri_materials, bottom, top, [mat_slot; 6]);
830    }
831
832    /// Appends a closed cylindrical wheel assembly aligned along the X axle with matte rubber tire tread and inset metallic alloy rim face.
833    ///
834    /// # Arguments
835    ///
836    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
837    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
838    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
839    /// - `Vec3` - Wheel hub center `(center_x, center_y, center_z)`.
840    /// - `(f32, f32, f32)` - `(tire_radius, rim_radius, tire_width)`.
841    /// - `(u16, u16)` - `(tire_slot, rim_slot)` sub-material slots.
842    fn push_wheel_assembly(
843        vertices: &mut Vec<Vertex3D>,
844        indices: &mut Vec<[u32; 3]>,
845        tri_materials: &mut Vec<u16>,
846        center: Vec3,
847        dims: (f32, f32, f32),
848        slots: (u16, u16),
849    ) {
850        let (tire_radius, rim_radius, tire_width): (f32, f32, f32) = dims;
851        let (tire_slot, rim_slot): (u16, u16) = slots;
852        let half_w: f32 = tire_width * 0.5;
853        let cx: f32 = center.get_x();
854        let cy: f32 = center.get_y();
855        let cz: f32 = center.get_z();
856        let x_left: f32 = cx - half_w;
857        let x_right: f32 = cx + half_w;
858        let left_hub: Vec3 = Vec3::new(x_left, cy, cz);
859        let right_hub: Vec3 = Vec3::new(x_right, cy, cz);
860        let outer_sign: f32 = if cx >= 0.0 { 1.0 } else { -1.0 };
861        let rim_x: f32 = cx + outer_sign * (half_w + 0.014);
862        let brake_x: f32 = cx + outer_sign * (half_w + 0.006);
863        let rim_hub: Vec3 = Vec3::new(rim_x, cy, cz);
864        let brake_hub: Vec3 = Vec3::new(brake_x, cy, cz);
865        let step_rad: f32 = (2.0 * PI) / (MESH_CAR_WHEEL_SEGMENTS as f32);
866        for seg_idx in 0..MESH_CAR_WHEEL_SEGMENTS {
867            let a0: f32 = (seg_idx as f32) * step_rad;
868            let a1: f32 = ((seg_idx + 1) as f32) * step_rad;
869            let (s0, c0): (f32, f32) = a0.sin_cos();
870            let (s1, c1): (f32, f32) = a1.sin_cos();
871            let l0: Vec3 = Vec3::new(x_left, cy + s0 * tire_radius, cz + c0 * tire_radius);
872            let l1: Vec3 = Vec3::new(x_left, cy + s1 * tire_radius, cz + c1 * tire_radius);
873            let r0: Vec3 = Vec3::new(x_right, cy + s0 * tire_radius, cz + c0 * tire_radius);
874            let r1: Vec3 = Vec3::new(x_right, cy + s1 * tire_radius, cz + c1 * tire_radius);
875            Self::push_flat_quad(
876                vertices,
877                indices,
878                tri_materials,
879                [l0, r0, r1, l1],
880                tire_slot,
881            );
882            Self::push_flat_tri(
883                vertices,
884                indices,
885                tri_materials,
886                (right_hub, r1, r0),
887                tire_slot,
888            );
889            Self::push_flat_tri(
890                vertices,
891                indices,
892                tri_materials,
893                (left_hub, l0, l1),
894                tire_slot,
895            );
896            let bm0: Vec3 = Vec3::new(brake_x, cy + s0 * rim_radius, cz + c0 * rim_radius);
897            let bm1: Vec3 = Vec3::new(brake_x, cy + s1 * rim_radius, cz + c1 * rim_radius);
898            if outer_sign > 0.0 {
899                Self::push_flat_tri(
900                    vertices,
901                    indices,
902                    tri_materials,
903                    (brake_hub, bm1, bm0),
904                    tire_slot,
905                );
906            } else {
907                Self::push_flat_tri(
908                    vertices,
909                    indices,
910                    tri_materials,
911                    (brake_hub, bm0, bm1),
912                    tire_slot,
913                );
914            }
915            let lip_in: f32 = rim_radius * 0.78;
916            let rm0: Vec3 = Vec3::new(rim_x, cy + s0 * rim_radius, cz + c0 * rim_radius);
917            let rm1: Vec3 = Vec3::new(rim_x, cy + s1 * rim_radius, cz + c1 * rim_radius);
918            let ri0: Vec3 = Vec3::new(rim_x, cy + s0 * lip_in, cz + c0 * lip_in);
919            let ri1: Vec3 = Vec3::new(rim_x, cy + s1 * lip_in, cz + c1 * lip_in);
920            if outer_sign > 0.0 {
921                Self::push_flat_quad(
922                    vertices,
923                    indices,
924                    tri_materials,
925                    [ri0, rm0, rm1, ri1],
926                    rim_slot,
927                );
928            } else {
929                Self::push_flat_quad(
930                    vertices,
931                    indices,
932                    tri_materials,
933                    [ri1, rm1, rm0, ri0],
934                    rim_slot,
935                );
936            }
937            if seg_idx % 2 == 0 {
938                let spoke_rad: f32 = rim_radius * 0.84;
939                let a_mid: f32 = a0 + step_rad * 0.48;
940                let (sm, cm): (f32, f32) = a_mid.sin_cos();
941                let sp0: Vec3 = Vec3::new(rim_x, cy + s0 * spoke_rad, cz + c0 * spoke_rad);
942                let sp1: Vec3 = Vec3::new(rim_x, cy + sm * spoke_rad, cz + cm * spoke_rad);
943                if outer_sign > 0.0 {
944                    Self::push_flat_tri(
945                        vertices,
946                        indices,
947                        tri_materials,
948                        (rim_hub, sp1, sp0),
949                        rim_slot,
950                    );
951                } else {
952                    Self::push_flat_tri(
953                        vertices,
954                        indices,
955                        tri_materials,
956                        (rim_hub, sp0, sp1),
957                        rim_slot,
958                    );
959                }
960            }
961        }
962    }
963
964    /// Generates an axis-aligned box mesh of dimensions `(w, h, d)` resting on `y = 0` or centered.
965    ///
966    /// # Arguments
967    ///
968    /// - `&str` - Mesh name.
969    /// - `f32` - Width along X.
970    /// - `f32` - Height along Y.
971    /// - `f32` - Depth along Z.
972    /// - `bool` - When `true`, base rests on `y = 0`; otherwise centered at origin.
973    /// - `PbrMaterial` - Surface PBR material.
974    ///
975    /// # Returns
976    ///
977    /// - `Self` - Indexed 12-triangle box mesh with crisp flat face normals.
978    #[must_use]
979    pub fn box_mesh(
980        name: &str,
981        width_val: f32,
982        height_val: f32,
983        delta_val: f32,
984        ground_pivot: bool,
985        material: PbrMaterial,
986    ) -> Self {
987        let hx: f32 = width_val * 0.5;
988        let hz: f32 = delta_val * 0.5;
989        let y0: f32 = if ground_pivot { 0.0 } else { -height_val * 0.5 };
990        let y1: f32 = if ground_pivot {
991            height_val
992        } else {
993            height_val * 0.5
994        };
995        let faces: [([Vec3; 4], Vec3); 6] = [
996            (
997                [
998                    Vec3::new(-hx, y0, hz),
999                    Vec3::new(hx, y0, hz),
1000                    Vec3::new(hx, y1, hz),
1001                    Vec3::new(-hx, y1, hz),
1002                ],
1003                Vec3::new(0.0, 0.0, 1.0),
1004            ),
1005            (
1006                [
1007                    Vec3::new(hx, y0, -hz),
1008                    Vec3::new(-hx, y0, -hz),
1009                    Vec3::new(-hx, y1, -hz),
1010                    Vec3::new(hx, y1, -hz),
1011                ],
1012                Vec3::new(0.0, 0.0, -1.0),
1013            ),
1014            (
1015                [
1016                    Vec3::new(hx, y0, hz),
1017                    Vec3::new(hx, y0, -hz),
1018                    Vec3::new(hx, y1, -hz),
1019                    Vec3::new(hx, y1, hz),
1020                ],
1021                Vec3::new(1.0, 0.0, 0.0),
1022            ),
1023            (
1024                [
1025                    Vec3::new(-hx, y0, -hz),
1026                    Vec3::new(-hx, y0, hz),
1027                    Vec3::new(-hx, y1, hz),
1028                    Vec3::new(-hx, y1, -hz),
1029                ],
1030                Vec3::new(-1.0, 0.0, 0.0),
1031            ),
1032            (
1033                [
1034                    Vec3::new(-hx, y1, hz),
1035                    Vec3::new(hx, y1, hz),
1036                    Vec3::new(hx, y1, -hz),
1037                    Vec3::new(-hx, y1, -hz),
1038                ],
1039                Vec3::new(0.0, 1.0, 0.0),
1040            ),
1041            (
1042                [
1043                    Vec3::new(-hx, y0, -hz),
1044                    Vec3::new(hx, y0, -hz),
1045                    Vec3::new(hx, y0, hz),
1046                    Vec3::new(-hx, y0, hz),
1047                ],
1048                Vec3::new(0.0, -1.0, 0.0),
1049            ),
1050        ];
1051        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(24);
1052        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(12);
1053        for (quad, item_count) in faces.into_iter() {
1054            let base: u32 = vertices.len() as u32;
1055            for point_val in quad.into_iter() {
1056                vertices.push(Vertex3D::new(point_val, item_count));
1057            }
1058            indices.push([base, base + 1, base + 2]);
1059            indices.push([base, base + 2, base + 3]);
1060        }
1061        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
1062        mesh.set_is_closed(true);
1063        mesh
1064    }
1065
1066    /// Generates a horizontal ground/road quad plane at `y = 0` subdivided for crisp specular/shadow falloff.
1067    ///
1068    /// # Arguments
1069    ///
1070    /// - `&str` - Mesh name.
1071    /// - `f32` - Width along X.
1072    /// - `f32` - Depth along Z.
1073    /// - `usize` - Grid subdivisions per axis.
1074    /// - `PbrMaterial` - Surface PBR material.
1075    ///
1076    /// # Returns
1077    ///
1078    /// - `Self` - Subdivided ground plane mesh.
1079    #[must_use]
1080    pub fn ground_plane(
1081        name: &str,
1082        width_val: f32,
1083        delta_val: f32,
1084        subdivisions: usize,
1085        material: PbrMaterial,
1086    ) -> Self {
1087        let segs: usize = subdivisions.clamp(1, 16);
1088        let mut vertices: Vec<Vertex3D> = Vec::with_capacity((segs + 1) * (segs + 1));
1089        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(segs * segs * 2);
1090        let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
1091        for iz in 0..=segs {
1092            let vz: f32 = ((iz as f32) / (segs as f32) - 0.5) * delta_val;
1093            for ix in 0..=segs {
1094                let vx: f32 = ((ix as f32) / (segs as f32) - 0.5) * width_val;
1095                vertices.push(Vertex3D::new(Vec3::new(vx, 0.0, vz), up));
1096            }
1097        }
1098        let stride: u32 = (segs + 1) as u32;
1099        for iz in 0..segs {
1100            for ix in 0..segs {
1101                let i0: u32 = (iz as u32) * stride + (ix as u32);
1102                let i1: u32 = i0 + 1;
1103                let i2: u32 = i0 + stride;
1104                let i3: u32 = i2 + 1;
1105                indices.push([i0, i2, i1]);
1106                indices.push([i1, i2, i3]);
1107            }
1108        }
1109        Self::from_parts(name.to_string(), vertices, indices, material)
1110    }
1111
1112    /// Builds a subdivided coastal ocean water ring mesh spanning `outer_span` while omitting submerged interior quads strictly inside the solid island footprint and grouping triangles into spatially coherent 4x4 blocks for Nanite frustum culling.
1113    ///
1114    /// # Arguments
1115    ///
1116    /// - `&str` - Mesh asset name.
1117    /// - `f32` - Total horizontal outer span in meters along X and Z.
1118    /// - `f32` - Solid island half-width along X in meters.
1119    /// - `f32` - Solid island half-depth along Z in meters.
1120    /// - `usize` - Grid subdivisions along each axis (`8..=32`).
1121    /// - `PbrMaterial` - Ocean water PBR material.
1122    ///
1123    /// # Returns
1124    ///
1125    /// - `Self` - Watertight coastal ocean ring mesh with spatial meshlets.
1126    #[must_use]
1127    pub fn coastal_ocean_ring(
1128        name: &str,
1129        outer_span: f32,
1130        inner_half_x: f32,
1131        inner_half_z: f32,
1132        subdivisions: usize,
1133        material: PbrMaterial,
1134    ) -> Self {
1135        let seg_count: usize = subdivisions.clamp(8, 32);
1136        let cut_half_x: f32 = (inner_half_x - 2.0).max(0.0);
1137        let cut_half_z: f32 = (inner_half_z - 2.0).max(0.0);
1138        let mut vertices: Vec<Vertex3D> = Vec::with_capacity((seg_count + 1) * (seg_count + 1));
1139        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(seg_count * seg_count * 2);
1140        let up_normal: Vec3 = Vec3::new(0.0, 1.0, 0.0);
1141        let inv_segs: f32 = 1.0 / (seg_count as f32);
1142        for grid_z in 0..=seg_count {
1143            let pos_z: f32 = ((grid_z as f32) * inv_segs - 0.5) * outer_span;
1144            for grid_x in 0..=seg_count {
1145                let pos_x: f32 = ((grid_x as f32) * inv_segs - 0.5) * outer_span;
1146                vertices.push(Vertex3D::new(Vec3::new(pos_x, 0.0, pos_z), up_normal));
1147            }
1148        }
1149        let row_stride: u32 = (seg_count + 1) as u32;
1150        let mut block_z: usize = 0;
1151        while block_z < seg_count {
1152            let end_z: usize = (block_z + 4).min(seg_count);
1153            let mut block_x: usize = 0;
1154            while block_x < seg_count {
1155                let end_x: usize = (block_x + 4).min(seg_count);
1156                for grid_z in block_z..end_z {
1157                    let quad_z0: f32 = ((grid_z as f32) * inv_segs - 0.5) * outer_span;
1158                    let quad_z1: f32 = (((grid_z + 1) as f32) * inv_segs - 0.5) * outer_span;
1159                    for grid_x in block_x..end_x {
1160                        let quad_x0: f32 = ((grid_x as f32) * inv_segs - 0.5) * outer_span;
1161                        let quad_x1: f32 = (((grid_x + 1) as f32) * inv_segs - 0.5) * outer_span;
1162                        let inside_x: bool = quad_x0 >= -cut_half_x && quad_x1 <= cut_half_x;
1163                        let inside_z: bool = quad_z0 >= -cut_half_z && quad_z1 <= cut_half_z;
1164                        if inside_x && inside_z {
1165                            continue;
1166                        }
1167                        let idx0: u32 = (grid_z as u32) * row_stride + (grid_x as u32);
1168                        let idx1: u32 = idx0 + 1;
1169                        let idx2: u32 = idx0 + row_stride;
1170                        let idx3: u32 = idx2 + 1;
1171                        indices.push([idx0, idx2, idx1]);
1172                        indices.push([idx1, idx2, idx3]);
1173                    }
1174                }
1175                block_x += 4;
1176            }
1177            block_z += 4;
1178        }
1179        Self::from_parts(name.to_string(), vertices, indices, material)
1180    }
1181
1182    /// Builds a sculpted widebody multi-material GT supercar mesh with smoked glass greenhouse, carbon aero splitter/diffuser/wing, crimson LED taillight bar, xenon headlights, dark undercarriage contact shadow, and round cylindrical wheels with metallic alloy rims.
1183    ///
1184    /// # Arguments
1185    ///
1186    /// - `&str` - Asset name.
1187    /// - `PbrMaterial` - Primary car body clearcoat paint PBR material.
1188    ///
1189    /// # Returns
1190    ///
1191    /// - `Self` - Composite multi-material vehicle mesh.
1192    #[must_use]
1193    pub fn sports_car(name: &str, material: PbrMaterial) -> Self {
1194        let sub_materials: Vec<PbrMaterial> = vec![
1195            PbrMaterial::glass(Color::hex(0x0A101E), 0.05),
1196            PbrMaterial::dielectric(Color::hex(0x0D1015), 0.90),
1197            PbrMaterial::metallic(Color::hex(0xDCE6F2), 0.12),
1198            PbrMaterial::pbr(Color::hex(0x121722), 0.34, 0.32, 0.26),
1199            PbrMaterial::neon(Color::hex(0xFF1744), 3.8),
1200            PbrMaterial::neon(Color::hex(0xFFF6DC), 3.6),
1201            PbrMaterial::dielectric(Color::hex(0x04060A), 0.96),
1202            PbrMaterial::neon(Color::hex(0xFF9100), 2.2),
1203        ];
1204        let slot_body: u16 = 0;
1205        let slot_glass: u16 = 1;
1206        let slot_tire: u16 = 2;
1207        let slot_chrome: u16 = 3;
1208        let slot_carbon: u16 = 4;
1209        let slot_taillight: u16 = 5;
1210        let slot_headlight: u16 = 6;
1211        let slot_underbody: u16 = 7;
1212        let slot_amber: u16 = 8;
1213        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(960);
1214        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(340);
1215        let mut tri_materials: Vec<u16> = Vec::with_capacity(340);
1216        Self::push_box_part(
1217            &mut vertices,
1218            &mut indices,
1219            &mut tri_materials,
1220            Vec3::new(0.0, 0.14, 0.0),
1221            Vec3::new(2.06, 0.20, 4.46),
1222            slot_underbody,
1223        );
1224        Self::push_box_part(
1225            &mut vertices,
1226            &mut indices,
1227            &mut tri_materials,
1228            Vec3::new(0.0, 0.22, -2.28),
1229            Vec3::new(2.10, 0.09, 0.36),
1230            slot_carbon,
1231        );
1232        for skirt_side in [-1.0_f32, 1.0_f32] {
1233            Self::push_box_part(
1234                &mut vertices,
1235                &mut indices,
1236                &mut tri_materials,
1237                Vec3::new(skirt_side * 1.12, 0.24, 0.02),
1238                Vec3::new(0.14, 0.14, 2.04),
1239                slot_carbon,
1240            );
1241        }
1242        let front_bot: [Vec3; 4] = [
1243            Vec3::new(-1.14, 0.24, -0.78),
1244            Vec3::new(1.14, 0.24, -0.78),
1245            Vec3::new(0.98, 0.26, -2.38),
1246            Vec3::new(-0.98, 0.26, -2.38),
1247        ];
1248        let front_top: [Vec3; 4] = [
1249            Vec3::new(-1.04, 0.90, -0.78),
1250            Vec3::new(1.04, 0.90, -0.78),
1251            Vec3::new(0.84, 0.60, -2.32),
1252            Vec3::new(-0.84, 0.60, -2.32),
1253        ];
1254        Self::push_tapered_prism(
1255            &mut vertices,
1256            &mut indices,
1257            &mut tri_materials,
1258            front_bot,
1259            front_top,
1260            [
1261                slot_body,
1262                slot_body,
1263                slot_body,
1264                slot_body,
1265                slot_body,
1266                slot_underbody,
1267            ],
1268        );
1269        let mid_bot: [Vec3; 4] = [
1270            Vec3::new(-1.06, 0.24, 1.04),
1271            Vec3::new(1.06, 0.24, 1.04),
1272            Vec3::new(1.04, 0.24, -0.82),
1273            Vec3::new(-1.04, 0.24, -0.82),
1274        ];
1275        let mid_top: [Vec3; 4] = [
1276            Vec3::new(-1.04, 0.96, 1.04),
1277            Vec3::new(1.04, 0.96, 1.04),
1278            Vec3::new(1.00, 0.89, -0.82),
1279            Vec3::new(-1.00, 0.89, -0.82),
1280        ];
1281        Self::push_tapered_prism(
1282            &mut vertices,
1283            &mut indices,
1284            &mut tri_materials,
1285            mid_bot,
1286            mid_top,
1287            [
1288                slot_body,
1289                slot_body,
1290                slot_body,
1291                slot_body,
1292                slot_body,
1293                slot_underbody,
1294            ],
1295        );
1296        let rear_bot: [Vec3; 4] = [
1297            Vec3::new(-1.12, 0.36, 2.34),
1298            Vec3::new(1.12, 0.36, 2.34),
1299            Vec3::new(1.18, 0.26, 1.04),
1300            Vec3::new(-1.18, 0.26, 1.04),
1301        ];
1302        let rear_top: [Vec3; 4] = [
1303            Vec3::new(-1.06, 1.02, 2.24),
1304            Vec3::new(1.06, 1.02, 2.24),
1305            Vec3::new(1.14, 0.98, 1.04),
1306            Vec3::new(-1.14, 0.98, 1.04),
1307        ];
1308        Self::push_tapered_prism(
1309            &mut vertices,
1310            &mut indices,
1311            &mut tri_materials,
1312            rear_bot,
1313            rear_top,
1314            [
1315                slot_carbon,
1316                slot_body,
1317                slot_body,
1318                slot_body,
1319                slot_body,
1320                slot_underbody,
1321            ],
1322        );
1323        for fender_side in [-1.0_f32, 1.0_f32] {
1324            for (fender_z, flare_w) in [(-1.42_f32, 1.18_f32), (1.44_f32, 1.24_f32)] {
1325                let x_in: f32 = fender_side * 0.94;
1326                let x_out_lo: f32 = fender_side * flare_w;
1327                let x_out_hi: f32 = fender_side * (flare_w - 0.12);
1328                let (xa, xb): (f32, f32) = if fender_side > 0.0 {
1329                    (x_in, x_out_lo)
1330                } else {
1331                    (x_out_lo, x_in)
1332                };
1333                let (ta, tb): (f32, f32) = if fender_side > 0.0 {
1334                    (x_in, x_out_hi)
1335                } else {
1336                    (x_out_hi, x_in)
1337                };
1338                let arch_bot: [Vec3; 4] = [
1339                    Vec3::new(xa, 0.62, fender_z + 0.56),
1340                    Vec3::new(xb, 0.62, fender_z + 0.56),
1341                    Vec3::new(xb, 0.62, fender_z - 0.56),
1342                    Vec3::new(xa, 0.62, fender_z - 0.56),
1343                ];
1344                let arch_top: [Vec3; 4] = [
1345                    Vec3::new(ta, 0.98, fender_z + 0.42),
1346                    Vec3::new(tb, 0.98, fender_z + 0.42),
1347                    Vec3::new(tb, 0.98, fender_z - 0.42),
1348                    Vec3::new(ta, 0.98, fender_z - 0.42),
1349                ];
1350                Self::push_tapered_prism(
1351                    &mut vertices,
1352                    &mut indices,
1353                    &mut tri_materials,
1354                    arch_bot,
1355                    arch_top,
1356                    [
1357                        slot_body,
1358                        slot_body,
1359                        slot_body,
1360                        slot_body,
1361                        slot_body,
1362                        slot_underbody,
1363                    ],
1364                );
1365                Self::push_box_part(
1366                    &mut vertices,
1367                    &mut indices,
1368                    &mut tri_materials,
1369                    Vec3::new(fender_side * 0.92, 0.44, fender_z),
1370                    Vec3::new(0.28, 0.56, 0.88),
1371                    slot_underbody,
1372                );
1373            }
1374            Self::push_box_part(
1375                &mut vertices,
1376                &mut indices,
1377                &mut tri_materials,
1378                Vec3::new(fender_side * 1.02, 1.02, -0.46),
1379                Vec3::new(0.20, 0.09, 0.16),
1380                slot_carbon,
1381            );
1382        }
1383        let cabin_bot: [Vec3; 4] = [
1384            Vec3::new(-0.92, 0.96, 1.56),
1385            Vec3::new(0.92, 0.96, 1.56),
1386            Vec3::new(0.90, 0.88, -0.82),
1387            Vec3::new(-0.90, 0.88, -0.82),
1388        ];
1389        let cabin_top: [Vec3; 4] = [
1390            Vec3::new(-0.68, 1.48, 0.74),
1391            Vec3::new(0.68, 1.48, 0.74),
1392            Vec3::new(0.68, 1.45, -0.14),
1393            Vec3::new(-0.68, 1.45, -0.14),
1394        ];
1395        Self::push_tapered_prism(
1396            &mut vertices,
1397            &mut indices,
1398            &mut tri_materials,
1399            cabin_bot,
1400            cabin_top,
1401            [
1402                slot_glass,
1403                slot_glass,
1404                slot_glass,
1405                slot_glass,
1406                slot_body,
1407                slot_underbody,
1408            ],
1409        );
1410        let roof_bot: [Vec3; 4] = [
1411            Vec3::new(-0.66, 1.488, 0.75),
1412            Vec3::new(0.66, 1.488, 0.75),
1413            Vec3::new(0.66, 1.458, -0.15),
1414            Vec3::new(-0.66, 1.458, -0.15),
1415        ];
1416        let roof_top: [Vec3; 4] = [
1417            Vec3::new(-0.56, 1.545, 0.65),
1418            Vec3::new(0.56, 1.545, 0.65),
1419            Vec3::new(0.56, 1.525, -0.05),
1420            Vec3::new(-0.56, 1.525, -0.05),
1421        ];
1422        Self::push_tapered_prism(
1423            &mut vertices,
1424            &mut indices,
1425            &mut tri_materials,
1426            roof_bot,
1427            roof_top,
1428            [slot_body; 6],
1429        );
1430        Self::push_box_part(
1431            &mut vertices,
1432            &mut indices,
1433            &mut tri_materials,
1434            Vec3::new(0.0, 0.78, 2.34),
1435            Vec3::new(1.94, 0.11, 0.08),
1436            slot_taillight,
1437        );
1438        for tail_side in [-1.0_f32, 1.0_f32] {
1439            Self::push_box_part(
1440                &mut vertices,
1441                &mut indices,
1442                &mut tri_materials,
1443                Vec3::new(tail_side * 0.76, 0.78, 2.36),
1444                Vec3::new(0.42, 0.17, 0.08),
1445                slot_taillight,
1446            );
1447            Self::push_box_part(
1448                &mut vertices,
1449                &mut indices,
1450                &mut tri_materials,
1451                Vec3::new(tail_side * 0.72, 0.56, -2.35),
1452                Vec3::new(0.42, 0.13, 0.10),
1453                slot_headlight,
1454            );
1455        }
1456        Self::push_box_part(
1457            &mut vertices,
1458            &mut indices,
1459            &mut tri_materials,
1460            Vec3::new(0.0, 0.42, -2.36),
1461            Vec3::new(1.26, 0.18, 0.08),
1462            slot_carbon,
1463        );
1464        Self::push_box_part(
1465            &mut vertices,
1466            &mut indices,
1467            &mut tri_materials,
1468            Vec3::new(0.0, 0.30, 2.32),
1469            Vec3::new(1.74, 0.24, 0.24),
1470            slot_carbon,
1471        );
1472        for fin_x in [-0.54_f32, -0.18_f32, 0.18_f32, 0.54_f32] {
1473            Self::push_box_part(
1474                &mut vertices,
1475                &mut indices,
1476                &mut tri_materials,
1477                Vec3::new(fin_x, 0.28, 2.40),
1478                Vec3::new(0.06, 0.22, 0.16),
1479                slot_carbon,
1480            );
1481        }
1482        for pipe_x in [-0.74_f32, -0.56_f32, 0.56_f32, 0.74_f32] {
1483            Self::push_box_part(
1484                &mut vertices,
1485                &mut indices,
1486                &mut tri_materials,
1487                Vec3::new(pipe_x, 0.32, 2.40),
1488                Vec3::new(0.11, 0.11, 0.14),
1489                slot_chrome,
1490            );
1491            Self::push_box_part(
1492                &mut vertices,
1493                &mut indices,
1494                &mut tri_materials,
1495                Vec3::new(pipe_x, 0.32, 2.46),
1496                Vec3::new(0.06, 0.06, 0.04),
1497                slot_amber,
1498            );
1499        }
1500        Self::push_box_part(
1501            &mut vertices,
1502            &mut indices,
1503            &mut tri_materials,
1504            Vec3::new(0.0, 1.29, 2.12),
1505            Vec3::new(2.04, 0.06, 0.38),
1506            slot_carbon,
1507        );
1508        for wing_side in [-1.0_f32, 1.0_f32] {
1509            Self::push_box_part(
1510                &mut vertices,
1511                &mut indices,
1512                &mut tri_materials,
1513                Vec3::new(wing_side * 1.02, 1.28, 2.12),
1514                Vec3::new(0.05, 0.14, 0.42),
1515                slot_carbon,
1516            );
1517            Self::push_box_part(
1518                &mut vertices,
1519                &mut indices,
1520                &mut tri_materials,
1521                Vec3::new(wing_side * 0.56, 1.14, 2.06),
1522                Vec3::new(0.05, 0.28, 0.18),
1523                slot_carbon,
1524            );
1525        }
1526        let wheel_specs: [(f32, f32, f32, f32, f32); 4] = [
1527            (-1.04, -1.42, 0.35, 0.24, 0.34),
1528            (1.04, -1.42, 0.35, 0.24, 0.34),
1529            (-1.06, 1.44, 0.37, 0.25, 0.44),
1530            (1.06, 1.44, 0.37, 0.25, 0.44),
1531        ];
1532        for (wheel_x, wheel_z, tire_r, rim_r, tire_w) in wheel_specs.into_iter() {
1533            Self::push_wheel_assembly(
1534                &mut vertices,
1535                &mut indices,
1536                &mut tri_materials,
1537                Vec3::new(wheel_x, tire_r, wheel_z),
1538                (tire_r, rim_r, tire_w),
1539                (slot_tire, slot_chrome),
1540            );
1541        }
1542        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
1543        mesh.set_sub_materials(sub_materials);
1544        mesh.set_tri_materials(tri_materials);
1545        mesh.set_is_closed(true);
1546        mesh
1547    }
1548
1549    /// Builds an instanced Vice Boulevard coastal palm tree with a gracefully leaning segmented trunk and seven arching multi-segment tropical fronds.
1550    ///
1551    /// # Arguments
1552    ///
1553    /// - `&str` - Asset name.
1554    ///
1555    /// # Returns
1556    ///
1557    /// - `Self` - Multi-material palm tree mesh (`slot 0` warm bark trunk, `slot 1` emerald tropical fronds).
1558    #[must_use]
1559    pub fn palm_tree(name: &str) -> Self {
1560        let bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
1561        let frond_top_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x227848), 0.05, 0.56, 0.08);
1562        let frond_under_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x134A2D), 0.04, 0.68, 0.05);
1563        let sub_materials: Vec<PbrMaterial> = vec![frond_top_mat, frond_under_mat];
1564        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(520);
1565        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(260);
1566        let mut tri_materials: Vec<u16> = Vec::with_capacity(260);
1567        let ring_specs: [(f32, f32, f32, f32); 5] = [
1568            (0.0, 0.0, 0.0, 0.30),
1569            (1.9, 0.14, 0.05, 0.25),
1570            (3.9, 0.32, 0.08, 0.21),
1571            (5.8, 0.44, 0.06, 0.17),
1572            (7.5, 0.48, 0.02, 0.14),
1573        ];
1574        let trunk_step: f32 = (2.0 * PI) / (MESH_PALM_TRUNK_SEGMENTS as f32);
1575        for seg_idx in 0..4usize {
1576            let (y0, ox0, oz0, r0): (f32, f32, f32, f32) = ring_specs[seg_idx];
1577            let (y1, ox1, oz1, r1): (f32, f32, f32, f32) = ring_specs[seg_idx + 1];
1578            for side_idx in 0..MESH_PALM_TRUNK_SEGMENTS {
1579                let a0: f32 = (side_idx as f32) * trunk_step;
1580                let a1: f32 = ((side_idx + 1) as f32) * trunk_step;
1581                let (s0, c0): (f32, f32) = a0.sin_cos();
1582                let (s1, c1): (f32, f32) = a1.sin_cos();
1583                let p0: Vec3 = Vec3::new(ox0 + c0 * r0, y0, oz0 + s0 * r0);
1584                let p1: Vec3 = Vec3::new(ox0 + c1 * r0, y0, oz0 + s1 * r0);
1585                let p2: Vec3 = Vec3::new(ox1 + c1 * r1, y1, oz1 + s1 * r1);
1586                let p3: Vec3 = Vec3::new(ox1 + c0 * r1, y1, oz1 + s0 * r1);
1587                Self::push_flat_quad(
1588                    &mut vertices,
1589                    &mut indices,
1590                    &mut tri_materials,
1591                    [p0, p1, p2, p3],
1592                    0,
1593                );
1594            }
1595        }
1596        let crown: Vec3 = Vec3::new(0.48, 7.45, 0.02);
1597        let frond_step: f32 = (2.0 * PI) / (MESH_PALM_FROND_COUNT as f32);
1598        for tier_idx in 0..2usize {
1599            let tier_count: usize = if tier_idx == 0 {
1600                MESH_PALM_FROND_COUNT
1601            } else {
1602                5
1603            };
1604            let tier_step: f32 = if tier_idx == 0 {
1605                frond_step
1606            } else {
1607                (2.0 * PI) / 5.0
1608            };
1609            let tier_yaw_off: f32 = if tier_idx == 0 { 0.25 } else { 0.62 };
1610            let tier_origin: Vec3 = crown.add(Vec3::new(0.0, (tier_idx as f32) * 0.22, 0.0));
1611            for frond_idx in 0..tier_count {
1612                let yaw: f32 = (frond_idx as f32) * tier_step + tier_yaw_off;
1613                let (sy, cy): (f32, f32) = yaw.sin_cos();
1614                let dir: Vec3 = Vec3::new(cy, 0.0, sy);
1615                let right: Vec3 = Vec3::new(-sy, 0.0, cy);
1616                let reach: f32 = if tier_idx == 0 {
1617                    if frond_idx % 2 == 0 { 2.85 } else { 2.45 }
1618                } else {
1619                    1.85
1620                };
1621                let lift: f32 = if tier_idx == 0 { 0.48 } else { 0.92 };
1622                let drop_tip: f32 = if tier_idx == 0 { -1.18 } else { -0.18 };
1623                let p_mid: Vec3 = tier_origin
1624                    .add(dir.scale(reach * 0.44))
1625                    .add(Vec3::new(0.0, lift, 0.0));
1626                let p_arch: Vec3 = tier_origin.add(dir.scale(reach * 0.78)).add(Vec3::new(
1627                    0.0,
1628                    lift * 0.15 - 0.12,
1629                    0.0,
1630                ));
1631                let p_tip: Vec3 = tier_origin
1632                    .add(dir.scale(reach))
1633                    .add(Vec3::new(0.0, drop_tip, 0.0));
1634                let w_mid: Vec3 = right.scale(if tier_idx == 0 { 0.34 } else { 0.26 });
1635                let w_arch: Vec3 = right.scale(if tier_idx == 0 { 0.24 } else { 0.18 });
1636                let sag_mid: Vec3 = Vec3::new(0.0, -0.16, 0.0);
1637                let sag_arch: Vec3 = Vec3::new(0.0, -0.20, 0.0);
1638                let mid_l: Vec3 = p_mid.sub(w_mid).add(sag_mid);
1639                let mid_r: Vec3 = p_mid.add(w_mid).add(sag_mid);
1640                let arch_l: Vec3 = p_arch.sub(w_arch).add(sag_arch);
1641                let arch_r: Vec3 = p_arch.add(w_arch).add(sag_arch);
1642                Self::push_flat_tri(
1643                    &mut vertices,
1644                    &mut indices,
1645                    &mut tri_materials,
1646                    (tier_origin, p_mid, mid_l),
1647                    1,
1648                );
1649                Self::push_flat_tri(
1650                    &mut vertices,
1651                    &mut indices,
1652                    &mut tri_materials,
1653                    (tier_origin, mid_r, p_mid),
1654                    1,
1655                );
1656                Self::push_flat_tri(
1657                    &mut vertices,
1658                    &mut indices,
1659                    &mut tri_materials,
1660                    (tier_origin, mid_l, p_mid),
1661                    2,
1662                );
1663                Self::push_flat_tri(
1664                    &mut vertices,
1665                    &mut indices,
1666                    &mut tri_materials,
1667                    (tier_origin, p_mid, mid_r),
1668                    2,
1669                );
1670                Self::push_flat_quad(
1671                    &mut vertices,
1672                    &mut indices,
1673                    &mut tri_materials,
1674                    [mid_l, p_mid, p_arch, arch_l],
1675                    1,
1676                );
1677                Self::push_flat_quad(
1678                    &mut vertices,
1679                    &mut indices,
1680                    &mut tri_materials,
1681                    [p_mid, mid_r, arch_r, p_arch],
1682                    1,
1683                );
1684                Self::push_flat_quad(
1685                    &mut vertices,
1686                    &mut indices,
1687                    &mut tri_materials,
1688                    [arch_l, p_arch, p_mid, mid_l],
1689                    2,
1690                );
1691                Self::push_flat_quad(
1692                    &mut vertices,
1693                    &mut indices,
1694                    &mut tri_materials,
1695                    [p_arch, arch_r, mid_r, p_mid],
1696                    2,
1697                );
1698                Self::push_flat_tri(
1699                    &mut vertices,
1700                    &mut indices,
1701                    &mut tri_materials,
1702                    (arch_l, p_arch, p_tip),
1703                    1,
1704                );
1705                Self::push_flat_tri(
1706                    &mut vertices,
1707                    &mut indices,
1708                    &mut tri_materials,
1709                    (p_arch, arch_r, p_tip),
1710                    1,
1711                );
1712                Self::push_flat_tri(
1713                    &mut vertices,
1714                    &mut indices,
1715                    &mut tri_materials,
1716                    (p_arch, arch_l, p_tip),
1717                    2,
1718                );
1719                Self::push_flat_tri(
1720                    &mut vertices,
1721                    &mut indices,
1722                    &mut tri_materials,
1723                    (arch_r, p_arch, p_tip),
1724                    2,
1725                );
1726            }
1727        }
1728        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, bark_mat);
1729        mesh.set_sub_materials(sub_materials);
1730        mesh.set_tri_materials(tri_materials);
1731        mesh.set_is_closed(false);
1732        mesh
1733    }
1734
1735    /// Builds a box mesh from a fluent `BoxMeshDesc`.
1736    ///
1737    /// # Arguments
1738    ///
1739    /// - `&BoxMeshDesc` - Box mesh descriptor.
1740    ///
1741    /// # Returns
1742    ///
1743    /// - `Self` - Indexed 12-triangle box mesh.
1744    #[must_use]
1745    pub fn from_box_desc(desc: &BoxMeshDesc) -> Self {
1746        let size: Vec3 = desc.get_size();
1747        Self::box_mesh(
1748            desc.get_name(),
1749            size.get_x(),
1750            size.get_y(),
1751            size.get_z(),
1752            desc.get_ground_pivot(),
1753            desc.get_material(),
1754        )
1755    }
1756
1757    /// Builds a subdivided ground plane from a fluent `GroundPlaneDesc`.
1758    ///
1759    /// # Arguments
1760    ///
1761    /// - `&GroundPlaneDesc` - Ground plane descriptor.
1762    ///
1763    /// # Returns
1764    ///
1765    /// - `Self` - Subdivided ground plane mesh.
1766    #[must_use]
1767    pub fn from_ground_desc(desc: &GroundPlaneDesc) -> Self {
1768        Self::ground_plane(
1769            desc.get_name(),
1770            desc.get_width(),
1771            desc.get_depth(),
1772            desc.get_subdivisions(),
1773            desc.get_material(),
1774        )
1775    }
1776
1777    /// Builds a simplified proxy mesh enclosing this mesh's axis-aligned bounding box for distant LOD tiers.
1778    ///
1779    /// # Arguments
1780    ///
1781    /// - `&Self` - Source mesh reference.
1782    /// - `&str` - LOD suffix label.
1783    ///
1784    /// # Returns
1785    ///
1786    /// - `Self` - Lightweight 12-triangle LOD proxy mesh.
1787    #[must_use]
1788    pub fn build_lod_proxy(&self, suffix: &str) -> Self {
1789        let blue_val: AxisAlignedBox3D = self.get_bounds();
1790        let size: Vec3 = blue_val.get_max().sub(blue_val.get_min());
1791        let center: Vec3 = blue_val.center();
1792        let mut proxy: Self = Self::box_mesh(
1793            &format!("{}_{suffix}", self.get_name()),
1794            size.get_x().max(0.2),
1795            size.get_y().max(0.2),
1796            size.get_z().max(0.2),
1797            false,
1798            self.get_material(),
1799        );
1800        for item_val in proxy.get_mut_vertices().iter_mut() {
1801            item_val.set_position(item_val.get_position().add(center));
1802        }
1803        proxy.set_bounds(blue_val);
1804        let meshlets: Vec<Meshlet3D> =
1805            Self::build_meshlets_from_parts(proxy.get_vertices(), proxy.get_indices());
1806        proxy.set_meshlets(meshlets);
1807        proxy
1808    }
1809
1810    /// Produces a mid-detail decimated mesh by retaining dominant triangles while preserving bounding silhouette.
1811    ///
1812    /// # Arguments
1813    ///
1814    /// - `&Self` - Source mesh reference.
1815    /// - `&str` - LOD suffix label.
1816    ///
1817    /// # Returns
1818    ///
1819    /// - `Self` - Decimated intermediate LOD mesh.
1820    #[must_use]
1821    pub fn build_mid_lod(&self, suffix: &str) -> Self {
1822        let verts: &[Vertex3D] = self.get_vertices().as_slice();
1823        let tris: &[[u32; 3]] = self.get_indices().as_slice();
1824        if tris.len() <= 24 {
1825            return self.build_lod_proxy(suffix);
1826        }
1827        let mut scored: Vec<(f32, [u32; 3], u16)> = Vec::with_capacity(tris.len());
1828        let default_mat: PbrMaterial = self.get_material();
1829        for (tri_idx, tri) in tris.iter().copied().enumerate() {
1830            let (i0, i1, i2): (usize, usize, usize) =
1831                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1832            if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1833                let p0: Vec3 = verts[i0].get_position();
1834                let p1: Vec3 = verts[i1].get_position();
1835                let p2: Vec3 = verts[i2].get_position();
1836                let area2: f32 = p1.sub(p0).cross(p2.sub(p0)).length_sq();
1837                let (resolved_mat, slot): (PbrMaterial, u16) =
1838                    self.resolve_triangle_material(tri_idx, default_mat);
1839                let emissive_boost: f32 = if resolved_mat.get_emissive().length_sq() > 0.25 {
1840                    8.0
1841                } else {
1842                    1.0
1843                };
1844                scored.push((area2 * emissive_boost, tri, slot));
1845            }
1846        }
1847        scored.sort_unstable_by(
1848            |alpha_val: &(f32, [u32; 3], u16), blue_val: &(f32, [u32; 3], u16)| {
1849                blue_val.0.total_cmp(&alpha_val.0)
1850            },
1851        );
1852        let keep: usize = (scored.len() / 2).max(12);
1853        let mut reduced: Vec<[u32; 3]> = Vec::with_capacity(keep);
1854        let mut reduced_slots: Vec<u16> = if self.get_tri_materials().is_empty() {
1855            Vec::new()
1856        } else {
1857            Vec::with_capacity(keep)
1858        };
1859        for (_, tri, slot) in scored.into_iter().take(keep) {
1860            reduced.push(tri);
1861            if !self.get_tri_materials().is_empty() {
1862                reduced_slots.push(slot);
1863            }
1864        }
1865        let mut mid_mesh: Self = Self::from_parts(
1866            format!("{}_{suffix}", self.get_name()),
1867            self.get_vertices().clone(),
1868            reduced,
1869            self.get_material(),
1870        );
1871        if !reduced_slots.is_empty() {
1872            mid_mesh.set_sub_materials(self.get_sub_materials().clone());
1873            mid_mesh.set_tri_materials(reduced_slots);
1874        }
1875        mid_mesh.set_is_closed(self.get_is_closed());
1876        mid_mesh
1877    }
1878}
1879
1880/// Multi-level continuous LOD chain creation and screen-error selection for `MeshLodChain`.
1881impl MeshLodChain {
1882    /// Builds a continuous 3-tier Nanite-style LOD chain (`LOD0` full -> `LOD1` mid -> `LOD2` proxy) automatically.
1883    ///
1884    /// # Arguments
1885    ///
1886    /// - `Mesh3D` - Full-resolution `LOD0` mesh.
1887    ///
1888    /// # Returns
1889    ///
1890    /// - `Self` - Ready LOD chain.
1891    #[must_use]
1892    pub fn from_mesh(mesh: Mesh3D) -> Self {
1893        let tri_count: usize = mesh.get_indices().len();
1894        if tri_count > 32 {
1895            let lod1: Mesh3D = mesh.build_mid_lod(MESH_LOD1_SUFFIX);
1896            let lod2: Mesh3D = mesh.build_lod_proxy(MESH_LOD2_SUFFIX);
1897            Self {
1898                levels: vec![mesh, lod1, lod2],
1899            }
1900        } else if tri_count > 16 {
1901            let lod1: Mesh3D = mesh.build_lod_proxy(MESH_LOD1_SUFFIX);
1902            Self {
1903                levels: vec![mesh, lod1],
1904            }
1905        } else {
1906            let clone_lod1: Mesh3D = mesh.clone();
1907            Self {
1908                levels: vec![mesh, clone_lod1],
1909            }
1910        }
1911    }
1912
1913    /// Selects the appropriate `Mesh3D` detail level for `distance` and `lod_bias`.
1914    ///
1915    /// # Arguments
1916    ///
1917    /// - `&Self` - LOD chain reference.
1918    /// - `f32` - Camera-to-object distance in meters.
1919    /// - `f32` - Quality LOD bias multiplier.
1920    ///
1921    /// # Returns
1922    ///
1923    /// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
1924    #[must_use]
1925    pub fn select(&self, distance: f32, lod_bias: f32) -> (&Mesh3D, usize) {
1926        let levels: &[Mesh3D] = self.get_levels().as_slice();
1927        let effective_dist: f32 = distance * lod_bias.max(0.25);
1928        if levels.len() > 2 && effective_dist > 135.0 {
1929            (&levels[2], 2)
1930        } else if levels.len() > 1 && effective_dist > 78.0 {
1931            (&levels[1], 1)
1932        } else {
1933            (&levels[0], 0)
1934        }
1935    }
1936
1937    /// Nanite-style continuous LOD selection driven by projected screen-space pixel coverage.
1938    ///
1939    /// # Arguments
1940    ///
1941    /// - `&Self` - LOD chain reference.
1942    /// - `f32` - Camera-to-object distance in meters.
1943    /// - `f32` - World-space bounding sphere radius in meters.
1944    /// - `f32` - Projected viewport focal length in pixels (`height / (2 * tan(fov/2))`).
1945    /// - `f32` - Quality LOD bias multiplier (`< 1.0` higher detail, `> 1.0` aggressive simplification).
1946    ///
1947    /// # Returns
1948    ///
1949    /// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
1950    #[must_use]
1951    pub fn select_screen_error(
1952        &self,
1953        distance: f32,
1954        bounds_radius: f32,
1955        focal_px: f32,
1956        lod_bias: f32,
1957    ) -> (&Mesh3D, usize) {
1958        let levels: &[Mesh3D] = self.get_levels().as_slice();
1959        let safe_dist: f32 = distance.max(0.5);
1960        let projected_px: f32 =
1961            (bounds_radius.max(0.2) * focal_px) / (safe_dist * lod_bias.max(0.25));
1962        if levels.len() > 2 && projected_px < 22.0 {
1963            (&levels[2], 2)
1964        } else if levels.len() > 1 && projected_px < 58.0 {
1965            (&levels[1], 1)
1966        } else {
1967            (&levels[0], 0)
1968        }
1969    }
1970}
1971
1972/// Native Wavefront `.obj`, Khronos glTF 2.0 `.gltf`/`.glb`, and baked binary model importers for `ModelImporter3D`.
1973impl ModelImporter3D {
1974    /// Imports a 3D model from text source in the specified `ModelFormat` and generates LOD chains.
1975    ///
1976    /// # Arguments
1977    ///
1978    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
1979    /// - `&str` - Raw `.obj` or `.gltf` text content.
1980    /// - `PbrMaterial` - Fallback PBR material when source omits material definitions.
1981    ///
1982    /// # Returns
1983    ///
1984    /// - `Result<ImportedModel3D, String>` - Imported model bundle or parse error diagnostic.
1985    pub fn import(
1986        format: ModelFormat,
1987        source: &str,
1988        fallback_material: PbrMaterial,
1989    ) -> Result<ImportedModel3D, String> {
1990        match format {
1991            ModelFormat::Obj => Self::parse_obj(source, fallback_material),
1992            ModelFormat::GltfJson => Self::parse_gltf_json(source, fallback_material),
1993            ModelFormat::GlbBinary | ModelFormat::Euv3dBinary | ModelFormat::BlendInspect => {
1994                Err(ERR_TEXT_FORMAT_UNSUPPORTED.to_string())
1995            }
1996        }
1997    }
1998
1999    /// Imports a 3D model from raw binary or UTF-8 bytes in `Obj`, `GltfJson`, or `GlbBinary` format.
2000    ///
2001    /// # Arguments
2002    ///
2003    /// - `ModelFormat` - Source interchange format.
2004    /// - `&[u8]` - Raw file bytes.
2005    /// - `PbrMaterial` - Fallback PBR material when source omits material definitions.
2006    ///
2007    /// # Returns
2008    ///
2009    /// - `Result<ImportedModel3D, String>` - Imported model bundle or parse error.
2010    pub fn import_bytes(
2011        format: ModelFormat,
2012        bytes: &[u8],
2013        fallback_material: PbrMaterial,
2014    ) -> Result<ImportedModel3D, String> {
2015        match format {
2016            ModelFormat::Obj => {
2017                let text: &str = from_utf8(bytes)
2018                    .ok()
2019                    .ok_or_else(|| ERR_OBJ_EMPTY.to_string())?;
2020                Self::parse_obj(text, fallback_material)
2021            }
2022            ModelFormat::GltfJson => {
2023                let text: &str = from_utf8(bytes)
2024                    .ok()
2025                    .ok_or_else(|| ERR_GLTF_EMPTY.to_string())?;
2026                Self::parse_gltf_json(text, fallback_material)
2027            }
2028            ModelFormat::GlbBinary => {
2029                let scene: ImportedScene3D = parse_glb_bytes(bytes)?;
2030                if scene.get_meshes().is_empty() {
2031                    return Err(ERR_GLTF_EMPTY.to_string());
2032                }
2033                let mut model: ImportedModel3D = scene.to_imported_model(ModelFormat::GlbBinary);
2034                if scene.get_materials().is_empty() {
2035                    for chain in model.get_mut_meshes().iter_mut() {
2036                        for lvl in chain.get_mut_levels().iter_mut() {
2037                            lvl.set_material(fallback_material);
2038                        }
2039                    }
2040                }
2041                Ok(model)
2042            }
2043            ModelFormat::Euv3dBinary => {
2044                let bundle: BakedAssetBundle3D = Euv3dPackage::decode_bytes(bytes)?;
2045                if bundle.get_lod_chains().is_empty() {
2046                    return Err(ERR_GLTF_EMPTY.to_string());
2047                }
2048                let total_vertices: usize = bundle
2049                    .get_lod_chains()
2050                    .iter()
2051                    .filter_map(|c: &MeshLodChain| c.get_levels().first())
2052                    .map(|m: &Mesh3D| m.get_vertices().len())
2053                    .sum();
2054                let total_triangles: usize = bundle
2055                    .get_lod_chains()
2056                    .iter()
2057                    .filter_map(|c: &MeshLodChain| c.get_levels().first())
2058                    .map(|m: &Mesh3D| m.get_indices().len())
2059                    .sum();
2060                Ok(ImportedModel3D {
2061                    name: bundle.get_scene().get_name().clone(),
2062                    format: ModelFormat::Euv3dBinary,
2063                    meshes: bundle.get_lod_chains().clone(),
2064                    total_vertices,
2065                    total_triangles,
2066                })
2067            }
2068            ModelFormat::BlendInspect => Err(ERR_BINARY_FORMAT_UNSUPPORTED.to_string()),
2069        }
2070    }
2071
2072    /// Resolves a signed 1-based Wavefront OBJ index (positive or negative relative to `len`) into a 0-based index.
2073    ///
2074    /// # Arguments
2075    ///
2076    /// - `i32` - Signed 1-based OBJ index.
2077    /// - `usize` - Current length of the corresponding attribute array.
2078    ///
2079    /// # Returns
2080    ///
2081    /// - `Option<usize>` - Resolved 0-based index if in bounds.
2082    #[must_use]
2083    fn resolve_obj_index(raw: i32, len: usize) -> Option<usize> {
2084        if raw > 0 {
2085            let idx: usize = (raw - 1) as usize;
2086            if idx < len { Some(idx) } else { None }
2087        } else if raw < 0 {
2088            let idx: isize = (len as isize) + (raw as isize);
2089            if idx >= 0 && (idx as usize) < len {
2090                Some(idx as usize)
2091            } else {
2092                None
2093            }
2094        } else {
2095            None
2096        }
2097    }
2098
2099    /// Parses a Wavefront `.mtl` material library into a named `PbrMaterial` map (`Kd`, `Ke`, `Ns`, `Pm`, `Pr`).
2100    ///
2101    /// # Arguments
2102    ///
2103    /// - `&str` - Raw `.mtl` ASCII text.
2104    /// - `PbrMaterial` - Base fallback material template.
2105    ///
2106    /// # Returns
2107    ///
2108    /// - `HashMap<String, PbrMaterial>` - Parsed material table keyed by `newmtl` identifier.
2109    #[must_use]
2110    pub fn parse_mtl(mtl_source: &str, fallback: PbrMaterial) -> HashMap<String, PbrMaterial> {
2111        let mut table: HashMap<String, PbrMaterial> = HashMap::new();
2112        let mut active_name: Option<String> = None;
2113        let mut active_mat: PbrMaterial = fallback;
2114        for raw_line in mtl_source.lines() {
2115            let line: &str = raw_line.trim();
2116            if line.is_empty() || line.starts_with('#') {
2117                continue;
2118            }
2119            let parts: Vec<&str> = line.split_whitespace().collect();
2120            if parts.is_empty() {
2121                continue;
2122            }
2123            if parts[0] == MTL_DIRECTIVE_NEWMTL && parts.len() >= 2 {
2124                if let Some(prev_name) = active_name.take() {
2125                    let _: Option<PbrMaterial> = table.insert(prev_name, active_mat);
2126                }
2127                active_name = Some(parts[1].to_string());
2128                active_mat = fallback;
2129            } else if parts[0] == "Kd" && parts.len() >= 4 {
2130                let r: f32 = parts[1].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
2131                let g: f32 = parts[2].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
2132                let b: f32 = parts[3].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
2133                active_mat.set_base_color(Vec3::new(r, g, b));
2134            } else if parts[0] == "Ke" && parts.len() >= 4 {
2135                let r: f32 = parts[1].parse::<f32>().unwrap_or(0.0).max(0.0);
2136                let g: f32 = parts[2].parse::<f32>().unwrap_or(0.0).max(0.0);
2137                let b: f32 = parts[3].parse::<f32>().unwrap_or(0.0).max(0.0);
2138                active_mat.set_emissive(Vec3::new(r, g, b));
2139            } else if parts[0] == "Pm" && parts.len() >= 2 {
2140                let metal: f32 = parts[1].parse::<f32>().unwrap_or(0.0).clamp(0.0, 1.0);
2141                active_mat.set_metallic(metal);
2142            } else if parts[0] == "Pr" && parts.len() >= 2 {
2143                let rough: f32 = parts[1].parse::<f32>().unwrap_or(0.5).clamp(0.04, 1.0);
2144                active_mat.set_roughness(rough);
2145                active_mat.set_reflectivity((1.0 - rough).clamp(0.05, 0.95));
2146            } else if parts[0] == "Ns" && parts.len() >= 2 {
2147                let ns: f32 = parts[1].parse::<f32>().unwrap_or(64.0).clamp(0.0, 1000.0);
2148                let rough: f32 = (1.0 - (ns / 1000.0).sqrt()).clamp(0.04, 1.0);
2149                active_mat.set_roughness(rough);
2150                active_mat.set_reflectivity((1.0 - rough).clamp(0.05, 0.95));
2151            }
2152        }
2153        if let Some(last_name) = active_name {
2154            let _: Option<PbrMaterial> = table.insert(last_name, active_mat);
2155        }
2156        table
2157    }
2158
2159    /// Parses a Wavefront `.obj` mesh (`o`, `g`, `v`, `vt`, `vn`, `f`, `mtllib`, `usemtl`) with optional `.mtl` library, negative index support, vertex deduplication, and Lengyel tangents.
2160    ///
2161    /// # Arguments
2162    ///
2163    /// - `&str` - Raw `.obj` ASCII text.
2164    /// - `Option<&str>` - Optional companion `.mtl` ASCII text.
2165    /// - `PbrMaterial` - Fallback PBR material.
2166    ///
2167    /// # Returns
2168    ///
2169    /// - `Result<ImportedModel3D, String>` - Parsed model or error string.
2170    pub fn parse_obj_with_mtl(
2171        source: &str,
2172        mtl_source: Option<&str>,
2173        material: PbrMaterial,
2174    ) -> Result<ImportedModel3D, String> {
2175        let mtl_table: HashMap<String, PbrMaterial> = mtl_source
2176            .map(|text: &str| Self::parse_mtl(text, material))
2177            .unwrap_or_default();
2178        let mut positions: Vec<Vec3> = Vec::new();
2179        let mut uvs: Vec<[f32; 2]> = Vec::new();
2180        let mut normals: Vec<Vec3> = Vec::new();
2181        let mut vertices: Vec<Vertex3D> = Vec::new();
2182        let mut indices: Vec<[u32; 3]> = Vec::new();
2183        let mut dedup: HashMap<(usize, Option<usize>, Option<usize>), u32> = HashMap::new();
2184        let mut sub_materials: Vec<PbrMaterial> = Vec::new();
2185        let mut sub_mat_slots: HashMap<String, u16> = HashMap::new();
2186        let mut tri_materials: Vec<u16> = Vec::new();
2187        let mut active_slot: u16 = 0;
2188        let mut model_name: String = MESH_OBJ_DEFAULT_NAME.to_string();
2189        let mut saw_any_uv: bool = false;
2190        let mut saw_any_normal: bool = false;
2191        for raw_line in source.lines() {
2192            let line: &str = raw_line.trim();
2193            if line.is_empty() || line.starts_with('#') {
2194                continue;
2195            }
2196            let parts: Vec<&str> = line.split_whitespace().collect();
2197            if parts.is_empty() {
2198                continue;
2199            }
2200            match parts[0] {
2201                "o" | "g" if parts.len() >= 2 => {
2202                    model_name = parts[1].to_string();
2203                }
2204                token if token == OBJ_DIRECTIVE_MTLLIB => {}
2205                token if token == OBJ_DIRECTIVE_USEMTL && parts.len() >= 2 => {
2206                    let mat_name: &str = parts[1];
2207                    if let Some(&slot) = sub_mat_slots.get(mat_name) {
2208                        active_slot = slot;
2209                    } else if let Some(&parsed_mat) = mtl_table.get(mat_name) {
2210                        sub_materials.push(parsed_mat);
2211                        let new_slot: u16 = sub_materials.len() as u16;
2212                        let _: Option<u16> = sub_mat_slots.insert(mat_name.to_string(), new_slot);
2213                        active_slot = new_slot;
2214                    } else {
2215                        active_slot = 0;
2216                    }
2217                }
2218                "v" if parts.len() >= 4 => {
2219                    let pos_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
2220                    let pos_y: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
2221                    let pos_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
2222                    positions.push(Vec3::new(pos_x, pos_y, pos_z));
2223                }
2224                "vt" if parts.len() >= 3 => {
2225                    let coord_u: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
2226                    let coord_v: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
2227                    uvs.push([coord_u, coord_v]);
2228                    saw_any_uv = true;
2229                }
2230                "vn" if parts.len() >= 4 => {
2231                    let coord_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
2232                    let coord_y: f32 = parts[2].parse::<f32>().unwrap_or(1.0);
2233                    let coord_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
2234                    normals.push(Vec3::new(coord_x, coord_y, coord_z).normalize());
2235                    saw_any_normal = true;
2236                }
2237                "f" if parts.len() >= 4 => {
2238                    let mut face_refs: Vec<(usize, Option<usize>, Option<usize>)> =
2239                        Vec::with_capacity(parts.len() - 1);
2240                    for token in parts.iter().skip(1) {
2241                        let comps: Vec<&str> = token.split('/').collect();
2242                        let v_raw: i32 = comps
2243                            .first()
2244                            .and_then(|s: &&str| s.parse::<i32>().ok())
2245                            .unwrap_or(0);
2246                        let Some(v_idx) = Self::resolve_obj_index(v_raw, positions.len()) else {
2247                            continue;
2248                        };
2249                        let vt_idx: Option<usize> = comps
2250                            .get(1)
2251                            .and_then(|s: &&str| s.parse::<i32>().ok())
2252                            .and_then(|raw: i32| Self::resolve_obj_index(raw, uvs.len()));
2253                        let vn_idx: Option<usize> = comps
2254                            .get(2)
2255                            .and_then(|s: &&str| s.parse::<i32>().ok())
2256                            .and_then(|raw: i32| Self::resolve_obj_index(raw, normals.len()));
2257                        face_refs.push((v_idx, vt_idx, vn_idx));
2258                    }
2259                    if face_refs.len() >= 3 {
2260                        for entry_index in 1..(face_refs.len() - 1) {
2261                            let tri_keys: [(usize, Option<usize>, Option<usize>); 3] = [
2262                                face_refs[0],
2263                                face_refs[entry_index],
2264                                face_refs[entry_index + 1],
2265                            ];
2266                            let p0: Vec3 = positions[tri_keys[0].0];
2267                            let p1: Vec3 = positions[tri_keys[1].0];
2268                            let p2: Vec3 = positions[tri_keys[2].0];
2269                            let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
2270                            let mut out_tri: [u32; 3] = [0u32; 3];
2271                            for lane in 0..3usize {
2272                                let key: (usize, Option<usize>, Option<usize>) = tri_keys[lane];
2273                                let vert_id: u32 = if key.2.is_some() {
2274                                    if let Some(&existing) = dedup.get(&key) {
2275                                        existing
2276                                    } else {
2277                                        let id: u32 = vertices.len() as u32;
2278                                        let mut v: Vertex3D = Vertex3D::new(
2279                                            positions[key.0],
2280                                            key.2
2281                                                .and_then(|ni: usize| normals.get(ni).copied())
2282                                                .unwrap_or(face_n),
2283                                        );
2284                                        if let Some(ti) = key.1
2285                                            && let Some(&uv_pair) = uvs.get(ti)
2286                                        {
2287                                            v.set_uv0(uv_pair);
2288                                            v.set_flags(1);
2289                                        }
2290                                        vertices.push(v);
2291                                        let _: Option<u32> = dedup.insert(key, id);
2292                                        id
2293                                    }
2294                                } else {
2295                                    let id: u32 = vertices.len() as u32;
2296                                    let mut v: Vertex3D = Vertex3D::new(positions[key.0], face_n);
2297                                    if let Some(ti) = key.1
2298                                        && let Some(&uv_pair) = uvs.get(ti)
2299                                    {
2300                                        v.set_uv0(uv_pair);
2301                                        v.set_flags(1);
2302                                    }
2303                                    vertices.push(v);
2304                                    id
2305                                };
2306                                out_tri[lane] = vert_id;
2307                            }
2308                            indices.push(out_tri);
2309                            if !sub_materials.is_empty() {
2310                                tri_materials.push(active_slot);
2311                            }
2312                        }
2313                    }
2314                }
2315                _ => {}
2316            }
2317        }
2318        if indices.is_empty() {
2319            return Err(ERR_OBJ_EMPTY.to_string());
2320        }
2321        let mut mesh: Mesh3D = Mesh3D::from_parts(model_name.clone(), vertices, indices, material);
2322        if !sub_materials.is_empty() {
2323            if tri_materials.len() < mesh.get_indices().len() {
2324                tri_materials.resize(mesh.get_indices().len(), 0);
2325            }
2326            mesh.set_sub_materials(sub_materials);
2327            mesh.set_tri_materials(tri_materials);
2328        }
2329        if !saw_any_normal && dedup.len() < mesh.get_vertices().len() {
2330            mesh.compute_smooth_normals();
2331        }
2332        if saw_any_uv {
2333            mesh.compute_lengyel_tangents();
2334        }
2335        let total_vertices: usize = mesh.get_vertices().len();
2336        let total_triangles: usize = mesh.get_indices().len();
2337        Ok(ImportedModel3D {
2338            name: model_name,
2339            format: ModelFormat::Obj,
2340            meshes: vec![MeshLodChain::from_mesh(mesh)],
2341            total_vertices,
2342            total_triangles,
2343        })
2344    }
2345
2346    /// Parses a Wavefront `.obj` mesh (`o`, `g`, `v`, `vt`, `vn`, `f` with n-gon fan triangulation, negative indices, and auto-normals).
2347    ///
2348    /// # Arguments
2349    ///
2350    /// - `&str` - Raw `.obj` ASCII text.
2351    /// - `PbrMaterial` - Material assigned to the parsed mesh.
2352    ///
2353    /// # Returns
2354    ///
2355    /// - `Result<ImportedModel3D, String>` - Parsed model or error string.
2356    pub fn parse_obj(source: &str, material: PbrMaterial) -> Result<ImportedModel3D, String> {
2357        Self::parse_obj_with_mtl(source, None, material)
2358    }
2359
2360    /// Parses a Khronos glTF 2.0 JSON asset (full buffers/bufferViews/accessors/Principled BSDF plus legacy inline geometry fallback).
2361    ///
2362    /// # Arguments
2363    ///
2364    /// - `&str` - Raw `.gltf` JSON string.
2365    /// - `PbrMaterial` - Fallback PBR material when JSON omits `materials`.
2366    ///
2367    /// # Returns
2368    ///
2369    /// - `Result<ImportedModel3D, String>` - Parsed model bundle or validation error.
2370    pub fn parse_gltf_json(
2371        source: &str,
2372        fallback_material: PbrMaterial,
2373    ) -> Result<ImportedModel3D, String> {
2374        let scene: ImportedScene3D = parse_gltf_document(source, None, None)?;
2375        if scene.get_meshes().is_empty() {
2376            return Err(ERR_GLTF_EMPTY.to_string());
2377        }
2378        let mut model: ImportedModel3D = scene.to_imported_model(ModelFormat::GltfJson);
2379        if scene.get_materials().is_empty() {
2380            for chain in model.get_mut_meshes().iter_mut() {
2381                for lvl in chain.get_mut_levels().iter_mut() {
2382                    lvl.set_material(fallback_material);
2383                }
2384            }
2385        }
2386        Ok(model)
2387    }
2388}