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 supercar wheel assembly aligned along the X axle with matte rubber tire tread, recessed metallic brake rotor, contrasting brake caliper, and forged alloy Y-spoke or 5-twin-spoke 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, u16, u16)` - `(tire_slot, rim_slot, rotor_slot, caliper_slot)` sub-material slots.
842    /// - `bool` - When `true`, renders Lamborghini Y-spokes; when `false`, renders Shelby 5-twin-spokes.
843    fn push_supercar_wheel_assembly(
844        vertices: &mut Vec<Vertex3D>,
845        indices: &mut Vec<[u32; 3]>,
846        tri_materials: &mut Vec<u16>,
847        center: Vec3,
848        dims: (f32, f32, f32),
849        slots: (u16, u16, u16, u16),
850        y_spoke_style: bool,
851    ) {
852        let (tire_radius, rim_radius, tire_width): (f32, f32, f32) = dims;
853        let (tire_slot, rim_slot, rotor_slot, caliper_slot): (u16, u16, u16, u16) = slots;
854        let half_w: f32 = tire_width * 0.5;
855        let cx: f32 = center.get_x();
856        let cy: f32 = center.get_y();
857        let cz: f32 = center.get_z();
858        let x_left: f32 = cx - half_w;
859        let x_right: f32 = cx + half_w;
860        let left_hub: Vec3 = Vec3::new(x_left, cy, cz);
861        let right_hub: Vec3 = Vec3::new(x_right, cy, cz);
862        let outer_sign: f32 = if cx >= 0.0 { 1.0 } else { -1.0 };
863        let barrel_x: f32 = cx + outer_sign * (half_w + 0.004);
864        let rotor_x: f32 = cx + outer_sign * (half_w + 0.009);
865        let rim_x: f32 = cx + outer_sign * (half_w + 0.018);
866        let barrel_hub: Vec3 = Vec3::new(barrel_x, cy, cz);
867        let rotor_hub: Vec3 = Vec3::new(rotor_x, cy, cz);
868        let rim_hub: Vec3 = Vec3::new(rim_x, cy, cz);
869        let step_rad: f32 = (2.0 * PI) / (MESH_CAR_WHEEL_SEGMENTS as f32);
870        for seg_idx in 0..MESH_CAR_WHEEL_SEGMENTS {
871            let a0: f32 = (seg_idx as f32) * step_rad;
872            let a1: f32 = ((seg_idx + 1) as f32) * step_rad;
873            let (s0, c0): (f32, f32) = a0.sin_cos();
874            let (s1, c1): (f32, f32) = a1.sin_cos();
875            let l0: Vec3 = Vec3::new(x_left, cy + s0 * tire_radius, cz + c0 * tire_radius);
876            let l1: Vec3 = Vec3::new(x_left, cy + s1 * tire_radius, cz + c1 * tire_radius);
877            let r0: Vec3 = Vec3::new(x_right, cy + s0 * tire_radius, cz + c0 * tire_radius);
878            let r1: Vec3 = Vec3::new(x_right, cy + s1 * tire_radius, cz + c1 * tire_radius);
879            Self::push_flat_quad(
880                vertices,
881                indices,
882                tri_materials,
883                [l0, r0, r1, l1],
884                tire_slot,
885            );
886            Self::push_flat_tri(
887                vertices,
888                indices,
889                tri_materials,
890                (right_hub, r1, r0),
891                tire_slot,
892            );
893            Self::push_flat_tri(
894                vertices,
895                indices,
896                tri_materials,
897                (left_hub, l0, l1),
898                tire_slot,
899            );
900            let bm0: Vec3 = Vec3::new(barrel_x, cy + s0 * rim_radius, cz + c0 * rim_radius);
901            let bm1: Vec3 = Vec3::new(barrel_x, cy + s1 * rim_radius, cz + c1 * rim_radius);
902            let rotor_r: f32 = rim_radius * 0.72;
903            let rt0: Vec3 = Vec3::new(rotor_x, cy + s0 * rotor_r, cz + c0 * rotor_r);
904            let rt1: Vec3 = Vec3::new(rotor_x, cy + s1 * rotor_r, cz + c1 * rotor_r);
905            if outer_sign > 0.0 {
906                Self::push_flat_tri(
907                    vertices,
908                    indices,
909                    tri_materials,
910                    (barrel_hub, bm1, bm0),
911                    tire_slot,
912                );
913                Self::push_flat_tri(
914                    vertices,
915                    indices,
916                    tri_materials,
917                    (rotor_hub, rt1, rt0),
918                    rotor_slot,
919                );
920            } else {
921                Self::push_flat_tri(
922                    vertices,
923                    indices,
924                    tri_materials,
925                    (barrel_hub, bm0, bm1),
926                    tire_slot,
927                );
928                Self::push_flat_tri(
929                    vertices,
930                    indices,
931                    tri_materials,
932                    (rotor_hub, rt0, rt1),
933                    rotor_slot,
934                );
935            }
936            let lip_in: f32 = rim_radius * 0.84;
937            let rm0: Vec3 = Vec3::new(rim_x, cy + s0 * rim_radius, cz + c0 * rim_radius);
938            let rm1: Vec3 = Vec3::new(rim_x, cy + s1 * rim_radius, cz + c1 * rim_radius);
939            let ri0: Vec3 = Vec3::new(rim_x, cy + s0 * lip_in, cz + c0 * lip_in);
940            let ri1: Vec3 = Vec3::new(rim_x, cy + s1 * lip_in, cz + c1 * lip_in);
941            if outer_sign > 0.0 {
942                Self::push_flat_quad(
943                    vertices,
944                    indices,
945                    tri_materials,
946                    [ri0, rm0, rm1, ri1],
947                    rim_slot,
948                );
949            } else {
950                Self::push_flat_quad(
951                    vertices,
952                    indices,
953                    tri_materials,
954                    [ri1, rm1, rm0, ri0],
955                    rim_slot,
956                );
957            }
958        }
959        let cal_x: f32 = cx + outer_sign * (half_w + 0.013);
960        let cal_z_off: f32 = if cz < 0.0 {
961            rim_radius * 0.56
962        } else {
963            -rim_radius * 0.56
964        };
965        Self::push_box_part(
966            vertices,
967            indices,
968            tri_materials,
969            Vec3::new(cal_x, cy + rim_radius * 0.14, cz + cal_z_off),
970            Vec3::new(0.022, rim_radius * 0.62, rim_radius * 0.28),
971            caliper_slot,
972        );
973        let spoke_count: usize = 5;
974        let spoke_step: f32 = (2.0 * PI) / (spoke_count as f32);
975        let spoke_outer: f32 = rim_radius * 0.88;
976        let spoke_mid: f32 = rim_radius * 0.44;
977        let hub_r: f32 = rim_radius * 0.24;
978        for spoke_idx in 0..spoke_count {
979            let base_a: f32 = (spoke_idx as f32) * spoke_step + 0.18;
980            let (sb, cb): (f32, f32) = base_a.sin_cos();
981            let (s_hi, c_hi): (f32, f32) = (base_a + 0.12).sin_cos();
982            let (s_lo, c_lo): (f32, f32) = (base_a - 0.12).sin_cos();
983            if y_spoke_style {
984                let (s_fl, c_fl): (f32, f32) = (base_a - 0.24).sin_cos();
985                let (s_fr, c_fr): (f32, f32) = (base_a + 0.24).sin_cos();
986                let (s_fl2, c_fl2): (f32, f32) = (base_a - 0.16).sin_cos();
987                let (s_fr2, c_fr2): (f32, f32) = (base_a + 0.16).sin_cos();
988                let stem_a: Vec3 = Vec3::new(rim_x, cy + s_lo * hub_r, cz + c_lo * hub_r);
989                let stem_b: Vec3 = Vec3::new(rim_x, cy + s_hi * hub_r, cz + c_hi * hub_r);
990                let fork_c: Vec3 = Vec3::new(rim_x, cy + sb * spoke_mid, cz + cb * spoke_mid);
991                let tip_l0: Vec3 =
992                    Vec3::new(rim_x, cy + s_fl * spoke_outer, cz + c_fl * spoke_outer);
993                let tip_l1: Vec3 =
994                    Vec3::new(rim_x, cy + s_fl2 * spoke_outer, cz + c_fl2 * spoke_outer);
995                let tip_r0: Vec3 =
996                    Vec3::new(rim_x, cy + s_fr2 * spoke_outer, cz + c_fr2 * spoke_outer);
997                let tip_r1: Vec3 =
998                    Vec3::new(rim_x, cy + s_fr * spoke_outer, cz + c_fr * spoke_outer);
999                if outer_sign > 0.0 {
1000                    Self::push_flat_tri(
1001                        vertices,
1002                        indices,
1003                        tri_materials,
1004                        (stem_a, fork_c, stem_b),
1005                        rim_slot,
1006                    );
1007                    Self::push_flat_tri(
1008                        vertices,
1009                        indices,
1010                        tri_materials,
1011                        (fork_c, tip_l0, tip_l1),
1012                        rim_slot,
1013                    );
1014                    Self::push_flat_tri(
1015                        vertices,
1016                        indices,
1017                        tri_materials,
1018                        (fork_c, tip_r0, tip_r1),
1019                        rim_slot,
1020                    );
1021                } else {
1022                    Self::push_flat_tri(
1023                        vertices,
1024                        indices,
1025                        tri_materials,
1026                        (stem_a, stem_b, fork_c),
1027                        rim_slot,
1028                    );
1029                    Self::push_flat_tri(
1030                        vertices,
1031                        indices,
1032                        tri_materials,
1033                        (fork_c, tip_l1, tip_l0),
1034                        rim_slot,
1035                    );
1036                    Self::push_flat_tri(
1037                        vertices,
1038                        indices,
1039                        tri_materials,
1040                        (fork_c, tip_r1, tip_r0),
1041                        rim_slot,
1042                    );
1043                }
1044            } else {
1045                for pair_off in [-0.13_f32, 0.13_f32] {
1046                    let a_p: f32 = base_a + pair_off;
1047                    let (sp0, cp0): (f32, f32) = (a_p - 0.05).sin_cos();
1048                    let (sp1, cp1): (f32, f32) = (a_p + 0.05).sin_cos();
1049                    let p_o0: Vec3 =
1050                        Vec3::new(rim_x, cy + sp0 * spoke_outer, cz + cp0 * spoke_outer);
1051                    let p_o1: Vec3 =
1052                        Vec3::new(rim_x, cy + sp1 * spoke_outer, cz + cp1 * spoke_outer);
1053                    if outer_sign > 0.0 {
1054                        Self::push_flat_tri(
1055                            vertices,
1056                            indices,
1057                            tri_materials,
1058                            (rim_hub, p_o1, p_o0),
1059                            rim_slot,
1060                        );
1061                    } else {
1062                        Self::push_flat_tri(
1063                            vertices,
1064                            indices,
1065                            tri_materials,
1066                            (rim_hub, p_o0, p_o1),
1067                            rim_slot,
1068                        );
1069                    }
1070                }
1071            }
1072        }
1073        Self::push_box_part(
1074            vertices,
1075            indices,
1076            tri_materials,
1077            Vec3::new(rim_x + outer_sign * 0.005, cy, cz),
1078            Vec3::new(0.016, hub_r * 1.15, hub_r * 1.15),
1079            rim_slot,
1080        );
1081    }
1082
1083    /// Appends a closed N-sided extruded or twisted polygon prism connecting `bottom_ring` to `top_ring` (rings ordered CCW when viewed from `+Y`).
1084    ///
1085    /// # Arguments
1086    ///
1087    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
1088    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
1089    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
1090    /// - `&[Vec3]` - Bottom polygon vertices in CCW order from `+Y`.
1091    /// - `&[Vec3]` - Top polygon vertices matching `bottom_ring.len()` in CCW order from `+Y`.
1092    /// - `(u16, u16, u16)` - `(side_slot, top_slot, bottom_slot)` material slots.
1093    fn push_polygon_prism(
1094        vertices: &mut Vec<Vertex3D>,
1095        indices: &mut Vec<[u32; 3]>,
1096        tri_materials: &mut Vec<u16>,
1097        bottom_ring: &[Vec3],
1098        top_ring: &[Vec3],
1099        slots: (u16, u16, u16),
1100    ) {
1101        let count: usize = bottom_ring.len().min(top_ring.len());
1102        if count < 3 {
1103            return;
1104        }
1105        let (side_slot, top_slot, bottom_slot): (u16, u16, u16) = slots;
1106        let inv_n: f32 = 1.0 / (count as f32);
1107        let mut bot_center: Vec3 = Vec3::zero();
1108        let mut top_center: Vec3 = Vec3::zero();
1109        for idx in 0..count {
1110            bot_center = bot_center.add(bottom_ring[idx]);
1111            top_center = top_center.add(top_ring[idx]);
1112            let next_idx: usize = (idx + 1) % count;
1113            Self::push_flat_quad(
1114                vertices,
1115                indices,
1116                tri_materials,
1117                [
1118                    bottom_ring[idx],
1119                    bottom_ring[next_idx],
1120                    top_ring[next_idx],
1121                    top_ring[idx],
1122                ],
1123                side_slot,
1124            );
1125        }
1126        bot_center = bot_center.scale(inv_n);
1127        top_center = top_center.scale(inv_n);
1128        for idx in 0..count {
1129            let next_idx: usize = (idx + 1) % count;
1130            Self::push_flat_tri(
1131                vertices,
1132                indices,
1133                tri_materials,
1134                (top_center, top_ring[idx], top_ring[next_idx]),
1135                top_slot,
1136            );
1137            Self::push_flat_tri(
1138                vertices,
1139                indices,
1140                tri_materials,
1141                (bot_center, bottom_ring[next_idx], bottom_ring[idx]),
1142                bottom_slot,
1143            );
1144        }
1145    }
1146
1147    /// Appends a crisp oriented rectangular 3D beam spanning from `start_pt` to `end_pt` with cross-section `(half_width, half_height)`.
1148    ///
1149    /// # Arguments
1150    ///
1151    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
1152    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
1153    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
1154    /// - `(Vec3, Vec3)` - Beam endpoints `(start_pt, end_pt)`.
1155    /// - `(f32, f32)` - Half cross-section `(half_right, half_up)`.
1156    /// - `u16` - Material slot assigned to all six faces.
1157    fn push_angled_bar(
1158        vertices: &mut Vec<Vertex3D>,
1159        indices: &mut Vec<[u32; 3]>,
1160        tri_materials: &mut Vec<u16>,
1161        endpoints: (Vec3, Vec3),
1162        half_extents: (f32, f32),
1163        mat_slot: u16,
1164    ) {
1165        let (start_pt, end_pt): (Vec3, Vec3) = endpoints;
1166        let (half_right, half_up): (f32, f32) = half_extents;
1167        let axis_vec: Vec3 = end_pt.sub(start_pt);
1168        if axis_vec.length_sq() <= 1.0e-8 {
1169            return;
1170        }
1171        let fwd: Vec3 = axis_vec.normalize();
1172        let ref_up: Vec3 = if fwd.get_y().abs() > 0.92 {
1173            Vec3::new(0.0, 0.0, 1.0)
1174        } else {
1175            Vec3::new(0.0, 1.0, 0.0)
1176        };
1177        let right: Vec3 = fwd.cross(ref_up).normalize().scale(half_right);
1178        let up: Vec3 = right.cross(fwd).normalize().scale(half_up);
1179        let ring_a: [Vec3; 4] = [
1180            start_pt.sub(right).sub(up),
1181            start_pt.add(right).sub(up),
1182            start_pt.add(right).add(up),
1183            start_pt.sub(right).add(up),
1184        ];
1185        let ring_b: [Vec3; 4] = [
1186            end_pt.sub(right).sub(up),
1187            end_pt.add(right).sub(up),
1188            end_pt.add(right).add(up),
1189            end_pt.sub(right).add(up),
1190        ];
1191        for idx in 0..4usize {
1192            let next_idx: usize = (idx + 1) % 4;
1193            Self::push_flat_quad(
1194                vertices,
1195                indices,
1196                tri_materials,
1197                [ring_a[idx], ring_b[idx], ring_b[next_idx], ring_a[next_idx]],
1198                mat_slot,
1199            );
1200        }
1201        Self::push_flat_quad(
1202            vertices,
1203            indices,
1204            tri_materials,
1205            [ring_a[3], ring_a[2], ring_a[1], ring_a[0]],
1206            mat_slot,
1207        );
1208        Self::push_flat_quad(
1209            vertices,
1210            indices,
1211            tri_materials,
1212            [ring_b[0], ring_b[1], ring_b[2], ring_b[3]],
1213            mat_slot,
1214        );
1215    }
1216
1217    /// Generates an axis-aligned box mesh of dimensions `(w, h, d)` resting on `y = 0` or centered.
1218    ///
1219    /// # Arguments
1220    ///
1221    /// - `&str` - Mesh name.
1222    /// - `f32` - Width along X.
1223    /// - `f32` - Height along Y.
1224    /// - `f32` - Depth along Z.
1225    /// - `bool` - When `true`, base rests on `y = 0`; otherwise centered at origin.
1226    /// - `PbrMaterial` - Surface PBR material.
1227    ///
1228    /// # Returns
1229    ///
1230    /// - `Self` - Indexed 12-triangle box mesh with crisp flat face normals.
1231    #[must_use]
1232    pub fn box_mesh(
1233        name: &str,
1234        width_val: f32,
1235        height_val: f32,
1236        delta_val: f32,
1237        ground_pivot: bool,
1238        material: PbrMaterial,
1239    ) -> Self {
1240        let hx: f32 = width_val * 0.5;
1241        let hz: f32 = delta_val * 0.5;
1242        let y0: f32 = if ground_pivot { 0.0 } else { -height_val * 0.5 };
1243        let y1: f32 = if ground_pivot {
1244            height_val
1245        } else {
1246            height_val * 0.5
1247        };
1248        let faces: [([Vec3; 4], Vec3); 6] = [
1249            (
1250                [
1251                    Vec3::new(-hx, y0, hz),
1252                    Vec3::new(hx, y0, hz),
1253                    Vec3::new(hx, y1, hz),
1254                    Vec3::new(-hx, y1, hz),
1255                ],
1256                Vec3::new(0.0, 0.0, 1.0),
1257            ),
1258            (
1259                [
1260                    Vec3::new(hx, y0, -hz),
1261                    Vec3::new(-hx, y0, -hz),
1262                    Vec3::new(-hx, y1, -hz),
1263                    Vec3::new(hx, y1, -hz),
1264                ],
1265                Vec3::new(0.0, 0.0, -1.0),
1266            ),
1267            (
1268                [
1269                    Vec3::new(hx, y0, hz),
1270                    Vec3::new(hx, y0, -hz),
1271                    Vec3::new(hx, y1, -hz),
1272                    Vec3::new(hx, y1, hz),
1273                ],
1274                Vec3::new(1.0, 0.0, 0.0),
1275            ),
1276            (
1277                [
1278                    Vec3::new(-hx, y0, -hz),
1279                    Vec3::new(-hx, y0, hz),
1280                    Vec3::new(-hx, y1, hz),
1281                    Vec3::new(-hx, y1, -hz),
1282                ],
1283                Vec3::new(-1.0, 0.0, 0.0),
1284            ),
1285            (
1286                [
1287                    Vec3::new(-hx, y1, hz),
1288                    Vec3::new(hx, y1, hz),
1289                    Vec3::new(hx, y1, -hz),
1290                    Vec3::new(-hx, y1, -hz),
1291                ],
1292                Vec3::new(0.0, 1.0, 0.0),
1293            ),
1294            (
1295                [
1296                    Vec3::new(-hx, y0, -hz),
1297                    Vec3::new(hx, y0, -hz),
1298                    Vec3::new(hx, y0, hz),
1299                    Vec3::new(-hx, y0, hz),
1300                ],
1301                Vec3::new(0.0, -1.0, 0.0),
1302            ),
1303        ];
1304        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(24);
1305        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(12);
1306        for (quad, item_count) in faces.into_iter() {
1307            let base: u32 = vertices.len() as u32;
1308            for point_val in quad.into_iter() {
1309                vertices.push(Vertex3D::new(point_val, item_count));
1310            }
1311            indices.push([base, base + 1, base + 2]);
1312            indices.push([base, base + 2, base + 3]);
1313        }
1314        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
1315        mesh.set_is_closed(true);
1316        mesh
1317    }
1318
1319    /// Generates a horizontal ground/road quad plane at `y = 0` subdivided for crisp specular/shadow falloff.
1320    ///
1321    /// # Arguments
1322    ///
1323    /// - `&str` - Mesh name.
1324    /// - `f32` - Width along X.
1325    /// - `f32` - Depth along Z.
1326    /// - `usize` - Grid subdivisions per axis.
1327    /// - `PbrMaterial` - Surface PBR material.
1328    ///
1329    /// # Returns
1330    ///
1331    /// - `Self` - Subdivided ground plane mesh.
1332    #[must_use]
1333    pub fn ground_plane(
1334        name: &str,
1335        width_val: f32,
1336        delta_val: f32,
1337        subdivisions: usize,
1338        material: PbrMaterial,
1339    ) -> Self {
1340        let segs: usize = subdivisions.clamp(1, 16);
1341        let mut vertices: Vec<Vertex3D> = Vec::with_capacity((segs + 1) * (segs + 1));
1342        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(segs * segs * 2);
1343        let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
1344        for iz in 0..=segs {
1345            let vz: f32 = ((iz as f32) / (segs as f32) - 0.5) * delta_val;
1346            for ix in 0..=segs {
1347                let vx: f32 = ((ix as f32) / (segs as f32) - 0.5) * width_val;
1348                vertices.push(Vertex3D::new(Vec3::new(vx, 0.0, vz), up));
1349            }
1350        }
1351        let stride: u32 = (segs + 1) as u32;
1352        for iz in 0..segs {
1353            for ix in 0..segs {
1354                let i0: u32 = (iz as u32) * stride + (ix as u32);
1355                let i1: u32 = i0 + 1;
1356                let i2: u32 = i0 + stride;
1357                let i3: u32 = i2 + 1;
1358                indices.push([i0, i2, i1]);
1359                indices.push([i1, i2, i3]);
1360            }
1361        }
1362        Self::from_parts(name.to_string(), vertices, indices, material)
1363    }
1364
1365    /// 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.
1366    ///
1367    /// # Arguments
1368    ///
1369    /// - `&str` - Mesh asset name.
1370    /// - `f32` - Total horizontal outer span in meters along X and Z.
1371    /// - `f32` - Solid island half-width along X in meters.
1372    /// - `f32` - Solid island half-depth along Z in meters.
1373    /// - `usize` - Grid subdivisions along each axis (`8..=32`).
1374    /// - `PbrMaterial` - Ocean water PBR material.
1375    ///
1376    /// # Returns
1377    ///
1378    /// - `Self` - Watertight coastal ocean ring mesh with spatial meshlets.
1379    #[must_use]
1380    pub fn coastal_ocean_ring(
1381        name: &str,
1382        outer_span: f32,
1383        inner_half_x: f32,
1384        inner_half_z: f32,
1385        subdivisions: usize,
1386        material: PbrMaterial,
1387    ) -> Self {
1388        let seg_count: usize = subdivisions.clamp(8, 32);
1389        let cut_half_x: f32 = (inner_half_x - 2.0).max(0.0);
1390        let cut_half_z: f32 = (inner_half_z - 2.0).max(0.0);
1391        let mut vertices: Vec<Vertex3D> = Vec::with_capacity((seg_count + 1) * (seg_count + 1));
1392        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(seg_count * seg_count * 2);
1393        let up_normal: Vec3 = Vec3::new(0.0, 1.0, 0.0);
1394        let inv_segs: f32 = 1.0 / (seg_count as f32);
1395        for grid_z in 0..=seg_count {
1396            let pos_z: f32 = ((grid_z as f32) * inv_segs - 0.5) * outer_span;
1397            for grid_x in 0..=seg_count {
1398                let pos_x: f32 = ((grid_x as f32) * inv_segs - 0.5) * outer_span;
1399                vertices.push(Vertex3D::new(Vec3::new(pos_x, 0.0, pos_z), up_normal));
1400            }
1401        }
1402        let row_stride: u32 = (seg_count + 1) as u32;
1403        let mut block_z: usize = 0;
1404        while block_z < seg_count {
1405            let end_z: usize = (block_z + 4).min(seg_count);
1406            let mut block_x: usize = 0;
1407            while block_x < seg_count {
1408                let end_x: usize = (block_x + 4).min(seg_count);
1409                for grid_z in block_z..end_z {
1410                    let quad_z0: f32 = ((grid_z as f32) * inv_segs - 0.5) * outer_span;
1411                    let quad_z1: f32 = (((grid_z + 1) as f32) * inv_segs - 0.5) * outer_span;
1412                    for grid_x in block_x..end_x {
1413                        let quad_x0: f32 = ((grid_x as f32) * inv_segs - 0.5) * outer_span;
1414                        let quad_x1: f32 = (((grid_x + 1) as f32) * inv_segs - 0.5) * outer_span;
1415                        let inside_x: bool = quad_x0 >= -cut_half_x && quad_x1 <= cut_half_x;
1416                        let inside_z: bool = quad_z0 >= -cut_half_z && quad_z1 <= cut_half_z;
1417                        if inside_x && inside_z {
1418                            continue;
1419                        }
1420                        let idx0: u32 = (grid_z as u32) * row_stride + (grid_x as u32);
1421                        let idx1: u32 = idx0 + 1;
1422                        let idx2: u32 = idx0 + row_stride;
1423                        let idx3: u32 = idx2 + 1;
1424                        indices.push([idx0, idx2, idx1]);
1425                        indices.push([idx1, idx2, idx3]);
1426                    }
1427                }
1428                block_x += 4;
1429            }
1430            block_z += 4;
1431        }
1432        Self::from_parts(name.to_string(), vertices, indices, material)
1433    }
1434
1435    /// Builds the default sculpted GT supercar mesh (Lamborghini Aventador SVJ V12 stealth wedge).
1436    ///
1437    /// # Arguments
1438    ///
1439    /// - `&str` - Asset name.
1440    /// - `PbrMaterial` - Primary car body clearcoat paint PBR material.
1441    ///
1442    /// # Returns
1443    ///
1444    /// - `Self` - Composite multi-material vehicle mesh.
1445    #[must_use]
1446    pub fn sports_car(name: &str, material: PbrMaterial) -> Self {
1447        Self::aventador_svj(name, material)
1448    }
1449
1450    /// Builds a sculpted Lamborghini Aventador SVJ V12 stealth-fighter wedge supercar with hexagonal low nose, Y-shaped xenon DRL headlights, scissor-door mid-engine air intakes, louvered V12 engine bay with metallic plenums, swan-neck dual-pylon carbon rear wing, Y-motif crimson LED taillights, central triple hexagonal exhausts, and Y-spoke dark forged wheels with yellow ceramic brake calipers.
1451    ///
1452    /// # Arguments
1453    ///
1454    /// - `&str` - Asset name.
1455    /// - `PbrMaterial` - Primary metallic pearlescent body paint PBR material.
1456    ///
1457    /// # Returns
1458    ///
1459    /// - `Self` - Closed multi-material Lamborghini Aventador SVJ mesh.
1460    #[must_use]
1461    pub fn aventador_svj(name: &str, material: PbrMaterial) -> Self {
1462        let sub_materials: Vec<PbrMaterial> = vec![
1463            PbrMaterial::glass(Color::hex(0x070B14), 0.04),
1464            PbrMaterial::dielectric(Color::hex(0x0B0E13), 0.90),
1465            PbrMaterial::metallic(Color::hex(0x94A3B8), 0.16),
1466            PbrMaterial::pbr(Color::hex(0x11151E), 0.34, 0.30, 0.28),
1467            PbrMaterial::neon(Color::hex(0xFF1744), 3.4),
1468            PbrMaterial::neon(Color::hex(0xF8FCFF), 3.3),
1469            PbrMaterial::dielectric(Color::hex(0x04060A), 0.96),
1470            PbrMaterial::pbr(Color::hex(0xFACC15), 0.16, 0.24, 0.38),
1471            PbrMaterial::metallic(Color::hex(0xCBD5E1), 0.14),
1472            PbrMaterial::neon(Color::hex(0xFF7A00), 2.1),
1473        ];
1474        let slot_body: u16 = 0;
1475        let slot_glass: u16 = 1;
1476        let slot_tire: u16 = 2;
1477        let slot_rim: u16 = 3;
1478        let slot_carbon: u16 = 4;
1479        let slot_taillight: u16 = 5;
1480        let slot_headlight: u16 = 6;
1481        let slot_underbody: u16 = 7;
1482        let slot_caliper: u16 = 8;
1483        let slot_chrome: u16 = 9;
1484        let slot_amber: u16 = 10;
1485        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(2400);
1486        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(900);
1487        let mut tri_materials: Vec<u16> = Vec::with_capacity(900);
1488        Self::push_box_part(
1489            &mut vertices,
1490            &mut indices,
1491            &mut tri_materials,
1492            Vec3::new(0.0, 0.13, 0.02),
1493            Vec3::new(2.04, 0.16, 4.42),
1494            slot_underbody,
1495        );
1496        let splitter_bot: [Vec3; 4] = [
1497            Vec3::new(-1.08, 0.16, -1.96),
1498            Vec3::new(1.08, 0.16, -1.96),
1499            Vec3::new(0.92, 0.17, -2.42),
1500            Vec3::new(-0.92, 0.17, -2.42),
1501        ];
1502        let splitter_top: [Vec3; 4] = [
1503            Vec3::new(-1.06, 0.23, -1.96),
1504            Vec3::new(1.06, 0.23, -1.96),
1505            Vec3::new(0.88, 0.23, -2.40),
1506            Vec3::new(-0.88, 0.23, -2.40),
1507        ];
1508        Self::push_tapered_prism(
1509            &mut vertices,
1510            &mut indices,
1511            &mut tri_materials,
1512            splitter_bot,
1513            splitter_top,
1514            [slot_carbon; 6],
1515        );
1516        let nose_bot: [Vec3; 4] = [
1517            Vec3::new(-1.06, 0.22, -1.62),
1518            Vec3::new(1.06, 0.22, -1.62),
1519            Vec3::new(0.76, 0.24, -2.38),
1520            Vec3::new(-0.76, 0.24, -2.38),
1521        ];
1522        let nose_top: [Vec3; 4] = [
1523            Vec3::new(-0.98, 0.66, -1.62),
1524            Vec3::new(0.98, 0.66, -1.62),
1525            Vec3::new(0.56, 0.42, -2.36),
1526            Vec3::new(-0.56, 0.42, -2.36),
1527        ];
1528        Self::push_tapered_prism(
1529            &mut vertices,
1530            &mut indices,
1531            &mut tri_materials,
1532            nose_bot,
1533            nose_top,
1534            [
1535                slot_body,
1536                slot_carbon,
1537                slot_body,
1538                slot_body,
1539                slot_body,
1540                slot_underbody,
1541            ],
1542        );
1543        let hood_bot: [Vec3; 4] = [
1544            Vec3::new(-1.08, 0.22, -0.82),
1545            Vec3::new(1.08, 0.22, -0.82),
1546            Vec3::new(1.06, 0.22, -1.64),
1547            Vec3::new(-1.06, 0.22, -1.64),
1548        ];
1549        let hood_top: [Vec3; 4] = [
1550            Vec3::new(-1.02, 0.80, -0.82),
1551            Vec3::new(1.02, 0.80, -0.82),
1552            Vec3::new(0.98, 0.66, -1.64),
1553            Vec3::new(-0.98, 0.66, -1.64),
1554        ];
1555        Self::push_tapered_prism(
1556            &mut vertices,
1557            &mut indices,
1558            &mut tri_materials,
1559            hood_bot,
1560            hood_top,
1561            [
1562                slot_body,
1563                slot_body,
1564                slot_body,
1565                slot_body,
1566                slot_body,
1567                slot_underbody,
1568            ],
1569        );
1570        let crease_bot: [Vec3; 4] = [
1571            Vec3::new(-0.48, 0.78, -0.90),
1572            Vec3::new(0.48, 0.78, -0.90),
1573            Vec3::new(0.28, 0.44, -2.28),
1574            Vec3::new(-0.28, 0.44, -2.28),
1575        ];
1576        let crease_top: [Vec3; 4] = [
1577            Vec3::new(-0.36, 0.84, -0.94),
1578            Vec3::new(0.36, 0.84, -0.94),
1579            Vec3::new(0.18, 0.48, -2.22),
1580            Vec3::new(-0.18, 0.48, -2.22),
1581        ];
1582        Self::push_tapered_prism(
1583            &mut vertices,
1584            &mut indices,
1585            &mut tri_materials,
1586            crease_bot,
1587            crease_top,
1588            [slot_body; 6],
1589        );
1590        Self::push_box_part(
1591            &mut vertices,
1592            &mut indices,
1593            &mut tri_materials,
1594            Vec3::new(0.0, 0.34, -2.37),
1595            Vec3::new(0.22, 0.16, 0.10),
1596            slot_body,
1597        );
1598        let mid_bot: [Vec3; 4] = [
1599            Vec3::new(-1.02, 0.22, 0.96),
1600            Vec3::new(1.02, 0.22, 0.96),
1601            Vec3::new(1.02, 0.22, -0.84),
1602            Vec3::new(-1.02, 0.22, -0.84),
1603        ];
1604        let mid_top: [Vec3; 4] = [
1605            Vec3::new(-1.06, 0.92, 0.96),
1606            Vec3::new(1.06, 0.92, 0.96),
1607            Vec3::new(0.98, 0.80, -0.84),
1608            Vec3::new(-0.98, 0.80, -0.84),
1609        ];
1610        Self::push_tapered_prism(
1611            &mut vertices,
1612            &mut indices,
1613            &mut tri_materials,
1614            mid_bot,
1615            mid_top,
1616            [
1617                slot_body,
1618                slot_body,
1619                slot_body,
1620                slot_body,
1621                slot_body,
1622                slot_underbody,
1623            ],
1624        );
1625        let rear_bot: [Vec3; 4] = [
1626            Vec3::new(-1.08, 0.36, 2.34),
1627            Vec3::new(1.08, 0.36, 2.34),
1628            Vec3::new(1.18, 0.24, 0.94),
1629            Vec3::new(-1.18, 0.24, 0.94),
1630        ];
1631        let rear_top: [Vec3; 4] = [
1632            Vec3::new(-1.02, 0.96, 2.26),
1633            Vec3::new(1.02, 0.96, 2.26),
1634            Vec3::new(1.14, 0.94, 0.94),
1635            Vec3::new(-1.14, 0.94, 0.94),
1636        ];
1637        Self::push_tapered_prism(
1638            &mut vertices,
1639            &mut indices,
1640            &mut tri_materials,
1641            rear_bot,
1642            rear_top,
1643            [
1644                slot_carbon,
1645                slot_body,
1646                slot_body,
1647                slot_body,
1648                slot_body,
1649                slot_underbody,
1650            ],
1651        );
1652        for side in [-1.0_f32, 1.0_f32] {
1653            Self::push_box_part(
1654                &mut vertices,
1655                &mut indices,
1656                &mut tri_materials,
1657                Vec3::new(side * 0.48, 0.31, -2.30),
1658                Vec3::new(0.46, 0.14, 0.12),
1659                slot_carbon,
1660            );
1661            Self::push_angled_bar(
1662                &mut vertices,
1663                &mut indices,
1664                &mut tri_materials,
1665                (
1666                    Vec3::new(side * 0.20, 0.39, -2.36),
1667                    Vec3::new(side * 0.78, 0.24, -2.28),
1668                ),
1669                (0.028, 0.028),
1670                slot_body,
1671            );
1672            Self::push_box_part(
1673                &mut vertices,
1674                &mut indices,
1675                &mut tri_materials,
1676                Vec3::new(side * 1.11, 0.22, -0.02),
1677                Vec3::new(0.16, 0.12, 2.12),
1678                slot_carbon,
1679            );
1680            Self::push_box_part(
1681                &mut vertices,
1682                &mut indices,
1683                &mut tri_materials,
1684                Vec3::new(side * 1.04, 0.52, 0.64),
1685                Vec3::new(0.14, 0.32, 0.64),
1686                slot_carbon,
1687            );
1688            Self::push_angled_bar(
1689                &mut vertices,
1690                &mut indices,
1691                &mut tri_materials,
1692                (
1693                    Vec3::new(side * 1.02, 0.40, 0.28),
1694                    Vec3::new(side * 1.12, 0.68, 0.94),
1695                ),
1696                (0.032, 0.030),
1697                slot_body,
1698            );
1699            Self::push_box_part(
1700                &mut vertices,
1701                &mut indices,
1702                &mut tri_materials,
1703                Vec3::new(side * 0.94, 0.93, 0.66),
1704                Vec3::new(0.14, 0.06, 0.42),
1705                slot_carbon,
1706            );
1707            for (fender_z, flare_w, h_rear, h_front) in [
1708                (-1.42_f32, 1.15_f32, 0.75_f32, 0.56_f32),
1709                (1.44_f32, 1.21_f32, 0.96_f32, 0.95_f32),
1710            ] {
1711                let x_in: f32 = side * 0.92;
1712                let x_out_lo: f32 = side * flare_w;
1713                let x_out_hi: f32 = side * (flare_w - 0.14);
1714                let (xa, xb): (f32, f32) = if side > 0.0 {
1715                    (x_in, x_out_lo)
1716                } else {
1717                    (x_out_lo, x_in)
1718                };
1719                let (ta, tb): (f32, f32) = if side > 0.0 {
1720                    (x_in, x_out_hi)
1721                } else {
1722                    (x_out_hi, x_in)
1723                };
1724                let arch_bot: [Vec3; 4] = [
1725                    Vec3::new(xa, 0.50, fender_z + 0.54),
1726                    Vec3::new(xb, 0.50, fender_z + 0.54),
1727                    Vec3::new(xb, 0.44, fender_z - 0.54),
1728                    Vec3::new(xa, 0.44, fender_z - 0.54),
1729                ];
1730                let arch_top: [Vec3; 4] = [
1731                    Vec3::new(ta, h_rear, fender_z + 0.40),
1732                    Vec3::new(tb, h_rear, fender_z + 0.40),
1733                    Vec3::new(tb, h_front, fender_z - 0.40),
1734                    Vec3::new(ta, h_front, fender_z - 0.40),
1735                ];
1736                Self::push_tapered_prism(
1737                    &mut vertices,
1738                    &mut indices,
1739                    &mut tri_materials,
1740                    arch_bot,
1741                    arch_top,
1742                    [
1743                        slot_body,
1744                        slot_body,
1745                        slot_body,
1746                        slot_body,
1747                        slot_body,
1748                        slot_underbody,
1749                    ],
1750                );
1751                Self::push_box_part(
1752                    &mut vertices,
1753                    &mut indices,
1754                    &mut tri_materials,
1755                    Vec3::new(side * 0.92, 0.40, fender_z),
1756                    Vec3::new(0.28, 0.48, 0.86),
1757                    slot_underbody,
1758                );
1759            }
1760            Self::push_angled_bar(
1761                &mut vertices,
1762                &mut indices,
1763                &mut tri_materials,
1764                (
1765                    Vec3::new(side * 0.94, 0.84, -0.66),
1766                    Vec3::new(side * 1.12, 0.93, -0.62),
1767                ),
1768                (0.025, 0.020),
1769                slot_carbon,
1770            );
1771            Self::push_box_part(
1772                &mut vertices,
1773                &mut indices,
1774                &mut tri_materials,
1775                Vec3::new(side * 1.12, 0.94, -0.60),
1776                Vec3::new(0.16, 0.07, 0.14),
1777                slot_body,
1778            );
1779            let butt_bot: [Vec3; 4] = [
1780                Vec3::new(if side > 0.0 { 0.54 } else { -0.92 }, 0.94, 1.82),
1781                Vec3::new(if side > 0.0 { 0.92 } else { -0.54 }, 0.94, 1.82),
1782                Vec3::new(if side > 0.0 { 0.84 } else { -0.54 }, 0.92, 0.56),
1783                Vec3::new(if side > 0.0 { 0.54 } else { -0.84 }, 0.92, 0.56),
1784            ];
1785            let butt_top: [Vec3; 4] = [
1786                Vec3::new(if side > 0.0 { 0.54 } else { -0.78 }, 0.99, 1.74),
1787                Vec3::new(if side > 0.0 { 0.78 } else { -0.54 }, 0.99, 1.74),
1788                Vec3::new(if side > 0.0 { 0.66 } else { -0.50 }, 1.21, 0.56),
1789                Vec3::new(if side > 0.0 { 0.50 } else { -0.66 }, 1.21, 0.56),
1790            ];
1791            Self::push_tapered_prism(
1792                &mut vertices,
1793                &mut indices,
1794                &mut tri_materials,
1795                butt_bot,
1796                butt_top,
1797                [slot_body; 6],
1798            );
1799            let hl_in: f32 = side * 0.44;
1800            let hl_out: f32 = side * 0.84;
1801            let (hx0, hx1): (f32, f32) = if side > 0.0 {
1802                (hl_in, hl_out)
1803            } else {
1804                (hl_out, hl_in)
1805            };
1806            let hl_bot: [Vec3; 4] = [
1807                Vec3::new(hx0, 0.56, -1.86),
1808                Vec3::new(hx1, 0.56, -1.86),
1809                Vec3::new(hx1 * 0.90, 0.43, -2.28),
1810                Vec3::new(hx0 * 0.90, 0.43, -2.28),
1811            ];
1812            let hl_top: [Vec3; 4] = [
1813                Vec3::new(hx0, 0.61, -1.86),
1814                Vec3::new(hx1, 0.61, -1.86),
1815                Vec3::new(hx1 * 0.90, 0.47, -2.28),
1816                Vec3::new(hx0 * 0.90, 0.47, -2.28),
1817            ];
1818            Self::push_tapered_prism(
1819                &mut vertices,
1820                &mut indices,
1821                &mut tri_materials,
1822                hl_bot,
1823                hl_top,
1824                [slot_carbon; 6],
1825            );
1826            Self::push_angled_bar(
1827                &mut vertices,
1828                &mut indices,
1829                &mut tri_materials,
1830                (
1831                    Vec3::new(side * 0.48, 0.48, -2.26),
1832                    Vec3::new(side * 0.78, 0.61, -1.90),
1833                ),
1834                (0.024, 0.020),
1835                slot_headlight,
1836            );
1837            Self::push_angled_bar(
1838                &mut vertices,
1839                &mut indices,
1840                &mut tri_materials,
1841                (
1842                    Vec3::new(side * 0.62, 0.55, -2.08),
1843                    Vec3::new(side * 0.50, 0.62, -1.92),
1844                ),
1845                (0.020, 0.018),
1846                slot_headlight,
1847            );
1848            Self::push_angled_bar(
1849                &mut vertices,
1850                &mut indices,
1851                &mut tri_materials,
1852                (
1853                    Vec3::new(side * 0.62, 0.55, -2.08),
1854                    Vec3::new(side * 0.78, 0.52, -2.14),
1855                ),
1856                (0.020, 0.018),
1857                slot_headlight,
1858            );
1859            Self::push_angled_bar(
1860                &mut vertices,
1861                &mut indices,
1862                &mut tri_materials,
1863                (
1864                    Vec3::new(side * 0.42, 0.79, 2.35),
1865                    Vec3::new(side * 0.76, 0.79, 2.35),
1866                ),
1867                (0.036, 0.036),
1868                slot_taillight,
1869            );
1870            Self::push_angled_bar(
1871                &mut vertices,
1872                &mut indices,
1873                &mut tri_materials,
1874                (
1875                    Vec3::new(side * 0.74, 0.79, 2.35),
1876                    Vec3::new(side * 0.95, 0.88, 2.32),
1877                ),
1878                (0.032, 0.032),
1879                slot_taillight,
1880            );
1881            Self::push_angled_bar(
1882                &mut vertices,
1883                &mut indices,
1884                &mut tri_materials,
1885                (
1886                    Vec3::new(side * 0.74, 0.79, 2.35),
1887                    Vec3::new(side * 0.95, 0.70, 2.32),
1888                ),
1889                (0.032, 0.032),
1890                slot_taillight,
1891            );
1892            Self::push_box_part(
1893                &mut vertices,
1894                &mut indices,
1895                &mut tri_materials,
1896                Vec3::new(side * 0.24, 0.92, 1.24),
1897                Vec3::new(0.16, 0.08, 0.94),
1898                slot_chrome,
1899            );
1900        }
1901        let cabin_bot: [Vec3; 4] = [
1902            Vec3::new(-0.84, 0.92, 0.86),
1903            Vec3::new(0.84, 0.92, 0.86),
1904            Vec3::new(0.86, 0.78, -1.04),
1905            Vec3::new(-0.86, 0.78, -1.04),
1906        ];
1907        let cabin_top: [Vec3; 4] = [
1908            Vec3::new(-0.56, 1.22, 0.56),
1909            Vec3::new(0.56, 1.22, 0.56),
1910            Vec3::new(0.58, 1.19, -0.14),
1911            Vec3::new(-0.58, 1.19, -0.14),
1912        ];
1913        Self::push_tapered_prism(
1914            &mut vertices,
1915            &mut indices,
1916            &mut tri_materials,
1917            cabin_bot,
1918            cabin_top,
1919            [
1920                slot_glass,
1921                slot_glass,
1922                slot_glass,
1923                slot_glass,
1924                slot_body,
1925                slot_underbody,
1926            ],
1927        );
1928        let roof_bot: [Vec3; 4] = [
1929            Vec3::new(-0.54, 1.225, 0.57),
1930            Vec3::new(0.54, 1.225, 0.57),
1931            Vec3::new(0.56, 1.195, -0.15),
1932            Vec3::new(-0.56, 1.195, -0.15),
1933        ];
1934        let roof_top: [Vec3; 4] = [
1935            Vec3::new(-0.42, 1.265, 0.48),
1936            Vec3::new(0.42, 1.265, 0.48),
1937            Vec3::new(0.44, 1.240, -0.06),
1938            Vec3::new(-0.44, 1.240, -0.06),
1939        ];
1940        Self::push_tapered_prism(
1941            &mut vertices,
1942            &mut indices,
1943            &mut tri_materials,
1944            roof_bot,
1945            roof_top,
1946            [slot_body; 6],
1947        );
1948        Self::push_box_part(
1949            &mut vertices,
1950            &mut indices,
1951            &mut tri_materials,
1952            Vec3::new(0.0, 0.88, 1.24),
1953            Vec3::new(0.96, 0.08, 1.18),
1954            slot_underbody,
1955        );
1956        for (louver_z, louver_y, louver_w) in [
1957            (0.84_f32, 1.10_f32, 0.86_f32),
1958            (1.22_f32, 1.04_f32, 0.92_f32),
1959            (1.60_f32, 0.99_f32, 0.96_f32),
1960        ] {
1961            let lv_bot: [Vec3; 4] = [
1962                Vec3::new(-louver_w * 0.5, louver_y - 0.03, louver_z + 0.13),
1963                Vec3::new(louver_w * 0.5, louver_y - 0.03, louver_z + 0.13),
1964                Vec3::new(louver_w * 0.46, louver_y + 0.01, louver_z - 0.12),
1965                Vec3::new(-louver_w * 0.46, louver_y + 0.01, louver_z - 0.12),
1966            ];
1967            let lv_top: [Vec3; 4] = [
1968                Vec3::new(-louver_w * 0.48, louver_y, louver_z + 0.12),
1969                Vec3::new(louver_w * 0.48, louver_y, louver_z + 0.12),
1970                Vec3::new(louver_w * 0.44, louver_y + 0.04, louver_z - 0.11),
1971                Vec3::new(-louver_w * 0.44, louver_y + 0.04, louver_z - 0.11),
1972            ];
1973            Self::push_tapered_prism(
1974                &mut vertices,
1975                &mut indices,
1976                &mut tri_materials,
1977                lv_bot,
1978                lv_top,
1979                [slot_carbon; 6],
1980            );
1981        }
1982        Self::push_box_part(
1983            &mut vertices,
1984            &mut indices,
1985            &mut tri_materials,
1986            Vec3::new(0.0, 0.28, 2.31),
1987            Vec3::new(1.82, 0.24, 0.24),
1988            slot_carbon,
1989        );
1990        for fin_x in [-0.62_f32, -0.22_f32, 0.22_f32, 0.62_f32] {
1991            Self::push_box_part(
1992                &mut vertices,
1993                &mut indices,
1994                &mut tri_materials,
1995                Vec3::new(fin_x, 0.26, 2.39),
1996                Vec3::new(0.055, 0.22, 0.16),
1997                slot_carbon,
1998            );
1999        }
2000        Self::push_box_part(
2001            &mut vertices,
2002            &mut indices,
2003            &mut tri_materials,
2004            Vec3::new(0.0, 0.49, 2.34),
2005            Vec3::new(0.66, 0.18, 0.12),
2006            slot_carbon,
2007        );
2008        for pipe_x in [-0.18_f32, 0.0_f32, 0.18_f32] {
2009            Self::push_box_part(
2010                &mut vertices,
2011                &mut indices,
2012                &mut tri_materials,
2013                Vec3::new(pipe_x, 0.49, 2.39),
2014                Vec3::new(0.12, 0.11, 0.12),
2015                slot_chrome,
2016            );
2017            Self::push_box_part(
2018                &mut vertices,
2019                &mut indices,
2020                &mut tri_materials,
2021                Vec3::new(pipe_x, 0.49, 2.43),
2022                Vec3::new(0.07, 0.06, 0.04),
2023                slot_amber,
2024            );
2025        }
2026        let wing_bot: [Vec3; 4] = [
2027            Vec3::new(-1.04, 1.24, 2.24),
2028            Vec3::new(1.04, 1.24, 2.24),
2029            Vec3::new(0.98, 1.20, 1.90),
2030            Vec3::new(-0.98, 1.20, 1.90),
2031        ];
2032        let wing_top: [Vec3; 4] = [
2033            Vec3::new(-1.04, 1.29, 2.24),
2034            Vec3::new(1.04, 1.29, 2.24),
2035            Vec3::new(0.98, 1.24, 1.90),
2036            Vec3::new(-0.98, 1.24, 1.90),
2037        ];
2038        Self::push_tapered_prism(
2039            &mut vertices,
2040            &mut indices,
2041            &mut tri_materials,
2042            wing_bot,
2043            wing_top,
2044            [slot_carbon; 6],
2045        );
2046        Self::push_box_part(
2047            &mut vertices,
2048            &mut indices,
2049            &mut tri_materials,
2050            Vec3::new(0.0, 1.12, 2.04),
2051            Vec3::new(0.04, 0.24, 0.34),
2052            slot_carbon,
2053        );
2054        for wing_side in [-1.0_f32, 1.0_f32] {
2055            Self::push_box_part(
2056                &mut vertices,
2057                &mut indices,
2058                &mut tri_materials,
2059                Vec3::new(wing_side * 1.04, 1.24, 2.08),
2060                Vec3::new(0.045, 0.18, 0.44),
2061                slot_carbon,
2062            );
2063            Self::push_angled_bar(
2064                &mut vertices,
2065                &mut indices,
2066                &mut tri_materials,
2067                (
2068                    Vec3::new(wing_side * 0.48, 0.94, 1.94),
2069                    Vec3::new(wing_side * 0.48, 1.24, 2.08),
2070                ),
2071                (0.025, 0.065),
2072                slot_carbon,
2073            );
2074        }
2075        let wheel_specs: [(f32, f32, f32, f32, f32); 4] = [
2076            (-1.03, -1.42, 0.34, 0.24, 0.34),
2077            (1.03, -1.42, 0.34, 0.24, 0.34),
2078            (-1.06, 1.44, 0.36, 0.26, 0.44),
2079            (1.06, 1.44, 0.36, 0.26, 0.44),
2080        ];
2081        for (wheel_x, wheel_z, tire_r, rim_r, tire_w) in wheel_specs.into_iter() {
2082            Self::push_supercar_wheel_assembly(
2083                &mut vertices,
2084                &mut indices,
2085                &mut tri_materials,
2086                Vec3::new(wheel_x, tire_r, wheel_z),
2087                (tire_r, rim_r, tire_w),
2088                (slot_tire, slot_rim, slot_underbody, slot_caliper),
2089                true,
2090            );
2091        }
2092        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
2093        mesh.set_sub_materials(sub_materials);
2094        mesh.set_tri_materials(tri_materials);
2095        mesh.set_is_closed(true);
2096        mesh
2097    }
2098
2099    /// Builds a sculpted Ford Mustang Shelby GT500 Cobra fastback muscle car with long sculpted hood, recessed power-dome heat extractor, nose-to-tail twin Le Mans racing stripes, deep hexagonal Cobra grille, tri-bar fang LED headlights, fastback quarter-window louvers, blacked-out decklid panel with iconic vertical tri-bar crimson LED taillights, Gurney-flap track spoiler, quad metallic exhausts, and 5-twin-spoke forged alloy wheels with crimson Brembo brake calipers.
2100    ///
2101    /// # Arguments
2102    ///
2103    /// - `&str` - Asset name.
2104    /// - `PbrMaterial` - Primary metallic muscle-car paint PBR material.
2105    ///
2106    /// # Returns
2107    ///
2108    /// - `Self` - Closed multi-material Ford Mustang Shelby GT500 Cobra mesh.
2109    #[must_use]
2110    pub fn shelby_cobra(name: &str, material: PbrMaterial) -> Self {
2111        let sub_materials: Vec<PbrMaterial> = vec![
2112            PbrMaterial::glass(Color::hex(0x0B1220), 0.05),
2113            PbrMaterial::dielectric(Color::hex(0x0B0E13), 0.90),
2114            PbrMaterial::metallic(Color::hex(0xDCE6F2), 0.14),
2115            PbrMaterial::pbr(Color::hex(0x11151E), 0.30, 0.32, 0.26),
2116            PbrMaterial::neon(Color::hex(0xFF1744), 4.2),
2117            PbrMaterial::neon(Color::hex(0xF8FCFF), 3.9),
2118            PbrMaterial::dielectric(Color::hex(0x04060A), 0.96),
2119            PbrMaterial::pbr(Color::hex(0xF4F7FB), 0.16, 0.16, 0.55),
2120            PbrMaterial::pbr(Color::hex(0xE11D48), 0.24, 0.22, 0.42),
2121            PbrMaterial::neon(Color::hex(0xFF8800), 1.9),
2122        ];
2123        let slot_body: u16 = 0;
2124        let slot_glass: u16 = 1;
2125        let slot_tire: u16 = 2;
2126        let slot_rim: u16 = 3;
2127        let slot_carbon: u16 = 4;
2128        let slot_taillight: u16 = 5;
2129        let slot_headlight: u16 = 6;
2130        let slot_underbody: u16 = 7;
2131        let slot_stripe: u16 = 8;
2132        let slot_caliper: u16 = 9;
2133        let slot_amber: u16 = 10;
2134        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(2400);
2135        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(900);
2136        let mut tri_materials: Vec<u16> = Vec::with_capacity(900);
2137        Self::push_box_part(
2138            &mut vertices,
2139            &mut indices,
2140            &mut tri_materials,
2141            Vec3::new(0.0, 0.15, 0.0),
2142            Vec3::new(2.02, 0.18, 4.46),
2143            slot_underbody,
2144        );
2145        let chin_bot: [Vec3; 4] = [
2146            Vec3::new(-1.10, 0.18, -1.96),
2147            Vec3::new(1.10, 0.18, -1.96),
2148            Vec3::new(1.04, 0.19, -2.42),
2149            Vec3::new(-1.04, 0.19, -2.42),
2150        ];
2151        let chin_top: [Vec3; 4] = [
2152            Vec3::new(-1.08, 0.25, -1.96),
2153            Vec3::new(1.08, 0.25, -1.96),
2154            Vec3::new(1.02, 0.26, -2.40),
2155            Vec3::new(-1.02, 0.26, -2.40),
2156        ];
2157        Self::push_tapered_prism(
2158            &mut vertices,
2159            &mut indices,
2160            &mut tri_materials,
2161            chin_bot,
2162            chin_top,
2163            [slot_carbon; 6],
2164        );
2165        let hood_bot: [Vec3; 4] = [
2166            Vec3::new(-1.08, 0.24, -0.52),
2167            Vec3::new(1.08, 0.24, -0.52),
2168            Vec3::new(0.98, 0.26, -2.30),
2169            Vec3::new(-0.98, 0.26, -2.30),
2170        ];
2171        let hood_top: [Vec3; 4] = [
2172            Vec3::new(-1.02, 0.96, -0.52),
2173            Vec3::new(1.02, 0.96, -0.52),
2174            Vec3::new(0.92, 0.78, -2.38),
2175            Vec3::new(-0.92, 0.78, -2.38),
2176        ];
2177        Self::push_tapered_prism(
2178            &mut vertices,
2179            &mut indices,
2180            &mut tri_materials,
2181            hood_bot,
2182            hood_top,
2183            [
2184                slot_body,
2185                slot_body,
2186                slot_body,
2187                slot_body,
2188                slot_body,
2189                slot_underbody,
2190            ],
2191        );
2192        let dome_bot: [Vec3; 4] = [
2193            Vec3::new(-0.48, 0.93, -0.62),
2194            Vec3::new(0.48, 0.93, -0.62),
2195            Vec3::new(0.42, 0.80, -2.02),
2196            Vec3::new(-0.42, 0.80, -2.02),
2197        ];
2198        let dome_top: [Vec3; 4] = [
2199            Vec3::new(-0.40, 1.00, -0.66),
2200            Vec3::new(0.40, 1.00, -0.66),
2201            Vec3::new(0.34, 0.86, -1.94),
2202            Vec3::new(-0.34, 0.86, -1.94),
2203        ];
2204        Self::push_tapered_prism(
2205            &mut vertices,
2206            &mut indices,
2207            &mut tri_materials,
2208            dome_bot,
2209            dome_top,
2210            [slot_body; 6],
2211        );
2212        Self::push_box_part(
2213            &mut vertices,
2214            &mut indices,
2215            &mut tri_materials,
2216            Vec3::new(0.0, 0.945, -1.34),
2217            Vec3::new(0.56, 0.05, 0.64),
2218            slot_carbon,
2219        );
2220        for vent_z in [-1.54_f32, -1.34_f32, -1.14_f32] {
2221            Self::push_box_part(
2222                &mut vertices,
2223                &mut indices,
2224                &mut tri_materials,
2225                Vec3::new(0.0, 0.975, vent_z),
2226                Vec3::new(0.50, 0.025, 0.07),
2227                slot_underbody,
2228            );
2229        }
2230        Self::push_box_part(
2231            &mut vertices,
2232            &mut indices,
2233            &mut tri_materials,
2234            Vec3::new(0.0, 0.50, -2.36),
2235            Vec3::new(1.36, 0.42, 0.09),
2236            slot_carbon,
2237        );
2238        Self::push_box_part(
2239            &mut vertices,
2240            &mut indices,
2241            &mut tri_materials,
2242            Vec3::new(0.0, 0.50, -2.39),
2243            Vec3::new(1.42, 0.09, 0.06),
2244            slot_carbon,
2245        );
2246        Self::push_box_part(
2247            &mut vertices,
2248            &mut indices,
2249            &mut tri_materials,
2250            Vec3::new(0.32, 0.61, -2.41),
2251            Vec3::new(0.08, 0.11, 0.03),
2252            slot_rim,
2253        );
2254        let mid_bot: [Vec3; 4] = [
2255            Vec3::new(-1.06, 0.24, 1.08),
2256            Vec3::new(1.06, 0.24, 1.08),
2257            Vec3::new(1.06, 0.24, -0.54),
2258            Vec3::new(-1.06, 0.24, -0.54),
2259        ];
2260        let mid_top: [Vec3; 4] = [
2261            Vec3::new(-1.04, 1.00, 1.08),
2262            Vec3::new(1.04, 1.00, 1.08),
2263            Vec3::new(1.02, 0.96, -0.54),
2264            Vec3::new(-1.02, 0.96, -0.54),
2265        ];
2266        Self::push_tapered_prism(
2267            &mut vertices,
2268            &mut indices,
2269            &mut tri_materials,
2270            mid_bot,
2271            mid_top,
2272            [
2273                slot_body,
2274                slot_body,
2275                slot_body,
2276                slot_body,
2277                slot_body,
2278                slot_underbody,
2279            ],
2280        );
2281        let rear_bot: [Vec3; 4] = [
2282            Vec3::new(-1.08, 0.34, 2.34),
2283            Vec3::new(1.08, 0.34, 2.34),
2284            Vec3::new(1.16, 0.26, 1.06),
2285            Vec3::new(-1.16, 0.26, 1.06),
2286        ];
2287        let rear_top: [Vec3; 4] = [
2288            Vec3::new(-1.02, 1.02, 2.28),
2289            Vec3::new(1.02, 1.02, 2.28),
2290            Vec3::new(1.12, 1.02, 1.06),
2291            Vec3::new(-1.12, 1.02, 1.06),
2292        ];
2293        Self::push_tapered_prism(
2294            &mut vertices,
2295            &mut indices,
2296            &mut tri_materials,
2297            rear_bot,
2298            rear_top,
2299            [
2300                slot_body,
2301                slot_body,
2302                slot_body,
2303                slot_body,
2304                slot_body,
2305                slot_underbody,
2306            ],
2307        );
2308        let cabin_bot: [Vec3; 4] = [
2309            Vec3::new(-0.92, 1.00, 1.82),
2310            Vec3::new(0.92, 1.00, 1.82),
2311            Vec3::new(0.90, 0.94, -0.58),
2312            Vec3::new(-0.90, 0.94, -0.58),
2313        ];
2314        let cabin_top: [Vec3; 4] = [
2315            Vec3::new(-0.68, 1.38, 0.80),
2316            Vec3::new(0.68, 1.38, 0.80),
2317            Vec3::new(0.68, 1.36, 0.04),
2318            Vec3::new(-0.68, 1.36, 0.04),
2319        ];
2320        Self::push_tapered_prism(
2321            &mut vertices,
2322            &mut indices,
2323            &mut tri_materials,
2324            cabin_bot,
2325            cabin_top,
2326            [
2327                slot_glass,
2328                slot_glass,
2329                slot_glass,
2330                slot_glass,
2331                slot_body,
2332                slot_underbody,
2333            ],
2334        );
2335        let roof_bot: [Vec3; 4] = [
2336            Vec3::new(-0.66, 1.385, 0.81),
2337            Vec3::new(0.66, 1.385, 0.81),
2338            Vec3::new(0.66, 1.365, 0.03),
2339            Vec3::new(-0.66, 1.365, 0.03),
2340        ];
2341        let roof_top: [Vec3; 4] = [
2342            Vec3::new(-0.58, 1.425, 0.75),
2343            Vec3::new(0.58, 1.425, 0.75),
2344            Vec3::new(0.58, 1.410, 0.10),
2345            Vec3::new(-0.58, 1.410, 0.10),
2346        ];
2347        Self::push_tapered_prism(
2348            &mut vertices,
2349            &mut indices,
2350            &mut tri_materials,
2351            roof_bot,
2352            roof_top,
2353            [slot_body; 6],
2354        );
2355        for stripe_side in [-1.0_f32, 1.0_f32] {
2356            let sx0: f32 = if stripe_side > 0.0 { 0.07 } else { -0.25 };
2357            let sx1: f32 = if stripe_side > 0.0 { 0.25 } else { -0.07 };
2358            let hood_st_bot: [Vec3; 4] = [
2359                Vec3::new(sx0, 0.995, -0.60),
2360                Vec3::new(sx1, 0.995, -0.60),
2361                Vec3::new(sx1, 0.790, -2.32),
2362                Vec3::new(sx0, 0.790, -2.32),
2363            ];
2364            let hood_st_top: [Vec3; 4] = [
2365                Vec3::new(sx0, 1.015, -0.60),
2366                Vec3::new(sx1, 1.015, -0.60),
2367                Vec3::new(sx1, 0.810, -2.32),
2368                Vec3::new(sx0, 0.810, -2.32),
2369            ];
2370            Self::push_tapered_prism(
2371                &mut vertices,
2372                &mut indices,
2373                &mut tri_materials,
2374                hood_st_bot,
2375                hood_st_top,
2376                [slot_stripe; 6],
2377            );
2378            Self::push_box_part(
2379                &mut vertices,
2380                &mut indices,
2381                &mut tri_materials,
2382                Vec3::new((sx0 + sx1) * 0.5, 1.428, 0.42),
2383                Vec3::new(0.18, 0.022, 0.68),
2384                slot_stripe,
2385            );
2386            Self::push_box_part(
2387                &mut vertices,
2388                &mut indices,
2389                &mut tri_materials,
2390                Vec3::new((sx0 + sx1) * 0.5, 1.032, 2.04),
2391                Vec3::new(0.18, 0.022, 0.46),
2392                slot_stripe,
2393            );
2394            Self::push_box_part(
2395                &mut vertices,
2396                &mut indices,
2397                &mut tri_materials,
2398                Vec3::new((sx0 + sx1) * 0.5, 0.74, -2.35),
2399                Vec3::new(0.18, 0.12, 0.04),
2400                slot_stripe,
2401            );
2402        }
2403        Self::push_box_part(
2404            &mut vertices,
2405            &mut indices,
2406            &mut tri_materials,
2407            Vec3::new(0.0, 0.79, 2.33),
2408            Vec3::new(1.96, 0.30, 0.07),
2409            slot_carbon,
2410        );
2411        Self::push_box_part(
2412            &mut vertices,
2413            &mut indices,
2414            &mut tri_materials,
2415            Vec3::new(0.0, 0.79, 2.37),
2416            Vec3::new(0.14, 0.14, 0.03),
2417            slot_rim,
2418        );
2419        for side in [-1.0_f32, 1.0_f32] {
2420            Self::push_box_part(
2421                &mut vertices,
2422                &mut indices,
2423                &mut tri_materials,
2424                Vec3::new(side * 1.08, 0.24, 0.02),
2425                Vec3::new(0.14, 0.12, 2.08),
2426                slot_carbon,
2427            );
2428            Self::push_angled_bar(
2429                &mut vertices,
2430                &mut indices,
2431                &mut tri_materials,
2432                (
2433                    Vec3::new(side * 1.00, 0.34, -2.32),
2434                    Vec3::new(side * 1.12, 0.40, -2.14),
2435                ),
2436                (0.025, 0.020),
2437                slot_carbon,
2438            );
2439            Self::push_box_part(
2440                &mut vertices,
2441                &mut indices,
2442                &mut tri_materials,
2443                Vec3::new(side * 1.06, 0.64, -0.82),
2444                Vec3::new(0.08, 0.24, 0.16),
2445                slot_carbon,
2446            );
2447            Self::push_box_part(
2448                &mut vertices,
2449                &mut indices,
2450                &mut tri_materials,
2451                Vec3::new(side * 1.08, 0.64, 0.86),
2452                Vec3::new(0.10, 0.26, 0.44),
2453                slot_carbon,
2454            );
2455            for (fender_z, flare_w, h_rear, h_front) in [
2456                (-1.42_f32, 1.14_f32, 0.90_f32, 0.79_f32),
2457                (1.44_f32, 1.20_f32, 1.02_f32, 1.01_f32),
2458            ] {
2459                let x_in: f32 = side * 0.92;
2460                let x_out_lo: f32 = side * flare_w;
2461                let x_out_hi: f32 = side * (flare_w - 0.10);
2462                let (xa, xb): (f32, f32) = if side > 0.0 {
2463                    (x_in, x_out_lo)
2464                } else {
2465                    (x_out_lo, x_in)
2466                };
2467                let (ta, tb): (f32, f32) = if side > 0.0 {
2468                    (x_in, x_out_hi)
2469                } else {
2470                    (x_out_hi, x_in)
2471                };
2472                let arch_bot: [Vec3; 4] = [
2473                    Vec3::new(xa, 0.58, fender_z + 0.54),
2474                    Vec3::new(xb, 0.58, fender_z + 0.54),
2475                    Vec3::new(xb, 0.54, fender_z - 0.54),
2476                    Vec3::new(xa, 0.54, fender_z - 0.54),
2477                ];
2478                let arch_top: [Vec3; 4] = [
2479                    Vec3::new(ta, h_rear, fender_z + 0.42),
2480                    Vec3::new(tb, h_rear, fender_z + 0.42),
2481                    Vec3::new(tb, h_front, fender_z - 0.42),
2482                    Vec3::new(ta, h_front, fender_z - 0.42),
2483                ];
2484                Self::push_tapered_prism(
2485                    &mut vertices,
2486                    &mut indices,
2487                    &mut tri_materials,
2488                    arch_bot,
2489                    arch_top,
2490                    [
2491                        slot_body,
2492                        slot_body,
2493                        slot_body,
2494                        slot_body,
2495                        slot_body,
2496                        slot_underbody,
2497                    ],
2498                );
2499                Self::push_box_part(
2500                    &mut vertices,
2501                    &mut indices,
2502                    &mut tri_materials,
2503                    Vec3::new(side * 0.92, 0.44, fender_z),
2504                    Vec3::new(0.28, 0.54, 0.88),
2505                    slot_underbody,
2506                );
2507            }
2508            Self::push_box_part(
2509                &mut vertices,
2510                &mut indices,
2511                &mut tri_materials,
2512                Vec3::new(side * 1.04, 1.03, -0.34),
2513                Vec3::new(0.18, 0.08, 0.14),
2514                slot_body,
2515            );
2516            for louver_i in 0..3usize {
2517                let lz: f32 = 0.72 + (louver_i as f32) * 0.16;
2518                Self::push_angled_bar(
2519                    &mut vertices,
2520                    &mut indices,
2521                    &mut tri_materials,
2522                    (
2523                        Vec3::new(side * 0.84, 1.04, lz + 0.06),
2524                        Vec3::new(side * 0.74, 1.24, lz - 0.04),
2525                    ),
2526                    (0.020, 0.025),
2527                    slot_carbon,
2528                );
2529            }
2530            Self::push_box_part(
2531                &mut vertices,
2532                &mut indices,
2533                &mut tri_materials,
2534                Vec3::new(side * 0.74, 0.68, -2.33),
2535                Vec3::new(0.36, 0.14, 0.08),
2536                slot_carbon,
2537            );
2538            for gill_idx in 0..3usize {
2539                let gx: f32 = side * (0.61 + (gill_idx as f32) * 0.085);
2540                Self::push_box_part(
2541                    &mut vertices,
2542                    &mut indices,
2543                    &mut tri_materials,
2544                    Vec3::new(gx, 0.68, -2.37),
2545                    Vec3::new(0.045, 0.11, 0.04),
2546                    slot_headlight,
2547                );
2548            }
2549            for bar_idx in 0..3usize {
2550                let bx: f32 = side * (0.56 + (bar_idx as f32) * 0.16);
2551                Self::push_box_part(
2552                    &mut vertices,
2553                    &mut indices,
2554                    &mut tri_materials,
2555                    Vec3::new(bx, 0.79, 2.37),
2556                    Vec3::new(0.08, 0.24, 0.05),
2557                    slot_taillight,
2558                );
2559            }
2560        }
2561        Self::push_box_part(
2562            &mut vertices,
2563            &mut indices,
2564            &mut tri_materials,
2565            Vec3::new(0.0, 0.28, 2.31),
2566            Vec3::new(1.78, 0.22, 0.22),
2567            slot_carbon,
2568        );
2569        for fin_x in [-0.36_f32, -0.12_f32, 0.12_f32, 0.36_f32] {
2570            Self::push_box_part(
2571                &mut vertices,
2572                &mut indices,
2573                &mut tri_materials,
2574                Vec3::new(fin_x, 0.26, 2.38),
2575                Vec3::new(0.05, 0.20, 0.14),
2576                slot_carbon,
2577            );
2578        }
2579        for pipe_x in [-0.76_f32, -0.58_f32, 0.58_f32, 0.76_f32] {
2580            Self::push_box_part(
2581                &mut vertices,
2582                &mut indices,
2583                &mut tri_materials,
2584                Vec3::new(pipe_x, 0.30, 2.38),
2585                Vec3::new(0.11, 0.11, 0.14),
2586                slot_rim,
2587            );
2588            Self::push_box_part(
2589                &mut vertices,
2590                &mut indices,
2591                &mut tri_materials,
2592                Vec3::new(pipe_x, 0.30, 2.43),
2593                Vec3::new(0.06, 0.06, 0.04),
2594                slot_amber,
2595            );
2596        }
2597        Self::push_box_part(
2598            &mut vertices,
2599            &mut indices,
2600            &mut tri_materials,
2601            Vec3::new(0.0, 1.12, 2.24),
2602            Vec3::new(1.94, 0.05, 0.26),
2603            slot_carbon,
2604        );
2605        Self::push_box_part(
2606            &mut vertices,
2607            &mut indices,
2608            &mut tri_materials,
2609            Vec3::new(0.0, 1.16, 2.35),
2610            Vec3::new(1.92, 0.07, 0.04),
2611            slot_carbon,
2612        );
2613        for post_side in [-1.0_f32, 1.0_f32] {
2614            Self::push_box_part(
2615                &mut vertices,
2616                &mut indices,
2617                &mut tri_materials,
2618                Vec3::new(post_side * 0.74, 1.06, 2.22),
2619                Vec3::new(0.09, 0.12, 0.18),
2620                slot_carbon,
2621            );
2622            Self::push_box_part(
2623                &mut vertices,
2624                &mut indices,
2625                &mut tri_materials,
2626                Vec3::new(post_side * 0.96, 1.13, 2.24),
2627                Vec3::new(0.04, 0.12, 0.28),
2628                slot_carbon,
2629            );
2630        }
2631        let wheel_specs: [(f32, f32, f32, f32, f32); 4] = [
2632            (-1.03, -1.42, 0.35, 0.24, 0.34),
2633            (1.03, -1.42, 0.35, 0.24, 0.34),
2634            (-1.06, 1.44, 0.36, 0.25, 0.42),
2635            (1.06, 1.44, 0.36, 0.25, 0.42),
2636        ];
2637        for (wheel_x, wheel_z, tire_r, rim_r, tire_w) in wheel_specs.into_iter() {
2638            Self::push_supercar_wheel_assembly(
2639                &mut vertices,
2640                &mut indices,
2641                &mut tri_materials,
2642                Vec3::new(wheel_x, tire_r, wheel_z),
2643                (tire_r, rim_r, tire_w),
2644                (slot_tire, slot_rim, slot_carbon, slot_caliper),
2645                false,
2646            );
2647        }
2648        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
2649        mesh.set_sub_materials(sub_materials);
2650        mesh.set_tri_materials(tri_materials);
2651        mesh.set_is_closed(true);
2652        mesh
2653    }
2654
2655    /// Generates an 8-vertex CCW chamfered octagon ring centered at `(0, y, 0)` with flat cardinal walls at `±half_extent` and 45-degree corner bevels cut at `±chamfer_inner`, optionally rotated by `twist_rad` around `+Y`.
2656    ///
2657    /// # Arguments
2658    ///
2659    /// - `f32` - Elevation along Y.
2660    /// - `f32` - Half-extent to flat cardinal walls.
2661    /// - `f32` - Coordinate where diagonal corner bevel begins (`<= half_extent`).
2662    /// - `f32` - Counter-clockwise rotation around `+Y` in radians.
2663    ///
2664    /// # Returns
2665    ///
2666    /// - `[Vec3; 8]` - Eight vertices ordered CCW when viewed from `+Y`.
2667    fn building_chamfered_ring(
2668        y_val: f32,
2669        half_extent: f32,
2670        chamfer_inner: f32,
2671        twist_rad: f32,
2672    ) -> [Vec3; 8] {
2673        let raw: [(f32, f32); 8] = [
2674            (half_extent, chamfer_inner),
2675            (half_extent, -chamfer_inner),
2676            (chamfer_inner, -half_extent),
2677            (-chamfer_inner, -half_extent),
2678            (-half_extent, -chamfer_inner),
2679            (-half_extent, chamfer_inner),
2680            (-chamfer_inner, half_extent),
2681            (chamfer_inner, half_extent),
2682        ];
2683        let (sin_t, cos_t): (f32, f32) = twist_rad.sin_cos();
2684        let mut ring: [Vec3; 8] = [Vec3::zero(); 8];
2685        for (idx, &(rx, rz)) in raw.iter().enumerate() {
2686            let rot_x: f32 = rx * cos_t + rz * sin_t;
2687            let rot_z: f32 = -rx * sin_t + rz * cos_t;
2688            ring[idx] = Vec3::new(rot_x, y_val, rot_z);
2689        }
2690        ring
2691    }
2692
2693    /// Generates a 16-vertex CCW circular/slanted ring centered at `(0, y_base, 0)` with vertices aligned on cardinal axes `(±radius, 0)` and `(0, ±radius)`.
2694    ///
2695    /// # Arguments
2696    ///
2697    /// - `f32` - Base elevation along Y.
2698    /// - `f32` - Ring radius in XZ (`<= 0.50`).
2699    /// - `f32` - Linear Y slope applied along `+X` (`0.0` for horizontal rings).
2700    ///
2701    /// # Returns
2702    ///
2703    /// - `[Vec3; MESH_CYLINDER_TOWER_SEGMENTS]` - Sixteen vertices ordered CCW when viewed from `+Y`.
2704    fn building_cylinder_ring(
2705        y_base: f32,
2706        radius: f32,
2707        slope_x: f32,
2708    ) -> [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] {
2709        let mut ring: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
2710            [Vec3::zero(); MESH_CYLINDER_TOWER_SEGMENTS];
2711        let step_rad: f32 = (2.0 * PI) / (MESH_CYLINDER_TOWER_SEGMENTS as f32);
2712        for (idx, dst) in ring.iter_mut().enumerate() {
2713            let angle: f32 = (idx as f32) * step_rad;
2714            let (sin_a, cos_a): (f32, f32) = angle.sin_cos();
2715            let px: f32 = cos_a * radius;
2716            let pz: f32 = -sin_a * radius;
2717            let py: f32 = y_base + cos_a * slope_x;
2718            *dst = Vec3::new(px, py, pz);
2719        }
2720        ring
2721    }
2722
2723    /// Builds the shared 4-slot architectural accent sub-material table (`slot 1` warm stone/titanium trim, `slot 2` smoked roof/mullion, `slot 3` champagne-bronze metallic ribs/spires, `slot 4` warm illuminated crown/soffit glow).
2724    ///
2725    /// # Arguments
2726    ///
2727    /// - `Color` - Stone/trim accent color (`slot 1`).
2728    /// - `Color` - Metallic rib/spire accent color (`slot 3`).
2729    /// - `Color` - Warm illuminated architectural glow color (`slot 4`).
2730    ///
2731    /// # Returns
2732    ///
2733    /// - `Vec<PbrMaterial>` - Four architectural accent sub-materials.
2734    fn building_sub_materials(
2735        trim_color: Color,
2736        metal_color: Color,
2737        glow_color: Color,
2738    ) -> Vec<PbrMaterial> {
2739        vec![
2740            PbrMaterial::pbr(trim_color, 0.22, 0.42, 0.32),
2741            PbrMaterial::pbr(Color::hex(0x161D29), 0.36, 0.56, 0.24),
2742            PbrMaterial::metallic(metal_color, 0.18),
2743            PbrMaterial::neon(glow_color, 1.15),
2744        ]
2745    }
2746
2747    /// Builds Archetype 1: an Art-Deco stepped setback skyscraper (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) featuring a grand stone podium, three tiered setbacks with vertical corner pilasters, an illuminated warm-gold crown pavilion, and a slender tapered spire.
2748    ///
2749    /// # Arguments
2750    ///
2751    /// - `&str` - Mesh asset name.
2752    /// - `PbrMaterial` - Primary curtain-wall facade material (`slot 0`).
2753    ///
2754    /// # Returns
2755    ///
2756    /// - `Self` - Closed multi-material unit Art-Deco setback tower mesh.
2757    #[must_use]
2758    pub fn building_art_deco_tower(name: &str, material: PbrMaterial) -> Self {
2759        let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
2760            Color::hex(0x9A8970),
2761            Color::hex(0xB89456),
2762            Color::hex(0xFFCB6B),
2763        );
2764        let slot_facade: u16 = 0;
2765        let slot_stone: u16 = 1;
2766        let slot_roof: u16 = 2;
2767        let slot_metal: u16 = 3;
2768        let slot_glow: u16 = 4;
2769        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(640);
2770        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(280);
2771        let mut tri_materials: Vec<u16> = Vec::with_capacity(280);
2772        Self::push_box_part(
2773            &mut vertices,
2774            &mut indices,
2775            &mut tri_materials,
2776            Vec3::new(0.0, 0.085, 0.0),
2777            Vec3::new(1.0, 0.17, 1.0),
2778            slot_facade,
2779        );
2780        Self::push_box_part(
2781            &mut vertices,
2782            &mut indices,
2783            &mut tri_materials,
2784            Vec3::new(0.0, 0.175, 0.0),
2785            Vec3::new(1.0, 0.024, 1.0),
2786            slot_stone,
2787        );
2788        Self::push_box_part(
2789            &mut vertices,
2790            &mut indices,
2791            &mut tri_materials,
2792            Vec3::new(0.0, 0.37, 0.0),
2793            Vec3::new(0.86, 0.38, 0.86),
2794            slot_facade,
2795        );
2796        Self::push_box_part(
2797            &mut vertices,
2798            &mut indices,
2799            &mut tri_materials,
2800            Vec3::new(0.0, 0.565, 0.0),
2801            Vec3::new(0.88, 0.022, 0.88),
2802            slot_stone,
2803        );
2804        Self::push_box_part(
2805            &mut vertices,
2806            &mut indices,
2807            &mut tri_materials,
2808            Vec3::new(0.0, 0.665, 0.0),
2809            Vec3::new(0.68, 0.19, 0.68),
2810            slot_facade,
2811        );
2812        Self::push_box_part(
2813            &mut vertices,
2814            &mut indices,
2815            &mut tri_materials,
2816            Vec3::new(0.0, 0.765, 0.0),
2817            Vec3::new(0.70, 0.020, 0.70),
2818            slot_stone,
2819        );
2820        Self::push_box_part(
2821            &mut vertices,
2822            &mut indices,
2823            &mut tri_materials,
2824            Vec3::new(0.0, 0.815, 0.0),
2825            Vec3::new(0.48, 0.09, 0.48),
2826            slot_facade,
2827        );
2828        Self::push_box_part(
2829            &mut vertices,
2830            &mut indices,
2831            &mut tri_materials,
2832            Vec3::new(0.0, 0.862, 0.0),
2833            Vec3::new(0.50, 0.016, 0.50),
2834            slot_metal,
2835        );
2836        Self::push_box_part(
2837            &mut vertices,
2838            &mut indices,
2839            &mut tri_materials,
2840            Vec3::new(0.0, 0.892, 0.0),
2841            Vec3::new(0.32, 0.056, 0.32),
2842            slot_glow,
2843        );
2844        Self::push_box_part(
2845            &mut vertices,
2846            &mut indices,
2847            &mut tri_materials,
2848            Vec3::new(0.0, 0.922, 0.0),
2849            Vec3::new(0.34, 0.014, 0.34),
2850            slot_roof,
2851        );
2852        let spire_bot: [Vec3; 4] = [
2853            Vec3::new(-0.075, 0.925, 0.075),
2854            Vec3::new(0.075, 0.925, 0.075),
2855            Vec3::new(0.075, 0.925, -0.075),
2856            Vec3::new(-0.075, 0.925, -0.075),
2857        ];
2858        let spire_top: [Vec3; 4] = [
2859            Vec3::new(-0.014, 0.992, 0.014),
2860            Vec3::new(0.014, 0.992, 0.014),
2861            Vec3::new(0.014, 0.992, -0.014),
2862            Vec3::new(-0.014, 0.992, -0.014),
2863        ];
2864        Self::push_tapered_prism(
2865            &mut vertices,
2866            &mut indices,
2867            &mut tri_materials,
2868            spire_bot,
2869            spire_top,
2870            [slot_metal; 6],
2871        );
2872        Self::push_box_part(
2873            &mut vertices,
2874            &mut indices,
2875            &mut tri_materials,
2876            Vec3::new(0.0, 0.994, 0.0),
2877            Vec3::new(0.036, 0.012, 0.036),
2878            slot_glow,
2879        );
2880        for sx in [-1.0_f32, 1.0_f32] {
2881            for sz in [-1.0_f32, 1.0_f32] {
2882                Self::push_box_part(
2883                    &mut vertices,
2884                    &mut indices,
2885                    &mut tri_materials,
2886                    Vec3::new(sx * 0.445, 0.37, sz * 0.445),
2887                    Vec3::new(0.07, 0.40, 0.07),
2888                    slot_metal,
2889                );
2890                Self::push_box_part(
2891                    &mut vertices,
2892                    &mut indices,
2893                    &mut tri_materials,
2894                    Vec3::new(sx * 0.355, 0.67, sz * 0.355),
2895                    Vec3::new(0.055, 0.21, 0.055),
2896                    slot_metal,
2897                );
2898            }
2899        }
2900        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
2901        mesh.set_sub_materials(sub_materials);
2902        mesh.set_tri_materials(tri_materials);
2903        mesh.set_is_closed(true);
2904        mesh
2905    }
2906
2907    /// Builds Archetype 2: a chamfered octagonal modernist glass tower (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) with horizontal structural sky-deck slab bands, a recessed illuminated mid-level sky-garden notch, and a sculpted angled roof parapet.
2908    ///
2909    /// # Arguments
2910    ///
2911    /// - `&str` - Mesh asset name.
2912    /// - `PbrMaterial` - Primary glass curtain-wall material (`slot 0`).
2913    ///
2914    /// # Returns
2915    ///
2916    /// - `Self` - Closed multi-material unit chamfered glass tower mesh.
2917    #[must_use]
2918    pub fn building_chamfered_glass_tower(name: &str, material: PbrMaterial) -> Self {
2919        let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
2920            Color::hex(0x64748B),
2921            Color::hex(0x94A3B8),
2922            Color::hex(0x7DD3FC),
2923        );
2924        let slot_facade: u16 = 0;
2925        let slot_slab: u16 = 1;
2926        let slot_roof: u16 = 2;
2927        let slot_metal: u16 = 3;
2928        let slot_glow: u16 = 4;
2929        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(680);
2930        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(300);
2931        let mut tri_materials: Vec<u16> = Vec::with_capacity(300);
2932        let b0: [Vec3; 8] = Self::building_chamfered_ring(0.0, 0.50, 0.33, 0.0);
2933        let b1: [Vec3; 8] = Self::building_chamfered_ring(0.52, 0.50, 0.33, 0.0);
2934        Self::push_polygon_prism(
2935            &mut vertices,
2936            &mut indices,
2937            &mut tri_materials,
2938            &b0,
2939            &b1,
2940            (slot_facade, slot_roof, slot_roof),
2941        );
2942        for &band_y in &[0.14_f32, 0.33_f32, 0.51_f32, 0.76_f32] {
2943            let rb0: [Vec3; 8] = Self::building_chamfered_ring(band_y, 0.50, 0.335, 0.0);
2944            let rb1: [Vec3; 8] = Self::building_chamfered_ring(band_y + 0.024, 0.50, 0.335, 0.0);
2945            Self::push_polygon_prism(
2946                &mut vertices,
2947                &mut indices,
2948                &mut tri_materials,
2949                &rb0,
2950                &rb1,
2951                (slot_slab, slot_slab, slot_slab),
2952            );
2953        }
2954        let n0: [Vec3; 8] = Self::building_chamfered_ring(0.52, 0.40, 0.27, 0.0);
2955        let n1: [Vec3; 8] = Self::building_chamfered_ring(0.61, 0.40, 0.27, 0.0);
2956        Self::push_polygon_prism(
2957            &mut vertices,
2958            &mut indices,
2959            &mut tri_materials,
2960            &n0,
2961            &n1,
2962            (slot_facade, slot_glow, slot_roof),
2963        );
2964        for sx in [-1.0_f32, 1.0_f32] {
2965            for sz in [-1.0_f32, 1.0_f32] {
2966                Self::push_box_part(
2967                    &mut vertices,
2968                    &mut indices,
2969                    &mut tri_materials,
2970                    Vec3::new(sx * 0.37, 0.565, sz * 0.37),
2971                    Vec3::new(0.06, 0.095, 0.06),
2972                    slot_metal,
2973                );
2974            }
2975        }
2976        let u0: [Vec3; 8] = Self::building_chamfered_ring(0.61, 0.49, 0.32, 0.0);
2977        let u1: [Vec3; 8] = Self::building_chamfered_ring(0.885, 0.49, 0.32, 0.0);
2978        Self::push_polygon_prism(
2979            &mut vertices,
2980            &mut indices,
2981            &mut tri_materials,
2982            &u0,
2983            &u1,
2984            (slot_facade, slot_roof, slot_glow),
2985        );
2986        let g0: [Vec3; 8] = Self::building_chamfered_ring(0.885, 0.495, 0.325, 0.0);
2987        let g1: [Vec3; 8] = Self::building_chamfered_ring(0.912, 0.495, 0.325, 0.0);
2988        Self::push_polygon_prism(
2989            &mut vertices,
2990            &mut indices,
2991            &mut tri_materials,
2992            &g0,
2993            &g1,
2994            (slot_glow, slot_roof, slot_roof),
2995        );
2996        let c0: [Vec3; 8] = Self::building_chamfered_ring(0.912, 0.495, 0.325, 0.0);
2997        let mut c1: [Vec3; 8] = Self::building_chamfered_ring(0.955, 0.48, 0.31, 0.0);
2998        for corner in c1.iter_mut() {
2999            let slope_y: f32 = corner.get_y() + corner.get_x() * 0.088;
3000            corner.set_y(slope_y.min(1.0));
3001        }
3002        Self::push_polygon_prism(
3003            &mut vertices,
3004            &mut indices,
3005            &mut tri_materials,
3006            &c0,
3007            &c1,
3008            (slot_metal, slot_roof, slot_roof),
3009        );
3010        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
3011        mesh.set_sub_materials(sub_materials);
3012        mesh.set_tri_materials(tri_materials);
3013        mesh.set_is_closed(true);
3014        mesh
3015    }
3016
3017    /// Builds Archetype 3: a twisted tapering futuristic spire (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) with helical metallic exoskeletal ribs, a glowing observation rim band, and an asymmetrical diagonal roof fin.
3018    ///
3019    /// # Arguments
3020    ///
3021    /// - `&str` - Mesh asset name.
3022    /// - `PbrMaterial` - Primary curtain-wall facade material (`slot 0`).
3023    ///
3024    /// # Returns
3025    ///
3026    /// - `Self` - Closed multi-material unit twisted spire mesh.
3027    #[must_use]
3028    pub fn building_twisted_spire_tower(name: &str, material: PbrMaterial) -> Self {
3029        let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
3030            Color::hex(0x334155),
3031            Color::hex(0xD8E2EE),
3032            Color::hex(0x38BDF8),
3033        );
3034        let slot_facade: u16 = 0;
3035        let slot_base: u16 = 1;
3036        let slot_roof: u16 = 2;
3037        let slot_metal: u16 = 3;
3038        let slot_glow: u16 = 4;
3039        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(720);
3040        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(320);
3041        let mut tri_materials: Vec<u16> = Vec::with_capacity(320);
3042        let base_lo: [Vec3; 8] = Self::building_chamfered_ring(0.0, 0.50, 0.34, 0.0);
3043        let base_hi: [Vec3; 8] = Self::building_chamfered_ring(0.12, 0.49, 0.33, 0.0);
3044        Self::push_polygon_prism(
3045            &mut vertices,
3046            &mut indices,
3047            &mut tri_materials,
3048            &base_lo,
3049            &base_hi,
3050            (slot_base, slot_roof, slot_roof),
3051        );
3052        let tiers: [(f32, f32, f32, f32); 5] = [
3053            (0.12, 0.45, 0.30, 0.0),
3054            (0.32, 0.41, 0.27, 0.16),
3055            (0.52, 0.36, 0.24, 0.32),
3056            (0.70, 0.31, 0.20, 0.48),
3057            (0.84, 0.26, 0.17, 0.62),
3058        ];
3059        for seg_i in 0..(tiers.len() - 1) {
3060            let (y0, h0, c0, t0): (f32, f32, f32, f32) = tiers[seg_i];
3061            let (y1, h1, c1, t1): (f32, f32, f32, f32) = tiers[seg_i + 1];
3062            let r0: [Vec3; 8] = Self::building_chamfered_ring(y0, h0, c0, t0);
3063            let r1: [Vec3; 8] = Self::building_chamfered_ring(y1, h1, c1, t1);
3064            Self::push_polygon_prism(
3065                &mut vertices,
3066                &mut indices,
3067                &mut tri_materials,
3068                &r0,
3069                &r1,
3070                (slot_facade, slot_roof, slot_roof),
3071            );
3072            for rib_idx in [0usize, 2usize, 4usize, 6usize] {
3073                Self::push_angled_bar(
3074                    &mut vertices,
3075                    &mut indices,
3076                    &mut tri_materials,
3077                    (r0[rib_idx], r1[rib_idx]),
3078                    (0.022, 0.022),
3079                    slot_metal,
3080                );
3081            }
3082        }
3083        let g0: [Vec3; 8] = Self::building_chamfered_ring(0.84, 0.270, 0.175, 0.62);
3084        let g1: [Vec3; 8] = Self::building_chamfered_ring(0.860, 0.270, 0.175, 0.62);
3085        Self::push_polygon_prism(
3086            &mut vertices,
3087            &mut indices,
3088            &mut tri_materials,
3089            &g0,
3090            &g1,
3091            (slot_glow, slot_roof, slot_roof),
3092        );
3093        let cap0: [Vec3; 8] = Self::building_chamfered_ring(0.860, 0.265, 0.172, 0.62);
3094        let cap1: [Vec3; 8] = Self::building_chamfered_ring(0.880, 0.255, 0.165, 0.62);
3095        Self::push_polygon_prism(
3096            &mut vertices,
3097            &mut indices,
3098            &mut tri_materials,
3099            &cap0,
3100            &cap1,
3101            (slot_base, slot_roof, slot_roof),
3102        );
3103        let fin_bot: [Vec3; 4] = [
3104            Vec3::new(-0.20, 0.875, 0.08),
3105            Vec3::new(0.22, 0.875, 0.08),
3106            Vec3::new(0.22, 0.875, -0.08),
3107            Vec3::new(-0.20, 0.875, -0.08),
3108        ];
3109        let fin_top: [Vec3; 4] = [
3110            Vec3::new(0.06, 1.00, 0.045),
3111            Vec3::new(0.21, 0.99, 0.045),
3112            Vec3::new(0.21, 0.99, -0.045),
3113            Vec3::new(0.06, 1.00, -0.045),
3114        ];
3115        Self::push_tapered_prism(
3116            &mut vertices,
3117            &mut indices,
3118            &mut tri_materials,
3119            fin_bot,
3120            fin_top,
3121            [slot_metal; 6],
3122        );
3123        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
3124        mesh.set_sub_materials(sub_materials);
3125        mesh.set_tri_materials(tri_materials);
3126        mesh.set_is_closed(true);
3127        mesh
3128    }
3129
3130    /// Builds Archetype 4: a cantilevered contemporary tech and cultural tower (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) with a sleek glass podium, recessed atrium waist, boldly offset upper cantilevered volumes with warm illuminated overhang soffits, and a rooftop louver pergola.
3131    ///
3132    /// # Arguments
3133    ///
3134    /// - `&str` - Mesh asset name.
3135    /// - `PbrMaterial` - Primary curtain-wall facade material (`slot 0`).
3136    ///
3137    /// # Returns
3138    ///
3139    /// - `Self` - Closed multi-material unit cantilevered tower mesh.
3140    #[must_use]
3141    pub fn building_cantilever_tech_tower(name: &str, material: PbrMaterial) -> Self {
3142        let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
3143            Color::hex(0x475569),
3144            Color::hex(0xCBD5E1),
3145            Color::hex(0xFBBF24),
3146        );
3147        let slot_facade: u16 = 0;
3148        let slot_frame: u16 = 1;
3149        let slot_roof: u16 = 2;
3150        let slot_metal: u16 = 3;
3151        let slot_glow: u16 = 4;
3152        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(640);
3153        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(280);
3154        let mut tri_materials: Vec<u16> = Vec::with_capacity(280);
3155        Self::push_box_part(
3156            &mut vertices,
3157            &mut indices,
3158            &mut tri_materials,
3159            Vec3::new(0.0, 0.105, 0.0),
3160            Vec3::new(1.0, 0.21, 1.0),
3161            slot_facade,
3162        );
3163        Self::push_box_part(
3164            &mut vertices,
3165            &mut indices,
3166            &mut tri_materials,
3167            Vec3::new(0.0, 0.222, 0.0),
3168            Vec3::new(1.0, 0.024, 1.0),
3169            slot_frame,
3170        );
3171        Self::push_box_part(
3172            &mut vertices,
3173            &mut indices,
3174            &mut tri_materials,
3175            Vec3::new(0.0, 0.336, 0.0),
3176            Vec3::new(0.70, 0.204, 0.70),
3177            slot_facade,
3178        );
3179        Self::push_box_part(
3180            &mut vertices,
3181            &mut indices,
3182            &mut tri_materials,
3183            Vec3::new(-0.09, 0.448, 0.02),
3184            Vec3::new(0.80, 0.020, 0.92),
3185            slot_glow,
3186        );
3187        Self::push_box_part(
3188            &mut vertices,
3189            &mut indices,
3190            &mut tri_materials,
3191            Vec3::new(-0.09, 0.576, 0.02),
3192            Vec3::new(0.82, 0.236, 0.94),
3193            slot_facade,
3194        );
3195        Self::push_box_part(
3196            &mut vertices,
3197            &mut indices,
3198            &mut tri_materials,
3199            Vec3::new(-0.09, 0.704, 0.02),
3200            Vec3::new(0.83, 0.020, 0.95),
3201            slot_frame,
3202        );
3203        Self::push_box_part(
3204            &mut vertices,
3205            &mut indices,
3206            &mut tri_materials,
3207            Vec3::new(0.10, 0.724, -0.03),
3208            Vec3::new(0.78, 0.020, 0.90),
3209            slot_glow,
3210        );
3211        Self::push_box_part(
3212            &mut vertices,
3213            &mut indices,
3214            &mut tri_materials,
3215            Vec3::new(0.10, 0.834, -0.03),
3216            Vec3::new(0.80, 0.200, 0.92),
3217            slot_facade,
3218        );
3219        Self::push_box_part(
3220            &mut vertices,
3221            &mut indices,
3222            &mut tri_materials,
3223            Vec3::new(0.10, 0.944, -0.03),
3224            Vec3::new(0.80, 0.020, 0.92),
3225            slot_roof,
3226        );
3227        for sx in [-0.26_f32, 0.46_f32] {
3228            for sz in [-0.44_f32, 0.38_f32] {
3229                Self::push_box_part(
3230                    &mut vertices,
3231                    &mut indices,
3232                    &mut tri_materials,
3233                    Vec3::new(sx, 0.972, sz),
3234                    Vec3::new(0.04, 0.055, 0.04),
3235                    slot_metal,
3236                );
3237            }
3238        }
3239        for beam_i in 0..5usize {
3240            let bz: f32 = -0.40 + (beam_i as f32) * 0.19;
3241            Self::push_box_part(
3242                &mut vertices,
3243                &mut indices,
3244                &mut tri_materials,
3245                Vec3::new(0.10, 0.992, bz),
3246                Vec3::new(0.76, 0.016, 0.045),
3247                slot_metal,
3248            );
3249        }
3250        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
3251        mesh.set_sub_materials(sub_materials);
3252        mesh.set_tri_materials(tri_materials);
3253        mesh.set_is_closed(true);
3254        mesh
3255    }
3256
3257    /// Builds Archetype 5: a 16-sided smooth cylindrical landmark glass tower (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) with a recessed lobby colonnade, horizontal metallic floor-slab rings, and a sculpted slanted crown.
3258    ///
3259    /// # Arguments
3260    ///
3261    /// - `&str` - Mesh asset name.
3262    /// - `PbrMaterial` - Primary curved glass facade material (`slot 0`).
3263    ///
3264    /// # Returns
3265    ///
3266    /// - `Self` - Closed multi-material unit cylindrical landmark mesh.
3267    #[must_use]
3268    pub fn building_cylindrical_landmark(name: &str, material: PbrMaterial) -> Self {
3269        let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
3270            Color::hex(0xCBD5E1),
3271            Color::hex(0xE2E8F0),
3272            Color::hex(0x34D399),
3273        );
3274        let slot_facade: u16 = 0;
3275        let slot_stone: u16 = 1;
3276        let slot_roof: u16 = 2;
3277        let slot_metal: u16 = 3;
3278        let slot_glow: u16 = 4;
3279        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(920);
3280        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(420);
3281        let mut tri_materials: Vec<u16> = Vec::with_capacity(420);
3282        let lob0: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3283            Self::building_cylinder_ring(0.0, 0.46, 0.0);
3284        let lob1: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3285            Self::building_cylinder_ring(0.14, 0.46, 0.0);
3286        Self::push_polygon_prism(
3287            &mut vertices,
3288            &mut indices,
3289            &mut tri_materials,
3290            &lob0,
3291            &lob1,
3292            (slot_facade, slot_roof, slot_roof),
3293        );
3294        let col_step: f32 = (2.0 * PI) / 8.0;
3295        for col_i in 0..8usize {
3296            let ca: f32 = (col_i as f32) * col_step;
3297            let (sc, cc): (f32, f32) = ca.sin_cos();
3298            Self::push_box_part(
3299                &mut vertices,
3300                &mut indices,
3301                &mut tri_materials,
3302                Vec3::new(cc * 0.452, 0.07, -sc * 0.452),
3303                Vec3::new(0.092, 0.14, 0.092),
3304                slot_stone,
3305            );
3306        }
3307        let deck0: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3308            Self::building_cylinder_ring(0.135, 0.50, 0.0);
3309        let deck1: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3310            Self::building_cylinder_ring(0.165, 0.50, 0.0);
3311        Self::push_polygon_prism(
3312            &mut vertices,
3313            &mut indices,
3314            &mut tri_materials,
3315            &deck0,
3316            &deck1,
3317            (slot_stone, slot_stone, slot_stone),
3318        );
3319        let sh0: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3320            Self::building_cylinder_ring(0.165, 0.485, 0.0);
3321        let sh1: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3322            Self::building_cylinder_ring(0.86, 0.485, 0.0);
3323        Self::push_polygon_prism(
3324            &mut vertices,
3325            &mut indices,
3326            &mut tri_materials,
3327            &sh0,
3328            &sh1,
3329            (slot_facade, slot_roof, slot_roof),
3330        );
3331        for &ring_y in &[0.38_f32, 0.60_f32, 0.82_f32] {
3332            let r0: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3333                Self::building_cylinder_ring(ring_y, 0.50, 0.0);
3334            let r1: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3335                Self::building_cylinder_ring(ring_y + 0.022, 0.50, 0.0);
3336            Self::push_polygon_prism(
3337                &mut vertices,
3338                &mut indices,
3339                &mut tri_materials,
3340                &r0,
3341                &r1,
3342                (slot_metal, slot_metal, slot_metal),
3343            );
3344        }
3345        let cr0: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3346            Self::building_cylinder_ring(0.86, 0.485, 0.0);
3347        let cr1: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3348            Self::building_cylinder_ring(0.945, 0.46, 0.055);
3349        Self::push_polygon_prism(
3350            &mut vertices,
3351            &mut indices,
3352            &mut tri_materials,
3353            &cr0,
3354            &cr1,
3355            (slot_metal, slot_roof, slot_roof),
3356        );
3357        let gl0: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3358            Self::building_cylinder_ring(0.848, 0.495, 0.0);
3359        let gl1: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
3360            Self::building_cylinder_ring(0.864, 0.495, 0.0);
3361        Self::push_polygon_prism(
3362            &mut vertices,
3363            &mut indices,
3364            &mut tri_materials,
3365            &gl0,
3366            &gl1,
3367            (slot_glow, slot_glow, slot_glow),
3368        );
3369        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
3370        mesh.set_sub_materials(sub_materials);
3371        mesh.set_tri_materials(tri_materials);
3372        mesh.set_is_closed(true);
3373        mesh
3374    }
3375
3376    /// Builds Archetype 6: a human-scale boutique neo-classical mid-rise boulevard podium block (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) with a recessed warm-lit ground-floor retail arcade colonnade, projecting stone cornices, pilasters, terraced penthouse setback, and rooftop warm accent lighting.
3377    ///
3378    /// # Arguments
3379    ///
3380    /// - `&str` - Mesh asset name.
3381    /// - `PbrMaterial` - Primary architectural facade material (`slot 0`).
3382    ///
3383    /// # Returns
3384    ///
3385    /// - `Self` - Closed multi-material unit boutique boulevard podium mesh.
3386    #[must_use]
3387    pub fn building_boutique_podium_block(name: &str, material: PbrMaterial) -> Self {
3388        let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
3389            Color::hex(0xA6957C),
3390            Color::hex(0x9B7B4A),
3391            Color::hex(0xFDE68A),
3392        );
3393        let slot_facade: u16 = 0;
3394        let slot_stone: u16 = 1;
3395        let slot_roof: u16 = 2;
3396        let slot_metal: u16 = 3;
3397        let slot_glow: u16 = 4;
3398        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(720);
3399        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(320);
3400        let mut tri_materials: Vec<u16> = Vec::with_capacity(320);
3401        Self::push_box_part(
3402            &mut vertices,
3403            &mut indices,
3404            &mut tri_materials,
3405            Vec3::new(0.0, 0.14, 0.0),
3406            Vec3::new(0.88, 0.28, 0.88),
3407            slot_facade,
3408        );
3409        Self::push_box_part(
3410            &mut vertices,
3411            &mut indices,
3412            &mut tri_materials,
3413            Vec3::new(0.0, 0.245, 0.0),
3414            Vec3::new(0.90, 0.036, 0.90),
3415            slot_glow,
3416        );
3417        let pier_coords: [f32; 3] = [-0.455, 0.0, 0.455];
3418        for &px in pier_coords.iter() {
3419            for &pz in pier_coords.iter() {
3420                if px.abs() < 0.01 && pz.abs() < 0.01 {
3421                    continue;
3422                }
3423                Self::push_box_part(
3424                    &mut vertices,
3425                    &mut indices,
3426                    &mut tri_materials,
3427                    Vec3::new(px, 0.14, pz),
3428                    Vec3::new(0.09, 0.28, 0.09),
3429                    slot_stone,
3430                );
3431            }
3432        }
3433        Self::push_box_part(
3434            &mut vertices,
3435            &mut indices,
3436            &mut tri_materials,
3437            Vec3::new(0.0, 0.305, 0.0),
3438            Vec3::new(1.0, 0.05, 1.0),
3439            slot_stone,
3440        );
3441        Self::push_box_part(
3442            &mut vertices,
3443            &mut indices,
3444            &mut tri_materials,
3445            Vec3::new(0.0, 0.54, 0.0),
3446            Vec3::new(0.92, 0.43, 0.92),
3447            slot_facade,
3448        );
3449        for sx in [-1.0_f32, 1.0_f32] {
3450            for sz in [-1.0_f32, 1.0_f32] {
3451                Self::push_box_part(
3452                    &mut vertices,
3453                    &mut indices,
3454                    &mut tri_materials,
3455                    Vec3::new(sx * 0.455, 0.54, sz * 0.455),
3456                    Vec3::new(0.075, 0.44, 0.075),
3457                    slot_stone,
3458                );
3459            }
3460        }
3461        Self::push_box_part(
3462            &mut vertices,
3463            &mut indices,
3464            &mut tri_materials,
3465            Vec3::new(0.0, 0.775, 0.0),
3466            Vec3::new(1.0, 0.05, 1.0),
3467            slot_stone,
3468        );
3469        Self::push_box_part(
3470            &mut vertices,
3471            &mut indices,
3472            &mut tri_materials,
3473            Vec3::new(0.0, 0.87, 0.0),
3474            Vec3::new(0.66, 0.14, 0.66),
3475            slot_facade,
3476        );
3477        Self::push_box_part(
3478            &mut vertices,
3479            &mut indices,
3480            &mut tri_materials,
3481            Vec3::new(0.0, 0.948, 0.0),
3482            Vec3::new(0.70, 0.020, 0.70),
3483            slot_roof,
3484        );
3485        Self::push_box_part(
3486            &mut vertices,
3487            &mut indices,
3488            &mut tri_materials,
3489            Vec3::new(0.0, 0.968, 0.0),
3490            Vec3::new(0.64, 0.018, 0.64),
3491            slot_glow,
3492        );
3493        for sx in [-0.28_f32, 0.28_f32] {
3494            Self::push_box_part(
3495                &mut vertices,
3496                &mut indices,
3497                &mut tri_materials,
3498                Vec3::new(sx, 0.988, 0.0),
3499                Vec3::new(0.04, 0.024, 0.62),
3500                slot_metal,
3501            );
3502        }
3503        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
3504        mesh.set_sub_materials(sub_materials);
3505        mesh.set_tri_materials(tri_materials);
3506        mesh.set_is_closed(true);
3507        mesh
3508    }
3509
3510    /// Builds an instanced Vice Boulevard coastal palm tree with a gracefully leaning segmented trunk and seven arching multi-segment tropical fronds.
3511    ///
3512    /// # Arguments
3513    ///
3514    /// - `&str` - Asset name.
3515    ///
3516    /// # Returns
3517    ///
3518    /// - `Self` - Multi-material palm tree mesh (`slot 0` warm bark trunk, `slot 1` emerald tropical fronds).
3519    #[must_use]
3520    pub fn palm_tree(name: &str) -> Self {
3521        let bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
3522        let frond_top_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x227848), 0.05, 0.56, 0.08);
3523        let frond_under_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x134A2D), 0.04, 0.68, 0.05);
3524        let sub_materials: Vec<PbrMaterial> = vec![frond_top_mat, frond_under_mat];
3525        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(520);
3526        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(260);
3527        let mut tri_materials: Vec<u16> = Vec::with_capacity(260);
3528        let ring_specs: [(f32, f32, f32, f32); 5] = [
3529            (0.0, 0.0, 0.0, 0.30),
3530            (1.9, 0.14, 0.05, 0.25),
3531            (3.9, 0.32, 0.08, 0.21),
3532            (5.8, 0.44, 0.06, 0.17),
3533            (7.5, 0.48, 0.02, 0.14),
3534        ];
3535        let trunk_step: f32 = (2.0 * PI) / (MESH_PALM_TRUNK_SEGMENTS as f32);
3536        for seg_idx in 0..4usize {
3537            let (y0, ox0, oz0, r0): (f32, f32, f32, f32) = ring_specs[seg_idx];
3538            let (y1, ox1, oz1, r1): (f32, f32, f32, f32) = ring_specs[seg_idx + 1];
3539            for side_idx in 0..MESH_PALM_TRUNK_SEGMENTS {
3540                let a0: f32 = (side_idx as f32) * trunk_step;
3541                let a1: f32 = ((side_idx + 1) as f32) * trunk_step;
3542                let (s0, c0): (f32, f32) = a0.sin_cos();
3543                let (s1, c1): (f32, f32) = a1.sin_cos();
3544                let p0: Vec3 = Vec3::new(ox0 + c0 * r0, y0, oz0 + s0 * r0);
3545                let p1: Vec3 = Vec3::new(ox0 + c1 * r0, y0, oz0 + s1 * r0);
3546                let p2: Vec3 = Vec3::new(ox1 + c1 * r1, y1, oz1 + s1 * r1);
3547                let p3: Vec3 = Vec3::new(ox1 + c0 * r1, y1, oz1 + s0 * r1);
3548                Self::push_flat_quad(
3549                    &mut vertices,
3550                    &mut indices,
3551                    &mut tri_materials,
3552                    [p0, p1, p2, p3],
3553                    0,
3554                );
3555            }
3556        }
3557        let crown: Vec3 = Vec3::new(0.48, 7.45, 0.02);
3558        let frond_step: f32 = (2.0 * PI) / (MESH_PALM_FROND_COUNT as f32);
3559        for tier_idx in 0..2usize {
3560            let tier_count: usize = if tier_idx == 0 {
3561                MESH_PALM_FROND_COUNT
3562            } else {
3563                5
3564            };
3565            let tier_step: f32 = if tier_idx == 0 {
3566                frond_step
3567            } else {
3568                (2.0 * PI) / 5.0
3569            };
3570            let tier_yaw_off: f32 = if tier_idx == 0 { 0.25 } else { 0.62 };
3571            let tier_origin: Vec3 = crown.add(Vec3::new(0.0, (tier_idx as f32) * 0.22, 0.0));
3572            for frond_idx in 0..tier_count {
3573                let yaw: f32 = (frond_idx as f32) * tier_step + tier_yaw_off;
3574                let (sy, cy): (f32, f32) = yaw.sin_cos();
3575                let dir: Vec3 = Vec3::new(cy, 0.0, sy);
3576                let right: Vec3 = Vec3::new(-sy, 0.0, cy);
3577                let reach: f32 = if tier_idx == 0 {
3578                    if frond_idx % 2 == 0 { 2.85 } else { 2.45 }
3579                } else {
3580                    1.85
3581                };
3582                let lift: f32 = if tier_idx == 0 { 0.48 } else { 0.92 };
3583                let drop_tip: f32 = if tier_idx == 0 { -1.18 } else { -0.18 };
3584                let p_mid: Vec3 = tier_origin
3585                    .add(dir.scale(reach * 0.44))
3586                    .add(Vec3::new(0.0, lift, 0.0));
3587                let p_arch: Vec3 = tier_origin.add(dir.scale(reach * 0.78)).add(Vec3::new(
3588                    0.0,
3589                    lift * 0.15 - 0.12,
3590                    0.0,
3591                ));
3592                let p_tip: Vec3 = tier_origin
3593                    .add(dir.scale(reach))
3594                    .add(Vec3::new(0.0, drop_tip, 0.0));
3595                let w_mid: Vec3 = right.scale(if tier_idx == 0 { 0.34 } else { 0.26 });
3596                let w_arch: Vec3 = right.scale(if tier_idx == 0 { 0.24 } else { 0.18 });
3597                let sag_mid: Vec3 = Vec3::new(0.0, -0.16, 0.0);
3598                let sag_arch: Vec3 = Vec3::new(0.0, -0.20, 0.0);
3599                let mid_l: Vec3 = p_mid.sub(w_mid).add(sag_mid);
3600                let mid_r: Vec3 = p_mid.add(w_mid).add(sag_mid);
3601                let arch_l: Vec3 = p_arch.sub(w_arch).add(sag_arch);
3602                let arch_r: Vec3 = p_arch.add(w_arch).add(sag_arch);
3603                Self::push_flat_tri(
3604                    &mut vertices,
3605                    &mut indices,
3606                    &mut tri_materials,
3607                    (tier_origin, p_mid, mid_l),
3608                    1,
3609                );
3610                Self::push_flat_tri(
3611                    &mut vertices,
3612                    &mut indices,
3613                    &mut tri_materials,
3614                    (tier_origin, mid_r, p_mid),
3615                    1,
3616                );
3617                Self::push_flat_tri(
3618                    &mut vertices,
3619                    &mut indices,
3620                    &mut tri_materials,
3621                    (tier_origin, mid_l, p_mid),
3622                    2,
3623                );
3624                Self::push_flat_tri(
3625                    &mut vertices,
3626                    &mut indices,
3627                    &mut tri_materials,
3628                    (tier_origin, p_mid, mid_r),
3629                    2,
3630                );
3631                Self::push_flat_quad(
3632                    &mut vertices,
3633                    &mut indices,
3634                    &mut tri_materials,
3635                    [mid_l, p_mid, p_arch, arch_l],
3636                    1,
3637                );
3638                Self::push_flat_quad(
3639                    &mut vertices,
3640                    &mut indices,
3641                    &mut tri_materials,
3642                    [p_mid, mid_r, arch_r, p_arch],
3643                    1,
3644                );
3645                Self::push_flat_quad(
3646                    &mut vertices,
3647                    &mut indices,
3648                    &mut tri_materials,
3649                    [arch_l, p_arch, p_mid, mid_l],
3650                    2,
3651                );
3652                Self::push_flat_quad(
3653                    &mut vertices,
3654                    &mut indices,
3655                    &mut tri_materials,
3656                    [p_arch, arch_r, mid_r, p_mid],
3657                    2,
3658                );
3659                Self::push_flat_tri(
3660                    &mut vertices,
3661                    &mut indices,
3662                    &mut tri_materials,
3663                    (arch_l, p_arch, p_tip),
3664                    1,
3665                );
3666                Self::push_flat_tri(
3667                    &mut vertices,
3668                    &mut indices,
3669                    &mut tri_materials,
3670                    (p_arch, arch_r, p_tip),
3671                    1,
3672                );
3673                Self::push_flat_tri(
3674                    &mut vertices,
3675                    &mut indices,
3676                    &mut tri_materials,
3677                    (p_arch, arch_l, p_tip),
3678                    2,
3679                );
3680                Self::push_flat_tri(
3681                    &mut vertices,
3682                    &mut indices,
3683                    &mut tri_materials,
3684                    (arch_r, p_arch, p_tip),
3685                    2,
3686                );
3687            }
3688        }
3689        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, bark_mat);
3690        mesh.set_sub_materials(sub_materials);
3691        mesh.set_tri_materials(tri_materials);
3692        mesh.set_is_closed(false);
3693        mesh
3694    }
3695
3696    /// Builds a box mesh from a fluent `BoxMeshDesc`.
3697    ///
3698    /// # Arguments
3699    ///
3700    /// - `&BoxMeshDesc` - Box mesh descriptor.
3701    ///
3702    /// # Returns
3703    ///
3704    /// - `Self` - Indexed 12-triangle box mesh.
3705    #[must_use]
3706    pub fn from_box_desc(desc: &BoxMeshDesc) -> Self {
3707        let size: Vec3 = desc.get_size();
3708        Self::box_mesh(
3709            desc.get_name(),
3710            size.get_x(),
3711            size.get_y(),
3712            size.get_z(),
3713            desc.get_ground_pivot(),
3714            desc.get_material(),
3715        )
3716    }
3717
3718    /// Builds a subdivided ground plane from a fluent `GroundPlaneDesc`.
3719    ///
3720    /// # Arguments
3721    ///
3722    /// - `&GroundPlaneDesc` - Ground plane descriptor.
3723    ///
3724    /// # Returns
3725    ///
3726    /// - `Self` - Subdivided ground plane mesh.
3727    #[must_use]
3728    pub fn from_ground_desc(desc: &GroundPlaneDesc) -> Self {
3729        Self::ground_plane(
3730            desc.get_name(),
3731            desc.get_width(),
3732            desc.get_depth(),
3733            desc.get_subdivisions(),
3734            desc.get_material(),
3735        )
3736    }
3737
3738    /// Builds a simplified proxy mesh enclosing this mesh's axis-aligned bounding box for distant LOD tiers.
3739    ///
3740    /// # Arguments
3741    ///
3742    /// - `&Self` - Source mesh reference.
3743    /// - `&str` - LOD suffix label.
3744    ///
3745    /// # Returns
3746    ///
3747    /// - `Self` - Lightweight 12-triangle LOD proxy mesh.
3748    #[must_use]
3749    pub fn build_lod_proxy(&self, suffix: &str) -> Self {
3750        let blue_val: AxisAlignedBox3D = self.get_bounds();
3751        let size: Vec3 = blue_val.get_max().sub(blue_val.get_min());
3752        let center: Vec3 = blue_val.center();
3753        let mut proxy: Self = Self::box_mesh(
3754            &format!("{}_{suffix}", self.get_name()),
3755            size.get_x().max(0.2),
3756            size.get_y().max(0.2),
3757            size.get_z().max(0.2),
3758            false,
3759            self.get_material(),
3760        );
3761        for item_val in proxy.get_mut_vertices().iter_mut() {
3762            item_val.set_position(item_val.get_position().add(center));
3763        }
3764        proxy.set_bounds(blue_val);
3765        let meshlets: Vec<Meshlet3D> =
3766            Self::build_meshlets_from_parts(proxy.get_vertices(), proxy.get_indices());
3767        proxy.set_meshlets(meshlets);
3768        proxy
3769    }
3770
3771    /// Produces a mid-detail decimated mesh by retaining dominant triangles while preserving bounding silhouette.
3772    ///
3773    /// # Arguments
3774    ///
3775    /// - `&Self` - Source mesh reference.
3776    /// - `&str` - LOD suffix label.
3777    ///
3778    /// # Returns
3779    ///
3780    /// - `Self` - Decimated intermediate LOD mesh.
3781    #[must_use]
3782    pub fn build_mid_lod(&self, suffix: &str) -> Self {
3783        let verts: &[Vertex3D] = self.get_vertices().as_slice();
3784        let tris: &[[u32; 3]] = self.get_indices().as_slice();
3785        if tris.len() <= 24 {
3786            return self.build_lod_proxy(suffix);
3787        }
3788        let mut scored: Vec<(f32, [u32; 3], u16)> = Vec::with_capacity(tris.len());
3789        let default_mat: PbrMaterial = self.get_material();
3790        for (tri_idx, tri) in tris.iter().copied().enumerate() {
3791            let (i0, i1, i2): (usize, usize, usize) =
3792                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3793            if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3794                let p0: Vec3 = verts[i0].get_position();
3795                let p1: Vec3 = verts[i1].get_position();
3796                let p2: Vec3 = verts[i2].get_position();
3797                let area2: f32 = p1.sub(p0).cross(p2.sub(p0)).length_sq();
3798                let (resolved_mat, slot): (PbrMaterial, u16) =
3799                    self.resolve_triangle_material(tri_idx, default_mat);
3800                let emissive_boost: f32 = if resolved_mat.get_emissive().length_sq() > 0.25 {
3801                    8.0
3802                } else {
3803                    1.0
3804                };
3805                scored.push((area2 * emissive_boost, tri, slot));
3806            }
3807        }
3808        scored.sort_unstable_by(
3809            |alpha_val: &(f32, [u32; 3], u16), blue_val: &(f32, [u32; 3], u16)| {
3810                blue_val.0.total_cmp(&alpha_val.0)
3811            },
3812        );
3813        let keep: usize = (scored.len() / 2).max(12);
3814        let mut reduced: Vec<[u32; 3]> = Vec::with_capacity(keep);
3815        let mut reduced_slots: Vec<u16> = if self.get_tri_materials().is_empty() {
3816            Vec::new()
3817        } else {
3818            Vec::with_capacity(keep)
3819        };
3820        for (_, tri, slot) in scored.into_iter().take(keep) {
3821            reduced.push(tri);
3822            if !self.get_tri_materials().is_empty() {
3823                reduced_slots.push(slot);
3824            }
3825        }
3826        let mut mid_mesh: Self = Self::from_parts(
3827            format!("{}_{suffix}", self.get_name()),
3828            self.get_vertices().clone(),
3829            reduced,
3830            self.get_material(),
3831        );
3832        if !reduced_slots.is_empty() {
3833            mid_mesh.set_sub_materials(self.get_sub_materials().clone());
3834            mid_mesh.set_tri_materials(reduced_slots);
3835        }
3836        mid_mesh.set_is_closed(self.get_is_closed());
3837        mid_mesh
3838    }
3839}
3840
3841/// Multi-level continuous LOD chain creation and screen-error selection for `MeshLodChain`.
3842impl MeshLodChain {
3843    /// Builds a continuous 3-tier Nanite-style LOD chain (`LOD0` full -> `LOD1` mid -> `LOD2` proxy) automatically.
3844    ///
3845    /// # Arguments
3846    ///
3847    /// - `Mesh3D` - Full-resolution `LOD0` mesh.
3848    ///
3849    /// # Returns
3850    ///
3851    /// - `Self` - Ready LOD chain.
3852    #[must_use]
3853    pub fn from_mesh(mesh: Mesh3D) -> Self {
3854        let tri_count: usize = mesh.get_indices().len();
3855        if tri_count > 32 {
3856            let lod1: Mesh3D = mesh.build_mid_lod(MESH_LOD1_SUFFIX);
3857            let lod2: Mesh3D = mesh.build_lod_proxy(MESH_LOD2_SUFFIX);
3858            Self {
3859                levels: vec![mesh, lod1, lod2],
3860            }
3861        } else if tri_count > 16 {
3862            let lod1: Mesh3D = mesh.build_lod_proxy(MESH_LOD1_SUFFIX);
3863            Self {
3864                levels: vec![mesh, lod1],
3865            }
3866        } else {
3867            let clone_lod1: Mesh3D = mesh.clone();
3868            Self {
3869                levels: vec![mesh, clone_lod1],
3870            }
3871        }
3872    }
3873
3874    /// Wraps a sculpted hero or foliage mesh in a single-level LOD chain so it never degrades into an opaque bounding-box proxy.
3875    ///
3876    /// # Arguments
3877    ///
3878    /// - `Mesh3D` - Full-resolution `LOD0` mesh.
3879    ///
3880    /// # Returns
3881    ///
3882    /// - `Self` - Single-tier LOD chain preserving exact silhouette at all distances.
3883    #[must_use]
3884    pub fn single_level(mesh: Mesh3D) -> Self {
3885        Self { levels: vec![mesh] }
3886    }
3887
3888    /// Selects the appropriate `Mesh3D` detail level for `distance` and `lod_bias`.
3889    ///
3890    /// # Arguments
3891    ///
3892    /// - `&Self` - LOD chain reference.
3893    /// - `f32` - Camera-to-object distance in meters.
3894    /// - `f32` - Quality LOD bias multiplier.
3895    ///
3896    /// # Returns
3897    ///
3898    /// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
3899    #[must_use]
3900    pub fn select(&self, distance: f32, lod_bias: f32) -> (&Mesh3D, usize) {
3901        let levels: &[Mesh3D] = self.get_levels().as_slice();
3902        let effective_dist: f32 = distance * lod_bias.max(0.25);
3903        if levels.len() > 2 && effective_dist > 135.0 {
3904            (&levels[2], 2)
3905        } else if levels.len() > 1 && effective_dist > 78.0 {
3906            (&levels[1], 1)
3907        } else {
3908            (&levels[0], 0)
3909        }
3910    }
3911
3912    /// Nanite-style continuous LOD selection driven by projected screen-space pixel coverage.
3913    ///
3914    /// # Arguments
3915    ///
3916    /// - `&Self` - LOD chain reference.
3917    /// - `f32` - Camera-to-object distance in meters.
3918    /// - `f32` - World-space bounding sphere radius in meters.
3919    /// - `f32` - Projected viewport focal length in pixels (`height / (2 * tan(fov/2))`).
3920    /// - `f32` - Quality LOD bias multiplier (`< 1.0` higher detail, `> 1.0` aggressive simplification).
3921    ///
3922    /// # Returns
3923    ///
3924    /// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
3925    #[must_use]
3926    pub fn select_screen_error(
3927        &self,
3928        distance: f32,
3929        bounds_radius: f32,
3930        focal_px: f32,
3931        lod_bias: f32,
3932    ) -> (&Mesh3D, usize) {
3933        let levels: &[Mesh3D] = self.get_levels().as_slice();
3934        let safe_dist: f32 = distance.max(0.5);
3935        let projected_px: f32 =
3936            (bounds_radius.max(0.2) * focal_px) / (safe_dist * lod_bias.max(0.25));
3937        if levels.len() > 2 && projected_px < 3.5 {
3938            (&levels[2], 2)
3939        } else if levels.len() > 1 && projected_px < 9.0 {
3940            (&levels[1], 1)
3941        } else {
3942            (&levels[0], 0)
3943        }
3944    }
3945}
3946
3947/// Native Wavefront `.obj`, Khronos glTF 2.0 `.gltf`/`.glb`, and baked binary model importers for `ModelImporter3D`.
3948impl ModelImporter3D {
3949    /// Imports a 3D model from text source in the specified `ModelFormat` and generates LOD chains.
3950    ///
3951    /// # Arguments
3952    ///
3953    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
3954    /// - `&str` - Raw `.obj` or `.gltf` text content.
3955    /// - `PbrMaterial` - Fallback PBR material when source omits material definitions.
3956    ///
3957    /// # Returns
3958    ///
3959    /// - `Result<ImportedModel3D, String>` - Imported model bundle or parse error diagnostic.
3960    pub fn import(
3961        format: ModelFormat,
3962        source: &str,
3963        fallback_material: PbrMaterial,
3964    ) -> Result<ImportedModel3D, String> {
3965        match format {
3966            ModelFormat::Obj => Self::parse_obj(source, fallback_material),
3967            ModelFormat::GltfJson => Self::parse_gltf_json(source, fallback_material),
3968            ModelFormat::GlbBinary | ModelFormat::Euv3dBinary | ModelFormat::BlendInspect => {
3969                Err(ERR_TEXT_FORMAT_UNSUPPORTED.to_string())
3970            }
3971        }
3972    }
3973
3974    /// Imports a 3D model from raw binary or UTF-8 bytes in `Obj`, `GltfJson`, or `GlbBinary` format.
3975    ///
3976    /// # Arguments
3977    ///
3978    /// - `ModelFormat` - Source interchange format.
3979    /// - `&[u8]` - Raw file bytes.
3980    /// - `PbrMaterial` - Fallback PBR material when source omits material definitions.
3981    ///
3982    /// # Returns
3983    ///
3984    /// - `Result<ImportedModel3D, String>` - Imported model bundle or parse error.
3985    pub fn import_bytes(
3986        format: ModelFormat,
3987        bytes: &[u8],
3988        fallback_material: PbrMaterial,
3989    ) -> Result<ImportedModel3D, String> {
3990        match format {
3991            ModelFormat::Obj => {
3992                let text: &str = from_utf8(bytes)
3993                    .ok()
3994                    .ok_or_else(|| ERR_OBJ_EMPTY.to_string())?;
3995                Self::parse_obj(text, fallback_material)
3996            }
3997            ModelFormat::GltfJson => {
3998                let text: &str = from_utf8(bytes)
3999                    .ok()
4000                    .ok_or_else(|| ERR_GLTF_EMPTY.to_string())?;
4001                Self::parse_gltf_json(text, fallback_material)
4002            }
4003            ModelFormat::GlbBinary => {
4004                let scene: ImportedScene3D = parse_glb_bytes(bytes)?;
4005                if scene.get_meshes().is_empty() {
4006                    return Err(ERR_GLTF_EMPTY.to_string());
4007                }
4008                let mut model: ImportedModel3D = scene.to_imported_model(ModelFormat::GlbBinary);
4009                if scene.get_materials().is_empty() {
4010                    for chain in model.get_mut_meshes().iter_mut() {
4011                        for lvl in chain.get_mut_levels().iter_mut() {
4012                            lvl.set_material(fallback_material);
4013                        }
4014                    }
4015                }
4016                Ok(model)
4017            }
4018            ModelFormat::Euv3dBinary => {
4019                let bundle: BakedAssetBundle3D = Euv3dPackage::decode_bytes(bytes)?;
4020                if bundle.get_lod_chains().is_empty() {
4021                    return Err(ERR_GLTF_EMPTY.to_string());
4022                }
4023                let total_vertices: usize = bundle
4024                    .get_lod_chains()
4025                    .iter()
4026                    .filter_map(|c: &MeshLodChain| c.get_levels().first())
4027                    .map(|m: &Mesh3D| m.get_vertices().len())
4028                    .sum();
4029                let total_triangles: usize = bundle
4030                    .get_lod_chains()
4031                    .iter()
4032                    .filter_map(|c: &MeshLodChain| c.get_levels().first())
4033                    .map(|m: &Mesh3D| m.get_indices().len())
4034                    .sum();
4035                Ok(ImportedModel3D {
4036                    name: bundle.get_scene().get_name().clone(),
4037                    format: ModelFormat::Euv3dBinary,
4038                    meshes: bundle.get_lod_chains().clone(),
4039                    total_vertices,
4040                    total_triangles,
4041                })
4042            }
4043            ModelFormat::BlendInspect => Err(ERR_BINARY_FORMAT_UNSUPPORTED.to_string()),
4044        }
4045    }
4046
4047    /// Resolves a signed 1-based Wavefront OBJ index (positive or negative relative to `len`) into a 0-based index.
4048    ///
4049    /// # Arguments
4050    ///
4051    /// - `i32` - Signed 1-based OBJ index.
4052    /// - `usize` - Current length of the corresponding attribute array.
4053    ///
4054    /// # Returns
4055    ///
4056    /// - `Option<usize>` - Resolved 0-based index if in bounds.
4057    #[must_use]
4058    fn resolve_obj_index(raw: i32, len: usize) -> Option<usize> {
4059        if raw > 0 {
4060            let idx: usize = (raw - 1) as usize;
4061            if idx < len { Some(idx) } else { None }
4062        } else if raw < 0 {
4063            let idx: isize = (len as isize) + (raw as isize);
4064            if idx >= 0 && (idx as usize) < len {
4065                Some(idx as usize)
4066            } else {
4067                None
4068            }
4069        } else {
4070            None
4071        }
4072    }
4073
4074    /// Parses a Wavefront `.mtl` material library into a named `PbrMaterial` map (`Kd`, `Ke`, `Ns`, `Pm`, `Pr`).
4075    ///
4076    /// # Arguments
4077    ///
4078    /// - `&str` - Raw `.mtl` ASCII text.
4079    /// - `PbrMaterial` - Base fallback material template.
4080    ///
4081    /// # Returns
4082    ///
4083    /// - `HashMap<String, PbrMaterial>` - Parsed material table keyed by `newmtl` identifier.
4084    #[must_use]
4085    pub fn parse_mtl(mtl_source: &str, fallback: PbrMaterial) -> HashMap<String, PbrMaterial> {
4086        let mut table: HashMap<String, PbrMaterial> = HashMap::new();
4087        let mut active_name: Option<String> = None;
4088        let mut active_mat: PbrMaterial = fallback;
4089        for raw_line in mtl_source.lines() {
4090            let line: &str = raw_line.trim();
4091            if line.is_empty() || line.starts_with('#') {
4092                continue;
4093            }
4094            let parts: Vec<&str> = line.split_whitespace().collect();
4095            if parts.is_empty() {
4096                continue;
4097            }
4098            if parts[0] == MTL_DIRECTIVE_NEWMTL && parts.len() >= 2 {
4099                if let Some(prev_name) = active_name.take() {
4100                    let _: Option<PbrMaterial> = table.insert(prev_name, active_mat);
4101                }
4102                active_name = Some(parts[1].to_string());
4103                active_mat = fallback;
4104            } else if parts[0] == "Kd" && parts.len() >= 4 {
4105                let r: f32 = parts[1].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
4106                let g: f32 = parts[2].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
4107                let b: f32 = parts[3].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
4108                active_mat.set_base_color(Vec3::new(r, g, b));
4109            } else if parts[0] == "Ke" && parts.len() >= 4 {
4110                let r: f32 = parts[1].parse::<f32>().unwrap_or(0.0).max(0.0);
4111                let g: f32 = parts[2].parse::<f32>().unwrap_or(0.0).max(0.0);
4112                let b: f32 = parts[3].parse::<f32>().unwrap_or(0.0).max(0.0);
4113                active_mat.set_emissive(Vec3::new(r, g, b));
4114            } else if parts[0] == "Pm" && parts.len() >= 2 {
4115                let metal: f32 = parts[1].parse::<f32>().unwrap_or(0.0).clamp(0.0, 1.0);
4116                active_mat.set_metallic(metal);
4117            } else if parts[0] == "Pr" && parts.len() >= 2 {
4118                let rough: f32 = parts[1].parse::<f32>().unwrap_or(0.5).clamp(0.04, 1.0);
4119                active_mat.set_roughness(rough);
4120                active_mat.set_reflectivity((1.0 - rough).clamp(0.05, 0.95));
4121            } else if parts[0] == "Ns" && parts.len() >= 2 {
4122                let ns: f32 = parts[1].parse::<f32>().unwrap_or(64.0).clamp(0.0, 1000.0);
4123                let rough: f32 = (1.0 - (ns / 1000.0).sqrt()).clamp(0.04, 1.0);
4124                active_mat.set_roughness(rough);
4125                active_mat.set_reflectivity((1.0 - rough).clamp(0.05, 0.95));
4126            }
4127        }
4128        if let Some(last_name) = active_name {
4129            let _: Option<PbrMaterial> = table.insert(last_name, active_mat);
4130        }
4131        table
4132    }
4133
4134    /// 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.
4135    ///
4136    /// # Arguments
4137    ///
4138    /// - `&str` - Raw `.obj` ASCII text.
4139    /// - `Option<&str>` - Optional companion `.mtl` ASCII text.
4140    /// - `PbrMaterial` - Fallback PBR material.
4141    ///
4142    /// # Returns
4143    ///
4144    /// - `Result<ImportedModel3D, String>` - Parsed model or error string.
4145    pub fn parse_obj_with_mtl(
4146        source: &str,
4147        mtl_source: Option<&str>,
4148        material: PbrMaterial,
4149    ) -> Result<ImportedModel3D, String> {
4150        let mtl_table: HashMap<String, PbrMaterial> = mtl_source
4151            .map(|text: &str| Self::parse_mtl(text, material))
4152            .unwrap_or_default();
4153        let mut positions: Vec<Vec3> = Vec::new();
4154        let mut uvs: Vec<[f32; 2]> = Vec::new();
4155        let mut normals: Vec<Vec3> = Vec::new();
4156        let mut vertices: Vec<Vertex3D> = Vec::new();
4157        let mut indices: Vec<[u32; 3]> = Vec::new();
4158        let mut dedup: HashMap<(usize, Option<usize>, Option<usize>), u32> = HashMap::new();
4159        let mut sub_materials: Vec<PbrMaterial> = Vec::new();
4160        let mut sub_mat_slots: HashMap<String, u16> = HashMap::new();
4161        let mut tri_materials: Vec<u16> = Vec::new();
4162        let mut active_slot: u16 = 0;
4163        let mut model_name: String = MESH_OBJ_DEFAULT_NAME.to_string();
4164        let mut saw_any_uv: bool = false;
4165        let mut saw_any_normal: bool = false;
4166        for raw_line in source.lines() {
4167            let line: &str = raw_line.trim();
4168            if line.is_empty() || line.starts_with('#') {
4169                continue;
4170            }
4171            let parts: Vec<&str> = line.split_whitespace().collect();
4172            if parts.is_empty() {
4173                continue;
4174            }
4175            match parts[0] {
4176                "o" | "g" if parts.len() >= 2 => {
4177                    model_name = parts[1].to_string();
4178                }
4179                token if token == OBJ_DIRECTIVE_MTLLIB => {}
4180                token if token == OBJ_DIRECTIVE_USEMTL && parts.len() >= 2 => {
4181                    let mat_name: &str = parts[1];
4182                    if let Some(&slot) = sub_mat_slots.get(mat_name) {
4183                        active_slot = slot;
4184                    } else if let Some(&parsed_mat) = mtl_table.get(mat_name) {
4185                        sub_materials.push(parsed_mat);
4186                        let new_slot: u16 = sub_materials.len() as u16;
4187                        let _: Option<u16> = sub_mat_slots.insert(mat_name.to_string(), new_slot);
4188                        active_slot = new_slot;
4189                    } else {
4190                        active_slot = 0;
4191                    }
4192                }
4193                "v" if parts.len() >= 4 => {
4194                    let pos_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
4195                    let pos_y: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
4196                    let pos_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
4197                    positions.push(Vec3::new(pos_x, pos_y, pos_z));
4198                }
4199                "vt" if parts.len() >= 3 => {
4200                    let coord_u: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
4201                    let coord_v: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
4202                    uvs.push([coord_u, coord_v]);
4203                    saw_any_uv = true;
4204                }
4205                "vn" if parts.len() >= 4 => {
4206                    let coord_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
4207                    let coord_y: f32 = parts[2].parse::<f32>().unwrap_or(1.0);
4208                    let coord_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
4209                    normals.push(Vec3::new(coord_x, coord_y, coord_z).normalize());
4210                    saw_any_normal = true;
4211                }
4212                "f" if parts.len() >= 4 => {
4213                    let mut face_refs: Vec<(usize, Option<usize>, Option<usize>)> =
4214                        Vec::with_capacity(parts.len() - 1);
4215                    for token in parts.iter().skip(1) {
4216                        let comps: Vec<&str> = token.split('/').collect();
4217                        let v_raw: i32 = comps
4218                            .first()
4219                            .and_then(|s: &&str| s.parse::<i32>().ok())
4220                            .unwrap_or(0);
4221                        let Some(v_idx) = Self::resolve_obj_index(v_raw, positions.len()) else {
4222                            continue;
4223                        };
4224                        let vt_idx: Option<usize> = comps
4225                            .get(1)
4226                            .and_then(|s: &&str| s.parse::<i32>().ok())
4227                            .and_then(|raw: i32| Self::resolve_obj_index(raw, uvs.len()));
4228                        let vn_idx: Option<usize> = comps
4229                            .get(2)
4230                            .and_then(|s: &&str| s.parse::<i32>().ok())
4231                            .and_then(|raw: i32| Self::resolve_obj_index(raw, normals.len()));
4232                        face_refs.push((v_idx, vt_idx, vn_idx));
4233                    }
4234                    if face_refs.len() >= 3 {
4235                        for entry_index in 1..(face_refs.len() - 1) {
4236                            let tri_keys: [(usize, Option<usize>, Option<usize>); 3] = [
4237                                face_refs[0],
4238                                face_refs[entry_index],
4239                                face_refs[entry_index + 1],
4240                            ];
4241                            let p0: Vec3 = positions[tri_keys[0].0];
4242                            let p1: Vec3 = positions[tri_keys[1].0];
4243                            let p2: Vec3 = positions[tri_keys[2].0];
4244                            let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
4245                            let mut out_tri: [u32; 3] = [0u32; 3];
4246                            for lane in 0..3usize {
4247                                let key: (usize, Option<usize>, Option<usize>) = tri_keys[lane];
4248                                let vert_id: u32 = if key.2.is_some() {
4249                                    if let Some(&existing) = dedup.get(&key) {
4250                                        existing
4251                                    } else {
4252                                        let id: u32 = vertices.len() as u32;
4253                                        let mut v: Vertex3D = Vertex3D::new(
4254                                            positions[key.0],
4255                                            key.2
4256                                                .and_then(|ni: usize| normals.get(ni).copied())
4257                                                .unwrap_or(face_n),
4258                                        );
4259                                        if let Some(ti) = key.1
4260                                            && let Some(&uv_pair) = uvs.get(ti)
4261                                        {
4262                                            v.set_uv0(uv_pair);
4263                                            v.set_flags(1);
4264                                        }
4265                                        vertices.push(v);
4266                                        let _: Option<u32> = dedup.insert(key, id);
4267                                        id
4268                                    }
4269                                } else {
4270                                    let id: u32 = vertices.len() as u32;
4271                                    let mut v: Vertex3D = Vertex3D::new(positions[key.0], face_n);
4272                                    if let Some(ti) = key.1
4273                                        && let Some(&uv_pair) = uvs.get(ti)
4274                                    {
4275                                        v.set_uv0(uv_pair);
4276                                        v.set_flags(1);
4277                                    }
4278                                    vertices.push(v);
4279                                    id
4280                                };
4281                                out_tri[lane] = vert_id;
4282                            }
4283                            indices.push(out_tri);
4284                            if !sub_materials.is_empty() {
4285                                tri_materials.push(active_slot);
4286                            }
4287                        }
4288                    }
4289                }
4290                _ => {}
4291            }
4292        }
4293        if indices.is_empty() {
4294            return Err(ERR_OBJ_EMPTY.to_string());
4295        }
4296        let mut mesh: Mesh3D = Mesh3D::from_parts(model_name.clone(), vertices, indices, material);
4297        if !sub_materials.is_empty() {
4298            if tri_materials.len() < mesh.get_indices().len() {
4299                tri_materials.resize(mesh.get_indices().len(), 0);
4300            }
4301            mesh.set_sub_materials(sub_materials);
4302            mesh.set_tri_materials(tri_materials);
4303        }
4304        if !saw_any_normal && dedup.len() < mesh.get_vertices().len() {
4305            mesh.compute_smooth_normals();
4306        }
4307        if saw_any_uv {
4308            mesh.compute_lengyel_tangents();
4309        }
4310        let total_vertices: usize = mesh.get_vertices().len();
4311        let total_triangles: usize = mesh.get_indices().len();
4312        Ok(ImportedModel3D {
4313            name: model_name,
4314            format: ModelFormat::Obj,
4315            meshes: vec![MeshLodChain::from_mesh(mesh)],
4316            total_vertices,
4317            total_triangles,
4318        })
4319    }
4320
4321    /// Parses a Wavefront `.obj` mesh (`o`, `g`, `v`, `vt`, `vn`, `f` with n-gon fan triangulation, negative indices, and auto-normals).
4322    ///
4323    /// # Arguments
4324    ///
4325    /// - `&str` - Raw `.obj` ASCII text.
4326    /// - `PbrMaterial` - Material assigned to the parsed mesh.
4327    ///
4328    /// # Returns
4329    ///
4330    /// - `Result<ImportedModel3D, String>` - Parsed model or error string.
4331    pub fn parse_obj(source: &str, material: PbrMaterial) -> Result<ImportedModel3D, String> {
4332        Self::parse_obj_with_mtl(source, None, material)
4333    }
4334
4335    /// Parses a Khronos glTF 2.0 JSON asset (full buffers/bufferViews/accessors/Principled BSDF plus legacy inline geometry fallback).
4336    ///
4337    /// # Arguments
4338    ///
4339    /// - `&str` - Raw `.gltf` JSON string.
4340    /// - `PbrMaterial` - Fallback PBR material when JSON omits `materials`.
4341    ///
4342    /// # Returns
4343    ///
4344    /// - `Result<ImportedModel3D, String>` - Parsed model bundle or validation error.
4345    pub fn parse_gltf_json(
4346        source: &str,
4347        fallback_material: PbrMaterial,
4348    ) -> Result<ImportedModel3D, String> {
4349        let scene: ImportedScene3D = parse_gltf_document(source, None, None)?;
4350        if scene.get_meshes().is_empty() {
4351            return Err(ERR_GLTF_EMPTY.to_string());
4352        }
4353        let mut model: ImportedModel3D = scene.to_imported_model(ModelFormat::GltfJson);
4354        if scene.get_materials().is_empty() {
4355            for chain in model.get_mut_meshes().iter_mut() {
4356                for lvl in chain.get_mut_levels().iter_mut() {
4357                    lvl.set_material(fallback_material);
4358                }
4359            }
4360        }
4361        Ok(model)
4362    }
4363}