source: trunk/src/timer.cpp @ 174

Last change on this file since 174 was 174, checked in by sam, 10 years ago

Do not use SDL for Win32 timers. The OS has all we need.

  • Property svn:keywords set to Id
File size: 2.3 KB
Line 
1//
2// Deus Hax (working title)
3// Copyright (c) 2010 Sam Hocevar <sam@hocevar.net>
4//
5
6#if defined HAVE_CONFIG_H
7#   include "config.h"
8#endif
9
10#include <cstdlib>
11#include <cstdio>
12#include <stdint.h>
13
14#if defined __linux__
15#   include <sys/time.h>
16#   include <unistd.h>
17#elif defined _WIN32
18#   define WIN32_LEAN_AND_MEAN
19#   include <windows.h>
20#else
21#   include <SDL.h>
22#endif
23
24#include "core.h"
25
26/*
27 * Timer implementation class
28 */
29
30class TimerData
31{
32    friend class Timer;
33
34private:
35    TimerData()
36    {
37#if defined __linux__
38        gettimeofday(&tv0, NULL);
39#elif defined _WIN32
40        LARGE_INTEGER tmp;
41        QueryPerformanceFrequency(&tmp);
42        ms_per_cycle = 1e3f / tmp.QuadPart;
43        QueryPerformanceCounter(&cycles0);
44#else
45        SDL_Init(SDL_INIT_TIMER);
46        ticks0 = SDL_GetTicks();
47#endif
48    }
49
50    float GetOrWait(float deltams, bool update)
51    {
52        float ret, towait;
53#if defined __linux__
54        struct timeval tv;
55        gettimeofday(&tv, NULL);
56        ret = 1e-3f * (tv.tv_usec - tv0.tv_usec)
57            + 1e3f * (tv.tv_sec - tv0.tv_sec);
58        if (update)
59            tv0 = tv;
60        towait = deltams - ret;
61        if (towait > 0.0f)
62            usleep((int)(towait * 1e3f));
63#elif defined _WIN32
64        LARGE_INTEGER cycles;
65        QueryPerformanceCounter(&cycles);
66        ret = ms_per_cycle * (cycles.QuadPart - cycles0.QuadPart);
67        if (update)
68            cycles0 = cycles;
69        towait = deltams - ret;
70        if (towait > 5e-4f) // FIXME: use native Win32 stuff
71            Sleep((int)(towait + 0.5f));
72#else
73        /* The crappy SDL fallback */
74        Uint32 ticks = SDL_GetTicks();
75        ret = 1e-6f * (ticks - ticks0);
76        if (update)
77            ticks0 = ticks;
78        towait = deltams - ret;
79        if (towait > 0.5f)
80            SDL_Delay((int)(towait + 0.5f));
81#endif
82        return ret;
83    }
84
85#if defined __linux__
86    struct timeval tv0;
87#elif defined _WIN32
88    float ms_per_cycle;
89    LARGE_INTEGER cycles0;
90#else
91    Uint32 ticks0;
92#endif
93};
94
95/*
96 * Timer public class
97 */
98
99Timer::Timer()
100{
101    data = new TimerData();
102}
103
104Timer::~Timer()
105{
106    delete data;
107}
108
109float Timer::GetMs()
110{
111    return data->GetOrWait(0.0f, true);
112}
113
114float Timer::PollMs()
115{
116    return data->GetOrWait(0.0f, false);
117}
118
119void Timer::WaitMs(float deltams)
120{
121    (void)data->GetOrWait(deltams, false);
122}
123
Note: See TracBrowser for help on using the repository browser.