From 51c8a51b53a850265955a3e4bc45b40ad3f8c477 Mon Sep 17 00:00:00 2001 From: WBoerenkamps Date: Wed, 23 Oct 2024 21:13:28 +0200 Subject: custom commit poc working --- mwe/events/src/timer.cpp | 54 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 mwe/events/src/timer.cpp (limited to 'mwe/events/src/timer.cpp') diff --git a/mwe/events/src/timer.cpp b/mwe/events/src/timer.cpp new file mode 100644 index 0000000..f4fee23 --- /dev/null +++ b/mwe/events/src/timer.cpp @@ -0,0 +1,54 @@ +#include "timer.h" + +LoopTimer::LoopTimer() {} +LoopTimer & LoopTimer::getInstance() { + static LoopTimer instance; + return instance; +} + +void LoopTimer::start() { + lastFrameTime = SDL_GetTicks64(); + elapsedTime = 0; + elapsedFixedTime = 0; + deltaTime = 0; +} + +// Update the timer, calculate deltaTime +void LoopTimer::update() { + uint64_t currentFrameTime = SDL_GetTicks64(); + deltaTime + = (currentFrameTime - lastFrameTime) / 1000.0; + + if (deltaTime > maximumDeltaTime) { + deltaTime = maximumDeltaTime; + } + + elapsedTime += deltaTime; + lastFrameTime = currentFrameTime; +} + +double LoopTimer::getDeltaTime() const { return deltaTime; } +int LoopTimer::getCurrentTime() const { return SDL_GetTicks(); } + +void LoopTimer::advanceFixedUpdate() { elapsedFixedTime += fixedDeltaTime; } + +double LoopTimer::getFixedDeltaTime() const { return fixedDeltaTime; } + +void LoopTimer::setFPS(int FPS) { + this->FPS = FPS; + frameTargetTime = 1.0 / FPS; +} + +int LoopTimer::getFPS() const { return FPS; } + +void LoopTimer::enforceFrameRate() { + uint64_t currentFrameTime = SDL_GetTicks64(); + double frameDuration = (currentFrameTime - lastFrameTime) / 1000.0; + + if (frameDuration < frameTargetTime) { + uint32_t delayTime + = (uint32_t) ((frameTargetTime - frameDuration) * 1000.0); + SDL_Delay(delayTime); + } +} +double LoopTimer::getLag() const { return elapsedTime - elapsedFixedTime; } -- cgit v1.2.3