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
//! Gamepad input resource.
use std::collections::VecDeque;

use crate::prelude::*;

/// Resource containing the gamepad input events detected this frame.
#[derive(HasSchema, Clone, Default, Debug)]
pub struct GamepadInputs {
    /// The gampad events.
    pub gamepad_events: SVec<GamepadEvent>,
}

/// A gamepad event.
#[derive(HasSchema, Clone, Debug)]
#[repr(C, u8)]
pub enum GamepadEvent {
    /// A connection event.
    Connection(GamepadConnectionEvent),
    /// A button event.
    Button(GamepadButtonEvent),
    /// An axis event.
    Axis(GamepadAxisEvent),
}

impl Default for GamepadEvent {
    fn default() -> Self {
        Self::Connection(default())
    }
}

/// A gamepad connection event.
#[derive(HasSchema, Clone, Debug, Default)]
#[repr(C)]
pub struct GamepadConnectionEvent {
    /// The ID of the gamepad.
    pub gamepad: u32,
    /// The type of connection event.
    pub event: GamepadConnectionEventKind,
}

/// The kind of gamepad connection event.
#[derive(HasSchema, Clone, Debug, Default)]
#[repr(u8)]
pub enum GamepadConnectionEventKind {
    #[default]
    /// The gamepad was connected.
    Connected,
    /// The gamepad was disconnected.
    Disconnected,
}

/// A gamepad button event.
#[derive(HasSchema, Clone, Debug, Default)]
#[repr(C)]
pub struct GamepadButtonEvent {
    /// The ID of the gamepad.
    pub gamepad: u32,
    /// The gamepad button.
    pub button: GamepadButton,
    /// The value of the button, for example, this will be `1.0` when presssed and `0.0` when
    /// released if this is a normal button.
    pub value: f32,
}

/// A specific button on a gamepad.
#[allow(missing_docs)]
#[derive(HasSchema, Clone, Debug, Default, PartialEq, Eq, Hash)]
#[repr(C, u8)]
pub enum GamepadButton {
    #[default]
    South,
    East,
    North,
    West,
    C,
    Z,
    LeftTrigger,
    LeftTrigger2,
    RightTrigger,
    RightTrigger2,
    Select,
    Start,
    Mode,
    LeftThumb,
    RightThumb,
    DPadUp,
    DPadDown,
    DPadLeft,
    DPadRight,
    Other(u8),
}

impl std::fmt::Display for GamepadButton {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                GamepadButton::South => "South",
                GamepadButton::East => "East",
                GamepadButton::North => "North",
                GamepadButton::West => "West",
                GamepadButton::C => "C",
                GamepadButton::Z => "Z",
                GamepadButton::LeftTrigger => "Left Trigger",
                GamepadButton::LeftTrigger2 => "Left Trigger 2",
                GamepadButton::RightTrigger => "Right Trigger",
                GamepadButton::RightTrigger2 => "Right Trigger 2",
                GamepadButton::Select => "Select",
                GamepadButton::Start => "Start",
                GamepadButton::Mode => "Mode",
                GamepadButton::LeftThumb => "Left Thumb",
                GamepadButton::RightThumb => "Right Thumb",
                GamepadButton::DPadUp => "DPad Up",
                GamepadButton::DPadDown => "DPad Down",
                GamepadButton::DPadLeft => "DPad Left",
                GamepadButton::DPadRight => "DPad Right",
                GamepadButton::Other(n) => return write!(f, "Button {n}"),
            }
        )
    }
}

/// A gamepad axis event.
#[derive(HasSchema, Clone, Debug)]
#[schema(no_default)]
#[repr(C)]
pub struct GamepadAxisEvent {
    /// The ID of the gamepad.
    pub gamepad: u32,
    /// The axis that has changed.
    pub axis: GamepadAxis,
    /// The value of the axis.
    pub value: f32,
}

/// A specific gamepad axis that may have changed.
#[derive(HasSchema, Clone, Debug, PartialEq, Eq, Hash)]
#[schema(no_default)]
#[allow(missing_docs)]
#[repr(C, u8)]
pub enum GamepadAxis {
    LeftStickX,
    LeftStickY,
    LeftZ,
    RightStickX,
    RightStickY,
    RightZ,
    Other(u8),
}

