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;
pub struct Frames {
count: usize,
timer: Instant,
time_start: u128,
fps: u128,
}
impl Frames {
@ -12,6 +14,7 @@ impl Frames {
count: 0,
timer: Instant::now(),
time_start: 0,
fps: 1000 / 63,
}
}
@ -34,4 +37,14 @@ impl Frames {
pub fn count(&self) -> usize {
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() {
let mut emulator = Emulator::new();
let mut frames = Frames::new();
let mut frame_limit = Frames::new();
env_logger::init();
let event_loop = EventLoop::new();
@ -80,16 +81,16 @@ pub fn start_eventloop() {
*control_flow = ControlFlow::Exit
},
Event::MainEventsCleared => {
frame_limit.reset_timer();
emulator.run(Cycles(70224), pixels.get_frame());
frames.increment();
window.request_redraw();
if frames.elapsed_ms() >= 1000 {
window.set_title(&format!("rmg-001 (FPS: {})", frames.count()));
frames.reset_count();
frames.reset_timer();
}
// thread::sleep(time::Duration::from_millis(1));
window.request_redraw();
frame_limit.limit();
},
Event::RedrawRequested(_) => {
if pixels