bevy_archie 0.2.1

A comprehensive game controller support module for Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
//! Input action mapping system.
//!
//! This module provides an abstraction layer over raw input,
//! allowing games to define logical actions that can be bound
//! to various input sources.

use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Predefined game actions that can be mapped to inputs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Reflect)]
pub enum GameAction {
    // Navigation
    /// Confirm/select action (A button, Enter key)
    Confirm,
    /// Cancel/back action (B button, Escape key)
    Cancel,
    /// Pause/menu action (Start button)
    Pause,
    /// Secondary menu action (Select button)
    Select,

    // Movement
    /// Move up
    Up,
    /// Move down
    Down,
    /// Move left
    Left,
    /// Move right
    Right,

    // Camera/View
    /// Look up
    LookUp,
    /// Look down
    LookDown,
    /// Look left
    LookLeft,
    /// Look right
    LookRight,

    // Actions
    /// Primary action (X button)
    Primary,
    /// Secondary action (Y button)
    Secondary,
    /// Left shoulder button
    LeftShoulder,
    /// Right shoulder button
    RightShoulder,
    /// Left trigger
    LeftTrigger,
    /// Right trigger
    RightTrigger,

    // UI Navigation
    /// Page left (in menus)
    PageLeft,
    /// Page right (in menus)
    PageRight,

    // Custom actions (use these for game-specific bindings)
    /// Custom action slot 1
    Custom1,
    /// Custom action slot 2
    Custom2,
    /// Custom action slot 3
    Custom3,
    /// Custom action slot 4
    Custom4,
}

impl GameAction {
    /// Get all actions as a slice.
    #[must_use]
    pub fn all() -> &'static [GameAction] {
        &[
            Self::Confirm,
            Self::Cancel,
            Self::Pause,
            Self::Select,
            Self::Up,
            Self::Down,
            Self::Left,
            Self::Right,
            Self::LookUp,
            Self::LookDown,
            Self::LookLeft,
            Self::LookRight,
            Self::Primary,
            Self::Secondary,
            Self::LeftShoulder,
            Self::RightShoulder,
            Self::LeftTrigger,
            Self::RightTrigger,
            Self::PageLeft,
            Self::PageRight,
            Self::Custom1,
            Self::Custom2,
            Self::Custom3,
            Self::Custom4,
        ]
    }

    /// Get the display name for this action.
    #[must_use]
    pub const fn display_name(self) -> &'static str {
        match self {
            Self::Confirm => "Confirm",
            Self::Cancel => "Cancel",
            Self::Pause => "Pause",
            Self::Select => "Select",
            Self::Up => "Up",
            Self::Down => "Down",
            Self::Left => "Left",
            Self::Right => "Right",
            Self::LookUp => "Look Up",
            Self::LookDown => "Look Down",
            Self::LookLeft => "Look Left",
            Self::LookRight => "Look Right",
            Self::Primary => "Primary Action",
            Self::Secondary => "Secondary Action",
            Self::LeftShoulder => "Left Shoulder",
            Self::RightShoulder => "Right Shoulder",
            Self::LeftTrigger => "Left Trigger",
            Self::RightTrigger => "Right Trigger",
            Self::PageLeft => "Page Left",
            Self::PageRight => "Page Right",
            Self::Custom1 => "Custom 1",
            Self::Custom2 => "Custom 2",
            Self::Custom3 => "Custom 3",
            Self::Custom4 => "Custom 4",
        }
    }

    /// Whether this action can be remapped by the player.
    #[must_use]
    pub const fn is_remappable(self) -> bool {
        !matches!(self, Self::Pause) // Pause is usually not remappable
    }

    /// Whether this action requires a binding (cannot be unbound).
    #[must_use]
    pub const fn is_required(self) -> bool {
        matches!(self, Self::Confirm | Self::Cancel | Self::Pause)
    }
}

/// A binding source for an action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InputBinding {
    /// A gamepad button
    GamepadButton(GamepadButton),
    /// A gamepad axis (with direction)
    GamepadAxis(GamepadAxis, AxisDirection),
    /// A keyboard key
    Key(KeyCode),
    /// A mouse button
    MouseButton(MouseButton),
}

