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;
10 pub struct ControllerManager {
11 ctrl: GameControllerSubsystem,
12 haptic: Rc<HapticSubsystem>,
13 pub controllers: Vec<Rc<Controller>>,
17 pub struct Controller {
19 pub ctrl: GameController,
20 haptic: Option<Rc<RefCell<Haptic>>>,
23 impl ControllerManager {
24 pub fn new(ctrl: GameControllerSubsystem, haptic: HapticSubsystem) -> Self {
27 haptic: Rc::new(haptic),
32 pub fn handle_event(&mut self, event: &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()) }
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(),
53 let c = Rc::new(Controller {id, ctrl, haptic: haptic.map(|h| Rc::new(RefCell::new(h)))});
55 self.controllers.push(c);
58 pub fn remove_device(&mut self, id: i32) {
59 println!("device removed ({})!", id);
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);