]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - sys_win.c
rewrite of map texture loading (mainly to do with HL textures and wads)
[xonotic/darkplaces.git] / sys_win.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
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.
8
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.  
12
13 See the GNU General Public License for more details.
14
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.
18
19 */
20 // sys_win.c -- Win32 system interface code
21
22 #include "quakedef.h"
23 #include "winquake.h"
24 #include "errno.h"
25 #include "resource.h"
26 #include "conproc.h"
27 #include "direct.h"
28
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
33
34 int                     starttime;
35 qboolean        ActiveApp, Minimized;
36 qboolean        WinNT;
37
38 static double           pfreq;
39 static double           curtime = 0.0;
40 static double           lastcurtime = 0.0;
41 static int                      lowshift;
42 qboolean                        isDedicated;
43 static qboolean         sc_return_on_enter = false;
44 HANDLE                          hinput, houtput;
45
46 static char                     *tracking_tag = "Clams & Mooses";
47
48 static HANDLE   tevent;
49 static HANDLE   hFile;
50 static HANDLE   heventParent;
51 static HANDLE   heventChild;
52
53 void Sys_InitFloatTime (void);
54
55 volatile int                                    sys_checksum;
56
57
58 /*
59 ================
60 Sys_PageIn
61 ================
62 */
63 /*
64 void Sys_PageIn (void *ptr, int size)
65 {
66         byte    *x;
67         int             m, n;
68
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)
72         x = (byte *)ptr;
73
74         for (n=0 ; n<4 ; n++)
75         {
76                 for (m=0 ; m<(size - 16 * 0x1000) ; m += 4)
77                 {
78                         sys_checksum += *(int *)&x[m];
79                         sys_checksum += *(int *)&x[m + 16 * 0x1000];
80                 }
81         }
82 }
83 */
84
85
86 /*
87 ===============================================================================
88
89 FILE IO
90
91 ===============================================================================
92 */
93
94 // LordHavoc: 256 pak files (was 10)
95 #define MAX_HANDLES             256
96 FILE    *sys_handles[MAX_HANDLES];
97
98 int             findhandle (void)
99 {
100         int             i;
101         
102         for (i=1 ; i<MAX_HANDLES ; i++)
103                 if (!sys_handles[i])
104                         return i;
105         Sys_Error ("out of handles");
106         return -1;
107 }
108
109 /*
110 ================
111 filelength
112 ================
113 */
114 int filelength (FILE *f)
115 {
116         int             pos;
117         int             end;
118
119         pos = ftell (f);
120         fseek (f, 0, SEEK_END);
121         end = ftell (f);
122         fseek (f, pos, SEEK_SET);
123
124         return end;
125 }
126
127 int Sys_FileOpenRead (char *path, int *hndl)
128 {
129         FILE    *f;
130         int             i, retval;
131
132         i = findhandle ();
133
134         f = fopen(path, "rb");
135
136         if (!f)
137         {
138                 *hndl = -1;
139                 retval = -1;
140         }
141         else
142         {
143                 sys_handles[i] = f;
144                 *hndl = i;
145                 retval = filelength(f);
146         }
147
148         return retval;
149 }
150
151 int Sys_FileOpenWrite (char *path)
152 {
153         FILE    *f;
154         int             i;
155
156         i = findhandle ();
157
158         f = fopen(path, "wb");
159         if (!f)
160                 Host_Error ("Error opening %s: %s", path,strerror(errno));
161         sys_handles[i] = f;
162         
163         return i;
164 }
165
166 void Sys_FileClose (int handle)
167 {
168         fclose (sys_handles[handle]);
169         sys_handles[handle] = NULL;
170 }
171
172 void Sys_FileSeek (int handle, int position)
173 {
174         fseek (sys_handles[handle], position, SEEK_SET);
175 }
176
177 int Sys_FileRead (int handle, void *dest, int count)
178 {
179         return fread (dest, 1, count, sys_handles[handle]);
180 }
181
182 int Sys_FileWrite (int handle, void *data, int count)
183 {
184         return fwrite (data, 1, count, sys_handles[handle]);
185 }
186
187 int     Sys_FileTime (char *path)
188 {
189         FILE    *f;
190         int             retval;
191
192         f = fopen(path, "rb");
193
194         if (f)
195         {
196                 fclose(f);
197                 retval = 1;
198         }
199         else
200         {
201                 retval = -1;
202         }
203         
204         return retval;
205 }
206
207 void Sys_mkdir (char *path)
208 {
209         _mkdir (path);
210 }
211
212
213 /*
214 ===============================================================================
215
216 SYSTEM IO
217
218 ===============================================================================
219 */
220
221 /*
222 ================
223 Sys_MakeCodeWriteable
224 ================
225 */
226 void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
227 {
228         DWORD  flOldProtect;
229
230         if (!VirtualProtect((LPVOID)startaddr, length, PAGE_READWRITE, &flOldProtect))
231                 Sys_Error("Protection change failed\n");
232 }
233
234
235 /*
236 ================
237 Sys_Init
238 ================
239 */
240 void Sys_Init (void)
241 {
242         LARGE_INTEGER   PerformanceFreq;
243         unsigned int    lowpart, highpart;
244         OSVERSIONINFO   vinfo;
245
246         if (!QueryPerformanceFrequency (&PerformanceFreq))
247                 Sys_Error ("No hardware timer available");
248
249 // get 32 out of the 64 time bits such that we have around
250 // 1 microsecond resolution
251 #ifdef __BORLANDC__
252         lowpart = (unsigned int)PerformanceFreq.u.LowPart;
253         highpart = (unsigned int)PerformanceFreq.u.HighPart;
254 #else
255         lowpart = (unsigned int)PerformanceFreq.LowPart;
256         highpart = (unsigned int)PerformanceFreq.HighPart;
257 #endif  
258         lowshift = 0;
259
260         while (highpart || (lowpart > 2000000.0))
261         {
262                 lowshift++;
263                 lowpart >>= 1;
264                 lowpart |= (highpart & 1) << 31;
265                 highpart >>= 1;
266         }
267
268         pfreq = 1.0 / (double)lowpart;
269
270         Sys_InitFloatTime ();
271
272         vinfo.dwOSVersionInfoSize = sizeof(vinfo);
273
274         if (!GetVersionEx (&vinfo))
275                 Sys_Error ("Couldn't get OS info");
276
277         if ((vinfo.dwMajorVersion < 4) ||
278                 (vinfo.dwPlatformId == VER_PLATFORM_WIN32s))
279         {
280                 Sys_Error ("WinQuake requires at least Win95 or NT 4.0");
281         }
282
283         if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
284                 WinNT = true;
285         else
286                 WinNT = false;
287 }
288
289
290 void Sys_Error (char *error, ...)
291 {
292         va_list         argptr;
293         char            text[1024], text2[1024];
294         char            *text3 = "Press Enter to exit\n";
295         char            *text4 = "***********************************\n";
296         char            *text5 = "\n";
297         DWORD           dummy;
298         double          starttime;
299         static int      in_sys_error0 = 0;
300         static int      in_sys_error1 = 0;
301         static int      in_sys_error2 = 0;
302         static int      in_sys_error3 = 0;
303
304         if (!in_sys_error3)
305                 in_sys_error3 = 1;
306
307         va_start (argptr, error);
308         vsprintf (text, error, argptr);
309         va_end (argptr);
310
311         if (isDedicated)
312         {
313                 va_start (argptr, error);
314                 vsprintf (text, error, argptr);
315                 va_end (argptr);
316
317                 sprintf (text2, "ERROR: %s\n", text);
318                 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
319                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
320                 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
321                 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
322                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
323
324
325                 starttime = Sys_FloatTime ();
326                 sc_return_on_enter = true;      // so Enter will get us out of here
327
328                 while (!Sys_ConsoleInput () &&
329                                 ((Sys_FloatTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
330                 {
331                 }
332         }
333         else
334         {
335         // switch to windowed so the message box is visible, unless we already
336         // tried that and failed
337                 if (!in_sys_error0)
338                 {
339                         in_sys_error0 = 1;
340                         VID_SetDefaultMode ();
341                         MessageBox(NULL, text, "Quake Error",
342                                            MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
343                 }
344                 else
345                 {
346                         MessageBox(NULL, text, "Double Quake Error",
347                                            MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
348                 }
349         }
350
351         if (!in_sys_error1)
352         {
353                 in_sys_error1 = 1;
354                 Host_Shutdown ();
355         }
356
357 // shut down QHOST hooks if necessary
358         if (!in_sys_error2)
359         {
360                 in_sys_error2 = 1;
361                 DeinitConProc ();
362         }
363
364         exit (1);
365 }
366
367 void Sys_Printf (char *fmt, ...)
368 {
369         va_list         argptr;
370         char            text[1024];
371         DWORD           dummy;
372         
373         if (isDedicated)
374         {
375                 va_start (argptr,fmt);
376                 vsprintf (text, fmt, argptr);
377                 va_end (argptr);
378
379                 WriteFile(houtput, text, strlen (text), &dummy, NULL);  
380         }
381 }
382
383 void Sys_Quit (void)
384 {
385
386         Host_Shutdown();
387
388         if (tevent)
389                 CloseHandle (tevent);
390
391         if (isDedicated)
392                 FreeConsole ();
393
394 // shut down QHOST hooks if necessary
395         DeinitConProc ();
396
397         exit (0);
398 }
399
400
401 /*
402 ================
403 Sys_FloatTime
404 ================
405 */
406 double Sys_FloatTime (void)
407 {
408         static int                      sametimecount;
409         static unsigned int     oldtime;
410         static int                      first = 1;
411         LARGE_INTEGER           PerformanceCount;
412         unsigned int            temp, t2;
413         double                          time;
414
415         QueryPerformanceCounter (&PerformanceCount);
416
417 #ifdef __BORLANDC__
418         temp = ((unsigned int)PerformanceCount.u.LowPart >> lowshift) |
419             ((unsigned int)PerformanceCount.u.HighPart << (32 - lowshift));
420 #else
421
422         temp = ((unsigned int)PerformanceCount.LowPart >> lowshift) |
423                    ((unsigned int)PerformanceCount.HighPart << (32 - lowshift));
424 #endif
425         if (first)
426         {
427                 oldtime = temp;
428                 first = 0;
429         }
430         else
431         {
432         // check for turnover or backward time
433                 if ((temp <= oldtime) && ((oldtime - temp) < 0x10000000))
434                 {
435                         oldtime = temp; // so we can't get stuck
436                 }
437                 else
438                 {
439                         t2 = temp - oldtime;
440
441                         time = (double)t2 * pfreq;
442                         oldtime = temp;
443
444                         curtime += time;
445
446                         if (curtime == lastcurtime)
447                         {
448                                 sametimecount++;
449
450                                 if (sametimecount > 100000)
451                                 {
452                                         curtime += 1.0;
453                                         sametimecount = 0;
454                                 }
455                         }
456                         else
457                         {
458                                 sametimecount = 0;
459                         }
460
461                         lastcurtime = curtime;
462                 }
463         }
464
465     return curtime;
466 }
467
468
469 /*
470 ================
471 Sys_InitFloatTime
472 ================
473 */
474 void Sys_InitFloatTime (void)
475 {
476         int             j;
477
478         Sys_FloatTime ();
479
480         j = COM_CheckParm("-starttime");
481
482         if (j)
483         {
484                 curtime = (double) (atof(com_argv[j+1]));
485         }
486         else
487         {
488                 curtime = 0.0;
489         }
490
491         lastcurtime = curtime;
492 }
493
494
495 char *Sys_ConsoleInput (void)
496 {
497         static char     text[256];
498         static int              len;
499         INPUT_RECORD    recs[1024];
500         int             dummy;
501         int             ch, numread, numevents;
502
503         if (!isDedicated)
504                 return NULL;
505
506
507         for ( ;; )
508         {
509                 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
510                         Sys_Error ("Error getting # of console events");
511
512                 if (numevents <= 0)
513                         break;
514
515                 if (!ReadConsoleInput(hinput, recs, 1, &numread))
516                         Sys_Error ("Error reading console input");
517
518                 if (numread != 1)
519                         Sys_Error ("Couldn't read console input");
520
521                 if (recs[0].EventType == KEY_EVENT)
522                 {
523                         if (!recs[0].Event.KeyEvent.bKeyDown)
524                         {
525                                 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
526
527                                 switch (ch)
528                                 {
529                                         case '\r':
530                                                 WriteFile(houtput, "\r\n", 2, &dummy, NULL);    
531
532                                                 if (len)
533                                                 {
534                                                         text[len] = 0;
535                                                         len = 0;
536                                                         return text;
537                                                 }
538                                                 else if (sc_return_on_enter)
539                                                 {
540                                                 // special case to allow exiting from the error handler on Enter
541                                                         text[0] = '\r';
542                                                         len = 0;
543                                                         return text;
544                                                 }
545
546                                                 break;
547
548                                         case '\b':
549                                                 WriteFile(houtput, "\b \b", 3, &dummy, NULL);   
550                                                 if (len)
551                                                 {
552                                                         len--;
553                                                 }
554                                                 break;
555
556                                         default:
557                                                 if (ch >= ' ')
558                                                 {
559                                                         WriteFile(houtput, &ch, 1, &dummy, NULL);       
560                                                         text[len] = ch;
561                                                         len = (len + 1) & 0xff;
562                                                 }
563
564                                                 break;
565
566                                 }
567                         }
568                 }
569         }
570
571         return NULL;
572 }
573
574 void Sys_Sleep (void)
575 {
576         Sleep (1);
577 }
578
579
580 void Sys_SendKeyEvents (void)
581 {
582     MSG        msg;
583
584         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
585         {
586         // we always update if there are any event, even if we're paused
587                 scr_skipupdate = 0;
588
589                 if (!GetMessage (&msg, NULL, 0, 0))
590                         Sys_Quit ();
591
592         TranslateMessage (&msg);
593         DispatchMessage (&msg);
594         }
595 }
596
597
598 /*
599 ==============================================================================
600
601  WINDOWS CRAP
602
603 ==============================================================================
604 */
605
606
607 /*
608 ==================
609 WinMain
610 ==================
611 */
612 void SleepUntilInput (int time)
613 {
614
615         MsgWaitForMultipleObjects(1, &tevent, false, time, QS_ALLINPUT);
616 }
617
618
619 /*
620 ==================
621 WinMain
622 ==================
623 */
624 HINSTANCE       global_hInstance;
625 int                     global_nCmdShow;
626 char            *argv[MAX_NUM_ARGVS];
627 static char     *empty_string = "";
628
629 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
630 {
631         double                  time, oldtime, newtime/*, timediff*/;
632         MEMORYSTATUS    lpBuffer;
633         static  char    cwd[1024];
634         int                             t;
635
636     /* previous instances do not exist in Win32 */
637     if (hPrevInstance)
638         return 0;
639
640         global_hInstance = hInstance;
641         global_nCmdShow = nCmdShow;
642
643         lpBuffer.dwLength = sizeof(MEMORYSTATUS);
644         GlobalMemoryStatus (&lpBuffer);
645
646         if (!GetCurrentDirectory (sizeof(cwd), cwd))
647                 Sys_Error ("Couldn't determine current directory");
648
649         if (cwd[strlen(cwd)-1] == '/')
650                 cwd[strlen(cwd)-1] = 0;
651
652         host_parms.basedir = cwd;
653         host_parms.cachedir = NULL;
654
655         host_parms.argc = 1;
656         argv[0] = empty_string;
657
658         while (*lpCmdLine && (host_parms.argc < MAX_NUM_ARGVS))
659         {
660                 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
661                         lpCmdLine++;
662
663                 if (*lpCmdLine)
664                 {
665                         argv[host_parms.argc] = lpCmdLine;
666                         host_parms.argc++;
667
668                         while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
669                                 lpCmdLine++;
670
671                         if (*lpCmdLine)
672                         {
673                                 *lpCmdLine = 0;
674                                 lpCmdLine++;
675                         }
676                         
677                 }
678         }
679
680         host_parms.argv = argv;
681
682         COM_InitArgv (host_parms.argc, host_parms.argv);
683
684         host_parms.argc = com_argc;
685         host_parms.argv = com_argv;
686
687         isDedicated = (COM_CheckParm ("-dedicated") != 0);
688
689 // take the greater of all the available memory or half the total memory,
690 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
691 // request otherwise
692         /*
693         host_parms.memsize = lpBuffer.dwAvailPhys;
694
695         if (host_parms.memsize < MINIMUM_WIN_MEMORY)
696                 host_parms.memsize = MINIMUM_WIN_MEMORY;
697
698         if (host_parms.memsize < (lpBuffer.dwTotalPhys >> 1))
699                 host_parms.memsize = lpBuffer.dwTotalPhys >> 1;
700
701         if (host_parms.memsize > MAXIMUM_WIN_MEMORY)
702                 host_parms.memsize = MAXIMUM_WIN_MEMORY;
703         */
704         host_parms.memsize = DEFAULTMEM * 1048576;
705
706         if ((t = COM_CheckParm("-heapsize")))
707         {
708                 t++;
709                 if (t < com_argc)
710                         host_parms.memsize = atoi (com_argv[t]) * 1024;
711         }
712         else if ((t = COM_CheckParm("-mem")) || (t = COM_CheckParm("-winmem")))
713         {
714                 t++;
715                 if (t < com_argc)
716                         host_parms.memsize = atoi (com_argv[t]) * 1048576;
717         }
718
719         host_parms.membase = qmalloc(host_parms.memsize);
720
721         if (!host_parms.membase)
722                 Sys_Error ("Not enough memory free; check disk space\n");
723
724 //      Sys_PageIn (parms.membase, parms.memsize);
725
726         tevent = CreateEvent(NULL, false, false, NULL);
727
728         if (!tevent)
729                 Sys_Error ("Couldn't create event");
730
731         if (isDedicated)
732         {
733                 if (!AllocConsole ())
734                 {
735                         Sys_Error ("Couldn't create dedicated server console");
736                 }
737
738                 hinput = GetStdHandle (STD_INPUT_HANDLE);
739                 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
740
741         // give QHOST a chance to hook into the console
742                 if ((t = COM_CheckParm ("-HFILE")) > 0)
743                 {
744                         if (t < com_argc)
745                                 hFile = (HANDLE)atoi (com_argv[t+1]);
746                 }
747                         
748                 if ((t = COM_CheckParm ("-HPARENT")) > 0)
749                 {
750                         if (t < com_argc)
751                                 heventParent = (HANDLE)atoi (com_argv[t+1]);
752                 }
753                         
754                 if ((t = COM_CheckParm ("-HCHILD")) > 0)
755                 {
756                         if (t < com_argc)
757                                 heventChild = (HANDLE)atoi (com_argv[t+1]);
758                 }
759
760                 InitConProc (hFile, heventParent, heventChild);
761         }
762
763         Sys_Init ();
764
765 // because sound is off until we become active
766         S_BlockSound ();
767
768         Sys_Printf ("Host_Init\n");
769         Host_Init ();
770
771         oldtime = Sys_FloatTime ();
772
773     /* main window message loop */
774         while (1)
775         {
776                 if (isDedicated)
777                 {
778                         newtime = Sys_FloatTime ();
779                         time = newtime - oldtime;
780
781                         while (time < sys_ticrate.value )
782                         {
783                                 Sys_Sleep();
784                                 newtime = Sys_FloatTime ();
785                                 time = newtime - oldtime;
786                         }
787                 }
788                 else
789                 {
790                 // yield the CPU for a little while when paused, minimized, or not the focus
791                         if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized)
792                         {
793                                 SleepUntilInput (PAUSE_SLEEP);
794                                 scr_skipupdate = 1;             // no point in bothering to draw
795                         }
796                         else if (!ActiveApp && !DDActive)
797                         {
798                                 SleepUntilInput (NOT_FOCUS_SLEEP);
799                         }
800                         /*
801                         else if (!cls.timedemo && time < (timediff = 1.0 / maxfps.value))
802                         {
803                                 newtime = Sys_FloatTime ();
804                                 time = newtime - oldtime;
805
806                                 while (time < timediff)
807                                 {
808                                         Sys_Sleep();
809                                         newtime = Sys_FloatTime ();
810                                         time = newtime - oldtime;
811                                 }
812                         }
813                         */
814
815                         newtime = Sys_FloatTime ();
816                         time = newtime - oldtime;
817                 }
818
819                 Host_Frame (time);
820                 oldtime = newtime;
821         }
822
823     /* return success of application */
824     return true;
825 }
826