Skip to main content

rusting_core/
input.rs

1//! Runtime-side input capture and named action mapping.
2//!
3//! `RuntimeInput` holds raw keyboard and mouse state for gameplay systems.
4//! Window integrations record raw events into it and clear edge state once per
5//! rendered frame after gameplay systems have had a chance to read it.
6
7use std::collections::{BTreeSet, HashMap};
8
9use bevy_ecs::entity::Entity;
10use bevy_ecs::prelude::Resource;
11use serde::{Deserialize, Serialize};
12pub use winit::event::MouseButton;
13pub use winit::keyboard::KeyCode;
14
15/// Fired the frame a mouse button is pressed over a renderable entity.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct ClickEvent {
18    pub entity: Entity,
19    pub button: MouseButton,
20    pub world_position: [f32; 3],
21}
22
23/// Held keys, mouse buttons, and cursor position for the current frame.
24///
25/// `just_pressed`/`just_released` sets are edge-triggered: they hold exactly
26/// the keys or buttons that changed state since the last call to
27/// [`RuntimeInput::clear_frame_edges`]. Runtime integrations call that method
28/// once per rendered frame after gameplay systems have had a chance to read
29/// them.
30///
31/// It serializes whole, so replays can record what each frame's systems saw.
32#[derive(
33    Resource, Clone, Debug, Default, PartialEq, Serialize, Deserialize,
34)]
35pub struct RuntimeInput {
36    keys_held: BTreeSet<KeyCode>,
37    keys_just_pressed: BTreeSet<KeyCode>,
38    keys_just_released: BTreeSet<KeyCode>,
39    mouse_held: BTreeSet<MouseButton>,
40    mouse_just_pressed: BTreeSet<MouseButton>,
41    mouse_just_released: BTreeSet<MouseButton>,
42    cursor_position: Option<[f32; 2]>,
43    viewport_size: [f32; 2],
44    mouse_motion: [f32; 2],
45    cursor_captured: bool,
46}
47
48impl RuntimeInput {
49    #[must_use]
50    pub fn key_held(&self, key: KeyCode) -> bool {
51        self.keys_held.contains(&key)
52    }
53    #[must_use]
54    pub fn key_just_pressed(&self, key: KeyCode) -> bool {
55        self.keys_just_pressed.contains(&key)
56    }
57    #[must_use]
58    pub fn key_just_released(&self, key: KeyCode) -> bool {
59        self.keys_just_released.contains(&key)
60    }
61    #[must_use]
62    pub fn mouse_held(&self, button: MouseButton) -> bool {
63        self.mouse_held.contains(&button)
64    }
65    #[must_use]
66    pub fn mouse_just_pressed(&self, button: MouseButton) -> bool {
67        self.mouse_just_pressed.contains(&button)
68    }
69    #[must_use]
70    pub fn mouse_just_released(&self, button: MouseButton) -> bool {
71        self.mouse_just_released.contains(&button)
72    }
73    #[must_use]
74    pub fn cursor_position(&self) -> Option<[f32; 2]> {
75        self.cursor_position
76    }
77
78    /// Raw mouse movement since the last [`Self::clear_frame_edges`]. It keeps
79    /// counting while the cursor is captured and cannot move.
80    #[must_use]
81    pub fn mouse_motion(&self) -> [f32; 2] {
82        self.mouse_motion
83    }
84
85    /// True when gameplay asked the window to hide and lock the cursor.
86    #[must_use]
87    pub fn cursor_captured(&self) -> bool {
88        self.cursor_captured
89    }
90
91    /// Asks the window to hide and lock the cursor, for mouse look. The
92    /// window runner applies the request after the frame's systems ran.
93    pub fn set_cursor_captured(&mut self, captured: bool) {
94        self.cursor_captured = captured;
95    }
96
97    /// Current window/render-viewport size in pixels, used to convert cursor
98    /// positions into normalized device coordinates for gameplay picking.
99    #[must_use]
100    pub fn viewport_size(&self) -> [f32; 2] {
101        self.viewport_size
102    }
103
104    /// Records one keyboard `WindowEvent`. Ignores OS auto-repeat: repeated
105    /// presses do not re-fire `just_pressed`.
106    pub fn record_key(&mut self, key: KeyCode, pressed: bool) {
107        if pressed {
108            if self.keys_held.insert(key) {
109                self.keys_just_pressed.insert(key);
110            }
111        } else if self.keys_held.remove(&key) {
112            self.keys_just_released.insert(key);
113        }
114    }
115
116    /// Records one mouse button `WindowEvent`.
117    pub fn record_mouse_button(&mut self, button: MouseButton, pressed: bool) {
118        if pressed {
119            if self.mouse_held.insert(button) {
120                self.mouse_just_pressed.insert(button);
121            }
122        } else if self.mouse_held.remove(&button) {
123            self.mouse_just_released.insert(button);
124        }
125    }
126
127    /// Releases every held key and button, reporting each as just released.
128    /// Call it when the window loses focus, because the matching release
129    /// events then go to another window.
130    pub fn release_all(&mut self) {
131        self.keys_just_released.append(&mut self.keys_held);
132        self.mouse_just_released.append(&mut self.mouse_held);
133    }
134
135    /// Records the latest cursor position from a `CursorMoved` event.
136    pub fn record_cursor_position(&mut self, position: [f32; 2]) {
137        self.cursor_position = Some(position);
138    }
139    /// Adds one raw `DeviceEvent::MouseMotion` delta.
140    pub fn record_mouse_motion(&mut self, delta: [f32; 2]) {
141        self.mouse_motion[0] += delta[0];
142        self.mouse_motion[1] += delta[1];
143    }
144    /// Records the current window/render-viewport size in pixels.
145    pub fn record_viewport_size(&mut self, size: [f32; 2]) {
146        self.viewport_size = size;
147    }
148
149    /// Clears this frame's edge sets. Runtime integrations call this once per
150    /// rendered frame after gameplay systems have read them, so the next frame
151    /// starts empty.
152    pub fn clear_frame_edges(&mut self) {
153        self.keys_just_pressed.clear();
154        self.keys_just_released.clear();
155        self.mouse_just_pressed.clear();
156        self.mouse_just_released.clear();
157        self.mouse_motion = [0.0; 2];
158    }
159}
160
161/// A raw input source which can satisfy a named gameplay action.
162///
163/// The enum deliberately leaves room for a future `Gamepad(GamepadButton)`
164/// variant without changing the [`ActionMap`] API.
165#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
166pub enum InputBinding {
167    Key(KeyCode),
168    Mouse(MouseButton),
169}
170
171/// Maps action names to one or more raw input bindings (any bound input
172/// satisfies the action).
173#[derive(Resource, Clone, Default)]
174pub struct ActionMap {
175    bindings: HashMap<String, Vec<InputBinding>>,
176}
177
178impl ActionMap {
179    pub fn bind(
180        &mut self,
181        action: impl Into<String>,
182        binding: InputBinding,
183    ) -> &mut Self {
184        self.bindings
185            .entry(action.into())
186            .or_default()
187            .push(binding);
188        self
189    }
190    /// Removes one binding of `action`; other bindings stay.
191    pub fn unbind(&mut self, action: &str, binding: InputBinding) {
192        if let Some(list) = self.bindings.get_mut(action) {
193            list.retain(|bound| *bound != binding);
194            if list.is_empty() {
195                self.bindings.remove(action);
196            }
197        }
198    }
199    #[must_use]
200    pub fn held(&self, input: &RuntimeInput, action: &str) -> bool {
201        self.bindings_for(action).any(|binding| match binding {
202            InputBinding::Key(key) => input.key_held(*key),
203            InputBinding::Mouse(button) => input.mouse_held(*button),
204        })
205    }
206    #[must_use]
207    pub fn just_pressed(&self, input: &RuntimeInput, action: &str) -> bool {
208        self.bindings_for(action).any(|binding| match binding {
209            InputBinding::Key(key) => input.key_just_pressed(*key),
210            InputBinding::Mouse(button) => input.mouse_just_pressed(*button),
211        })
212    }
213    #[must_use]
214    pub fn just_released(&self, input: &RuntimeInput, action: &str) -> bool {
215        self.bindings_for(action).any(|binding| match binding {
216            InputBinding::Key(key) => input.key_just_released(*key),
217            InputBinding::Mouse(button) => input.mouse_just_released(*button),
218        })
219    }
220    /// Inputs bound to `action`, in binding order; empty when unbound.
221    #[must_use]
222    pub fn bindings(&self, action: &str) -> &[InputBinding] {
223        self.bindings.get(action).map_or(&[], Vec::as_slice)
224    }
225    fn bindings_for(
226        &self,
227        action: &str,
228    ) -> impl Iterator<Item = &InputBinding> {
229        self.bindings.get(action).into_iter().flatten()
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236    use bevy_ecs::prelude::Resource;
237
238    #[test]
239    fn mouse_motion_adds_up_until_the_frame_ends() {
240        let mut input = RuntimeInput::default();
241        input.record_mouse_motion([1.0, -2.0]);
242        input.record_mouse_motion([0.5, 1.0]);
243        assert_eq!(input.mouse_motion(), [1.5, -1.0]);
244        input.clear_frame_edges();
245        assert_eq!(input.mouse_motion(), [0.0, 0.0]);
246    }
247
248    #[test]
249    fn release_all_clears_held_input_as_releases() {
250        let mut input = RuntimeInput::default();
251        input.record_key(KeyCode::KeyW, true);
252        input.record_mouse_button(MouseButton::Right, true);
253        input.clear_frame_edges();
254        input.release_all();
255        assert!(!input.key_held(KeyCode::KeyW));
256        assert!(input.key_just_released(KeyCode::KeyW));
257        assert!(input.mouse_just_released(MouseButton::Right));
258    }
259
260    #[test]
261    fn runtime_input_and_action_map_are_ecs_resources() {
262        fn assert_resource<T: Resource>() {}
263        assert_resource::<RuntimeInput>();
264        assert_resource::<ActionMap>();
265    }
266    #[test]
267    fn keyboard_edges_and_auto_repeat_are_tracked() {
268        let mut input = RuntimeInput::default();
269        input.record_key(KeyCode::Space, true);
270        assert!(input.key_held(KeyCode::Space));
271        assert!(input.key_just_pressed(KeyCode::Space));
272        input.record_key(KeyCode::Space, true);
273        input.clear_frame_edges();
274        assert!(input.key_held(KeyCode::Space));
275        assert!(!input.key_just_pressed(KeyCode::Space));
276        input.record_key(KeyCode::Space, false);
277        assert!(input.key_just_released(KeyCode::Space));
278    }
279    #[test]
280    fn mouse_cursor_and_viewport_are_tracked() {
281        let mut input = RuntimeInput::default();
282        input.record_mouse_button(MouseButton::Left, true);
283        input.record_cursor_position([12.0, 34.0]);
284        input.record_viewport_size([800.0, 600.0]);
285        assert!(input.mouse_held(MouseButton::Left));
286        assert!(input.mouse_just_pressed(MouseButton::Left));
287        assert_eq!(input.cursor_position(), Some([12.0, 34.0]));
288        assert_eq!(input.viewport_size(), [800.0, 600.0]);
289        input.clear_frame_edges();
290        input.record_mouse_button(MouseButton::Left, false);
291        assert!(input.mouse_just_released(MouseButton::Left));
292        assert!(!input.mouse_held(MouseButton::Left));
293    }
294    #[test]
295    fn actions_cover_keyboard_mouse_and_edge_clearing() {
296        let mut map = ActionMap::default();
297        map.bind("jump", InputBinding::Key(KeyCode::Space))
298            .bind("jump", InputBinding::Mouse(MouseButton::Left));
299        let mut input = RuntimeInput::default();
300        input.record_key(KeyCode::Space, true);
301        assert!(map.just_pressed(&input, "jump"));
302        assert!(map.held(&input, "jump"));
303        input.clear_frame_edges();
304        assert!(!map.just_pressed(&input, "jump"));
305        assert!(map.held(&input, "jump"));
306        input.record_key(KeyCode::Space, false);
307        assert!(map.just_released(&input, "jump"));
308        input.clear_frame_edges();
309        input.record_mouse_button(MouseButton::Left, true);
310        assert!(map.just_pressed(&input, "jump"));
311        assert!(map.held(&input, "jump"));
312        assert!(!map.held(&input, "unbound_action"));
313    }
314}