Skip to main content

repame_input/
binding.rs

1//! Physical input bindings: one action fires from many inputs.
2
3use repose_core::input::{GamepadAxis, GamepadButton, PointerButton};
4use repose_core::shortcuts::KeyChord;
5
6/// One physical source that can drive an action. Many-to-one: several
7/// bindings can point at the same action (keyboard + pad + axis).
8#[derive(Clone, Debug)]
9pub enum Binding {
10    /// Keyboard chord (key + modifiers), same shape as repose shortcuts.
11    Key(KeyChord),
12    /// Mouse button press.
13    Mouse(PointerButton),
14    /// Gamepad button press.
15    Pad(GamepadButton),
16    /// Analog axis crossing. Active while `value >= threshold` for a
17    /// positive threshold, `value <= threshold` for a negative one, so
18    /// `-0.5` on `LeftStickX` means "pushed left past half".
19    Axis { axis: GamepadAxis, threshold: f32 },
20}
21
22// Manual `PartialEq`: repose `PointerButton` has no `PartialEq`, so
23// compare mouse variants by discriminant.
24impl PartialEq for Binding {
25    fn eq(&self, other: &Self) -> bool {
26        match (self, other) {
27            (Binding::Key(a), Binding::Key(b)) => a == b,
28            (Binding::Mouse(a), Binding::Mouse(b)) => {
29                std::mem::discriminant(a) == std::mem::discriminant(b)
30            }
31            (Binding::Pad(a), Binding::Pad(b)) => a == b,
32            (
33                Binding::Axis {
34                    axis: a,
35                    threshold: t,
36                },
37                Binding::Axis {
38                    axis: b,
39                    threshold: u,
40                },
41            ) => a == b && t == u,
42            _ => false,
43        }
44    }
45}
46
47impl Binding {
48    /// True while the latest axis value holds past the threshold.
49    /// A zero threshold means "any non-zero deflection" (rest stick at
50    /// exactly 0.0 is inactive), so a centered stick never holds an
51    /// action forever.
52    pub fn axis_active(threshold: f32, value: f32) -> bool {
53        if !value.is_finite() {
54            return false;
55        }
56        if threshold == 0.0 {
57            value != 0.0
58        } else if threshold > 0.0 {
59            value >= threshold
60        } else {
61            value <= threshold
62        }
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn axis_threshold_sign_selects_side() {
72        assert!(Binding::axis_active(0.5, 0.7));
73        assert!(!Binding::axis_active(0.5, 0.3));
74        assert!(Binding::axis_active(-0.5, -0.7));
75        assert!(!Binding::axis_active(-0.5, -0.3));
76        assert!(!Binding::axis_active(0.0, 0.0));
77        assert!(Binding::axis_active(0.0, 0.1));
78        assert!(Binding::axis_active(0.0, -0.1));
79        assert!(!Binding::axis_active(0.0, f32::NAN));
80        assert!(!Binding::axis_active(0.5, f32::NAN));
81        assert!(!Binding::axis_active(-0.5, f32::NAN));
82    }
83}