gdk-graphics 0b051eb9b5c1eaa0658babaa4463dd7a80aa9d2c
Loading...
Searching...
No Matches
game_loop.h
1// © Joseph Cameron - All Rights Reserved
2
3#ifndef GDK_GAME_LOOP_H
4#define GDK_GAME_LOOP_H
5
6#include <chrono>
7#include <functional>
8#include <thread>
9
10namespace gdk {
11 void game_loop(const float aMaxFramesPerSecond,
12 std::function<bool /*shouldClose*/(const double /*time*/, const double /*delta time*/)> aLoopBehavior) {
13 bool shouldClose(false);
14 double time(0);
15 double deltaTime(0);
16 double frameTime(1.0 / aMaxFramesPerSecond);
17
18 while (!shouldClose) {
19 using namespace std::chrono;
20
21 steady_clock::time_point currentFrameStartTimePoint(steady_clock::now());
22
23 shouldClose = aLoopBehavior(time, deltaTime);
24
25 time += deltaTime;
26
27 while (true) {
28 steady_clock::time_point currentTimePoint(steady_clock::now());
29
30 duration<double> timeSpentOnCurrentFrame = duration_cast<duration<double>>(currentTimePoint - currentFrameStartTimePoint);
31
32 if (deltaTime = timeSpentOnCurrentFrame.count(); deltaTime >= frameTime) break;
33
34 std::this_thread::sleep_for(1s * (frameTime - deltaTime) / 10.0);
35 }
36 }
37 }
38}
39
40#endif
41