Skip to main content

sim_logic/application/input/
pointer.rs

1//! Validated logical pointer coordinates and portable mouse buttons.
2
3use std::{
4    error::Error,
5    fmt,
6    hash::{Hash, Hasher},
7};
8
9use sim_engine::{Camera2d, Camera2dError, LogicalScreenPosition, LogicalViewport, Vec2};
10
11/// A portable mouse button supported by the desktop and headless adapters.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum MouseButton {
15    /// The primary (left) physical mouse button.
16    Left,
17    /// The secondary (right) physical mouse button.
18    Right,
19    /// The middle physical mouse button, usually the wheel button.
20    Middle,
21}
22
23pub(super) const ALL_MOUSE_BUTTONS: [MouseButton; 3] =
24    [MouseButton::Left, MouseButton::Right, MouseButton::Middle];
25
26pub(super) const fn mouse_button_index(button: MouseButton) -> usize {
27    match button {
28        MouseButton::Left => 0,
29        MouseButton::Right => 1,
30        MouseButton::Middle => 2,
31    }
32}
33
34/// Rejection that preserves an existing mouse-button binding.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct DuplicateMouseBinding {
37    pub(super) button: MouseButton,
38}
39
40impl DuplicateMouseBinding {
41    /// Returns the physical button that was already bound.
42    pub const fn button(self) -> MouseButton {
43        self.button
44    }
45}
46
47impl fmt::Display for DuplicateMouseBinding {
48    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49        write!(formatter, "mouse button {:?} is already bound", self.button)
50    }
51}
52
53impl Error for DuplicateMouseBinding {}
54
55/// Rejection of a pointer position containing NaN or infinity.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct PointerSampleError;
58
59impl fmt::Display for PointerSampleError {
60    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61        formatter.write_str("pointer coordinates must be finite logical pixels")
62    }
63}
64
65impl Error for PointerSampleError {}
66
67/// A finite pointer position and its event-time logical viewport.
68///
69/// Both use logical pixels with a top-left origin and downward-positive y.
70/// Positions outside the viewport are allowed and are never clamped. Values
71/// are immutable, so an action edge can preserve a click's position even when
72/// later motion, resizing, or a DPI change updates the current pointer.
73#[derive(Debug, Clone, Copy, PartialEq)]
74pub struct PointerSample {
75    position: LogicalScreenPosition,
76    viewport: LogicalViewport,
77}
78
79impl PointerSample {
80    /// Captures coordinates without requiring a window or renderer.
81    ///
82    /// Rejects non-finite positions. The supplied viewport already guarantees
83    /// finite, strictly positive dimensions through its own constructor.
84    pub fn new(
85        position: LogicalScreenPosition,
86        viewport: LogicalViewport,
87    ) -> Result<Self, PointerSampleError> {
88        if !position.is_finite() {
89            return Err(PointerSampleError);
90        }
91        Ok(Self { position, viewport })
92    }
93
94    /// Returns the captured top-left-relative logical position.
95    pub const fn position(self) -> LogicalScreenPosition {
96        self.position
97    }
98
99    /// Returns the viewport captured alongside this position.
100    pub const fn viewport(self) -> LogicalViewport {
101        self.viewport
102    }
103
104    pub(crate) fn is_inside_viewport(self) -> bool {
105        let point = self.position.to_vec2();
106        point.x() >= 0.0
107            && point.y() >= 0.0
108            && point.x() < self.viewport.width()
109            && point.y() < self.viewport.height()
110    }
111
112    /// Converts this sample to the supplied camera's depth-zero world plane.
113    ///
114    /// This delegates exactly to [`Camera2d::screen_to_world`], preserving its
115    /// projection errors. No active or interpolated camera is chosen implicitly;
116    /// callers decide which camera snapshot their interaction should use.
117    pub fn world_position(self, camera: Camera2d) -> Result<Vec2, Camera2dError> {
118        camera.screen_to_world(self.position, self.viewport)
119    }
120}
121
122// Finite construction makes float equality reflexive. Hash canonicalizes the
123// two signed zero representations, which compare equal under PartialEq.
124impl Eq for PointerSample {}
125
126impl Hash for PointerSample {
127    fn hash<H: Hasher>(&self, state: &mut H) {
128        let position = self.position.to_vec2();
129        for value in [
130            position.x(),
131            position.y(),
132            self.viewport.width(),
133            self.viewport.height(),
134        ] {
135            let bits = if value == 0.0 { 0 } else { value.to_bits() };
136            bits.hash(state);
137        }
138    }
139}