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
254 lowpart = (unsigned int)PerformanceFreq.LowPart;
255 highpart = (unsigned int)PerformanceFreq.HighPart;
258 while (highpart || (lowpart > 2000000.0))
262 lowpart |= (highpart & 1) << 31;
266 pfreq = 1.0 / (double)lowpart;
268 Sys_InitFloatTime ();
270 vinfo.dwOSVersionInfoSize = sizeof(vinfo);
272 if (!GetVersionEx (&vinfo))
273 Sys_Error ("Couldn't get OS info");
275 if ((vinfo.dwMajorVersion < 4) ||
276 (vinfo.dwPlatformId == VER_PLATFORM_WIN32s))
278 Sys_Error ("WinQuake requires at least Win95 or NT 4.0");
281 if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
288 void Sys_Error (char *error, ...)
291 char text[1024], text2[1024];
292 char *text3 = "Press Enter to exit\n";
293 char *text4 = "***********************************\n";
297 static int in_sys_error0 = 0;
298 static int in_sys_error1 = 0;
299 static int in_sys_error2 = 0;
300 static int in_sys_error3 = 0;
305 va_start (argptr, error);
306 vsprintf (text, error, argptr);
311 va_start (argptr, error);
312 vsprintf (text, error, argptr);
315 sprintf (text2, "ERROR: %s\n", text);
316 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
317 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
318 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
319 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
320 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
323 starttime = Sys_FloatTime ();
324 sc_return_on_enter = true; // so Enter will get us out of here
326 while (!Sys_ConsoleInput () &&
327 ((Sys_FloatTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
333 // switch to windowed so the message box is visible, unless we already
334 // tried that and failed
338 VID_SetDefaultMode ();
339 MessageBox(NULL, text, "Quake Error",
340 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
344 MessageBox(NULL, text, "Double Quake Error",
345 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
355 // shut down QHOST hooks if necessary
365 void Sys_Printf (char *fmt, ...)
373 va_start (argptr,fmt);
374 vsprintf (text, fmt, argptr);
377 WriteFile(houtput, text, strlen (text), &dummy, NULL);
387 CloseHandle (tevent);
392 // shut down QHOST hooks if necessary
404 double Sys_FloatTime (void)
406 static int sametimecount;
407 static unsigned int oldtime;
408 static int first = 1;
409 LARGE_INTEGER PerformanceCount;
410 unsigned int temp, t2;
413 QueryPerformanceCounter (&PerformanceCount);
415 temp = ((unsigned int)PerformanceCount.LowPart >> lowshift) |
416 ((unsigned int)PerformanceCount.HighPart << (32 - lowshift));
425 // check for turnover or backward time
426 if ((temp <= oldtime) && ((oldtime - temp) < 0x10000000))
428 oldtime = temp; // so we can't get stuck
434 time = (double)t2 * pfreq;
439 if (curtime == lastcurtime)
443 if (sametimecount > 100000)
454 lastcurtime = curtime;
467 void Sys_InitFloatTime (void)
473 j = COM_CheckParm("-starttime");
477 curtime = (double) (atof(com_argv[j+1]));
484 lastcurtime = curtime;
488 char *Sys_ConsoleInput (void)
490 static char text[256];
492 INPUT_RECORD recs[1024];
494 int ch, numread, numevents;
502 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
503 Sys_Error ("Error getting # of console events");
508 if (!ReadConsoleInput(hinput, recs, 1, &numread))
509 Sys_Error ("Error reading console input");
512 Sys_Error ("Couldn't read console input");
514 if (recs[0].EventType == KEY_EVENT)
516 if (!recs[0].Event.KeyEvent.bKeyDown)
518 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
523 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
531 else if (sc_return_on_enter)
533 // special case to allow exiting from the error handler on Enter
542 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
552 WriteFile(houtput, &ch, 1, &dummy, NULL);
554 len = (len + 1) & 0xff;
567 void Sys_Sleep (void)
573 void Sys_SendKeyEvents (void)
577 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
579 // we always update if there are any event, even if we're paused
582 if (!GetMessage (&msg, NULL, 0, 0))
585 TranslateMessage (&msg);
586 DispatchMessage (&msg);
592 ==============================================================================
596 ==============================================================================
605 void SleepUntilInput (int time)
608 MsgWaitForMultipleObjects(1, &tevent, FALSE, time, QS_ALLINPUT);
617 HINSTANCE global_hInstance;
619 char *argv[MAX_NUM_ARGVS];
620 static char *empty_string = "";
624 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];
633 /* previous instances do not exist in Win32 */
637 global_hInstance = hInstance;
638 global_nCmdShow = nCmdShow;
640 lpBuffer.dwLength = sizeof(MEMORYSTATUS);
641 GlobalMemoryStatus (&lpBuffer);
643 if (!GetCurrentDirectory (sizeof(cwd), cwd))
644 Sys_Error ("Couldn't determine current directory");
646 if (cwd[strlen(cwd)-1] == '/')
647 cwd[strlen(cwd)-1] = 0;
650 parms.cachedir = NULL;
653 argv[0] = empty_string;
655 while (*lpCmdLine && (parms.argc < MAX_NUM_ARGVS))
657 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
662 argv[parms.argc] = lpCmdLine;
665 while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
679 COM_InitArgv (parms.argc, parms.argv);
681 parms.argc = com_argc;
682 parms.argv = com_argv;
684 isDedicated = (COM_CheckParm ("-dedicated") != 0);
688 hwnd_dialog = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, NULL);
692 if (GetWindowRect (hwnd_dialog, &rect))
694 if (rect.left > (rect.top * 2))
696 SetWindowPos (hwnd_dialog, 0,
697 (rect.left / 2) - ((rect.right - rect.left) / 2),
699 SWP_NOZORDER | SWP_NOSIZE);
703 ShowWindow (hwnd_dialog, SW_SHOWDEFAULT);
704 UpdateWindow (hwnd_dialog);
705 SetForegroundWindow (hwnd_dialog);
709 // take the greater of all the available memory or half the total memory,
710 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
712 parms.memsize = lpBuffer.dwAvailPhys;
714 if (parms.memsize < MINIMUM_WIN_MEMORY)
715 parms.memsize = MINIMUM_WIN_MEMORY;
717 if (parms.memsize < (lpBuffer.dwTotalPhys >> 1))
718 parms.memsize = lpBuffer.dwTotalPhys >> 1;
720 if (parms.memsize > MAXIMUM_WIN_MEMORY)
721 parms.memsize = MAXIMUM_WIN_MEMORY;
723 if (COM_CheckParm ("-heapsize"))
725 t = COM_CheckParm("-heapsize") + 1;
728 parms.memsize = atoi (com_argv[t]) * 1024;
731 if (COM_CheckParm ("-mem"))
733 t = COM_CheckParm("-mem") + 1;
736 parms.memsize = atoi (com_argv[t]) * 1048576;
739 if (COM_CheckParm ("-winmem"))
741 t = COM_CheckParm("-winmem") + 1;
744 parms.memsize = atoi (com_argv[t]) * 1048576;
747 parms.membase = malloc (parms.memsize);
750 Sys_Error ("Not enough memory free; check disk space\n");
752 Sys_PageIn (parms.membase, parms.memsize);
754 tevent = CreateEvent(NULL, FALSE, FALSE, NULL);
757 Sys_Error ("Couldn't create event");
761 if (!AllocConsole ())
763 Sys_Error ("Couldn't create dedicated server console");
766 hinput = GetStdHandle (STD_INPUT_HANDLE);
767 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
769 // give QHOST a chance to hook into the console
770 if ((t = COM_CheckParm ("-HFILE")) > 0)
773 hFile = (HANDLE)atoi (com_argv[t+1]);
776 if ((t = COM_CheckParm ("-HPARENT")) > 0)
779 heventParent = (HANDLE)atoi (com_argv[t+1]);
782 if ((t = COM_CheckParm ("-HCHILD")) > 0)
785 heventChild = (HANDLE)atoi (com_argv[t+1]);
788 InitConProc (hFile, heventParent, heventChild);
793 // because sound is off until we become active
796 Sys_Printf ("Host_Init\n");
799 oldtime = Sys_FloatTime ();
801 /* main window message loop */
806 newtime = Sys_FloatTime ();
807 time = newtime - oldtime;
809 while (time < sys_ticrate.value )
812 newtime = Sys_FloatTime ();
813 time = newtime - oldtime;
818 // yield the CPU for a little while when paused, minimized, or not the focus
819 if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized)
821 SleepUntilInput (PAUSE_SLEEP);
822 scr_skipupdate = 1; // no point in bothering to draw
824 else if (!ActiveApp && !DDActive)
826 SleepUntilInput (NOT_FOCUS_SLEEP);
829 else if (!cls.timedemo && time < (timediff = 1.0 / maxfps.value))
831 newtime = Sys_FloatTime ();
832 time = newtime - oldtime;
834 while (time < timediff)
837 newtime = Sys_FloatTime ();
838 time = newtime - oldtime;
843 newtime = Sys_FloatTime ();
844 time = newtime - oldtime;
851 /* return success of application */