Add FPS counter

This commit is contained in:
numzero 2024-09-26 20:00:33 +03:00
parent 45ed4dff90
commit bf38462c78

View File

@ -116,6 +116,7 @@ struct State<'a> {
device: wgpu::Device, device: wgpu::Device,
queue: wgpu::Queue, queue: wgpu::Queue,
fps: fps::Counter,
kbd: keyctl::Keyboard, kbd: keyctl::Keyboard,
t1: Instant, t1: Instant,
@ -187,12 +188,15 @@ impl<'a> State<'a> {
let scene = prepare_scene(&device); let scene = prepare_scene(&device);
let fps = fps::Counter::new();
Self { Self {
device, device,
queue, queue,
viewport, viewport,
line_rend, line_rend,
kbd, kbd,
fps,
cam_loc, cam_loc,
cam_obj, cam_obj,
t1, t1,
@ -229,6 +233,9 @@ impl<'a> State<'a> {
} }
fn render(&mut self) -> Result<(), wgpu::SurfaceError> { fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
self.fps.on_frame();
self.window
.set_title(&format!("Space Refraction ({:.1} FPS)", self.fps.get()));
self.viewport self.viewport
.render_single_pass(&self.device, &self.queue, |mut render_pass| { .render_single_pass(&self.device, &self.queue, |mut render_pass| {
self.line_rend.render( self.line_rend.render(
@ -310,3 +317,40 @@ pub async fn run() {
fn main() { fn main() {
pollster::block_on(run()); pollster::block_on(run());
} }
mod fps {
use std::time::{Duration, Instant};
pub struct Counter {
fps: f32,
t1: Instant,
frames: u32,
}
impl Counter {
pub fn new() -> Self {
Self {
fps: 0.,
t1: Instant::now(),
frames: 0,
}
}
pub fn get(&self) -> f32 {
self.fps
}
pub fn on_frame(&mut self) {
self.frames += 1;
let t2 = Instant::now();
let dt = t2 - self.t1;
if dt >= Duration::from_secs(1) {
*self = Self {
fps: self.frames as f32 / dt.as_secs_f32(),
t1: t2,
frames: 0,
}
}
}
}
}