]> git.localhorst.tv Git - blank.git/blob - src/app/IntervalTimer.hpp
some experiements with state sync
[blank.git] / src / app / IntervalTimer.hpp
1 #ifndef BLANK_APP_INTERVALTIMER_HPP
2 #define BLANK_APP_INTERVALTIMER_HPP
3
4
5 namespace blank {
6
7 /// Timer that hits every n milliseconds. Resolution is that of the
8 /// delta values passed to Update(), minimum 1ms.
9 /// Also tracks the number of iterations as well as milliseconds
10 /// passed.
11 class IntervalTimer {
12
13 public:
14         /// Create a timer that hits every interval_ms milliseconds.
15         /// Initial state is stopped.
16         explicit IntervalTimer(int interval_ms = 0) noexcept
17         : intv(interval_ms) { }
18
19         void Start() noexcept {
20                 speed = 1;
21         }
22         void Stop() noexcept {
23                 value = 0;
24                 speed = 0;
25         }
26         void Reset() noexcept {
27                 value = 0;
28         }
29
30         bool Running() const noexcept {
31                 return speed != 0;
32         }
33         /// true if an interval boundary was passed by the last call to Update()
34         bool Hit() const noexcept {
35                 return Running() && value % intv < last_dt;
36         }
37         bool HitOnce() const noexcept {
38                 return Running() && value >= intv;
39         }
40         int Elapsed() const noexcept {
41                 return value;
42         }
43         int Interval() const noexcept {
44                 return intv;
45         }
46         int Iteration() const noexcept {
47                 return value / intv;
48         }
49         void PopIteration() noexcept {
50                 value -= intv;
51         }
52
53         void Update(int dt) noexcept {
54                 value += dt * speed;
55                 last_dt = dt;
56         }
57
58 private:
59         int intv;
60         int value = 0;
61         int speed = 0;
62         int last_dt = 0;
63
64 };
65
66 }
67
68 #endif