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    pub fn axis_active(threshold: f32, value: f32) -> bool {
50        if threshold >= 0.0 {
51            value >= threshold
52        } else {
53            value <= threshold
54        }
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn axis_threshold_sign_selects_side() {
64        assert!(Binding::axis_active(0.5, 0.7));
65        assert!(!Binding::axis_active(0.5, 0.3));
66        assert!(Binding::axis_active(-0.5, -0.7));
67        assert!(!Binding::axis_active(-0.5, -0.3));
68        assert!(Binding::axis_active(0.0, 0.0));
69    }
70}