63 lines
1.9 KiB
C++
63 lines
1.9 KiB
C++
// calls callbackfunc on specified interval based on accumulated deltatime
|
|
#include "timer.hpp"
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <memory>
|
|
#include <ncurses.h>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
// infinite timer
|
|
Timer::Timer(std::string name_input, double interval_input,
|
|
std::unique_ptr<TimerAction> action_input)
|
|
: time_interval(interval_input), name(name_input), is_infinite(true),
|
|
action(std::move(action_input)) {}
|
|
|
|
// limited timer
|
|
Timer::Timer(std::string name, double interval_input, int trigger_amount,
|
|
std::unique_ptr<TimerAction> action_input)
|
|
: trigger_amount(trigger_amount), time_interval(interval_input), name(name),
|
|
action(std::move(action_input)) {}
|
|
|
|
// callbackfunc once enough time has accumulated
|
|
void Timer::updatetime(double delta_time) {
|
|
accumulator += delta_time;
|
|
if (!is_expired) {
|
|
if (accumulator >= time_interval) {
|
|
action->update(*this);
|
|
accumulator -= time_interval;
|
|
trigger_counter++;
|
|
if (!is_infinite && trigger_counter >= trigger_amount) {
|
|
is_expired = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void TimerManager::addtimer(std::unique_ptr<Timer> input_timer) {
|
|
timers.push_back(std::move(input_timer));
|
|
}
|
|
|
|
void TimerManager::updatetimers() {
|
|
//get dtime
|
|
auto current_time = std::chrono::steady_clock::now();
|
|
std::chrono::duration<double> myDeltaTime = current_time - prev_time;
|
|
double dtime = myDeltaTime.count();
|
|
|
|
//update timers with dtime
|
|
for (auto &mytimer : timers) {
|
|
mytimer->updatetime(dtime);
|
|
mvprintw(12, 0, "updated timer %s", mytimer->name.c_str());
|
|
}
|
|
//reset for next tick
|
|
prev_time = current_time;
|
|
timers.erase(std::remove_if(timers.begin(), timers.end(),
|
|
[](auto &timer) { return timer->is_expired; }),
|
|
timers.end());
|
|
// implement delete timers
|
|
refresh();
|
|
}
|
|
|
|
TimerManager::TimerManager(): prev_time(std::chrono::steady_clock::now()){}
|
|
|