Functional input binding

This commit is contained in:
2024-11-10 14:05:10 -05:00
parent a69247dd33
commit 5cb36d0bcc
8 changed files with 254 additions and 81 deletions
+38 -24
View File
@@ -1,4 +1,8 @@
use std::{collections::HashMap, fmt::Debug};
use std::{
collections::HashMap,
fmt::Debug,
sync::{Arc, RwLock},
};
use game::GameWindow;
use winit::{
@@ -8,7 +12,11 @@ use winit::{
window::WindowId,
};
use crate::emulator::EmulatorClient;
use crate::{
controller::ControllerState,
emulator::{EmulatorClient, EmulatorCommand},
input::InputMapper,
};
mod common;
mod game;
@@ -16,32 +24,35 @@ mod input;
pub struct App {
windows: HashMap<WindowId, Box<dyn AppWindow>>,
focused_window: Option<WindowId>,
client: EmulatorClient,
input_mapper: Arc<RwLock<InputMapper>>,
controller: ControllerState,
proxy: EventLoopProxy<UserEvent>,
}
impl App {
pub fn new(client: EmulatorClient, proxy: EventLoopProxy<UserEvent>) -> Self {
let input_mapper = Arc::new(RwLock::new(InputMapper::new()));
let controller = ControllerState::new(input_mapper.clone());
Self {
windows: HashMap::new(),
focused_window: None,
client,
input_mapper,
controller,
proxy,
}
}
fn active_window(&mut self) -> Option<&mut Box<dyn AppWindow>> {
let active_window = self.focused_window?;
self.windows.get_mut(&active_window)
}
}
impl ApplicationHandler<UserEvent> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let mut window = GameWindow::new(event_loop, self.client.clone(), self.proxy.clone());
let mut window = GameWindow::new(
event_loop,
self.client.clone(),
self.input_mapper.clone(),
self.proxy.clone(),
);
window.init();
self.focused_window = Some(window.id());
self.windows.insert(window.id(), Box::new(window));
}
@@ -51,11 +62,10 @@ impl ApplicationHandler<UserEvent> for App {
window_id: WindowId,
event: WindowEvent,
) {
if let WindowEvent::Focused(focused) = event {
if focused {
self.focused_window = Some(window_id);
} else {
self.focused_window = None;
if let WindowEvent::KeyboardInput { event, .. } = &event {
if self.controller.key_event(event) {
self.client
.send_command(EmulatorCommand::SetKeys(self.controller.pressed()));
}
}
let Some(window) = self.windows.get_mut(&window_id) else {
@@ -82,17 +92,21 @@ impl ApplicationHandler<UserEvent> for App {
device_id: winit::event::DeviceId,
event: winit::event::DeviceEvent,
) {
let Some(window) = self.active_window() else {
return;
};
window.handle_event(event_loop, &Event::DeviceEvent { device_id, event });
for window in self.windows.values_mut() {
window.handle_event(
event_loop,
&Event::DeviceEvent {
device_id,
event: event.clone(),
},
);
}
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
let Some(window) = self.active_window() else {
return;
};
window.handle_event(event_loop, &Event::AboutToWait);
for window in self.windows.values_mut() {
window.handle_event(event_loop, &Event::AboutToWait);
}
}
}