Skip to main content

sim_logic/application/input/
motion.rs

1//! Relative pointer displacement in device motion units, not window coordinates.
2
3use std::{error::Error, fmt};
4
5/// Finite relative mouse displacement; positive X is right, positive Y is down.
6///
7/// These are raw device motion units, not logical pixels or world distances.
8/// Apply application sensitivity once, without multiplying by frame duration.
9/// The absolute per-axis bound also applies to each accumulated frame.
10#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
11pub struct RelativePointerMotion {
12    bits: [u64; 2],
13}
14
15impl RelativePointerMotion {
16    /// No displacement.
17    pub const ZERO: Self = Self { bits: [0; 2] };
18    /// Inclusive absolute per-axis event and frame displacement ceiling.
19    pub const MAX_DISPLACEMENT: f64 = 1_000_000.0;
20
21    /// Validates both coordinates before constructing a portable input value.
22    pub fn new(x: f64, y: f64) -> Result<Self, RelativePointerMotionError> {
23        if !x.is_finite() || !y.is_finite() {
24            return Err(RelativePointerMotionError::NonFinite);
25        }
26        if x.abs() > Self::MAX_DISPLACEMENT || y.abs() > Self::MAX_DISPLACEMENT {
27            return Err(RelativePointerMotionError::OutOfRange);
28        }
29        Ok(Self {
30            bits: [canonical_bits(x), canonical_bits(y)],
31        })
32    }
33    /// Horizontal raw displacement, positive to the right.
34    pub const fn x(self) -> f64 {
35        f64::from_bits(self.bits[0])
36    }
37    /// Vertical raw displacement, positive downward.
38    pub const fn y(self) -> f64 {
39        f64::from_bits(self.bits[1])
40    }
41    /// Adds displacements within the same explicit bounds, or changes nothing.
42    pub fn checked_add(self, other: Self) -> Result<Self, RelativePointerMotionError> {
43        Self::new(self.x() + other.x(), self.y() + other.y())
44    }
45}
46
47fn canonical_bits(value: f64) -> u64 {
48    if value == 0.0 { 0 } else { value.to_bits() }
49}
50
51/// A relative motion event or accumulated frame exceeded its numeric contract.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum RelativePointerMotionError {
54    /// A coordinate was NaN or infinite.
55    NonFinite,
56    /// A coordinate exceeded the inclusive absolute displacement ceiling.
57    OutOfRange,
58}
59
60impl fmt::Display for RelativePointerMotionError {
61    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
62        formatter.write_str(match self {
63            Self::NonFinite => "relative pointer motion must be finite",
64            Self::OutOfRange => "relative pointer motion exceeds the displacement limit",
65        })
66    }
67}
68impl Error for RelativePointerMotionError {}
69
70pub(super) fn frame_motion(
71    events: &[super::InputEvent],
72) -> Result<(RelativePointerMotion, bool), RelativePointerMotionError> {
73    let mut motion = RelativePointerMotion::ZERO;
74    let mut focus_lost = false;
75    for event in events {
76        match event {
77            super::InputEvent::RelativePointerMotion { motion: incoming } if !focus_lost => {
78                motion = motion.checked_add(*incoming)?;
79            }
80            super::InputEvent::FocusLost => {
81                motion = RelativePointerMotion::ZERO;
82                focus_lost = true;
83            }
84            _ => {}
85        }
86    }
87    Ok((motion, focus_lost))
88}