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