Skip to main content

rayengine_core/
input.rs

1//! Action input whose edges survive render frames and are consumed per tick.
2
3use glam::Vec2;
4
5/// Small numeric action key, normally declared as a game-level constant.
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7pub struct Action(pub u16);
8
9/// Small numeric analog axis key, in a separate namespace from button actions.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub struct Axis(pub u16);
12
13#[derive(Clone, Copy, Debug, Default)]
14struct State {
15    down: bool,
16    pressed: bool,
17    released: bool,
18}
19
20/// Contiguous action states; reads and sampling allocate nothing after setup.
21///
22/// Multiple physical bindings must be ORed before calling [`Self::set`].
23/// Consume edges after each fixed update, not after every render frame.
24///
25/// ```
26/// use rayengine_core::input::{Action, Input};
27/// const JUMP: Action = Action(0);
28/// let mut input = Input::with_capacity(1);
29/// input.set(JUMP, true);
30/// assert!(input.pressed(JUMP));
31/// input.consume_edges();
32/// assert!(input.down(JUMP));
33/// assert!(!input.pressed(JUMP));
34/// ```
35#[derive(Debug, Default)]
36pub struct Input {
37    states: Vec<State>,
38    axes: Vec<f32>,
39    pointer_delta: Vec2,
40    reset_pending: bool,
41}
42
43impl Input {
44    /// Borrows action input with explicit per-update masks, without changing the
45    /// original states or allocating. Block UI-owned actions and relative look
46    /// motion before passing this view to gameplay. Held actions resume when
47    /// unmasked; edges still follow the caller's normal tick consumption.
48    pub fn routed<'a>(&'a self, blocked: &'a [Action], block_motion: bool) -> InputView<'a> {
49        InputView {
50            input: self,
51            blocked,
52            blocked_axes: &[],
53            block_motion,
54        }
55    }
56    /// Preallocates action slots to avoid allocation during input sampling.
57    pub fn with_capacity(actions: usize) -> Self {
58        Self {
59            states: vec![State::default(); actions],
60            axes: Vec::new(),
61            pointer_delta: Vec2::ZERO,
62            reset_pending: false,
63        }
64    }
65
66    /// Preallocates independent button and analog slots for frame sampling.
67    pub fn with_capacities(actions: usize, axes: usize) -> Self {
68        Self {
69            axes: vec![0.0; axes],
70            ..Self::with_capacity(actions)
71        }
72    }
73
74    /// Stores the latest analog value, clamped to `[-1, 1]`. Nonfinite values
75    /// become neutral. Unlike pointer displacement, values persist across ticks.
76    pub fn set_axis(&mut self, axis: Axis, value: f32) {
77        let index = usize::from(axis.0);
78        if index >= self.axes.len() {
79            self.axes.resize(index + 1, 0.0);
80        }
81        self.axes[index] = if value.is_finite() {
82            value.clamp(-1.0, 1.0)
83        } else {
84            0.0
85        };
86    }
87
88    /// Latest sampled analog value. Unbound/unknown axes return zero.
89    pub fn value(&self, axis: Axis) -> f32 {
90        self.axes.get(usize::from(axis.0)).copied().unwrap_or(0.0)
91    }
92
93    /// Samples a combined action state. Automatically grows for new action IDs.
94    pub fn set(&mut self, action: Action, down: bool) {
95        let index = usize::from(action.0);
96        if index >= self.states.len() {
97            self.states.resize(index + 1, State::default());
98        }
99        let state = &mut self.states[index];
100        state.pressed |= down && !state.down;
101        state.released |= !down && state.down;
102        state.down = down;
103    }
104
105    /// Whether an action is currently held.
106    pub fn down(&self, action: Action) -> bool {
107        self.states
108            .get(usize::from(action.0))
109            .is_some_and(|s| s.down)
110    }
111
112    /// Whether an action was pressed since the last consumed tick.
113    pub fn pressed(&self, action: Action) -> bool {
114        self.states
115            .get(usize::from(action.0))
116            .is_some_and(|s| s.pressed)
117    }
118
119    /// Whether an action was released since the last consumed tick.
120    pub fn released(&self, action: Action) -> bool {
121        self.states
122            .get(usize::from(action.0))
123            .is_some_and(|s| s.released)
124    }
125
126    /// Digital axis in `[-1, 1]`; opposing held actions cancel.
127    pub fn axis(&self, negative: Action, positive: Action) -> f32 {
128        f32::from(self.down(positive)) - f32::from(self.down(negative))
129    }
130
131    /// Accumulates relative pointer motion sampled between fixed updates.
132    /// The SDK supplies logical window units, independent of viewport scaling.
133    /// Panics for nonfinite motion.
134    pub fn add_pointer_delta(&mut self, delta: Vec2) {
135        assert!(delta.is_finite());
136        self.pointer_delta += delta;
137    }
138
139    /// Relative pointer motion since the previous consumed tick.
140    /// Apply sensitivity directly; this is displacement, not velocity.
141    pub fn pointer_delta(&self) -> Vec2 {
142        self.pointer_delta
143    }
144
145    /// Whether focus loss/reset occurred since the previous consumed tick.
146    /// Retained through paused render frames so UI capture can be cancelled
147    /// even if the window regains focus before simulation resumes.
148    pub fn reset_pending(&self) -> bool {
149        self.reset_pending
150    }
151
152    /// Clears transitions and pointer motion after one fixed update, preserving held actions.
153    pub fn consume_edges(&mut self) {
154        for state in &mut self.states {
155            state.pressed = false;
156            state.released = false;
157        }
158        self.pointer_delta = Vec2::ZERO;
159        self.reset_pending = false;
160    }
161
162    /// Releases every held action, e.g. on focus loss. Releases are observable.
163    pub fn release_all(&mut self) {
164        self.reset_pending = true;
165        for state in &mut self.states {
166            state.released |= state.down;
167            state.down = false;
168        }
169        self.pointer_delta = Vec2::ZERO;
170        self.axes.fill(0.0);
171    }
172}
173
174/// Read-only gameplay input with game-chosen action and pointer-motion masks.
175#[derive(Clone, Copy, Debug)]
176pub struct InputView<'a> {
177    input: &'a Input,
178    blocked: &'a [Action],
179    blocked_axes: &'a [Axis],
180    block_motion: bool,
181}
182
183impl<'a> InputView<'a> {
184    /// Adds explicit analog masks to this gameplay view. Masked values are
185    /// neutral; raw input stays readable by UI and held values resume unmasked.
186    pub fn with_blocked_axes(mut self, blocked: &'a [Axis]) -> Self {
187        self.blocked_axes = blocked;
188        self
189    }
190
191    /// Latest analog value, or zero when this axis is masked.
192    pub fn value(&self, axis: Axis) -> f32 {
193        if self.blocked_axes.contains(&axis) {
194            0.0
195        } else {
196            self.input.value(axis)
197        }
198    }
199    /// Whether an unmasked action is held.
200    pub fn down(&self, action: Action) -> bool {
201        !self.blocked.contains(&action) && self.input.down(action)
202    }
203
204    /// Whether an unmasked action was pressed.
205    pub fn pressed(&self, action: Action) -> bool {
206        !self.blocked.contains(&action) && self.input.pressed(action)
207    }
208
209    /// Whether an unmasked action was released.
210    pub fn released(&self, action: Action) -> bool {
211        !self.blocked.contains(&action) && self.input.released(action)
212    }
213
214    /// Digital axis with masked actions contributing zero.
215    pub fn axis(&self, negative: Action, positive: Action) -> f32 {
216        f32::from(self.down(positive)) - f32::from(self.down(negative))
217    }
218
219    /// Relative look motion, or zero while the UI owns it.
220    pub fn pointer_delta(&self) -> Vec2 {
221        if self.block_motion {
222            Vec2::ZERO
223        } else {
224            self.input.pointer_delta()
225        }
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn analog_values_persist_across_ticks_route_and_reset_to_neutral() {
235        let movement = Axis(0);
236        let look = Axis(1);
237        let mut input = Input::with_capacities(1, 2);
238        assert_eq!(input.value(Axis(99)), 0.0);
239        input.set_axis(movement, 0.4);
240        input.set_axis(look, -0.8);
241        input.set(Action(0), true);
242        input.add_pointer_delta(Vec2::ONE);
243        let axes = [movement, look];
244        let view = input.routed(&[Action(0)], true).with_blocked_axes(&axes);
245        assert_eq!(view.value(movement), 0.0);
246        assert_eq!(view.value(look), 0.0);
247        assert!(!view.pressed(Action(0)));
248        assert_eq!(input.value(movement), 0.4);
249        input.consume_edges();
250        for _ in 0..3 {
251            assert_eq!(input.value(movement), 0.4);
252            assert_eq!(input.routed(&[], false).value(look), -0.8);
253            assert!(!input.pressed(Action(0)));
254            assert_eq!(input.pointer_delta(), Vec2::ZERO);
255            input.consume_edges();
256        }
257        input.set_axis(movement, -0.2); // A new render frame replaces the old value.
258        assert_eq!(input.value(movement), -0.2);
259        input.release_all();
260        assert_eq!(input.value(movement), 0.0);
261        assert_eq!(input.value(look), 0.0);
262        assert!(input.released(Action(0)));
263    }
264
265    #[test]
266    fn analog_samples_are_bounded_and_nonfinite_values_are_neutral() {
267        let mut input = Input::default();
268        for (raw, expected) in [
269            (5.0, 1.0),
270            (-5.0, -1.0),
271            (f32::NAN, 0.0),
272            (f32::INFINITY, 0.0),
273            (f32::NEG_INFINITY, 0.0),
274        ] {
275            input.set_axis(Axis(2), raw);
276            assert_eq!(input.value(Axis(2)), expected);
277        }
278    }
279
280    #[test]
281    fn transitions_survive_frames_but_only_fire_on_one_tick() {
282        let mut input = Input::default();
283        input.set(Action(2), true);
284        input.set(Action(2), true); // Another render frame before a simulation tick.
285        assert!(input.pressed(Action(2)));
286        input.consume_edges();
287        assert!(!input.pressed(Action(2)));
288        assert!(input.down(Action(2)));
289        input.set(Action(2), false);
290        assert!(input.released(Action(2)));
291    }
292
293    #[test]
294    fn quick_tap_keeps_both_edges() {
295        let mut input = Input::default();
296        input.set(Action(0), true);
297        input.set(Action(0), false);
298        assert!(input.pressed(Action(0)) && input.released(Action(0)));
299        assert!(!input.down(Action(0)));
300    }
301
302    #[test]
303    fn unknown_actions_and_focus_loss_are_safe() {
304        let mut input = Input::default();
305        assert_eq!(input.axis(Action(0), Action(1)), 0.0);
306        input.set(Action(1), true);
307        input.release_all();
308        assert!(!input.down(Action(1)));
309        assert!(input.released(Action(1)));
310    }
311
312    #[test]
313    fn relative_motion_accumulates_until_one_tick_and_is_not_repeated_during_catch_up() {
314        let mut input = Input::with_capacity(1);
315        input.set(Action(0), true);
316        input.add_pointer_delta(Vec2::new(4.0, -2.0));
317        input.add_pointer_delta(Vec2::new(3.0, 1.0));
318        assert_eq!(input.pointer_delta(), Vec2::new(7.0, -1.0));
319        input.consume_edges();
320        assert_eq!(input.pointer_delta(), Vec2::ZERO);
321        assert!(input.down(Action(0)));
322        input.consume_edges();
323        assert_eq!(input.pointer_delta(), Vec2::ZERO);
324        input.add_pointer_delta(Vec2::new(-2.0, 3.0));
325        input.release_all();
326        assert_eq!(input.pointer_delta(), Vec2::ZERO);
327    }
328}