/// Direction for axis bindings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AxisDirection {
    /// Positive direction (right, up)
    Positive,
    /// Negative direction (left, down)
    Negative,
}

/// Resource containing action-to-input mappings.
#[derive(Debug, Clone, Resource, Serialize, Deserialize, Reflect)]
#[reflect(Resource)]
pub struct ActionMap {
    /// Gamepad button bindings
    #[reflect(ignore)]
    #[serde(skip)]
    pub gamepad_bindings: HashMap<GameAction, Vec<GamepadButton>>,

    /// Gamepad axis bindings (action -> (axis, direction, threshold))
    #[reflect(ignore)]
    #[serde(skip)]
    pub axis_bindings: HashMap<GameAction, Vec<(GamepadAxis, AxisDirection, f32)>>,

    /// Keyboard bindings
    #[reflect(ignore)]
    #[serde(skip)]
    pub key_bindings: HashMap<GameAction, Vec<KeyCode>>,

    /// Mouse button bindings
    #[reflect(ignore)]
    #[serde(skip)]
    pub mouse_bindings: HashMap<GameAction, Vec<MouseButton>>,
}

impl Default for ActionMap {
    fn default() -> Self {
        let mut map = Self {
            gamepad_bindings: HashMap::new(),
            axis_bindings: HashMap::new(),
            key_bindings: HashMap::new(),
            mouse_bindings: HashMap::new(),
        };

        // Default gamepad bindings
        map.bind_gamepad(GameAction::Confirm, GamepadButton::South);
        map.bind_gamepad(GameAction::Cancel, GamepadButton::East);
        map.bind_gamepad(GameAction::Pause, GamepadButton::Start);
        map.bind_gamepad(GameAction::Select, GamepadButton::Select);
        map.bind_gamepad(GameAction::Primary, GamepadButton::West);
        map.bind_gamepad(GameAction::Secondary, GamepadButton::North);
        map.bind_gamepad(GameAction::LeftShoulder, GamepadButton::LeftTrigger);
        map.bind_gamepad(GameAction::RightShoulder, GamepadButton::RightTrigger);
        map.bind_gamepad(GameAction::LeftTrigger, GamepadButton::LeftTrigger2);
        map.bind_gamepad(GameAction::RightTrigger, GamepadButton::RightTrigger2);
        map.bind_gamepad(GameAction::PageLeft, GamepadButton::LeftTrigger);
        map.bind_gamepad(GameAction::PageRight, GamepadButton::RightTrigger);

        // D-pad bindings
        map.bind_gamepad(GameAction::Up, GamepadButton::DPadUp);
        map.bind_gamepad(GameAction::Down, GamepadButton::DPadDown);
        map.bind_gamepad(GameAction::Left, GamepadButton::DPadLeft);
        map.bind_gamepad(GameAction::Right, GamepadButton::DPadRight);

        // Left stick axis bindings
        map.bind_axis(
            GameAction::Up,
            GamepadAxis::LeftStickY,
            AxisDirection::Positive,
            0.5,
        );
        map.bind_axis(
            GameAction::Down,
            GamepadAxis::LeftStickY,
            AxisDirection::Negative,
            0.5,
        );
        map.bind_axis(
            GameAction::Left,
            GamepadAxis::LeftStickX,
            AxisDirection::Negative,
            0.5,
        );
        map.bind_axis(
            GameAction::Right,
            GamepadAxis::LeftStickX,
            AxisDirection::Positive,
            0.5,
        );

        // Right stick for looking
        map.bind_axis(
            GameAction::LookUp,
            GamepadAxis::RightStickY,
            AxisDirection::Positive,
            0.5,
        );
        map.bind_axis(
            GameAction::LookDown,
            GamepadAxis::RightStickY,
            AxisDirection::Negative,
            0.5,
        );
        map.bind_axis(
            GameAction::LookLeft,
            GamepadAxis::RightStickX,
            AxisDirection::Negative,
            0.5,
        );
        map.bind_axis(
            GameAction::LookRight,
            GamepadAxis::RightStickX,
            AxisDirection::Positive,
            0.5,
        );

        // Default keyboard bindings
        map.bind_key(GameAction::Confirm, KeyCode::Enter);
        map.bind_key(GameAction::Confirm, KeyCode::Space);
        map.bind_key(GameAction::Cancel, KeyCode::Escape);
        map.bind_key(GameAction::Pause, KeyCode::Escape);
        map.bind_key(GameAction::Up, KeyCode::ArrowUp);
        map.bind_key(GameAction::Up, KeyCode::KeyW);
        map.bind_key(GameAction::Down, KeyCode::ArrowDown);
        map.bind_key(GameAction::Down, KeyCode::KeyS);
        map.bind_key(GameAction::Left, KeyCode::ArrowLeft);
        map.bind_key(GameAction::Left, KeyCode::KeyA);
        map.bind_key(GameAction::Right, KeyCode::ArrowRight);
        map.bind_key(GameAction::Right, KeyCode::KeyD);
        map.bind_key(GameAction::PageLeft, KeyCode::KeyQ);
        map.bind_key(GameAction::PageRight, KeyCode::KeyE);

        map
    }
}