impl std::fmt::Display for GamepadAxis {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                GamepadAxis::LeftStickX => "Left Stick X",
                GamepadAxis::LeftStickY => "Left Stick Y",
                GamepadAxis::LeftZ => "Left Z",
                GamepadAxis::RightStickX => "Right Stick X",
                GamepadAxis::RightStickY => "Right Stick Y",
                GamepadAxis::RightZ => "Right Z",
                GamepadAxis::Other(n) => return write!(f, "Axis {n}"),
            }
        )
    }
}

/// Struct that represents intensity of a rumble
#[derive(HasSchema, Default, Clone, Debug, Copy)]
pub struct GamepadRumbleIntensity {
    /// The intensity of the strong motor, between 0.0 - 1.0.
    strong_motor: f32,
    /// The intensity of the weak motor, between 0.0 - 1.0.
    weak_motor: f32,
}

impl GamepadRumbleIntensity {
    /// Represents no rumble intensity.
    pub const ZERO: Self = Self {
        strong_motor: 0.0,
        weak_motor: 0.0,
    };
    /// Represents maximum rumble intensity for both motors.
    pub const MAX_BOTH: Self = Self {
        strong_motor: 1.0,
        weak_motor: 1.0,
    };
    /// Represents maximum rumble intensity for the strong motor only.
    pub const MAX_STRONG: Self = Self {
        strong_motor: 1.0,
        weak_motor: 0.0,
    };
    /// Represents maximum rumble intensity for the weak motor only.
    pub const MAX_WEAK: Self = Self {
        strong_motor: 0.0,
        weak_motor: 1.0,
    };
    /// Represents medium rumble intensity for both motors.
    pub const MEDIUM_BOTH: Self = Self {
        strong_motor: 0.5,
        weak_motor: 0.5,
    };
    /// Represents medium rumble intensity for the strong motor only.
    pub const MEDIUM_STRONG: Self = Self {
        strong_motor: 0.5,
        weak_motor: 0.0,
    };
    /// Represents medium rumble intensity for the weak motor only.
    pub const MEDIUM_WEAK: Self = Self {
        strong_motor: 0.0,
        weak_motor: 0.5,
    };
    /// Represents light rumble intensity for both motors.
    pub const LIGHT_BOTH: Self = Self {
        strong_motor: 0.25,
        weak_motor: 0.25,
    };
    /// Represents light rumble intensity for the strong motor only.
    pub const LIGHT_STRONG: Self = Self {
        strong_motor: 0.25,
        weak_motor: 0.0,
    };
    /// Represents light rumble intensity for the weak motor only.
    pub const LIGHT_WEAK: Self = Self {
        strong_motor: 0.0,
        weak_motor: 0.25,
    };
    /// Represents very light rumble intensity for both motors.
    pub const VERY_LIGHT_BOTH: Self = Self {
        strong_motor: 0.1,
        weak_motor: 0.1,
    };
    /// Represents very light rumble intensity for the strong motor only.
    pub const VERY_LIGHT_STRONG: Self = Self {
        strong_motor: 0.1,
        weak_motor: 0.0,
    };
    /// Represents very light rumble intensity for the weak motor only.
    pub const VERY_LIGHT_WEAK: Self = Self {
        strong_motor: 0.0,
        weak_motor: 0.1,
    };

    /// Get the intensity of the strong motor.
    pub fn strong_motor(&self) -> f32 {
        self.strong_motor
    }

    /// Set the intensity of the strong motor, clamping it between 0.0 and 1.0.
    pub fn set_strong_motor(&mut self, value: f32) {
        self.strong_motor = value.clamp(0.0, 1.0);
    }

    /// Get the intensity of the weak motor.
    pub fn weak_motor(&self) -> f32 {
        self.weak_motor
    }

    /// Set the intensity of the weak motor, clamping it between 0.0 and 1.0.
    pub fn set_weak_motor(&mut self, value: f32) {
        self.weak_motor = value.clamp(0.0, 1.0);
    }
}

/// Represents a request to either add, set, or stop rumble on a specific gamepad
#[derive(HasSchema, Clone, Debug)]
pub enum GamepadRumbleRequest {
    /// Request to add rumble to a gamepad.
    AddRumble {
        /// The ID of the gamepad to rumble.
        gamepad: u32,
        /// The intensity of the rumble.
        intensity: GamepadRumbleIntensity,
        /// The duration of the rumble in seconds.
        duration: f32,
    },
    /// Request to set rumble on a gamepad, replacing any existing rumble.
    SetRumble {
        /// The ID of the gamepad to rumble.
        gamepad: u32,
        /// The intensity of the rumble.
        intensity: GamepadRumbleIntensity,
        /// The duration of the rumble in seconds.
        duration: f32,
    },
    /// Request to stop rumble on a gamepad.
    Stop {
        /// The ID of the gamepad to stop rumbling.
        gamepad: u32,
    },
}

