Fleshed out the controller
authorTomas Wenström <tomas.wenstrom@gmail.com>
Sun, 17 Jan 2021 13:57:12 +0000 (14:57 +0100)
committerTomas Wenström <tomas.wenstrom@gmail.com>
Sun, 17 Jan 2021 13:57:12 +0000 (14:57 +0100)
src/common.rs
src/core/app.rs
src/core/controller.rs
src/core/game.rs

index 2be427e..6306bf6 100644 (file)
@@ -19,6 +19,13 @@ impl Point2D<f64> {
     pub fn length(self) -> f64 {
         ((self.x * self.x) + (self.y * self.y)).sqrt()
     }
+
+    pub fn to_i32(self) -> Point2D<i32> {
+       Point2D {
+           x: self.x as i32,
+           y: self.y as i32,
+       }
+    }
 }
 
 macro_rules! point_op {
@@ -116,6 +123,12 @@ impl<T> From<(T, T)> for Point2D<T> {
     }
 }
 
+impl<T> From<Point2D<T>> for (T, T) {
+    fn from(item: Point2D<T>) -> Self {
+        (item.x, item.y)
+    }
+}
+
 impl From<Degrees> for Point2D<f64> {
     fn from(item: Degrees) -> Self {
         Point2D {
@@ -134,18 +147,20 @@ impl From<Radians> for Point2D<f64> {
     }
 }
 
-#[derive(Debug, PartialEq, Clone, Copy)]
-struct Degrees(f64);
-#[derive(Debug, PartialEq, Clone, Copy)]
-struct Radians(f64);
+#[derive(Debug, Default, PartialEq, Clone, Copy)]
+pub struct Degrees(pub f64);
+#[derive(Debug, Default, PartialEq, Clone, Copy)]
+pub struct Radians(pub f64);
 
 impl Degrees {
+    #[allow(dead_code)]
     fn to_radians(&self) -> Radians {
        Radians(self.0 * std::f64::consts::PI / 180.0)
     }
 }
 
 impl Radians {
+    #[allow(dead_code)]
     fn to_degrees(&self) -> Degrees {
        Degrees(self.0 * 180.0 * std::f64::consts::FRAC_1_PI)
     }
index 62d7507..ddfe3d9 100644 (file)
@@ -72,15 +72,13 @@ impl AppBuilder {
         let event_pump = context.event_pump()?;
         let sprites = SpriteManager::new(canvas.texture_creator());
        let screen = canvas.output_size().unwrap();
-       let ctrl = context.game_controller()?;
-       ctrl.set_event_state(true);
 
         Ok(App {
             canvas,
             event_pump,
             sprites,
             state: self.state.unwrap_or_else(|| Box::new(ActiveState::new(screen))),
-           ctrl_man: ControllerManager::new(ctrl, context.haptic()?),
+           ctrl_man: ControllerManager::new(context.joystick()?, context.haptic()?),
         })
     }
 
@@ -160,6 +158,7 @@ impl App {
             let duration =
                 last_time.to(PreciseTime::now()).num_nanoseconds().unwrap() as Nanoseconds;
             last_time = PreciseTime::now();
+           self.ctrl_man.update(duration);
             self.state.update(duration);
 
            self.render();
index fb56465..127c309 100644 (file)
-use std::collections::HashMap;
-use std::cell::RefCell;
-use sdl2::haptic::Haptic;
+use sdl2::JoystickSubsystem;
+use common::Nanoseconds;
+use common::Radians;
+use common::Point2D;
 use sdl2::HapticSubsystem;
-pub use sdl2::GameControllerSubsystem;
 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;
 
-//#[derive(Debug)]
-pub struct ControllerManager {
-    pub ctrl: GameControllerSubsystem,
-    haptic: Rc<HapticSubsystem>,
-    pub controllers: HashMap<u32, Rc<RefCell<Controller>>>,
+#[derive(Debug, Default)]
+pub struct Button {
+    pub time_pressed: Nanoseconds,
+    pub time_released: Nanoseconds,
+    pub is_pressed: bool,
+    pub was_pressed: bool,
+    pub toggle: bool,
+}
+
+impl Button {
+    fn update(&mut self, device: &Joystick, dt: Nanoseconds, 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;
+                   self.toggle = !self.toggle;
+               }
+               self.time_pressed += dt;
+               true
+           }
+           Ok(false) => {
+               if self.was_pressed {
+                   self.time_released = 0;
+               }
+               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: Nanoseconds, 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: Nanoseconds, 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<f64> {
+       Point2D {
+           x: self.x as f64,
+           y: self.y as f64,
+       }
+    }
+
+    pub fn to_adjusted_point(&self) -> Point2D<f64> {
+       Point2D::from(self.a) * self.len as f64
+    }
+}
+
+impl From<&Stick> for Point2D<f64> {
+    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 ctrl: GameController,
+    pub device: Joystick,
     haptic: Option<Rc<RefCell<Haptic>>>,
+
+    pub mov: Stick,
+    pub aim: Stick,
+    pub jump: Button,
+    pub start: Button,
+    pub shoot: Button,
+}
+
+impl Controller {
+    pub fn new(device: Joystick, haptic: Option<Rc<RefCell<Haptic>>>) -> 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: Nanoseconds) {
+       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_ms: u32) {
+       if let Some(h) = &self.haptic {
+           h.borrow_mut().rumble_play(strength, duration_ms);
+       }
+    }
+}
+
+//#[derive(Debug)]
+pub struct ControllerManager {
+    pub joystick: JoystickSubsystem,
+    haptic: Rc<HapticSubsystem>,
+    pub controllers: HashMap<u32, Rc<RefCell<Controller>>>,
 }
 
 impl ControllerManager {
-    pub fn new(ctrl: GameControllerSubsystem, haptic: HapticSubsystem) -> Self {
+    pub fn new(joystick: JoystickSubsystem, haptic: HapticSubsystem) -> Self {
+       joystick.set_event_state(true);
        let mut c = ControllerManager {
-           ctrl,
+           joystick,
            haptic: Rc::new(haptic),
            controllers: HashMap::new(),
        };
@@ -32,34 +177,37 @@ impl ControllerManager {
     }
 
     fn init(&mut self) {
-       for i in 0..self.ctrl.num_joysticks().unwrap() {
+       for i in 0..self.joystick.num_joysticks().unwrap() {
            self.add_device(i);
        }
     }
 
+    pub fn update(&mut self, dt: Nanoseconds) {
+       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 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 ctrl.set_rumble(0, 256, 100) {
+       let haptic = match device.set_rumble(0, 256, 100) {
            Ok(_) => self.haptic.open_from_joystick_id(id).ok(),
            Err(_) => None
        };
@@ -68,31 +216,22 @@ impl ControllerManager {
            return;
        }
 
-       let detached = self.controllers.values().find(|c| !c.borrow().ctrl.attached());
+       let detached = self.controllers.values().find(|c| !c.borrow().device.attached());
        match detached {
            Some(c) => {
                let mut c = c.borrow_mut();
-               c.ctrl = ctrl;
+               c.device = device;
                c.haptic = haptic.map(|h| Rc::new(RefCell::new(h)));
            }
            None => {
-               let c = Rc::new(RefCell::new(Controller {ctrl, haptic: haptic.map(|h| Rc::new(RefCell::new(h)))}));
+               let c = Rc::new(RefCell::new(Controller::new(device, haptic.map(|h| Rc::new(RefCell::new(h))))));
                self.controllers.insert(id, c);
            }
        };
     }
 
-    pub fn remove_device(&mut self, id: i32) {
+    fn remove_device(&mut self, id: i32) {
        println!("device removed ({})!", id);
        // TODO
     }
 }
-
-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);
-       }
-    }
-}
index bf6d0ba..bf7d2df 100644 (file)
@@ -1,17 +1,16 @@
-use sdl2::controller::{Axis, Button};
-use core::controller::ControllerManager;
-use std::cell::RefCell;
-use std::rc::Rc;
-use core::controller::Controller;
-use common::Point2D;
-use sdl2::rect::Rect;
+use AppState;
 use common::Nanoseconds;
+use common::Point2D;
+use core::controller::Controller;
+use core::controller::ControllerManager;
+use point;
 use sdl2::event::Event;
-use sprites::SpriteManager;
+use sdl2::rect::Rect;
 use sdl2::render::Canvas;
 use sdl2::video::Window;
-use AppState;
-use point;
+use sprites::SpriteManager;
+use std::cell::RefCell;
+use std::rc::Rc;
 
 ////////// GAMESTATE ///////////////////////////////////////////////////////////
 
@@ -152,32 +151,32 @@ impl Object for Character {
        self.vel += lvl.gravity;
        self.pos += self.vel;
 
-       let ctrl = &self.ctrl.borrow().ctrl;
-       let right_stick = point!(ctrl.axis(Axis::RightX) as f64 / 32768.0, ctrl.axis(Axis::RightY) as f64 / 32768.0);
+       let ctrl = self.ctrl.borrow();
 
        if self.pos.y >= lvl.ground {
            self.pos.y = lvl.ground;
            self.vel.y = 0.0;
            self.vel.x *= 0.9;
 
-           if ctrl.button(Button::LeftShoulder) {
-               self.vel = right_stick * 5.0;
+           if ctrl.jump.is_pressed {
+               self.vel = ctrl.aim.to_point() * 5.0;
            }
        }
 
-       if ctrl.button(Button::RightShoulder) {
+       if ctrl.shoot.is_pressed {
            use rand::distributions::{Distribution, Normal};
            let normal = Normal::new(0.0, 0.1);
            for _i in 0..100 {
                objects.push(Box::new(Boll {
                    pos: self.pos,
-                   vel: right_stick * (3.0 + rand::random::<f64>()) + point!(normal.sample(&mut rand::thread_rng()), normal.sample(&mut rand::thread_rng())) + self.vel,
+                   vel: ctrl.aim.to_adjusted_point() * (3.0 + rand::random::<f64>()) + point!(normal.sample(&mut rand::thread_rng()), normal.sample(&mut rand::thread_rng())) + self.vel,
                    bounces: 2,
                }));
            }
+           ctrl.rumble(1.0, _dt as u32 / 1_000_000);
        }
 
-       match ctrl.axis(Axis::LeftX) as f64 / 32768.0 {
+       match ctrl.mov.x {
            v if v < -0.9 => { self.vel.x -= 0.5 }
            v if v > 0.9 => { self.vel.x += 0.5 }
            _ => {}
@@ -190,13 +189,33 @@ impl Object for Character {
         let block = sprites.get("mario");
        let size = 32;
         canvas.copy(block, None, Rect::new(self.pos.x as i32 - size as i32 / 2, self.pos.y as i32 - size as i32, size, size)).unwrap();
-       let ctrl = &self.ctrl.borrow().ctrl;
-       let (x, y) = (ctrl.axis(Axis::RightX) as f64 / 32768.0, ctrl.axis(Axis::RightY) as f64 / 32768.0);
+
+       let ctrl = &self.ctrl.borrow();
+       let l = 300.0;
+       let pos = (self.pos.x as i32, self.pos.y as i32);
+       // axis values
+       let p = (self.pos + ctrl.aim.to_point() * l).to_i32().into();
        canvas.set_draw_color((0, 255, 0));
-       canvas.draw_line((self.pos.x as i32, self.pos.y as i32), ((self.pos.x + x * size as f64) as i32, (self.pos.y + y * size as f64) as i32)).unwrap();
+       canvas.draw_line(pos, p).unwrap();
+       draw_cross(canvas, p);
+       // adjusted values
+       let p = (self.pos + ctrl.aim.to_adjusted_point() * l).to_i32().into();
+       canvas.set_draw_color((255, 0, 0));
+       canvas.draw_line(pos, p).unwrap();
+       draw_cross(canvas, p);
+       // circle values
+       let p = (self.pos + Point2D::from(ctrl.aim.a) * l).to_i32().into();
+       canvas.set_draw_color((0, 0, 255));
+       canvas.draw_line(pos, p).unwrap();
+       draw_cross(canvas, p);
     }
 }
 
+fn draw_cross(canvas: &mut Canvas<Window>, p: (i32, i32)) {
+    canvas.draw_line((p.0 - 5, p.1), (p.0 + 5, p.1)).unwrap();
+    canvas.draw_line((p.0, p.1 - 5), (p.0, p.1 + 5)).unwrap();
+}
+
 pub struct Boll {
     pos: Point2D<f64>,
     vel: Point2D<f64>,