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 // LordHavoc: raised min to 24mb (was 8.5mb)
30 #define MINIMUM_WIN_MEMORY 0x1800000
31 // LordHavoc: raised max to 24mb (was 16mb)
32 #define MAXIMUM_WIN_MEMORY 0x1800000
34 #define CONSOLE_ERROR_TIMEOUT 60.0 // # of seconds to wait on Sys_Error running
35 // dedicated before exiting
36 #define PAUSE_SLEEP 50 // sleep time on pause or minimization
37 #define NOT_FOCUS_SLEEP 20 // sleep time when not focus
40 qboolean ActiveApp, Minimized;
44 static double curtime = 0.0;
45 static double lastcurtime = 0.0;
48 static qboolean sc_return_on_enter = false;
49 HANDLE hinput, houtput;
51 static char *tracking_tag = "Clams & Mooses";
55 static HANDLE heventParent;
56 static HANDLE heventChild;
58 void MaskExceptions (void);
59 void Sys_InitFloatTime (void);
60 void Sys_PushFPCW_SetHigh (void);
61 void Sys_PopFPCW (void);
63 volatile int sys_checksum;
71 void Sys_PageIn (void *ptr, int size)
76 // touch all the memory to make sure it's there. The 16-page skip is to
77 // keep Win 95 from thinking we're trying to page ourselves in (we are
78 // doing that, of course, but there's no reason we shouldn't)
83 for (m=0 ; m<(size - 16 * 0x1000) ; m += 4)
85 sys_checksum += *(int *)&x[m];
86 sys_checksum += *(int *)&x[m + 16 * 0x1000];
93 ===============================================================================
97 ===============================================================================
100 // LordHavoc: 256 pak files (was 10)
101 #define MAX_HANDLES 256
102 FILE *sys_handles[MAX_HANDLES];
104 int findhandle (void)
108 for (i=1 ; i<MAX_HANDLES ; i++)
111 Sys_Error ("out of handles");
120 int filelength (FILE *f)
126 fseek (f, 0, SEEK_END);
128 fseek (f, pos, SEEK_SET);
133 int Sys_FileOpenRead (char *path, int *hndl)
140 f = fopen(path, "rb");
151 retval = filelength(f);
157 int Sys_FileOpenWrite (char *path)
164 f = fopen(path, "wb");
166 Host_Error ("Error opening %s: %s", path,strerror(errno));
172 void Sys_FileClose (int handle)
174 fclose (sys_handles[handle]);
175 sys_handles[handle] = NULL;
178 void Sys_FileSeek (int handle, int position)
180 fseek (sys_handles[handle], position, SEEK_SET);
183 int Sys_FileRead (int handle, void *dest, int count)
185 return fread (dest, 1, count, sys_handles[handle]);
188 int Sys_FileWrite (int handle, void *data, int count)
190 return fwrite (data, 1, count, sys_handles[handle]);
193 int Sys_FileTime (char *path)
198 f = fopen(path, "rb");
213 void Sys_mkdir (char *path)
220 ===============================================================================
224 ===============================================================================
229 Sys_MakeCodeWriteable
232 void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
236 if (!VirtualProtect((LPVOID)startaddr, length, PAGE_READWRITE, &flOldProtect))
237 Sys_Error("Protection change failed\n");
243 void Sys_SetFPCW (void)
247 void Sys_PushFPCW_SetHigh (void)
251 void Sys_PopFPCW (void)
255 void MaskExceptions (void)
268 LARGE_INTEGER PerformanceFreq;
269 unsigned int lowpart, highpart;
275 if (!QueryPerformanceFrequency (&PerformanceFreq))
276 Sys_Error ("No hardware timer available");
278 // get 32 out of the 64 time bits such that we have around
279 // 1 microsecond resolution
280 lowpart = (unsigned int)PerformanceFreq.LowPart;
281 highpart = (unsigned int)PerformanceFreq.HighPart;
284 while (highpart || (lowpart > 2000000.0))
288 lowpart |= (highpart & 1) << 31;
292 pfreq = 1.0 / (double)lowpart;
294 Sys_InitFloatTime ();
296 vinfo.dwOSVersionInfoSize = sizeof(vinfo);
298 if (!GetVersionEx (&vinfo))
299 Sys_Error ("Couldn't get OS info");
301 if ((vinfo.dwMajorVersion < 4) ||
302 (vinfo.dwPlatformId == VER_PLATFORM_WIN32s))
304 Sys_Error ("WinQuake requires at least Win95 or NT 4.0");
307 if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
314 void Sys_Error (char *error, ...)
317 char text[1024], text2[1024];
318 char *text3 = "Press Enter to exit\n";
319 char *text4 = "***********************************\n";
323 static int in_sys_error0 = 0;
324 static int in_sys_error1 = 0;
325 static int in_sys_error2 = 0;
326 static int in_sys_error3 = 0;
331 va_start (argptr, error);
332 vsprintf (text, error, argptr);
337 va_start (argptr, error);
338 vsprintf (text, error, argptr);
341 sprintf (text2, "ERROR: %s\n", text);
342 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
343 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
344 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
345 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
346 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
349 starttime = Sys_FloatTime ();
350 sc_return_on_enter = true; // so Enter will get us out of here
352 while (!Sys_ConsoleInput () &&
353 ((Sys_FloatTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
359 // switch to windowed so the message box is visible, unless we already
360 // tried that and failed
364 VID_SetDefaultMode ();
365 MessageBox(NULL, text, "Quake Error",
366 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
370 MessageBox(NULL, text, "Double Quake Error",
371 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
381 // shut down QHOST hooks if necessary
391 void Sys_Printf (char *fmt, ...)
399 va_start (argptr,fmt);
400 vsprintf (text, fmt, argptr);
403 WriteFile(houtput, text, strlen (text), &dummy, NULL);
413 CloseHandle (tevent);
418 // shut down QHOST hooks if necessary
430 double Sys_FloatTime (void)
432 static int sametimecount;
433 static unsigned int oldtime;
434 static int first = 1;
435 LARGE_INTEGER PerformanceCount;
436 unsigned int temp, t2;
439 Sys_PushFPCW_SetHigh ();
441 QueryPerformanceCounter (&PerformanceCount);
443 temp = ((unsigned int)PerformanceCount.LowPart >> lowshift) |
444 ((unsigned int)PerformanceCount.HighPart << (32 - lowshift));
453 // check for turnover or backward time
454 if ((temp <= oldtime) && ((oldtime - temp) < 0x10000000))
456 oldtime = temp; // so we can't get stuck
462 time = (double)t2 * pfreq;
467 if (curtime == lastcurtime)
471 if (sametimecount > 100000)
482 lastcurtime = curtime;
497 void Sys_InitFloatTime (void)
503 j = COM_CheckParm("-starttime");
507 curtime = (double) (atof(com_argv[j+1]));
514 lastcurtime = curtime;
518 char *Sys_ConsoleInput (void)
520 static char text[256];
522 INPUT_RECORD recs[1024];
524 int ch, numread, numevents;
532 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
533 Sys_Error ("Error getting # of console events");
538 if (!ReadConsoleInput(hinput, recs, 1, &numread))
539 Sys_Error ("Error reading console input");
542 Sys_Error ("Couldn't read console input");
544 if (recs[0].EventType == KEY_EVENT)
546 if (!recs[0].Event.KeyEvent.bKeyDown)
548 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
553 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
561 else if (sc_return_on_enter)
563 // special case to allow exiting from the error handler on Enter
572 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
582 WriteFile(houtput, &ch, 1, &dummy, NULL);
584 len = (len + 1) & 0xff;
597 void Sys_Sleep (void)
603 void Sys_SendKeyEvents (void)
607 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
609 // we always update if there are any event, even if we're paused
612 if (!GetMessage (&msg, NULL, 0, 0))
615 TranslateMessage (&msg);
616 DispatchMessage (&msg);
622 ==============================================================================
626 ==============================================================================
635 void SleepUntilInput (int time)
638 MsgWaitForMultipleObjects(1, &tevent, FALSE, time, QS_ALLINPUT);
647 HINSTANCE global_hInstance;
649 char *argv[MAX_NUM_ARGVS];
650 static char *empty_string = "";
654 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
657 double time, oldtime, newtime/*, timediff*/;
658 MEMORYSTATUS lpBuffer;
659 static char cwd[1024];
663 /* previous instances do not exist in Win32 */
667 global_hInstance = hInstance;
668 global_nCmdShow = nCmdShow;
670 lpBuffer.dwLength = sizeof(MEMORYSTATUS);
671 GlobalMemoryStatus (&lpBuffer);
673 if (!GetCurrentDirectory (sizeof(cwd), cwd))
674 Sys_Error ("Couldn't determine current directory");
676 if (cwd[strlen(cwd)-1] == '/')
677 cwd[strlen(cwd)-1] = 0;
680 parms.cachedir = NULL;
683 argv[0] = empty_string;
685 while (*lpCmdLine && (parms.argc < MAX_NUM_ARGVS))
687 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
692 argv[parms.argc] = lpCmdLine;
695 while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
709 COM_InitArgv (parms.argc, parms.argv);
711 parms.argc = com_argc;
712 parms.argv = com_argv;
714 isDedicated = (COM_CheckParm ("-dedicated") != 0);
718 hwnd_dialog = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, NULL);
722 if (GetWindowRect (hwnd_dialog, &rect))
724 if (rect.left > (rect.top * 2))
726 SetWindowPos (hwnd_dialog, 0,
727 (rect.left / 2) - ((rect.right - rect.left) / 2),
729 SWP_NOZORDER | SWP_NOSIZE);
733 ShowWindow (hwnd_dialog, SW_SHOWDEFAULT);
734 UpdateWindow (hwnd_dialog);
735 SetForegroundWindow (hwnd_dialog);
739 // take the greater of all the available memory or half the total memory,
740 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
742 parms.memsize = lpBuffer.dwAvailPhys;
744 if (parms.memsize < MINIMUM_WIN_MEMORY)
745 parms.memsize = MINIMUM_WIN_MEMORY;
747 if (parms.memsize < (lpBuffer.dwTotalPhys >> 1))
748 parms.memsize = lpBuffer.dwTotalPhys >> 1;
750 if (parms.memsize > MAXIMUM_WIN_MEMORY)
751 parms.memsize = MAXIMUM_WIN_MEMORY;
753 if (COM_CheckParm ("-heapsize"))
755 t = COM_CheckParm("-heapsize") + 1;
758 parms.memsize = atoi (com_argv[t]) * 1024;
761 if (COM_CheckParm ("-mem"))
763 t = COM_CheckParm("-mem") + 1;
766 parms.memsize = atoi (com_argv[t]) * 1048576;
769 if (COM_CheckParm ("-winmem"))
771 t = COM_CheckParm("-winmem") + 1;
774 parms.memsize = atoi (com_argv[t]) * 1048576;
777 parms.membase = malloc (parms.memsize);
780 Sys_Error ("Not enough memory free; check disk space\n");
782 Sys_PageIn (parms.membase, parms.memsize);
784 tevent = CreateEvent(NULL, FALSE, FALSE, NULL);
787 Sys_Error ("Couldn't create event");
791 if (!AllocConsole ())
793 Sys_Error ("Couldn't create dedicated server console");
796 hinput = GetStdHandle (STD_INPUT_HANDLE);
797 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
799 // give QHOST a chance to hook into the console
800 if ((t = COM_CheckParm ("-HFILE")) > 0)
803 hFile = (HANDLE)atoi (com_argv[t+1]);
806 if ((t = COM_CheckParm ("-HPARENT")) > 0)
809 heventParent = (HANDLE)atoi (com_argv[t+1]);
812 if ((t = COM_CheckParm ("-HCHILD")) > 0)
815 heventChild = (HANDLE)atoi (com_argv[t+1]);
818 InitConProc (hFile, heventParent, heventChild);
823 // because sound is off until we become active
826 Sys_Printf ("Host_Init\n");
829 oldtime = Sys_FloatTime ();
831 /* main window message loop */
836 newtime = Sys_FloatTime ();
837 time = newtime - oldtime;
839 while (time < sys_ticrate.value )
842 newtime = Sys_FloatTime ();
843 time = newtime - oldtime;
848 // yield the CPU for a little while when paused, minimized, or not the focus
849 if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized)
851 SleepUntilInput (PAUSE_SLEEP);
852 scr_skipupdate = 1; // no point in bothering to draw
854 else if (!ActiveApp && !DDActive)
856 SleepUntilInput (NOT_FOCUS_SLEEP);
859 else if (!cls.timedemo && time < (timediff = 1.0 / maxfps.value))
861 newtime = Sys_FloatTime ();
862 time = newtime - oldtime;
864 while (time < timediff)
867 newtime = Sys_FloatTime ();
868 time = newtime - oldtime;
873 newtime = Sys_FloatTime ();
874 time = newtime - oldtime;
881 /* return success of application */