]> git.localhorst.tv Git - blank.git/blob - src/app/IntervalTimer.hpp
centralize entity controllers
[blank.git] / src / app / IntervalTimer.hpp
1 #ifndef BLANK_APP_INTERVALTIMER_HPP
2 #define BLANK_APP_INTERVALTIMER_HPP
3
4 #include <cmath>
5
6
7 namespace blank {
8
9 /// Timer that hits every n Time units. Resolution is that of the
10 /// delta values passed to Update().
11 /// Also tracks the number of iterations as well as Time units
12 /// passed.
13 template<class Time = int>
14 class IntervalTimer {
15
16 public:
17         /// Create a timer that hits every interval Time units.
18         /// Initial state is stopped.
19         explicit IntervalTimer(Time interval_ms = Time(0)) noexcept
20         : intv(interval_ms) { }
21
22         void Start() noexcept {
23                 speed = Time(1);
24         }
25         void Stop() noexcept {
26                 value = Time(0);
27                 speed = Time(0);
28         }
29         void Reset() noexcept {
30                 value = Time(0);
31         }
32
33         bool Running() const noexcept {
34                 return speed != Time(0);
35         }
36         /// true if an interval boundary was passed by the last call to Update()
37         bool Hit() const noexcept {
38                 return Running() && mod(value, intv) < last_dt;
39         }
40         bool HitOnce() const noexcept {
41                 return Running() && value >= intv;
42         }
43         Time Elapsed() const noexcept {
44                 return value;
45         }
46         Time Interval() const noexcept {
47                 return intv;
48         }
49         int Iteration() const noexcept {
50                 return value / intv;
51         }
52         void PopIteration() noexcept {
53                 value -= intv;
54         }
55
56         void Update(Time dt) noexcept {
57                 value += dt * speed;
58                 last_dt = dt;
59         }
60
61         static Time mod(Time val, Time m) noexcept {
62                 return val % m;
63         }
64
65 private:
66         Time intv;
67         Time value = Time(0);
68         Time speed = Time(0);
69         Time last_dt = Time(0);
70
71 };
72
73 using CoarseTimer = IntervalTimer<int>;
74 using FineTimer = IntervalTimer<float>;
75
76 template<>
77 inline float IntervalTimer<float>::mod(float val, float m) noexcept {
78         return std::fmod(val, m);
79 }
80
81 template<>
82 inline int IntervalTimer<float>::Iteration() const noexcept {
83         return std::floor(value / intv);
84 }
85
86 }
87
88 #endif