130 lines
2.2 KiB
C++
130 lines
2.2 KiB
C++
// TJP COPYRIGHT HEADER
|
|
|
|
//
|
|
// Server.hpp
|
|
// TimeSync
|
|
//
|
|
// Created by Timothy Prepscius on 1/27/17.
|
|
// Copyright © 2017 Timothy Prepscius. All rights reserved.
|
|
//
|
|
|
|
#pragma once
|
|
|
|
#include "TimeSource.h"
|
|
#include "Time.h"
|
|
#include <chrono>
|
|
|
|
namespace timprepscius {
|
|
namespace core {
|
|
namespace time {
|
|
|
|
class TimeSource
|
|
{
|
|
public:
|
|
virtual ~TimeSource () {}
|
|
|
|
virtual Time getTime () = 0;
|
|
virtual size_t getTimeTicks () = 0;
|
|
virtual Time getTimeAt (size_t ticks) = 0;
|
|
} ;
|
|
|
|
template<typename Resolution>
|
|
class TimeSourceResolution : public TimeSource
|
|
{
|
|
public:
|
|
typedef Resolution resolution;
|
|
|
|
Time getTime () override
|
|
{
|
|
return getTimeAt(getTimeTicks());
|
|
}
|
|
|
|
Time getTimeAt (size_t ticks) override
|
|
{
|
|
auto denominator = Resolution::period::den;
|
|
if (time::Denominator == 1)
|
|
return toTime((time::V)ticks / denominator);
|
|
|
|
const auto d0 = time::Denominator;
|
|
const auto d1 = denominator;
|
|
|
|
if (d0 > d1)
|
|
{
|
|
V r = d0 / d1;
|
|
return toTime( (time::V)ticks * r );
|
|
}
|
|
else
|
|
{
|
|
V r = d1 / d0;
|
|
return toTime( (time::V)ticks / r );
|
|
}
|
|
}
|
|
} ;
|
|
|
|
template<typename clock_type_t, typename Resolution = std::chrono::microseconds>
|
|
class TimeSourceResolutionStandard : public TimeSourceResolution<Resolution>
|
|
{
|
|
public:
|
|
typedef clock_type_t clock_type;
|
|
|
|
protected:
|
|
clock_type clock;
|
|
typename clock_type::time_point startTime;
|
|
|
|
public:
|
|
TimeSourceResolutionStandard ()
|
|
{
|
|
startTime = clock.now();
|
|
}
|
|
|
|
size_t getTimeTicks () override
|
|
{
|
|
return std::chrono::duration_cast<Resolution>(clock.now() - startTime).count() + 0;
|
|
}
|
|
} ;
|
|
|
|
class ManualTimeSource : public TimeSource
|
|
{
|
|
protected:
|
|
TimeSource *source;
|
|
size_t ticks;
|
|
|
|
public:
|
|
ManualTimeSource(TimeSource *source_) :
|
|
source(source_)
|
|
{
|
|
ticks = source_->getTimeTicks();
|
|
}
|
|
|
|
size_t getTimeTicks () override
|
|
{
|
|
return ticks;
|
|
}
|
|
|
|
Time getTime () override
|
|
{
|
|
return source->getTimeAt(ticks);
|
|
}
|
|
|
|
Time getTimeAt (size_t ticks) override
|
|
{
|
|
return source->getTimeAt(ticks);
|
|
}
|
|
|
|
void update ()
|
|
{
|
|
ticks = source->getTimeTicks();
|
|
}
|
|
} ;
|
|
|
|
class TimeSourceStandard : public TimeSourceResolutionStandard<std::chrono::high_resolution_clock>
|
|
{
|
|
public:
|
|
TimeSourceStandard() {}
|
|
} ;
|
|
|
|
} // namespace
|
|
} // namespace
|
|
} // namespace
|
|
|