-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.c
137 lines (107 loc) · 2.42 KB
/
timer.c
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include "timer.h"
#include <stdlib.h>
#include <assert.h>
#include "common.h"
/* THIS MODULE IS DEFUNCT */
/*
This module implements non-callback
non-threaded timers tied to the frame
loop. A timer firing can be missed so
it should be checked each frame where
applicable.
*/
typedef struct
{
int oneshot;
TimerHandle handle;
float time;
float interval;
} Timer;
static int timerCount = 0;
static int maxHandle = 0;
Timer **timers = NULL;
void timer_ProcessTimers(float lag)
{
int i;
for(i = 0; i < timerCount; ++i)
timers[i]->time += lag;
}
int timer_Fired(TimerHandle handle)
{
int a, b, c, d = 0;
if(timerCount == 0)
return 0;
a = 0;
b = timerCount - 1;
c = timerCount / 2;
while(a != b &&
timers[a]->handle != handle &&
timers[b]->handle != handle &&
timers[c]->handle != handle)
{
c = a + ((b - a) / 2);
if(timers[c]->handle > handle)
b = c;
else
a = c;
}
if(timers[a]->handle == handle)
d = a;
else if(timers[b]->handle == handle)
d = b;
else if(timers[c]->handle == handle)
d = c;
else
return 0;
if(timers[d]->time >= timers[d]->interval)
return 1;
return 0;
}
TimerHandle timer_AddTimer(float interval, int oneshot)
{
Timer *t = malloc(sizeof(Timer));
t->handle = maxHandle;
t->interval = interval;
t->oneshot = oneshot;
t->time = 0;
maxHandle++;
timers = realloc(timers, sizeof(Timer*) * (timerCount + 1));
timers[timerCount] = t;
timerCount++;
return t-> handle;
}
void timer_CleanTimers()
{
if(timerCount == 0)
return;
Timer **tmptimers = NULL;
int tmptimerCount = 0;
int i;
for(i = 0; i < timerCount; ++i)
{
Timer *t = timers[i];
if(t->time < t->interval || !t->oneshot)
{
tmptimers = realloc(tmptimers, sizeof(Timer*) * (tmptimerCount + 1));
tmptimers[tmptimerCount] = t;
tmptimerCount++;
}
if(t->time >= t->interval)
{
if(!t->oneshot)
t->time -= t->interval;
else
free(t);
}
}
if(tmptimerCount == 0)
{
free(timers);
timers = NULL;
timerCount = 0;
return;
}
free(timers);
timers = tmptimers;
timerCount = tmptimerCount;
}