-
Notifications
You must be signed in to change notification settings - Fork 0
/
Clock.h
59 lines (43 loc) · 1.36 KB
/
Clock.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#pragma once
// The more previous fps we store, the more accurate the average fps.
#define ACCURACY 50
#define SEC_PER_TICK 1.0/60.0
extern float g_dt;
extern float g_time_elapsed;
struct EngineClock {
void tick();
float last_tick_time = 0;
// for average fps
float fpss[ACCURACY];
int fpss_index = -1;
int average_fps = -1;
char average_fps_str[5];
};
// odd naming to avoid collision with clock() in <time.h>
#ifdef ENGINE_IMPLEMENTATION
void EngineClock::tick() {
// DT
float tick_time = SDL_GetTicks();
g_dt = (tick_time - last_tick_time) / 1000;
last_tick_time = tick_time;
// Total Time
g_time_elapsed += g_dt;
// Average FPS
float sum = 0;
for (int i = 0; i < ACCURACY; i++) {
sum += fpss[i];
}
average_fps = sum / ACCURACY;
if (g_dt != 0)
fpss[fpss_index] = 1 / g_dt;
fpss_index = (fpss_index + 1) % ACCURACY;
// SDL_GetTicks() returns junk values the first few times.
// This means that average_fps may be some very long number, more than
// the 5 characters that we allocated for it. And so, we do this range bound
// to make sure itoa doesn't overide other memory we're using.
if (average_fps > 0 && average_fps < 9999)
itoa(average_fps, average_fps_str, 10);
}
float g_dt = 0.f;
float g_time_elapsed = 0.f;
#endif