9dbc24efc1
split timeractions from timers into seperate header integrated the experiments into an improved displaynumbers, which includes the vector as well as bars above them outsourced the calculation of delta time to the manager to clean up main()
64 lines
1.9 KiB
C++
64 lines
1.9 KiB
C++
// calls callbackfunc on specified interval based on accumulated deltatime
|
|
#include "timer.hpp"
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <cstddef>
|
|
#include <memory>
|
|
#include <ncurses.h>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
// infinite timer
|
|
timer::timer(std::string name_input, size_t 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, size_t interval_input, int triggeramount,
|
|
std::unique_ptr<timeraction> action_input)
|
|
: triggeramount(triggeramount), time_interval(interval_input), name(name),
|
|
action(std::move(action_input)) {}
|
|
|
|
// callbackfunc once enough time has accumulated
|
|
void timer::updatetime(double DeltaTime) {
|
|
accumulator += DeltaTime;
|
|
if (!is_expired) {
|
|
if (accumulator >= time_interval) {
|
|
action->update(*this);
|
|
accumulator -= time_interval;
|
|
triggercounter++;
|
|
if (!is_infinite && triggercounter >= triggeramount) {
|
|
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 currenttime = std::chrono::steady_clock::now();
|
|
std::chrono::duration<double> myDeltaTime = currenttime - prevtime;
|
|
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
|
|
prevtime = currenttime;
|
|
timers.erase(std::remove_if(timers.begin(), timers.end(),
|
|
[](auto &timer) { return timer->is_expired; }),
|
|
timers.end());
|
|
// implement delete timers
|
|
refresh();
|
|
}
|
|
|
|
timermanager::timermanager(): prevtime(std::chrono::steady_clock::now()){}
|
|
|