66 lines
1.5 KiB
Rust
66 lines
1.5 KiB
Rust
use std::thread::sleep;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use self::input::InputState;
|
|
use self::screen::Screen;
|
|
|
|
type UpdateFn = fn(&mut Screen, &InputState) -> bool;
|
|
|
|
mod input;
|
|
mod screen;
|
|
|
|
pub struct Trekstor {
|
|
pub screen: Screen,
|
|
pub input: InputState,
|
|
accumulator: Duration,
|
|
last_time: Instant,
|
|
current_time: Instant,
|
|
update_timestep: Duration,
|
|
}
|
|
|
|
impl Trekstor {
|
|
pub fn new(update_fps: i32) -> Self {
|
|
let screen = Screen::new();
|
|
let input = InputState::new(&screen);
|
|
|
|
Self {
|
|
screen,
|
|
input,
|
|
accumulator: Duration::default(),
|
|
current_time: Instant::now(),
|
|
last_time: Instant::now(),
|
|
update_timestep: Duration::from_nanos(
|
|
(1_000_000_000f64 / update_fps as f64).round() as u64
|
|
),
|
|
}
|
|
}
|
|
|
|
pub fn update(&mut self, update: UpdateFn) {
|
|
loop {
|
|
self.input.handle_event();
|
|
self.current_time = Instant::now();
|
|
let dt = self.current_time - self.last_time;
|
|
|
|
println!("Frame");
|
|
|
|
if !update(&mut self.screen, &self.input) {
|
|
return;
|
|
}
|
|
|
|
self.screen.flush();
|
|
self.input.finish();
|
|
|
|
let wait_time = if dt < self.update_timestep {
|
|
self.update_timestep - dt
|
|
} else {
|
|
Duration::from_millis(33)
|
|
};
|
|
|
|
dbg!(dt, self.update_timestep);
|
|
|
|
self.last_time = self.current_time;
|
|
sleep(wait_time);
|
|
}
|
|
}
|
|
}
|