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.set_pointer_delta(Point::new(0.0, 0.0));
14        self.set_scroll_delta(Point::new(0.0, 0.0));
15    }
16
17    /// Updates continuous and edge-triggered states from a platform `WindowEvent`.
18    ///
19    /// # Arguments
20    ///
21    /// - `&Self` - Mutable input state.
22    /// - `&WindowEvent` - Incoming OS or test event.
23    pub fn ingest(&mut self, event: &WindowEvent) {
24        match event {
25            WindowEvent::KeyDown(_, key) => {
26                self.set_modifiers(key.get_modifiers());
27                let code: KeyCode = key.get_code();
28                if self.get_mut_keys_down().insert(code) {
29                    let _: bool = self.get_mut_keys_just_pressed().insert(code);
30                }
31            }
32            WindowEvent::KeyUp(_, key) => {
33                self.set_modifiers(key.get_modifiers());
34                let code: KeyCode = key.get_code();
35                if self.get_mut_keys_down().remove(&code) {
36                    let _: bool = self.get_mut_keys_just_released().insert(code);
37                }
38            }
39            WindowEvent::PointerMove(_, ptr) => {
40                self.set_modifiers(ptr.get_modifiers());
41                let prev: Point = self.get_pointer_position();
42                let next: Point = ptr.get_position();
43                let delta: Point = self.get_pointer_delta();
44                self.set_pointer_delta(Point::new(
45                    delta.get_x() + (next.get_x() - prev.get_x()),
46                    delta.get_y() + (next.get_y() - prev.get_y()),
47                ));
48                self.set_pointer_position(next);
49            }
50            WindowEvent::PointerDown(_, ptr) => {
51                self.set_modifiers(ptr.get_modifiers());
52                self.set_pointer_position(ptr.get_position());
53                let _: bool = self.get_mut_buttons_down().insert(ptr.get_button());
54            }
55            WindowEvent::PointerUp(_, ptr) => {
56                self.set_modifiers(ptr.get_modifiers());
57                self.set_pointer_position(ptr.get_position());
58                let _: bool = self.get_mut_buttons_down().remove(&ptr.get_button());
59            }
60            WindowEvent::Scroll(_, delta) => {
61                let cur: Point = self.get_scroll_delta();
62                self.set_scroll_delta(Point::new(
63                    cur.get_x() + delta.get_x(),
64                    cur.get_y() + delta.get_y(),
65                ));
66            }
67            WindowEvent::Focused(_, false) => {
68                self.get_mut_keys_down().clear();
69                self.get_mut_buttons_down().clear();
70                self.set_modifiers(Modifiers::default());
71            }
72            _ => {}
73        }
74    }
75
76    /// Returns `true` while `key` is held down.
77    ///
78    /// # Arguments
79    ///
80    /// - `&Self` - Input state reference.
81    /// - `KeyCode` - Key to query.
82    ///
83    /// # Returns
84    ///
85    /// - `bool` - Whether the key is held.
86    #[must_use]
87    pub fn is_key_down(&self, key: KeyCode) -> bool {
88        self.get_keys_down().contains(&key)
89    }
90
91    /// Returns `true` if `key` transitioned from up to down during the current frame.
92    ///
93    /// # Arguments
94    ///
95    /// - `&Self` - Input state reference.
96    /// - `KeyCode` - Key to query.
97    ///
98    /// # Returns
99    ///
100    /// - `bool` - Whether the key was just pressed.
101    #[must_use]
102    pub fn is_key_just_pressed(&self, key: KeyCode) -> bool {
103        self.get_keys_just_pressed().contains(&key)
104    }
105
106    /// Returns `true` while pointer `button` is held down.
107    ///
108    /// # Arguments
109    ///
110    /// - `&Self` - Input state reference.
111    /// - `PointerButton` - Button to query.
112    ///
113    /// # Returns
114    ///
115    /// - `bool` - Whether the button is held.
116    #[must_use]
117    pub fn is_button_down(&self, button: PointerButton) -> bool {
118        self.get_buttons_down().contains(&button)
119    }
120
121    /// Computes a normalized `-1.0..=1.0` movement axis from negative and positive key bindings.
122    ///
123    /// # Arguments
124    ///
125    /// - `&Self` - Input state reference.
126    /// - `KeyCode` - Negative direction key.
127    /// - `KeyCode` - Positive direction key.
128    ///
129    /// # Returns
130    ///
131    /// - `f32` - Axis value in `{-1.0, 0.0, 1.0}`.
132    #[must_use]
133    pub fn axis(&self, negative: KeyCode, positive: KeyCode) -> f32 {
134        let mut value: f32 = 0.0;
135        if self.is_key_down(negative) {
136            value -= 1.0;
137        }
138        if self.is_key_down(positive) {
139            value += 1.0;
140        }
141        value
142    }
143
144    /// Sets the normalized analog virtual stick vector `(dx, dy)` for mobile touch joysticks or gamepads.
145    ///
146    /// # Arguments
147    ///
148    /// - `&Self` - Mutable input state.
149    /// - `f32` - Horizontal axis in `[-1.0, 1.0]`.
150    /// - `f32` - Vertical axis in `[-1.0, 1.0]`.
151    pub fn set_virtual_stick(&mut self, dx: f32, dy: f32) {
152        self.set_virtual_axis(Point::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)));
153    }
154
155    /// Resets the virtual analog stick to neutral `(0.0, 0.0)`.
156    ///
157    /// # Arguments
158    ///
159    /// - `&Self` - Mutable input state.
160    pub fn clear_virtual_stick(&mut self) {
161        self.set_virtual_axis(Point::new(0.0, 0.0));
162    }
163}
164
165/// Default arcade action map binding WASD + Arrows, Space/Click fire, Shift/E dash, and P/Esc pause.
166impl Default for ActionMap {
167    /// Creates an `ActionMap` pre-populated with standard desktop/web arcade controls.
168    ///
169    /// # Returns
170    ///
171    /// - `Self` - Standard arcade action map.
172    fn default() -> Self {
173        let mut map: Self = Self {
174            key_bindings: HashMap::new(),
175            button_bindings: HashMap::new(),
176        };
177        map.bind_key(GameAction::MoveLeft, KeyCode::ArrowLeft);
178        map.bind_key(GameAction::MoveLeft, KeyCode::Character('a'));
179        map.bind_key(GameAction::MoveLeft, KeyCode::Character('A'));
180        map.bind_key(GameAction::MoveRight, KeyCode::ArrowRight);
181        map.bind_key(GameAction::MoveRight, KeyCode::Character('d'));
182        map.bind_key(GameAction::MoveRight, KeyCode::Character('D'));
183        map.bind_key(GameAction::MoveUp, KeyCode::ArrowUp);
184        map.bind_key(GameAction::MoveUp, KeyCode::Character('w'));
185        map.bind_key(GameAction::MoveUp, KeyCode::Character('W'));
186        map.bind_key(GameAction::MoveDown, KeyCode::ArrowDown);
187        map.bind_key(GameAction::MoveDown, KeyCode::Character('s'));
188        map.bind_key(GameAction::MoveDown, KeyCode::Character('S'));
189        map.bind_key(GameAction::Fire, KeyCode::Space);
190        map.bind_key(GameAction::Fire, KeyCode::Character('j'));
191        map.bind_button(GameAction::Fire, PointerButton::Primary);
192        map.bind_key(GameAction::Dash, KeyCode::Character('e'));
193        map.bind_key(GameAction::Dash, KeyCode::Character('E'));
194        map.bind_key(GameAction::Jump, KeyCode::Space);
195        map.bind_key(GameAction::Pause, KeyCode::Escape);
196        map.bind_key(GameAction::Pause, KeyCode::Character('p'));
197        map.bind_key(GameAction::ActionAlt, KeyCode::Character('r'));
198        map.bind_key(GameAction::ActionAlt, KeyCode::Character('R'));
199        map
200    }
201}
202
203/// Binding registration and real-time input queries for `ActionMap`.
204impl ActionMap {
205    /// Binds a `KeyCode` to `action`.
206    ///
207    /// # Arguments
208    ///
209    /// - `&Self` - Mutable action map.
210    /// - `GameAction` - Semantic game action.
211    /// - `KeyCode` - Keyboard key to bind.
212    pub fn bind_key(&mut self, action: GameAction, key: KeyCode) {
213        self.get_mut_key_bindings()
214            .entry(action)
215            .or_default()
216            .push(key);
217    }
218
219    /// Binds a `PointerButton` to `action`.
220    ///
221    /// # Arguments
222    ///
223    /// - `&Self` - Mutable action map.
224    /// - `GameAction` - Semantic game action.
225    /// - `PointerButton` - Mouse/touch button to bind.
226    pub fn bind_button(&mut self, action: GameAction, button: PointerButton) {
227        self.get_mut_button_bindings()
228            .entry(action)
229            .or_default()
230            .push(button);
231    }
232
233    /// Returns `true` while any key or button bound to `action` is held in `input`.
234    ///
235    /// # Arguments
236    ///
237    /// - `&Self` - Action map reference.
238    /// - `GameAction` - Action to query.
239    /// - `&InputState` - Current polled input snapshot.
240    ///
241    /// # Returns
242    ///
243    /// - `bool` - Whether `action` is currently active.
244    #[must_use]
245    pub fn is_active(&self, action: GameAction, input: &InputState) -> bool {
246        if action == GameAction::Fire && input.get_virtual_fire() {
247            return true;
248        }
249        if action == GameAction::Dash && input.get_virtual_dash() {
250            return true;
251        }
252        let key_hit: bool = self
253            .get_key_bindings()
254            .get(&action)
255            .map(|keys: &Vec<KeyCode>| keys.iter().copied().any(|k: KeyCode| input.is_key_down(k)))
256            .unwrap_or(false);
257        if key_hit {
258            return true;
259        }
260        self.get_button_bindings()
261            .get(&action)
262            .map(|btns: &Vec<PointerButton>| {
263                btns.iter()
264                    .copied()
265                    .any(|b: PointerButton| input.is_button_down(b))
266            })
267            .unwrap_or(false)
268    }
269
270    /// Returns `true` when any key bound to `action` transitioned down on this frame.
271    ///
272    /// # Arguments
273    ///
274    /// - `&Self` - Action map reference.
275    /// - `GameAction` - Action to query.
276    /// - `&InputState` - Current polled input snapshot.
277    ///
278    /// # Returns
279    ///
280    /// - `bool` - Whether `action` was just triggered.
281    #[must_use]
282    pub fn is_just_pressed(&self, action: GameAction, input: &InputState) -> bool {
283        self.get_key_bindings()
284            .get(&action)
285            .map(|keys: &Vec<KeyCode>| {
286                keys.iter()
287                    .copied()
288                    .any(|k: KeyCode| input.is_key_just_pressed(k))
289            })
290            .unwrap_or(false)
291    }
292
293    /// Computes a normalized 2D movement vector `(dx, dy)` from directional action bindings.
294    ///
295    /// # Arguments
296    ///
297    /// - `&Self` - Action map reference.
298    /// - `&InputState` - Current polled input snapshot.
299    ///
300    /// # Returns
301    ///
302    /// - `Point` - Normalized movement vector with length `<= 1.0`.
303    #[must_use]
304    pub fn movement_vector(&self, input: &InputState) -> Point {
305        let mut dx: f32 = input.get_virtual_axis().get_x();
306        let mut dy: f32 = input.get_virtual_axis().get_y();
307        if self.is_active(GameAction::MoveLeft, input) {
308            dx -= 1.0;
309        }
310        if self.is_active(GameAction::MoveRight, input) {
311            dx += 1.0;
312        }
313        if self.is_active(GameAction::MoveUp, input) {
314            dy -= 1.0;
315        }
316        if self.is_active(GameAction::MoveDown, input) {
317            dy += 1.0;
318        }
319        let len: f32 = (dx * dx + dy * dy).sqrt();
320        if len > 1.0 {
321            Point::new(dx / len, dy / len)
322        } else {
323            Point::new(dx, dy)
324        }
325    }
326}