1use 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#[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#[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 #[must_use]
81 pub fn mouse_motion(&self) -> [f32; 2] {
82 self.mouse_motion
83 }
84
85 #[must_use]
87 pub fn cursor_captured(&self) -> bool {
88 self.cursor_captured
89 }
90
91 pub fn set_cursor_captured(&mut self, captured: bool) {
94 self.cursor_captured = captured;
95 }
96
97 #[must_use]
100 pub fn viewport_size(&self) -> [f32; 2] {
101 self.viewport_size
102 }
103
104 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 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 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 pub fn record_cursor_position(&mut self, position: [f32; 2]) {
137 self.cursor_position = Some(position);
138 }
139 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 pub fn record_viewport_size(&mut self, size: [f32; 2]) {
146 self.viewport_size = size;
147 }
148
149 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
166pub enum InputBinding {
167 Key(KeyCode),
168 Mouse(MouseButton),
169}
170
171#[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 #[must_use]
191 pub fn held(&self, input: &RuntimeInput, action: &str) -> bool {
192 self.bindings_for(action).any(|binding| match binding {
193 InputBinding::Key(key) => input.key_held(*key),
194 InputBinding::Mouse(button) => input.mouse_held(*button),
195 })
196 }
197 #[must_use]
198 pub fn just_pressed(&self, input: &RuntimeInput, action: &str) -> bool {
199 self.bindings_for(action).any(|binding| match binding {
200 InputBinding::Key(key) => input.key_just_pressed(*key),
201 InputBinding::Mouse(button) => input.mouse_just_pressed(*button),
202 })
203 }
204 #[must_use]
205 pub fn just_released(&self, input: &RuntimeInput, action: &str) -> bool {
206 self.bindings_for(action).any(|binding| match binding {
207 InputBinding::Key(key) => input.key_just_released(*key),
208 InputBinding::Mouse(button) => input.mouse_just_released(*button),
209 })
210 }
211 #[must_use]
213 pub fn bindings(&self, action: &str) -> &[InputBinding] {
214 self.bindings.get(action).map_or(&[], Vec::as_slice)
215 }
216 fn bindings_for(
217 &self,
218 action: &str,
219 ) -> impl Iterator<Item = &InputBinding> {
220 self.bindings.get(action).into_iter().flatten()
221 }
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227 use bevy_ecs::prelude::Resource;
228
229 #[test]
230 fn mouse_motion_adds_up_until_the_frame_ends() {
231 let mut input = RuntimeInput::default();
232 input.record_mouse_motion([1.0, -2.0]);
233 input.record_mouse_motion([0.5, 1.0]);
234 assert_eq!(input.mouse_motion(), [1.5, -1.0]);
235 input.clear_frame_edges();
236 assert_eq!(input.mouse_motion(), [0.0, 0.0]);
237 }
238
239 #[test]
240 fn release_all_clears_held_input_as_releases() {
241 let mut input = RuntimeInput::default();
242 input.record_key(KeyCode::KeyW, true);
243 input.record_mouse_button(MouseButton::Right, true);
244 input.clear_frame_edges();
245 input.release_all();
246 assert!(!input.key_held(KeyCode::KeyW));
247 assert!(input.key_just_released(KeyCode::KeyW));
248 assert!(input.mouse_just_released(MouseButton::Right));
249 }
250
251 #[test]
252 fn runtime_input_and_action_map_are_ecs_resources() {
253 fn assert_resource<T: Resource>() {}
254 assert_resource::<RuntimeInput>();
255 assert_resource::<ActionMap>();
256 }
257 #[test]
258 fn keyboard_edges_and_auto_repeat_are_tracked() {
259 let mut input = RuntimeInput::default();
260 input.record_key(KeyCode::Space, true);
261 assert!(input.key_held(KeyCode::Space));
262 assert!(input.key_just_pressed(KeyCode::Space));
263 input.record_key(KeyCode::Space, true);
264 input.clear_frame_edges();
265 assert!(input.key_held(KeyCode::Space));
266 assert!(!input.key_just_pressed(KeyCode::Space));
267 input.record_key(KeyCode::Space, false);
268 assert!(input.key_just_released(KeyCode::Space));
269 }
270 #[test]
271 fn mouse_cursor_and_viewport_are_tracked() {
272 let mut input = RuntimeInput::default();
273 input.record_mouse_button(MouseButton::Left, true);
274 input.record_cursor_position([12.0, 34.0]);
275 input.record_viewport_size([800.0, 600.0]);
276 assert!(input.mouse_held(MouseButton::Left));
277 assert!(input.mouse_just_pressed(MouseButton::Left));
278 assert_eq!(input.cursor_position(), Some([12.0, 34.0]));
279 assert_eq!(input.viewport_size(), [800.0, 600.0]);
280 input.clear_frame_edges();
281 input.record_mouse_button(MouseButton::Left, false);
282 assert!(input.mouse_just_released(MouseButton::Left));
283 assert!(!input.mouse_held(MouseButton::Left));
284 }
285 #[test]
286 fn actions_cover_keyboard_mouse_and_edge_clearing() {
287 let mut map = ActionMap::default();
288 map.bind("jump", InputBinding::Key(KeyCode::Space))
289 .bind("jump", InputBinding::Mouse(MouseButton::Left));
290 let mut input = RuntimeInput::default();
291 input.record_key(KeyCode::Space, true);
292 assert!(map.just_pressed(&input, "jump"));
293 assert!(map.held(&input, "jump"));
294 input.clear_frame_edges();
295 assert!(!map.just_pressed(&input, "jump"));
296 assert!(map.held(&input, "jump"));
297 input.record_key(KeyCode::Space, false);
298 assert!(map.just_released(&input, "jump"));
299 input.clear_frame_edges();
300 input.record_mouse_button(MouseButton::Left, true);
301 assert!(map.just_pressed(&input, "jump"));
302 assert!(map.held(&input, "jump"));
303 assert!(!map.held(&input, "unbound_action"));
304 }
305}