summaryrefslogtreecommitdiff
path: root/src/guitimer_func.h
blob: f37bd5dbbc6e40c27b03a86a4f196c779dae8623 (plain)
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
/*
 * This file is part of OpenTTD.
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 */

/** @file guitimer_func.h GUI Timers. */

#ifndef GUITIMER_FUNC_H
#define GUITIMER_FUNC_H

class GUITimer
{
protected:
	uint timer;
	uint interval;

public:
	GUITimer() : timer(0), interval(0) { }
	explicit GUITimer(uint interval) : timer(0), interval(interval) { }

	inline bool HasElapsed() const
	{
		return this->interval == 0;
	}

	inline void SetInterval(uint interval)
	{
		this->timer = 0;
		this->interval = interval;
	}

	/**
	 * Count how many times the interval has elapsed.
	 * Use to ensure a specific amount of events happen within a timeframe, e.g. for animation.
	 * @param delta Time since last test.
	 * @return Number of times the interval has elapsed.
	 */
	inline uint CountElapsed(uint delta)
	{
		if (this->interval == 0) return 0;
		uint count = delta / this->interval;
		if (this->timer + (delta % this->interval) >= this->interval) count++;
		this->timer = (this->timer + delta) % this->interval;
		return count;
	}

	/**
	 * Test if a timer has elapsed.
	 * Use to ensure an event happens only once within a timeframe, e.g. for window updates.
	 * @param delta Time since last test.
	 * @return True iff the timer has elapsed.
	 */
	inline bool Elapsed(uint delta)
	{
		if (this->CountElapsed(delta) == 0) return false;
		this->SetInterval(0);
		return true;
	}
};

#endif /* GUITIMER_FUNC_H */