use common::Point2D; use common::Radians; use sdl2::HapticSubsystem; use sdl2::JoystickSubsystem; use sdl2::event::Event; use sdl2::haptic::Haptic; use sdl2::joystick::Joystick; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use time::{Duration, prelude::*}; #[derive(Debug, Default)] pub struct Button { pub time_pressed: Duration, pub time_released: Duration, pub is_pressed: bool, pub was_pressed: bool, pub toggle: bool, } impl Button { fn update(&mut self, device: &Joystick, dt: Duration, btn: u8) { self.was_pressed = self.is_pressed; self.is_pressed = match device.button(btn as u32) { Ok(true) => { if !self.was_pressed { self.time_pressed = 0.seconds(); self.toggle = !self.toggle; } self.time_pressed += dt; true } Ok(false) => { if self.was_pressed { self.time_released = 0.seconds(); } self.time_released += dt; false } Err(_) => { panic!("invalid button {}", btn) } } } } #[derive(Debug, Default)] pub struct Axis { pub val: f32, } impl Axis { #[allow(dead_code)] fn update(&mut self, device: &Joystick, _dt: Duration, axis: u8) { self.val = match device.axis(axis as u32) { Ok(val) => val as f32 / 32768.0, Err(_) => panic!("invalid axis {}", axis), } } } #[derive(Debug, Default)] pub struct Stick { pub x: f32, pub y: f32, pub a: Radians, pub len: f32, } impl Stick { fn update(&mut self, device: &Joystick, _dt: Duration, x_axis: u8, y_axis: u8) { self.x = match device.axis(x_axis as u32) { Ok(val) => val as f32 / 32768.0, Err(_) => panic!("invalid x axis {}", x_axis), }; self.y = match device.axis(y_axis as u32) { Ok(val) => val as f32 / 32768.0, Err(_) => panic!("invalid y axis {}", y_axis), }; self.a = Radians(self.y.atan2(self.x) as f64); self.len = { let x = (self.x / self.y).abs().min(1.0); let y = (self.y / self.x).abs().min(1.0); (self.x.powi(2) + self.y.powi(2)).sqrt() / (x.powi(2) + y.powi(2)).sqrt() } } #[inline(always)] #[allow(dead_code)] fn up(&self) -> bool { self.y > 0.99 } #[inline(always)] #[allow(dead_code)] fn down(&self) -> bool { self.y < -0.99 } #[inline(always)] #[allow(dead_code)] fn left(&self) -> bool { self.x < -0.99 } #[inline(always)] #[allow(dead_code)] fn right(&self) -> bool { self.x > 0.99 } pub fn to_point(&self) -> Point2D { Point2D { x: self.x as f64, y: self.y as f64, } } pub fn to_adjusted_point(&self) -> Point2D { Point2D::from(self.a) * self.len as f64 } } impl From<&Stick> for Point2D { fn from(item: &Stick) -> Self { Self { x: item.x as f64, y: item.y as f64, } } } impl From<&Stick> for (f64, f64) { fn from(item: &Stick) -> Self { (item.x as f64, item.y as f64) } } //#[derive(Debug)] pub struct Controller { pub device: Joystick, haptic: Option>>, pub mov: Stick, pub aim: Stick, pub jump: Button, pub start: Button, pub shoot: Button, } impl Controller { pub fn new(device: Joystick, haptic: Option>>) -> Self { Controller { device, haptic, mov: Default::default(), aim: Default::default(), jump: Default::default(), start: Default::default(), shoot: Default::default(), } } pub fn update(&mut self, dt: Duration) { self.mov.update(&self.device, dt, 0, 1); // left stick self.aim.update(&self.device, dt, 3, 4); // right stick self.jump.update(&self.device, dt, 4); // left shoulder self.shoot.update(&self.device, dt, 5); // right shoulder self.start.update(&self.device, dt, 9); // start } /// strength [0 - 1] pub fn rumble(&self, strength: f32, duration: Duration) { if let Some(h) = &self.haptic { h.borrow_mut().rumble_play(strength, duration.whole_milliseconds() as u32); } } } //#[derive(Debug)] pub struct ControllerManager { pub joystick: JoystickSubsystem, haptic: Rc, pub controllers: HashMap>>, } impl ControllerManager { pub fn new(joystick: JoystickSubsystem, haptic: HapticSubsystem) -> Self { joystick.set_event_state(true); let mut c = ControllerManager { joystick, haptic: Rc::new(haptic), controllers: HashMap::new(), }; c.init(); c } fn init(&mut self) { for i in 0..self.joystick.num_joysticks().unwrap() { self.add_device(i); } } pub fn update(&mut self, dt: Duration) { self.controllers.iter().for_each(|(_, v)| v.borrow_mut().update(dt)); } pub fn handle_event(&mut self, event: &Event) { match event { Event::JoyDeviceAdded { which, .. } => { self.add_device(*which) } Event::JoyDeviceRemoved { which, .. } => { self.remove_device(*which) } Event::JoyButtonDown { which, button_idx, .. } => { println!("device {} button {} down!", which, button_idx) } Event::JoyButtonUp { which, button_idx, .. } => { println!("device {} button {} up!", which, button_idx) } Event::JoyAxisMotion { which, axis_idx, .. } => { println!("device {} axis motion {}!", which, axis_idx) } _ => {} } } fn add_device(&mut self, id: u32) { println!("device added ({})!", id); let mut device = self.joystick.open(id).unwrap(); println!("opened {}", device.name()); /* note about set_rumble (for dualshock 3 at least): the active range for the low frequency is from 65536/4 to 65536 and escalates in large steps throughout the range the active range for the high frequency is from 256 to 65536 and effect is the same throughout the whole range */ let haptic = match device.set_rumble(0, 256, 100) { Ok(_) => self.haptic.open_from_joystick_id(id).ok(), Err(_) => None }; if self.controllers.contains_key(&id) { return; } let detached = self.controllers.values().find(|c| !c.borrow().device.attached()); match detached { Some(c) => { let mut c = c.borrow_mut(); c.device = device; c.haptic = haptic.map(|h| Rc::new(RefCell::new(h))); } None => { let c = Rc::new(RefCell::new(Controller::new(device, haptic.map(|h| Rc::new(RefCell::new(h)))))); self.controllers.insert(id, c); } }; } fn remove_device(&mut self, id: i32) { println!("device removed ({})!", id); // TODO } }