From d060e3a50c987d10799ccc739bdbf9d7d7a13c10 Mon Sep 17 00:00:00 2001 From: Hannes Schulze Date: Thu, 6 Feb 2025 18:24:59 +0100 Subject: implement settings --- lib/nes/common/CMakeLists.txt | 4 +++- lib/nes/common/fps-counter.cc | 29 +++++++++++++++++++++++++++++ lib/nes/common/fps-counter.hh | 23 +++++++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 lib/nes/common/fps-counter.cc create mode 100644 lib/nes/common/fps-counter.hh (limited to 'lib/nes/common') diff --git a/lib/nes/common/CMakeLists.txt b/lib/nes/common/CMakeLists.txt index 3920d36..9a7cc6b 100644 --- a/lib/nes/common/CMakeLists.txt +++ b/lib/nes/common/CMakeLists.txt @@ -5,6 +5,8 @@ target_sources( debug.hh rgb.hh display.hh - status.hh) + status.hh + fps-counter.hh + fps-counter.cc) add_subdirectory(containers) \ No newline at end of file diff --git a/lib/nes/common/fps-counter.cc b/lib/nes/common/fps-counter.cc new file mode 100644 index 0000000..ef6169b --- /dev/null +++ b/lib/nes/common/fps-counter.cc @@ -0,0 +1,29 @@ +#include "nes/common/fps-counter.hh" + +namespace nes +{ + auto fps_counter::frame(std::chrono::microseconds const elapsed_time) -> void + { + if (elapsed_time.count() <= 0) { return; } + + if (buffer_position_ == 0) + { + // Update fps count. + auto sum = u32{ 0 }; + for (auto i = u32{ 0 }; i < buffer_size; ++i) { sum += frame_times_[i]; } + if (sum > 0) + { + buffered_fps_ = (buffer_size * 1000000) / sum; + } + else + { + buffered_fps_ = 0; + } + } + + // Add the frame time to the buffer, replacing any existing content in the ring buffer. + auto const frame_time = static_cast(elapsed_time.count()); + frame_times_[buffer_position_] = frame_time; + buffer_position_ = (buffer_position_ + 1) % buffer_size; + } +} // namespace nes \ No newline at end of file diff --git a/lib/nes/common/fps-counter.hh b/lib/nes/common/fps-counter.hh new file mode 100644 index 0000000..96db98c --- /dev/null +++ b/lib/nes/common/fps-counter.hh @@ -0,0 +1,23 @@ +#pragma once + +#include "nes/common/types.hh" +#include + +namespace nes +{ + /// Counts frames. + class fps_counter + { + static constexpr auto buffer_size = u32{ 20 }; + + u32 frame_times_[buffer_size]{}; // The time until the next frame for the last frames. + u32 buffer_position_{ 0 }; // Position in the ring buffer. + u32 buffered_fps_{ 0 }; // Delay updates to FPS to one update per round in the ring buffer. + + public: + explicit fps_counter() = default; + + auto frame(std::chrono::microseconds elapsed_time) -> void; + auto get_fps() const -> u32 { return buffered_fps_; } + }; +} // namespace nes \ No newline at end of file -- cgit v1.3.1