forked from yangsu/Synaptic-Wall
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Timer.pde
80 lines (67 loc) · 1.96 KB
/
Timer.pde
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
public class Timer {
private int fID;
private int fStartTime, fEndTime, fLastFiredTime, fThrottleInterval, fLength;
private float fFiringPos;
private boolean fFired;
private ArrayList<TimerSubscriber> fSubs;
public Timer(TimerSubscriber sub, int lengthMS) {
this(sub, lengthMS, 1, 0);// Default to fire at the end of the timer interval
}
public Timer(TimerSubscriber sub, int lengthMS, float firingPos) {
this(sub, lengthMS, firingPos, 0);
}
public Timer(TimerSubscriber sub, int lengthMS, float firingPos, int throttleInterval) {
fID = gIDCount++;
fLength = lengthMS;
fFiringPos = firingPos;
fThrottleInterval = throttleInterval;
fLastFiredTime = 0;
fSubs = new ArrayList<TimerSubscriber>();
addSub(sub);
fFired = false;
}
public void update() {
int currentTime = millis();
if (currentTime >= fEndTime && !fFired && !throttled()) {
fFired = true;
fLastFiredTime = currentTime;
for (TimerSubscriber sub : fSubs)
sub.onTimerFiring(fID, currentTime);
}
}
public void reset() {
if (gDebug) println(fID + " reset");
// println((fLastFiredTime - fStartTime) +" "+ (fEndTime - fStartTime));
fStartTime = millis();
fEndTime = fStartTime + round(fLength * fFiringPos);
fFired = false;
}
public float getProgress() {
return float(millis() - fStartTime)/fLength;
}
public int getLastFiredTime() {
return fLastFiredTime;
}
public void setLength(int l) {
fLength = l;
}
public boolean throttled() {
int time = millis();
return (time >= fStartTime) && (time <= fEndTime + fThrottleInterval);
}
public boolean ended() {
return getProgress() >= 1;
}
public boolean fired() {
return fFired;
}
public void addSub(TimerSubscriber sub) {
fSubs.add(sub);
}
public void removeSub(TimerSubscriber sub) {
fSubs.remove(sub);
}
}
public interface TimerSubscriber {
public void onTimerFiring(int id, int currentTime);
}