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}
276
277/// Immutable validated topology for retained stereometry rendering.
278///
279/// Vertices use caller-defined model-space world units. Triangle indices are a
280/// flat triangle list. Winding is preserved but deliberately not interpreted:
281/// the current surface pass disables face culling, and a global
282/// "counter-clockwise" rule is meaningless without a declared outward side.
283/// Optional display edges identify the mathematical edges that a later
284/// visible/hidden-line pass should draw; they are not inferred from triangle
285/// adjacency because triangulation diagonals are not necessarily meaningful
286/// construction edges. A mesh may contain surfaces, display edges, or both.
287#[derive(Debug, Clone, PartialEq)]
288pub struct Mesh3d {
289    storage: Arc<Mesh3dStorage>,
290    bounds_min: Vec3,
291    bounds_max: Vec3,
292}
293
294impl Mesh3d {
295    /// Builds a surface mesh without explicit display edges.
296    pub fn new(vertices: Vec<Vec3>, triangle_indices: Vec<u32>) -> Result<Self, Mesh3dError> {
297        Self::with_display_edges(vertices, triangle_indices, Vec::new())
298    }
299
300    /// Builds a mesh with explicit mathematical display edges.
301    ///
302    /// Construction rejects an empty vertex set, geometry with neither
303    /// triangles nor display edges, incomplete triangle lists, out-of-range
304    /// indices, repeated/collinear triangle vertices, duplicate display edges,
305    /// display edges with coincident endpoints, and display edges outside the
306    /// vertex array.
307    pub fn with_display_edges(
308        vertices: Vec<Vec3>,
309        triangle_indices: Vec<u32>,
310        display_edges: Vec<MeshEdge3d>,
311    ) -> Result<Self, Mesh3dError> {
312        if vertices.is_empty() {
313            return Err(Mesh3dError::EmptyVertices);
314        }
315        if triangle_indices.is_empty() && display_edges.is_empty() {
316            return Err(Mesh3dError::EmptyGeometry);
317        }
318        if !triangle_indices.len().is_multiple_of(3) {
319            return Err(Mesh3dError::InvalidTriangleIndexCount {
320                index_count: triangle_indices.len(),
321            });
322        }
323
324        for (triangle, indices) in triangle_indices.chunks_exact(3).enumerate() {
325            let [first, second, third] = [indices[0], indices[1], indices[2]];
326            validate_index(first, vertices.len())?;
327            validate_index(second, vertices.len())?;
328            validate_index(third, vertices.len())?;
329            if first == second
330                || second == third
331                || first == third
332                || triangle_is_degenerate(
333                    vertices[first as usize],
334                    vertices[second as usize],
335                    vertices[third as usize],
336                )
337            {
338                return Err(Mesh3dError::DegenerateTriangle { triangle });
339            }
340        }
341
342        for edge in &display_edges {
343            validate_index(edge.start, vertices.len())?;
344            validate_index(edge.end, vertices.len())?;
345            if vertices[edge.start as usize] == vertices[edge.end as usize] {
346                return Err(Mesh3dError::DegenerateDisplayEdge {
347                    start: edge.start,
348                    end: edge.end,
349                });
350            }
351        }
352
353        let canonical_bytes = display_edges
354            .len()
355            .checked_mul(std::mem::size_of::<((u32, u32), usize)>())
356            .ok_or(Mesh3dError::AllocationFailed {
357                requested_bytes: usize::MAX,
358            })?;
359        let mut canonical_edges = Vec::new();
360        canonical_edges
361            .try_reserve_exact(display_edges.len())
362            .map_err(|_| Mesh3dError::AllocationFailed {
363                requested_bytes: canonical_bytes,
364            })?;
365        for (index, edge) in display_edges.iter().enumerate() {
366            canonical_edges.push((edge.canonical(), index));
367        }
368        canonical_edges.sort_unstable_by_key(|entry| entry.0);
369        if let Some(pair) = canonical_edges
370            .windows(2)
371            .find(|pair| pair[0].0 == pair[1].0)
372        {
373            let duplicate = display_edges[pair[0].1.max(pair[1].1)];
374            return Err(Mesh3dError::DuplicateDisplayEdge {
375                start: duplicate.start,
376                end: duplicate.end,
377            });
378        }
379
380        let (bounds_min, bounds_max) = mesh_bounds(&vertices);
381        Ok(Self {
382            // One fixed-size Arc control block makes Mesh3d cloning O(1)
383            // without copying any caller-scale topology buffers.
384            storage: Arc::new(Mesh3dStorage {
385                vertices,
386                triangle_indices,
387                display_edges,
388            }),
389            bounds_min,
390            bounds_max,
391        })
392    }
393
394    /// Returns immutable model-space vertices.
395    pub fn vertices(&self) -> &[Vec3] {
396        &self.storage.vertices
397    }
398
399    /// Returns the flat host-wound triangle index list.
400    pub fn triangle_indices(&self) -> &[u32] {
401        &self.storage.triangle_indices
402    }
403
404    /// Returns explicit mathematical edges, excluding triangulation diagonals.
405    pub fn display_edges(&self) -> &[MeshEdge3d] {
406        &self.storage.display_edges
407    }
408
409    /// Returns the number of retained triangles.
410    pub fn triangle_count(&self) -> usize {
411        self.storage.triangle_indices.len() / 3
412    }
413
414    /// Returns the inclusive model-space lower bound.
415    pub const fn bounds_min(&self) -> Vec3 {
416        self.bounds_min
417    }
418
419    /// Returns the inclusive model-space upper bound.
420    pub const fn bounds_max(&self) -> Vec3 {
421        self.bounds_max
422    }
423
424    /// Returns retained CPU bytes used by vertices, indices, and display edges.
425    pub fn recovery_memory_bytes(&self) -> usize {
426        self.storage
427            .vertices
428            .capacity()
429            .saturating_mul(std::mem::size_of::<Vec3>())
430            .saturating_add(
431                self.storage
432                    .triangle_indices
433                    .capacity()
434                    .saturating_mul(std::mem::size_of::<u32>()),
435            )
436            .saturating_add(
437                self.storage
438                    .display_edges
439                    .capacity()
440                    .saturating_mul(std::mem::size_of::<MeshEdge3d>()),
441            )
442    }
443}
444
445/// Rejection reason for retained 3D topology.
446#[derive(Debug, Clone, Copy, PartialEq, Eq)]
447pub enum Mesh3dError {
448    /// A retained mesh requires at least one model-space vertex.
449    EmptyVertices,
450    /// A retained mesh requires at least one triangle or display edge.
451    EmptyGeometry,
452    /// The triangle index list was not divisible by three.
453    InvalidTriangleIndexCount {
454        /// Rejected number of indices.
455        index_count: usize,
456    },
457    /// A triangle or display edge referenced a missing vertex.
458    IndexOutOfBounds {
459        /// Rejected vertex index.
460        index: u32,
461        /// Number of vertices available in the mesh.
462        vertex_count: usize,
463    },
464    /// A triangle repeated a vertex or had zero model-space area.
465    DegenerateTriangle {
466        /// Zero-based triangle number in the index list.
467        triangle: usize,
468    },
469    /// A display edge used one index twice or referenced coincident vertices.
470    DegenerateDisplayEdge {
471        /// First endpoint in the rejected declaration.
472        start: u32,
473        /// Second endpoint in the rejected declaration.
474        end: u32,
475    },
476    /// The same undirected display edge appeared more than once.
477    DuplicateDisplayEdge {
478        /// First endpoint in the rejected declaration.
479        start: u32,
480        /// Second endpoint in the rejected declaration.
481        end: u32,
482    },
483    /// Temporary validation storage could not be reserved.
484    AllocationFailed {
485        /// Bytes requested for duplicate-edge validation.
486        requested_bytes: usize,
487    },
488}
489
490impl fmt::Display for Mesh3dError {
491    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
492        match self {
493            Self::EmptyVertices => write!(formatter, "3D mesh requires at least one vertex"),
494            Self::EmptyGeometry => {
495                write!(formatter, "3D mesh requires triangles or display edges")
496            }
497            Self::InvalidTriangleIndexCount { index_count } => write!(
498                formatter,
499                "3D mesh triangle index count, when present, must be divisible by three, got {index_count}"
500            ),
501            Self::IndexOutOfBounds {
502                index,
503                vertex_count,
504            } => write!(
505                formatter,
506                "3D mesh index {index} is outside {vertex_count} vertices"
507            ),
508            Self::DegenerateTriangle { triangle } => {
509                write!(formatter, "3D mesh triangle {triangle} has zero area")
510            }
511            Self::DegenerateDisplayEdge { start, end } => {
512                write!(formatter, "3D display edge {start}-{end} has zero length")
513            }
514            Self::DuplicateDisplayEdge { start, end } => {
515                write!(formatter, "3D display edge {start}-{end} is duplicated")
516            }
517            Self::AllocationFailed { requested_bytes } => write!(
518                formatter,
519                "could not reserve {requested_bytes} bytes for 3D mesh validation"
520            ),
521        }
522    }
523}
524
525impl Error for Mesh3dError {}
526
527fn validate_index(index: u32, vertex_count: usize) -> Result<(), Mesh3dError> {
528    ((index as u64) < vertex_count as u64)
529        .then_some(())
530        .ok_or(Mesh3dError::IndexOutOfBounds {
531            index,
532            vertex_count,
533        })
534}
535
536fn triangle_is_degenerate(first: Vec3, second: Vec3, third: Vec3) -> bool {
537    let ab = (
538        second.x() as f64 - first.x() as f64,
539        second.y() as f64 - first.y() as f64,
540        second.z() as f64 - first.z() as f64,
541    );
542    let ac = (
543        third.x() as f64 - first.x() as f64,
544        third.y() as f64 - first.y() as f64,
545        third.z() as f64 - first.z() as f64,
546    );
547    let cross = (
548        ab.1 * ac.2 - ab.2 * ac.1,
549        ab.2 * ac.0 - ab.0 * ac.2,
550        ab.0 * ac.1 - ab.1 * ac.0,
551    );
552    cross.0 == 0.0 && cross.1 == 0.0 && cross.2 == 0.0
553}
554
555fn mesh_bounds(vertices: &[Vec3]) -> (Vec3, Vec3) {
556    let first = vertices[0];
557    let mut minimum = [first.x(), first.y(), first.z()];
558    let mut maximum = minimum;
559    for vertex in &vertices[1..] {
560        let components = [vertex.x(), vertex.y(), vertex.z()];
561        for axis in 0..3 {
562            minimum[axis] = minimum[axis].min(components[axis]);
563            maximum[axis] = maximum[axis].max(components[axis]);
564        }
565    }
566    (
567        Vec3::new_unchecked(minimum[0], minimum[1], minimum[2]),
568        Vec3::new_unchecked(maximum[0], maximum[1], maximum[2]),
569    )
570}
571
572#[cfg(test)]
573mod tests {
574    use super::{
575        Mesh3d, Mesh3dError, Mesh3dStyleError, MeshEdge3d, MeshStyle3d, SurfaceStyle3d,
576        WireframeStyle3d,
577    };
578    use crate::{Color, LogicalPixels, UnitError, Vec3};
579
580    fn vector(x: f32, y: f32, z: f32) -> Vec3 {
581        Vec3::new(x, y, z).unwrap()
582    }
583
584    fn logical(value: f32) -> LogicalPixels {
585        LogicalPixels::new(value).unwrap()
586    }
587
588    #[test]
589    fn mesh_validates_topology_and_preserves_explicit_edges() {
590        let mesh = Mesh3d::with_display_edges(
591            vec![
592                vector(-1.0, -1.0, 0.0),
593                vector(1.0, -1.0, 0.0),
594                vector(0.0, 1.0, 0.0),
595            ],
596            vec![0, 1, 2],
597            vec![
598                MeshEdge3d::new(0, 1).unwrap(),
599                MeshEdge3d::new(1, 2).unwrap(),
600            ],
601        )
602        .unwrap();
603        assert_eq!(mesh.triangle_count(), 1);
604        assert_eq!(mesh.display_edges().len(), 2);
605        assert_eq!(mesh.bounds_min(), vector(-1.0, -1.0, 0.0));
606        assert_eq!(mesh.bounds_max(), vector(1.0, 1.0, 0.0));
607    }
608
609    #[test]
610    fn mesh_rejects_invalid_and_degenerate_topology() {
611        assert_eq!(
612            Mesh3d::new(Vec::new(), vec![0, 1, 2]),
613            Err(Mesh3dError::EmptyVertices)
614        );
615        let vertices = vec![
616            vector(0.0, 0.0, 0.0),
617            vector(1.0, 0.0, 0.0),
618            vector(2.0, 0.0, 0.0),
619        ];
620        assert_eq!(
621            Mesh3d::new(vertices.clone(), vec![0, 1]),
622            Err(Mesh3dError::InvalidTriangleIndexCount { index_count: 2 })
623        );
624        assert_eq!(
625            Mesh3d::new(vertices.clone(), vec![0, 1, 3]),
626            Err(Mesh3dError::IndexOutOfBounds {
627                index: 3,
628                vertex_count: 3,
629            })
630        );
631        assert_eq!(
632            Mesh3d::new(vertices, vec![0, 1, 2]),
633            Err(Mesh3dError::DegenerateTriangle { triangle: 0 })
634        );
635    }
636
637    #[test]
638    fn mesh_rejects_duplicate_undirected_display_edges() {
639        let vertices = vec![
640            vector(0.0, 0.0, 0.0),
641            vector(1.0, 0.0, 0.0),
642            vector(0.0, 1.0, 0.0),
643        ];
644        assert_eq!(
645            Mesh3d::with_display_edges(
646                vertices,
647                vec![0, 1, 2],
648                vec![
649                    MeshEdge3d::new(0, 1).unwrap(),
650                    MeshEdge3d::new(1, 0).unwrap(),
651                ],
652            ),
653            Err(Mesh3dError::DuplicateDisplayEdge { start: 1, end: 0 })
654        );
655        assert_eq!(
656            MeshEdge3d::new(2, 2),
657            Err(Mesh3dError::DegenerateDisplayEdge { start: 2, end: 2 })
658        );
659    }
660
661    #[test]
662    fn mesh_rejects_geometrically_zero_length_display_edges() {
663        assert_eq!(
664            Mesh3d::with_display_edges(
665                vec![vector(1.0, 2.0, 3.0), vector(1.0, 2.0, 3.0)],
666                Vec::new(),
667                vec![MeshEdge3d::new(0, 1).unwrap()],
668            ),
669            Err(Mesh3dError::DegenerateDisplayEdge { start: 0, end: 1 })
670        );
671    }
672
673    #[test]
674    fn mesh_accepts_edge_only_construction_geometry() {
675        let mesh = Mesh3d::with_display_edges(
676            vec![vector(0.0, 0.0, 0.0), vector(1.0, 0.0, 0.0)],
677            Vec::new(),
678            vec![MeshEdge3d::new(0, 1).unwrap()],
679        )
680        .unwrap();
681        assert_eq!(mesh.triangle_count(), 0);
682        assert_eq!(mesh.display_edges().len(), 1);
683        assert_eq!(
684            Mesh3d::new(vec![vector(0.0, 0.0, 0.0)], Vec::new()),
685            Err(Mesh3dError::EmptyGeometry)
686        );
687    }
688
689    #[test]
690    fn wireframe_style_validates_logical_pixel_contract() {
691        let style = WireframeStyle3d::visible(Color::WHITE, logical(2.0))
692            .unwrap()
693            .with_hidden(
694                Color::rgba(0.5, 0.5, 0.5, 1.0),
695                logical(1.5),
696                logical(6.0),
697                logical(4.0),
698            )
699            .unwrap();
700        assert_eq!(style.visible_width(), logical(2.0));
701        assert_eq!(style.hidden_pattern(), Some((logical(6.0), logical(4.0))));
702        assert_eq!(
703            LogicalPixels::new(0.0),
704            Err(UnitError::InvalidLogicalPixels { value: 0.0 })
705        );
706        assert_eq!(
707            WireframeStyle3d::visible(Color::WHITE, logical(f32::MAX)),
708            Err(Mesh3dStyleError::InvalidColorOrWidth)
709        );
710        assert_eq!(
711            WireframeStyle3d::visible(Color::WHITE, logical(f32::MIN_POSITIVE / 2.0)),
712            Err(Mesh3dStyleError::InvalidColorOrWidth)
713        );
714        assert_eq!(
715            WireframeStyle3d::visible(Color::rgb(-0.01, 0.0, 0.0), logical(1.0)),
716            Err(Mesh3dStyleError::InvalidColorOrWidth)
717        );
718        assert_eq!(
719            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
720                .unwrap()
721                .with_hidden(Color::WHITE, logical(1.0), logical(f32::MAX), logical(2.0),),
722            Err(Mesh3dStyleError::InvalidDashPattern)
723        );
724        assert_eq!(
725            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
726                .unwrap()
727                .with_hidden(
728                    Color::WHITE,
729                    logical(1.0),
730                    logical(f32::MIN_POSITIVE / 2.0),
731                    logical(2.0),
732                ),
733            Err(Mesh3dStyleError::InvalidDashPattern)
734        );
735        assert_eq!(
736            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
737                .unwrap()
738                .with_hidden(
739                    Color::WHITE,
740                    logical(1.0),
741                    logical(f32::MAX),
742                    logical(f32::MAX),
743                ),
744            Err(Mesh3dStyleError::InvalidDashPattern)
745        );
746    }
747
748    #[test]
749    fn mesh_style_keeps_surface_and_wireframe_extensible() {
750        let surface = SurfaceStyle3d::opaque(Color::rgb(0.2, 0.3, 0.4)).unwrap();
751        let wireframe = WireframeStyle3d::visible(Color::WHITE, logical(2.0)).unwrap();
752        let style = MeshStyle3d::surface(surface).with_wireframe(wireframe);
753        assert_eq!(style.surface_style(), Some(surface));
754        assert_eq!(style.wireframe_style(), Some(wireframe));
755        assert_eq!(
756            SurfaceStyle3d::opaque(Color::rgba(1.0, 1.0, 1.0, 0.5)),
757            Err(Mesh3dStyleError::InvalidSurfaceColor)
758        );
759        assert_eq!(
760            SurfaceStyle3d::opaque(Color::rgb(1.01, 0.0, 0.0)),
761            Err(Mesh3dStyleError::InvalidSurfaceColor)
762        );
763        assert_eq!(MeshStyle3d::wireframe(wireframe).surface_style(), None);
764    }
765}