source: trunk/src/timer.cpp @ 118

Last change on this file since 118 was 118, checked in by sam, 11 years ago

Fixed framerate now has sub-millisecond accuracy on Linux.

  • 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#   include <SDL.h> // FIXME: this should not be needed
21#else
22#   include <SDL.h>
23#endif
24
25#include "timer.h"
26
27/*
28 * Timer implementation class
29 */
30
31class TimerData
32{
33    friend class Timer;
34
35private:
36    TimerData()
37    {
38#if defined __linux__
39        gettimeofday(&tv0, NULL);
40#elif defined _WIN32
41        LARGE_INTEGER tmp;
42        QueryPerformanceFrequency(&tmp);
43        seconds_per_cycle = 1.0f / tmp.QuadPart;
44        QueryPerformanceCounter(&cycles0);
45#else
46        SDL_Init(SDL_INIT_TIMER);
47        ticks0 = SDL_GetTicks();
48#endif
49    }
50
51    float GetSeconds(bool update)
52    {
53        float ret;
54#if defined __linux__
55        struct timeval tv;
56        gettimeofday(&tv, NULL);
57        ret = 1e-6f * (tv.tv_usec - tv0.tv_usec) + (tv.tv_sec - tv0.tv_sec);
58        if (update)
59            tv0 = tv;
60#elif defined _WIN32
61        LARGE_INTEGER cycles;
62        QueryPerformanceCounter(&cycles);
63        ret = seconds_per_cycle * (cycles.QuadPart - cycles0.QuadPart);
64        if (update)
65            cycles0 = cycles;
66#else
67        Uint32 ticks = SDL_GetTicks();
68        ret = 1e-3f * (ticks - ticks0);
69        if (update)
70            ticks0 = ticks;
71#endif
72        return ret;
73    }
74
75    void WaitSeconds(float seconds)
76    {
77#if defined __linux__
78        usleep((int)(seconds * 1000000.0f));
79#elif defined _WIN32
80        /* FIXME: use native Win32 stuff */
81        SDL_Delay((int)(seconds * 1000.0f + 0.5f));
82#else
83        SDL_Delay((int)(seconds * 1000.0f + 0.5f));
84#endif
85    }
86
87#if defined __linux__
88    struct timeval tv0;
89#elif defined _WIN32
90    float seconds_per_cycle;
91    LARGE_INTEGER cycles0;
92#else
93    Uint32 ticks0;
94#endif
95};
96
97/*
98 * Timer public class
99 */
100
101Timer::Timer()
102{
103    data = new TimerData();
104}
105
106Timer::~Timer()
107{
108    delete data;
109}
110
111float Timer::GetSeconds()
112{
113    return data->GetSeconds(true);
114}
115
116void Timer::WaitSeconds(float seconds)
117{
118    float sleep = seconds - data->GetSeconds(false);
119    if (sleep > 1e-4f)
120        data->WaitSeconds(sleep);
121}
122
Note: See TracBrowser for help on using the repository browser.