Skip to main content

sim_engine/
mesh3d_environment.rs

1//! Bounded, application-supplied lighting and distance fog.
2
3use crate::{Color, Vec3};
4use std::{error::Error, fmt};
5
6/// Surface RGB illumination; alpha and mathematical display edges are unaffected.
7#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
8#[non_exhaustive]
9pub enum SurfaceLighting3d {
10    /// Preserves the surface/vertex/texture color product without reading normals.
11    #[default]
12    Unlit,
13    /// Ambient plus one directional Lambert term, saturated to normalized LDR RGB.
14    Lambert,
15}
16
17/// Normalized opaque RGB and bounded ambient intensity.
18#[derive(Debug, Clone, Copy, PartialEq)]
19pub struct AmbientLight3d {
20    color: Color,
21    intensity: f32,
22}
23
24impl AmbientLight3d {
25    /// Accepts normalized opaque linear RGB and a finite intensity in `0..=1`.
26    pub fn new(color: Color, intensity: f32) -> Result<Self, Lighting3dError> {
27        validate_light(color, intensity)?;
28        Ok(Self { color, intensity })
29    }
30    /// Returns normalized opaque linear RGB.
31    pub const fn color(self) -> Color {
32        self.color
33    }
34    /// Returns the bounded linear intensity.
35    pub const fn intensity(self) -> f32 {
36        self.intensity
37    }
38}
39
40/// One directional source whose direction points from a surface toward the light.
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub struct DirectionalLight3d {
43    direction: Vec3,
44    color: Color,
45    intensity: f32,
46}
47
48impl DirectionalLight3d {
49    /// Normalizes a nonzero finite direction robustly, without generating normals.
50    /// Color is normalized opaque linear RGB; intensity must be finite in `0..=1`.
51    pub fn new(
52        direction_toward_light: Vec3,
53        color: Color,
54        intensity: f32,
55    ) -> Result<Self, Lighting3dError> {
56        validate_light(color, intensity)?;
57        let direction = direction_toward_light
58            .normalized()
59            .map_err(|_| Lighting3dError::InvalidDirection)?;
60        Ok(Self {
61            direction,
62            color,
63            intensity,
64        })
65    }
66    /// Returns the normalized world-space direction toward the light.
67    pub const fn direction(self) -> Vec3 {
68        self.direction
69    }
70    /// Returns normalized opaque linear RGB.
71    pub const fn color(self) -> Color {
72        self.color
73    }
74    /// Returns bounded linear intensity; zero disables directional evaluation.
75    pub const fn intensity(self) -> f32 {
76        self.intensity
77    }
78}
79
80/// Ready visual lighting state: ambient and at most one directional source.
81#[derive(Debug, Clone, Copy, PartialEq)]
82pub struct Lighting3d {
83    ambient: AmbientLight3d,
84    directional: Option<DirectionalLight3d>,
85}
86
87impl Default for Lighting3d {
88    fn default() -> Self {
89        Self::new(AmbientLight3d {
90            color: Color::WHITE,
91            intensity: 1.0,
92        })
93    }
94}
95
96impl Lighting3d {
97    /// Starts with ambient illumination and no directional source.
98    pub const fn new(ambient: AmbientLight3d) -> Self {
99        Self {
100            ambient,
101            directional: None,
102        }
103    }
104    /// Replaces or disables the single directional source.
105    pub const fn with_directional(mut self, light: Option<DirectionalLight3d>) -> Self {
106        self.directional = light;
107        self
108    }
109    /// Returns ambient illumination.
110    pub const fn ambient(self) -> AmbientLight3d {
111        self.ambient
112    }
113    /// Returns the optional directional source.
114    pub const fn directional(self) -> Option<DirectionalLight3d> {
115        self.directional
116    }
117}
118
119/// Invalid source lighting state, rejected before any scene mutation.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121#[non_exhaustive]
122pub enum Lighting3dError {
123    /// Light color must be normalized opaque linear RGB.
124    InvalidColor,
125    /// Intensity must be finite in `0..=1`.
126    InvalidIntensity,
127    /// Direction must be finite and nonzero.
128    InvalidDirection,
129}
130
131impl fmt::Display for Lighting3dError {
132    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
133        formatter.write_str(match self {
134            Self::InvalidColor => "3D light color must be normalized opaque linear RGB",
135            Self::InvalidIntensity => "3D light intensity must be finite in 0..=1",
136            Self::InvalidDirection => "3D light direction must be finite and nonzero",
137        })
138    }
139}
140impl Error for Lighting3dError {}
141
142fn validate_light(color: Color, intensity: f32) -> Result<(), Lighting3dError> {
143    if !color.is_normalized() || color.alpha() != 1.0 {
144        return Err(Lighting3dError::InvalidColor);
145    }
146    if !intensity.is_finite() || !(0.0..=1.0).contains(&intensity) {
147        return Err(Lighting3dError::InvalidIntensity);
148    }
149    Ok(())
150}
151
152/// Exponential RGB fog using camera-forward world distance, never a culling rule.
153///
154/// Participating surfaces use `1 - exp(-density * max(view_depth - start, 0))`.
155/// Depth is distance along camera forward, not radial distance or projection Z;
156/// perspective and orthographic cameras share this contract. Alpha, depth writes,
157/// mathematical edges and scene clear color are unchanged. Every surface opts in
158/// with `SurfaceStyle3d::with_fog(true)`, independently of illumination mode.
159#[derive(Debug, Clone, Copy, PartialEq)]
160pub struct Fog3d {
161    color: Color,
162    start: f32,
163    density: f32,
164}
165
166impl Fog3d {
167    /// Accepts normalized opaque fog RGB, start in world-distance units and density
168    /// in inverse world-distance units. Scalars must be zero or normal positive
169    /// finite values; zero density disables fog without evaluating its arithmetic.
170    pub fn new(color: Color, start_world_distance: f32, density: f32) -> Result<Self, Fog3dError> {
171        if !color.is_normalized() || color.alpha() != 1.0 {
172            return Err(Fog3dError::InvalidColor);
173        }
174        if !nonnegative_normal(start_world_distance) {
175            return Err(Fog3dError::InvalidStart);
176        }
177        if !nonnegative_normal(density) {
178            return Err(Fog3dError::InvalidDensity);
179        }
180        Ok(Self {
181            color,
182            start: start_world_distance,
183            density,
184        })
185    }
186    /// Returns normalized opaque linear fog RGB.
187    pub const fn color(self) -> Color {
188        self.color
189    }
190    /// Returns the nonnegative camera-forward distance where fog begins.
191    pub const fn start(self) -> f32 {
192        self.start
193    }
194    /// Returns inverse world-distance density; zero disables fog.
195    pub const fn density(self) -> f32 {
196        self.density
197    }
198}
199
200fn nonnegative_normal(value: f32) -> bool {
201    value == 0.0 || (value.is_normal() && value > 0.0)
202}
203
204/// Invalid source fog state, rejected before scene mutation.
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206#[non_exhaustive]
207pub enum Fog3dError {
208    /// Fog color must be normalized opaque linear RGB.
209    InvalidColor,
210    /// Start must be zero or positive normal finite world distance.
211    InvalidStart,
212    /// Density must be zero or positive normal finite inverse world distance.
213    InvalidDensity,
214}
215impl fmt::Display for Fog3dError {
216    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
217        formatter.write_str(match self {
218            Self::InvalidColor => "3D fog color must be normalized opaque linear RGB",
219            Self::InvalidStart => {
220                "3D fog start must be zero or positive normal finite world distance"
221            }
222            Self::InvalidDensity => {
223                "3D fog density must be zero or positive normal finite inverse world distance"
224            }
225        })
226    }
227}
228impl Error for Fog3dError {}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn environment_rejects_invalid_values_and_normalizes_large_directions() {
236        for value in [f32::NAN, f32::INFINITY, -1.0, 1.1] {
237            assert_eq!(
238                AmbientLight3d::new(Color::WHITE, value),
239                Err(Lighting3dError::InvalidIntensity)
240            );
241        }
242        assert_eq!(
243            DirectionalLight3d::new(Vec3::ZERO, Color::WHITE, 0.0),
244            Err(Lighting3dError::InvalidDirection)
245        );
246        let large = DirectionalLight3d::new(
247            Vec3::new(f32::MAX, f32::MAX, 0.0).unwrap(),
248            Color::WHITE,
249            1.0,
250        )
251        .unwrap();
252        assert!((large.direction().x() - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-6);
253        for value in [f32::NAN, f32::INFINITY, -1.0, f32::from_bits(1)] {
254            assert_eq!(
255                Fog3d::new(Color::WHITE, value, 1.0),
256                Err(Fog3dError::InvalidStart)
257            );
258            assert_eq!(
259                Fog3d::new(Color::WHITE, 0.0, value),
260                Err(Fog3dError::InvalidDensity)
261            );
262        }
263        assert!(Fog3d::new(Color::WHITE, f32::MAX, f32::MAX).is_ok());
264        assert!(Fog3d::new(Color::WHITE, 0.0, 0.0).is_ok());
265    }
266}