Skip to main content

glory_render/
motion.rs

1use crate::Error;
2
3/// A finite host-owned graphic rotation. There is no application frame task.
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum GraphicAnimation {
6    Rotate { period_millis: u32 },
7}
8impl GraphicAnimation {
9    pub fn validate(self) -> Result<(), Error> {
10        match self {
11            Self::Rotate { period_millis } if (16..=60000).contains(&period_millis) => Ok(()),
12            _ => Err(Error::InvalidProps(
13                "graphic rotation period must be in 16..=60000 milliseconds",
14            )),
15        }
16    }
17    /// The phase stays finite even for a large finite host timestamp.
18    pub fn radians(self, seconds: f64) -> Result<f64, Error> {
19        self.validate()?;
20        if !seconds.is_finite() || seconds < 0. {
21            return Err(Error::InvalidProps(
22                "graphic clock must be finite and nonnegative",
23            ));
24        }
25        let Self::Rotate { period_millis } = self;
26        let period = f64::from(period_millis) / 1000.;
27        Ok(seconds.rem_euclid(period) / period * std::f64::consts::TAU)
28    }
29}
30
31/// Native hosts explicitly choose their preference. Unknown defaults to Reduce.
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33pub enum MotionPreference {
34    #[default]
35    Reduce,
36    NoPreference,
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42    #[test]
43    fn periods_and_clock_values_are_independently_bounded() {
44        for period_millis in [0, 1, 15, 60001, u32::MAX] {
45            assert!(
46                GraphicAnimation::Rotate { period_millis }
47                    .validate()
48                    .is_err()
49            );
50        }
51        for period_millis in [16, 1200, 60000] {
52            GraphicAnimation::Rotate { period_millis }
53                .validate()
54                .unwrap();
55        }
56        let animation = GraphicAnimation::Rotate {
57            period_millis: 1000,
58        };
59        for seconds in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.] {
60            assert!(animation.radians(seconds).is_err());
61        }
62        assert_eq!(animation.radians(0.).unwrap(), 0.);
63        assert!((animation.radians(0.25).unwrap() - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
64        assert!(animation.radians(f64::MAX).unwrap().is_finite());
65    }
66}