Codechange: introduce a framework for all our timers
IntervalTimer and TimeoutTimer use RAII, and can be used to replace all the time-based timeouts, lag-detection, "execute every N" we have. As it uses RAII, you can safely use it as static variable, class member, temporary variable, etc. As soon as it goes out-of-scope, it will be safely removed. This allows for much easier to read code when it comes to intervals.pull/544/head
parent
730687080a
commit
5e1bcee39b
@ -0,0 +1,8 @@
|
||||
add_files(
|
||||
timer_game_calendar.cpp
|
||||
timer_game_calendar.h
|
||||
timer_window.cpp
|
||||
timer_window.h
|
||||
timer_manager.h
|
||||
timer.h
|
||||
)
|
@ -0,0 +1,187 @@
|
||||
/*
|
||||
* 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 timer.h Definition of Interval and OneShot timers */
|
||||
|
||||
#ifndef TIMER_H
|
||||
#define TIMER_H
|
||||
|
||||
#include "timer_manager.h"
|
||||
|
||||
#include <functional>
|
||||
|
||||
/**
|
||||
* The base where every other type of timer is derived from.
|
||||
*
|
||||
* Never use this class directly yourself.
|
||||
*/
|
||||
template <typename TTimerType>
|
||||
class BaseTimer {
|
||||
public:
|
||||
using TPeriod = typename TTimerType::TPeriod;
|
||||
using TElapsed = typename TTimerType::TElapsed;
|
||||
using TStorage = typename TTimerType::TStorage;
|
||||
|
||||
/**
|
||||
* Create a new timer.
|
||||
*
|
||||
* @param period The period of the timer.
|
||||
*/
|
||||
NODISCARD BaseTimer(const TPeriod period) :
|
||||
period(period)
|
||||
{
|
||||
TimerManager<TTimerType>::RegisterTimer(*this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the timer.
|
||||
*/
|
||||
virtual ~BaseTimer()
|
||||
{
|
||||
TimerManager<TTimerType>::UnregisterTimer(*this);
|
||||
}
|
||||
|
||||
/* Although these variables are public, they are only public to make saveload easier; not for common use. */
|
||||
|
||||
TPeriod period; ///< The period of the timer.
|
||||
TStorage storage = {}; ///< The storage of the timer.
|
||||
|
||||
protected:
|
||||
/**
|
||||
* Called by the timer manager to notify the timer that the given amount of time has elapsed.
|
||||
*
|
||||
* @param delta Depending on the time type, this is either in milliseconds or in ticks.
|
||||
*/
|
||||
virtual void Elapsed(TElapsed delta) = 0;
|
||||
|
||||
/* To ensure only TimerManager can access Elapsed. */
|
||||
friend class TimerManager<TTimerType>;
|
||||
};
|
||||
|
||||
/**
|
||||
* An interval timer will fire every interval, and will continue to fire until it is deleted.
|
||||
*
|
||||
* The callback receives how many times the timer has fired since the last time it fired.
|
||||
* It will always try to fire every interval, but in times of severe stress it might be late.
|
||||
*
|
||||
* Each Timer-type needs to implement the Elapsed() method, and call the callback if needed.
|
||||
*
|
||||
* Setting the period to zero disables the interval. It can be reenabled at any time by
|
||||
* calling SetInterval() with a non-zero period.
|
||||
*/
|
||||
template <typename TTimerType>
|
||||
class IntervalTimer : public BaseTimer<TTimerType> {
|
||||
public:
|
||||
using TPeriod = typename TTimerType::TPeriod;
|
||||
using TElapsed = typename TTimerType::TElapsed;
|
||||
|
||||
/**
|
||||
* Create a new interval timer.
|
||||
*
|
||||
* @param interval The interval between each callback.
|
||||
* @param callback The callback to call when the interval has passed.
|
||||
*/
|
||||
NODISCARD IntervalTimer(const TPeriod interval, std::function<void(uint)> callback) :
|
||||
BaseTimer<TTimerType>(interval),
|
||||
callback(callback)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a new interval for the timer.
|
||||
*
|
||||
* @param interval The interval between each callback.
|
||||
* @param reset Whether to reset the timer to zero.
|
||||
*/
|
||||
void SetInterval(const TPeriod interval, bool reset = true)
|
||||
{
|
||||
this->period = interval;
|
||||
if (reset) this->storage = {};
|
||||
}
|
||||
|
||||
private:
|
||||
std::function<void(uint)> callback;
|
||||
|
||||
void Elapsed(TElapsed count) override;
|
||||
};
|
||||
|
||||
/**
|
||||
* A timeout timer will fire once after the interval. You can reset it to fire again.
|
||||
* The timer will never fire before the interval has passed, but in times of severe stress it might be late.
|
||||
*/
|
||||
template <typename TTimerType>
|
||||
class TimeoutTimer : public BaseTimer<TTimerType> {
|
||||
public:
|
||||
using TPeriod = typename TTimerType::TPeriod;
|
||||
using TElapsed = typename TTimerType::TElapsed;
|
||||
|
||||
/**
|
||||
* Create a new timeout timer.
|
||||
*
|
||||
* By default the timeout starts aborted; you will have to call Reset() before it starts.
|
||||
*
|
||||
* @param timeout The timeout after which the timer will fire.
|
||||
* @param callback The callback to call when the timeout has passed.
|
||||
* @param start Whether to start the timer immediately. If false, you can call Reset() to start it.
|
||||
*/
|
||||
NODISCARD TimeoutTimer(const TPeriod timeout, std::function<void()> callback, bool start = false) :
|
||||
BaseTimer<TTimerType>(timeout),
|
||||
fired(!start),
|
||||
callback(callback)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the timer, so it will fire again after the timeout.
|
||||
*/
|
||||
void Reset()
|
||||
{
|
||||
this->fired = false;
|
||||
this->storage = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the timer, so it will fire again after the timeout.
|
||||
*
|
||||
* @param timeout Set a new timeout for the next trigger.
|
||||
*/
|
||||
void Reset(const TPeriod timeout)
|
||||
{
|
||||
this->period = timeout;
|
||||
this->fired = false;
|
||||
this->storage = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Abort the timer so it doesn't fire if it hasn't yet.
|
||||
*/
|
||||
void Abort()
|
||||
{
|
||||
this->fired = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the timeout occurred.
|
||||
*
|
||||
* @return True iff the timeout occurred.
|
||||
*/
|
||||
bool HasFired() const
|
||||
{
|
||||
return this->fired;
|
||||
}
|
||||
|
||||
/* Although these variables are public, they are only public to make saveload easier; not for common use. */
|
||||
|
||||
bool fired; ///< Whether the timeout has occurred.
|
||||
|
||||
private:
|
||||
std::function<void()> callback;
|
||||
|
||||
void Elapsed(TElapsed count) override;
|
||||
};
|
||||
|
||||
#endif /* TIMER_H */
|
@ -0,0 +1,89 @@
|
||||
/*
|
||||
* 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 timer_game_calendar.cpp
|
||||
* This file implements the timer logic for the game-calendar-timer.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "date_func.h"
|
||||
#include "openttd.h"
|
||||
#include "timer.h"
|
||||
#include "timer_game_calendar.h"
|
||||
#include "vehicle_base.h"
|
||||
#include "linkgraph/linkgraph.h"
|
||||
|
||||
#include "safeguards.h"
|
||||
|
||||
template<>
|
||||
void IntervalTimer<TimerGameCalendar>::Elapsed(TimerGameCalendar::TElapsed trigger)
|
||||
{
|
||||
if (trigger == this->period.trigger) {
|
||||
this->callback(1);
|
||||
}
|
||||
}
|
||||
|
||||
template<>
|
||||
void TimeoutTimer<TimerGameCalendar>::Elapsed(TimerGameCalendar::TElapsed trigger)
|
||||
{
|
||||
if (this->fired) return;
|
||||
|
||||
if (trigger == this->period.trigger) {
|
||||
this->callback();
|
||||
this->fired = true;
|
||||
}
|
||||
}
|
||||
|
||||
template<>
|
||||
void TimerManager<TimerGameCalendar>::Elapsed(TimerGameCalendar::TElapsed delta)
|
||||
{
|
||||
assert(delta == 1);
|
||||
|
||||
_tick_counter++;
|
||||
|
||||
if (_game_mode == GM_MENU) return;
|
||||
|
||||
_date_fract++;
|
||||
if (_date_fract < DAY_TICKS) return;
|
||||
_date_fract = 0;
|
||||
|
||||
/* increase day counter */
|
||||
_date++;
|
||||
|
||||
YearMonthDay ymd;
|
||||
ConvertDateToYMD(_date, &ymd);
|
||||
|
||||
/* check if we entered a new month? */
|
||||
bool new_month = ymd.month != _cur_month;
|
||||
|
||||
/* check if we entered a new year? */
|
||||
bool new_year = ymd.year != _cur_year;
|
||||
|
||||
/* update internal variables before calling the daily/monthly/yearly loops */
|
||||
_cur_month = ymd.month;
|
||||
_cur_year = ymd.year;
|
||||
|
||||
/* Make a temporary copy of the timers, as a timer's callback might add/remove other timers. */
|
||||
auto timers = TimerManager<TimerGameCalendar>::GetTimers();
|
||||
|
||||
for (auto timer : timers) {
|
||||
timer->Elapsed(TimerGameCalendar::DAY);
|
||||
}
|
||||
|
||||
if (new_month) {
|
||||
for (auto timer : timers) {
|
||||
timer->Elapsed(TimerGameCalendar::MONTH);
|
||||
}
|
||||
}
|
||||
|
||||
if (new_year) {
|
||||
for (auto timer : timers) {
|
||||
timer->Elapsed(TimerGameCalendar::YEAR);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* 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 timer_game_calendar.h Definition of the game-calendar-timer */
|
||||
|
||||
#ifndef TIMER_GAME_CALENDAR_H
|
||||
#define TIMER_GAME_CALENDAR_H
|
||||
|
||||
/**
|
||||
* Timer that is increased every 27ms, and counts towards ticks / days / months / years.
|
||||
*
|
||||
* The amount of days in a month depends on the month and year (leap-years).
|
||||
* There are always 74 ticks in a day (and with 27ms, this makes 1 day 1.998 seconds).
|
||||
*
|
||||
* IntervalTimer and TimeoutTimer based on this Timer are a bit unusual, as their count is always one.
|
||||
* You create those timers based on a transition: a new day, a new month or a new year.
|
||||
*
|
||||
* Additionally, you need to set a priority. To ensure deterministic behaviour, events are executed
|
||||
* in priority. It is important that if you assign NONE, you do not use Random() in your callback.
|
||||
* Other than that, make sure you only set one callback per priority.
|
||||
*
|
||||
* For example:
|
||||
* IntervalTimer<TimerGameCalendar>({TimerGameCalendar::DAY, TimerGameCalendar::Priority::NONE}, [](uint count){});
|
||||
*
|
||||
*/
|
||||
class TimerGameCalendar {
|
||||
public:
|
||||
enum Trigger {
|
||||
DAY,
|
||||
MONTH,
|
||||
YEAR,
|
||||
};
|
||||
enum Priority {
|
||||
NONE, ///< These timers can be executed in any order; there is no Random() in them, so order is not relevant.
|
||||
|
||||
/* All other may have a Random() call in them, so order is important.
|
||||
* For safety, you can only setup a single timer on a single priority. */
|
||||
AUTOSAVE,
|
||||
COMPANY,
|
||||
DISASTER,
|
||||
ENGINE,
|
||||
INDUSTRY,
|
||||
STATION,
|
||||
SUBSIDY,
|
||||
TOWN,
|
||||
VEHICLE,
|
||||
};
|
||||
|
||||
struct TPeriod {
|
||||
Trigger trigger;
|
||||
Priority priority;
|
||||
|
||||
TPeriod(Trigger trigger, Priority priority) : trigger(trigger), priority(priority) {}
|
||||
|
||||
bool operator < (const TPeriod &other) const
|
||||
{
|
||||
if (this->trigger != other.trigger) return this->trigger < other.trigger;
|
||||
return this->priority < other.priority;
|
||||
}
|
||||
|
||||
bool operator == (const TPeriod &other) const
|
||||
{
|
||||
return this->trigger == other.trigger && this->priority == other.priority;
|
||||
}
|
||||
};
|
||||
|
||||
using TElapsed = uint;
|
||||
struct TStorage {
|
||||
};
|
||||
};
|
||||
|
||||
#endif /* TIMER_GAME_CALENDAR_H */
|
@ -0,0 +1,86 @@
|
||||
/*
|
||||
* 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 timer_manager.h Definition of the TimerManager */
|
||||
/** @note don't include this file; include "timer.h". */
|
||||
|
||||
#ifndef TIMER_MANAGER_H
|
||||
#define TIMER_MANAGER_H
|
||||
|
||||
#include "stdafx.h"
|
||||
|
||||
#include <set>
|
||||
|
||||
template <typename TTimerType>
|
||||
class BaseTimer;
|
||||
|
||||
/**
|
||||
* The TimerManager manages a single Timer-type.
|
||||
*
|
||||
* It allows for automatic registration and unregistration of timers like Interval and OneShot.
|
||||
*
|
||||
* Each Timer-type needs to implement the Elapsed() method, and distribute that to the timers if needed.
|
||||
*/
|
||||
template <typename TTimerType>
|
||||
class TimerManager {
|
||||
public:
|
||||
using TElapsed = typename TTimerType::TElapsed;
|
||||
|
||||
/* Avoid copying this object; it is a singleton object. */
|
||||
TimerManager(TimerManager const &) = delete;
|
||||
TimerManager &operator=(TimerManager const &) = delete;
|
||||
|
||||
/**
|
||||
* Register a timer.
|
||||
*
|
||||
* @param timer The timer to register.
|
||||
*/
|
||||
static void RegisterTimer(BaseTimer<TTimerType> &timer) {
|
||||
GetTimers().insert(&timer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister a timer.
|
||||
*
|
||||
* @param timer The timer to unregister.
|
||||
*/
|
||||
static void UnregisterTimer(BaseTimer<TTimerType> &timer) {
|
||||
GetTimers().erase(&timer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when time for this timer elapsed.
|
||||
*
|
||||
* The implementation per type is different, but they all share a similar goal:
|
||||
* Call the Elapsed() method of all active timers.
|
||||
*
|
||||
* @param value The amount of time that has elapsed.
|
||||
*/
|
||||
static void Elapsed(TElapsed value);
|
||||
|
||||
private:
|
||||
/**
|
||||
* Sorter for timers.
|
||||
*
|
||||
* It will sort based on the period, smaller first. If the period is the
|
||||
* same, it will sort based on the pointer value.
|
||||
*/
|
||||
struct base_timer_sorter {
|
||||
bool operator() (BaseTimer<TTimerType> *a, BaseTimer<TTimerType> *b) const {
|
||||
if (a->period == b->period) return a < b;
|
||||
return a->period < b->period;
|
||||
}
|
||||
};
|
||||
|
||||
/** Singleton list, to store all the active timers. */
|
||||
static std::set<BaseTimer<TTimerType> *, base_timer_sorter> &GetTimers() {
|
||||
static std::set<BaseTimer<TTimerType> *, base_timer_sorter> timers;
|
||||
return timers;
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* TIMER_MANAGER_H */
|
@ -0,0 +1,60 @@
|
||||
/*
|
||||
* 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 timer_window.cpp
|
||||
* This file implements the timer logic for the Window system.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "timer.h"
|
||||
#include "timer_window.h"
|
||||
|
||||
#include "safeguards.h"
|
||||
|
||||
template<>
|
||||
void IntervalTimer<TimerWindow>::Elapsed(TimerWindow::TElapsed delta)
|
||||
{
|
||||
if (this->period == std::chrono::milliseconds::zero()) return;
|
||||
|
||||
this->storage.elapsed += delta;
|
||||
|
||||
uint count = 0;
|
||||
while (this->storage.elapsed >= this->period) {
|
||||
this->storage.elapsed -= this->period;
|
||||
count++;
|
||||
}
|
||||
|
||||
if (count > 0) {
|
||||
this->callback(count);
|
||||
}
|
||||
}
|
||||
|
||||
template<>
|
||||
void TimeoutTimer<TimerWindow>::Elapsed(TimerWindow::TElapsed delta)
|
||||
{
|
||||
if (this->fired) return;
|
||||
if (this->period == std::chrono::milliseconds::zero()) return;
|
||||
|
||||
this->storage.elapsed += delta;
|
||||
|
||||
if (this->storage.elapsed >= this->period) {
|
||||
this->callback();
|
||||
this->fired = true;
|
||||
}
|
||||
}
|
||||
|
||||
template<>
|
||||
void TimerManager<TimerWindow>::Elapsed(TimerWindow::TElapsed delta)
|
||||
{
|
||||
/* Make a temporary copy of the timers, as a timer's callback might add/remove other timers. */
|
||||
auto timers = TimerManager<TimerWindow>::GetTimers();
|
||||
|
||||
for (auto timer : timers) {
|
||||
timer->Elapsed(delta);
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
/*
|
||||
* 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 timer_window.h Definition of the Window system */
|
||||
|
||||
#ifndef TIMER_WINDOW_H
|
||||
#define TIMER_WINDOW_H
|
||||
|
||||
#include <chrono>
|
||||
|
||||
/**
|
||||
* Timer that represents the real time, usable for the Window system.
|
||||
*
|
||||
* This can be used to create intervals based on milliseconds, seconds, etc.
|
||||
* Mostly used for animation, scrolling, etc.
|
||||
*
|
||||
* Please be mindful that the order in which timers are called is not guaranteed.
|
||||
*
|
||||
* @note The lowest possible interval is 1ms.
|
||||
* @note These timers can only be used in the Window system.
|
||||
*/
|
||||
class TimerWindow {
|
||||
public:
|
||||
using TPeriod = std::chrono::milliseconds;
|
||||
using TElapsed = std::chrono::milliseconds;
|
||||
struct TStorage {
|
||||
std::chrono::milliseconds elapsed;
|
||||
};
|
||||
};
|
||||
|
||||
#endif /* TIMER_WINDOW_H */
|
Loading…
Reference in New Issue