Skip to main content

sim_engine/mesh3d/
material.rs

1//! Explicit surface alpha and face-visibility policy, independent of wireframes.
2
3use super::{Color, Mesh3dStyleError, SurfaceLighting3d};
4
5/// Coverage/depth behavior for a retained surface.
6#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum SurfaceAlphaMode3d {
9    /// Ignores combined alpha, writes opaque coverage and depth.
10    #[default]
11    Opaque,
12    /// Discards alpha below the cutoff; surviving fragments write alpha one/depth.
13    Mask,
14    /// Straight-alpha blending after opaque/masked surfaces, without depth writes.
15    Blend,
16}
17
18/// Surface face visibility after camera projection; display edges are unaffected.
19#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum SurfaceSidedness3d {
22    /// Preserves both source windings and disables face culling.
23    #[default]
24    TwoSided,
25    /// Keeps projected counter-clockwise front faces and culls their back faces.
26    /// This is viewer-relative winding, not a proof of globally outward topology.
27    FrontOnly,
28}
29
30/// Validated surface tint, alpha policy and projected face visibility.
31///
32/// Blend objects are sorted back-to-front by transformed model-bounds-center
33/// camera-forward distance, with insertion-order ties. This does not solve
34/// intersecting/cyclic overlap or triangle ordering inside one mesh. Blend
35/// surfaces do not occlude mathematical hidden-line edges; edges render last.
36/// Positive-scale transforms preserve source orientation; reflections are not
37/// accepted by `Transform3d`. Lighting and fog are explicit opt-ins; no physically
38/// based glass, shadows or automatic normals are implied.
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub struct SurfaceStyle3d {
41    color: Color,
42    alpha_mode: SurfaceAlphaMode3d,
43    mask_cutoff: f32,
44    sidedness: SurfaceSidedness3d,
45    lighting: SurfaceLighting3d,
46    fog: bool,
47}
48
49impl SurfaceStyle3d {
50    /// Creates the legacy normalized opaque tint, rejecting alpha other than one.
51    /// Vertex/texture alpha is ignored by this surface mode, with depth writes.
52    pub fn opaque(color: Color) -> Result<Self, Mesh3dStyleError> {
53        if !color.is_normalized() || color.alpha() != 1.0 {
54            return Err(Mesh3dStyleError::InvalidSurfaceColor);
55        }
56        Ok(Self {
57            color,
58            alpha_mode: SurfaceAlphaMode3d::Opaque,
59            mask_cutoff: 0.0,
60            sidedness: SurfaceSidedness3d::TwoSided,
61            lighting: SurfaceLighting3d::Unlit,
62            fog: false,
63        })
64    }
65
66    /// Creates alpha-cutout coverage with a cutoff that is zero or a normal finite value in `0..=1`.
67    /// Combined surface/vertex/texture/material alpha below cutoff is discarded;
68    /// equality survives and writes alpha one/depth. Filtering happens before
69    /// the comparison; no alpha-to-coverage or automatic coverage preservation.
70    pub fn mask(color: Color, cutoff: f32) -> Result<Self, Mesh3dStyleError> {
71        if !color.is_normalized() {
72            return Err(Mesh3dStyleError::InvalidMaterialColor);
73        }
74        if !cutoff.is_finite()
75            || !(0.0..=1.0).contains(&cutoff)
76            || (cutoff != 0.0 && !cutoff.is_normal())
77        {
78            return Err(Mesh3dStyleError::InvalidMaskCutoff);
79        }
80        Ok(Self {
81            color,
82            alpha_mode: SurfaceAlphaMode3d::Mask,
83            mask_cutoff: cutoff,
84            sidedness: SurfaceSidedness3d::TwoSided,
85            lighting: SurfaceLighting3d::Unlit,
86            fog: false,
87        })
88    }
89
90    /// Creates normalized straight-linear RGBA blending with depth-test/no-write.
91    /// Combined alpha zero produces no color coverage and never writes depth.
92    pub fn blend(color: Color) -> Result<Self, Mesh3dStyleError> {
93        if !color.is_normalized() {
94            return Err(Mesh3dStyleError::InvalidMaterialColor);
95        }
96        Ok(Self {
97            color,
98            alpha_mode: SurfaceAlphaMode3d::Blend,
99            mask_cutoff: 0.0,
100            sidedness: SurfaceSidedness3d::TwoSided,
101            lighting: SurfaceLighting3d::Unlit,
102            fog: false,
103        })
104    }
105
106    /// Selects projected face culling without changing mathematical display edges.
107    pub const fn with_sidedness(mut self, sidedness: SurfaceSidedness3d) -> Self {
108        self.sidedness = sidedness;
109        self
110    }
111    /// Selects RGB illumination. Lambert requires application-supplied model normals.
112    /// Two-sided back-facing fragments reverse the interpolated shading normal.
113    pub const fn with_lighting(mut self, lighting: SurfaceLighting3d) -> Self {
114        self.lighting = lighting;
115        self
116    }
117    /// Returns illumination policy; Unlit is the default and bypasses normal math.
118    pub const fn lighting(self) -> SurfaceLighting3d {
119        self.lighting
120    }
121    /// Selects scene fog participation independently of lighting; disabled by default.
122    pub const fn with_fog(mut self, enabled: bool) -> Self {
123        self.fog = enabled;
124        self
125    }
126    /// Returns explicit participation in optional scene fog.
127    pub const fn fog_enabled(self) -> bool {
128        self.fog
129    }
130    /// Returns the normalized straight-linear multiplicative RGBA tint.
131    pub const fn color(self) -> Color {
132        self.color
133    }
134    /// Returns the surface coverage/depth mode.
135    pub const fn alpha_mode(self) -> SurfaceAlphaMode3d {
136        self.alpha_mode
137    }
138    /// Returns the alpha cutoff only for masked surfaces.
139    pub const fn mask_cutoff(self) -> Option<f32> {
140        match self.alpha_mode {
141            SurfaceAlphaMode3d::Mask => Some(self.mask_cutoff),
142            _ => None,
143        }
144    }
145    /// Returns viewer-relative face visibility; defaults to both sides.
146    pub const fn sidedness(self) -> SurfaceSidedness3d {
147        self.sidedness
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    #[test]
155    fn explicit_surface_alpha_preserves_opaque_validation_and_cutoff_endpoints() {
156        assert_eq!(
157            SurfaceStyle3d::opaque(Color::rgba(1.0, 0.0, 0.0, 0.5)),
158            Err(Mesh3dStyleError::InvalidSurfaceColor)
159        );
160        for alpha in [0.0, 0.5, 1.0] {
161            let color = Color::rgba(0.25, 0.5, 1.0, alpha);
162            assert_eq!(
163                SurfaceStyle3d::blend(color).unwrap().alpha_mode(),
164                SurfaceAlphaMode3d::Blend
165            );
166            for cutoff in [0.0, 0.5, 1.0] {
167                let surface = SurfaceStyle3d::mask(color, cutoff).unwrap();
168                assert_eq!(surface.mask_cutoff(), Some(cutoff));
169                assert_eq!(surface.sidedness(), SurfaceSidedness3d::TwoSided);
170                assert_eq!(
171                    surface
172                        .with_sidedness(SurfaceSidedness3d::FrontOnly)
173                        .color(),
174                    color
175                );
176            }
177        }
178        for cutoff in [f32::NAN, f32::INFINITY, f32::from_bits(1), -0.1, 1.1] {
179            assert_eq!(
180                SurfaceStyle3d::mask(Color::WHITE, cutoff),
181                Err(Mesh3dStyleError::InvalidMaskCutoff)
182            );
183        }
184        for color in [
185            Color::rgba(f32::NAN, 0.0, 0.0, 1.0),
186            Color::rgba(1.1, 0.0, 0.0, 0.5),
187        ] {
188            assert_eq!(
189                SurfaceStyle3d::blend(color),
190                Err(Mesh3dStyleError::InvalidMaterialColor)
191            );
192            assert_eq!(
193                SurfaceStyle3d::mask(color, 0.5),
194                Err(Mesh3dStyleError::InvalidMaterialColor)
195            );
196        }
197    }
198}