impl ActionMap {
    /// Bind a gamepad button to an action.
    pub fn bind_gamepad(&mut self, action: GameAction, button: GamepadButton) {
        self.gamepad_bindings
            .entry(action)
            .or_default()
            .push(button);
    }

    /// Bind a gamepad axis to an action.
    pub fn bind_axis(
        &mut self,
        action: GameAction,
        axis: GamepadAxis,
        direction: AxisDirection,
        threshold: f32,
    ) {
        self.axis_bindings
            .entry(action)
            .or_default()
            .push((axis, direction, threshold));
    }

    /// Bind a keyboard key to an action.
    pub fn bind_key(&mut self, action: GameAction, key: KeyCode) {
        self.key_bindings.entry(action).or_default().push(key);
    }

    /// Bind a mouse button to an action.
    pub fn bind_mouse(&mut self, action: GameAction, button: MouseButton) {
        self.mouse_bindings.entry(action).or_default().push(button);
    }

    /// Clear all bindings for an action.
    pub fn clear_bindings(&mut self, action: GameAction) {
        self.gamepad_bindings.remove(&action);
        self.axis_bindings.remove(&action);
        self.key_bindings.remove(&action);
        self.mouse_bindings.remove(&action);
    }

    /// Clear only gamepad bindings for an action.
    pub fn clear_gamepad_bindings(&mut self, action: GameAction) {
        self.gamepad_bindings.remove(&action);
        self.axis_bindings.remove(&action);
    }

    /// Get the primary gamepad button for an action (for icon display).
    #[must_use]
    pub fn primary_gamepad_button(&self, action: GameAction) -> Option<GamepadButton> {
        self.gamepad_bindings
            .get(&action)
            .and_then(|buttons| buttons.first().copied())
    }
}

/// Resource tracking the current state of all actions.
#[derive(Debug, Clone, Default, Resource, Reflect)]
#[reflect(Resource)]
pub struct ActionState {
    /// Actions that are currently pressed.
    #[reflect(ignore)]
    pressed: HashMap<GameAction, bool>,

    /// Actions that were just pressed this frame.
    #[reflect(ignore)]
    just_pressed: HashMap<GameAction, bool>,

    /// Actions that were just released this frame.
    #[reflect(ignore)]
    just_released: HashMap<GameAction, bool>,

    /// Analog values for actions (0.0 - 1.0).
    #[reflect(ignore)]
    values: HashMap<GameAction, f32>,
}

impl ActionState {
    /// Check if an action is currently pressed.
    #[must_use]
    pub fn pressed(&self, action: GameAction) -> bool {
        self.pressed.get(&action).copied().unwrap_or(false)
    }

    /// Check if an action was just pressed this frame.
    #[must_use]
    pub fn just_pressed(&self, action: GameAction) -> bool {
        self.just_pressed.get(&action).copied().unwrap_or(false)
    }

    /// Check if an action was just released this frame.
    #[must_use]
    pub fn just_released(&self, action: GameAction) -> bool {
        self.just_released.get(&action).copied().unwrap_or(false)
    }

    /// Get the analog value of an action (0.0 - 1.0).
    #[must_use]
    pub fn value(&self, action: GameAction) -> f32 {
        self.values.get(&action).copied().unwrap_or(0.0)
    }

