use num_traits::{Float, FromPrimitive};
use timelib;
#[derive(Debug, Clone)]
pub struct Time<T> {
frame: usize,
delta: T,
unscaled_fixed_delta: T,
fixed_delta: T,
scale: T,
current: T,
start_time: T,
fps: T,
}
impl<T> Default for Time<T>
where
T: Float + FromPrimitive,
{
#[inline]
fn default() -> Self {
Self::new(
0_usize,
T::from_f64(0.016666666666666667).unwrap(),
T::from_f64(0.016666666666666667).unwrap(),
T::one(),
T::zero(),
T::zero(),
T::from_usize(60).unwrap(),
)
}
}
impl<T> Time<T>
where
T: Float,
{
#[inline(always)]
pub fn new(
frame: usize,
delta: T,
fixed_delta: T,
scale: T,
current: T,
start_time: T,
fps: T,
) -> Self {
Time {
frame: frame,
delta: delta,
unscaled_fixed_delta: fixed_delta,
fixed_delta: fixed_delta * scale,
scale: scale,
current: current,
start_time: start_time,
fps: fps,
}
}
}
impl<T> Time<T>
where
T: Float + FromPrimitive,
{
#[inline(always)]
pub fn frame(&self) -> usize {
self.frame
}
#[inline(always)]
pub fn delta(&self) -> T {
self.delta
}
#[inline(always)]
pub fn current(&self) -> T {
self.current - self.start_time
}
#[inline(always)]
pub fn start_time(&self) -> T {
self.start_time
}
#[inline]
pub fn fps(&self) -> T {
T::from_usize(self.frame).unwrap() / self.current()
}
#[inline]
pub fn set_scale(&mut self, scale: T) -> &mut Self {
self.scale = scale;
self.fixed_delta = self.unscaled_fixed_delta * scale;
self
}
#[inline(always)]
pub fn scale(&self) -> T {
self.scale
}
#[inline(always)]
pub fn fixed_delta(&self) -> T {
self.fixed_delta
}
#[inline]
pub fn set_fixed_delta(&mut self, fixed_delta: T) -> &mut Self {
self.unscaled_fixed_delta = fixed_delta;
self.fixed_delta = self.unscaled_fixed_delta * self.scale;
self
}
#[inline]
fn internal_update(&mut self, current_time: T) -> &mut Self {
if self.frame == 0 {
self.start_time = current_time;
self.current = current_time - self.delta;
}
let delta = current_time - self.current;
self.frame += 1;
self.current = current_time;
self.delta = delta;
self
}
#[inline]
pub fn update(&mut self) -> &mut Self {
self.internal_update(T::from_f64(timelib::precise_time_s()).unwrap())
}
}