1use std::collections::{HashMap, HashSet};
8
9use bevy_ecs::prelude::Resource;
10pub use winit::event::MouseButton;
11pub use winit::keyboard::KeyCode;
12
13#[derive(Resource, Default)]
21pub struct RuntimeInput {
22 keys_held: HashSet<KeyCode>,
23 keys_just_pressed: HashSet<KeyCode>,
24 keys_just_released: HashSet<KeyCode>,
25 mouse_held: HashSet<MouseButton>,
26 mouse_just_pressed: HashSet<MouseButton>,
27 mouse_just_released: HashSet<MouseButton>,
28 cursor_position: Option<[f32; 2]>,
29 viewport_size: [f32; 2],
30}
31
32impl RuntimeInput {
33 #[must_use]
34 pub fn key_held(&self, key: KeyCode) -> bool {
35 self.keys_held.contains(&key)
36 }
37 #[must_use]
38 pub fn key_just_pressed(&self, key: KeyCode) -> bool {
39 self.keys_just_pressed.contains(&key)
40 }
41 #[must_use]
42 pub fn key_just_released(&self, key: KeyCode) -> bool {
43 self.keys_just_released.contains(&key)
44 }
45 #[must_use]
46 pub fn mouse_held(&self, button: MouseButton) -> bool {
47 self.mouse_held.contains(&button)
48 }
49 #[must_use]
50 pub fn mouse_just_pressed(&self, button: MouseButton) -> bool {
51 self.mouse_just_pressed.contains(&button)
52 }
53 #[must_use]
54 pub fn mouse_just_released(&self, button: MouseButton) -> bool {
55 self.mouse_just_released.contains(&button)
56 }
57 #[must_use]
58 pub fn cursor_position(&self) -> Option<[f32; 2]> {
59 self.cursor_position
60 }
61
62 #[must_use]
65 pub fn viewport_size(&self) -> [f32; 2] {
66 self.viewport_size
67 }
68
69 pub fn record_key(&mut self, key: KeyCode, pressed: bool) {
72 if pressed {
73 if self.keys_held.insert(key) {
74 self.keys_just_pressed.insert(key);
75 }
76 } else if self.keys_held.remove(&key) {
77 self.keys_just_released.insert(key);
78 }
79 }
80
81 pub fn record_mouse_button(&mut self, button: MouseButton, pressed: bool) {
83 if pressed {
84 if self.mouse_held.insert(button) {
85 self.mouse_just_pressed.insert(button);
86 }
87 } else if self.mouse_held.remove(&button) {
88 self.mouse_just_released.insert(button);
89 }
90 }
91
92 pub fn release_all(&mut self) {
96 self.keys_just_released.extend(self.keys_held.drain());
97 self.mouse_just_released.extend(self.mouse_held.drain());
98 }
99
100 pub fn record_cursor_position(&mut self, position: [f32; 2]) {
102 self.cursor_position = Some(position);
103 }
104 pub fn record_viewport_size(&mut self, size: [f32; 2]) {
106 self.viewport_size = size;
107 }
108
109 pub fn clear_frame_edges(&mut self) {
113 self.keys_just_pressed.clear();
114 self.keys_just_released.clear();
115 self.mouse_just_pressed.clear();
116 self.mouse_just_released.clear();
117 }
118}
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
125pub enum InputBinding {
126 Key(KeyCode),
127 Mouse(MouseButton),
128}
129
130#[derive(Resource, Default)]
133pub struct ActionMap {
134 bindings: HashMap<String, Vec<InputBinding>>,
135}
136
137impl ActionMap {
138 pub fn bind(
139 &mut self,
140 action: impl Into<String>,
141 binding: InputBinding,
142 ) -> &mut Self {
143 self.bindings
144 .entry(action.into())
145 .or_default()
146 .push(binding);
147 self
148 }
149 #[must_use]
150 pub fn held(&self, input: &RuntimeInput, action: &str) -> bool {
151 self.bindings_for(action).any(|binding| match binding {
152 InputBinding::Key(key) => input.key_held(*key),
153 InputBinding::Mouse(button) => input.mouse_held(*button),
154 })
155 }
156 #[must_use]
157 pub fn just_pressed(&self, input: &RuntimeInput, action: &str) -> bool {
158 self.bindings_for(action).any(|binding| match binding {
159 InputBinding::Key(key) => input.key_just_pressed(*key),
160 InputBinding::Mouse(button) => input.mouse_just_pressed(*button),
161 })
162 }
163 #[must_use]
164 pub fn just_released(&self, input: &RuntimeInput, action: &str) -> bool {
165 self.bindings_for(action).any(|binding| match binding {
166 InputBinding::Key(key) => input.key_just_released(*key),
167 InputBinding::Mouse(button) => input.mouse_just_released(*button),
168 })
169 }
170 fn bindings_for(
171 &self,
172 action: &str,
173 ) -> impl Iterator<Item = &InputBinding> {
174 self.bindings.get(action).into_iter().flatten()
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181 use bevy_ecs::prelude::Resource;
182
183 #[test]
184 fn release_all_clears_held_input_as_releases() {
185 let mut input = RuntimeInput::default();
186 input.record_key(KeyCode::KeyW, true);
187 input.record_mouse_button(MouseButton::Right, true);
188 input.clear_frame_edges();
189 input.release_all();
190 assert!(!input.key_held(KeyCode::KeyW));
191 assert!(input.key_just_released(KeyCode::KeyW));
192 assert!(input.mouse_just_released(MouseButton::Right));
193 }
194
195 #[test]
196 fn runtime_input_and_action_map_are_ecs_resources() {
197 fn assert_resource<T: Resource>() {}
198 assert_resource::<RuntimeInput>();
199 assert_resource::<ActionMap>();
200 }
201 #[test]
202 fn keyboard_edges_and_auto_repeat_are_tracked() {
203 let mut input = RuntimeInput::default();
204 input.record_key(KeyCode::Space, true);
205 assert!(input.key_held(KeyCode::Space));
206 assert!(input.key_just_pressed(KeyCode::Space));
207 input.record_key(KeyCode::Space, true);
208 input.clear_frame_edges();
209 assert!(input.key_held(KeyCode::Space));
210 assert!(!input.key_just_pressed(KeyCode::Space));
211 input.record_key(KeyCode::Space, false);
212 assert!(input.key_just_released(KeyCode::Space));
213 }
214 #[test]
215 fn mouse_cursor_and_viewport_are_tracked() {
216 let mut input = RuntimeInput::default();
217 input.record_mouse_button(MouseButton::Left, true);
218 input.record_cursor_position([12.0, 34.0]);
219 input.record_viewport_size([800.0, 600.0]);
220 assert!(input.mouse_held(MouseButton::Left));
221 assert!(input.mouse_just_pressed(MouseButton::Left));
222 assert_eq!(input.cursor_position(), Some([12.0, 34.0]));
223 assert_eq!(input.viewport_size(), [800.0, 600.0]);
224 input.clear_frame_edges();
225 input.record_mouse_button(MouseButton::Left, false);
226 assert!(input.mouse_just_released(MouseButton::Left));
227 assert!(!input.mouse_held(MouseButton::Left));
228 }
229 #[test]
230 fn actions_cover_keyboard_mouse_and_edge_clearing() {
231 let mut map = ActionMap::default();
232 map.bind("jump", InputBinding::Key(KeyCode::Space))
233 .bind("jump", InputBinding::Mouse(MouseButton::Left));
234 let mut input = RuntimeInput::default();
235 input.record_key(KeyCode::Space, true);
236 assert!(map.just_pressed(&input, "jump"));
237 assert!(map.held(&input, "jump"));
238 input.clear_frame_edges();
239 assert!(!map.just_pressed(&input, "jump"));
240 assert!(map.held(&input, "jump"));
241 input.record_key(KeyCode::Space, false);
242 assert!(map.just_released(&input, "jump"));
243 input.clear_frame_edges();
244 input.record_mouse_button(MouseButton::Left, true);
245 assert!(map.just_pressed(&input, "jump"));
246 assert!(map.held(&input, "jump"));
247 assert!(!map.held(&input, "unbound_action"));
248 }
249}