    /// Reset `just_pressed` and `just_released` flags.
    pub(crate) fn reset_frame_state(&mut self) {
        self.just_pressed.clear();
        self.just_released.clear();
    }

    /// Set an action's pressed state.
    pub(crate) fn set_pressed(&mut self, action: GameAction, pressed: bool) {
        let was_pressed = self.pressed.get(&action).copied().unwrap_or(false);

        if pressed && !was_pressed {
            self.just_pressed.insert(action, true);
        } else if !pressed && was_pressed {
            self.just_released.insert(action, true);
        }

        self.pressed.insert(action, pressed);
    }

    /// Set an action's analog value.
    pub(crate) fn set_value(&mut self, action: GameAction, value: f32) {
        self.values.insert(action, value.clamp(0.0, 1.0));
    }
}

/// System to update action states from input.
pub fn update_action_state(
    mut state: ResMut<ActionState>,
    action_map: Res<ActionMap>,
    keyboard: Res<ButtonInput<KeyCode>>,
    mouse_buttons: Res<ButtonInput<MouseButton>>,
    gamepads: Query<&Gamepad>,
) {
    // Reset frame state
    state.reset_frame_state();

    // Check all actions
    for action in GameAction::all() {
        let mut pressed = false;
        let mut value = 0.0f32;

        // Check keyboard bindings
        if let Some(keys) = action_map.key_bindings.get(action) {
            for key in keys {
                if keyboard.pressed(*key) {
                    pressed = true;
                    value = 1.0;
                    break;
                }
            }
        }

        // Check mouse bindings
        if !pressed && let Some(buttons) = action_map.mouse_bindings.get(action) {
            for button in buttons {
                if mouse_buttons.pressed(*button) {
                    pressed = true;
                    value = 1.0;
                    break;
                }
            }
        }

        // Check gamepad bindings
        if !pressed {
            for gamepad in gamepads.iter() {
                // Check button bindings
                if let Some(buttons) = action_map.gamepad_bindings.get(action) {
                    for button_type in buttons {
                        if gamepad.pressed(*button_type) {
                            pressed = true;
                            value = 1.0;
                            break;
                        }
                    }
                }

                // Check axis bindings
                if !pressed && let Some(axes) = action_map.axis_bindings.get(action) {
                    for (axis_type, direction, threshold) in axes {
                        if let Some(axis_value) = gamepad.get(*axis_type) {
                            let check_value = match direction {
                                AxisDirection::Positive => axis_value,
                                AxisDirection::Negative => -axis_value,
                            };

                            if check_value > *threshold {
                                pressed = true;
                                value = value.max(check_value);
                            }
                        }
                    }
                }

                if pressed {
                    break;
                }
            }
        }

        state.set_pressed(*action, pressed);
        state.set_value(*action, value);
    }
}

/// Plugin for registering action types and systems.
pub(crate) fn register_action_types(app: &mut App) {
    app.register_type::<GameAction>()
        .register_type::<ActionMap>()
        .register_type::<ActionState>()
        .init_resource::<ActionMap>()
        .init_resource::<ActionState>();
}

