GameKit  0.0.1a
C++ gamedev tools
GameClock.cpp
Go to the documentation of this file.
1 /*
2  * =====================================================================================
3  *
4  * Filename: GameClock.cpp
5  *
6  * Description:
7  *
8  * Created: 14/12/2014 13:42:26
9  *
10  * Author: Quentin Bazin, <quent42340@gmail.com>
11  *
12  * =====================================================================================
13  */
14 #include "gk/core/SDLHeaders.hpp"
15 #include "gk/core/GameClock.hpp"
16 
17 namespace gk {
18 
20 
21 u32 GameClock::getTicks(bool realTime) {
22  if(realTime) {
23  return SDL_GetTicks();
24  } else {
25  return ticks;
26  }
27 }
28 
30  u32 now = getTicks(true) - m_timeDropped;
31  u32 lastFrameDuration = now - m_lastFrameDate;
32 
33  m_lastFrameDate = now;
34  m_lag += lastFrameDuration;
35 
36  if(m_lag >= 200) {
38  m_lag = m_timestep;
39  m_lastFrameDate = getTicks(true) - m_timeDropped;
40  }
41 }
42 
43 void GameClock::updateGame(std::function<void(void)> updateFunc) {
44  m_numUpdates = 0;
45 
46  while(m_lag >= m_timestep && m_numUpdates < 10) {
47  ticks += m_timestep;
48 
49  updateFunc();
50 
51  m_lag -= m_timestep;
52  m_numUpdates++;
53  }
54 }
55 
56 void GameClock::drawGame(std::function<void(void)> drawFunc) {
57  if(m_numUpdates > 0) {
58  drawFunc();
59  }
60 
62 }
63 
65  u32 lastFrameDuration = getTicks(true) - m_timeDropped - m_lastFrameDate;
66 
67  if(lastFrameDuration < m_timestep) {
68  SDL_Delay(m_timestep - lastFrameDuration);
69  }
70 
72 }
73 
74 } // namespace gk
75 
u32 m_lastFrameDate
Definition: GameClock.hpp:40
static u32 ticks
Definition: GameClock.hpp:38
unsigned int u32
Definition: IntTypes.hpp:23
void drawGame(std::function< void(void)> drawFunc)
Definition: GameClock.cpp:56
void updateGame(std::function< void(void)> updateFunc)
Definition: GameClock.cpp:43
static u32 getTicks(bool realTime=false)
Definition: GameClock.cpp:21
void waitForNextFrame()
Definition: GameClock.cpp:64
void measureLastFrameDuration()
Definition: GameClock.cpp:29