Skip to main content

sim_engine/mesh3d/
style.rs

1//! Logical-screen wireframe presentation and extensible mesh style.
2
3use std::{error::Error, fmt};
4
5use super::SurfaceStyle3d;
6use crate::{Color, LogicalPixels};
7
8const MAX_LOGICAL_EDGE_METRIC: f32 = 1_048_576.0;
9
10/// Extensible visual material bundle for a retained 3D object.
11///
12/// Surface and wireframe presentation are independent. Edge-only construction
13/// geometry uses `surface = None`; future section materials can extend
14/// [`SurfaceStyle3d`] without changing scene insertion or object addressing.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct MeshStyle3d {
17    surface: Option<SurfaceStyle3d>,
18    wireframe: Option<WireframeStyle3d>,
19}
20
21impl MeshStyle3d {
22    /// Creates an object with the selected surface material and no display edges.
23    pub const fn surface(surface: SurfaceStyle3d) -> Self {
24        Self {
25            surface: Some(surface),
26            wireframe: None,
27        }
28    }
29
30    /// Creates display edges without a surface/depth-writing face pass.
31    pub const fn wireframe(wireframe: WireframeStyle3d) -> Self {
32        Self {
33            surface: None,
34            wireframe: Some(wireframe),
35        }
36    }
37
38    /// Adds or replaces display-edge presentation.
39    pub const fn with_wireframe(mut self, wireframe: WireframeStyle3d) -> Self {
40        self.wireframe = Some(wireframe);
41        self
42    }
43
44    /// Returns the optional surface material.
45    pub const fn surface_style(self) -> Option<SurfaceStyle3d> {
46        self.surface
47    }
48
49    /// Returns the optional edge presentation.
50    pub const fn wireframe_style(self) -> Option<WireframeStyle3d> {
51        self.wireframe
52    }
53}
54
55/// Logical-screen presentation for explicit mathematical mesh edges.
56///
57/// Visible fragments are solid. Fragments occluded beyond the depth buffer's
58/// conservative coplanar tolerance may be drawn with a logical-pixel dash/gap
59/// pattern. Classification uses one implementation depth unit away from the
60/// camera for hidden fragments and one unit toward it for visible fragments,
61/// with visible fragments rendered last. Therefore coplanar and
62/// sub-depth-resolution separations intentionally resolve as visible; this is
63/// raster visibility, not exact analytic solid geometry.
64#[derive(Debug, Clone, Copy, PartialEq)]
65pub struct WireframeStyle3d {
66    visible_color: Color,
67    visible_width: LogicalPixels,
68    hidden: Option<HiddenEdgeStyle3d>,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq)]
72struct HiddenEdgeStyle3d {
73    color: Color,
74    width: LogicalPixels,
75    dash_length: LogicalPixels,
76    gap_length: LogicalPixels,
77}
78
79impl WireframeStyle3d {
80    /// Largest accepted width, dash, or gap in logical pixels.
81    ///
82    /// The bound keeps every style-derived shader operation inside the
83    /// cross-backend arithmetic envelope.
84    pub const MAX_LOGICAL_PIXELS: f32 = MAX_LOGICAL_EDGE_METRIC;
85
86    /// Creates solid visible edges with hidden fragments disabled.
87    pub fn visible(color: Color, width: LogicalPixels) -> Result<Self, Mesh3dStyleError> {
88        validate_edge_color_width(color, width)?;
89        Ok(Self {
90            visible_color: color,
91            visible_width: width,
92            hidden: None,
93        })
94    }
95
96    /// Enables dashed depth-occluded fragments in logical screen pixels.
97    ///
98    /// Occlusion must exceed the conservative two-unit coplanar tolerance
99    /// documented on [`WireframeStyle3d`] before a fragment resolves hidden.
100    pub fn with_hidden(
101        mut self,
102        color: Color,
103        width: LogicalPixels,
104        dash_length: LogicalPixels,
105        gap_length: LogicalPixels,
106    ) -> Result<Self, Mesh3dStyleError> {
107        validate_edge_color_width(color, width)?;
108        if !is_stable_edge_metric(dash_length.get())
109            || !is_stable_edge_metric(gap_length.get())
110            || !(dash_length.get() + gap_length.get()).is_finite()
111        {
112            return Err(Mesh3dStyleError::InvalidDashPattern);
113        }
114        self.hidden = Some(HiddenEdgeStyle3d {
115            color,
116            width,
117            dash_length,
118            gap_length,
119        });
120        Ok(self)
121    }
122
123    /// Returns the solid visible-edge color in linear RGBA.
124    pub const fn visible_color(self) -> Color {
125        self.visible_color
126    }
127
128    /// Returns visible-edge width in logical screen pixels.
129    pub const fn visible_width(self) -> LogicalPixels {
130        self.visible_width
131    }
132
133    /// Returns whether depth-occluded edge fragments should be drawn.
134    pub const fn hidden_enabled(self) -> bool {
135        self.hidden.is_some()
136    }
137
138    /// Returns hidden-edge color when enabled.
139    pub const fn hidden_color(self) -> Option<Color> {
140        match self.hidden {
141            Some(hidden) => Some(hidden.color),
142            None => None,
143        }
144    }
145
146    /// Returns hidden-edge width in logical screen pixels when enabled.
147    pub const fn hidden_width(self) -> Option<LogicalPixels> {
148        match self.hidden {
149            Some(hidden) => Some(hidden.width),
150            None => None,
151        }
152    }
153
154    /// Returns hidden dash and gap lengths in logical screen pixels.
155    pub const fn hidden_pattern(self) -> Option<(LogicalPixels, LogicalPixels)> {
156        match self.hidden {
157            Some(hidden) => Some((hidden.dash_length, hidden.gap_length)),
158            None => None,
159        }
160    }
161}
162
163/// Rejection reason for logical-screen 3D edge presentation.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum Mesh3dStyleError {
166    /// A mask/blend tint must have finite straight-linear RGBA in 0..=1.
167    InvalidMaterialColor,
168    /// The alpha-mask cutoff must be zero or normal and finite in 0..=1.
169    InvalidMaskCutoff,
170    /// The legacy opaque constructor requires normalized color with alpha one.
171    InvalidSurfaceColor,
172    /// Edge color must be normalized and opaque, and width must be a normal
173    /// positive value no greater than [`WireframeStyle3d::MAX_LOGICAL_PIXELS`].
174    InvalidColorOrWidth,
175    /// Hidden dash and gap must be normal positive values, each no greater than
176    /// [`WireframeStyle3d::MAX_LOGICAL_PIXELS`], with a finite sum.
177    InvalidDashPattern,
178}
179
180impl fmt::Display for Mesh3dStyleError {
181    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
182        match self {
183            Self::InvalidMaterialColor => write!(
184                formatter,
185                "3D material color must be normalized straight-linear RGBA"
186            ),
187            Self::InvalidMaskCutoff => write!(
188                formatter,
189                "3D mask cutoff must be zero or normal and finite in 0..=1"
190            ),
191            Self::InvalidSurfaceColor => write!(formatter, "3D surface color must be opaque"),
192            Self::InvalidColorOrWidth => {
193                write!(
194                    formatter,
195                    "3D edge color must be opaque and width must be normal and in 0..={MAX_LOGICAL_EDGE_METRIC} logical pixels"
196                )
197            }
198            Self::InvalidDashPattern => {
199                write!(
200                    formatter,
201                    "3D hidden-edge dash and gap must each be normal and in 0..={MAX_LOGICAL_EDGE_METRIC} logical pixels with a finite sum"
202                )
203            }
204        }
205    }
206}
207
208impl Error for Mesh3dStyleError {}
209
210fn validate_edge_color_width(color: Color, width: LogicalPixels) -> Result<(), Mesh3dStyleError> {
211    if color.is_normalized() && color.alpha() == 1.0 && is_stable_edge_metric(width.get()) {
212        Ok(())
213    } else {
214        Err(Mesh3dStyleError::InvalidColorOrWidth)
215    }
216}
217
218fn is_stable_edge_metric(value: f32) -> bool {
219    value.is_normal() && value <= MAX_LOGICAL_EDGE_METRIC
220}