/// Add action systems to the app.
pub(crate) fn add_action_systems(app: &mut App) {
    app.add_systems(PreUpdate, update_action_state);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_game_action_all_contains_all_variants() {
        let all_actions = GameAction::all();
        assert!(all_actions.contains(&GameAction::Confirm));
        assert!(all_actions.contains(&GameAction::Cancel));
        assert!(all_actions.contains(&GameAction::Custom4));
        assert_eq!(all_actions.len(), 24);
    }

    #[test]
    fn test_game_action_display_names() {
        assert_eq!(GameAction::Confirm.display_name(), "Confirm");
        assert_eq!(GameAction::LeftTrigger.display_name(), "Left Trigger");
        assert_eq!(GameAction::Custom1.display_name(), "Custom 1");
    }

    #[test]
    fn test_game_action_remappable() {
        assert!(GameAction::Confirm.is_remappable());
        assert!(GameAction::Primary.is_remappable());
        // Pause is typically not remappable (system action)
        assert!(!GameAction::Pause.is_remappable());
    }

    #[test]
    fn test_game_action_required() {
        assert!(GameAction::Confirm.is_required());
        assert!(GameAction::Cancel.is_required());
        assert!(!GameAction::Custom1.is_required());
        assert!(!GameAction::Custom4.is_required());
    }

    #[test]
    fn test_action_binding_new() {
        let binding = InputBinding::GamepadButton(GamepadButton::South);
        assert!(matches!(binding, InputBinding::GamepadButton(_)));
    }

    #[test]
    fn test_action_binding_matches_button() {
        let binding = InputBinding::GamepadButton(GamepadButton::South);
        if let InputBinding::GamepadButton(btn) = binding {
            assert_eq!(btn, GamepadButton::South);
        }
    }

    #[test]
    fn test_action_binding_matches_key() {
        let binding = InputBinding::Key(KeyCode::Space);
        if let InputBinding::Key(key) = binding {
            assert_eq!(key, KeyCode::Space);
        }
    }

    #[test]
    fn test_action_map_default_bindings() {
        let map = ActionMap::default();

        // Check that default bindings exist for core actions
        assert!(map.primary_gamepad_button(GameAction::Confirm).is_some());
        assert!(map.primary_gamepad_button(GameAction::Cancel).is_some());
    }

    #[test]
    fn test_action_map_bind_gamepad() {
        let mut map = ActionMap::default();
        map.bind_gamepad(GameAction::Custom1, GamepadButton::West);

        let button = map.primary_gamepad_button(GameAction::Custom1);
        assert_eq!(button, Some(GamepadButton::West));
    }

    #[test]
    fn test_action_map_bind_key() {
        let mut map = ActionMap::default();
        map.bind_key(GameAction::Custom2, KeyCode::KeyG);

        let bindings = &map.key_bindings[&GameAction::Custom2];
        assert!(bindings.contains(&KeyCode::KeyG));
    }

    #[test]
    fn test_action_map_bind_mouse() {
        let mut map = ActionMap::default();
        map.bind_mouse(GameAction::Primary, MouseButton::Left);

        assert!(map.mouse_bindings.contains_key(&GameAction::Primary));
    }

    #[test]
    fn test_action_map_clear_bindings() {
        let mut map = ActionMap::default();
        map.bind_key(GameAction::Custom3, KeyCode::KeyH);

        map.clear_bindings(GameAction::Custom3);
        // After clearing, the action should have no bindings
        assert!(
            map.key_bindings
                .get(&GameAction::Custom3)
                .map_or(true, |v| v.is_empty())
        );
    }

    #[test]
    fn test_action_state_pressed() {
        let mut state = ActionState::default();

        state.set_pressed(GameAction::Confirm, true);
        assert!(state.pressed(GameAction::Confirm));
        assert!(!state.pressed(GameAction::Cancel));
    }

    #[test]
    fn test_action_state_just_pressed() {
        let mut state = ActionState::default();

        state.just_pressed.insert(GameAction::Primary, true);
        assert!(state.just_pressed(GameAction::Primary));
        assert!(!state.just_pressed(GameAction::Secondary));
    }

    #[test]
    fn test_action_state_just_released() {
        let mut state = ActionState::default();

        state.just_released.insert(GameAction::LeftShoulder, true);
        assert!(state.just_released(GameAction::LeftShoulder));
        assert!(!state.just_released(GameAction::RightShoulder));
    }

    #[test]
    fn test_action_state_value() {
        let mut state = ActionState::default();

        state.set_value(GameAction::LeftTrigger, 0.75);
        assert_eq!(state.value(GameAction::LeftTrigger), 0.75);
        assert_eq!(state.value(GameAction::RightTrigger), 0.0);
    }

    #[test]
    fn test_action_state_set_pressed_updates_state() {
        let mut state = ActionState::default();

        // First press should set pressed
        state.set_pressed(GameAction::Confirm, true);
        assert!(state.pressed(GameAction::Confirm));

        // Release should clear pressed
        state.set_pressed(GameAction::Confirm, false);
        assert!(!state.pressed(GameAction::Confirm));
    }

    #[test]
    fn test_axis_direction_variants() {
        let pos = AxisDirection::Positive;
        let neg = AxisDirection::Negative;
        assert_ne!(pos, neg);
    }
}