From 834f2fac0d85258a1bf2541ed4774178de07df43 Mon Sep 17 00:00:00 2001 From: Leo dev Date: Sat, 29 Nov 2025 13:15:51 +0100 Subject: [PATCH] Fps counter --- examples/cube.rs | 82 +++++++++++++++++++++++++++++++++++------------- src/lib.rs | 2 +- src/renderer.rs | 10 ++++++ 3 files changed, 72 insertions(+), 22 deletions(-) diff --git a/examples/cube.rs b/examples/cube.rs index d83c9f5..2cf9e99 100644 --- a/examples/cube.rs +++ b/examples/cube.rs @@ -1,34 +1,74 @@ pub mod components; +use std::sync::{Arc, Mutex}; + use osmium::{renderer::Point, terminal}; fn main() { let engine = osmium::init(); - engine.entity(|r| { - r.draw_vertex( - 0, - 0, - &[ - Point { x: 0, y: 0 }, - Point { x: 30, y: 0 }, - Point { x: 15, y: 8 }, - ], - 0x0000ff, - ); + let last_frame = Arc::new(Mutex::new(std::time::Instant::now())); + let peak: Arc> = Arc::new(Mutex::new(0)); + let low: Arc> = Arc::new(Mutex::new(1000)); - r.draw_vertex_outline( - 0, - 0, - &[ - Point { x: 0, y: 0 }, - Point { x: 30, y: 0 }, - Point { x: 15, y: 8 }, - ], - 0xff0000, - ); + engine.entity(move |r| { + let current_frame = std::time::Instant::now(); + let since = current_frame + .duration_since(last_frame.lock().unwrap().clone()) + .as_millis(); + + if since > 0 { + let fps: u32 = 1000 / since as u32; + + r.draw_text( + 0, + 0, + format!("{fps}\n{}\n{}", peak.lock().unwrap(), low.lock().unwrap()), + ); + + { + let mut peak = peak.lock().unwrap(); + let mut low = low.lock().unwrap(); + + if fps > *peak { + *peak = fps; + } + + if fps < *low { + *low = fps; + } + } + } + + *last_frame.lock().unwrap() = current_frame; }); + engine + .entity(|r| { + r.draw_vertex( + 0, + 0, + &[ + Point { x: 0, y: 0 }, + Point { x: 30, y: 0 }, + Point { x: 15, y: 8 }, + ], + 0x0000ff, + ); + + r.draw_vertex_outline( + 0, + 0, + &[ + Point { x: 0, y: 0 }, + Point { x: 30, y: 0 }, + Point { x: 15, y: 8 }, + ], + 0xff0000, + ); + }) + .set_position(20, 0); + terminal::hide_cursor().unwrap(); engine.start(); diff --git a/src/lib.rs b/src/lib.rs index cb30aad..2434344 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -99,7 +99,7 @@ impl Engine { loop { self.render(); - sleep(160); + sleep(16); } } } diff --git a/src/renderer.rs b/src/renderer.rs index b437276..804f36a 100644 --- a/src/renderer.rs +++ b/src/renderer.rs @@ -19,6 +19,16 @@ impl Renderer { } } + pub fn draw_text(&mut self, x: u16, y: u16, text: T) { + write_liner( + &mut self.buf, + self.pos.x + x, + self.pos.y + y, + "", + &text.to_string(), + ); + } + pub fn draw_rect(&mut self, x: u16, y: u16, width: u16, height: u16, color: u32) { let rl = " ".repeat(width as usize) + "\x1b[0m"; let rect = (rl + "\n").repeat(height as usize);