cleaned up/simplified Sys_Error, now should never get in a recursive crash loop,...
[divverent/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
52 DLL MANAGEMENT
53
54 ===============================================================================
55 */
56
57 dllhandle_t Sys_LoadLibrary (const char* name)
58 {
59         return LoadLibrary (name);
60 }
61
62 void Sys_UnloadLibrary (dllhandle_t handle)
63 {
64         FreeLibrary (handle);
65 }
66
67 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
68 {
69         return (void *)GetProcAddress (handle, name);
70 }
71
72
73 /*
74 ===============================================================================
75
76 SYSTEM IO
77
78 ===============================================================================
79 */
80
81 void SleepUntilInput (int time);
82
83 void Sys_Error (const char *error, ...)
84 {
85         va_list         argptr;
86         char            text[1024];
87         static int      in_sys_error0 = 0;
88         static int      in_sys_error1 = 0;
89         static int      in_sys_error2 = 0;
90
91         va_start (argptr, error);
92         vsprintf (text, error, argptr);
93         va_end (argptr);
94
95         // close video so the message box is visible, unless we already tried that
96         if (!in_sys_error0 && cls.state != ca_dedicated)
97         {
98                 in_sys_error0 = 1;
99                 VID_Shutdown();
100         }
101         MessageBox(NULL, text, "Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
102
103         if (!in_sys_error1)
104         {
105                 in_sys_error1 = 1;
106                 Host_Shutdown ();
107         }
108
109 // shut down QHOST hooks if necessary
110         if (!in_sys_error2)
111         {
112                 in_sys_error2 = 1;
113                 DeinitConProc ();
114         }
115
116         exit (1);
117 }
118
119 void Sys_Quit (void)
120 {
121         Host_Shutdown();
122
123         if (tevent)
124                 CloseHandle (tevent);
125
126         if (cls.state == ca_dedicated)
127                 FreeConsole ();
128
129 // shut down QHOST hooks if necessary
130         DeinitConProc ();
131
132         exit (0);
133 }
134
135
136 /*
137 ================
138 Sys_DoubleTime
139 ================
140 */
141 double Sys_DoubleTime (void)
142 {
143         static int first = true;
144         static double oldtime = 0.0, curtime = 0.0;
145         double newtime;
146         // LordHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
147         if (sys_usetimegettime.integer)
148         {
149                 static int firsttimegettime = true;
150                 // timeGetTime
151                 // platform:
152                 // Windows 95/98/ME/NT/2000/XP
153                 // features:
154                 // reasonable accuracy (millisecond)
155                 // issues:
156                 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
157
158                 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
159                 if (firsttimegettime)
160                 {
161                         timeBeginPeriod (1);
162                         firsttimegettime = false;
163                 }
164
165                 newtime = (double) timeGetTime () / 1000.0;
166         }
167         else
168         {
169                 // QueryPerformanceCounter
170                 // platform:
171                 // Windows 95/98/ME/NT/2000/XP
172                 // features:
173                 // very accurate (CPU cycles)
174                 // known issues:
175                 // does not necessarily match realtime too well (tends to get faster and faster in win98)
176                 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
177                 double timescale;
178                 LARGE_INTEGER PerformanceFreq;
179                 LARGE_INTEGER PerformanceCount;
180
181                 if (!QueryPerformanceFrequency (&PerformanceFreq))
182                         Sys_Error ("No hardware timer available");
183                 QueryPerformanceCounter (&PerformanceCount);
184
185                 #ifdef __BORLANDC__
186                 timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
187                 newtime = ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale;
188                 #else
189                 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
190                 newtime = ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
191                 #endif
192         }
193
194         if (first)
195         {
196                 first = false;
197                 oldtime = newtime;
198         }
199
200         if (newtime < oldtime)
201         {
202                 // warn if it's significant
203                 if (newtime - oldtime < -0.01)
204                         Con_Printf("Sys_DoubleTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, newtime - oldtime);
205         }
206         else
207                 curtime += newtime - oldtime;
208         oldtime = newtime;
209
210         return curtime;
211 }
212
213
214 char *Sys_ConsoleInput (void)
215 {
216         static char text[256];
217         static int len;
218         INPUT_RECORD recs[1024];
219         int ch;
220         DWORD numread, numevents, dummy;
221
222         if (cls.state != ca_dedicated)
223                 return NULL;
224
225
226         for ( ;; )
227         {
228                 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
229                         Sys_Error ("Error getting # of console events");
230
231                 if (numevents <= 0)
232                         break;
233
234                 if (!ReadConsoleInput(hinput, recs, 1, &numread))
235                         Sys_Error ("Error reading console input");
236
237                 if (numread != 1)
238                         Sys_Error ("Couldn't read console input");
239
240                 if (recs[0].EventType == KEY_EVENT)
241                 {
242                         if (!recs[0].Event.KeyEvent.bKeyDown)
243                         {
244                                 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
245
246                                 switch (ch)
247                                 {
248                                         case '\r':
249                                                 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
250
251                                                 if (len)
252                                                 {
253                                                         text[len] = 0;
254                                                         len = 0;
255                                                         return text;
256                                                 }
257                                                 else if (sc_return_on_enter)
258                                                 {
259                                                 // special case to allow exiting from the error handler on Enter
260                                                         text[0] = '\r';
261                                                         len = 0;
262                                                         return text;
263                                                 }
264
265                                                 break;
266
267                                         case '\b':
268                                                 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
269                                                 if (len)
270                                                 {
271                                                         len--;
272                                                 }
273                                                 break;
274
275                                         default:
276                                                 if (ch >= ' ')
277                                                 {
278                                                         WriteFile(houtput, &ch, 1, &dummy, NULL);
279                                                         text[len] = ch;
280                                                         len = (len + 1) & 0xff;
281                                                 }
282
283                                                 break;
284
285                                 }
286                         }
287                 }
288         }
289
290         return NULL;
291 }
292
293 void Sys_Sleep (void)
294 {
295         Sleep (1);
296 }
297
298
299 void Sys_SendKeyEvents (void)
300 {
301         MSG msg;
302
303         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
304         {
305         // we always update if there are any event, even if we're paused
306                 scr_skipupdate = 0;
307
308                 if (!GetMessage (&msg, NULL, 0, 0))
309                         Sys_Quit ();
310
311                 TranslateMessage (&msg);
312                 DispatchMessage (&msg);
313         }
314 }
315
316
317 /*
318 ==============================================================================
319
320 WINDOWS CRAP
321
322 ==============================================================================
323 */
324
325
326 void SleepUntilInput (int time)
327 {
328         MsgWaitForMultipleObjects(1, &tevent, false, time, QS_ALLINPUT);
329 }
330
331
332 /*
333 ==================
334 WinMain
335 ==================
336 */
337 HINSTANCE       global_hInstance;
338 int                     global_nCmdShow;
339 const char      *argv[MAX_NUM_ARGVS];
340 char            program_name[MAX_OSPATH];
341
342 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
343 {
344         double frameoldtime, framenewtime;
345         MEMORYSTATUS lpBuffer;
346         int t;
347
348         /* previous instances do not exist in Win32 */
349         if (hPrevInstance)
350                 return 0;
351
352         global_hInstance = hInstance;
353         global_nCmdShow = nCmdShow;
354
355         lpBuffer.dwLength = sizeof(MEMORYSTATUS);
356         GlobalMemoryStatus (&lpBuffer);
357
358         com_argc = 1;
359         program_name[sizeof(program_name)-1] = 0;
360         GetModuleFileNameA(NULL, program_name, sizeof(program_name) - 1);
361         argv[0] = program_name;
362
363         while (*lpCmdLine && (com_argc < MAX_NUM_ARGVS))
364         {
365                 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
366                         lpCmdLine++;
367
368                 if (*lpCmdLine)
369                 {
370                         argv[com_argc] = lpCmdLine;
371                         com_argc++;
372
373                         while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
374                                 lpCmdLine++;
375
376                         if (*lpCmdLine)
377                         {
378                                 *lpCmdLine = 0;
379                                 lpCmdLine++;
380                         }
381                 }
382         }
383         com_argv = argv;
384
385         Sys_Shared_EarlyInit();
386
387         Cvar_RegisterVariable(&sys_usetimegettime);
388
389         tevent = CreateEvent(NULL, false, false, NULL);
390
391         if (!tevent)
392                 Sys_Error ("Couldn't create event");
393
394         // LordHavoc: can't check cls.state because it hasn't been initialized yet
395         // if (cls.state == ca_dedicated)
396         if (COM_CheckParm("-dedicated"))
397         {
398                 if (!AllocConsole ())
399                         Sys_Error ("Couldn't create dedicated server console");
400
401                 hinput = GetStdHandle (STD_INPUT_HANDLE);
402                 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
403
404         // give QHOST a chance to hook into the console
405                 if ((t = COM_CheckParm ("-HFILE")) > 0)
406                 {
407                         if (t < com_argc)
408                                 hFile = (HANDLE)atoi (com_argv[t+1]);
409                 }
410
411                 if ((t = COM_CheckParm ("-HPARENT")) > 0)
412                 {
413                         if (t < com_argc)
414                                 heventParent = (HANDLE)atoi (com_argv[t+1]);
415                 }
416
417                 if ((t = COM_CheckParm ("-HCHILD")) > 0)
418                 {
419                         if (t < com_argc)
420                                 heventChild = (HANDLE)atoi (com_argv[t+1]);
421                 }
422
423                 InitConProc (hFile, heventParent, heventChild);
424         }
425
426 // because sound is off until we become active
427         S_BlockSound ();
428
429         Host_Init ();
430
431         Sys_Shared_LateInit();
432
433         frameoldtime = Sys_DoubleTime ();
434
435         /* main window message loop */
436         while (1)
437         {
438                 if (cls.state != ca_dedicated)
439                 {
440                 // yield the CPU for a little while when paused, minimized, or not the focus
441                         if ((cl.paused && !vid_activewindow) || vid_hidden)
442                         {
443                                 SleepUntilInput (PAUSE_SLEEP);
444                                 scr_skipupdate = 1;             // no point in bothering to draw
445                         }
446                         else if (!vid_activewindow)
447                                 SleepUntilInput (NOT_FOCUS_SLEEP);
448                 }
449
450                 framenewtime = Sys_DoubleTime ();
451                 Host_Frame (framenewtime - frameoldtime);
452                 frameoldtime = framenewtime;
453         }
454
455         /* return success of application */
456         return true;
457 }
458