Calculating frames delay in microseconds

This commit is contained in:
Franco Colmenarez 2021-11-20 20:52:56 -05:00
parent 4caac23f66
commit 7abe363e75
2 changed files with 14 additions and 15 deletions

View File

@ -14,7 +14,7 @@ impl Frames {
count: 0, count: 0,
timer: Instant::now(), timer: Instant::now(),
time_start: 0, time_start: 0,
fps: 1000 / 63, fps: 16600,
} }
} }
@ -23,7 +23,7 @@ impl Frames {
} }
pub fn reset_timer(&mut self) { pub fn reset_timer(&mut self) {
self.time_start = self.timer.elapsed().as_millis(); self.timer = Instant::now();
} }
pub fn increment(&mut self) { pub fn increment(&mut self) {
@ -38,13 +38,12 @@ impl Frames {
self.count self.count
} }
pub fn limit(&mut self) { pub fn limit(&self) {
let elapsed = self.elapsed_ms(); let elapsed = self.timer.elapsed().as_micros();
// println!("{}", elapsed);
if elapsed > self.fps { if elapsed > self.fps {
// println!("Frame dropped");
return; return;
} }
thread::sleep(time::Duration::from_millis((self.fps - elapsed).try_into().unwrap())); let wait = (self.fps - elapsed).try_into().unwrap();
thread::sleep(time::Duration::from_micros(wait));
} }
} }

View File

@ -42,7 +42,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 frame_counter = Frames::new();
let mut frame_limit = Frames::new(); let mut frame_limit = Frames::new();
env_logger::init(); env_logger::init();
@ -81,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(); frame_counter.increment();
window.request_redraw(); if frame_counter.elapsed_ms() >= 1000 {
if frames.elapsed_ms() >= 1000 { window.set_title(&format!("rmg-001 (FPS: {})", frame_counter.count()));
window.set_title(&format!("rmg-001 (FPS: {})", frames.count())); frame_counter.reset_count();
frames.reset_count(); frame_counter.reset_timer();
frames.reset_timer();
} }
window.request_redraw();
frame_limit.limit(); frame_limit.limit();
frame_limit.reset_timer();
}, },
Event::RedrawRequested(_) => { Event::RedrawRequested(_) => {
if pixels if pixels