2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // sys_win.c -- Win32 system interface code
29 #define CONSOLE_ERROR_TIMEOUT 60.0 // # of seconds to wait on Sys_Error running
30 // dedicated before exiting
31 #define PAUSE_SLEEP 50 // sleep time on pause or minimization
32 #define NOT_FOCUS_SLEEP 20 // sleep time when not focus
35 qboolean ActiveApp, Minimized;
39 static double curtime = 0.0;
40 static double lastcurtime = 0.0;
43 static qboolean sc_return_on_enter = false;
44 HANDLE hinput, houtput;
46 static char *tracking_tag = "Clams & Mooses";
50 static HANDLE heventParent;
51 static HANDLE heventChild;
53 void Sys_InitFloatTime (void);
55 volatile int sys_checksum;
64 void Sys_PageIn (void *ptr, int size)
69 // touch all the memory to make sure it's there. The 16-page skip is to
70 // keep Win 95 from thinking we're trying to page ourselves in (we are
71 // doing that, of course, but there's no reason we shouldn't)
76 for (m=0 ; m<(size - 16 * 0x1000) ; m += 4)
78 sys_checksum += *(int *)&x[m];
79 sys_checksum += *(int *)&x[m + 16 * 0x1000];
87 ===============================================================================
91 ===============================================================================
94 // LordHavoc: 256 pak files (was 10)
95 #define MAX_HANDLES 256
96 FILE *sys_handles[MAX_HANDLES];
102 for (i=1 ; i<MAX_HANDLES ; i++)
105 Sys_Error ("out of handles");
114 int filelength (FILE *f)
120 fseek (f, 0, SEEK_END);
122 fseek (f, pos, SEEK_SET);
127 int Sys_FileOpenRead (char *path, int *hndl)
134 f = fopen(path, "rb");
145 retval = filelength(f);
151 int Sys_FileOpenWrite (char *path)
158 f = fopen(path, "wb");
160 Host_Error ("Error opening %s: %s", path,strerror(errno));
166 void Sys_FileClose (int handle)
168 fclose (sys_handles[handle]);
169 sys_handles[handle] = NULL;
172 void Sys_FileSeek (int handle, int position)
174 fseek (sys_handles[handle], position, SEEK_SET);
177 int Sys_FileRead (int handle, void *dest, int count)
179 return fread (dest, 1, count, sys_handles[handle]);
182 int Sys_FileWrite (int handle, void *data, int count)
184 return fwrite (data, 1, count, sys_handles[handle]);
187 int Sys_FileTime (char *path)
191 f = fopen(path, "rb");
201 void Sys_mkdir (char *path)
208 ===============================================================================
212 ===============================================================================
218 Sys_MakeCodeWriteable
221 void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
225 if (!VirtualProtect((LPVOID)startaddr, length, PAGE_READWRITE, &flOldProtect))
226 Sys_Error("Protection change failed\n");
238 LARGE_INTEGER PerformanceFreq;
239 unsigned int lowpart, highpart;
242 if (!QueryPerformanceFrequency (&PerformanceFreq))
243 Sys_Error ("No hardware timer available");
245 // get 32 out of the 64 time bits such that we have around
246 // 1 microsecond resolution
248 lowpart = (unsigned int)PerformanceFreq.u.LowPart;
249 highpart = (unsigned int)PerformanceFreq.u.HighPart;
251 lowpart = (unsigned int)PerformanceFreq.LowPart;
252 highpart = (unsigned int)PerformanceFreq.HighPart;
256 while (highpart || (lowpart > 2000000.0))
260 lowpart |= (highpart & 1) << 31;
264 pfreq = 1.0 / (double)lowpart;
266 Sys_InitFloatTime ();
268 vinfo.dwOSVersionInfoSize = sizeof(vinfo);
270 if (!GetVersionEx (&vinfo))
271 Sys_Error ("Couldn't get OS info");
273 if ((vinfo.dwMajorVersion < 4) ||
274 (vinfo.dwPlatformId == VER_PLATFORM_WIN32s))
276 Sys_Error ("WinQuake requires at least Win95 or NT 4.0");
279 if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
286 void Sys_Error (char *error, ...)
289 char text[1024], text2[1024];
290 char *text3 = "Press Enter to exit\n";
291 char *text4 = "***********************************\n";
295 static int in_sys_error0 = 0;
296 static int in_sys_error1 = 0;
297 static int in_sys_error2 = 0;
298 static int in_sys_error3 = 0;
303 va_start (argptr, error);
304 vsprintf (text, error, argptr);
309 va_start (argptr, error);
310 vsprintf (text, error, argptr);
313 sprintf (text2, "ERROR: %s\n", text);
314 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
315 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
316 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
317 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
318 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
321 starttime = Sys_FloatTime ();
322 sc_return_on_enter = true; // so Enter will get us out of here
324 while (!Sys_ConsoleInput () &&
325 ((Sys_FloatTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
331 // switch to windowed so the message box is visible, unless we already
332 // tried that and failed
336 VID_SetDefaultMode ();
337 MessageBox(NULL, text, "Quake Error",
338 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
342 MessageBox(NULL, text, "Double Quake Error",
343 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
353 // shut down QHOST hooks if necessary
363 void Sys_Printf (char *fmt, ...)
371 va_start (argptr,fmt);
372 vsprintf (text, fmt, argptr);
375 WriteFile(houtput, text, strlen (text), &dummy, NULL);
385 CloseHandle (tevent);
390 // shut down QHOST hooks if necessary
402 double Sys_FloatTime (void)
404 static int sametimecount;
405 static unsigned int oldtime;
406 static int first = 1;
407 LARGE_INTEGER PerformanceCount;
408 unsigned int temp, t2;
411 QueryPerformanceCounter (&PerformanceCount);
414 temp = ((unsigned int)PerformanceCount.u.LowPart >> lowshift) |
415 ((unsigned int)PerformanceCount.u.HighPart << (32 - lowshift));
418 temp = ((unsigned int)PerformanceCount.LowPart >> lowshift) |
419 ((unsigned int)PerformanceCount.HighPart << (32 - lowshift));
428 // check for turnover or backward time
429 if ((temp <= oldtime) && ((oldtime - temp) < 0x10000000))
431 oldtime = temp; // so we can't get stuck
437 time = (double)t2 * pfreq;
442 if (curtime == lastcurtime)
446 if (sametimecount > 100000)
457 lastcurtime = curtime;
470 void Sys_InitFloatTime (void)
476 j = COM_CheckParm("-starttime");
480 curtime = (double) (atof(com_argv[j+1]));
487 lastcurtime = curtime;
491 char *Sys_ConsoleInput (void)
493 static char text[256];
495 INPUT_RECORD recs[1024];
497 int ch, numread, numevents;
505 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
506 Sys_Error ("Error getting # of console events");
511 if (!ReadConsoleInput(hinput, recs, 1, &numread))
512 Sys_Error ("Error reading console input");
515 Sys_Error ("Couldn't read console input");
517 if (recs[0].EventType == KEY_EVENT)
519 if (!recs[0].Event.KeyEvent.bKeyDown)
521 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
526 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
534 else if (sc_return_on_enter)
536 // special case to allow exiting from the error handler on Enter
545 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
555 WriteFile(houtput, &ch, 1, &dummy, NULL);
557 len = (len + 1) & 0xff;
570 void Sys_Sleep (void)
576 void Sys_SendKeyEvents (void)
580 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
582 // we always update if there are any event, even if we're paused
585 if (!GetMessage (&msg, NULL, 0, 0))
588 TranslateMessage (&msg);
589 DispatchMessage (&msg);
595 ==============================================================================
599 ==============================================================================
608 void SleepUntilInput (int time)
611 MsgWaitForMultipleObjects(1, &tevent, false, time, QS_ALLINPUT);
620 HINSTANCE global_hInstance;
622 char *argv[MAX_NUM_ARGVS];
623 static char *empty_string = "";
625 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
627 double time, oldtime, newtime/*, timediff*/;
628 MEMORYSTATUS lpBuffer;
629 static char cwd[1024];
632 /* previous instances do not exist in Win32 */
636 global_hInstance = hInstance;
637 global_nCmdShow = nCmdShow;
639 lpBuffer.dwLength = sizeof(MEMORYSTATUS);
640 GlobalMemoryStatus (&lpBuffer);
642 if (!GetCurrentDirectory (sizeof(cwd), cwd))
643 Sys_Error ("Couldn't determine current directory");
645 if (cwd[strlen(cwd)-1] == '/')
646 cwd[strlen(cwd)-1] = 0;
648 memset(&host_parms, 0, sizeof(host_parms));
650 host_parms.basedir = cwd;
653 argv[0] = empty_string;
655 while (*lpCmdLine && (host_parms.argc < MAX_NUM_ARGVS))
657 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
662 argv[host_parms.argc] = lpCmdLine;
665 while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
677 host_parms.argv = argv;
679 COM_InitArgv (host_parms.argc, host_parms.argv);
681 host_parms.argc = com_argc;
682 host_parms.argv = com_argv;
684 isDedicated = (COM_CheckParm ("-dedicated") != 0);
686 // take the greater of all the available memory or half the total memory,
687 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
690 host_parms.memsize = lpBuffer.dwAvailPhys;
692 if (host_parms.memsize < MINIMUM_WIN_MEMORY)
693 host_parms.memsize = MINIMUM_WIN_MEMORY;
695 if (host_parms.memsize < (lpBuffer.dwTotalPhys >> 1))
696 host_parms.memsize = lpBuffer.dwTotalPhys >> 1;
698 if (host_parms.memsize > MAXIMUM_WIN_MEMORY)
699 host_parms.memsize = MAXIMUM_WIN_MEMORY;
702 // Sys_PageIn (parms.membase, parms.memsize);
704 tevent = CreateEvent(NULL, false, false, NULL);
707 Sys_Error ("Couldn't create event");
711 if (!AllocConsole ())
713 Sys_Error ("Couldn't create dedicated server console");
716 hinput = GetStdHandle (STD_INPUT_HANDLE);
717 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
719 // give QHOST a chance to hook into the console
720 if ((t = COM_CheckParm ("-HFILE")) > 0)
723 hFile = (HANDLE)atoi (com_argv[t+1]);
726 if ((t = COM_CheckParm ("-HPARENT")) > 0)
729 heventParent = (HANDLE)atoi (com_argv[t+1]);
732 if ((t = COM_CheckParm ("-HCHILD")) > 0)
735 heventChild = (HANDLE)atoi (com_argv[t+1]);
738 InitConProc (hFile, heventParent, heventChild);
743 // because sound is off until we become active
746 Sys_Printf ("Host_Init\n");
749 oldtime = Sys_FloatTime ();
751 /* main window message loop */
756 newtime = Sys_FloatTime ();
757 time = newtime - oldtime;
759 while (time < sys_ticrate.value )
762 newtime = Sys_FloatTime ();
763 time = newtime - oldtime;
768 // yield the CPU for a little while when paused, minimized, or not the focus
769 if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized)
771 SleepUntilInput (PAUSE_SLEEP);
772 scr_skipupdate = 1; // no point in bothering to draw
774 else if (!ActiveApp && !DDActive)
776 SleepUntilInput (NOT_FOCUS_SLEEP);
779 else if (!cls.timedemo && time < (timediff = 1.0 / maxfps.value))
781 newtime = Sys_FloatTime ();
782 time = newtime - oldtime;
784 while (time < timediff)
787 newtime = Sys_FloatTime ();
788 time = newtime - oldtime;
793 newtime = Sys_FloatTime ();
794 time = newtime - oldtime;
801 /* return success of application */