refactor: handle pausing within game, reduce input system allocations

This commit is contained in:
2025-08-14 10:36:39 -05:00
parent b7429cd9ec
commit 2f1ff85d8f
5 changed files with 47 additions and 42 deletions

View File

@@ -6,7 +6,7 @@ use sdl2::render::{Canvas, ScaleMode, Texture, TextureCreator};
use sdl2::ttf::Sdl2TtfContext;
use sdl2::video::{Window, WindowContext};
use sdl2::{AudioSubsystem, EventPump, Sdl, VideoSubsystem};
use tracing::{debug, error, info, warn};
use tracing::{error, info, warn};
use crate::error::{GameError, GameResult};
@@ -20,11 +20,11 @@ pub struct App {
game: Game,
input_system: InputSystem,
canvas: Canvas<Window>,
event_pump: &'static mut EventPump,
backbuffer: Texture<'static>,
paused: bool,
focused: bool,
event_pump: &'static mut EventPump,
last_tick: Instant,
focused: bool,
cursor_pos: Vec2,
}
@@ -87,7 +87,6 @@ impl App {
canvas,
event_pump,
backbuffer,
paused: false,
focused: true,
last_tick: Instant::now(),
cursor_pos: Vec2::ZERO,
@@ -105,17 +104,10 @@ impl App {
self.focused = true;
}
WindowEvent::FocusLost => {
debug!("Window focus lost");
self.focused = false;
}
_ => {}
},
// It doesn't really make sense to have this available in the browser
#[cfg(not(target_os = "emscripten"))]
Event::Quit { .. } => {
info!("Exit requested. Exiting...");
return false;
}
Event::MouseMotion { x, y, .. } => {
// Convert window coordinates to logical coordinates
self.cursor_pos = Vec2::new(x as f32, y as f32);
@@ -123,17 +115,12 @@ impl App {
_ => {}
}
let commands = self.input_system.handle_event(&event);
for command in commands {
if let Some(command) = self.input_system.handle_event(&event) {
match command {
GameCommand::Exit => {
info!("Exit requested. Exiting...");
return false;
}
GameCommand::TogglePause => {
self.paused = !self.paused;
info!("{}", if self.paused { "Paused" } else { "Unpaused" });
}
_ => self.game.post_event(command.into()),
}
}
@@ -142,17 +129,20 @@ impl App {
let dt = self.last_tick.elapsed().as_secs_f32();
self.last_tick = Instant::now();
if !self.paused {
self.game.tick(dt);
if let Err(e) = self.game.draw(&mut self.canvas, &mut self.backbuffer) {
error!("Failed to draw game: {}", e);
}
if let Err(e) = self
.game
.present_backbuffer(&mut self.canvas, &self.backbuffer, self.cursor_pos)
{
error!("Failed to present backbuffer: {}", e);
}
let exit = self.game.tick(dt);
if exit {
return false;
}
if let Err(e) = self.game.draw(&mut self.canvas, &mut self.backbuffer) {
error!("Failed to draw game: {}", e);
}
if let Err(e) = self
.game
.present_backbuffer(&mut self.canvas, &self.backbuffer, self.cursor_pos)
{
error!("Failed to present backbuffer: {}", e);
}
if start.elapsed() < LOOP_TIME {