spacebox/src/Timer.hpp

124 lines
3.4 KiB
C++

/* +------------------------------------------------------+
____/ \____ /| - Open source game framework licensed to freely use, |
\ / / | copy, modify and sell without restriction |
+--\ ^__^ /--+ | |
| ~/ \~ | | - created for <https://foam.shampoo.ooo> |
| ~~~~~~~~~~~~ | +------------------------------------------------------+
| SPACE ~~~~~ | /
| ~~~~~~~ BOX |/
+-------------*/
#pragma once
#include <iostream>
#include <string>
namespace sb
{
/*!
* Timer in seconds which can be paused and resumed.
*
* It must be updated every frame with the timestamp passed to Game::update, regardless of whether it is actively timing or not.
*/
class Timer
{
private:
bool timing = false, previous_is_recorded = false;
float stamp_previous = 0.0f, frame_duration = 0.0f, _elapsed = 0.0f, _stamp = 0.0f;
public:
enum State : bool
{
OFF,
ON
};
/*!
* @return boolean indicating whether timer object is keeping time or not
*/
operator bool() const;
/*!
* Convert a sb::Timer to a float by returning the elapsed time.
*/
operator float() const;
/*!
* Toggle timing on/off
*/
void toggle();
/*!
* @param state set timing state explictly by passing a boolean
*/
void toggle(bool state);
/*!
* Start timing.
*/
void on();
/*!
* Stop timing.
*/
void off();
/*!
* Reset time elapsed to zero.
*/
void reset();
/*!
* @return seconds elapsed on timer
*/
float elapsed() const;
/*!
* @param time Set the clock to a certain amount of seconds
*/
void elapsed(float seconds);
/*!
* @return length of the previous frame in seconds
*/
float frame() const;
/*!
* @return timestamp at the last update
*/
float stamp() const;
/*!
* Update the timer's elapsed time using the given timestamp to determine the amount of time passed since the previous update.
*
* The timestamp will be saved and can be retrieved with Timer::stamp().
*
* The timer can be updated even if it is not currently timing.
*
* The timestamp should be forwarded from the value passed to Game::update, so that it is consistently the timestamp at the
* beginning of the frame.
*
* @param stamp seconds elapsed since the start of the program
*/
void update(float stamp);
/*!
* Applies delta timing to a value: returns the value as weighted by the amount of time passed since the
* last frame update, allowing for values to change the same amount over time independent of the frame rate.
* The amount passed is how much the value should change per second.
*
* @param amount any scalar value to be weighted
* @return weighted value
*/
template<typename Type>
Type delta(Type amount) const
{
return frame() * amount;
}
};
}