Skip to main content

sim_engine/mesh3d/
mod.rs

1//! Validated retained model topology, vertex attributes and visual materials.
2
3use std::{error::Error, fmt, sync::Arc};
4
5use crate::{Color, Vec3};
6
7mod attributes;
8mod environment;
9mod material;
10mod style;
11#[cfg(test)]
12mod tests;
13mod uv;
14
15pub use attributes::Mesh3dAttributes;
16pub use environment::{
17    AmbientLight3d, DirectionalLight3d, Fog3d, Fog3dError, Lighting3d, Lighting3dError,
18    SurfaceLighting3d,
19};
20pub use material::{SurfaceAlphaMode3d, SurfaceSidedness3d, SurfaceStyle3d};
21pub use style::{Mesh3dStyleError, MeshStyle3d, WireframeStyle3d};
22pub use uv::{TextureAddressMode3d, TextureUvTransform3d, TextureUvTransformError};
23
24/// One explicit display edge in a retained 3D mesh.
25///
26/// Endpoints index the mesh vertex array. A mesh validates the indices and
27/// rejects repeated or zero-length edges when it is constructed.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
29pub struct MeshEdge3d {
30    start: u32,
31    end: u32,
32}
33
34impl MeshEdge3d {
35    /// Describes an edge between two distinct vertex indices.
36    pub fn new(start: u32, end: u32) -> Result<Self, Mesh3dError> {
37        if start == end {
38            return Err(Mesh3dError::DegenerateDisplayEdge { start, end });
39        }
40        Ok(Self { start, end })
41    }
42
43    /// Returns the first mesh vertex index.
44    pub const fn start(self) -> u32 {
45        self.start
46    }
47
48    /// Returns the second mesh vertex index.
49    pub const fn end(self) -> u32 {
50        self.end
51    }
52
53    fn canonical(self) -> (u32, u32) {
54        if self.start < self.end {
55            (self.start, self.end)
56        } else {
57            (self.end, self.start)
58        }
59    }
60}
61
62#[derive(Debug, PartialEq)]
63struct Mesh3dStorage {
64    vertices: Vec<Vec3>,
65    triangle_indices: Vec<u32>,
66    display_edges: Vec<MeshEdge3d>,
67    texture_coordinates: Vec<TextureCoordinate2d>,
68    vertex_colors: Vec<Color>,
69    normals: Vec<Vec3>,
70}
71
72/// Normalized texture coordinate with a top-left origin and downward V axis.
73///
74/// Both components are finite in `0..=1`. Material UV transforms and addressing
75/// control repetition independently of these source coordinates. Textures use
76/// mip level zero by default and can opt into complete mip chains. Atlas cells
77/// should map geometry to their edge texel centers for nearest sampling; linear
78/// filtering also needs extruded gutters. Independent cropped tiles isolate
79/// generated mip chains from neighboring atlas cells.
80#[derive(Debug, Clone, Copy, PartialEq)]
81pub struct TextureCoordinate2d {
82    u: f32,
83    v: f32,
84}
85
86impl TextureCoordinate2d {
87    /// Validates normalized U/V without clamping invalid caller input.
88    pub fn new(u: f32, v: f32) -> Result<Self, Mesh3dError> {
89        if !u.is_finite()
90            || !v.is_finite()
91            || !(0.0..=1.0).contains(&u)
92            || !(0.0..=1.0).contains(&v)
93        {
94            return Err(Mesh3dError::InvalidTextureCoordinate);
95        }
96        Ok(Self { u, v })
97    }
98    /// Horizontal normalized texture coordinate, increasing toward the right.
99    pub const fn u(self) -> f32 {
100        self.u
101    }
102    /// Vertical normalized texture coordinate, increasing toward the bottom.
103    pub const fn v(self) -> f32 {
104        self.v
105    }
106}
107
108/// Immutable validated topology for retained stereometry rendering.
109///
110/// Vertices use caller-defined model-space world units. Triangle indices are a
111/// flat triangle list. Construction preserves winding without inferring an
112/// outward side. Surfaces are two-sided by default; an explicitly one-sided
113/// [`SurfaceSidedness3d`] material keeps projected counter-clockwise front faces.
114/// Optional display edges identify the mathematical edges that a later
115/// visible/hidden-line pass should draw; they are not inferred from triangle
116/// adjacency because triangulation diagonals are not necessarily meaningful
117/// construction edges. A mesh may contain surfaces, display edges, or both.
118#[derive(Debug, Clone, PartialEq)]
119pub struct Mesh3d {
120    storage: Arc<Mesh3dStorage>,
121    bounds_min: Vec3,
122    bounds_max: Vec3,
123    minimum_nonzero_components: [f32; 3],
124}
125
126impl Mesh3d {
127    /// Builds a surface mesh without explicit display edges.
128    pub fn new(vertices: Vec<Vec3>, triangle_indices: Vec<u32>) -> Result<Self, Mesh3dError> {
129        Self::with_display_edges(vertices, triangle_indices, Vec::new())
130    }
131
132    /// Builds a mesh with explicit mathematical display edges.
133    ///
134    /// Construction rejects an empty vertex set, geometry with neither
135    /// triangles nor display edges, incomplete triangle lists, out-of-range
136    /// indices, repeated/collinear triangle vertices, duplicate display edges,
137    /// display edges with coincident endpoints, and display edges outside the
138    /// vertex array.
139    pub fn with_display_edges(
140        vertices: Vec<Vec3>,
141        triangle_indices: Vec<u32>,
142        display_edges: Vec<MeshEdge3d>,
143    ) -> Result<Self, Mesh3dError> {
144        Self::with_attributes(
145            vertices,
146            triangle_indices,
147            display_edges,
148            Mesh3dAttributes::new(),
149        )
150    }
151
152    /// Builds surfaces with one validated texture coordinate per model vertex.
153    ///
154    /// Duplicate model positions with different UVs are valid for atlas seams.
155    /// Winding and explicit display edges keep the untextured mesh contract.
156    /// A texture/material is attached only when uploading or binding to a
157    /// renderer; constructing this data requires no GPU dependencies.
158    pub fn textured(
159        vertices: Vec<Vec3>,
160        texture_coordinates: Vec<TextureCoordinate2d>,
161        triangle_indices: Vec<u32>,
162        display_edges: Vec<MeshEdge3d>,
163    ) -> Result<Self, Mesh3dError> {
164        if texture_coordinates.len() != vertices.len() {
165            return Err(Mesh3dError::TextureCoordinateCountMismatch {
166                vertex_count: vertices.len(),
167                coordinate_count: texture_coordinates.len(),
168            });
169        }
170        Self::with_attributes(
171            vertices,
172            triangle_indices,
173            display_edges,
174            Mesh3dAttributes::new().with_texture_coordinates(texture_coordinates),
175        )
176    }
177
178    /// Builds topology with optional UVs and normalized straight-linear colors.
179    /// Supplied attributes must match every vertex, including unused vertices.
180    /// Missing colors multiply by white. Opaque ignores alpha; Mask and Blend
181    /// use combined vertex/material/texture alpha. All buffers are moved into immutable shared storage without copies.
182    pub fn with_attributes(
183        vertices: Vec<Vec3>,
184        triangle_indices: Vec<u32>,
185        display_edges: Vec<MeshEdge3d>,
186        attributes: Mesh3dAttributes,
187    ) -> Result<Self, Mesh3dError> {
188        if let Some(coordinates) = &attributes.texture_coordinates
189            && coordinates.len() != vertices.len()
190        {
191            return Err(Mesh3dError::TextureCoordinateCountMismatch {
192                vertex_count: vertices.len(),
193                coordinate_count: coordinates.len(),
194            });
195        }
196        if let Some(colors) = &attributes.vertex_colors
197            && colors.len() != vertices.len()
198        {
199            return Err(Mesh3dError::VertexColorCountMismatch {
200                vertex_count: vertices.len(),
201                color_count: colors.len(),
202            });
203        }
204        if let Some(normals) = &attributes.normals
205            && normals.len() != vertices.len()
206        {
207            return Err(Mesh3dError::NormalCountMismatch {
208                vertex_count: vertices.len(),
209                normal_count: normals.len(),
210            });
211        }
212        if vertices.is_empty() {
213            return Err(Mesh3dError::EmptyVertices);
214        }
215        if triangle_indices.is_empty() && display_edges.is_empty() {
216            return Err(Mesh3dError::EmptyGeometry);
217        }
218        if !triangle_indices.len().is_multiple_of(3) {
219            return Err(Mesh3dError::InvalidTriangleIndexCount {
220                index_count: triangle_indices.len(),
221            });
222        }
223
224        for (triangle, indices) in triangle_indices.chunks_exact(3).enumerate() {
225            let [first, second, third] = [indices[0], indices[1], indices[2]];
226            validate_index(first, vertices.len())?;
227            validate_index(second, vertices.len())?;
228            validate_index(third, vertices.len())?;
229            if first == second
230                || second == third
231                || first == third
232                || triangle_is_degenerate(
233                    vertices[first as usize],
234                    vertices[second as usize],
235                    vertices[third as usize],
236                )
237            {
238                return Err(Mesh3dError::DegenerateTriangle { triangle });
239            }
240        }
241
242        for edge in &display_edges {
243            validate_index(edge.start, vertices.len())?;
244            validate_index(edge.end, vertices.len())?;
245            if vertices[edge.start as usize] == vertices[edge.end as usize] {
246                return Err(Mesh3dError::DegenerateDisplayEdge {
247                    start: edge.start,
248                    end: edge.end,
249                });
250            }
251        }
252
253        let canonical_bytes = display_edges
254            .len()
255            .checked_mul(std::mem::size_of::<((u32, u32), usize)>())
256            .ok_or(Mesh3dError::AllocationFailed {
257                requested_bytes: usize::MAX,
258            })?;
259        let mut canonical_edges = Vec::new();
260        canonical_edges
261            .try_reserve_exact(display_edges.len())
262            .map_err(|_| Mesh3dError::AllocationFailed {
263                requested_bytes: canonical_bytes,
264            })?;
265        for (index, edge) in display_edges.iter().enumerate() {
266            canonical_edges.push((edge.canonical(), index));
267        }
268        canonical_edges.sort_unstable_by_key(|entry| entry.0);
269        if let Some(pair) = canonical_edges
270            .windows(2)
271            .find(|pair| pair[0].0 == pair[1].0)
272        {
273            let duplicate = display_edges[pair[0].1.max(pair[1].1)];
274            return Err(Mesh3dError::DuplicateDisplayEdge {
275                start: duplicate.start,
276                end: duplicate.end,
277            });
278        }
279
280        let (bounds_min, bounds_max, minimum_nonzero_components) = mesh_bounds(&vertices);
281        Ok(Self {
282            // One fixed-size Arc control block makes Mesh3d cloning O(1)
283            // without copying any caller-scale topology buffers.
284            storage: Arc::new(Mesh3dStorage {
285                vertices,
286                triangle_indices,
287                display_edges,
288                texture_coordinates: attributes.texture_coordinates.unwrap_or_default(),
289                vertex_colors: attributes.vertex_colors.unwrap_or_default(),
290                normals: attributes.normals.unwrap_or_default(),
291            }),
292            bounds_min,
293            bounds_max,
294            minimum_nonzero_components,
295        })
296    }
297
298    /// Returns immutable model-space vertices.
299    pub fn vertices(&self) -> &[Vec3] {
300        &self.storage.vertices
301    }
302
303    /// Returns the flat host-wound triangle index list.
304    pub fn triangle_indices(&self) -> &[u32] {
305        &self.storage.triangle_indices
306    }
307
308    /// Returns explicit mathematical edges, excluding triangulation diagonals.
309    pub fn display_edges(&self) -> &[MeshEdge3d] {
310        &self.storage.display_edges
311    }
312
313    /// Returns per-vertex normalized UVs, or an empty slice for untextured data.
314    pub fn texture_coordinates(&self) -> &[TextureCoordinate2d] {
315        &self.storage.texture_coordinates
316    }
317
318    /// Returns normalized straight-linear vertex RGBA, or empty for white.
319    /// The opaque surface pass ignores alpha; mathematical edges are unaffected.
320    pub fn vertex_colors(&self) -> &[Color] {
321        &self.storage.vertex_colors
322    }
323
324    /// Returns normalized application-supplied model normals, or an empty slice.
325    /// Lambert surfaces require normals; Unlit surfaces never evaluate them.
326    pub fn normals(&self) -> &[Vec3] {
327        &self.storage.normals
328    }
329
330    /// Returns the number of retained triangles.
331    pub fn triangle_count(&self) -> usize {
332        self.storage.triangle_indices.len() / 3
333    }
334
335    /// Returns the inclusive model-space lower bound.
336    pub const fn bounds_min(&self) -> Vec3 {
337        self.bounds_min
338    }
339
340    /// Returns the inclusive model-space upper bound.
341    pub const fn bounds_max(&self) -> Vec3 {
342        self.bounds_max
343    }
344
345    // Bounds alone cannot detect a subnormal source hidden between ordinary
346    // extrema. Immutable source metadata also covers unreferenced vertices.
347    #[cfg(feature = "wgpu")]
348    pub(crate) const fn minimum_nonzero_components(&self) -> [f32; 3] {
349        self.minimum_nonzero_components
350    }
351
352    /// Returns retained CPU capacity bytes for topology and optional attributes.
353    pub fn recovery_memory_bytes(&self) -> usize {
354        self.storage
355            .vertices
356            .capacity()
357            .saturating_mul(std::mem::size_of::<Vec3>())
358            .saturating_add(
359                self.storage
360                    .triangle_indices
361                    .capacity()
362                    .saturating_mul(std::mem::size_of::<u32>()),
363            )
364            .saturating_add(
365                self.storage
366                    .display_edges
367                    .capacity()
368                    .saturating_mul(std::mem::size_of::<MeshEdge3d>()),
369            )
370            .saturating_add(
371                self.storage
372                    .texture_coordinates
373                    .capacity()
374                    .saturating_mul(std::mem::size_of::<TextureCoordinate2d>()),
375            )
376            .saturating_add(
377                self.storage
378                    .vertex_colors
379                    .capacity()
380                    .saturating_mul(std::mem::size_of::<Color>()),
381            )
382            .saturating_add(
383                self.storage
384                    .normals
385                    .capacity()
386                    .saturating_mul(std::mem::size_of::<Vec3>()),
387            )
388    }
389}
390
391/// Rejection reason for retained 3D topology.
392#[derive(Debug, Clone, Copy, PartialEq, Eq)]
393pub enum Mesh3dError {
394    /// A supplied normal is zero or cannot be normalized to a finite direction.
395    InvalidVertexNormal {
396        /// Source attribute index, including unused vertices.
397        vertex_index: usize,
398    },
399    /// Explicit normals must match every model vertex, including unused ones.
400    NormalCountMismatch {
401        /// Number of model vertices.
402        vertex_count: usize,
403        /// Number of supplied normals.
404        normal_count: usize,
405    },
406    /// A vertex color contains a non-finite or non-normalized channel.
407    InvalidVertexColor {
408        /// Zero-based source vertex/attribute index, including unused vertices.
409        vertex_index: usize,
410    },
411    /// An explicitly supplied color array must cover every model vertex.
412    VertexColorCountMismatch {
413        /// Number of model vertices.
414        vertex_count: usize,
415        /// Number of supplied straight-linear RGBA values.
416        color_count: usize,
417    },
418    /// A U/V component was non-finite or outside normalized `0..=1` bounds.
419    InvalidTextureCoordinate,
420    /// Textured topology must supply exactly one UV for each model vertex.
421    TextureCoordinateCountMismatch {
422        /// Number of model-space vertices.
423        vertex_count: usize,
424        /// Number of normalized texture coordinates provided.
425        coordinate_count: usize,
426    },
427    /// A retained mesh requires at least one model-space vertex.
428    EmptyVertices,
429    /// A retained mesh requires at least one triangle or display edge.
430    EmptyGeometry,
431    /// The triangle index list was not divisible by three.
432    InvalidTriangleIndexCount {
433        /// Rejected number of indices.
434        index_count: usize,
435    },
436    /// A triangle or display edge referenced a missing vertex.
437    IndexOutOfBounds {
438        /// Rejected vertex index.
439        index: u32,
440        /// Number of vertices available in the mesh.
441        vertex_count: usize,
442    },
443    /// A triangle repeated a vertex or had zero model-space area.
444    DegenerateTriangle {
445        /// Zero-based triangle number in the index list.
446        triangle: usize,
447    },
448    /// A display edge used one index twice or referenced coincident vertices.
449    DegenerateDisplayEdge {
450        /// First endpoint in the rejected declaration.
451        start: u32,
452        /// Second endpoint in the rejected declaration.
453        end: u32,
454    },
455    /// The same undirected display edge appeared more than once.
456    DuplicateDisplayEdge {
457        /// First endpoint in the rejected declaration.
458        start: u32,
459        /// Second endpoint in the rejected declaration.
460        end: u32,
461    },
462    /// Temporary validation storage could not be reserved.
463    AllocationFailed {
464        /// Bytes requested for duplicate-edge validation.
465        requested_bytes: usize,
466    },
467}
468
469impl fmt::Display for Mesh3dError {
470    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
471        match self {
472            Self::InvalidVertexNormal { vertex_index } => write!(
473                formatter,
474                "3D vertex {vertex_index} normal must be a nonzero finite direction"
475            ),
476            Self::NormalCountMismatch {
477                vertex_count,
478                normal_count,
479            } => write!(
480                formatter,
481                "{vertex_count} mesh vertices require matching normals, got {normal_count}"
482            ),
483            Self::InvalidVertexColor { vertex_index } => write!(
484                formatter,
485                "3D vertex {vertex_index} color must be finite straight-linear RGBA in 0..=1"
486            ),
487            Self::VertexColorCountMismatch {
488                vertex_count,
489                color_count,
490            } => write!(
491                formatter,
492                "{vertex_count} mesh vertices require matching colors, got {color_count}"
493            ),
494            Self::InvalidTextureCoordinate => {
495                write!(formatter, "texture coordinates must be finite in 0..=1")
496            }
497            Self::TextureCoordinateCountMismatch {
498                vertex_count,
499                coordinate_count,
500            } => write!(
501                formatter,
502                "{vertex_count} mesh vertices require matching UVs, got {coordinate_count}"
503            ),
504            Self::EmptyVertices => write!(formatter, "3D mesh requires at least one vertex"),
505            Self::EmptyGeometry => {
506                write!(formatter, "3D mesh requires triangles or display edges")
507            }
508            Self::InvalidTriangleIndexCount { index_count } => write!(
509                formatter,
510                "3D mesh triangle index count, when present, must be divisible by three, got {index_count}"
511            ),
512            Self::IndexOutOfBounds {
513                index,
514                vertex_count,
515            } => write!(
516                formatter,
517                "3D mesh index {index} is outside {vertex_count} vertices"
518            ),
519            Self::DegenerateTriangle { triangle } => {
520                write!(formatter, "3D mesh triangle {triangle} has zero area")
521            }
522            Self::DegenerateDisplayEdge { start, end } => {
523                write!(formatter, "3D display edge {start}-{end} has zero length")
524            }
525            Self::DuplicateDisplayEdge { start, end } => {
526                write!(formatter, "3D display edge {start}-{end} is duplicated")
527            }
528            Self::AllocationFailed { requested_bytes } => write!(
529                formatter,
530                "could not reserve {requested_bytes} bytes for 3D mesh validation"
531            ),
532        }
533    }
534}
535
536impl Error for Mesh3dError {}
537
538fn validate_index(index: u32, vertex_count: usize) -> Result<(), Mesh3dError> {
539    ((index as u64) < vertex_count as u64)
540        .then_some(())
541        .ok_or(Mesh3dError::IndexOutOfBounds {
542            index,
543            vertex_count,
544        })
545}
546
547fn triangle_is_degenerate(first: Vec3, second: Vec3, third: Vec3) -> bool {
548    let ab = (
549        second.x() as f64 - first.x() as f64,
550        second.y() as f64 - first.y() as f64,
551        second.z() as f64 - first.z() as f64,
552    );
553    let ac = (
554        third.x() as f64 - first.x() as f64,
555        third.y() as f64 - first.y() as f64,
556        third.z() as f64 - first.z() as f64,
557    );
558    let cross = (
559        ab.1 * ac.2 - ab.2 * ac.1,
560        ab.2 * ac.0 - ab.0 * ac.2,
561        ab.0 * ac.1 - ab.1 * ac.0,
562    );
563    cross.0 == 0.0 && cross.1 == 0.0 && cross.2 == 0.0
564}
565
566fn mesh_bounds(vertices: &[Vec3]) -> (Vec3, Vec3, [f32; 3]) {
567    let first = vertices[0];
568    let mut minimum = [first.x(), first.y(), first.z()];
569    let mut maximum = minimum;
570    let mut minimum_nonzero = [f32::INFINITY; 3];
571    for vertex in vertices {
572        let components = [vertex.x(), vertex.y(), vertex.z()];
573        for axis in 0..3 {
574            minimum[axis] = minimum[axis].min(components[axis]);
575            maximum[axis] = maximum[axis].max(components[axis]);
576            if components[axis] != 0.0 {
577                minimum_nonzero[axis] = minimum_nonzero[axis].min(components[axis].abs());
578            }
579        }
580    }
581    (
582        Vec3::new_unchecked(minimum[0], minimum[1], minimum[2]),
583        Vec3::new_unchecked(maximum[0], maximum[1], maximum[2]),
584        minimum_nonzero,
585    )
586}