diff --git a/uw8-window/src/lib.rs b/uw8-window/src/lib.rs index dd2dd27..a0b4be8 100644 --- a/uw8-window/src/lib.rs +++ b/uw8-window/src/lib.rs @@ -4,31 +4,64 @@ use std::time::Instant; mod cpu; mod gpu; -pub struct Window(Box); +pub struct Window { + inner: Box, + fps_counter: Option, +} + +struct FpsCounter { + start: Instant, + num_frames: u32, +} impl Window { pub fn new(config: WindowConfig) -> Result { + let fps_counter = if config.fps_counter { + Some(FpsCounter { + start: Instant::now(), + num_frames: 0, + }) + } else { + None + }; if config.enable_gpu { match gpu::Window::new(config) { - Ok(window) => return Ok(Window(Box::new(window))), + Ok(window) => { + return Ok(Window { + inner: Box::new(window), + fps_counter, + }) + } Err(err) => eprintln!( "Failed to create gpu window: {}\nFalling back tp cpu window", err ), } } - cpu::Window::new().map(|window| Window(Box::new(window))) + cpu::Window::new().map(|window| Window { + inner: Box::new(window), + fps_counter, + }) } pub fn begin_frame(&mut self) -> Input { - self.0.begin_frame() + self.inner.begin_frame() } pub fn end_frame(&mut self, framebuffer: &[u8], palette: &[u8], next_frame: Instant) { - self.0.end_frame(framebuffer, palette, next_frame) + self.inner.end_frame(framebuffer, palette, next_frame); + if let Some(ref mut fps_counter) = self.fps_counter { + fps_counter.num_frames += 1; + let elapsed = fps_counter.start.elapsed().as_secs_f32(); + if elapsed >= 1.0 { + println!("fps: {:.1}", fps_counter.num_frames as f32 / elapsed); + fps_counter.num_frames = 0; + fps_counter.start = Instant::now(); + } + } } pub fn is_open(&self) -> bool { - self.0.is_open() + self.inner.is_open() } } @@ -37,6 +70,7 @@ pub struct WindowConfig { enable_gpu: bool, filter: u32, fullscreen: bool, + fps_counter: bool, } impl Default for WindowConfig { @@ -45,6 +79,7 @@ impl Default for WindowConfig { enable_gpu: true, filter: 5, fullscreen: false, + fps_counter: false, } } } @@ -66,6 +101,7 @@ impl WindowConfig { } } self.fullscreen = args.contains("--fullscreen"); + self.fps_counter = args.contains("--fps"); } }