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 ===============================================================================
217 Sys_MakeCodeWriteable
220 void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
224 if (!VirtualProtect((LPVOID)startaddr, length, PAGE_READWRITE, &flOldProtect))
225 Sys_Error("Protection change failed\n");
236 LARGE_INTEGER PerformanceFreq;
237 unsigned int lowpart, highpart;
240 if (!QueryPerformanceFrequency (&PerformanceFreq))
241 Sys_Error ("No hardware timer available");
243 // get 32 out of the 64 time bits such that we have around
244 // 1 microsecond resolution
246 lowpart = (unsigned int)PerformanceFreq.u.LowPart;
247 highpart = (unsigned int)PerformanceFreq.u.HighPart;
249 lowpart = (unsigned int)PerformanceFreq.LowPart;
250 highpart = (unsigned int)PerformanceFreq.HighPart;
254 while (highpart || (lowpart > 2000000.0))
258 lowpart |= (highpart & 1) << 31;
262 pfreq = 1.0 / (double)lowpart;
264 Sys_InitFloatTime ();
266 vinfo.dwOSVersionInfoSize = sizeof(vinfo);
268 if (!GetVersionEx (&vinfo))
269 Sys_Error ("Couldn't get OS info");
271 if ((vinfo.dwMajorVersion < 4) ||
272 (vinfo.dwPlatformId == VER_PLATFORM_WIN32s))
274 Sys_Error ("WinQuake requires at least Win95 or NT 4.0");
277 if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
284 void Sys_Error (char *error, ...)
287 char text[1024], text2[1024];
288 char *text3 = "Press Enter to exit\n";
289 char *text4 = "***********************************\n";
293 static int in_sys_error0 = 0;
294 static int in_sys_error1 = 0;
295 static int in_sys_error2 = 0;
296 static int in_sys_error3 = 0;
301 va_start (argptr, error);
302 vsprintf (text, error, argptr);
307 va_start (argptr, error);
308 vsprintf (text, error, argptr);
311 sprintf (text2, "ERROR: %s\n", text);
312 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
313 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
314 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
315 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
316 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
319 starttime = Sys_FloatTime ();
320 sc_return_on_enter = true; // so Enter will get us out of here
322 while (!Sys_ConsoleInput () &&
323 ((Sys_FloatTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
329 // switch to windowed so the message box is visible, unless we already
330 // tried that and failed
334 VID_SetDefaultMode ();
335 MessageBox(NULL, text, "Quake Error",
336 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
340 MessageBox(NULL, text, "Double Quake Error",
341 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
351 // shut down QHOST hooks if necessary
361 void Sys_Printf (char *fmt, ...)
369 va_start (argptr,fmt);
370 vsprintf (text, fmt, argptr);
373 WriteFile(houtput, text, strlen (text), &dummy, NULL);
383 CloseHandle (tevent);
388 // shut down QHOST hooks if necessary
400 double Sys_FloatTime (void)
402 static int sametimecount;
403 static unsigned int oldtime;
404 static int first = 1;
405 LARGE_INTEGER PerformanceCount;
406 unsigned int temp, t2;
409 QueryPerformanceCounter (&PerformanceCount);
412 temp = ((unsigned int)PerformanceCount.u.LowPart >> lowshift) |
413 ((unsigned int)PerformanceCount.u.HighPart << (32 - lowshift));
416 temp = ((unsigned int)PerformanceCount.LowPart >> lowshift) |
417 ((unsigned int)PerformanceCount.HighPart << (32 - lowshift));
426 // check for turnover or backward time
427 if ((temp <= oldtime) && ((oldtime - temp) < 0x10000000))
429 oldtime = temp; // so we can't get stuck
435 time = (double)t2 * pfreq;
440 if (curtime == lastcurtime)
444 if (sametimecount > 100000)
455 lastcurtime = curtime;
468 void Sys_InitFloatTime (void)
474 j = COM_CheckParm("-starttime");
478 curtime = (double) (atof(com_argv[j+1]));
485 lastcurtime = curtime;
489 char *Sys_ConsoleInput (void)
491 static char text[256];
493 INPUT_RECORD recs[1024];
495 int ch, numread, numevents;
503 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
504 Sys_Error ("Error getting # of console events");
509 if (!ReadConsoleInput(hinput, recs, 1, &numread))
510 Sys_Error ("Error reading console input");
513 Sys_Error ("Couldn't read console input");
515 if (recs[0].EventType == KEY_EVENT)
517 if (!recs[0].Event.KeyEvent.bKeyDown)
519 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
524 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
532 else if (sc_return_on_enter)
534 // special case to allow exiting from the error handler on Enter
543 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
553 WriteFile(houtput, &ch, 1, &dummy, NULL);
555 len = (len + 1) & 0xff;
568 void Sys_Sleep (void)
574 void Sys_SendKeyEvents (void)
578 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
580 // we always update if there are any event, even if we're paused
583 if (!GetMessage (&msg, NULL, 0, 0))
586 TranslateMessage (&msg);
587 DispatchMessage (&msg);
593 ==============================================================================
597 ==============================================================================
606 void SleepUntilInput (int time)
609 MsgWaitForMultipleObjects(1, &tevent, false, time, QS_ALLINPUT);
618 HINSTANCE global_hInstance;
620 char *argv[MAX_NUM_ARGVS];
621 static char *empty_string = "";
623 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
625 double time, oldtime, newtime/*, timediff*/;
626 MEMORYSTATUS lpBuffer;
627 static char cwd[1024];
630 /* previous instances do not exist in Win32 */
634 global_hInstance = hInstance;
635 global_nCmdShow = nCmdShow;
637 lpBuffer.dwLength = sizeof(MEMORYSTATUS);
638 GlobalMemoryStatus (&lpBuffer);
640 if (!GetCurrentDirectory (sizeof(cwd), cwd))
641 Sys_Error ("Couldn't determine current directory");
643 if (cwd[strlen(cwd)-1] == '/')
644 cwd[strlen(cwd)-1] = 0;
646 host_parms.basedir = cwd;
647 host_parms.cachedir = NULL;
650 argv[0] = empty_string;
652 while (*lpCmdLine && (host_parms.argc < MAX_NUM_ARGVS))
654 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
659 argv[host_parms.argc] = lpCmdLine;
662 while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
674 host_parms.argv = argv;
676 COM_InitArgv (host_parms.argc, host_parms.argv);
678 host_parms.argc = com_argc;
679 host_parms.argv = com_argv;
681 isDedicated = (COM_CheckParm ("-dedicated") != 0);
683 // take the greater of all the available memory or half the total memory,
684 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
687 host_parms.memsize = lpBuffer.dwAvailPhys;
689 if (host_parms.memsize < MINIMUM_WIN_MEMORY)
690 host_parms.memsize = MINIMUM_WIN_MEMORY;
692 if (host_parms.memsize < (lpBuffer.dwTotalPhys >> 1))
693 host_parms.memsize = lpBuffer.dwTotalPhys >> 1;
695 if (host_parms.memsize > MAXIMUM_WIN_MEMORY)
696 host_parms.memsize = MAXIMUM_WIN_MEMORY;
699 // Sys_PageIn (parms.membase, parms.memsize);
701 tevent = CreateEvent(NULL, false, false, NULL);
704 Sys_Error ("Couldn't create event");
708 if (!AllocConsole ())
710 Sys_Error ("Couldn't create dedicated server console");
713 hinput = GetStdHandle (STD_INPUT_HANDLE);
714 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
716 // give QHOST a chance to hook into the console
717 if ((t = COM_CheckParm ("-HFILE")) > 0)
720 hFile = (HANDLE)atoi (com_argv[t+1]);
723 if ((t = COM_CheckParm ("-HPARENT")) > 0)
726 heventParent = (HANDLE)atoi (com_argv[t+1]);
729 if ((t = COM_CheckParm ("-HCHILD")) > 0)
732 heventChild = (HANDLE)atoi (com_argv[t+1]);
735 InitConProc (hFile, heventParent, heventChild);
740 // because sound is off until we become active
743 Sys_Printf ("Host_Init\n");
746 oldtime = Sys_FloatTime ();
748 /* main window message loop */
753 newtime = Sys_FloatTime ();
754 time = newtime - oldtime;
756 while (time < sys_ticrate.value )
759 newtime = Sys_FloatTime ();
760 time = newtime - oldtime;
765 // yield the CPU for a little while when paused, minimized, or not the focus
766 if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized)
768 SleepUntilInput (PAUSE_SLEEP);
769 scr_skipupdate = 1; // no point in bothering to draw
771 else if (!ActiveApp && !DDActive)
773 SleepUntilInput (NOT_FOCUS_SLEEP);
776 else if (!cls.timedemo && time < (timediff = 1.0 / maxfps.value))
778 newtime = Sys_FloatTime ();
779 time = newtime - oldtime;
781 while (time < timediff)
784 newtime = Sys_FloatTime ();
785 time = newtime - oldtime;
790 newtime = Sys_FloatTime ();
791 time = newtime - oldtime;
798 /* return success of application */