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