Skip to main content

sim_engine/
mesh3d.rs

1use std::{error::Error, fmt, sync::Arc};
2
3use crate::{Color, LogicalPixels, Vec3};
4
5const MAX_LOGICAL_EDGE_METRIC: f32 = 1_048_576.0;
6
7/// Surface material for one retained 3D instance.
8///
9/// The representation is private so translucent and hatched section modes can
10/// be added without changing `Mesh3dInstance` construction. The first renderer
11/// slice supports only opaque color/depth-writing surfaces.
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct SurfaceStyle3d {
14    color: Color,
15}
16
17impl SurfaceStyle3d {
18    /// Creates an opaque linear-RGBA surface.
19    pub fn opaque(color: Color) -> Result<Self, Mesh3dStyleError> {
20        if !color.is_normalized() || color.alpha() != 1.0 {
21            return Err(Mesh3dStyleError::InvalidSurfaceColor);
22        }
23        Ok(Self { color })
24    }
25
26    /// Returns the opaque linear-RGBA color used by the current surface pass.
27    pub const fn color(self) -> Color {
28        self.color
29    }
30}
31
32/// Extensible visual material bundle for a retained 3D object.
33///
34/// Surface and wireframe presentation are independent. Edge-only construction
35/// geometry uses `surface = None`; future section materials can extend
36/// [`SurfaceStyle3d`] without changing scene insertion or object addressing.
37#[derive(Debug, Clone, Copy, PartialEq)]
38pub struct MeshStyle3d {
39    surface: Option<SurfaceStyle3d>,
40    wireframe: Option<WireframeStyle3d>,
41}
42
43impl MeshStyle3d {
44    /// Creates an object with an opaque surface and no display edges.
45    pub const fn surface(surface: SurfaceStyle3d) -> Self {
46        Self {
47            surface: Some(surface),
48            wireframe: None,
49        }
50    }
51
52    /// Creates display edges without a surface/depth-writing face pass.
53    pub const fn wireframe(wireframe: WireframeStyle3d) -> Self {
54        Self {
55            surface: None,
56            wireframe: Some(wireframe),
57        }
58    }
59
60    /// Adds or replaces display-edge presentation.
61    pub const fn with_wireframe(mut self, wireframe: WireframeStyle3d) -> Self {
62        self.wireframe = Some(wireframe);
63        self
64    }
65
66    /// Returns the optional surface material.
67    pub const fn surface_style(self) -> Option<SurfaceStyle3d> {
68        self.surface
69    }
70
71    /// Returns the optional edge presentation.
72    pub const fn wireframe_style(self) -> Option<WireframeStyle3d> {
73        self.wireframe
74    }
75}
76
77/// Logical-screen presentation for explicit mathematical mesh edges.
78///
79/// Visible fragments are solid. Fragments occluded beyond the depth buffer's
80/// conservative coplanar tolerance may be drawn with a logical-pixel dash/gap
81/// pattern. Classification uses one implementation depth unit away from the
82/// camera for hidden fragments and one unit toward it for visible fragments,
83/// with visible fragments rendered last. Therefore coplanar and
84/// sub-depth-resolution separations intentionally resolve as visible; this is
85/// raster visibility, not exact analytic solid geometry.
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub struct WireframeStyle3d {
88    visible_color: Color,
89    visible_width: LogicalPixels,
90    hidden: Option<HiddenEdgeStyle3d>,
91}
92
93#[derive(Debug, Clone, Copy, PartialEq)]
94struct HiddenEdgeStyle3d {
95    color: Color,
96    width: LogicalPixels,
97    dash_length: LogicalPixels,
98    gap_length: LogicalPixels,
99}
100
101impl WireframeStyle3d {
102    /// Largest accepted width, dash, or gap in logical pixels.
103    ///
104    /// The bound keeps every style-derived shader operation inside the
105    /// cross-backend arithmetic envelope.
106    pub const MAX_LOGICAL_PIXELS: f32 = MAX_LOGICAL_EDGE_METRIC;
107
108    /// Creates solid visible edges with hidden fragments disabled.
109    pub fn visible(color: Color, width: LogicalPixels) -> Result<Self, Mesh3dStyleError> {
110        validate_edge_color_width(color, width)?;
111        Ok(Self {
112            visible_color: color,
113            visible_width: width,
114            hidden: None,
115        })
116    }
117
118    /// Enables dashed depth-occluded fragments in logical screen pixels.
119    ///
120    /// Occlusion must exceed the conservative two-unit coplanar tolerance
121    /// documented on [`WireframeStyle3d`] before a fragment resolves hidden.
122    pub fn with_hidden(
123        mut self,
124        color: Color,
125        width: LogicalPixels,
126        dash_length: LogicalPixels,
127        gap_length: LogicalPixels,
128    ) -> Result<Self, Mesh3dStyleError> {
129        validate_edge_color_width(color, width)?;
130        if !is_stable_edge_metric(dash_length.get())
131            || !is_stable_edge_metric(gap_length.get())
132            || !(dash_length.get() + gap_length.get()).is_finite()
133        {
134            return Err(Mesh3dStyleError::InvalidDashPattern);
135        }
136        self.hidden = Some(HiddenEdgeStyle3d {
137            color,
138            width,
139            dash_length,
140            gap_length,
141        });
142        Ok(self)
143    }
144
145    /// Returns the solid visible-edge color in linear RGBA.
146    pub const fn visible_color(self) -> Color {
147        self.visible_color
148    }
149
150    /// Returns visible-edge width in logical screen pixels.
151    pub const fn visible_width(self) -> LogicalPixels {
152        self.visible_width
153    }
154
155    /// Returns whether depth-occluded edge fragments should be drawn.
156    pub const fn hidden_enabled(self) -> bool {
157        self.hidden.is_some()
158    }
159
160    /// Returns hidden-edge color when enabled.
161    pub const fn hidden_color(self) -> Option<Color> {
162        match self.hidden {
163            Some(hidden) => Some(hidden.color),
164            None => None,
165        }
166    }
167
168    /// Returns hidden-edge width in logical screen pixels when enabled.
169    pub const fn hidden_width(self) -> Option<LogicalPixels> {
170        match self.hidden {
171            Some(hidden) => Some(hidden.width),
172            None => None,
173        }
174    }
175
176    /// Returns hidden dash and gap lengths in logical screen pixels.
177    pub const fn hidden_pattern(self) -> Option<(LogicalPixels, LogicalPixels)> {
178        match self.hidden {
179            Some(hidden) => Some((hidden.dash_length, hidden.gap_length)),
180            None => None,
181        }
182    }
183}
184
185/// Rejection reason for logical-screen 3D edge presentation.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub enum Mesh3dStyleError {
188    /// Surface color must be normalized and opaque in the initial material mode.
189    InvalidSurfaceColor,
190    /// Edge color must be normalized and opaque, and width must be a normal
191    /// positive value no greater than [`WireframeStyle3d::MAX_LOGICAL_PIXELS`].
192    InvalidColorOrWidth,
193    /// Hidden dash and gap must be normal positive values, each no greater than
194    /// [`WireframeStyle3d::MAX_LOGICAL_PIXELS`], with a finite sum.
195    InvalidDashPattern,
196}
197
198impl fmt::Display for Mesh3dStyleError {
199    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
200        match self {
201            Self::InvalidSurfaceColor => write!(formatter, "3D surface color must be opaque"),
202            Self::InvalidColorOrWidth => {
203                write!(
204                    formatter,
205                    "3D edge color must be opaque and width must be normal and in 0..={MAX_LOGICAL_EDGE_METRIC} logical pixels"
206                )
207            }
208            Self::InvalidDashPattern => {
209                write!(
210                    formatter,
211                    "3D hidden-edge dash and gap must each be normal and in 0..={MAX_LOGICAL_EDGE_METRIC} logical pixels with a finite sum"
212                )
213            }
214        }
215    }
216}
217
218impl Error for Mesh3dStyleError {}
219
220fn validate_edge_color_width(color: Color, width: LogicalPixels) -> Result<(), Mesh3dStyleError> {
221    if color.is_normalized() && color.alpha() == 1.0 && is_stable_edge_metric(width.get()) {
222        Ok(())
223    } else {
224        Err(Mesh3dStyleError::InvalidColorOrWidth)
225    }
226}
227
228fn is_stable_edge_metric(value: f32) -> bool {
229    value.is_normal() && value <= MAX_LOGICAL_EDGE_METRIC
230}
231
232/// One explicit display edge in a retained 3D mesh.
233///
234/// Endpoints index the mesh vertex array. A mesh validates the indices and
235/// rejects repeated or zero-length edges when it is constructed.
236#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
237pub struct MeshEdge3d {
238    start: u32,
239    end: u32,
240}
241
242impl MeshEdge3d {
243    /// Describes an edge between two distinct vertex indices.
244    pub fn new(start: u32, end: u32) -> Result<Self, Mesh3dError> {
245        if start == end {
246            return Err(Mesh3dError::DegenerateDisplayEdge { start, end });
247        }
248        Ok(Self { start, end })
249    }
250
251    /// Returns the first mesh vertex index.
252    pub const fn start(self) -> u32 {
253        self.start
254    }
255
256    /// Returns the second mesh vertex index.
257    pub const fn end(self) -> u32 {
258        self.end
259    }
260
261    fn canonical(self) -> (u32, u32) {
262        if self.start < self.end {
263            (self.start, self.end)
264        } else {
265            (self.end, self.start)
266        }
267    }
268}
269
270#[derive(Debug, PartialEq)]
271struct Mesh3dStorage {
272    vertices: Vec<Vec3>,
273    triangle_indices: Vec<u32>,
274    display_edges: Vec<MeshEdge3d>,
275    texture_coordinates: Vec<TextureCoordinate2d>,
276}
277
278/// Normalized texture coordinate with a top-left origin and downward V axis.
279///
280/// Both components are finite in `0..=1`. The textured 3D path uses mip level
281/// zero and clamp-to-edge addressing. Atlas cells should map geometry to their
282/// edge texel centers for nearest sampling. Strict linear-filter isolation also
283/// requires host-owned extruded gutters to tolerate interpolation rounding.
284#[derive(Debug, Clone, Copy, PartialEq)]
285pub struct TextureCoordinate2d {
286    u: f32,
287    v: f32,
288}
289
290impl TextureCoordinate2d {
291    /// Validates normalized U/V without clamping invalid caller input.
292    pub fn new(u: f32, v: f32) -> Result<Self, Mesh3dError> {
293        if !u.is_finite()
294            || !v.is_finite()
295            || !(0.0..=1.0).contains(&u)
296            || !(0.0..=1.0).contains(&v)
297        {
298            return Err(Mesh3dError::InvalidTextureCoordinate);
299        }
300        Ok(Self { u, v })
301    }
302    /// Horizontal normalized texture coordinate, increasing toward the right.
303    pub const fn u(self) -> f32 {
304        self.u
305    }
306    /// Vertical normalized texture coordinate, increasing toward the bottom.
307    pub const fn v(self) -> f32 {
308        self.v
309    }
310}
311
312/// Immutable validated topology for retained stereometry rendering.
313///
314/// Vertices use caller-defined model-space world units. Triangle indices are a
315/// flat triangle list. Winding is preserved but deliberately not interpreted:
316/// the current surface pass disables face culling, and a global
317/// "counter-clockwise" rule is meaningless without a declared outward side.
318/// Optional display edges identify the mathematical edges that a later
319/// visible/hidden-line pass should draw; they are not inferred from triangle
320/// adjacency because triangulation diagonals are not necessarily meaningful
321/// construction edges. A mesh may contain surfaces, display edges, or both.
322#[derive(Debug, Clone, PartialEq)]
323pub struct Mesh3d {
324    storage: Arc<Mesh3dStorage>,
325    bounds_min: Vec3,
326    bounds_max: Vec3,
327}
328
329impl Mesh3d {
330    /// Builds a surface mesh without explicit display edges.
331    pub fn new(vertices: Vec<Vec3>, triangle_indices: Vec<u32>) -> Result<Self, Mesh3dError> {
332        Self::with_display_edges(vertices, triangle_indices, Vec::new())
333    }
334
335    /// Builds a mesh with explicit mathematical display edges.
336    ///
337    /// Construction rejects an empty vertex set, geometry with neither
338    /// triangles nor display edges, incomplete triangle lists, out-of-range
339    /// indices, repeated/collinear triangle vertices, duplicate display edges,
340    /// display edges with coincident endpoints, and display edges outside the
341    /// vertex array.
342    pub fn with_display_edges(
343        vertices: Vec<Vec3>,
344        triangle_indices: Vec<u32>,
345        display_edges: Vec<MeshEdge3d>,
346    ) -> Result<Self, Mesh3dError> {
347        Self::with_attributes(vertices, triangle_indices, display_edges, Vec::new())
348    }
349
350    /// Builds surfaces with one validated texture coordinate per model vertex.
351    ///
352    /// Duplicate model positions with different UVs are valid for atlas seams.
353    /// Winding and explicit display edges keep the untextured mesh contract.
354    /// A texture/material is attached only when uploading or binding to a
355    /// renderer; constructing this data requires no GPU dependencies.
356    pub fn textured(
357        vertices: Vec<Vec3>,
358        texture_coordinates: Vec<TextureCoordinate2d>,
359        triangle_indices: Vec<u32>,
360        display_edges: Vec<MeshEdge3d>,
361    ) -> Result<Self, Mesh3dError> {
362        if texture_coordinates.len() != vertices.len() {
363            return Err(Mesh3dError::TextureCoordinateCountMismatch {
364                vertex_count: vertices.len(),
365                coordinate_count: texture_coordinates.len(),
366            });
367        }
368        Self::with_attributes(
369            vertices,
370            triangle_indices,
371            display_edges,
372            texture_coordinates,
373        )
374    }
375
376    fn with_attributes(
377        vertices: Vec<Vec3>,
378        triangle_indices: Vec<u32>,
379        display_edges: Vec<MeshEdge3d>,
380        texture_coordinates: Vec<TextureCoordinate2d>,
381    ) -> Result<Self, Mesh3dError> {
382        if vertices.is_empty() {
383            return Err(Mesh3dError::EmptyVertices);
384        }
385        if triangle_indices.is_empty() && display_edges.is_empty() {
386            return Err(Mesh3dError::EmptyGeometry);
387        }
388        if !triangle_indices.len().is_multiple_of(3) {
389            return Err(Mesh3dError::InvalidTriangleIndexCount {
390                index_count: triangle_indices.len(),
391            });
392        }
393
394        for (triangle, indices) in triangle_indices.chunks_exact(3).enumerate() {
395            let [first, second, third] = [indices[0], indices[1], indices[2]];
396            validate_index(first, vertices.len())?;
397            validate_index(second, vertices.len())?;
398            validate_index(third, vertices.len())?;
399            if first == second
400                || second == third
401                || first == third
402                || triangle_is_degenerate(
403                    vertices[first as usize],
404                    vertices[second as usize],
405                    vertices[third as usize],
406                )
407            {
408                return Err(Mesh3dError::DegenerateTriangle { triangle });
409            }
410        }
411
412        for edge in &display_edges {
413            validate_index(edge.start, vertices.len())?;
414            validate_index(edge.end, vertices.len())?;
415            if vertices[edge.start as usize] == vertices[edge.end as usize] {
416                return Err(Mesh3dError::DegenerateDisplayEdge {
417                    start: edge.start,
418                    end: edge.end,
419                });
420            }
421        }
422
423        let canonical_bytes = display_edges
424            .len()
425            .checked_mul(std::mem::size_of::<((u32, u32), usize)>())
426            .ok_or(Mesh3dError::AllocationFailed {
427                requested_bytes: usize::MAX,
428            })?;
429        let mut canonical_edges = Vec::new();
430        canonical_edges
431            .try_reserve_exact(display_edges.len())
432            .map_err(|_| Mesh3dError::AllocationFailed {
433                requested_bytes: canonical_bytes,
434            })?;
435        for (index, edge) in display_edges.iter().enumerate() {
436            canonical_edges.push((edge.canonical(), index));
437        }
438        canonical_edges.sort_unstable_by_key(|entry| entry.0);
439        if let Some(pair) = canonical_edges
440            .windows(2)
441            .find(|pair| pair[0].0 == pair[1].0)
442        {
443            let duplicate = display_edges[pair[0].1.max(pair[1].1)];
444            return Err(Mesh3dError::DuplicateDisplayEdge {
445                start: duplicate.start,
446                end: duplicate.end,
447            });
448        }
449
450        let (bounds_min, bounds_max) = mesh_bounds(&vertices);
451        Ok(Self {
452            // One fixed-size Arc control block makes Mesh3d cloning O(1)
453            // without copying any caller-scale topology buffers.
454            storage: Arc::new(Mesh3dStorage {
455                vertices,
456                triangle_indices,
457                display_edges,
458                texture_coordinates,
459            }),
460            bounds_min,
461            bounds_max,
462        })
463    }
464
465    /// Returns immutable model-space vertices.
466    pub fn vertices(&self) -> &[Vec3] {
467        &self.storage.vertices
468    }
469
470    /// Returns the flat host-wound triangle index list.
471    pub fn triangle_indices(&self) -> &[u32] {
472        &self.storage.triangle_indices
473    }
474
475    /// Returns explicit mathematical edges, excluding triangulation diagonals.
476    pub fn display_edges(&self) -> &[MeshEdge3d] {
477        &self.storage.display_edges
478    }
479
480    /// Returns per-vertex normalized UVs, or an empty slice for untextured data.
481    pub fn texture_coordinates(&self) -> &[TextureCoordinate2d] {
482        &self.storage.texture_coordinates
483    }
484
485    /// Returns the number of retained triangles.
486    pub fn triangle_count(&self) -> usize {
487        self.storage.triangle_indices.len() / 3
488    }
489
490    /// Returns the inclusive model-space lower bound.
491    pub const fn bounds_min(&self) -> Vec3 {
492        self.bounds_min
493    }
494
495    /// Returns the inclusive model-space upper bound.
496    pub const fn bounds_max(&self) -> Vec3 {
497        self.bounds_max
498    }
499
500    /// Returns retained CPU bytes used by vertices, indices, and display edges.
501    pub fn recovery_memory_bytes(&self) -> usize {
502        self.storage
503            .vertices
504            .capacity()
505            .saturating_mul(std::mem::size_of::<Vec3>())
506            .saturating_add(
507                self.storage
508                    .triangle_indices
509                    .capacity()
510                    .saturating_mul(std::mem::size_of::<u32>()),
511            )
512            .saturating_add(
513                self.storage
514                    .display_edges
515                    .capacity()
516                    .saturating_mul(std::mem::size_of::<MeshEdge3d>()),
517            )
518            .saturating_add(
519                self.storage
520                    .texture_coordinates
521                    .capacity()
522                    .saturating_mul(std::mem::size_of::<TextureCoordinate2d>()),
523            )
524    }
525}
526
527/// Rejection reason for retained 3D topology.
528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
529pub enum Mesh3dError {
530    /// A U/V component was non-finite or outside normalized `0..=1` bounds.
531    InvalidTextureCoordinate,
532    /// Textured topology must supply exactly one UV for each model vertex.
533    TextureCoordinateCountMismatch {
534        /// Number of model-space vertices.
535        vertex_count: usize,
536        /// Number of normalized texture coordinates provided.
537        coordinate_count: usize,
538    },
539    /// A retained mesh requires at least one model-space vertex.
540    EmptyVertices,
541    /// A retained mesh requires at least one triangle or display edge.
542    EmptyGeometry,
543    /// The triangle index list was not divisible by three.
544    InvalidTriangleIndexCount {
545        /// Rejected number of indices.
546        index_count: usize,
547    },
548    /// A triangle or display edge referenced a missing vertex.
549    IndexOutOfBounds {
550        /// Rejected vertex index.
551        index: u32,
552        /// Number of vertices available in the mesh.
553        vertex_count: usize,
554    },
555    /// A triangle repeated a vertex or had zero model-space area.
556    DegenerateTriangle {
557        /// Zero-based triangle number in the index list.
558        triangle: usize,
559    },
560    /// A display edge used one index twice or referenced coincident vertices.
561    DegenerateDisplayEdge {
562        /// First endpoint in the rejected declaration.
563        start: u32,
564        /// Second endpoint in the rejected declaration.
565        end: u32,
566    },
567    /// The same undirected display edge appeared more than once.
568    DuplicateDisplayEdge {
569        /// First endpoint in the rejected declaration.
570        start: u32,
571        /// Second endpoint in the rejected declaration.
572        end: u32,
573    },
574    /// Temporary validation storage could not be reserved.
575    AllocationFailed {
576        /// Bytes requested for duplicate-edge validation.
577        requested_bytes: usize,
578    },
579}
580
581impl fmt::Display for Mesh3dError {
582    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
583        match self {
584            Self::InvalidTextureCoordinate => {
585                write!(formatter, "texture coordinates must be finite in 0..=1")
586            }
587            Self::TextureCoordinateCountMismatch {
588                vertex_count,
589                coordinate_count,
590            } => write!(
591                formatter,
592                "{vertex_count} mesh vertices require matching UVs, got {coordinate_count}"
593            ),
594            Self::EmptyVertices => write!(formatter, "3D mesh requires at least one vertex"),
595            Self::EmptyGeometry => {
596                write!(formatter, "3D mesh requires triangles or display edges")
597            }
598            Self::InvalidTriangleIndexCount { index_count } => write!(
599                formatter,
600                "3D mesh triangle index count, when present, must be divisible by three, got {index_count}"
601            ),
602            Self::IndexOutOfBounds {
603                index,
604                vertex_count,
605            } => write!(
606                formatter,
607                "3D mesh index {index} is outside {vertex_count} vertices"
608            ),
609            Self::DegenerateTriangle { triangle } => {
610                write!(formatter, "3D mesh triangle {triangle} has zero area")
611            }
612            Self::DegenerateDisplayEdge { start, end } => {
613                write!(formatter, "3D display edge {start}-{end} has zero length")
614            }
615            Self::DuplicateDisplayEdge { start, end } => {
616                write!(formatter, "3D display edge {start}-{end} is duplicated")
617            }
618            Self::AllocationFailed { requested_bytes } => write!(
619                formatter,
620                "could not reserve {requested_bytes} bytes for 3D mesh validation"
621            ),
622        }
623    }
624}
625
626impl Error for Mesh3dError {}
627
628fn validate_index(index: u32, vertex_count: usize) -> Result<(), Mesh3dError> {
629    ((index as u64) < vertex_count as u64)
630        .then_some(())
631        .ok_or(Mesh3dError::IndexOutOfBounds {
632            index,
633            vertex_count,
634        })
635}
636
637fn triangle_is_degenerate(first: Vec3, second: Vec3, third: Vec3) -> bool {
638    let ab = (
639        second.x() as f64 - first.x() as f64,
640        second.y() as f64 - first.y() as f64,
641        second.z() as f64 - first.z() as f64,
642    );
643    let ac = (
644        third.x() as f64 - first.x() as f64,
645        third.y() as f64 - first.y() as f64,
646        third.z() as f64 - first.z() as f64,
647    );
648    let cross = (
649        ab.1 * ac.2 - ab.2 * ac.1,
650        ab.2 * ac.0 - ab.0 * ac.2,
651        ab.0 * ac.1 - ab.1 * ac.0,
652    );
653    cross.0 == 0.0 && cross.1 == 0.0 && cross.2 == 0.0
654}
655
656fn mesh_bounds(vertices: &[Vec3]) -> (Vec3, Vec3) {
657    let first = vertices[0];
658    let mut minimum = [first.x(), first.y(), first.z()];
659    let mut maximum = minimum;
660    for vertex in &vertices[1..] {
661        let components = [vertex.x(), vertex.y(), vertex.z()];
662        for axis in 0..3 {
663            minimum[axis] = minimum[axis].min(components[axis]);
664            maximum[axis] = maximum[axis].max(components[axis]);
665        }
666    }
667    (
668        Vec3::new_unchecked(minimum[0], minimum[1], minimum[2]),
669        Vec3::new_unchecked(maximum[0], maximum[1], maximum[2]),
670    )
671}
672
673#[cfg(test)]
674mod tests {
675    use super::{
676        Mesh3d, Mesh3dError, Mesh3dStyleError, MeshEdge3d, MeshStyle3d, SurfaceStyle3d,
677        WireframeStyle3d,
678    };
679    use crate::{Color, LogicalPixels, UnitError, Vec3};
680
681    fn vector(x: f32, y: f32, z: f32) -> Vec3 {
682        Vec3::new(x, y, z).unwrap()
683    }
684
685    fn logical(value: f32) -> LogicalPixels {
686        LogicalPixels::new(value).unwrap()
687    }
688
689    #[test]
690    fn texture_coordinates_are_finite_normalized_and_match_vertices() {
691        use super::TextureCoordinate2d;
692        for value in [f32::NAN, f32::INFINITY, -f32::INFINITY, -0.01, 1.01] {
693            assert_eq!(
694                TextureCoordinate2d::new(value, 0.0),
695                Err(Mesh3dError::InvalidTextureCoordinate)
696            );
697            assert_eq!(
698                TextureCoordinate2d::new(0.0, value),
699                Err(Mesh3dError::InvalidTextureCoordinate)
700            );
701        }
702        let uv = TextureCoordinate2d::new(0.0, 1.0).unwrap();
703        assert_eq!((uv.u(), uv.v()), (0.0, 1.0));
704        let vertices = vec![Vec3::ZERO, Vec3::X, Vec3::Y];
705        for count in [0, 2, 4] {
706            assert_eq!(
707                Mesh3d::textured(vertices.clone(), vec![uv; count], vec![0, 1, 2], Vec::new()),
708                Err(Mesh3dError::TextureCoordinateCountMismatch {
709                    vertex_count: 3,
710                    coordinate_count: count
711                })
712            );
713        }
714        let bare = Mesh3d::new(vertices.clone(), vec![0, 1, 2]).unwrap();
715        let mesh = Mesh3d::textured(vertices, vec![uv; 3], vec![0, 1, 2], Vec::new()).unwrap();
716        assert_eq!(mesh.texture_coordinates(), &[uv; 3]);
717        assert_eq!(
718            mesh.recovery_memory_bytes(),
719            bare.recovery_memory_bytes() + 3 * std::mem::size_of::<TextureCoordinate2d>()
720        );
721        assert_eq!(
722            mesh.clone().texture_coordinates().as_ptr(),
723            mesh.texture_coordinates().as_ptr()
724        );
725    }
726
727    #[test]
728    fn mesh_validates_topology_and_preserves_explicit_edges() {
729        let mesh = Mesh3d::with_display_edges(
730            vec![
731                vector(-1.0, -1.0, 0.0),
732                vector(1.0, -1.0, 0.0),
733                vector(0.0, 1.0, 0.0),
734            ],
735            vec![0, 1, 2],
736            vec![
737                MeshEdge3d::new(0, 1).unwrap(),
738                MeshEdge3d::new(1, 2).unwrap(),
739            ],
740        )
741        .unwrap();
742        assert_eq!(mesh.triangle_count(), 1);
743        assert_eq!(mesh.display_edges().len(), 2);
744        assert_eq!(mesh.bounds_min(), vector(-1.0, -1.0, 0.0));
745        assert_eq!(mesh.bounds_max(), vector(1.0, 1.0, 0.0));
746    }
747
748    #[test]
749    fn mesh_rejects_invalid_and_degenerate_topology() {
750        assert_eq!(
751            Mesh3d::new(Vec::new(), vec![0, 1, 2]),
752            Err(Mesh3dError::EmptyVertices)
753        );
754        let vertices = vec![
755            vector(0.0, 0.0, 0.0),
756            vector(1.0, 0.0, 0.0),
757            vector(2.0, 0.0, 0.0),
758        ];
759        assert_eq!(
760            Mesh3d::new(vertices.clone(), vec![0, 1]),
761            Err(Mesh3dError::InvalidTriangleIndexCount { index_count: 2 })
762        );
763        assert_eq!(
764            Mesh3d::new(vertices.clone(), vec![0, 1, 3]),
765            Err(Mesh3dError::IndexOutOfBounds {
766                index: 3,
767                vertex_count: 3,
768            })
769        );
770        assert_eq!(
771            Mesh3d::new(vertices, vec![0, 1, 2]),
772            Err(Mesh3dError::DegenerateTriangle { triangle: 0 })
773        );
774    }
775
776    #[test]
777    fn mesh_rejects_duplicate_undirected_display_edges() {
778        let vertices = vec![
779            vector(0.0, 0.0, 0.0),
780            vector(1.0, 0.0, 0.0),
781            vector(0.0, 1.0, 0.0),
782        ];
783        assert_eq!(
784            Mesh3d::with_display_edges(
785                vertices,
786                vec![0, 1, 2],
787                vec![
788                    MeshEdge3d::new(0, 1).unwrap(),
789                    MeshEdge3d::new(1, 0).unwrap(),
790                ],
791            ),
792            Err(Mesh3dError::DuplicateDisplayEdge { start: 1, end: 0 })
793        );
794        assert_eq!(
795            MeshEdge3d::new(2, 2),
796            Err(Mesh3dError::DegenerateDisplayEdge { start: 2, end: 2 })
797        );
798    }
799
800    #[test]
801    fn mesh_rejects_geometrically_zero_length_display_edges() {
802        assert_eq!(
803            Mesh3d::with_display_edges(
804                vec![vector(1.0, 2.0, 3.0), vector(1.0, 2.0, 3.0)],
805                Vec::new(),
806                vec![MeshEdge3d::new(0, 1).unwrap()],
807            ),
808            Err(Mesh3dError::DegenerateDisplayEdge { start: 0, end: 1 })
809        );
810    }
811
812    #[test]
813    fn mesh_accepts_edge_only_construction_geometry() {
814        let mesh = Mesh3d::with_display_edges(
815            vec![vector(0.0, 0.0, 0.0), vector(1.0, 0.0, 0.0)],
816            Vec::new(),
817            vec![MeshEdge3d::new(0, 1).unwrap()],
818        )
819        .unwrap();
820        assert_eq!(mesh.triangle_count(), 0);
821        assert_eq!(mesh.display_edges().len(), 1);
822        assert_eq!(
823            Mesh3d::new(vec![vector(0.0, 0.0, 0.0)], Vec::new()),
824            Err(Mesh3dError::EmptyGeometry)
825        );
826    }
827
828    #[test]
829    fn wireframe_style_validates_logical_pixel_contract() {
830        let style = WireframeStyle3d::visible(Color::WHITE, logical(2.0))
831            .unwrap()
832            .with_hidden(
833                Color::rgba(0.5, 0.5, 0.5, 1.0),
834                logical(1.5),
835                logical(6.0),
836                logical(4.0),
837            )
838            .unwrap();
839        assert_eq!(style.visible_width(), logical(2.0));
840        assert_eq!(style.hidden_pattern(), Some((logical(6.0), logical(4.0))));
841        assert_eq!(
842            LogicalPixels::new(0.0),
843            Err(UnitError::InvalidLogicalPixels { value: 0.0 })
844        );
845        assert_eq!(
846            WireframeStyle3d::visible(Color::WHITE, logical(f32::MAX)),
847            Err(Mesh3dStyleError::InvalidColorOrWidth)
848        );
849        assert_eq!(
850            WireframeStyle3d::visible(Color::WHITE, logical(f32::MIN_POSITIVE / 2.0)),
851            Err(Mesh3dStyleError::InvalidColorOrWidth)
852        );
853        assert_eq!(
854            WireframeStyle3d::visible(Color::rgb(-0.01, 0.0, 0.0), logical(1.0)),
855            Err(Mesh3dStyleError::InvalidColorOrWidth)
856        );
857        assert_eq!(
858            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
859                .unwrap()
860                .with_hidden(Color::WHITE, logical(1.0), logical(f32::MAX), logical(2.0),),
861            Err(Mesh3dStyleError::InvalidDashPattern)
862        );
863        assert_eq!(
864            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
865                .unwrap()
866                .with_hidden(
867                    Color::WHITE,
868                    logical(1.0),
869                    logical(f32::MIN_POSITIVE / 2.0),
870                    logical(2.0),
871                ),
872            Err(Mesh3dStyleError::InvalidDashPattern)
873        );
874        assert_eq!(
875            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
876                .unwrap()
877                .with_hidden(
878                    Color::WHITE,
879                    logical(1.0),
880                    logical(f32::MAX),
881                    logical(f32::MAX),
882                ),
883            Err(Mesh3dStyleError::InvalidDashPattern)
884        );
885    }
886
887    #[test]
888    fn mesh_style_keeps_surface_and_wireframe_extensible() {
889        let surface = SurfaceStyle3d::opaque(Color::rgb(0.2, 0.3, 0.4)).unwrap();
890        let wireframe = WireframeStyle3d::visible(Color::WHITE, logical(2.0)).unwrap();
891        let style = MeshStyle3d::surface(surface).with_wireframe(wireframe);
892        assert_eq!(style.surface_style(), Some(surface));
893        assert_eq!(style.wireframe_style(), Some(wireframe));
894        assert_eq!(
895            SurfaceStyle3d::opaque(Color::rgba(1.0, 1.0, 1.0, 0.5)),
896            Err(Mesh3dStyleError::InvalidSurfaceColor)
897        );
898        assert_eq!(
899            SurfaceStyle3d::opaque(Color::rgb(1.01, 0.0, 0.0)),
900            Err(Mesh3dStyleError::InvalidSurfaceColor)
901        );
902        assert_eq!(MeshStyle3d::wireframe(wireframe).surface_style(), None);
903    }
904}