turned #define WIN32_USETIMEGETTIME into a cvar named sys_usetimegettime, default...
[xonotic/darkplaces.git] / sys_win.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // sys_win.c -- Win32 system interface code
21
22 #include "quakedef.h"
23 #include "winquake.h"
24 #include "errno.h"
25 #include "resource.h"
26 #include "conproc.h"
27 #include "direct.h"
28
29 cvar_t sys_usetimegettime = {CVAR_SAVE, "sys_usetimegettime", "1"};
30
31 // # of seconds to wait on Sys_Error running dedicated before exiting
32 #define CONSOLE_ERROR_TIMEOUT   60.0
33 // sleep time on pause or minimization
34 #define PAUSE_SLEEP             50
35 // sleep time when not focus
36 #define NOT_FOCUS_SLEEP 20
37
38 int                     starttime;
39
40 static qboolean         sc_return_on_enter = false;
41 HANDLE                          hinput, houtput;
42
43 static HANDLE   tevent;
44 static HANDLE   hFile;
45 static HANDLE   heventParent;
46 static HANDLE   heventChild;
47
48 /*
49 ===============================================================================
50
51 QFile IO
52
53 ===============================================================================
54 */
55
56 // LordHavoc: 256 pak files (was 10)
57 #define MAX_HANDLES             256
58 QFile   *sys_handles[MAX_HANDLES];
59
60 int             findhandle (void)
61 {
62         int             i;
63
64         for (i=1 ; i<MAX_HANDLES ; i++)
65                 if (!sys_handles[i])
66                         return i;
67         Sys_Error ("out of handles");
68         return -1;
69 }
70
71 /*
72 ================
73 Sys_FileLength
74 ================
75 */
76 int Sys_FileLength (QFile *f)
77 {
78         int             pos;
79         int             end;
80
81         pos = Qtell (f);
82         Qseek (f, 0, SEEK_END);
83         end = Qtell (f);
84         Qseek (f, pos, SEEK_SET);
85
86         return end;
87 }
88
89 int Sys_FileOpenRead (char *path, int *hndl)
90 {
91         QFile   *f;
92         int             i, retval;
93
94         i = findhandle ();
95
96         f = Qopen(path, "rbz");
97
98         if (!f)
99         {
100                 *hndl = -1;
101                 retval = -1;
102         }
103         else
104         {
105                 sys_handles[i] = f;
106                 *hndl = i;
107                 retval = Sys_FileLength(f);
108         }
109
110         return retval;
111 }
112
113 int Sys_FileOpenWrite (char *path)
114 {
115         QFile   *f;
116         int             i;
117
118         i = findhandle ();
119
120         f = Qopen(path, "wb");
121         if (!f)
122         {
123                 Con_Printf("Sys_FileOpenWrite: Error opening %s: %s", path, strerror(errno));
124                 return 0;
125         }
126         sys_handles[i] = f;
127
128         return i;
129 }
130
131 void Sys_FileClose (int handle)
132 {
133         Qclose (sys_handles[handle]);
134         sys_handles[handle] = NULL;
135 }
136
137 void Sys_FileSeek (int handle, int position)
138 {
139         Qseek (sys_handles[handle], position, SEEK_SET);
140 }
141
142 int Sys_FileRead (int handle, void *dest, int count)
143 {
144         return Qread (sys_handles[handle], dest, count);
145 }
146
147 int Sys_FileWrite (int handle, void *data, int count)
148 {
149         return Qwrite (sys_handles[handle], data, count);
150 }
151
152 int     Sys_FileTime (char *path)
153 {
154         QFile   *f;
155
156         f = Qopen(path, "rb");
157         if (f)
158         {
159                 Qclose(f);
160                 return 1;
161         }
162
163         return -1;
164 }
165
166 void Sys_mkdir (char *path)
167 {
168         _mkdir (path);
169 }
170
171
172 /*
173 ===============================================================================
174
175 SYSTEM IO
176
177 ===============================================================================
178 */
179
180 void SleepUntilInput (int time);
181
182 void Sys_Error (char *error, ...)
183 {
184         va_list         argptr;
185         char            text[1024], text2[1024];
186         char            *text3 = "Press Enter to exit\n";
187         char            *text4 = "***********************************\n";
188         char            *text5 = "\n";
189         DWORD           dummy;
190         double          starttime;
191         static int      in_sys_error0 = 0;
192         static int      in_sys_error1 = 0;
193         static int      in_sys_error2 = 0;
194         static int      in_sys_error3 = 0;
195
196         if (!in_sys_error3)
197                 in_sys_error3 = 1;
198
199         va_start (argptr, error);
200         vsprintf (text, error, argptr);
201         va_end (argptr);
202
203         if (cls.state == ca_dedicated)
204         {
205                 va_start (argptr, error);
206                 vsprintf (text, error, argptr);
207                 va_end (argptr);
208
209                 sprintf (text2, "ERROR: %s\n", text);
210                 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
211                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
212                 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
213                 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
214                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
215
216
217                 starttime = Sys_DoubleTime ();
218                 sc_return_on_enter = true;      // so Enter will get us out of here
219
220                 while (!Sys_ConsoleInput () && ((Sys_DoubleTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
221                         SleepUntilInput(1);
222         }
223         else
224         {
225         // switch to windowed so the message box is visible, unless we already
226         // tried that and failed
227                 if (!in_sys_error0)
228                 {
229                         in_sys_error0 = 1;
230                         VID_SetDefaultMode ();
231                         MessageBox(NULL, text, "Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
232                 }
233                 else
234                         MessageBox(NULL, text, "Double Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
235         }
236
237         if (!in_sys_error1)
238         {
239                 in_sys_error1 = 1;
240                 Host_Shutdown ();
241         }
242
243 // shut down QHOST hooks if necessary
244         if (!in_sys_error2)
245         {
246                 in_sys_error2 = 1;
247                 DeinitConProc ();
248         }
249
250         exit (1);
251 }
252
253 void Sys_Quit (void)
254 {
255         Host_Shutdown();
256
257         if (tevent)
258                 CloseHandle (tevent);
259
260         if (cls.state == ca_dedicated)
261                 FreeConsole ();
262
263 // shut down QHOST hooks if necessary
264         DeinitConProc ();
265
266         exit (0);
267 }
268
269
270 /*
271 ================
272 Sys_DoubleTime
273 ================
274 */
275 double Sys_DoubleTime (void)
276 {
277         static int first = true;
278         static double oldtime = 0.0, curtime = 0.0;
279         double newtime;
280         // LordHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
281         if (sys_usetimegettime.integer)
282         {
283                 static int firsttimegettime = true;
284                 // timeGetTime
285                 // platform:
286                 // Windows 95/98/ME/NT/2000/XP
287                 // features:
288                 // reasonable accuracy (millisecond)
289                 // issues:
290                 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
291
292                 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
293                 if (firsttimegettime)
294                 {
295                         timeBeginPeriod (1);
296                         firsttimegettime = false;
297                 }
298
299                 newtime = (double) timeGetTime () / 1000.0;
300         }
301         else
302         {
303                 // QueryPerformanceCounter
304                 // platform:
305                 // Windows 95/98/ME/NT/2000/XP
306                 // features:
307                 // very accurate (CPU cycles)
308                 // known issues:
309                 // does not necessarily match realtime too well (tends to get faster and faster in win98)
310                 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
311                 double timescale;
312                 LARGE_INTEGER PerformanceFreq;
313                 LARGE_INTEGER PerformanceCount;
314
315                 if (!QueryPerformanceFrequency (&PerformanceFreq))
316                         Sys_Error ("No hardware timer available");
317                 QueryPerformanceCounter (&PerformanceCount);
318
319                 #ifdef __BORLANDC__
320                 timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
321                 newtime = ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale;
322                 #else
323                 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
324                 newtime = ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
325                 #endif
326         }
327
328         if (first)
329         {
330                 first = false;
331                 oldtime = newtime;
332         }
333
334         if (newtime < oldtime)
335                 Con_Printf("Sys_DoubleTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, newtime - oldtime);
336         else
337                 curtime += newtime - oldtime;
338         oldtime = newtime;
339
340         return curtime;
341 }
342
343
344 char *Sys_ConsoleInput (void)
345 {
346         static char text[256];
347         static int len;
348         INPUT_RECORD recs[1024];
349         int ch;
350         DWORD numread, numevents, dummy;
351
352         if (cls.state != ca_dedicated)
353                 return NULL;
354
355
356         for ( ;; )
357         {
358                 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
359                         Sys_Error ("Error getting # of console events");
360
361                 if (numevents <= 0)
362                         break;
363
364                 if (!ReadConsoleInput(hinput, recs, 1, &numread))
365                         Sys_Error ("Error reading console input");
366
367                 if (numread != 1)
368                         Sys_Error ("Couldn't read console input");
369
370                 if (recs[0].EventType == KEY_EVENT)
371                 {
372                         if (!recs[0].Event.KeyEvent.bKeyDown)
373                         {
374                                 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
375
376                                 switch (ch)
377                                 {
378                                         case '\r':
379                                                 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
380
381                                                 if (len)
382                                                 {
383                                                         text[len] = 0;
384                                                         len = 0;
385                                                         return text;
386                                                 }
387                                                 else if (sc_return_on_enter)
388                                                 {
389                                                 // special case to allow exiting from the error handler on Enter
390                                                         text[0] = '\r';
391                                                         len = 0;
392                                                         return text;
393                                                 }
394
395                                                 break;
396
397                                         case '\b':
398                                                 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
399                                                 if (len)
400                                                 {
401                                                         len--;
402                                                 }
403                                                 break;
404
405                                         default:
406                                                 if (ch >= ' ')
407                                                 {
408                                                         WriteFile(houtput, &ch, 1, &dummy, NULL);
409                                                         text[len] = ch;
410                                                         len = (len + 1) & 0xff;
411                                                 }
412
413                                                 break;
414
415                                 }
416                         }
417                 }
418         }
419
420         return NULL;
421 }
422
423 void Sys_Sleep (void)
424 {
425         Sleep (1);
426 }
427
428
429 void Sys_SendKeyEvents (void)
430 {
431         MSG msg;
432
433         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
434         {
435         // we always update if there are any event, even if we're paused
436                 scr_skipupdate = 0;
437
438                 if (!GetMessage (&msg, NULL, 0, 0))
439                         Sys_Quit ();
440
441                 TranslateMessage (&msg);
442                 DispatchMessage (&msg);
443         }
444 }
445
446
447 /*
448 ==============================================================================
449
450 WINDOWS CRAP
451
452 ==============================================================================
453 */
454
455
456 void SleepUntilInput (int time)
457 {
458         MsgWaitForMultipleObjects(1, &tevent, false, time, QS_ALLINPUT);
459 }
460
461
462 /*
463 ==================
464 WinMain
465 ==================
466 */
467 HINSTANCE       global_hInstance;
468 int                     global_nCmdShow;
469 char            *argv[MAX_NUM_ARGVS];
470 static char     *empty_string = "";
471
472 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
473 {
474         double                  frameoldtime, framenewtime;
475         MEMORYSTATUS    lpBuffer;
476         static  char    cwd[1024];
477         int                             t;
478
479         /* previous instances do not exist in Win32 */
480         if (hPrevInstance)
481                 return 0;
482
483         Cvar_RegisterVariable(&sys_usetimegettime);
484
485         global_hInstance = hInstance;
486         global_nCmdShow = nCmdShow;
487
488         lpBuffer.dwLength = sizeof(MEMORYSTATUS);
489         GlobalMemoryStatus (&lpBuffer);
490
491         if (!GetCurrentDirectory (sizeof(cwd), cwd))
492                 Sys_Error ("Couldn't determine current directory");
493
494         if (cwd[strlen(cwd)-1] == '/')
495                 cwd[strlen(cwd)-1] = 0;
496
497         memset(&host_parms, 0, sizeof(host_parms));
498
499         host_parms.basedir = cwd;
500
501         host_parms.argc = 1;
502         argv[0] = empty_string;
503
504         while (*lpCmdLine && (host_parms.argc < MAX_NUM_ARGVS))
505         {
506                 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
507                         lpCmdLine++;
508
509                 if (*lpCmdLine)
510                 {
511                         argv[host_parms.argc] = lpCmdLine;
512                         host_parms.argc++;
513
514                         while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
515                                 lpCmdLine++;
516
517                         if (*lpCmdLine)
518                         {
519                                 *lpCmdLine = 0;
520                                 lpCmdLine++;
521                         }
522
523                 }
524         }
525
526         host_parms.argv = argv;
527
528         COM_InitArgv (host_parms.argc, host_parms.argv);
529
530         host_parms.argc = com_argc;
531         host_parms.argv = com_argv;
532
533         Sys_Shared_EarlyInit();
534
535         tevent = CreateEvent(NULL, false, false, NULL);
536
537         if (!tevent)
538                 Sys_Error ("Couldn't create event");
539
540         // LordHavoc: can't check cls.state because it hasn't been initialized yet
541         // if (cls.state == ca_dedicated)
542         if (COM_CheckParm("-dedicated"))
543         {
544                 if (!AllocConsole ())
545                         Sys_Error ("Couldn't create dedicated server console");
546
547                 hinput = GetStdHandle (STD_INPUT_HANDLE);
548                 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
549
550         // give QHOST a chance to hook into the console
551                 if ((t = COM_CheckParm ("-HFILE")) > 0)
552                 {
553                         if (t < com_argc)
554                                 hFile = (HANDLE)atoi (com_argv[t+1]);
555                 }
556
557                 if ((t = COM_CheckParm ("-HPARENT")) > 0)
558                 {
559                         if (t < com_argc)
560                                 heventParent = (HANDLE)atoi (com_argv[t+1]);
561                 }
562
563                 if ((t = COM_CheckParm ("-HCHILD")) > 0)
564                 {
565                         if (t < com_argc)
566                                 heventChild = (HANDLE)atoi (com_argv[t+1]);
567                 }
568
569                 InitConProc (hFile, heventParent, heventChild);
570         }
571
572 // because sound is off until we become active
573         S_BlockSound ();
574
575         Host_Init ();
576
577         Sys_Shared_LateInit();
578
579         frameoldtime = Sys_DoubleTime ();
580
581         /* main window message loop */
582         while (1)
583         {
584                 if (cls.state != ca_dedicated)
585                 {
586                 // yield the CPU for a little while when paused, minimized, or not the focus
587                         if ((cl.paused && !vid_activewindow) || vid_hidden)
588                         {
589                                 SleepUntilInput (PAUSE_SLEEP);
590                                 scr_skipupdate = 1;             // no point in bothering to draw
591                         }
592                         else if (!vid_activewindow)
593                                 SleepUntilInput (NOT_FOCUS_SLEEP);
594                 }
595
596                 framenewtime = Sys_DoubleTime ();
597                 Host_Frame (framenewtime - frameoldtime);
598                 frameoldtime = framenewtime;
599         }
600
601         /* return success of application */
602         return true;
603 }
604