diff --git a/src/fps_counter.rs b/src/fps_counter.rs new file mode 100644 index 0000000..feb1455 --- /dev/null +++ b/src/fps_counter.rs @@ -0,0 +1,28 @@ +pub struct FpsCounter { + last_frame_time: std::time::Instant, + frame_count: u32, + fps: u32 +} + +impl FpsCounter { + pub fn new() -> Self { + Self { + last_frame_time: std::time::Instant::now(), + frame_count: 0, + fps: 0, + } + } + + pub fn fps(&self) -> u32 { + self.fps + } + + pub fn tick(&mut self) { + self.frame_count += 1; + if self.last_frame_time.elapsed() > std::time::Duration::from_secs(1) { + self.fps = self.frame_count; + self.frame_count = 0; + self.last_frame_time = std::time::Instant::now(); + } + } +} diff --git a/src/main.rs b/src/main.rs index f97198a..6bbc416 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,8 +2,11 @@ mod color; mod emitter; mod particle; mod renderer; +mod fps_counter; + use emitter::{EmitShape, Emitter, EmitterOptions}; use particle::Particle; +use fps_counter::FpsCounter; use fontdue::{Font, FontSettings}; use glam::Vec2; @@ -75,6 +78,7 @@ fn main() { let mut particles: Vec = Vec::with_capacity(1000); let mut emitters: Vec = Vec::with_capacity(10); let mut renderer: Renderer = Renderer::new(WIDTH, HEIGHT); + let mut fps_counter: FpsCounter = FpsCounter::new(); let mut last_win_size: (usize, usize) = window.get_size(); let mut last_start_time: std::time::Instant = std::time::Instant::now(); @@ -89,6 +93,8 @@ fn main() { let frame_delta: std::time::Duration = last_start_time.elapsed(); last_start_time = std::time::Instant::now(); + fps_counter.tick(); + let win_size: (usize, usize) = window.get_size(); if win_size != last_win_size { last_win_size = win_size; @@ -121,7 +127,7 @@ fn main() { renderer.draw_text( &font, - format!("fps: {}\nparticles: {}", (1.0 / frame_delta.as_secs_f32()) as u32, particles.len()).as_str(), + format!("fps: {}\nparticles: {}", fps_counter.fps(), particles.len()).as_str(), Vec2::ZERO, 8.0, 0xffffff, diff --git a/src/particle.rs b/src/particle.rs index 65a97fe..647940f 100644 --- a/src/particle.rs +++ b/src/particle.rs @@ -44,6 +44,7 @@ impl Particle { // Returns true if alive pub fn update(&mut self, frame_delta: std::time::Duration, renderer: &mut Renderer) -> bool { + // Delete itself if it's out of bounds, TODO: Size should be used if self.position.y < 0.0 || self.position.y > renderer.height() as f32 || self.position.x < 0.0 || self.position.x > renderer.width() as f32 { return false; }