Skip to main content

sim_engine/
units.rs

1use std::{error::Error, fmt};
2
3/// Positive finite scalar measured in logical screen pixels.
4///
5/// Construction is explicit so physical pixels, world lengths, and DPI ratios
6/// cannot enter logical-width APIs through an unlabelled `f32`.
7#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
8pub struct LogicalPixels(f32);
9
10impl LogicalPixels {
11    /// Labels a positive finite scalar as logical screen pixels.
12    pub fn new(value: f32) -> Result<Self, UnitError> {
13        positive_finite(value)
14            .then_some(Self(value))
15            .ok_or(UnitError::InvalidLogicalPixels { value })
16    }
17
18    /// Returns the scalar value in logical screen pixels.
19    pub const fn get(self) -> f32 {
20        self.0
21    }
22}
23
24/// Positive finite distance measured in caller-defined 3D world units.
25///
26/// This type labels scalar distances such as camera near/far ranges. Positions
27/// and directions remain [`crate::Vec3`] because their three components have
28/// vector rather than scalar semantics.
29#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
30pub struct WorldLength(f32);
31
32impl WorldLength {
33    /// Labels a positive finite scalar as a 3D world-space distance.
34    pub fn new(value: f32) -> Result<Self, UnitError> {
35        positive_finite(value)
36            .then_some(Self(value))
37            .ok_or(UnitError::InvalidWorldLength { value })
38    }
39
40    /// Returns the scalar value in caller-defined world units.
41    pub const fn get(self) -> f32 {
42        self.0
43    }
44}
45
46/// Positive finite physical texels per logical screen pixel.
47///
48/// A value below one represents a downsampled target and a value above one a
49/// native HiDPI or supersampled target. It is not a line width.
50#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
51pub struct PhysicalPerLogical(f32);
52
53impl PhysicalPerLogical {
54    /// Labels a positive finite physical-to-logical pixel ratio.
55    pub fn new(value: f32) -> Result<Self, UnitError> {
56        positive_finite(value)
57            .then_some(Self(value))
58            .ok_or(UnitError::InvalidPhysicalPerLogical { value })
59    }
60
61    /// Returns physical texels per logical screen pixel.
62    pub const fn get(self) -> f32 {
63        self.0
64    }
65}
66
67/// Invalid scalar supplied to an explicitly typed rendering unit.
68#[derive(Debug, Clone, Copy, PartialEq)]
69pub enum UnitError {
70    /// Logical pixel lengths must be finite and strictly positive.
71    InvalidLogicalPixels {
72        /// Rejected untyped scalar.
73        value: f32,
74    },
75    /// World-space lengths must be finite and strictly positive.
76    InvalidWorldLength {
77        /// Rejected untyped scalar.
78        value: f32,
79    },
80    /// Physical-to-logical ratios must be finite and strictly positive.
81    InvalidPhysicalPerLogical {
82        /// Rejected untyped scalar.
83        value: f32,
84    },
85}
86
87impl fmt::Display for UnitError {
88    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89        match self {
90            Self::InvalidLogicalPixels { value } => {
91                write!(
92                    formatter,
93                    "logical pixel length must be positive and finite, got {value}"
94                )
95            }
96            Self::InvalidWorldLength { value } => {
97                write!(
98                    formatter,
99                    "world length must be positive and finite, got {value}"
100                )
101            }
102            Self::InvalidPhysicalPerLogical { value } => write!(
103                formatter,
104                "physical-per-logical ratio must be positive and finite, got {value}"
105            ),
106        }
107    }
108}
109
110impl Error for UnitError {}
111
112fn positive_finite(value: f32) -> bool {
113    value.is_finite() && value > 0.0
114}
115
116#[cfg(test)]
117mod tests {
118    use super::{LogicalPixels, PhysicalPerLogical, UnitError, WorldLength};
119
120    #[test]
121    fn scalar_units_reject_unlabelled_invalid_lengths() {
122        assert_eq!(LogicalPixels::new(2.0).unwrap().get(), 2.0);
123        assert_eq!(WorldLength::new(0.1).unwrap().get(), 0.1);
124        assert_eq!(PhysicalPerLogical::new(0.5).unwrap().get(), 0.5);
125        assert_eq!(
126            LogicalPixels::new(0.0),
127            Err(UnitError::InvalidLogicalPixels { value: 0.0 })
128        );
129        assert_eq!(
130            WorldLength::new(f32::INFINITY),
131            Err(UnitError::InvalidWorldLength {
132                value: f32::INFINITY,
133            })
134        );
135        assert_eq!(
136            PhysicalPerLogical::new(-1.0),
137            Err(UnitError::InvalidPhysicalPerLogical { value: -1.0 })
138        );
139    }
140}