1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
#ifdef _WIN32
#include <windows.h>
#if CETRIS_HI_RES
static DWORD WINAPI ctrs_game_loop(void* data) {
ctrs_game* game = (ctrs_game*)data;
LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
LARGE_INTEGER Frequency;
QueryPerformanceFrequency(&Frequency);
QueryPerformanceCounter(&StartingTime);
while(1) {
if (game->waiting) break;
QueryPerformanceCounter(&EndingTime);
ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;
ElapsedMicroseconds.QuadPart *= 1000000;
ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;
game->timer = ElapsedMicroseconds.QuadPart;
game->tick = ElapsedMicroseconds.QuadPart / 1000;
if (!ctrs_update_game_tick(game)) {
break;
}
Sleep(1);
}
return 0;
}
#else
static DWORD WINAPI ctrs_game_loop(void* data) {
ctrs_game* game = (ctrs_game*)data;
while(1) {
if (game->waiting) break;
game->tick += 16;
if (!ctrs_update_game_tick(game)) {
break;
}
Sleep(16); // little less than 60hz
}
}
#endif
static void ctrs_start_game(ctrs_game *g) {
g->waiting = false;
HANDLE thread = CreateThread(NULL, 0, ctrs_game_loop, g, 0, NULL);
}
#else
#include <pthread.h>
#include <unistd.h>
#if CETRIS_HI_RES
#include <time.h>
static void *ctrs_game_loop(void* data) {
ctrs_game *game = (ctrs_game*)data;
struct timespec start_time, end_time;
clock_gettime(CLOCK_MONOTONIC_RAW, &start_time);
while (1) {
if (game->waiting) break;
clock_gettime(CLOCK_MONOTONIC_RAW, &end_time);
long nsec_elapsed = (end_time.tv_sec - start_time.tv_sec) * (long)1e9 + (end_time.tv_nsec - start_time.tv_nsec);
game->timer = nsec_elapsed / 1000;
game->tick = nsec_elapsed / 1000000;
if (!ctrs_update_game_tick(game)) {
break;
}
usleep(1000);
}
return 0;
}
#else
static void *ctrs_game_loop(void *data) {
ctrs_game* game = (ctrs_game*)data;
while(1) {
if (game->waiting) break;
game->tick += 16;
if (!ctrs_update_game_tick(game)) {
break;
}
// could be more accurate, keeping
// it consistant with windows
usleep(16000);
}
}
#endif
static void ctrs_start_game(ctrs_game *g) {
g->waiting = false;
pthread_t thread;
pthread_create(&thread, NULL, ctrs_game_loop, (void*)g);
}
#endif
|