impl Default for GamepadRumbleRequest {
    fn default() -> Self {
        GamepadRumbleRequest::Stop { gamepad: 0 }
    }
}

/// Resource that provides an interface for triggering rumble on connected gamepads
#[derive(HasSchema, Clone)]
pub struct GamepadsRumble {
    /// A queue to hold all the gamepad rumble requests to be processed.
    pub requests: VecDeque<GamepadRumbleRequest>,
    /// A vector to keep track of which gamepads are enabled for rumble.
    enabled_gamepads: SVec<bool>,
}

impl GamepadsRumble {
    /// Adds rumble to a specific gamepad. Ignores if the gamepad is disabled (enabled by default).
    pub fn add_rumble(&mut self, gamepad: u32, intensity: GamepadRumbleIntensity, duration: f32) {
        if self.is_enabled(gamepad) {
            self.requests.push_back(GamepadRumbleRequest::AddRumble {
                gamepad,
                intensity,
                duration,
            });
        }
    }

    /// Sets rumble on a specific gamepad, replacing any existing rumble. Ignores if the gamepad is disabled.
    pub fn set_rumble(&mut self, gamepad: u32, intensity: GamepadRumbleIntensity, duration: f32) {
        if self.is_enabled(gamepad) {
            self.requests.push_back(GamepadRumbleRequest::SetRumble {
                gamepad,
                intensity,
                duration,
            });
        }
    }

    /// Stops rumble on a specific gamepad.
    pub fn stop(&mut self, gamepad: u32) {
        if self.is_enabled(gamepad) {
            self.requests
                .push_back(GamepadRumbleRequest::Stop { gamepad });
        }
    }

    /// Adds rumble to all enabled gamepads.
    pub fn add_rumble_all(&mut self, intensity: GamepadRumbleIntensity, duration: f32) {
        for gamepad in 0..self.enabled_gamepads.len() {
            if self.is_enabled(gamepad as u32) {
                self.add_rumble(gamepad as u32, intensity, duration);
            }
        }
    }

    /// Sets rumble on all enabled gamepads, replacing any existing rumble.
    pub fn set_rumble_all(&mut self, intensity: GamepadRumbleIntensity, duration: f32) {
        for gamepad in 0..self.enabled_gamepads.len() {
            if self.is_enabled(gamepad as u32) {
                self.set_rumble(gamepad as u32, intensity, duration);
            }
        }
    }

    /// Stops rumble on all enabled gamepads.
    pub fn stop_all(&mut self) {
        for gamepad in 0..self.enabled_gamepads.len() {
            if self.is_enabled(gamepad as u32) {
                self.stop(gamepad as u32);
            }
        }
    }

    /// Checks if a specific gamepad is enabled for rumble.
    pub fn is_enabled(&self, gamepad: u32) -> bool {
        let gamepad_index = gamepad as usize;
        if gamepad_index < self.enabled_gamepads.len() {
            self.enabled_gamepads[gamepad_index]
        } else {
            false
        }
    }

    /// Checks if a specific gamepad is disabled for rumble (no rumble requests will work).
    pub fn is_disabled(&self, gamepad: u32) -> bool {
        !self.is_enabled(gamepad)
    }

    /// Re-enables rumble for a specific gamepad.
    pub fn enable(&mut self, gamepad: u32) {
        if let Some(enabled) = self.enabled_gamepads.get_mut(gamepad as usize) {
            *enabled = true;
        }
    }

    /// Disables rumble for a specific gamepad (no rumble requests will work).
    pub fn disable(&mut self, gamepad: u32) {
        self.stop(gamepad);
        if let Some(enabled) = self.enabled_gamepads.get_mut(gamepad as usize) {
            *enabled = false;
        }
    }

    /// Enables rumble for all gamepads.
    pub fn enable_all(&mut self) {
        for gamepad in 0..self.enabled_gamepads.len() {
            self.enable(gamepad as u32);
        }
    }

    /// Disables rumble for all gamepads (no rumble requests will work).
    pub fn disable_all(&mut self) {
        for gamepad in 0..self.enabled_gamepads.len() {
            self.disable(gamepad as u32);
        }
    }
}

impl Default for GamepadsRumble {
    fn default() -> Self {
        GamepadsRumble {
            requests: VecDeque::new(),
            enabled_gamepads: vec![true; 4].into(),
        }
    }
}