diff --git a/main.lua b/main.lua index ac410d8..bc7ccd2 100644 --- a/main.lua +++ b/main.lua @@ -20,5 +20,5 @@ function couch.keypressed(scancode) end function couch.keyreleased(scancode) - if scancode == couch.KEY_A or scancode == couch.KEY_D then roll_x = 0.0 end + if scancode == couch.KEY_A or scancode == couch.KEY_D then roll_x = 0.0 end end diff --git a/src/device.rs b/src/device.rs new file mode 100644 index 0000000..ad2912b --- /dev/null +++ b/src/device.rs @@ -0,0 +1,34 @@ +use std::collections::HashMap; + +pub enum KeyEvent { + Pressed(u32), + Released(u32), +} + +pub struct DeviceManager { + key_map: HashMap, + key_event: Option, +} + +impl DeviceManager { + pub fn new() -> Self { + DeviceManager { + key_map: HashMap::new(), + key_event: None + } + } + pub fn update_key_event(&mut self, scancode: u32, pressed: bool) { + let old = *self.key_map.get(&scancode).unwrap_or(&false); + if old != pressed { + self.key_map.insert(scancode, pressed); + if pressed { + self.key_event = Some(KeyEvent::Pressed(scancode)); + } else { + self.key_event = Some(KeyEvent::Released(scancode)); + } + } + } + pub fn handle_key_event(&mut self) -> Option { + std::mem::replace(&mut self.key_event, None) + } +} diff --git a/src/main.rs b/src/main.rs index e8f83e8..0941390 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,6 @@ +mod device; +use device::*; + mod model; use model::Model; @@ -25,6 +28,8 @@ fn main() { let display = glium::Display::new(wb, cb, &events_loop).unwrap(); + let mut device_manager = DeviceManager::new(); + let vertex_shader_src = include_str!("flat.vert"); let fragment_shader_src = include_str!("flat.frag"); let program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None).unwrap(); @@ -63,9 +68,14 @@ fn main() { glutin::event::KeyboardInput { scancode, state, .. } ) = event { match state { - glutin::event::ElementState::Pressed => script_lang.key_pressed(scancode), - glutin::event::ElementState::Released => script_lang.key_released(scancode), - } + glutin::event::ElementState::Pressed => device_manager.update_key_event(scancode, true), + glutin::event::ElementState::Released => device_manager.update_key_event(scancode, false), + }; + match device_manager.handle_key_event() { + Some(KeyEvent::Pressed(x)) => script_lang.key_pressed(x), + Some(KeyEvent::Released(x)) => script_lang.key_released(x), + None => (), + }; }; }, glutin::event::Event::MainEventsCleared => {