-
Notifications
You must be signed in to change notification settings - Fork 1
/
clock.cpp
97 lines (87 loc) · 2.16 KB
/
clock.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <map>
#include <string>
#include <sstream>
using std::cout; using std::endl;
#include "clock.h"
using std::cout; using std::endl;
Clock& Clock::getInstance() {
if ( SDL_WasInit(SDL_INIT_VIDEO) == 0) {
throw std::string("Must init SDL before Clock");
}
static Clock clock;
return clock;
}
Clock::Clock() :
started(false),
paused(false),
frames(0),
timeAtStart(0), timeAtPause(0),
currTicks(0), prevTicks(0), ticks(0)
{
start();
}
Clock::Clock(const Clock& c) :
started(c.started),
paused(c.paused), frames(c.frames),
timeAtStart(c.timeAtStart), timeAtPause(c.timeAtPause),
currTicks(c.currTicks), prevTicks(c.prevTicks), ticks(c.ticks)
{
start();
}
void Clock::debug( ) {
cout << "The clock is:" << endl;
cout << "\tstarted:" << started << endl;
cout << "\tpaused:" << paused << endl;
cout << "\tframes:" << frames << endl;
cout << "\ttimeAtStart:" << timeAtStart << endl;
cout << "\ttimeAtPause:" << timeAtPause << endl;
cout << "\tcurrTicks:" << currTicks << endl;
cout << "\tprevTicks:" << prevTicks << endl;
cout << "\tticks:" << ticks << endl;
cout << endl;
}
unsigned Clock::getTicks() const {
if (paused) return timeAtPause;
else return SDL_GetTicks() - timeAtStart;
}
unsigned Clock::getElapsedTicks() {
if (paused) return 0;
currTicks = getTicks();
ticks = currTicks-prevTicks;
prevTicks = currTicks;
return ticks;
}
int Clock::getFps() const {
if ( getSeconds() > 0 ) return frames/getSeconds();
else if ( getTicks() > 1000 and getFrames() == 0 ) {
throw std::string("Can't getFps if you don't increment the frames");
}
else return 0;
}
Clock& Clock::operator++() {
if ( !paused ) ++frames;
return *this;
}
Clock Clock::operator++(int) {
if ( !paused ) frames++;
return *this;
}
void Clock::start() {
started = true;
paused = false;
frames = 0;
timeAtPause = timeAtStart = SDL_GetTicks();
}
void Clock::pause() {
if( started && !paused ) {
timeAtPause = SDL_GetTicks() - timeAtStart;
paused = true;
}
}
void Clock::unpause() {
if( started && paused ) {
timeAtStart = SDL_GetTicks() - timeAtPause;
paused = false;
}
}