Frame limiter

This commit is contained in:
Franco Colmenarez 2021-11-20 11:27:08 -05:00
parent 46262dfefa
commit 4caac23f66
2 changed files with 17 additions and 3 deletions

View File

@ -1,9 +1,11 @@
use std::{thread, time};
use std::time::Instant; use std::time::Instant;
pub struct Frames { pub struct Frames {
count: usize, count: usize,
timer: Instant, timer: Instant,
time_start: u128, time_start: u128,
fps: u128,
} }
impl Frames { impl Frames {
@ -12,6 +14,7 @@ impl Frames {
count: 0, count: 0,
timer: Instant::now(), timer: Instant::now(),
time_start: 0, time_start: 0,
fps: 1000 / 63,
} }
} }
@ -34,4 +37,14 @@ impl Frames {
pub fn count(&self) -> usize { pub fn count(&self) -> usize {
self.count self.count
} }
pub fn limit(&mut self) {
let elapsed = self.elapsed_ms();
// println!("{}", elapsed);
if elapsed > self.fps {
// println!("Frame dropped");
return;
}
thread::sleep(time::Duration::from_millis((self.fps - elapsed).try_into().unwrap()));
}
} }

View File

@ -43,6 +43,7 @@ pub fn create_window<T>(width: u32, height: u32, title: String, event_loop: &Eve
pub fn start_eventloop() { pub fn start_eventloop() {
let mut emulator = Emulator::new(); let mut emulator = Emulator::new();
let mut frames = Frames::new(); let mut frames = Frames::new();
let mut frame_limit = Frames::new();
env_logger::init(); env_logger::init();
let event_loop = EventLoop::new(); let event_loop = EventLoop::new();
@ -80,16 +81,16 @@ pub fn start_eventloop() {
*control_flow = ControlFlow::Exit *control_flow = ControlFlow::Exit
}, },
Event::MainEventsCleared => { Event::MainEventsCleared => {
frame_limit.reset_timer();
emulator.run(Cycles(70224), pixels.get_frame()); emulator.run(Cycles(70224), pixels.get_frame());
frames.increment(); frames.increment();
window.request_redraw();
if frames.elapsed_ms() >= 1000 { if frames.elapsed_ms() >= 1000 {
window.set_title(&format!("rmg-001 (FPS: {})", frames.count())); window.set_title(&format!("rmg-001 (FPS: {})", frames.count()));
frames.reset_count(); frames.reset_count();
frames.reset_timer(); frames.reset_timer();
} }
frame_limit.limit();
// thread::sleep(time::Duration::from_millis(1));
window.request_redraw();
}, },
Event::RedrawRequested(_) => { Event::RedrawRequested(_) => {
if pixels if pixels