Skip to main content

euv_core/game/input/
impl.rs

1use super::*;
2
3/// Per-frame input ingestion and real-time polling helpers for `InputState`.
4impl InputState {
5    /// Clears transient per-frame edge states (`just_pressed`, `just_released`, deltas) after a frame step.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Mutable input state.
10    pub fn begin_frame(&mut self) {
11        self.get_mut_keys_just_pressed().clear();
12        self.get_mut_keys_just_released().clear();
13        self.get_mut_buttons_just_pressed().clear();
14        self.get_mut_buttons_just_released().clear();
15        self.set_pointer_delta(Point::new(0.0, 0.0));
16        self.set_scroll_delta(Point::new(0.0, 0.0));
17    }
18
19    /// Returns a cloned snapshot containing held keys/buttons and axes with all transient edge events cleared.
20    ///
21    /// Used when executing subsequent fixed-timestep substeps so press/release edges are consumed exactly once.
22    ///
23    /// # Arguments
24    ///
25    /// - `&Self` - Input state reference.
26    ///
27    /// # Returns
28    ///
29    /// - `Self` - Edge-cleared input snapshot preserving held state.
30    #[must_use]
31    pub fn without_edges(&self) -> Self {
32        let mut copy: Self = self.clone();
33        copy.begin_frame();
34        copy
35    }
36
37    /// Returns `true` when any transient edge (`just_pressed`, `just_released`, pointer/scroll delta) is latched.
38    ///
39    /// # Arguments
40    ///
41    /// - `&Self` - Input state reference.
42    ///
43    /// # Returns
44    ///
45    /// - `bool` - Whether pending edge events remain unconsumed.
46    #[must_use]
47    pub fn has_pending_edges(&self) -> bool {
48        let key_edges: bool =
49            !self.get_keys_just_pressed().is_empty() || !self.get_keys_just_released().is_empty();
50        let btn_edges: bool = !self.get_buttons_just_pressed().is_empty()
51            || !self.get_buttons_just_released().is_empty();
52        let p_delta: Point = self.get_pointer_delta();
53        let s_delta: Point = self.get_scroll_delta();
54        let motion_edges: bool = p_delta.get_x() != 0.0
55            || p_delta.get_y() != 0.0
56            || s_delta.get_x() != 0.0
57            || s_delta.get_y() != 0.0;
58        if key_edges || btn_edges {
59            true
60        } else {
61            motion_edges
62        }
63    }
64
65    /// Updates continuous and edge-triggered states from a platform `WindowEvent`.
66    ///
67    /// # Arguments
68    ///
69    /// - `&Self` - Mutable input state.
70    /// - `&WindowEvent` - Incoming OS or test event.
71    pub fn ingest(&mut self, event: &WindowEvent) {
72        match event {
73            WindowEvent::KeyDown(_, key) => {
74                self.set_modifiers(key.get_modifiers());
75                let code: KeyCode = key.get_code();
76                if self.get_mut_keys_down().insert(code) {
77                    let _: bool = self.get_mut_keys_just_pressed().insert(code);
78                }
79            }
80            WindowEvent::KeyUp(_, key) => {
81                self.set_modifiers(key.get_modifiers());
82                let code: KeyCode = key.get_code();
83                if self.get_mut_keys_down().remove(&code) {
84                    let _: bool = self.get_mut_keys_just_released().insert(code);
85                }
86            }
87            WindowEvent::PointerMove(_, ptr) => {
88                self.set_modifiers(ptr.get_modifiers());
89                let prev: Point = self.get_pointer_position();
90                let next: Point = ptr.get_position();
91                let delta: Point = self.get_pointer_delta();
92                self.set_pointer_delta(Point::new(
93                    delta.get_x() + (next.get_x() - prev.get_x()),
94                    delta.get_y() + (next.get_y() - prev.get_y()),
95                ));
96                self.set_pointer_position(next);
97            }
98            WindowEvent::PointerDown(_, ptr) => {
99                self.set_modifiers(ptr.get_modifiers());
100                self.set_pointer_position(ptr.get_position());
101                let btn: PointerButton = ptr.get_button();
102                if self.get_mut_buttons_down().insert(btn) {
103                    let _: bool = self.get_mut_buttons_just_pressed().insert(btn);
104                }
105            }
106            WindowEvent::PointerUp(_, ptr) => {
107                self.set_modifiers(ptr.get_modifiers());
108                self.set_pointer_position(ptr.get_position());
109                let btn: PointerButton = ptr.get_button();
110                if self.get_mut_buttons_down().remove(&btn) {
111                    let _: bool = self.get_mut_buttons_just_released().insert(btn);
112                }
113            }
114            WindowEvent::Scroll(_, delta) => {
115                let cur: Point = self.get_scroll_delta();
116                self.set_scroll_delta(Point::new(
117                    cur.get_x() + delta.get_x(),
118                    cur.get_y() + delta.get_y(),
119                ));
120            }
121            WindowEvent::Focused(_, false) => {
122                self.get_mut_keys_down().clear();
123                self.get_mut_buttons_down().clear();
124                self.set_modifiers(Modifiers::default());
125            }
126            _ => {}
127        }
128    }
129
130    /// Returns `true` while `key` is held down.
131    ///
132    /// # Arguments
133    ///
134    /// - `&Self` - Input state reference.
135    /// - `KeyCode` - Key to query.
136    ///
137    /// # Returns
138    ///
139    /// - `bool` - Whether the key is held.
140    #[must_use]
141    pub fn is_key_down(&self, key: KeyCode) -> bool {
142        self.get_keys_down().contains(&key)
143    }
144
145    /// Returns `true` if `key` transitioned from up to down during the current frame.
146    ///
147    /// # Arguments
148    ///
149    /// - `&Self` - Input state reference.
150    /// - `KeyCode` - Key to query.
151    ///
152    /// # Returns
153    ///
154    /// - `bool` - Whether the key was just pressed.
155    #[must_use]
156    pub fn is_key_just_pressed(&self, key: KeyCode) -> bool {
157        self.get_keys_just_pressed().contains(&key)
158    }
159
160    /// Returns `true` if `key` transitioned from down to up during the current frame.
161    ///
162    /// # Arguments
163    ///
164    /// - `&Self` - Input state reference.
165    /// - `KeyCode` - Key to query.
166    ///
167    /// # Returns
168    ///
169    /// - `bool` - Whether the key was just released.
170    #[must_use]
171    pub fn is_key_just_released(&self, key: KeyCode) -> bool {
172        self.get_keys_just_released().contains(&key)
173    }
174
175    /// Returns `true` while pointer `button` is held down.
176    ///
177    /// # Arguments
178    ///
179    /// - `&Self` - Input state reference.
180    /// - `PointerButton` - Button to query.
181    ///
182    /// # Returns
183    ///
184    /// - `bool` - Whether the button is held.
185    #[must_use]
186    pub fn is_button_down(&self, button: PointerButton) -> bool {
187        self.get_buttons_down().contains(&button)
188    }
189
190    /// Returns `true` if pointer `button` transitioned from up to down during the current frame.
191    ///
192    /// # Arguments
193    ///
194    /// - `&Self` - Input state reference.
195    /// - `PointerButton` - Button to query.
196    ///
197    /// # Returns
198    ///
199    /// - `bool` - Whether the button was just pressed.
200    #[must_use]
201    pub fn is_button_just_pressed(&self, button: PointerButton) -> bool {
202        self.get_buttons_just_pressed().contains(&button)
203    }
204
205    /// Returns `true` if pointer `button` transitioned from down to up during the current frame.
206    ///
207    /// # Arguments
208    ///
209    /// - `&Self` - Input state reference.
210    /// - `PointerButton` - Button to query.
211    ///
212    /// # Returns
213    ///
214    /// - `bool` - Whether the button was just released.
215    #[must_use]
216    pub fn is_button_just_released(&self, button: PointerButton) -> bool {
217        self.get_buttons_just_released().contains(&button)
218    }
219
220    /// Computes a normalized `-1.0..=1.0` movement axis from negative and positive key bindings.
221    ///
222    /// # Arguments
223    ///
224    /// - `&Self` - Input state reference.
225    /// - `KeyCode` - Negative direction key.
226    /// - `KeyCode` - Positive direction key.
227    ///
228    /// # Returns
229    ///
230    /// - `f32` - Axis value in `{-1.0, 0.0, 1.0}`.
231    #[must_use]
232    pub fn axis(&self, negative: KeyCode, positive: KeyCode) -> f32 {
233        let mut value: f32 = 0.0;
234        if self.is_key_down(negative) {
235            value -= 1.0;
236        }
237        if self.is_key_down(positive) {
238            value += 1.0;
239        }
240        value
241    }
242
243    /// Sets the normalized analog virtual stick vector `(dx, dy)` for mobile touch joysticks or gamepads.
244    ///
245    /// # Arguments
246    ///
247    /// - `&Self` - Mutable input state.
248    /// - `f32` - Horizontal axis in `[-1.0, 1.0]`.
249    /// - `f32` - Vertical axis in `[-1.0, 1.0]`.
250    pub fn set_virtual_stick(&mut self, dx: f32, dy: f32) {
251        self.set_virtual_axis(Point::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)));
252    }
253
254    /// Resets the virtual analog stick to neutral `(0.0, 0.0)`.
255    ///
256    /// # Arguments
257    ///
258    /// - `&Self` - Mutable input state.
259    pub fn clear_virtual_stick(&mut self) {
260        self.set_virtual_axis(Point::new(0.0, 0.0));
261    }
262}
263
264/// Default arcade action map binding WASD + Arrows, Space/Click fire, Shift/E dash, and P/Esc pause.
265impl Default for ActionMap {
266    /// Creates an `ActionMap` pre-populated with standard desktop/web arcade controls.
267    ///
268    /// # Returns
269    ///
270    /// - `Self` - Standard arcade action map.
271    fn default() -> Self {
272        let mut map: Self = Self {
273            key_bindings: HashMap::new(),
274            button_bindings: HashMap::new(),
275        };
276        map.bind_key(GameAction::MoveLeft, KeyCode::ArrowLeft);
277        map.bind_key(GameAction::MoveLeft, KeyCode::Character('a'));
278        map.bind_key(GameAction::MoveLeft, KeyCode::Character('A'));
279        map.bind_key(GameAction::MoveRight, KeyCode::ArrowRight);
280        map.bind_key(GameAction::MoveRight, KeyCode::Character('d'));
281        map.bind_key(GameAction::MoveRight, KeyCode::Character('D'));
282        map.bind_key(GameAction::MoveUp, KeyCode::ArrowUp);
283        map.bind_key(GameAction::MoveUp, KeyCode::Character('w'));
284        map.bind_key(GameAction::MoveUp, KeyCode::Character('W'));
285        map.bind_key(GameAction::MoveDown, KeyCode::ArrowDown);
286        map.bind_key(GameAction::MoveDown, KeyCode::Character('s'));
287        map.bind_key(GameAction::MoveDown, KeyCode::Character('S'));
288        map.bind_key(GameAction::Fire, KeyCode::Space);
289        map.bind_key(GameAction::Fire, KeyCode::Character('j'));
290        map.bind_button(GameAction::Fire, PointerButton::Primary);
291        map.bind_key(GameAction::Dash, KeyCode::Character('e'));
292        map.bind_key(GameAction::Dash, KeyCode::Character('E'));
293        map.bind_key(GameAction::Jump, KeyCode::Space);
294        map.bind_key(GameAction::Pause, KeyCode::Escape);
295        map.bind_key(GameAction::Pause, KeyCode::Character('p'));
296        map.bind_key(GameAction::ActionAlt, KeyCode::Character('r'));
297        map.bind_key(GameAction::ActionAlt, KeyCode::Character('R'));
298        map
299    }
300}
301
302/// Binding registration and real-time input queries for `ActionMap`.
303impl ActionMap {
304    /// Binds a `KeyCode` to `action`.
305    ///
306    /// # Arguments
307    ///
308    /// - `&Self` - Mutable action map.
309    /// - `GameAction` - Semantic game action.
310    /// - `KeyCode` - Keyboard key to bind.
311    pub fn bind_key(&mut self, action: GameAction, key: KeyCode) {
312        self.get_mut_key_bindings()
313            .entry(action)
314            .or_default()
315            .push(key);
316    }
317
318    /// Binds a `PointerButton` to `action`.
319    ///
320    /// # Arguments
321    ///
322    /// - `&Self` - Mutable action map.
323    /// - `GameAction` - Semantic game action.
324    /// - `PointerButton` - Mouse/touch button to bind.
325    pub fn bind_button(&mut self, action: GameAction, button: PointerButton) {
326        self.get_mut_button_bindings()
327            .entry(action)
328            .or_default()
329            .push(button);
330    }
331
332    /// Returns `true` while any key or button bound to `action` is held in `input`.
333    ///
334    /// # Arguments
335    ///
336    /// - `&Self` - Action map reference.
337    /// - `GameAction` - Action to query.
338    /// - `&InputState` - Current polled input snapshot.
339    ///
340    /// # Returns
341    ///
342    /// - `bool` - Whether `action` is currently active.
343    #[must_use]
344    pub fn is_active(&self, action: GameAction, input: &InputState) -> bool {
345        if action == GameAction::Fire && input.get_virtual_fire() {
346            return true;
347        }
348        if action == GameAction::Dash && input.get_virtual_dash() {
349            return true;
350        }
351        let key_hit: bool = self
352            .get_key_bindings()
353            .get(&action)
354            .map(|keys: &Vec<KeyCode>| keys.iter().copied().any(|k: KeyCode| input.is_key_down(k)))
355            .unwrap_or(false);
356        if key_hit {
357            return true;
358        }
359        self.get_button_bindings()
360            .get(&action)
361            .map(|btns: &Vec<PointerButton>| {
362                btns.iter()
363                    .copied()
364                    .any(|b: PointerButton| input.is_button_down(b))
365            })
366            .unwrap_or(false)
367    }
368
369    /// Returns `true` when any key bound to `action` transitioned down on this frame.
370    ///
371    /// # Arguments
372    ///
373    /// - `&Self` - Action map reference.
374    /// - `GameAction` - Action to query.
375    /// - `&InputState` - Current polled input snapshot.
376    ///
377    /// # Returns
378    ///
379    /// - `bool` - Whether `action` was just triggered.
380    #[must_use]
381    pub fn is_just_pressed(&self, action: GameAction, input: &InputState) -> bool {
382        self.get_key_bindings()
383            .get(&action)
384            .map(|keys: &Vec<KeyCode>| {
385                keys.iter()
386                    .copied()
387                    .any(|k: KeyCode| input.is_key_just_pressed(k))
388            })
389            .unwrap_or(false)
390    }
391
392    /// Computes a normalized 2D movement vector `(dx, dy)` from directional action bindings.
393    ///
394    /// # Arguments
395    ///
396    /// - `&Self` - Action map reference.
397    /// - `&InputState` - Current polled input snapshot.
398    ///
399    /// # Returns
400    ///
401    /// - `Point` - Normalized movement vector with length `<= 1.0`.
402    #[must_use]
403    pub fn movement_vector(&self, input: &InputState) -> Point {
404        let mut dx: f32 = input.get_virtual_axis().get_x();
405        let mut dy: f32 = input.get_virtual_axis().get_y();
406        if self.is_active(GameAction::MoveLeft, input) {
407            dx -= 1.0;
408        }
409        if self.is_active(GameAction::MoveRight, input) {
410            dx += 1.0;
411        }
412        if self.is_active(GameAction::MoveUp, input) {
413            dy -= 1.0;
414        }
415        if self.is_active(GameAction::MoveDown, input) {
416            dy += 1.0;
417        }
418        let len: f32 = (dx * dx + dy * dy).sqrt();
419        if len > 1.0 {
420            Point::new(dx / len, dy / len)
421        } else {
422            Point::new(dx, dy)
423        }
424    }
425}