X-Git-Url: http://dolda2000.com/gitweb/?a=blobdiff_plain;f=src%2Fcore%2Fcontroller.rs;h=2eec33ade4cfcf255647aad6e7f008f1a3e045cc;hb=5d731022a8949b965bb0b2c13524ee7c5bfaf2e6;hp=b3f6201518ea5eae687102f4bd1b10a56281f9e0;hpb=fca4e4f02f42efcfe88104ca221e32302b4f4878;p=kaka%2Frust-sdl-test.git diff --git a/src/core/controller.rs b/src/core/controller.rs index b3f6201..2eec33a 100644 --- a/src/core/controller.rs +++ b/src/core/controller.rs @@ -1,70 +1,316 @@ -use std::cell::RefCell; -use sdl2::haptic::Haptic; +use common::Point2D; +use common::Radians; use sdl2::HapticSubsystem; -use sdl2::GameControllerSubsystem; +use sdl2::JoystickSubsystem; use sdl2::event::Event; -use sdl2::controller::GameController; +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)] -pub struct ControllerManager { - ctrl: GameControllerSubsystem, - haptic: Rc, - pub controllers: Vec>, +#[derive(Debug, Default)] +pub struct Button { + id: u8, + 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) { + self.was_pressed = self.is_pressed; + self.is_pressed = match device.button(self.id 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 {}", self.id) } + } + } +} + +#[derive(Debug, Default)] +pub struct Axis { + id: u8, + pub val: f32, +} + +impl Axis { + #[allow(dead_code)] + fn update(&mut self, device: &Joystick, _dt: Duration) { + self.val = match device.axis(self.id as u32) { + Ok(val) => val as f32 / 32768.0, + Err(_) => panic!("invalid axis {}", self.id), + } + } +} + +#[derive(Debug, Default)] +pub struct Stick { + idx: u8, + idy: u8, + pub x: f32, + pub y: f32, + pub a: Radians, + pub len: f32, +} + +impl Stick { + fn update(&mut self, device: &Joystick, _dt: Duration) { + self.x = match device.axis(self.idx as u32) { + Ok(val) => val as f32 / 32768.0, + Err(_) => panic!("invalid x axis {}", self.idx), + }; + self.y = match device.axis(self.idy as u32) { + Ok(val) => val as f32 / 32768.0, + Err(_) => panic!("invalid y axis {}", self.idy), + }; + 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) + } +} + +#[allow(dead_code)] +struct Axes { + left_x: u8, + left_y: u8, + right_x: u8, + right_y: u8, + trigger_left: u8, + trigger_right: u8, +} + +#[allow(dead_code)] +struct Buttons { + a: u8, + b: u8, + x: u8, + y: u8, + select: u8, + start: u8, + left_stick: u8, + right_stick: u8, + left_shoulder: u8, + right_shoulder: u8, + left_trigger: u8, + right_trigger: u8, + d_pad_up: u8, + d_pad_down: u8, + d_pad_left: u8, + d_pad_right: u8, +} + +struct Mapping { + axis: Axes, + btn: Buttons, } //#[derive(Debug)] pub struct Controller { - id: u32, - pub ctrl: GameController, + 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 { + let mut ctrl = Controller { + device, + haptic, + mov: Default::default(), + aim: Default::default(), + jump: Default::default(), + start: Default::default(), + shoot: Default::default(), + }; + let dualshock3 = Mapping { + axis: Axes { + left_x: 0, + left_y: 1, + right_x: 3, + right_y: 4, + trigger_left: 2, + trigger_right: 5, + }, + btn: Buttons { + a: 0, + b: 1, + x: 3, + y: 2, + select: 8, + start: 9, + left_stick: 11, + right_stick: 12, + left_shoulder: 4, + right_shoulder: 5, + left_trigger: 6, + right_trigger: 7, + d_pad_up: 13, + d_pad_down: 14, + d_pad_left: 15, + d_pad_right: 16, + }, + }; + ctrl.set_mapping(&dualshock3); + ctrl + } + + fn set_mapping(&mut self, map: &Mapping) { + self.mov.idx = map.axis.left_x; + self.mov.idy = map.axis.left_y; + self.aim.idx = map.axis.right_x; + self.aim.idy = map.axis.right_y; + self.jump.id = map.btn.left_shoulder; + self.shoot.id = map.btn.right_shoulder; + self.start.id = map.btn.start; + } + + pub fn update(&mut self, dt: Duration) { + self.mov.update(&self.device, dt); + self.aim.update(&self.device, dt); + self.jump.update(&self.device, dt); + self.shoot.update(&self.device, dt); + self.start.update(&self.device, dt); + } + + /// 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(ctrl: GameControllerSubsystem, haptic: HapticSubsystem) -> Self { - ControllerManager { - ctrl, + pub fn new(joystick: JoystickSubsystem, haptic: HapticSubsystem) -> Self { + joystick.set_event_state(true); + let mut c = ControllerManager { + joystick, haptic: Rc::new(haptic), - controllers: vec![], + 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::ControllerDeviceAdded { which, .. } => { self.add_device(*which) } - Event::ControllerDeviceRemoved { which, .. } => { self.remove_device(*which) } - Event::ControllerDeviceRemapped { which, .. } => { println!("device remapped ({})!", *which) } - Event::ControllerButtonDown { button, .. } => { println!("button {} down!", button.string()) } - Event::ControllerButtonUp { button, .. } => { println!("button {} up!", button.string()) } - Event::ControllerAxisMotion { axis, .. } => { println!("axis motion {}!", axis.string()) } + 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) } _ => {} } } - pub fn add_device(&mut self, id: u32) { + fn add_device(&mut self, id: u32) { println!("device added ({})!", id); - let mut ctrl = self.ctrl.open(id).unwrap(); - println!("opened {}", ctrl.name()); - let haptic = match ctrl.set_rumble(500, 1000, 500) { + 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 }; - let c = Rc::new(Controller {id, ctrl, haptic: haptic.map(|h| Rc::new(RefCell::new(h)))}); - c.rumble(0.5, 300); - self.controllers.push(c); - } + if self.controllers.contains_key(&id) { + return; + } - pub fn remove_device(&mut self, id: i32) { - println!("device removed ({})!", id); + 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); + } + }; } -} -impl Controller { - /// strength [0 - 1] - pub fn rumble(&self, strength: f32, duration_ms: u32) { - if let Some(h) = &self.haptic { - h.borrow_mut().rumble_play(strength, duration_ms); - } + fn remove_device(&mut self, id: i32) { + println!("device removed ({})!", id); + // TODO } }