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 world units.
25///
26/// This type labels scalar distances such as 2D world-space stroke widths and
27/// 3D camera near/far ranges. Positions and directions remain vector types.
28#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
29pub struct WorldLength(f32);
30
31impl WorldLength {
32    /// Labels a positive finite scalar as a caller-defined 2D or 3D
33    /// 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/// Backend-stable 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
53pub(crate) const MIN_STABLE_PHYSICAL_PER_LOGICAL: f64 =
54    u32::MAX as f64 * f32::MIN_POSITIVE as f64 / 2.0;
55// A one-texel viewport has a half-width/half-height translation in the camera
56// uniform. Keep that translation normal as well as the viewport dimension and
57// reciprocal clip scale.
58pub(crate) const MAX_STABLE_PHYSICAL_PER_LOGICAL: f64 = 0.5 / f32::MIN_POSITIVE as f64;
59
60impl PhysicalPerLogical {
61    /// Labels a backend-stable physical-to-logical pixel ratio.
62    ///
63    /// The bounded range keeps logical dimensions and their reciprocal clip
64    /// scales and half-viewport translations normal (not subnormal) for every
65    /// non-empty `u32` target.
66    pub fn new(value: f32) -> Result<Self, UnitError> {
67        stable_physical_per_logical(f64::from(value))
68            .then_some(Self(value))
69            .ok_or(UnitError::InvalidPhysicalPerLogical { value })
70    }
71
72    /// Returns physical texels per logical screen pixel.
73    pub const fn get(self) -> f32 {
74        self.0
75    }
76}
77
78/// Invalid scalar supplied to an explicitly typed rendering unit.
79#[derive(Debug, Clone, Copy, PartialEq)]
80pub enum UnitError {
81    /// Logical pixel lengths must be finite and strictly positive.
82    InvalidLogicalPixels {
83        /// Rejected untyped scalar.
84        value: f32,
85    },
86    /// World-space lengths must be finite and strictly positive.
87    InvalidWorldLength {
88        /// Rejected untyped scalar.
89        value: f32,
90    },
91    /// Physical-to-logical ratios must keep `u32` target transforms in the
92    /// normal finite `f32` range.
93    InvalidPhysicalPerLogical {
94        /// Rejected untyped scalar.
95        value: f32,
96    },
97}
98
99impl fmt::Display for UnitError {
100    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
101        match self {
102            Self::InvalidLogicalPixels { value } => {
103                write!(
104                    formatter,
105                    "logical pixel length must be positive and finite, got {value}"
106                )
107            }
108            Self::InvalidWorldLength { value } => {
109                write!(
110                    formatter,
111                    "world length must be positive and finite, got {value}"
112                )
113            }
114            Self::InvalidPhysicalPerLogical { value } => write!(
115                formatter,
116                "physical-per-logical ratio must keep u32 target transforms in the normal finite f32 range, got {value}"
117            ),
118        }
119    }
120}
121
122impl Error for UnitError {}
123
124fn positive_finite(value: f32) -> bool {
125    value.is_finite() && value > 0.0
126}
127
128pub(crate) fn stable_physical_per_logical(value: f64) -> bool {
129    value.is_finite()
130        && (MIN_STABLE_PHYSICAL_PER_LOGICAL..=MAX_STABLE_PHYSICAL_PER_LOGICAL).contains(&value)
131}
132
133#[cfg(test)]
134mod tests {
135    use super::{LogicalPixels, PhysicalPerLogical, UnitError, WorldLength};
136
137    #[test]
138    fn scalar_units_reject_unlabelled_invalid_lengths() {
139        assert_eq!(LogicalPixels::new(2.0).unwrap().get(), 2.0);
140        assert_eq!(WorldLength::new(0.1).unwrap().get(), 0.1);
141        assert_eq!(PhysicalPerLogical::new(0.5).unwrap().get(), 0.5);
142        assert_eq!(
143            LogicalPixels::new(0.0),
144            Err(UnitError::InvalidLogicalPixels { value: 0.0 })
145        );
146        assert_eq!(
147            WorldLength::new(f32::INFINITY),
148            Err(UnitError::InvalidWorldLength {
149                value: f32::INFINITY,
150            })
151        );
152        assert_eq!(
153            PhysicalPerLogical::new(-1.0),
154            Err(UnitError::InvalidPhysicalPerLogical { value: -1.0 })
155        );
156        assert!(matches!(
157            PhysicalPerLogical::new(f32::MIN_POSITIVE),
158            Err(UnitError::InvalidPhysicalPerLogical { .. })
159        ));
160        assert!(matches!(
161            PhysicalPerLogical::new(f32::MAX),
162            Err(UnitError::InvalidPhysicalPerLogical { .. })
163        ));
164    }
165
166    #[test]
167    fn physical_per_logical_keeps_one_texel_half_viewport_normal() {
168        let maximum = 0.5 / f32::MIN_POSITIVE;
169        let scale = PhysicalPerLogical::new(maximum).unwrap().get();
170        let logical_extent = 1.0_f32 / scale;
171
172        assert!(logical_extent.is_normal());
173        assert!((logical_extent * 0.5).is_normal());
174        assert!(PhysicalPerLogical::new(f32::from_bits(maximum.to_bits() + 1)).is_err());
175    }
176}