Baselib_CountdownTimer.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #pragma once
  2. #include "Baselib_Timer.h"
  3. #include <math.h>
  4. typedef struct Baselib_CountdownTimer
  5. {
  6. Baselib_Timer_Ticks startTimeInTicks;
  7. Baselib_Timer_Ticks timeoutInTicks;
  8. } Baselib_CountdownTimer;
  9. BASELIB_INLINE_API Baselib_Timer_Ticks Detail_MillisecondsToTicks(double milliseconds)
  10. {
  11. return (Baselib_Timer_Ticks)(milliseconds * Baselib_NanosecondsPerMillisecond / Baselib_Timer_TickToNanosecondsConversionFactor);
  12. }
  13. BASELIB_INLINE_API double Detail_TicksToMilliseconds(Baselib_Timer_Ticks ticks)
  14. {
  15. return ticks * Baselib_Timer_TickToNanosecondsConversionFactor / Baselib_NanosecondsPerMillisecond;
  16. }
  17. // Create and start a countdown timer
  18. BASELIB_INLINE_API Baselib_CountdownTimer Baselib_CountdownTimer_StartMs(uint32_t timeoutInMilliseconds)
  19. {
  20. const Baselib_CountdownTimer timer = {Baselib_Timer_GetHighPrecisionTimerTicks(), Detail_MillisecondsToTicks(timeoutInMilliseconds)};
  21. return timer;
  22. }
  23. BASELIB_INLINE_API Baselib_CountdownTimer Baselib_CountdownTimer_StartTicks(Baselib_Timer_Ticks timeoutInTicks)
  24. {
  25. const Baselib_CountdownTimer timer = {Baselib_Timer_GetHighPrecisionTimerTicks(), timeoutInTicks};
  26. return timer;
  27. }
  28. // Get the number of ticks left before countdown expires.
  29. //
  30. // This function is guaranteed to return zero once timeout expired.
  31. // It is also guaranteed that this function will not return zero until timeout expires.
  32. BASELIB_INLINE_API Baselib_Timer_Ticks Baselib_CountdownTimer_GetTimeLeftInTicks(Baselib_CountdownTimer timer)
  33. {
  34. const Baselib_Timer_Ticks then = timer.startTimeInTicks;
  35. const Baselib_Timer_Ticks now = Baselib_Timer_GetHighPrecisionTimerTicks();
  36. const Baselib_Timer_Ticks timeLeft = timer.timeoutInTicks - (now - then);
  37. return timeLeft <= timer.timeoutInTicks ? timeLeft : 0;
  38. }
  39. // Get the number of milliseconds left before countdown expires.
  40. //
  41. // This function is guaranteed to return zero once timeout expired.
  42. // It is also guaranteed that this function will not return zero until timeout expires.
  43. BASELIB_INLINE_API uint32_t Baselib_CountdownTimer_GetTimeLeftInMilliseconds(Baselib_CountdownTimer timer)
  44. {
  45. const Baselib_Timer_Ticks timeLeft = Baselib_CountdownTimer_GetTimeLeftInTicks(timer);
  46. return (uint32_t)ceil(Detail_TicksToMilliseconds(timeLeft));
  47. }
  48. // Check if timout has been reached.
  49. BASELIB_INLINE_API bool Baselib_CountdownTimer_TimeoutExpired(Baselib_CountdownTimer timer)
  50. {
  51. return Baselib_CountdownTimer_GetTimeLeftInTicks(timer) == 0;
  52. }