Skip to main content

euv_core/game/engine3d/mesh/
impl.rs

1use super::*;
2
3/// Default neutral matte PBR material.
4impl Default for PbrMaterial {
5    /// Returns a mid-gray dielectric PBR material.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default `PbrMaterial`.
10    fn default() -> Self {
11        Self {
12            base_color: Vec3::new(0.72, 0.75, 0.80),
13            metallic: 0.1,
14            roughness: 0.55,
15            emissive: Vec3::zero(),
16            reflectivity: 0.12,
17            surface_detail: SurfaceDetailMode::None,
18        }
19    }
20}
21
22/// Material presets and fluent builders for metallic conductors, dielectrics, architectural glass, and neon signage.
23impl PbrMaterial {
24    /// Creates a PBR material from an sRGB `Color`, `metallic`, `roughness`, and `reflectivity`.
25    ///
26    /// # Arguments
27    ///
28    /// - `Color` - Base albedo color.
29    /// - `f32` - Metallic scalar `[0.0, 1.0]`.
30    /// - `f32` - Roughness scalar `[0.04, 1.0]`.
31    /// - `f32` - Ray-traced reflectivity weight `[0.0, 1.0]`.
32    ///
33    /// # Returns
34    ///
35    /// - `Self` - Configured PBR material.
36    #[must_use]
37    pub fn pbr(color: Color, metallic: f32, roughness: f32, reflectivity: f32) -> Self {
38        Self {
39            base_color: Vec3::from_color(color),
40            metallic: metallic.clamp(0.0, 1.0),
41            roughness: roughness.clamp(0.04, 1.0),
42            emissive: Vec3::zero(),
43            reflectivity: reflectivity.clamp(0.0, 1.0),
44            surface_detail: SurfaceDetailMode::None,
45        }
46    }
47
48    /// Creates a metallic conductor PBR material (chrome, painted car body, brushed steel).
49    ///
50    /// # Arguments
51    ///
52    /// - `Color` - Base metallic reflectance color.
53    /// - `f32` - Surface roughness in `[0.04, 1.0]`.
54    ///
55    /// # Returns
56    ///
57    /// - `Self` - Conductor PBR material.
58    #[must_use]
59    pub fn metallic(color: Color, roughness: f32) -> Self {
60        let r: f32 = roughness.clamp(0.04, 1.0);
61        Self::pbr(color, 0.92, r, (1.0 - r * 0.8).clamp(0.15, 0.96))
62    }
63
64    /// Creates a non-metallic dielectric PBR material (asphalt, concrete, matte plastic, cloth).
65    ///
66    /// # Arguments
67    ///
68    /// - `Color` - Base diffuse albedo color.
69    /// - `f32` - Surface roughness in `[0.04, 1.0]`.
70    ///
71    /// # Returns
72    ///
73    /// - `Self` - Dielectric PBR material.
74    #[must_use]
75    pub fn dielectric(color: Color, roughness: f32) -> Self {
76        let r: f32 = roughness.clamp(0.04, 1.0);
77        Self::pbr(color, 0.04, r, (0.35 * (1.0 - r)).clamp(0.04, 0.35))
78    }
79
80    /// Creates a highly reflective architectural glass PBR material.
81    ///
82    /// # Arguments
83    ///
84    /// - `Color` - Subtle glass tint color.
85    /// - `f32` - Surface roughness in `[0.04, 0.4]`.
86    ///
87    /// # Returns
88    ///
89    /// - `Self` - Reflective glass PBR material.
90    #[must_use]
91    pub fn glass(color: Color, roughness: f32) -> Self {
92        let r: f32 = roughness.clamp(0.04, 0.4);
93        Self::pbr(color, 0.12, r, 0.88)
94    }
95
96    /// Creates an emissive neon PBR material for city signage, vehicle tail-lights, and beacons.
97    ///
98    /// # Arguments
99    ///
100    /// - `Color` - Base and emissive neon color.
101    /// - `f32` - Emissive intensity multiplier.
102    ///
103    /// # Returns
104    ///
105    /// - `Self` - Emissive PBR material.
106    #[must_use]
107    pub fn neon(color: Color, intensity: f32) -> Self {
108        let rgb: Vec3 = Vec3::from_color(color);
109        Self {
110            base_color: rgb,
111            metallic: 0.2,
112            roughness: 0.2,
113            emissive: rgb.scale(intensity.max(0.2)),
114            reflectivity: 0.3,
115            surface_detail: SurfaceDetailMode::None,
116        }
117    }
118
119    /// Returns a copy of this material with custom linear HDR emissive radiance.
120    ///
121    /// # Arguments
122    ///
123    /// - `Self` - Base material.
124    /// - `Vec3` - Emissive HDR RGB radiance.
125    ///
126    /// # Returns
127    ///
128    /// - `Self` - Updated material.
129    #[must_use]
130    pub fn with_emissive(mut self, emissive: Vec3) -> Self {
131        self.set_emissive(emissive);
132        self
133    }
134
135    /// Returns a copy of this material with adjusted surface roughness.
136    ///
137    /// # Arguments
138    ///
139    /// - `Self` - Base material.
140    /// - `f32` - Surface roughness clamped to `[0.04, 1.0]`.
141    ///
142    /// # Returns
143    ///
144    /// - `Self` - Updated material.
145    #[must_use]
146    pub fn with_roughness(mut self, roughness: f32) -> Self {
147        self.set_roughness(roughness.clamp(0.04, 1.0));
148        self
149    }
150
151    /// Returns a copy of this material with adjusted metallic factor.
152    ///
153    /// # Arguments
154    ///
155    /// - `Self` - Base material.
156    /// - `f32` - Metallic factor clamped to `[0.0, 1.0]`.
157    ///
158    /// # Returns
159    ///
160    /// - `Self` - Updated material.
161    #[must_use]
162    pub fn with_metallic(mut self, metallic: f32) -> Self {
163        self.set_metallic(metallic.clamp(0.0, 1.0));
164        self
165    }
166
167    /// Returns a copy of this material with adjusted ray-traced reflectivity.
168    ///
169    /// # Arguments
170    ///
171    /// - `Self` - Base material.
172    /// - `f32` - Reflectivity weight clamped to `[0.0, 1.0]`.
173    ///
174    /// # Returns
175    ///
176    /// - `Self` - Updated material.
177    #[must_use]
178    pub fn with_reflectivity(mut self, reflectivity: f32) -> Self {
179        self.set_reflectivity(reflectivity.clamp(0.0, 1.0));
180        self
181    }
182
183    /// Returns a copy of this material with the requested procedural surface detail overlay.
184    ///
185    /// # Arguments
186    ///
187    /// - `Self` - Base material.
188    /// - `SurfaceDetailMode` - Procedural surface detail mode.
189    ///
190    /// # Returns
191    ///
192    /// - `Self` - Updated material.
193    #[must_use]
194    pub fn with_surface_detail(mut self, mode: SurfaceDetailMode) -> Self {
195        self.set_surface_detail(mode);
196        self
197    }
198}
199
200/// Fluent constructors for `BoxMeshDesc`.
201impl BoxMeshDesc {
202    /// Creates a box mesh descriptor with default ground pivot and neutral PBR material.
203    ///
204    /// # Arguments
205    ///
206    /// - `&str` - Asset name.
207    /// - `Vec3` - Box extents `(width, height, depth)`.
208    ///
209    /// # Returns
210    ///
211    /// - `Self` - Ready descriptor.
212    #[must_use]
213    pub fn new(name: &str, size: Vec3) -> Self {
214        Self {
215            name: name.to_string(),
216            size,
217            ground_pivot: true,
218            material: PbrMaterial::default(),
219        }
220    }
221
222    /// Sets whether the box rests on `y = 0` or is centered at the origin.
223    ///
224    /// # Arguments
225    ///
226    /// - `Self` - Base descriptor.
227    /// - `bool` - Ground pivot toggle.
228    ///
229    /// # Returns
230    ///
231    /// - `Self` - Updated descriptor.
232    #[must_use]
233    pub fn with_ground_pivot(mut self, ground_pivot: bool) -> Self {
234        self.set_ground_pivot(ground_pivot);
235        self
236    }
237
238    /// Assigns the PBR material for the generated box mesh.
239    ///
240    /// # Arguments
241    ///
242    /// - `Self` - Base descriptor.
243    /// - `PbrMaterial` - Surface material.
244    ///
245    /// # Returns
246    ///
247    /// - `Self` - Updated descriptor.
248    #[must_use]
249    pub fn with_material(mut self, material: PbrMaterial) -> Self {
250        self.set_material(material);
251        self
252    }
253}
254
255/// Fluent constructors for `GroundPlaneDesc`.
256impl GroundPlaneDesc {
257    /// Creates a ground plane descriptor with default subdivisions and neutral PBR material.
258    ///
259    /// # Arguments
260    ///
261    /// - `&str` - Asset name.
262    /// - `f32` - Width along X.
263    /// - `f32` - Depth along Z.
264    ///
265    /// # Returns
266    ///
267    /// - `Self` - Ready descriptor.
268    #[must_use]
269    pub fn new(name: &str, width: f32, depth: f32) -> Self {
270        Self {
271            name: name.to_string(),
272            width,
273            depth,
274            subdivisions: 8,
275            material: PbrMaterial::default(),
276        }
277    }
278
279    /// Sets the grid subdivision count along each axis.
280    ///
281    /// # Arguments
282    ///
283    /// - `Self` - Base descriptor.
284    /// - `usize` - Subdivision count.
285    ///
286    /// # Returns
287    ///
288    /// - `Self` - Updated descriptor.
289    #[must_use]
290    pub fn with_subdivisions(mut self, subdivisions: usize) -> Self {
291        self.set_subdivisions(subdivisions);
292        self
293    }
294
295    /// Assigns the PBR material for the generated ground plane.
296    ///
297    /// # Arguments
298    ///
299    /// - `Self` - Base descriptor.
300    /// - `PbrMaterial` - Surface material.
301    ///
302    /// # Returns
303    ///
304    /// - `Self` - Updated descriptor.
305    #[must_use]
306    pub fn with_material(mut self, material: PbrMaterial) -> Self {
307        self.set_material(material);
308        self
309    }
310}
311
312/// Mesh construction, Nanite-style meshlet clustering, decimation, and procedural asset generators for `Mesh3D`.
313impl Mesh3D {
314    /// Partitions indexed triangles into Nanite-style `Meshlet3D` clusters with tight AABBs and normal cones.
315    ///
316    /// # Arguments
317    ///
318    /// - `&[Vertex3D]` - Source vertex buffer.
319    /// - `&[[u32; 3]]` - Source triangle indices.
320    ///
321    /// # Returns
322    ///
323    /// - `Vec<Meshlet3D>` - Contiguous cluster descriptors covering all triangles.
324    #[must_use]
325    pub fn build_meshlets_from_parts(
326        vertices: &[Vertex3D],
327        indices: &[[u32; 3]],
328    ) -> Vec<Meshlet3D> {
329        if indices.is_empty() {
330            return Vec::new();
331        }
332        let cluster_count: usize = indices.len().div_ceil(MESHLET_MAX_TRIS);
333        let mut out: Vec<Meshlet3D> = Vec::with_capacity(cluster_count);
334        let mut start: usize = 0;
335        while start < indices.len() {
336            let end: usize = (start + MESHLET_MAX_TRIS).min(indices.len());
337            let mut cluster_box: Aabb3D = Aabb3D::empty();
338            let mut avg_n: Vec3 = Vec3::zero();
339            let mut valid_tris: usize = 0;
340            for tri in &indices[start..end] {
341                let (i0, i1, i2): (usize, usize, usize) =
342                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
343                if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
344                    let p0: Vec3 = vertices[i0].get_position();
345                    let p1: Vec3 = vertices[i1].get_position();
346                    let p2: Vec3 = vertices[i2].get_position();
347                    cluster_box.expand_point(p0);
348                    cluster_box.expand_point(p1);
349                    cluster_box.expand_point(p2);
350                    let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
351                    avg_n = avg_n.add(fn_vec);
352                    valid_tris += 1;
353                }
354            }
355            if valid_tris == 0 {
356                cluster_box = Aabb3D::new(Vec3::zero(), Vec3::zero());
357            }
358            let cone_axis: Vec3 = avg_n.normalize();
359            let mut min_dot: f32 = 1.0;
360            for tri in &indices[start..end] {
361                let (i0, i1, i2): (usize, usize, usize) =
362                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
363                if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
364                    let p0: Vec3 = vertices[i0].get_position();
365                    let p1: Vec3 = vertices[i1].get_position();
366                    let p2: Vec3 = vertices[i2].get_position();
367                    let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
368                    min_dot = min_dot.min(fn_vec.dot(cone_axis));
369                }
370            }
371            let radius: f32 = cluster_box.radius().max(0.05);
372            let screen_error: f32 = radius / ((end - start).max(1) as f32).sqrt();
373            out.push(Meshlet3D::new(
374                start as u32,
375                (end - start) as u32,
376                cluster_box,
377                cone_axis,
378                min_dot,
379                screen_error,
380            ));
381            start = end;
382        }
383        out
384    }
385
386    /// Constructs a `Mesh3D`, computes its local `Aabb3D`, and partitions Nanite-style `Meshlet3D` clusters.
387    ///
388    /// # Arguments
389    ///
390    /// - `String` - Asset name.
391    /// - `Vec<Vertex3D>` - Vertex list.
392    /// - `Vec<[u32; 3]>` - Triangle indices.
393    /// - `PbrMaterial` - Default material.
394    ///
395    /// # Returns
396    ///
397    /// - `Self` - Ready indexed mesh with meshlets.
398    #[must_use]
399    pub fn from_parts(
400        name: String,
401        vertices: Vec<Vertex3D>,
402        indices: Vec<[u32; 3]>,
403        material: PbrMaterial,
404    ) -> Self {
405        let mut bounds: Aabb3D = Aabb3D::empty();
406        for v in vertices.iter() {
407            bounds.expand_point(v.get_position());
408        }
409        if vertices.is_empty() {
410            bounds = Aabb3D::new(Vec3::zero(), Vec3::zero());
411        }
412        let meshlets: Vec<Meshlet3D> = Self::build_meshlets_from_parts(&vertices, &indices);
413        Self {
414            name,
415            vertices,
416            indices,
417            bounds,
418            material,
419            meshlets,
420        }
421    }
422
423    /// Generates an axis-aligned box mesh of dimensions `(w, h, d)` resting on `y = 0` or centered.
424    ///
425    /// # Arguments
426    ///
427    /// - `&str` - Mesh name.
428    /// - `f32` - Width along X.
429    /// - `f32` - Height along Y.
430    /// - `f32` - Depth along Z.
431    /// - `bool` - When `true`, base rests on `y = 0`; otherwise centered at origin.
432    /// - `PbrMaterial` - Surface PBR material.
433    ///
434    /// # Returns
435    ///
436    /// - `Self` - Indexed 12-triangle box mesh with crisp flat face normals.
437    #[must_use]
438    pub fn box_mesh(
439        name: &str,
440        w: f32,
441        h: f32,
442        d: f32,
443        ground_pivot: bool,
444        material: PbrMaterial,
445    ) -> Self {
446        let hx: f32 = w * 0.5;
447        let hz: f32 = d * 0.5;
448        let y0: f32 = if ground_pivot { 0.0 } else { -h * 0.5 };
449        let y1: f32 = if ground_pivot { h } else { h * 0.5 };
450        let faces: [([Vec3; 4], Vec3); 6] = [
451            (
452                [
453                    Vec3::new(-hx, y0, hz),
454                    Vec3::new(hx, y0, hz),
455                    Vec3::new(hx, y1, hz),
456                    Vec3::new(-hx, y1, hz),
457                ],
458                Vec3::new(0.0, 0.0, 1.0),
459            ),
460            (
461                [
462                    Vec3::new(hx, y0, -hz),
463                    Vec3::new(-hx, y0, -hz),
464                    Vec3::new(-hx, y1, -hz),
465                    Vec3::new(hx, y1, -hz),
466                ],
467                Vec3::new(0.0, 0.0, -1.0),
468            ),
469            (
470                [
471                    Vec3::new(hx, y0, hz),
472                    Vec3::new(hx, y0, -hz),
473                    Vec3::new(hx, y1, -hz),
474                    Vec3::new(hx, y1, hz),
475                ],
476                Vec3::new(1.0, 0.0, 0.0),
477            ),
478            (
479                [
480                    Vec3::new(-hx, y0, -hz),
481                    Vec3::new(-hx, y0, hz),
482                    Vec3::new(-hx, y1, hz),
483                    Vec3::new(-hx, y1, -hz),
484                ],
485                Vec3::new(-1.0, 0.0, 0.0),
486            ),
487            (
488                [
489                    Vec3::new(-hx, y1, hz),
490                    Vec3::new(hx, y1, hz),
491                    Vec3::new(hx, y1, -hz),
492                    Vec3::new(-hx, y1, -hz),
493                ],
494                Vec3::new(0.0, 1.0, 0.0),
495            ),
496            (
497                [
498                    Vec3::new(-hx, y0, -hz),
499                    Vec3::new(hx, y0, -hz),
500                    Vec3::new(hx, y0, hz),
501                    Vec3::new(-hx, y0, hz),
502                ],
503                Vec3::new(0.0, -1.0, 0.0),
504            ),
505        ];
506        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(24);
507        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(12);
508        for (quad, n) in faces.into_iter() {
509            let base: u32 = vertices.len() as u32;
510            for p in quad.into_iter() {
511                vertices.push(Vertex3D::new(p, n));
512            }
513            indices.push([base, base + 1, base + 2]);
514            indices.push([base, base + 2, base + 3]);
515        }
516        Self::from_parts(name.to_string(), vertices, indices, material)
517    }
518
519    /// Generates a horizontal ground/road quad plane at `y = 0` subdivided for crisp specular/shadow falloff.
520    ///
521    /// # Arguments
522    ///
523    /// - `&str` - Mesh name.
524    /// - `f32` - Width along X.
525    /// - `f32` - Depth along Z.
526    /// - `usize` - Grid subdivisions per axis.
527    /// - `PbrMaterial` - Surface PBR material.
528    ///
529    /// # Returns
530    ///
531    /// - `Self` - Subdivided ground plane mesh.
532    #[must_use]
533    pub fn ground_plane(
534        name: &str,
535        w: f32,
536        d: f32,
537        subdivisions: usize,
538        material: PbrMaterial,
539    ) -> Self {
540        let segs: usize = subdivisions.clamp(1, 16);
541        let mut vertices: Vec<Vertex3D> = Vec::with_capacity((segs + 1) * (segs + 1));
542        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(segs * segs * 2);
543        let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
544        for iz in 0..=segs {
545            let vz: f32 = ((iz as f32) / (segs as f32) - 0.5) * d;
546            for ix in 0..=segs {
547                let vx: f32 = ((ix as f32) / (segs as f32) - 0.5) * w;
548                vertices.push(Vertex3D::new(Vec3::new(vx, 0.0, vz), up));
549            }
550        }
551        let stride: u32 = (segs + 1) as u32;
552        for iz in 0..segs {
553            for ix in 0..segs {
554                let i0: u32 = (iz as u32) * stride + (ix as u32);
555                let i1: u32 = i0 + 1;
556                let i2: u32 = i0 + stride;
557                let i3: u32 = i2 + 1;
558                indices.push([i0, i2, i1]);
559                indices.push([i1, i2, i3]);
560            }
561        }
562        Self::from_parts(name.to_string(), vertices, indices, material)
563    }
564
565    /// Generates a low-poly sculpted sports car chassis resting on `y = 0`.
566    ///
567    /// # Arguments
568    ///
569    /// - `&str` - Asset name.
570    /// - `PbrMaterial` - Car body paint PBR material.
571    ///
572    /// # Returns
573    ///
574    /// - `Self` - Composite vehicle mesh.
575    #[must_use]
576    pub fn sports_car(name: &str, material: PbrMaterial) -> Self {
577        let lower: Self = Self::box_mesh(MESH_CAR_LOWER, 2.2, 0.80, 4.6, true, material);
578        let cabin: Self = Self::box_mesh(MESH_CAR_CABIN, 1.82, 0.72, 2.2, true, material);
579        let wheel: Self = Self::box_mesh(MESH_CAR_WHEEL, 0.34, 0.56, 0.62, true, material);
580        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(144);
581        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(72);
582        let lower_offset: u32 = vertices.len() as u32;
583        for v in lower.get_vertices().iter() {
584            let p: Vec3 = v.get_position();
585            vertices.push(Vertex3D::new(
586                Vec3::new(p.get_x(), p.get_y() + 0.24, p.get_z()),
587                v.get_normal(),
588            ));
589        }
590        for tri in lower.get_indices().iter() {
591            indices.push([
592                tri[0] + lower_offset,
593                tri[1] + lower_offset,
594                tri[2] + lower_offset,
595            ]);
596        }
597        let cabin_offset: u32 = vertices.len() as u32;
598        for v in cabin.get_vertices().iter() {
599            let p: Vec3 = v.get_position();
600            vertices.push(Vertex3D::new(
601                Vec3::new(p.get_x(), p.get_y() + 1.04, p.get_z() - 0.15),
602                v.get_normal(),
603            ));
604        }
605        for tri in cabin.get_indices().iter() {
606            indices.push([
607                tri[0] + cabin_offset,
608                tri[1] + cabin_offset,
609                tri[2] + cabin_offset,
610            ]);
611        }
612        let wheel_offsets: [(f32, f32); 4] =
613            [(-1.12, -1.45), (1.12, -1.45), (-1.12, 1.45), (1.12, 1.45)];
614        for (wx, wz) in wheel_offsets.into_iter() {
615            let base: u32 = vertices.len() as u32;
616            for v in wheel.get_vertices().iter() {
617                let p: Vec3 = v.get_position();
618                vertices.push(Vertex3D::new(
619                    Vec3::new(p.get_x() + wx, p.get_y() + 0.02, p.get_z() + wz),
620                    v.get_normal(),
621                ));
622            }
623            for tri in wheel.get_indices().iter() {
624                indices.push([tri[0] + base, tri[1] + base, tri[2] + base]);
625            }
626        }
627        Self::from_parts(name.to_string(), vertices, indices, material)
628    }
629
630    /// Builds a box mesh from a fluent `BoxMeshDesc`.
631    ///
632    /// # Arguments
633    ///
634    /// - `&BoxMeshDesc` - Box mesh descriptor.
635    ///
636    /// # Returns
637    ///
638    /// - `Self` - Indexed 12-triangle box mesh.
639    #[must_use]
640    pub fn from_box_desc(desc: &BoxMeshDesc) -> Self {
641        let size: Vec3 = desc.get_size();
642        Self::box_mesh(
643            desc.get_name(),
644            size.get_x(),
645            size.get_y(),
646            size.get_z(),
647            desc.get_ground_pivot(),
648            desc.get_material(),
649        )
650    }
651
652    /// Builds a subdivided ground plane from a fluent `GroundPlaneDesc`.
653    ///
654    /// # Arguments
655    ///
656    /// - `&GroundPlaneDesc` - Ground plane descriptor.
657    ///
658    /// # Returns
659    ///
660    /// - `Self` - Subdivided ground plane mesh.
661    #[must_use]
662    pub fn from_ground_desc(desc: &GroundPlaneDesc) -> Self {
663        Self::ground_plane(
664            desc.get_name(),
665            desc.get_width(),
666            desc.get_depth(),
667            desc.get_subdivisions(),
668            desc.get_material(),
669        )
670    }
671
672    /// Builds a simplified proxy mesh enclosing this mesh's AABB for distant LOD tiers.
673    ///
674    /// # Arguments
675    ///
676    /// - `&Self` - Source mesh reference.
677    /// - `&str` - LOD suffix label.
678    ///
679    /// # Returns
680    ///
681    /// - `Self` - Lightweight 12-triangle LOD proxy mesh.
682    #[must_use]
683    pub fn build_lod_proxy(&self, suffix: &str) -> Self {
684        let b: Aabb3D = self.get_bounds();
685        let size: Vec3 = b.get_max().sub(b.get_min());
686        let center: Vec3 = b.center();
687        let mut proxy: Self = Self::box_mesh(
688            &format!("{}_{suffix}", self.get_name()),
689            size.get_x().max(0.2),
690            size.get_y().max(0.2),
691            size.get_z().max(0.2),
692            false,
693            self.get_material(),
694        );
695        for v in proxy.get_mut_vertices().iter_mut() {
696            v.set_position(v.get_position().add(center));
697        }
698        proxy.set_bounds(b);
699        let meshlets: Vec<Meshlet3D> =
700            Self::build_meshlets_from_parts(proxy.get_vertices(), proxy.get_indices());
701        proxy.set_meshlets(meshlets);
702        proxy
703    }
704
705    /// Produces a mid-detail decimated mesh by retaining dominant triangles while preserving bounding silhouette.
706    ///
707    /// # Arguments
708    ///
709    /// - `&Self` - Source mesh reference.
710    /// - `&str` - LOD suffix label.
711    ///
712    /// # Returns
713    ///
714    /// - `Self` - Decimated intermediate LOD mesh.
715    #[must_use]
716    pub fn build_mid_lod(&self, suffix: &str) -> Self {
717        let verts: &[Vertex3D] = self.get_vertices().as_slice();
718        let tris: &[[u32; 3]] = self.get_indices().as_slice();
719        if tris.len() <= 24 {
720            return self.build_lod_proxy(suffix);
721        }
722        let mut scored: Vec<(f32, [u32; 3])> = Vec::with_capacity(tris.len());
723        for tri in tris.iter().copied() {
724            let (i0, i1, i2): (usize, usize, usize) =
725                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
726            if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
727                let p0: Vec3 = verts[i0].get_position();
728                let p1: Vec3 = verts[i1].get_position();
729                let p2: Vec3 = verts[i2].get_position();
730                let area2: f32 = p1.sub(p0).cross(p2.sub(p0)).length_sq();
731                scored.push((area2, tri));
732            }
733        }
734        scored.sort_unstable_by(|a: &(f32, [u32; 3]), b: &(f32, [u32; 3])| b.0.total_cmp(&a.0));
735        let keep: usize = (scored.len() / 2).max(12);
736        let reduced: Vec<[u32; 3]> = scored
737            .into_iter()
738            .take(keep)
739            .map(|(_, t): (f32, [u32; 3])| t)
740            .collect();
741        Self::from_parts(
742            format!("{}_{suffix}", self.get_name()),
743            self.get_vertices().clone(),
744            reduced,
745            self.get_material(),
746        )
747    }
748}
749
750/// Multi-level continuous LOD chain creation and screen-error selection for `MeshLodChain`.
751impl MeshLodChain {
752    /// Builds a continuous 3-tier Nanite-style LOD chain (`LOD0` full -> `LOD1` mid -> `LOD2` proxy) automatically.
753    ///
754    /// # Arguments
755    ///
756    /// - `Mesh3D` - Full-resolution `LOD0` mesh.
757    ///
758    /// # Returns
759    ///
760    /// - `Self` - Ready LOD chain.
761    #[must_use]
762    pub fn from_mesh(mesh: Mesh3D) -> Self {
763        let tri_count: usize = mesh.get_indices().len();
764        if tri_count > 32 {
765            let lod1: Mesh3D = mesh.build_mid_lod(MESH_LOD1_SUFFIX);
766            let lod2: Mesh3D = mesh.build_lod_proxy(MESH_LOD2_SUFFIX);
767            Self {
768                levels: vec![mesh, lod1, lod2],
769            }
770        } else if tri_count > 16 {
771            let lod1: Mesh3D = mesh.build_lod_proxy(MESH_LOD1_SUFFIX);
772            Self {
773                levels: vec![mesh, lod1],
774            }
775        } else {
776            let clone_lod1: Mesh3D = mesh.clone();
777            Self {
778                levels: vec![mesh, clone_lod1],
779            }
780        }
781    }
782
783    /// Selects the appropriate `Mesh3D` detail level for `distance` and `lod_bias`.
784    ///
785    /// # Arguments
786    ///
787    /// - `&Self` - LOD chain reference.
788    /// - `f32` - Camera-to-object distance in meters.
789    /// - `f32` - Quality LOD bias multiplier.
790    ///
791    /// # Returns
792    ///
793    /// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
794    #[must_use]
795    pub fn select(&self, distance: f32, lod_bias: f32) -> (&Mesh3D, usize) {
796        let levels: &[Mesh3D] = self.get_levels().as_slice();
797        let effective_dist: f32 = distance * lod_bias.max(0.25);
798        if levels.len() > 2 && effective_dist > 135.0 {
799            (&levels[2], 2)
800        } else if levels.len() > 1 && effective_dist > 78.0 {
801            (&levels[1], 1)
802        } else {
803            (&levels[0], 0)
804        }
805    }
806
807    /// Nanite-style continuous LOD selection driven by projected screen-space pixel coverage.
808    ///
809    /// # Arguments
810    ///
811    /// - `&Self` - LOD chain reference.
812    /// - `f32` - Camera-to-object distance in meters.
813    /// - `f32` - World-space bounding sphere radius in meters.
814    /// - `f32` - Projected viewport focal length in pixels (`height / (2 * tan(fov/2))`).
815    /// - `f32` - Quality LOD bias multiplier (`< 1.0` higher detail, `> 1.0` aggressive simplification).
816    ///
817    /// # Returns
818    ///
819    /// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
820    #[must_use]
821    pub fn select_screen_error(
822        &self,
823        distance: f32,
824        bounds_radius: f32,
825        focal_px: f32,
826        lod_bias: f32,
827    ) -> (&Mesh3D, usize) {
828        let levels: &[Mesh3D] = self.get_levels().as_slice();
829        let safe_dist: f32 = distance.max(0.5);
830        let projected_px: f32 =
831            (bounds_radius.max(0.2) * focal_px) / (safe_dist * lod_bias.max(0.25));
832        if levels.len() > 2 && projected_px < 22.0 {
833            (&levels[2], 2)
834        } else if levels.len() > 1 && projected_px < 58.0 {
835            (&levels[1], 1)
836        } else {
837            (&levels[0], 0)
838        }
839    }
840}
841
842/// Native Wavefront `.obj` and glTF 2.0 `.gltf` JSON parsers for `ModelImporter3D`.
843impl ModelImporter3D {
844    /// Imports a 3D model from text source in the specified `ModelFormat` and generates LOD chains.
845    ///
846    /// # Arguments
847    ///
848    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
849    /// - `&str` - Raw `.obj` or `.gltf` text content.
850    /// - `PbrMaterial` - Fallback PBR material when source omits material definitions.
851    ///
852    /// # Returns
853    ///
854    /// - `Result<ImportedModel3D, String>` - Imported model bundle or parse error diagnostic.
855    pub fn import(
856        format: ModelFormat,
857        source: &str,
858        fallback_material: PbrMaterial,
859    ) -> Result<ImportedModel3D, String> {
860        match format {
861            ModelFormat::Obj => Self::parse_obj(source, fallback_material),
862            ModelFormat::GltfJson => Self::parse_gltf_json(source, fallback_material),
863        }
864    }
865
866    /// Parses a Wavefront `.obj` mesh (`o`, `v`, `vn`, `f` with n-gon fan triangulation and auto-normals).
867    ///
868    /// # Arguments
869    ///
870    /// - `&str` - Raw `.obj` ASCII text.
871    /// - `PbrMaterial` - Material assigned to the parsed mesh.
872    ///
873    /// # Returns
874    ///
875    /// - `Result<ImportedModel3D, String>` - Parsed model or error string.
876    pub fn parse_obj(source: &str, material: PbrMaterial) -> Result<ImportedModel3D, String> {
877        let mut positions: Vec<Vec3> = Vec::new();
878        let mut normals: Vec<Vec3> = Vec::new();
879        let mut vertices: Vec<Vertex3D> = Vec::new();
880        let mut indices: Vec<[u32; 3]> = Vec::new();
881        let mut model_name: String = MESH_OBJ_DEFAULT_NAME.to_string();
882        for raw_line in source.lines() {
883            let line: &str = raw_line.trim();
884            if line.is_empty() || line.starts_with('#') {
885                continue;
886            }
887            let parts: Vec<&str> = line.split_whitespace().collect();
888            if parts.is_empty() {
889                continue;
890            }
891            match parts[0] {
892                "o" | "g" if parts.len() >= 2 => {
893                    model_name = parts[1].to_string();
894                }
895                "v" if parts.len() >= 4 => {
896                    let x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
897                    let y: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
898                    let z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
899                    positions.push(Vec3::new(x, y, z));
900                }
901                "vn" if parts.len() >= 4 => {
902                    let x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
903                    let y: f32 = parts[2].parse::<f32>().unwrap_or(1.0);
904                    let z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
905                    normals.push(Vec3::new(x, y, z).normalize());
906                }
907                "f" if parts.len() >= 4 => {
908                    let mut face_verts: Vec<(Vec3, Option<Vec3>)> =
909                        Vec::with_capacity(parts.len() - 1);
910                    for token in parts.iter().skip(1) {
911                        let comps: Vec<&str> = token.split('/').collect();
912                        let v_idx_raw: i32 = comps
913                            .first()
914                            .and_then(|s: &&str| s.parse::<i32>().ok())
915                            .unwrap_or(0);
916                        let p_opt: Option<Vec3> = if v_idx_raw > 0 {
917                            positions.get((v_idx_raw - 1) as usize).copied()
918                        } else if v_idx_raw < 0 {
919                            let idx: isize = (positions.len() as isize) + (v_idx_raw as isize);
920                            if idx >= 0 {
921                                positions.get(idx as usize).copied()
922                            } else {
923                                None
924                            }
925                        } else {
926                            None
927                        };
928                        let n_opt: Option<Vec3> = comps
929                            .get(2)
930                            .and_then(|s: &&str| s.parse::<i32>().ok())
931                            .and_then(|n_raw: i32| {
932                                if n_raw > 0 {
933                                    normals.get((n_raw - 1) as usize).copied()
934                                } else {
935                                    None
936                                }
937                            });
938                        if let Some(pos) = p_opt {
939                            face_verts.push((pos, n_opt));
940                        }
941                    }
942                    if face_verts.len() >= 3 {
943                        for k in 1..(face_verts.len() - 1) {
944                            let (p0, n0): (Vec3, Option<Vec3>) = face_verts[0];
945                            let (p1, n1): (Vec3, Option<Vec3>) = face_verts[k];
946                            let (p2, n2): (Vec3, Option<Vec3>) = face_verts[k + 1];
947                            let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
948                            let base: u32 = vertices.len() as u32;
949                            vertices.push(Vertex3D::new(p0, n0.unwrap_or(face_n)));
950                            vertices.push(Vertex3D::new(p1, n1.unwrap_or(face_n)));
951                            vertices.push(Vertex3D::new(p2, n2.unwrap_or(face_n)));
952                            indices.push([base, base + 1, base + 2]);
953                        }
954                    }
955                }
956                _ => {}
957            }
958        }
959        if indices.is_empty() {
960            return Err(ERR_OBJ_EMPTY.to_string());
961        }
962        let total_vertices: usize = vertices.len();
963        let total_triangles: usize = indices.len();
964        let mesh: Mesh3D = Mesh3D::from_parts(model_name.clone(), vertices, indices, material);
965        Ok(ImportedModel3D {
966            name: model_name,
967            format: ModelFormat::Obj,
968            meshes: vec![MeshLodChain::from_mesh(mesh)],
969            total_vertices,
970            total_triangles,
971        })
972    }
973
974    /// Parses a glTF 2.0 JSON asset supporting inline PBR materials and embedded mesh positions/indices.
975    ///
976    /// # Arguments
977    ///
978    /// - `&str` - Raw `.gltf` JSON string.
979    /// - `PbrMaterial` - Fallback PBR material when JSON omits `pbrMetallicRoughness`.
980    ///
981    /// # Returns
982    ///
983    /// - `Result<ImportedModel3D, String>` - Parsed model bundle or validation error.
984    pub fn parse_gltf_json(
985        source: &str,
986        fallback_material: PbrMaterial,
987    ) -> Result<ImportedModel3D, String> {
988        let root: Value = from_str::<Value>(source)
989            .ok()
990            .ok_or_else(|| ERR_GLTF_JSON.to_string())?;
991        let name: String = root
992            .get(GLTF_KEY_ASSET)
993            .and_then(|a: &Value| a.get(GLTF_KEY_GENERATOR))
994            .and_then(Value::as_str)
995            .unwrap_or(MESH_GLTF_DEFAULT_NAME)
996            .to_string();
997        let mut mat: PbrMaterial = fallback_material;
998        if let Some(pbr) = root
999            .get(GLTF_KEY_MATERIALS)
1000            .and_then(Value::as_array)
1001            .and_then(|arr: &Vec<Value>| arr.first())
1002            .and_then(|m: &Value| m.get(GLTF_KEY_PBR))
1003        {
1004            if let Some(bc) = pbr.get(GLTF_KEY_BASE_COLOR).and_then(Value::as_array)
1005                && bc.len() >= 3
1006            {
1007                let r: f32 = bc[0].as_f64().unwrap_or(0.8) as f32;
1008                let g: f32 = bc[1].as_f64().unwrap_or(0.8) as f32;
1009                let b: f32 = bc[2].as_f64().unwrap_or(0.8) as f32;
1010                mat.set_base_color(Vec3::new(r, g, b));
1011            }
1012            if let Some(met) = pbr.get(GLTF_KEY_METALLIC).and_then(Value::as_f64) {
1013                mat.set_metallic((met as f32).clamp(0.0, 1.0));
1014            }
1015            if let Some(rough) = pbr.get(GLTF_KEY_ROUGHNESS).and_then(Value::as_f64) {
1016                mat.set_roughness((rough as f32).clamp(0.04, 1.0));
1017                mat.set_reflectivity((1.0 - (rough as f32)).clamp(0.05, 0.95));
1018            }
1019        }
1020        let mut chains: Vec<MeshLodChain> = Vec::new();
1021        let mut total_vertices: usize = 0;
1022        let mut total_triangles: usize = 0;
1023        if let Some(meshes_arr) = root.get(GLTF_KEY_MESHES).and_then(Value::as_array) {
1024            for (m_idx, m_val) in meshes_arr.iter().enumerate() {
1025                let mesh_name: String = m_val
1026                    .get(GLTF_KEY_NAME)
1027                    .and_then(Value::as_str)
1028                    .map(str::to_string)
1029                    .unwrap_or_else(|| format!("{name}_mesh_{m_idx}"));
1030                let Some(prims) = m_val.get(GLTF_KEY_PRIMITIVES).and_then(Value::as_array) else {
1031                    continue;
1032                };
1033                for prim in prims.iter() {
1034                    let extras: &Value = prim.get(GLTF_KEY_EXTRAS).unwrap_or(prim);
1035                    let pos_vals: Vec<f32> = extras
1036                        .get(GLTF_KEY_POSITIONS)
1037                        .and_then(Value::as_array)
1038                        .map(|a: &Vec<Value>| {
1039                            a.iter()
1040                                .filter_map(|v: &Value| v.as_f64().map(|n: f64| n as f32))
1041                                .collect()
1042                        })
1043                        .unwrap_or_default();
1044                    let idx_vals: Vec<u32> = extras
1045                        .get(GLTF_KEY_INDICES)
1046                        .and_then(Value::as_array)
1047                        .map(|a: &Vec<Value>| {
1048                            a.iter()
1049                                .filter_map(|v: &Value| v.as_u64().map(|n: u64| n as u32))
1050                                .collect()
1051                        })
1052                        .unwrap_or_default();
1053                    let mut raw_pts: Vec<Vec3> = Vec::new();
1054                    for chunk in pos_vals.as_chunks::<3>().0 {
1055                        raw_pts.push(Vec3::new(chunk[0], chunk[1], chunk[2]));
1056                    }
1057                    let mut verts: Vec<Vertex3D> = Vec::new();
1058                    let mut tris: Vec<[u32; 3]> = Vec::new();
1059                    for tri in idx_vals.as_chunks::<3>().0 {
1060                        let (i0, i1, i2): (usize, usize, usize) =
1061                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1062                        if i0 < raw_pts.len() && i1 < raw_pts.len() && i2 < raw_pts.len() {
1063                            let p0: Vec3 = raw_pts[i0];
1064                            let p1: Vec3 = raw_pts[i1];
1065                            let p2: Vec3 = raw_pts[i2];
1066                            let n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
1067                            let base: u32 = verts.len() as u32;
1068                            verts.push(Vertex3D::new(p0, n));
1069                            verts.push(Vertex3D::new(p1, n));
1070                            verts.push(Vertex3D::new(p2, n));
1071                            tris.push([base, base + 1, base + 2]);
1072                        }
1073                    }
1074                    if !tris.is_empty() {
1075                        total_vertices += verts.len();
1076                        total_triangles += tris.len();
1077                        let mesh: Mesh3D = Mesh3D::from_parts(mesh_name.clone(), verts, tris, mat);
1078                        chains.push(MeshLodChain::from_mesh(mesh));
1079                    }
1080                }
1081            }
1082        }
1083        if chains.is_empty() {
1084            return Err(ERR_GLTF_EMPTY.to_string());
1085        }
1086        Ok(ImportedModel3D {
1087            name,
1088            format: ModelFormat::GltfJson,
1089            meshes: chains,
1090            total_vertices,
1091            total_triangles,
1092        })
1093    }
1094}