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