aboutsummaryrefslogtreecommitdiff
path: root/mwe/events/src/timer.cpp
diff options
context:
space:
mode:
authorLoek Le Blansch <loek@pipeframe.xyz>2024-11-04 08:28:18 +0100
committerLoek Le Blansch <loek@pipeframe.xyz>2024-11-04 08:28:18 +0100
commit06f65659fc6ffde7cabd2135040cbfbf089e5a24 (patch)
treee3570bea52b87b6919550ee81d17927ccbc11cc5 /mwe/events/src/timer.cpp
parent128969619a22dfc17a9ea35335c0d21c6ad0c954 (diff)
parent6aa8fdd04728b6a499f526de727514ae3d0490b4 (diff)
merge `origin/master` into `master`
Diffstat (limited to 'mwe/events/src/timer.cpp')
-rw-r--r--mwe/events/src/timer.cpp53
1 files changed, 53 insertions, 0 deletions
diff --git a/mwe/events/src/timer.cpp b/mwe/events/src/timer.cpp
new file mode 100644
index 0000000..0b89bf5
--- /dev/null
+++ b/mwe/events/src/timer.cpp
@@ -0,0 +1,53 @@
+#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; }