You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

114 lines
2.0 KiB

  1. //
  2. // Deus Hax (working title)
  3. // Copyright (c) 2010 Sam Hocevar <sam@hocevar.net>
  4. //
  5. #if defined HAVE_CONFIG_H
  6. # include "config.h"
  7. #endif
  8. #include <cstdlib>
  9. #include <cstdio>
  10. #include <stdint.h>
  11. #if defined __linux__
  12. # include <sys/time.h>
  13. #elif defined _WIN32
  14. # define WIN32_LEAN_AND_MEAN
  15. # include <windows.h>
  16. #else
  17. # include <SDL.h>
  18. #endif
  19. // XXX
  20. #include <SDL.h>
  21. #include "timer.h"
  22. /*
  23. * Timer implementation class
  24. */
  25. class TimerData
  26. {
  27. friend class Timer;
  28. private:
  29. TimerData()
  30. {
  31. #if defined __linux__
  32. gettimeofday(&tv0, NULL);
  33. #elif defined _WIN32
  34. LARGE_INTEGER tmp;
  35. QueryPerformanceFrequency(&tmp);
  36. seconds_per_cycle = 1.0f / tmp.QuadPart;
  37. QueryPerformanceCounter(&cycles0);
  38. #else
  39. SDL_Init(SDL_INIT_TIMER);
  40. ticks0 = SDL_GetTicks();
  41. #endif
  42. }
  43. float GetSeconds(bool update)
  44. {
  45. float ret;
  46. #if defined __linux__
  47. struct timeval tv;
  48. gettimeofday(&tv, NULL);
  49. ret = 1e-6f * (tv.tv_usec - tv0.tv_usec) + (tv.tv_sec - tv0.tv_sec);
  50. if (update)
  51. tv0 = tv;
  52. #elif defined _WIN32
  53. LARGE_INTEGER cycles;
  54. QueryPerformanceCounter(&cycles);
  55. ret = seconds_per_cycle * (cycles.QuadPart - cycles0.QuadPart);
  56. if (update)
  57. cycles0 = cycles;
  58. #else
  59. Uint32 ticks = SDL_GetTicks();
  60. ret = 1e-3f * (ticks - ticks0);
  61. if (update)
  62. ticks0 = ticks;
  63. #endif
  64. return ret;
  65. }
  66. #if defined __linux__
  67. struct timeval tv0;
  68. #elif defined _WIN32
  69. float seconds_per_cycle;
  70. LARGE_INTEGER cycles0;
  71. #else
  72. Uint32 ticks0;
  73. #endif
  74. };
  75. /*
  76. * Timer public class
  77. */
  78. Timer::Timer()
  79. {
  80. data = new TimerData();
  81. }
  82. Timer::~Timer()
  83. {
  84. delete data;
  85. }
  86. float Timer::GetSeconds()
  87. {
  88. return data->GetSeconds(true);
  89. }
  90. void Timer::WaitSeconds(float seconds)
  91. {
  92. float sleep = seconds - data->GetSeconds(false);
  93. if (sleep <= 1e-4f)
  94. return;
  95. SDL_Delay((int)(sleep * 1000.0f + 0.5f));
  96. }