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