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 64mb (was 8.5mb)
30 #define MINIMUM_WIN_MEMORY 0x04000000
31 // LordHavoc: raised max to 64mb (was 16mb)
32 #define MAXIMUM_WIN_MEMORY 0x04000000
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 Sys_InitFloatTime (void);
60 volatile int sys_checksum;
68 void Sys_PageIn (void *ptr, int size)
73 // touch all the memory to make sure it's there. The 16-page skip is to
74 // keep Win 95 from thinking we're trying to page ourselves in (we are
75 // doing that, of course, but there's no reason we shouldn't)
80 for (m=0 ; m<(size - 16 * 0x1000) ; m += 4)
82 sys_checksum += *(int *)&x[m];
83 sys_checksum += *(int *)&x[m + 16 * 0x1000];
90 ===============================================================================
94 ===============================================================================
97 // LordHavoc: 256 pak files (was 10)
98 #define MAX_HANDLES 256
99 FILE *sys_handles[MAX_HANDLES];
101 int findhandle (void)
105 for (i=1 ; i<MAX_HANDLES ; i++)
108 Sys_Error ("out of handles");
117 int filelength (FILE *f)
123 fseek (f, 0, SEEK_END);
125 fseek (f, pos, SEEK_SET);
130 int Sys_FileOpenRead (char *path, int *hndl)
137 f = fopen(path, "rb");
148 retval = filelength(f);
154 int Sys_FileOpenWrite (char *path)
161 f = fopen(path, "wb");
163 Host_Error ("Error opening %s: %s", path,strerror(errno));
169 void Sys_FileClose (int handle)
171 fclose (sys_handles[handle]);
172 sys_handles[handle] = NULL;
175 void Sys_FileSeek (int handle, int position)
177 fseek (sys_handles[handle], position, SEEK_SET);
180 int Sys_FileRead (int handle, void *dest, int count)
182 return fread (dest, 1, count, sys_handles[handle]);
185 int Sys_FileWrite (int handle, void *data, int count)
187 return fwrite (data, 1, count, sys_handles[handle]);
190 int Sys_FileTime (char *path)
195 f = fopen(path, "rb");
210 void Sys_mkdir (char *path)
217 ===============================================================================
221 ===============================================================================
226 Sys_MakeCodeWriteable
229 void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
233 if (!VirtualProtect((LPVOID)startaddr, length, PAGE_READWRITE, &flOldProtect))
234 Sys_Error("Protection change failed\n");
245 LARGE_INTEGER PerformanceFreq;
246 unsigned int lowpart, highpart;
249 if (!QueryPerformanceFrequency (&PerformanceFreq))
250 Sys_Error ("No hardware timer available");
252 // get 32 out of the 64 time bits such that we have around
253 // 1 microsecond resolution
255 lowpart = (unsigned int)PerformanceFreq.u.LowPart;
256 highpart = (unsigned int)PerformanceFreq.u.HighPart;
258 lowpart = (unsigned int)PerformanceFreq.LowPart;
259 highpart = (unsigned int)PerformanceFreq.HighPart;
263 while (highpart || (lowpart > 2000000.0))
267 lowpart |= (highpart & 1) << 31;
271 pfreq = 1.0 / (double)lowpart;
273 Sys_InitFloatTime ();
275 vinfo.dwOSVersionInfoSize = sizeof(vinfo);
277 if (!GetVersionEx (&vinfo))
278 Sys_Error ("Couldn't get OS info");
280 if ((vinfo.dwMajorVersion < 4) ||
281 (vinfo.dwPlatformId == VER_PLATFORM_WIN32s))
283 Sys_Error ("WinQuake requires at least Win95 or NT 4.0");
286 if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
293 void Sys_Error (char *error, ...)
296 char text[1024], text2[1024];
297 char *text3 = "Press Enter to exit\n";
298 char *text4 = "***********************************\n";
302 static int in_sys_error0 = 0;
303 static int in_sys_error1 = 0;
304 static int in_sys_error2 = 0;
305 static int in_sys_error3 = 0;
310 va_start (argptr, error);
311 vsprintf (text, error, argptr);
316 va_start (argptr, error);
317 vsprintf (text, error, argptr);
320 sprintf (text2, "ERROR: %s\n", text);
321 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
322 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
323 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
324 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
325 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
328 starttime = Sys_FloatTime ();
329 sc_return_on_enter = true; // so Enter will get us out of here
331 while (!Sys_ConsoleInput () &&
332 ((Sys_FloatTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
338 // switch to windowed so the message box is visible, unless we already
339 // tried that and failed
343 VID_SetDefaultMode ();
344 MessageBox(NULL, text, "Quake Error",
345 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
349 MessageBox(NULL, text, "Double Quake Error",
350 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
360 // shut down QHOST hooks if necessary
370 void Sys_Printf (char *fmt, ...)
378 va_start (argptr,fmt);
379 vsprintf (text, fmt, argptr);
382 WriteFile(houtput, text, strlen (text), &dummy, NULL);
392 CloseHandle (tevent);
397 // shut down QHOST hooks if necessary
409 double Sys_FloatTime (void)
411 static int sametimecount;
412 static unsigned int oldtime;
413 static int first = 1;
414 LARGE_INTEGER PerformanceCount;
415 unsigned int temp, t2;
418 QueryPerformanceCounter (&PerformanceCount);
421 temp = ((unsigned int)PerformanceCount.u.LowPart >> lowshift) |
422 ((unsigned int)PerformanceCount.u.HighPart << (32 - lowshift));
425 temp = ((unsigned int)PerformanceCount.LowPart >> lowshift) |
426 ((unsigned int)PerformanceCount.HighPart << (32 - lowshift));
435 // check for turnover or backward time
436 if ((temp <= oldtime) && ((oldtime - temp) < 0x10000000))
438 oldtime = temp; // so we can't get stuck
444 time = (double)t2 * pfreq;
449 if (curtime == lastcurtime)
453 if (sametimecount > 100000)
464 lastcurtime = curtime;
477 void Sys_InitFloatTime (void)
483 j = COM_CheckParm("-starttime");
487 curtime = (double) (atof(com_argv[j+1]));
494 lastcurtime = curtime;
498 char *Sys_ConsoleInput (void)
500 static char text[256];
502 INPUT_RECORD recs[1024];
504 int ch, numread, numevents;
512 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
513 Sys_Error ("Error getting # of console events");
518 if (!ReadConsoleInput(hinput, recs, 1, &numread))
519 Sys_Error ("Error reading console input");
522 Sys_Error ("Couldn't read console input");
524 if (recs[0].EventType == KEY_EVENT)
526 if (!recs[0].Event.KeyEvent.bKeyDown)
528 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
533 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
541 else if (sc_return_on_enter)
543 // special case to allow exiting from the error handler on Enter
552 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
562 WriteFile(houtput, &ch, 1, &dummy, NULL);
564 len = (len + 1) & 0xff;
577 void Sys_Sleep (void)
583 void Sys_SendKeyEvents (void)
587 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
589 // we always update if there are any event, even if we're paused
592 if (!GetMessage (&msg, NULL, 0, 0))
595 TranslateMessage (&msg);
596 DispatchMessage (&msg);
602 ==============================================================================
606 ==============================================================================
615 void SleepUntilInput (int time)
618 MsgWaitForMultipleObjects(1, &tevent, FALSE, time, QS_ALLINPUT);
627 HINSTANCE global_hInstance;
629 char *argv[MAX_NUM_ARGVS];
630 static char *empty_string = "";
634 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
637 double time, oldtime, newtime/*, timediff*/;
638 MEMORYSTATUS lpBuffer;
639 static char cwd[1024];
643 /* previous instances do not exist in Win32 */
647 global_hInstance = hInstance;
648 global_nCmdShow = nCmdShow;
650 lpBuffer.dwLength = sizeof(MEMORYSTATUS);
651 GlobalMemoryStatus (&lpBuffer);
653 if (!GetCurrentDirectory (sizeof(cwd), cwd))
654 Sys_Error ("Couldn't determine current directory");
656 if (cwd[strlen(cwd)-1] == '/')
657 cwd[strlen(cwd)-1] = 0;
660 parms.cachedir = NULL;
663 argv[0] = empty_string;
665 while (*lpCmdLine && (parms.argc < MAX_NUM_ARGVS))
667 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
672 argv[parms.argc] = lpCmdLine;
675 while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
689 COM_InitArgv (parms.argc, parms.argv);
691 parms.argc = com_argc;
692 parms.argv = com_argv;
694 isDedicated = (COM_CheckParm ("-dedicated") != 0);
698 hwnd_dialog = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, NULL);
702 if (GetWindowRect (hwnd_dialog, &rect))
704 if (rect.left > (rect.top * 2))
706 SetWindowPos (hwnd_dialog, 0,
707 (rect.left / 2) - ((rect.right - rect.left) / 2),
709 SWP_NOZORDER | SWP_NOSIZE);
713 ShowWindow (hwnd_dialog, SW_SHOWDEFAULT);
714 UpdateWindow (hwnd_dialog);
715 SetForegroundWindow (hwnd_dialog);
719 // take the greater of all the available memory or half the total memory,
720 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
722 parms.memsize = lpBuffer.dwAvailPhys;
724 if (parms.memsize < MINIMUM_WIN_MEMORY)
725 parms.memsize = MINIMUM_WIN_MEMORY;
727 if (parms.memsize < (lpBuffer.dwTotalPhys >> 1))
728 parms.memsize = lpBuffer.dwTotalPhys >> 1;
730 if (parms.memsize > MAXIMUM_WIN_MEMORY)
731 parms.memsize = MAXIMUM_WIN_MEMORY;
733 if (COM_CheckParm ("-heapsize"))
735 t = COM_CheckParm("-heapsize") + 1;
738 parms.memsize = atoi (com_argv[t]) * 1024;
741 if (COM_CheckParm ("-mem"))
743 t = COM_CheckParm("-mem") + 1;
746 parms.memsize = atoi (com_argv[t]) * 1048576;
749 if (COM_CheckParm ("-winmem"))
751 t = COM_CheckParm("-winmem") + 1;
754 parms.memsize = atoi (com_argv[t]) * 1048576;
757 parms.membase = malloc (parms.memsize);
760 Sys_Error ("Not enough memory free; check disk space\n");
762 // Sys_PageIn (parms.membase, parms.memsize);
764 tevent = CreateEvent(NULL, FALSE, FALSE, NULL);
767 Sys_Error ("Couldn't create event");
771 if (!AllocConsole ())
773 Sys_Error ("Couldn't create dedicated server console");
776 hinput = GetStdHandle (STD_INPUT_HANDLE);
777 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
779 // give QHOST a chance to hook into the console
780 if ((t = COM_CheckParm ("-HFILE")) > 0)
783 hFile = (HANDLE)atoi (com_argv[t+1]);
786 if ((t = COM_CheckParm ("-HPARENT")) > 0)
789 heventParent = (HANDLE)atoi (com_argv[t+1]);
792 if ((t = COM_CheckParm ("-HCHILD")) > 0)
795 heventChild = (HANDLE)atoi (com_argv[t+1]);
798 InitConProc (hFile, heventParent, heventChild);
803 // because sound is off until we become active
806 Sys_Printf ("Host_Init\n");
809 oldtime = Sys_FloatTime ();
811 /* main window message loop */
816 newtime = Sys_FloatTime ();
817 time = newtime - oldtime;
819 while (time < sys_ticrate.value )
822 newtime = Sys_FloatTime ();
823 time = newtime - oldtime;
828 // yield the CPU for a little while when paused, minimized, or not the focus
829 if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized)
831 SleepUntilInput (PAUSE_SLEEP);
832 scr_skipupdate = 1; // no point in bothering to draw
834 else if (!ActiveApp && !DDActive)
836 SleepUntilInput (NOT_FOCUS_SLEEP);
839 else if (!cls.timedemo && time < (timediff = 1.0 / maxfps.value))
841 newtime = Sys_FloatTime ();
842 time = newtime - oldtime;
844 while (time < timediff)
847 newtime = Sys_FloatTime ();
848 time = newtime - oldtime;
853 newtime = Sys_FloatTime ();
854 time = newtime - oldtime;
861 /* return success of application */