| 1 | use std::cell::RefCell; |
| 2 | use sdl2::haptic::Haptic; |
| 3 | use sdl2::HapticSubsystem; |
| 4 | use sdl2::GameControllerSubsystem; |
| 5 | use sdl2::event::Event; |
| 6 | use sdl2::controller::GameController; |
| 7 | use std::rc::Rc; |
| 8 | |
| 9 | //#[derive(Debug)] |
| 10 | pub struct ControllerManager { |
| 11 | ctrl: GameControllerSubsystem, |
| 12 | haptic: Rc<HapticSubsystem>, |
| 13 | pub controllers: Vec<Rc<Controller>>, |
| 14 | } |
| 15 | |
| 16 | //#[derive(Debug)] |
| 17 | pub struct Controller { |
| 18 | id: u32, |
| 19 | pub ctrl: GameController, |
| 20 | haptic: Option<Rc<RefCell<Haptic>>>, |
| 21 | } |
| 22 | |
| 23 | impl ControllerManager { |
| 24 | pub fn new(ctrl: GameControllerSubsystem, haptic: HapticSubsystem) -> Self { |
| 25 | ControllerManager { |
| 26 | ctrl, |
| 27 | haptic: Rc::new(haptic), |
| 28 | controllers: vec![], |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | pub fn handle_event(&mut self, event: &Event) { |
| 33 | match event { |
| 34 | Event::ControllerDeviceAdded { which, .. } => { self.add_device(*which) } |
| 35 | Event::ControllerDeviceRemoved { which, .. } => { self.remove_device(*which) } |
| 36 | Event::ControllerDeviceRemapped { which, .. } => { println!("device remapped ({})!", *which) } |
| 37 | Event::ControllerButtonDown { button, .. } => { println!("button {} down!", button.string()) } |
| 38 | Event::ControllerButtonUp { button, .. } => { println!("button {} up!", button.string()) } |
| 39 | Event::ControllerAxisMotion { axis, .. } => { println!("axis motion {}!", axis.string()) } |
| 40 | _ => {} |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | pub fn add_device(&mut self, id: u32) { |
| 45 | println!("device added ({})!", id); |
| 46 | let mut ctrl = self.ctrl.open(id).unwrap(); |
| 47 | println!("opened {}", ctrl.name()); |
| 48 | let haptic = match ctrl.set_rumble(500, 1000, 500) { |
| 49 | Ok(_) => self.haptic.open_from_joystick_id(id).ok(), |
| 50 | Err(_) => None |
| 51 | }; |
| 52 | |
| 53 | let c = Rc::new(Controller {id, ctrl, haptic: haptic.map(|h| Rc::new(RefCell::new(h)))}); |
| 54 | c.rumble(0.5, 300); |
| 55 | self.controllers.push(c); |
| 56 | } |
| 57 | |
| 58 | pub fn remove_device(&mut self, id: i32) { |
| 59 | println!("device removed ({})!", id); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | impl Controller { |
| 64 | /// strength [0 - 1] |
| 65 | pub fn rumble(&self, strength: f32, duration_ms: u32) { |
| 66 | if let Some(h) = &self.haptic { |
| 67 | h.borrow_mut().rumble_play(strength, duration_ms); |
| 68 | } |
| 69 | } |
| 70 | } |