Debian Codegraph @

code/qcommon/common.c

raw symbols SCIP
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22 // common.c -- misc functions used in client and server
23
24 #include "q_shared.h"
25 #include "qcommon.h"
26 #include <setjmp.h>
27 #ifndef _WIN32
28 #include <netinet/in.h>
29 #include <sys/stat.h> // umask
30 #else
31 #include <winsock.h>
32 #endif
33
34 int demo_protocols[] =
35 { 67, 66, 0 };
36
37 #define MAX_NUM_ARGVS 50
38
39 #define MIN_DEDICATED_COMHUNKMEGS 1
40 #define DEF_COMHUNKMEGS 128
41 #define MIN_COMHUNKMEGS DEF_COMHUNKMEGS
42 #define DEF_COMZONEMEGS 48
43 #define DEF_COMHUNKMEGS_S XSTRING(DEF_COMHUNKMEGS)
44 #define DEF_COMZONEMEGS_S XSTRING(DEF_COMZONEMEGS)
45
46 int com_argc;
47 char *com_argv[MAX_NUM_ARGVS+1];
48
49 jmp_buf abortframe; // an ERR_DROP occurred, exit the entire frame
50
51
52 FILE *debuglogfile;
53 static fileHandle_t pipefile;
54 static fileHandle_t logfile;
55 fileHandle_t com_journalFile; // events are written here
56 fileHandle_t com_journalDataFile; // config files are written here
57
58 cvar_t *com_speeds;
59 cvar_t *com_developer;
60 cvar_t *com_dedicated;
61 cvar_t *com_timescale;
62 cvar_t *com_fixedtime;
63 cvar_t *com_journal;
64 cvar_t *com_maxfps;
65 cvar_t *com_altivec;
66 cvar_t *com_timedemo;
67 cvar_t *com_sv_running;
68 cvar_t *com_cl_running;
69 cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print
70 cvar_t *com_pipefile;
71 cvar_t *com_showtrace;
72 cvar_t *com_version;
73 cvar_t *com_blood;
74 cvar_t *com_buildScript; // for automated data building scripts
75 #ifdef CINEMATICS_INTRO
76 cvar_t *com_introPlayed;
77 #endif
78 cvar_t *cl_paused;
79 cvar_t *sv_paused;
80 cvar_t *cl_packetdelay;
81 cvar_t *sv_packetdelay;
82 cvar_t *com_cameraMode;
83 cvar_t *com_ansiColor;
84 cvar_t *com_unfocused;
85 cvar_t *com_maxfpsUnfocused;
86 cvar_t *com_minimized;
87 cvar_t *com_maxfpsMinimized;
88 cvar_t *com_abnormalExit;
89 cvar_t *com_standalone;
90 cvar_t *com_gamename;
91 cvar_t *com_protocol;
92 #ifdef LEGACY_PROTOCOL
93 cvar_t *com_legacyprotocol;
94 #endif
95 cvar_t *com_basegame;
96 cvar_t *com_homepath;
97 cvar_t *com_busyWait;
98 #ifndef DEDICATED
99 cvar_t *con_autochat;
100 #endif
101
102 #if idx64
103 int (*Q_VMftol)(void);
104 #elif id386
105 long (QDECL *Q_ftol)(float f);
106 int (QDECL *Q_VMftol)(void);
107 void (QDECL *Q_SnapVector)(vec3_t vec);
108 #endif
109
110 // com_speeds times
111 int time_game;
112 int time_frontend; // renderer frontend time
113 int time_backend; // renderer backend time
114
115 int com_frameTime;
116 int com_frameNumber;
117
118 qboolean com_errorEntered = qfalse;
119 qboolean com_fullyInitialized = qfalse;
120 qboolean com_gameRestarting = qfalse;
121 qboolean com_gameClientRestarting = qfalse;
122
123 char com_errorMessage[MAXPRINTMSG];
124
125 void Com_WriteConfig_f( void );
126 void CIN_CloseAllVideos( void );
127
128 //============================================================================
129
130 static char *rd_buffer;
131 static int rd_buffersize;
132 static void (*rd_flush)( char *buffer );
133
134 void Com_BeginRedirect (char *buffer, int buffersize, void (*flush)( char *) )
135 {
136 if (!buffer || !buffersize || !flush)
137 return;
138 rd_buffer = buffer;
139 rd_buffersize = buffersize;
140 rd_flush = flush;
141
142 *rd_buffer = 0;
143 }
144
145 void Com_EndRedirect (void)
146 {
147 if ( rd_flush ) {
148 rd_flush(rd_buffer);
149 }
150
151 rd_buffer = NULL;
152 rd_buffersize = 0;
153 rd_flush = NULL;
154 }
155
156 /*
157 =============
158 Com_Printf
159
160 Both client and server can use this, and it will output
161 to the appropriate place.
162
163 A raw string should NEVER be passed as fmt, because of "%f" type crashers.
164 =============
165 */
166 void QDECL Com_Printf( const char *fmt, ... ) {
167 va_list argptr;
168 char msg[MAXPRINTMSG];
169 static qboolean opening_qconsole = qfalse;
170
171
172 va_start (argptr,fmt);
173 Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
174 va_end (argptr);
175
176 if ( rd_buffer ) {
177 if ((strlen (msg) + strlen(rd_buffer)) > (rd_buffersize - 1)) {
178 rd_flush(rd_buffer);
179 *rd_buffer = 0;
180 }
181 Q_strcat(rd_buffer, rd_buffersize, msg);
182 // TTimo nooo .. that would defeat the purpose
183 //rd_flush(rd_buffer);
184 //*rd_buffer = 0;
185 return;
186 }
187
188 #ifndef DEDICATED
189 CL_ConsolePrint( msg );
190 #endif
191
192 // echo to dedicated console and early console
193 Sys_Print( msg );
194
195 // logfile
196 if ( com_logfile && com_logfile->integer ) {
197 // TTimo: only open the qconsole.log if the filesystem is in an initialized state
198 // also, avoid recursing in the qconsole.log opening (i.e. if fs_debug is on)
199 if ( !logfile && FS_Initialized() && !opening_qconsole) {
200 struct tm *newtime;
201 time_t aclock;
202
203 opening_qconsole = qtrue;
204
205 time( &aclock );
206 newtime = localtime( &aclock );
207
208 logfile = FS_FOpenFileWrite_HomeData( "qconsole.log" );
209
210 if(logfile)
211 {
212 Com_Printf( "logfile opened on %s\n", asctime( newtime ) );
213
214 if ( com_logfile->integer > 1 )
215 {
216 // force it to not buffer so we get valid
217 // data even if we are crashing
218 FS_ForceFlush(logfile);
219 }
220 }
221 else
222 {
223 Com_Printf("Opening qconsole.log failed!\n");
224 Cvar_SetValue("logfile", 0);
225 }
226
227 opening_qconsole = qfalse;
228 }
229 if ( logfile && FS_Initialized()) {
230 FS_Write(msg, strlen(msg), logfile);
231 }
232 }
233 }
234
235
236 /*
237 ================
238 Com_DPrintf
239
240 A Com_Printf that only shows up if the "developer" cvar is set
241 ================
242 */
243 void QDECL Com_DPrintf( const char *fmt, ...) {
244 va_list argptr;
245 char msg[MAXPRINTMSG];
246
247 if ( !com_developer || !com_developer->integer ) {
248 return; // don't confuse non-developers with techie stuff...
249 }
250
251 va_start (argptr,fmt);
252 Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
253 va_end (argptr);
254
255 Com_Printf ("%s", msg);
256 }
257
258 /*
259 =============
260 Com_Error
261
262 Both client and server can use this, and it will
263 do the appropriate thing.
264 =============
265 */
266 void QDECL Com_Error( int code, const char *fmt, ... ) {
267 va_list argptr;
268 static int lastErrorTime;
269 static int errorCount;
270 int currentTime;
271 qboolean restartClient;
272
273 if(com_errorEntered)
274 Sys_Error("recursive error after: %s", com_errorMessage);
275
276 com_errorEntered = qtrue;
277
278 Cvar_Set("com_errorCode", va("%i", code));
279
280 // when we are running automated scripts, make sure we
281 // know if anything failed
282 if ( com_buildScript && com_buildScript->integer ) {
283 code = ERR_FATAL;
284 }
285
286 // if we are getting a solid stream of ERR_DROP, do an ERR_FATAL
287 currentTime = Sys_Milliseconds();
288 if ( currentTime - lastErrorTime < 100 ) {
289 if ( ++errorCount > 3 ) {
290 code = ERR_FATAL;
291 }
292 } else {
293 errorCount = 0;
294 }
295 lastErrorTime = currentTime;
296
297 va_start (argptr,fmt);
298 Q_vsnprintf (com_errorMessage, sizeof(com_errorMessage),fmt,argptr);
299 va_end (argptr);
300
301 if (code != ERR_DISCONNECT && code != ERR_NEED_CD)
302 Cvar_Set("com_errorMessage", com_errorMessage);
303
304 restartClient = com_gameClientRestarting && !( com_cl_running && com_cl_running->integer );
305
306 com_gameRestarting = qfalse;
307 com_gameClientRestarting = qfalse;
308
309 if (code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT) {
310 VM_Forced_Unload_Start();
311 SV_Shutdown( "Server disconnected" );
312 if ( restartClient ) {
313 CL_Init();
314 }
315 CL_Disconnect( qtrue );
316 CL_FlushMemory( );
317 VM_Forced_Unload_Done();
318 // make sure we can get at our local stuff
319 FS_PureServerSetLoadedPaks("", "");
320 com_errorEntered = qfalse;
321 longjmp (abortframe, -1);
322 } else if (code == ERR_DROP) {
323 Com_Printf ("********************\nERROR: %s\n********************\n", com_errorMessage);
324 VM_Forced_Unload_Start();
325 SV_Shutdown (va("Server crashed: %s", com_errorMessage));
326 if ( restartClient ) {
327 CL_Init();
328 }
329 CL_Disconnect( qtrue );
330 CL_FlushMemory( );
331 VM_Forced_Unload_Done();
332 FS_PureServerSetLoadedPaks("", "");
333 com_errorEntered = qfalse;
334 longjmp (abortframe, -1);
335 } else if ( code == ERR_NEED_CD ) {
336 VM_Forced_Unload_Start();
337 SV_Shutdown( "Server didn't have CD" );
338 if ( restartClient ) {
339 CL_Init();
340 }
341 if ( com_cl_running && com_cl_running->integer ) {
342 CL_Disconnect( qtrue );
343 CL_FlushMemory( );
344 VM_Forced_Unload_Done();
345 CL_CDDialog();
346 } else {
347 Com_Printf("Server didn't have CD\n" );
348 VM_Forced_Unload_Done();
349 }
350
351 FS_PureServerSetLoadedPaks("", "");
352
353 com_errorEntered = qfalse;
354 longjmp (abortframe, -1);
355 } else {
356 VM_Forced_Unload_Start();
357 CL_Shutdown(va("Client fatal crashed: %s", com_errorMessage), qtrue, qtrue);
358 SV_Shutdown(va("Server fatal crashed: %s", com_errorMessage));
359 VM_Forced_Unload_Done();
360 }
361
362 Com_Shutdown ();
363
364 Sys_Error ("%s", com_errorMessage);
365 }
366
367
368 /*
369 =============
370 Com_Quit_f
371
372 Both client and server can use this, and it will
373 do the appropriate things.
374 =============
375 */
376 void Com_Quit_f( void ) {
377 // don't try to shutdown if we are in a recursive error
378 char *p = Cmd_Args( );
379 if ( !com_errorEntered ) {
380 // Some VMs might execute "quit" command directly,
381 // which would trigger an unload of active VM error.
382 // Sys_Quit will kill this process anyways, so
383 // a corrupt call stack makes no difference
384 VM_Forced_Unload_Start();
385 SV_Shutdown(p[0] ? p : "Server quit");
386 CL_Shutdown(p[0] ? p : "Client quit", qtrue, qtrue);
387 VM_Forced_Unload_Done();
388 Com_Shutdown ();
389 FS_Shutdown(qtrue);
390 }
391 Sys_Quit ();
392 }
393
394
395
396 /*
397 ============================================================================
398
399 COMMAND LINE FUNCTIONS
400
401 + characters separate the commandLine string into multiple console
402 command lines.
403
404 All of these are valid:
405
406 quake3 +set test blah +map test
407 quake3 set test blah+map test
408 quake3 set test blah + map test
409
410 ============================================================================
411 */
412
413 #define MAX_CONSOLE_LINES 32
414 int com_numConsoleLines;
415 char *com_consoleLines[MAX_CONSOLE_LINES];
416
417 /*
418 ==================
419 Com_ParseCommandLine
420
421 Break it up into multiple console lines
422 ==================
423 */
424 void Com_ParseCommandLine( char *commandLine ) {
425 int inq = 0;
426 com_consoleLines[0] = commandLine;
427 com_numConsoleLines = 1;
428
429 while ( *commandLine ) {
430 if (*commandLine == '"') {
431 inq = !inq;
432 }
433 // look for a + separating character
434 // if commandLine came from a file, we might have real line seperators
435 if ( (*commandLine == '+' && !inq) || *commandLine == '\n' || *commandLine == '\r' ) {
436 if ( com_numConsoleLines == MAX_CONSOLE_LINES ) {
437 return;
438 }
439 com_consoleLines[com_numConsoleLines] = commandLine + 1;
440 com_numConsoleLines++;
441 *commandLine = 0;
442 }
443 commandLine++;
444 }
445 }
446
447
448 /*
449 ===================
450 Com_SafeMode
451
452 Check for "safe" on the command line, which will
453 skip loading of q3config.cfg
454 ===================
455 */
456 qboolean Com_SafeMode( void ) {
457 int i;
458
459 for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
460 Cmd_TokenizeString( com_consoleLines[i] );
461 if ( !Q_stricmp( Cmd_Argv(0), "safe" )
462 || !Q_stricmp( Cmd_Argv(0), "cvar_restart" ) ) {
463 com_consoleLines[i][0] = 0;
464 return qtrue;
465 }
466 }
467 return qfalse;
468 }
469
470
471 /*
472 ===============
473 Com_StartupVariable
474
475 Searches for command line parameters that are set commands.
476 If match is not NULL, only that cvar will be looked for.
477 That is necessary because cddir and basedir need to be set
478 before the filesystem is started, but all other sets should
479 be after execing the config and default.
480 ===============
481 */
482 void Com_StartupVariable( const char *match ) {
483 int i;
484 char *s;
485
486 for (i=0 ; i < com_numConsoleLines ; i++) {
487 Cmd_TokenizeString( com_consoleLines[i] );
488 if ( strcmp( Cmd_Argv(0), "set" ) ) {
489 continue;
490 }
491
492 s = Cmd_Argv(1);
493
494 if(!match || !strcmp(s, match))
495 {
496 if(Cvar_Flags(s) == CVAR_NONEXISTENT)
497 Cvar_Get(s, Cmd_ArgsFrom(2), CVAR_USER_CREATED);
498 else
499 Cvar_Set2(s, Cmd_ArgsFrom(2), qfalse);
500 }
501 }
502 }
503
504
505 /*
506 =================
507 Com_AddStartupCommands
508
509 Adds command line parameters as script statements
510 Commands are separated by + signs
511
512 Returns qtrue if any late commands were added, which
513 will keep the demoloop from immediately starting
514 =================
515 */
516 qboolean Com_AddStartupCommands( void ) {
517 int i;
518 qboolean added;
519
520 added = qfalse;
521 // quote every token, so args with semicolons can work
522 for (i=0 ; i < com_numConsoleLines ; i++) {
523 if ( !com_consoleLines[i] || !com_consoleLines[i][0] ) {
524 continue;
525 }
526
527 // set commands already added with Com_StartupVariable
528 if ( !Q_stricmpn( com_consoleLines[i], "set ", 4 ) ) {
529 continue;
530 }
531
532 added = qtrue;
533 Cbuf_AddText( com_consoleLines[i] );
534 Cbuf_AddText( "\n" );
535 }
536
537 return added;
538 }
539
540
541 //============================================================================
542
543 void Info_Print( const char *s ) {
544 char key[BIG_INFO_KEY];
545 char value[BIG_INFO_VALUE];
546 char *o;
547 int l;
548
549 if (*s == '\\')
550 s++;
551 while (*s)
552 {
553 o = key;
554 while (*s && *s != '\\')
555 *o++ = *s++;
556
557 l = o - key;
558 if (l < 20)
559 {
560 Com_Memset (o, ' ', 20-l);
561 key[20] = 0;
562 }
563 else
564 *o = 0;
565 Com_Printf ("%s ", key);
566
567 if (!*s)
568 {
569 Com_Printf ("MISSING VALUE\n");
570 return;
571 }
572
573 o = value;
574 s++;
575 while (*s && *s != '\\')
576 *o++ = *s++;
577 *o = 0;
578
579 if (*s)
580 s++;
581 Com_Printf ("%s\n", value);
582 }
583 }
584
585 /*
586 ============
587 Com_StringContains
588 ============
589 */
590 char *Com_StringContains(char *str1, char *str2, int casesensitive) {
591 int len, i, j;
592
593 len = strlen(str1) - strlen(str2);
594 for (i = 0; i <= len; i++, str1++) {
595 for (j = 0; str2[j]; j++) {
596 if (casesensitive) {
597 if (str1[j] != str2[j]) {
598 break;
599 }
600 }
601 else {
602 if (toupper(str1[j]) != toupper(str2[j])) {
603 break;
604 }
605 }
606 }
607 if (!str2[j]) {
608 return str1;
609 }
610 }
611 return NULL;
612 }
613
614 /*
615 ============
616 Com_Filter
617 ============
618 */
619 int Com_Filter(char *filter, char *name, int casesensitive)
620 {
621 char buf[MAX_TOKEN_CHARS];
622 char *ptr;
623 int i, found;
624
625 while(*filter) {
626 if (*filter == '*') {
627 filter++;
628 for (i = 0; *filter; i++) {
629 if (*filter == '*' || *filter == '?' || *filter == '[') break;
630 buf[i] = *filter;
631 filter++;
632 }
633 buf[i] = '\0';
634 if (strlen(buf)) {
635 ptr = Com_StringContains(name, buf, casesensitive);
636 if (!ptr) return qfalse;
637 name = ptr + strlen(buf);
638 }
639 }
640 else if (*filter == '?') {
641 filter++;
642 name++;
643 }
644 else if (*filter == '[' && *(filter+1) == '[') {
645 filter++;
646 }
647 else if (*filter == '[') {
648 filter++;
649 found = qfalse;
650 while(*filter && !found) {
651 if (*filter == ']' && *(filter+1) != ']') break;
652 if (*(filter+1) == '-' && *(filter+2) && (*(filter+2) != ']' || *(filter+3) == ']')) {
653 if (casesensitive) {
654 if (*name >= *filter && *name <= *(filter+2)) found = qtrue;
655 }
656 else {
657 if (toupper(*name) >= toupper(*filter) &&
658 toupper(*name) <= toupper(*(filter+2))) found = qtrue;
659 }
660 filter += 3;
661 }
662 else {
663 if (casesensitive) {
664 if (*filter == *name) found = qtrue;
665 }
666 else {
667 if (toupper(*filter) == toupper(*name)) found = qtrue;
668 }
669 filter++;
670 }
671 }
672 if (!found) return qfalse;
673 while(*filter) {
674 if (*filter == ']' && *(filter+1) != ']') break;
675 filter++;
676 }
677 filter++;
678 name++;
679 }
680 else {
681 if (casesensitive) {
682 if (*filter != *name) return qfalse;
683 }
684 else {
685 if (toupper(*filter) != toupper(*name)) return qfalse;
686 }
687 filter++;
688 name++;
689 }
690 }
691 return qtrue;
692 }
693
694 /*
695 ============
696 Com_FilterPath
697 ============
698 */
699 int Com_FilterPath(char *filter, char *name, int casesensitive)
700 {
701 int i;
702 char new_filter[MAX_QPATH];
703 char new_name[MAX_QPATH];
704
705 for (i = 0; i < MAX_QPATH-1 && filter[i]; i++) {
706 if ( filter[i] == '\\' || filter[i] == ':' ) {
707 new_filter[i] = '/';
708 }
709 else {
710 new_filter[i] = filter[i];
711 }
712 }
713 new_filter[i] = '\0';
714 for (i = 0; i < MAX_QPATH-1 && name[i]; i++) {
715 if ( name[i] == '\\' || name[i] == ':' ) {
716 new_name[i] = '/';
717 }
718 else {
719 new_name[i] = name[i];
720 }
721 }
722 new_name[i] = '\0';
723 return Com_Filter(new_filter, new_name, casesensitive);
724 }
725
726 /*
727 ================
728 Com_RealTime
729 ================
730 */
731 int Com_RealTime(qtime_t *qtime) {
732 time_t t;
733 struct tm *tms;
734
735 t = time(NULL);
736 if (!qtime)
737 return t;
738 tms = localtime(&t);
739 if (tms) {
740 qtime->tm_sec = tms->tm_sec;
741 qtime->tm_min = tms->tm_min;
742 qtime->tm_hour = tms->tm_hour;
743 qtime->tm_mday = tms->tm_mday;
744 qtime->tm_mon = tms->tm_mon;
745 qtime->tm_year = tms->tm_year;
746 qtime->tm_wday = tms->tm_wday;
747 qtime->tm_yday = tms->tm_yday;
748 qtime->tm_isdst = tms->tm_isdst;
749 }
750 return t;
751 }
752
753
754 /*
755 ==============================================================================
756
757 ZONE MEMORY ALLOCATION
758
759 There is never any space between memblocks, and there will never be two
760 contiguous free memblocks.
761
762 The rover can be left pointing at a non-empty block
763
764 The zone calls are pretty much only used for small strings and structures,
765 all big things are allocated on the hunk.
766 ==============================================================================
767 */
768
769 #define ZONEID 0x1d4a11
770 #define MINFRAGMENT 64
771
772 typedef struct zonedebug_s {
773 char *label;
774 char *file;
775 int line;
776 int allocSize;
777 } zonedebug_t;
778
779 typedef struct memblock_s {
780 int size; // including the header and possibly tiny fragments
781 int tag; // a tag of 0 is a free block
782 struct memblock_s *next, *prev;
783 int id; // should be ZONEID
784 #ifdef ZONE_DEBUG
785 zonedebug_t d;
786 #endif
787 } memblock_t;
788
789 typedef struct {
790 int size; // total bytes malloced, including header
791 int used; // total bytes used
792 memblock_t blocklist; // start / end cap for linked list
793 memblock_t *rover;
794 } memzone_t;
795
796 // main zone for all "dynamic" memory allocation
797 static memzone_t *mainzone;
798 // we also have a small zone for small allocations that would only
799 // fragment the main zone (think of cvar and cmd strings)
800 static memzone_t *smallzone;
801
802 static void Z_CheckHeap( void );
803
804 /*
805 ========================
806 Z_ClearZone
807 ========================
808 */
809 static void Z_ClearZone( memzone_t *zone, int size ) {
810 memblock_t *block;
811
812 // set the entire zone to one free block
813
814 zone->blocklist.next = zone->blocklist.prev = block =
815 (memblock_t *)( (byte *)zone + sizeof(memzone_t) );
816 zone->blocklist.tag = 1; // in use block
817 zone->blocklist.id = 0;
818 zone->blocklist.size = 0;
819 zone->rover = block;
820 zone->size = size;
821 zone->used = 0;
822
823 block->prev = block->next = &zone->blocklist;
824 block->tag = 0; // free block
825 block->id = ZONEID;
826 block->size = size - sizeof(memzone_t);
827 }
828
829 /*
830 ========================
831 Z_AvailableZoneMemory
832 ========================
833 */
834 static int Z_AvailableZoneMemory( memzone_t *zone ) {
835 return zone->size - zone->used;
836 }
837
838 /*
839 ========================
840 Z_AvailableMemory
841 ========================
842 */
843 int Z_AvailableMemory( void ) {
844 return Z_AvailableZoneMemory( mainzone );
845 }
846
847 /*
848 ========================
849 Z_Free
850 ========================
851 */
852 void Z_Free( void *ptr ) {
853 memblock_t *block, *other;
854 memzone_t *zone;
855
856 if (!ptr) {
857 Com_Error( ERR_DROP, "Z_Free: NULL pointer" );
858 }
859
860 block = (memblock_t *) ( (byte *)ptr - sizeof(memblock_t));
861 if (block->id != ZONEID) {
862 Com_Error( ERR_FATAL, "Z_Free: freed a pointer without ZONEID" );
863 }
864 if (block->tag == 0) {
865 Com_Error( ERR_FATAL, "Z_Free: freed a freed pointer" );
866 }
867 // if static memory
868 if (block->tag == TAG_STATIC) {
869 return;
870 }
871
872 // check the memory trash tester
873 if ( *(int *)((byte *)block + block->size - 4 ) != ZONEID ) {
874 Com_Error( ERR_FATAL, "Z_Free: memory block wrote past end" );
875 }
876
877 if (block->tag == TAG_SMALL) {
878 zone = smallzone;
879 }
880 else {
881 zone = mainzone;
882 }
883
884 zone->used -= block->size;
885 // set the block to something that should cause problems
886 // if it is referenced...
887 Com_Memset( ptr, 0xaa, block->size - sizeof( *block ) );
888
889 block->tag = 0; // mark as free
890
891 other = block->prev;
892 if (!other->tag) {
893 // merge with previous free block
894 other->size += block->size;
895 other->next = block->next;
896 other->next->prev = other;
897 if (block == zone->rover) {
898 zone->rover = other;
899 }
900 block = other;
901 }
902
903 zone->rover = block;
904
905 other = block->next;
906 if ( !other->tag ) {
907 // merge the next free block onto the end
908 block->size += other->size;
909 block->next = other->next;
910 block->next->prev = block;
911 }
912 }
913
914
915 /*
916 ================
917 Z_FreeTags
918 ================
919 */
920 void Z_FreeTags( int tag ) {
921 memzone_t *zone;
922
923 if ( tag == TAG_SMALL ) {
924 zone = smallzone;
925 }
926 else {
927 zone = mainzone;
928 }
929 // use the rover as our pointer, because
930 // Z_Free automatically adjusts it
931 zone->rover = zone->blocklist.next;
932 do {
933 if ( zone->rover->tag == tag ) {
934 Z_Free( (void *)(zone->rover + 1) );
935 continue;
936 }
937 zone->rover = zone->rover->next;
938 } while ( zone->rover != &zone->blocklist );
939 }
940
941
942 /*
943 ================
944 Z_TagMalloc
945 ================
946 */
947 #ifdef ZONE_DEBUG
948 void *Z_TagMallocDebug( int size, int tag, char *label, char *file, int line ) {
949 int allocSize;
950 #else
951 void *Z_TagMalloc( int size, int tag ) {
952 #endif
953 int extra;
954 memblock_t *start, *rover, *new, *base;
955 memzone_t *zone;
956
957 if (!tag) {
958 Com_Error( ERR_FATAL, "Z_TagMalloc: tried to use a 0 tag" );
959 }
960
961 if ( tag == TAG_SMALL ) {
962 zone = smallzone;
963 }
964 else {
965 zone = mainzone;
966 }
967
968 #ifdef ZONE_DEBUG
969 allocSize = size;
970 #endif
971 //
972 // scan through the block list looking for the first free block
973 // of sufficient size
974 //
975 size += sizeof(memblock_t); // account for size of block header
976 size += 4; // space for memory trash tester
977 size = PAD(size, sizeof(intptr_t)); // align to 32/64 bit boundary
978
979 base = rover = zone->rover;
980 start = base->prev;
981
982 do {
983 if (rover == start) {
984 // scaned all the way around the list
985 #ifdef ZONE_DEBUG
986 Z_LogHeap();
987
988 Com_Error(ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone: %s, line: %d (%s)",
989 size, zone == smallzone ? "small" : "main", file, line, label);
990 #else
991 Com_Error(ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone",
992 size, zone == smallzone ? "small" : "main");
993 #endif
994 return NULL;
995 }
996 if (rover->tag) {
997 base = rover = rover->next;
998 } else {
999 rover = rover->next;
1000 }
1001 } while (base->tag || base->size < size);
1002
1003 //
1004 // found a block big enough
1005 //
1006 extra = base->size - size;
1007 if (extra > MINFRAGMENT) {
1008 // there will be a free fragment after the allocated block
1009 new = (memblock_t *) ((byte *)base + size );
1010 new->size = extra;
1011 new->tag = 0; // free block
1012 new->prev = base;
1013 new->id = ZONEID;
1014 new->next = base->next;
1015 new->next->prev = new;
1016 base->next = new;
1017 base->size = size;
1018 }
1019
1020 base->tag = tag; // no longer a free block
1021
1022 zone->rover = base->next; // next allocation will start looking here
1023 zone->used += base->size; //
1024
1025 base->id = ZONEID;
1026
1027 #ifdef ZONE_DEBUG
1028 base->d.label = label;
1029 base->d.file = file;
1030 base->d.line = line;
1031 base->d.allocSize = allocSize;
1032 #endif
1033
1034 // marker for memory trash testing
1035 *(int *)((byte *)base + base->size - 4) = ZONEID;
1036
1037 return (void *) ((byte *)base + sizeof(memblock_t));
1038 }
1039
1040 /*
1041 ========================
1042 Z_Malloc
1043 ========================
1044 */
1045 #ifdef ZONE_DEBUG
1046 void *Z_MallocDebug( int size, char *label, char *file, int line ) {
1047 #else
1048 void *Z_Malloc( int size ) {
1049 #endif
1050 void *buf;
1051
1052 //Z_CheckHeap (); // DEBUG
1053
1054 #ifdef ZONE_DEBUG
1055 buf = Z_TagMallocDebug( size, TAG_GENERAL, label, file, line );
1056 #else
1057 buf = Z_TagMalloc( size, TAG_GENERAL );
1058 #endif
1059 Com_Memset( buf, 0, size );
1060
1061 return buf;
1062 }
1063
1064 #ifdef ZONE_DEBUG
1065 void *S_MallocDebug( int size, char *label, char *file, int line ) {
1066 return Z_TagMallocDebug( size, TAG_SMALL, label, file, line );
1067 }
1068 #else
1069 void *S_Malloc( int size ) {
1070 return Z_TagMalloc( size, TAG_SMALL );
1071 }
1072 #endif
1073
1074 /*
1075 ========================
1076 Z_CheckHeap
1077 ========================
1078 */
1079 static void Z_CheckHeap( void ) {
1080 memblock_t *block;
1081
1082 for (block = mainzone->blocklist.next ; ; block = block->next) {
1083 if (block->next == &mainzone->blocklist) {
1084 break; // all blocks have been hit
1085 }
1086 if ( (byte *)block + block->size != (byte *)block->next)
1087 Com_Error( ERR_FATAL, "Z_CheckHeap: block size does not touch the next block" );
1088 if ( block->next->prev != block) {
1089 Com_Error( ERR_FATAL, "Z_CheckHeap: next block doesn't have proper back link" );
1090 }
1091 if ( !block->tag && !block->next->tag ) {
1092 Com_Error( ERR_FATAL, "Z_CheckHeap: two consecutive free blocks" );
1093 }
1094 }
1095 }
1096
1097 /*
1098 ========================
1099 Z_LogZoneHeap
1100 ========================
1101 */
1102 void Z_LogZoneHeap( memzone_t *zone, char *name ) {
1103 #ifdef ZONE_DEBUG
1104 char dump[32], *ptr;
1105 int i, j;
1106 #endif
1107 memblock_t *block;
1108 char buf[4096];
1109 int size, allocSize, numBlocks;
1110
1111 if (!logfile || !FS_Initialized())
1112 return;
1113 size = numBlocks = 0;
1114 #ifdef ZONE_DEBUG
1115 allocSize = 0;
1116 #endif
1117 Com_sprintf(buf, sizeof(buf), "\r\n================\r\n%s log\r\n================\r\n", name);
1118 FS_Write(buf, strlen(buf), logfile);
1119 for (block = zone->blocklist.next ; block->next != &zone->blocklist; block = block->next) {
1120 if (block->tag) {
1121 #ifdef ZONE_DEBUG
1122 ptr = ((char *) block) + sizeof(memblock_t);
1123 j = 0;
1124 for (i = 0; i < 20 && i < block->d.allocSize; i++) {
1125 if (ptr[i] >= 32 && ptr[i] < 127) {
1126 dump[j++] = ptr[i];
1127 }
1128 else {
1129 dump[j++] = '_';
1130 }
1131 }
1132 dump[j] = '\0';
1133 Com_sprintf(buf, sizeof(buf), "size = %8d: %s, line: %d (%s) [%s]\r\n", block->d.allocSize, block->d.file, block->d.line, block->d.label, dump);
1134 FS_Write(buf, strlen(buf), logfile);
1135 allocSize += block->d.allocSize;
1136 #endif
1137 size += block->size;
1138 numBlocks++;
1139 }
1140 }
1141 #ifdef ZONE_DEBUG
1142 // subtract debug memory
1143 size -= numBlocks * sizeof(zonedebug_t);
1144 #else
1145 allocSize = numBlocks * sizeof(memblock_t); // + 32 bit alignment
1146 #endif
1147 Com_sprintf(buf, sizeof(buf), "%d %s memory in %d blocks\r\n", size, name, numBlocks);
1148 FS_Write(buf, strlen(buf), logfile);
1149 Com_sprintf(buf, sizeof(buf), "%d %s memory overhead\r\n", size - allocSize, name);
1150 FS_Write(buf, strlen(buf), logfile);
1151 }
1152
1153 /*
1154 ========================
1155 Z_LogHeap
1156 ========================
1157 */
1158 void Z_LogHeap( void ) {
1159 Z_LogZoneHeap( mainzone, "MAIN" );
1160 Z_LogZoneHeap( smallzone, "SMALL" );
1161 }
1162
1163 // static mem blocks to reduce a lot of small zone overhead
1164 typedef struct memstatic_s {
1165 memblock_t b;
1166 byte mem[2];
1167 } memstatic_t;
1168
1169 memstatic_t emptystring =
1170 { {(sizeof(memblock_t)+2 + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'\0', '\0'} };
1171 memstatic_t numberstring[] = {
1172 { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'0', '\0'} },
1173 { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'1', '\0'} },
1174 { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'2', '\0'} },
1175 { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'3', '\0'} },
1176 { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'4', '\0'} },
1177 { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'5', '\0'} },
1178 { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'6', '\0'} },
1179 { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'7', '\0'} },
1180 { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'8', '\0'} },
1181 { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'9', '\0'} }
1182 };
1183
1184 /*
1185 ========================
1186 CopyString
1187
1188 NOTE: never write over the memory CopyString returns because
1189 memory from a memstatic_t might be returned
1190 ========================
1191 */
1192 char *CopyString( const char *in ) {
1193 char *out;
1194
1195 if (!in[0]) {
1196 return ((char *)&emptystring) + sizeof(memblock_t);
1197 }
1198 else if (!in[1]) {
1199 if (in[0] >= '0' && in[0] <= '9') {
1200 return ((char *)&numberstring[in[0]-'0']) + sizeof(memblock_t);
1201 }
1202 }
1203 out = S_Malloc (strlen(in)+1);
1204 strcpy (out, in);
1205 return out;
1206 }
1207
1208 /*
1209 ==============================================================================
1210
1211 Goals:
1212 reproducible without history effects -- no out of memory errors on weird map to map changes
1213 allow restarting of the client without fragmentation
1214 minimize total pages in use at run time
1215 minimize total pages needed during load time
1216
1217 Single block of memory with stack allocators coming from both ends towards the middle.
1218
1219 One side is designated the temporary memory allocator.
1220
1221 Temporary memory can be allocated and freed in any order.
1222
1223 A highwater mark is kept of the most in use at any time.
1224
1225 When there is no temporary memory allocated, the permanent and temp sides
1226 can be switched, allowing the already touched temp memory to be used for
1227 permanent storage.
1228
1229 Temp memory must never be allocated on two ends at once, or fragmentation
1230 could occur.
1231
1232 If we have any in-use temp memory, additional temp allocations must come from
1233 that side.
1234
1235 If not, we can choose to make either side the new temp side and push future
1236 permanent allocations to the other side. Permanent allocations should be
1237 kept on the side that has the current greatest wasted highwater mark.
1238
1239 ==============================================================================
1240 */
1241
1242
1243 #define HUNK_MAGIC 0x89537892
1244 #define HUNK_FREE_MAGIC 0x89537893
1245
1246 typedef struct {
1247 int magic;
1248 int size;
1249 } hunkHeader_t;
1250
1251 typedef struct {
1252 int mark;
1253 int permanent;
1254 int temp;
1255 int tempHighwater;
1256 } hunkUsed_t;
1257
1258 typedef struct hunkblock_s {
1259 int size;
1260 byte printed;
1261 struct hunkblock_s *next;
1262 char *label;
1263 char *file;
1264 int line;
1265 } hunkblock_t;
1266
1267 static hunkblock_t *hunkblocks;
1268
1269 static hunkUsed_t hunk_low, hunk_high;
1270 static hunkUsed_t *hunk_permanent, *hunk_temp;
1271
1272 static byte *s_hunkData = NULL;
1273 static int s_hunkTotal;
1274
1275 static int s_zoneTotal;
1276 static int s_smallZoneTotal;
1277
1278
1279 /*
1280 =================
1281 Com_Meminfo_f
1282 =================
1283 */
1284 void Com_Meminfo_f( void ) {
1285 memblock_t *block;
1286 int zoneBytes, zoneBlocks;
1287 int smallZoneBytes;
1288 int botlibBytes, rendererBytes;
1289 int unused;
1290
1291 zoneBytes = 0;
1292 botlibBytes = 0;
1293 rendererBytes = 0;
1294 zoneBlocks = 0;
1295 for (block = mainzone->blocklist.next ; ; block = block->next) {
1296 if ( Cmd_Argc() != 1 ) {
1297 Com_Printf ("block:%p size:%7i tag:%3i\n",
1298 (void *)block, block->size, block->tag);
1299 }
1300 if ( block->tag ) {
1301 zoneBytes += block->size;
1302 zoneBlocks++;
1303 if ( block->tag == TAG_BOTLIB ) {
1304 botlibBytes += block->size;
1305 } else if ( block->tag == TAG_RENDERER ) {
1306 rendererBytes += block->size;
1307 }
1308 }
1309
1310 if (block->next == &mainzone->blocklist) {
1311 break; // all blocks have been hit
1312 }
1313 if ( (byte *)block + block->size != (byte *)block->next) {
1314 Com_Printf ("ERROR: block size does not touch the next block\n");
1315 }
1316 if ( block->next->prev != block) {
1317 Com_Printf ("ERROR: next block doesn't have proper back link\n");
1318 }
1319 if ( !block->tag && !block->next->tag ) {
1320 Com_Printf ("ERROR: two consecutive free blocks\n");
1321 }
1322 }
1323
1324 smallZoneBytes = 0;
1325 for (block = smallzone->blocklist.next ; ; block = block->next) {
1326 if ( block->tag ) {
1327 smallZoneBytes += block->size;
1328 }
1329
1330 if (block->next == &smallzone->blocklist) {
1331 break; // all blocks have been hit
1332 }
1333 }
1334
1335 Com_Printf( "%8i bytes total hunk\n", s_hunkTotal );
1336 Com_Printf( "%8i bytes total zone\n", s_zoneTotal );
1337 Com_Printf( "\n" );
1338 Com_Printf( "%8i low mark\n", hunk_low.mark );
1339 Com_Printf( "%8i low permanent\n", hunk_low.permanent );
1340 if ( hunk_low.temp != hunk_low.permanent ) {
1341 Com_Printf( "%8i low temp\n", hunk_low.temp );
1342 }
1343 Com_Printf( "%8i low tempHighwater\n", hunk_low.tempHighwater );
1344 Com_Printf( "\n" );
1345 Com_Printf( "%8i high mark\n", hunk_high.mark );
1346 Com_Printf( "%8i high permanent\n", hunk_high.permanent );
1347 if ( hunk_high.temp != hunk_high.permanent ) {
1348 Com_Printf( "%8i high temp\n", hunk_high.temp );
1349 }
1350 Com_Printf( "%8i high tempHighwater\n", hunk_high.tempHighwater );
1351 Com_Printf( "\n" );
1352 Com_Printf( "%8i total hunk in use\n", hunk_low.permanent + hunk_high.permanent );
1353 unused = 0;
1354 if ( hunk_low.tempHighwater > hunk_low.permanent ) {
1355 unused += hunk_low.tempHighwater - hunk_low.permanent;
1356 }
1357 if ( hunk_high.tempHighwater > hunk_high.permanent ) {
1358 unused += hunk_high.tempHighwater - hunk_high.permanent;
1359 }
1360 Com_Printf( "%8i unused highwater\n", unused );
1361 Com_Printf( "\n" );
1362 Com_Printf( "%8i bytes in %i zone blocks\n", zoneBytes, zoneBlocks );
1363 Com_Printf( " %8i bytes in dynamic botlib\n", botlibBytes );
1364 Com_Printf( " %8i bytes in dynamic renderer\n", rendererBytes );
1365 Com_Printf( " %8i bytes in dynamic other\n", zoneBytes - ( botlibBytes + rendererBytes ) );
1366 Com_Printf( " %8i bytes in small Zone memory\n", smallZoneBytes );
1367 }
1368
1369 /*
1370 ===============
1371 Com_TouchMemory
1372
1373 Touch all known used data to make sure it is paged in
1374 ===============
1375 */
1376 void Com_TouchMemory( void ) {
1377 int start, end;
1378 int i, j;
1379 unsigned sum;
1380 memblock_t *block;
1381
1382 Z_CheckHeap();
1383
1384 start = Sys_Milliseconds();
1385
1386 sum = 0;
1387
1388 j = hunk_low.permanent >> 2;
1389 for ( i = 0 ; i < j ; i+=64 ) { // only need to touch each page
1390 sum += ((int *)s_hunkData)[i];
1391 }
1392
1393 i = ( s_hunkTotal - hunk_high.permanent ) >> 2;
1394 j = hunk_high.permanent >> 2;
1395 for ( ; i < j ; i+=64 ) { // only need to touch each page
1396 sum += ((int *)s_hunkData)[i];
1397 }
1398
1399 for (block = mainzone->blocklist.next ; ; block = block->next) {
1400 if ( block->tag ) {
1401 j = block->size >> 2;
1402 for ( i = 0 ; i < j ; i+=64 ) { // only need to touch each page
1403 sum += ((int *)block)[i];
1404 }
1405 }
1406 if ( block->next == &mainzone->blocklist ) {
1407 break; // all blocks have been hit
1408 }
1409 }
1410
1411 end = Sys_Milliseconds();
1412
1413 (void)sum; // Suppress warning
1414
1415 Com_Printf( "Com_TouchMemory: %i msec\n", end - start );
1416 }
1417
1418
1419
1420 /*
1421 =================
1422 Com_InitZoneMemory
1423 =================
1424 */
1425 void Com_InitSmallZoneMemory( void ) {
1426 s_smallZoneTotal = 512 * 1024;
1427 smallzone = calloc( s_smallZoneTotal, 1 );
1428 if ( !smallzone ) {
1429 Com_Error( ERR_FATAL, "Small zone data failed to allocate %1.1f megs", (float)s_smallZoneTotal / (1024*1024) );
1430 }
1431 Z_ClearZone( smallzone, s_smallZoneTotal );
1432 }
1433
1434 void Com_InitZoneMemory( void ) {
1435 cvar_t *cv;
1436
1437 // Please note: com_zoneMegs can only be set on the command line, and
1438 // not in q3config.cfg or Com_StartupVariable, as they haven't been
1439 // executed by this point. It's a chicken and egg problem. We need the
1440 // memory manager configured to handle those places where you would
1441 // configure the memory manager.
1442
1443 // allocate the random block zone
1444 cv = Cvar_Get( "com_zoneMegs", DEF_COMZONEMEGS_S, CVAR_LATCH | CVAR_ARCHIVE );
1445
1446 if ( cv->integer < DEF_COMZONEMEGS ) {
1447 s_zoneTotal = 1024 * 1024 * DEF_COMZONEMEGS;
1448 } else {
1449 s_zoneTotal = cv->integer * 1024 * 1024;
1450 }
1451
1452 mainzone = calloc( s_zoneTotal, 1 );
1453 if ( !mainzone ) {
1454 Com_Error( ERR_FATAL, "Zone data failed to allocate %i megs", s_zoneTotal / (1024*1024) );
1455 }
1456 Z_ClearZone( mainzone, s_zoneTotal );
1457
1458 }
1459
1460 /*
1461 =================
1462 Hunk_Log
1463 =================
1464 */
1465 void Hunk_Log( void) {
1466 hunkblock_t *block;
1467 char buf[4096];
1468 int size, numBlocks;
1469
1470 if (!logfile || !FS_Initialized())
1471 return;
1472 size = 0;
1473 numBlocks = 0;
1474 Com_sprintf(buf, sizeof(buf), "\r\n================\r\nHunk log\r\n================\r\n");
1475 FS_Write(buf, strlen(buf), logfile);
1476 for (block = hunkblocks ; block; block = block->next) {
1477 #ifdef HUNK_DEBUG
1478 Com_sprintf(buf, sizeof(buf), "size = %8d: %s, line: %d (%s)\r\n", block->size, block->file, block->line, block->label);
1479 FS_Write(buf, strlen(buf), logfile);
1480 #endif
1481 size += block->size;
1482 numBlocks++;
1483 }
1484 Com_sprintf(buf, sizeof(buf), "%d Hunk memory\r\n", size);
1485 FS_Write(buf, strlen(buf), logfile);
1486 Com_sprintf(buf, sizeof(buf), "%d hunk blocks\r\n", numBlocks);
1487 FS_Write(buf, strlen(buf), logfile);
1488 FS_Flush(logfile);
1489 }
1490
1491 /*
1492 =================
1493 Hunk_SmallLog
1494 =================
1495 */
1496 void Hunk_SmallLog( void) {
1497 hunkblock_t *block, *block2;
1498 char buf[4096];
1499 int size, locsize, numBlocks;
1500
1501 if (!logfile || !FS_Initialized())
1502 return;
1503 for (block = hunkblocks ; block; block = block->next) {
1504 block->printed = qfalse;
1505 }
1506 size = 0;
1507 numBlocks = 0;
1508 Com_sprintf(buf, sizeof(buf), "\r\n================\r\nHunk Small log\r\n================\r\n");
1509 FS_Write(buf, strlen(buf), logfile);
1510 for (block = hunkblocks; block; block = block->next) {
1511 if (block->printed) {
1512 continue;
1513 }
1514 locsize = block->size;
1515 for (block2 = block->next; block2; block2 = block2->next) {
1516 if (block->line != block2->line) {
1517 continue;
1518 }
1519 if (Q_stricmp(block->file, block2->file)) {
1520 continue;
1521 }
1522 size += block2->size;
1523 locsize += block2->size;
1524 block2->printed = qtrue;
1525 }
1526 #ifdef HUNK_DEBUG
1527 Com_sprintf(buf, sizeof(buf), "size = %8d: %s, line: %d (%s)\r\n", locsize, block->file, block->line, block->label);
1528 FS_Write(buf, strlen(buf), logfile);
1529 #else
1530 (void)locsize; // Suppress warning
1531 #endif
1532 size += block->size;
1533 numBlocks++;
1534 }
1535 Com_sprintf(buf, sizeof(buf), "%d Hunk memory\r\n", size);
1536 FS_Write(buf, strlen(buf), logfile);
1537 Com_sprintf(buf, sizeof(buf), "%d hunk blocks\r\n", numBlocks);
1538 FS_Write(buf, strlen(buf), logfile);
1539 FS_Flush(logfile);
1540 }
1541
1542 /*
1543 =================
1544 Com_InitHunkZoneMemory
1545 =================
1546 */
1547 void Com_InitHunkMemory( void ) {
1548 cvar_t *cv;
1549 int nMinAlloc;
1550 char *pMsg = NULL;
1551
1552 // make sure the file system has allocated and "not" freed any temp blocks
1553 // this allows the config and product id files ( journal files too ) to be loaded
1554 // by the file system without redunant routines in the file system utilizing different
1555 // memory systems
1556 if (FS_LoadStack() != 0) {
1557 Com_Error( ERR_FATAL, "Hunk initialization failed. File system load stack not zero");
1558 }
1559
1560 // allocate the stack based hunk allocator
1561 cv = Cvar_Get( "com_hunkMegs", DEF_COMHUNKMEGS_S, CVAR_LATCH | CVAR_ARCHIVE );
1562 Cvar_SetDescription(cv, "The size of the hunk memory segment");
1563
1564 // if we are not dedicated min allocation is 56, otherwise min is 1
1565 if (com_dedicated && com_dedicated->integer) {
1566 nMinAlloc = MIN_DEDICATED_COMHUNKMEGS;
1567 pMsg = "Minimum com_hunkMegs for a dedicated server is %i, allocating %i megs.\n";
1568 }
1569 else {
1570 nMinAlloc = MIN_COMHUNKMEGS;
1571 pMsg = "Minimum com_hunkMegs is %i, allocating %i megs.\n";
1572 }
1573
1574 if ( cv->integer < nMinAlloc ) {
1575 s_hunkTotal = 1024 * 1024 * nMinAlloc;
1576 Com_Printf(pMsg, nMinAlloc, s_hunkTotal / (1024 * 1024));
1577 } else {
1578 s_hunkTotal = cv->integer * 1024 * 1024;
1579 }
1580
1581 s_hunkData = calloc( s_hunkTotal + 31, 1 );
1582 if ( !s_hunkData ) {
1583 Com_Error( ERR_FATAL, "Hunk data failed to allocate %i megs", s_hunkTotal / (1024*1024) );
1584 }
1585 // cacheline align
1586 s_hunkData = (byte *) ( ( (intptr_t)s_hunkData + 31 ) & ~31 );
1587 Hunk_Clear();
1588
1589 Cmd_AddCommand( "meminfo", Com_Meminfo_f );
1590 #ifdef ZONE_DEBUG
1591 Cmd_AddCommand( "zonelog", Z_LogHeap );
1592 #endif
1593 #ifdef HUNK_DEBUG
1594 Cmd_AddCommand( "hunklog", Hunk_Log );
1595 Cmd_AddCommand( "hunksmalllog", Hunk_SmallLog );
1596 #endif
1597 }
1598
1599 /*
1600 ====================
1601 Hunk_MemoryRemaining
1602 ====================
1603 */
1604 int Hunk_MemoryRemaining( void ) {
1605 int low, high;
1606
1607 low = hunk_low.permanent > hunk_low.temp ? hunk_low.permanent : hunk_low.temp;
1608 high = hunk_high.permanent > hunk_high.temp ? hunk_high.permanent : hunk_high.temp;
1609
1610 return s_hunkTotal - ( low + high );
1611 }
1612
1613 /*
1614 ===================
1615 Hunk_SetMark
1616
1617 The server calls this after the level and game VM have been loaded
1618 ===================
1619 */
1620 void Hunk_SetMark( void ) {
1621 hunk_low.mark = hunk_low.permanent;
1622 hunk_high.mark = hunk_high.permanent;
1623 }
1624
1625 /*
1626 =================
1627 Hunk_ClearToMark
1628
1629 The client calls this before starting a vid_restart or snd_restart
1630 =================
1631 */
1632 void Hunk_ClearToMark( void ) {
1633 hunk_low.permanent = hunk_low.temp = hunk_low.mark;
1634 hunk_high.permanent = hunk_high.temp = hunk_high.mark;
1635 }
1636
1637 /*
1638 =================
1639 Hunk_CheckMark
1640 =================
1641 */
1642 qboolean Hunk_CheckMark( void ) {
1643 if( hunk_low.mark || hunk_high.mark ) {
1644 return qtrue;
1645 }
1646 return qfalse;
1647 }
1648
1649 void CL_ShutdownCGame( void );
1650 void CL_ShutdownUI( void );
1651 void SV_ShutdownGameProgs( void );
1652
1653 /*
1654 =================
1655 Hunk_Clear
1656
1657 The server calls this before shutting down or loading a new map
1658 =================
1659 */
1660 void Hunk_Clear( void ) {
1661
1662 #ifndef DEDICATED
1663 CL_ShutdownCGame();
1664 CL_ShutdownUI();
1665 #endif
1666 SV_ShutdownGameProgs();
1667 #ifndef DEDICATED
1668 CIN_CloseAllVideos();
1669 #endif
1670 hunk_low.mark = 0;
1671 hunk_low.permanent = 0;
1672 hunk_low.temp = 0;
1673 hunk_low.tempHighwater = 0;
1674
1675 hunk_high.mark = 0;
1676 hunk_high.permanent = 0;
1677 hunk_high.temp = 0;
1678 hunk_high.tempHighwater = 0;
1679
1680 hunk_permanent = &hunk_low;
1681 hunk_temp = &hunk_high;
1682
1683 Com_Printf( "Hunk_Clear: reset the hunk ok\n" );
1684 VM_Clear();
1685 #ifdef HUNK_DEBUG
1686 hunkblocks = NULL;
1687 #endif
1688 }
1689
1690 static void Hunk_SwapBanks( void ) {
1691 hunkUsed_t *swap;
1692
1693 // can't swap banks if there is any temp already allocated
1694 if ( hunk_temp->temp != hunk_temp->permanent ) {
1695 return;
1696 }
1697
1698 // if we have a larger highwater mark on this side, start making
1699 // our permanent allocations here and use the other side for temp
1700 if ( hunk_temp->tempHighwater - hunk_temp->permanent >
1701 hunk_permanent->tempHighwater - hunk_permanent->permanent ) {
1702 swap = hunk_temp;
1703 hunk_temp = hunk_permanent;
1704 hunk_permanent = swap;
1705 }
1706 }
1707
1708 /*
1709 =================
1710 Hunk_Alloc
1711
1712 Allocate permanent (until the hunk is cleared) memory
1713 =================
1714 */
1715 #ifdef HUNK_DEBUG
1716 void *Hunk_AllocDebug( int size, ha_pref preference, char *label, char *file, int line ) {
1717 #else
1718 void *Hunk_Alloc( int size, ha_pref preference ) {
1719 #endif
1720 void *buf;
1721
1722 if ( s_hunkData == NULL)
1723 {
1724 Com_Error( ERR_FATAL, "Hunk_Alloc: Hunk memory system not initialized" );
1725 }
1726
1727 // can't do preference if there is any temp allocated
1728 if (preference == h_dontcare || hunk_temp->temp != hunk_temp->permanent) {
1729 Hunk_SwapBanks();
1730 } else {
1731 if (preference == h_low && hunk_permanent != &hunk_low) {
1732 Hunk_SwapBanks();
1733 } else if (preference == h_high && hunk_permanent != &hunk_high) {
1734 Hunk_SwapBanks();
1735 }
1736 }
1737
1738 #ifdef HUNK_DEBUG
1739 size += sizeof(hunkblock_t);
1740 #endif
1741
1742 // round to cacheline
1743 size = (size+31)&~31;
1744
1745 if ( hunk_low.temp + hunk_high.temp + size > s_hunkTotal ) {
1746 #ifdef HUNK_DEBUG
1747 Hunk_Log();
1748 Hunk_SmallLog();
1749
1750 Com_Error(ERR_DROP, "Hunk_Alloc failed on %i: %s, line: %d (%s)", size, file, line, label);
1751 #else
1752 Com_Error(ERR_DROP, "Hunk_Alloc failed on %i", size);
1753 #endif
1754 }
1755
1756 if ( hunk_permanent == &hunk_low ) {
1757 buf = (void *)(s_hunkData + hunk_permanent->permanent);
1758 hunk_permanent->permanent += size;
1759 } else {
1760 hunk_permanent->permanent += size;
1761 buf = (void *)(s_hunkData + s_hunkTotal - hunk_permanent->permanent );
1762 }
1763
1764 hunk_permanent->temp = hunk_permanent->permanent;
1765
1766 Com_Memset( buf, 0, size );
1767
1768 #ifdef HUNK_DEBUG
1769 {
1770 hunkblock_t *block;
1771
1772 block = (hunkblock_t *) buf;
1773 block->size = size - sizeof(hunkblock_t);
1774 block->file = file;
1775 block->label = label;
1776 block->line = line;
1777 block->next = hunkblocks;
1778 hunkblocks = block;
1779 buf = ((byte *) buf) + sizeof(hunkblock_t);
1780 }
1781 #endif
1782 return buf;
1783 }
1784
1785 /*
1786 =================
1787 Hunk_AllocateTempMemory
1788
1789 This is used by the file loading system.
1790 Multiple files can be loaded in temporary memory.
1791 When the files-in-use count reaches zero, all temp memory will be deleted
1792 =================
1793 */
1794 void *Hunk_AllocateTempMemory( int size ) {
1795 void *buf;
1796 hunkHeader_t *hdr;
1797
1798 // return a Z_Malloc'd block if the hunk has not been initialized
1799 // this allows the config and product id files ( journal files too ) to be loaded
1800 // by the file system without redunant routines in the file system utilizing different
1801 // memory systems
1802 if ( s_hunkData == NULL )
1803 {
1804 return Z_Malloc(size);
1805 }
1806
1807 Hunk_SwapBanks();
1808
1809 size = PAD(size, sizeof(intptr_t)) + sizeof( hunkHeader_t );
1810
1811 if ( hunk_temp->temp + hunk_permanent->permanent + size > s_hunkTotal ) {
1812 Com_Error( ERR_DROP, "Hunk_AllocateTempMemory: failed on %i", size );
1813 }
1814
1815 if ( hunk_temp == &hunk_low ) {
1816 buf = (void *)(s_hunkData + hunk_temp->temp);
1817 hunk_temp->temp += size;
1818 } else {
1819 hunk_temp->temp += size;
1820 buf = (void *)(s_hunkData + s_hunkTotal - hunk_temp->temp );
1821 }
1822
1823 if ( hunk_temp->temp > hunk_temp->tempHighwater ) {
1824 hunk_temp->tempHighwater = hunk_temp->temp;
1825 }
1826
1827 hdr = (hunkHeader_t *)buf;
1828 buf = (void *)(hdr+1);
1829
1830 hdr->magic = HUNK_MAGIC;
1831 hdr->size = size;
1832
1833 // don't bother clearing, because we are going to load a file over it
1834 return buf;
1835 }
1836
1837
1838 /*
1839 ==================
1840 Hunk_FreeTempMemory
1841 ==================
1842 */
1843 void Hunk_FreeTempMemory( void *buf ) {
1844 hunkHeader_t *hdr;
1845
1846 // free with Z_Free if the hunk has not been initialized
1847 // this allows the config and product id files ( journal files too ) to be loaded
1848 // by the file system without redunant routines in the file system utilizing different
1849 // memory systems
1850 if ( s_hunkData == NULL )
1851 {
1852 Z_Free(buf);
1853 return;
1854 }
1855
1856
1857 hdr = ( (hunkHeader_t *)buf ) - 1;
1858 if ( hdr->magic != HUNK_MAGIC ) {
1859 Com_Error( ERR_FATAL, "Hunk_FreeTempMemory: bad magic" );
1860 }
1861
1862 hdr->magic = HUNK_FREE_MAGIC;
1863
1864 // this only works if the files are freed in stack order,
1865 // otherwise the memory will stay around until Hunk_ClearTempMemory
1866 if ( hunk_temp == &hunk_low ) {
1867 if ( hdr == (void *)(s_hunkData + hunk_temp->temp - hdr->size ) ) {
1868 hunk_temp->temp -= hdr->size;
1869 } else {
1870 Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
1871 }
1872 } else {
1873 if ( hdr == (void *)(s_hunkData + s_hunkTotal - hunk_temp->temp ) ) {
1874 hunk_temp->temp -= hdr->size;
1875 } else {
1876 Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
1877 }
1878 }
1879 }
1880
1881
1882 /*
1883 =================
1884 Hunk_ClearTempMemory
1885
1886 The temp space is no longer needed. If we have left more
1887 touched but unused memory on this side, have future
1888 permanent allocs use this side.
1889 =================
1890 */
1891 void Hunk_ClearTempMemory( void ) {
1892 if ( s_hunkData != NULL ) {
1893 hunk_temp->temp = hunk_temp->permanent;
1894 }
1895 }
1896
1897 /*
1898 ===================================================================
1899
1900 EVENTS AND JOURNALING
1901
1902 In addition to these events, .cfg files are also copied to the
1903 journaled file
1904 ===================================================================
1905 */
1906
1907 #define MAX_PUSHED_EVENTS 1024
1908 static int com_pushedEventsHead = 0;
1909 static int com_pushedEventsTail = 0;
1910 static sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS];
1911
1912 /*
1913 =================
1914 Com_InitJournaling
1915 =================
1916 */
1917 void Com_InitJournaling( void ) {
1918 Com_StartupVariable( "journal" );
1919 com_journal = Cvar_Get ("journal", "0", CVAR_INIT);
1920 if ( !com_journal->integer ) {
1921 return;
1922 }
1923
1924 if ( com_journal->integer == 1 ) {
1925 Com_Printf( "Journaling events\n");
1926 com_journalFile = FS_FOpenFileWrite_HomeState( "journal.dat" );
1927 com_journalDataFile = FS_FOpenFileWrite_HomeState( "journaldata.dat" );
1928 } else if ( com_journal->integer == 2 ) {
1929 Com_Printf( "Replaying journaled events\n");
1930 FS_FOpenFileRead( "journal.dat", &com_journalFile, qtrue );
1931 FS_FOpenFileRead( "journaldata.dat", &com_journalDataFile, qtrue );
1932 }
1933
1934 if ( !com_journalFile || !com_journalDataFile ) {
1935 Cvar_Set( "com_journal", "0" );
1936 com_journalFile = 0;
1937 com_journalDataFile = 0;
1938 Com_Printf( "Couldn't open journal files\n" );
1939 }
1940 }
1941
1942 /*
1943 ========================================================================
1944
1945 EVENT LOOP
1946
1947 ========================================================================
1948 */
1949
1950 #define MAX_QUEUED_EVENTS 256
1951 #define MASK_QUEUED_EVENTS ( MAX_QUEUED_EVENTS - 1 )
1952
1953 static sysEvent_t eventQueue[ MAX_QUEUED_EVENTS ];
1954 static int eventHead = 0;
1955 static int eventTail = 0;
1956
1957 /*
1958 ================
1959 Com_QueueEvent
1960
1961 A time of 0 will get the current time
1962 Ptr should either be null, or point to a block of data that can
1963 be freed by the game later.
1964 ================
1965 */
1966 void Com_QueueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr )
1967 {
1968 sysEvent_t *ev;
1969
1970 // combine mouse movement with previous mouse event
1971 if ( type == SE_MOUSE && eventHead != eventTail )
1972 {
1973 ev = &eventQueue[ ( eventHead + MAX_QUEUED_EVENTS - 1 ) & MASK_QUEUED_EVENTS ];
1974
1975 if ( ev->evType == SE_MOUSE )
1976 {
1977 ev->evValue += value;
1978 ev->evValue2 += value2;
1979 return;
1980 }
1981 }
1982
1983 ev = &eventQueue[ eventHead & MASK_QUEUED_EVENTS ];
1984
1985 if ( eventHead - eventTail >= MAX_QUEUED_EVENTS )
1986 {
1987 Com_Printf("Com_QueueEvent: overflow\n");
1988 // we are discarding an event, but don't leak memory
1989 if ( ev->evPtr )
1990 {
1991 Z_Free( ev->evPtr );
1992 }
1993 eventTail++;
1994 }
1995
1996 eventHead++;
1997
1998 if ( time == 0 )
1999 {
2000 time = Sys_Milliseconds();
2001 }
2002
2003 ev->evTime = time;
2004 ev->evType = type;
2005 ev->evValue = value;
2006 ev->evValue2 = value2;
2007 ev->evPtrLength = ptrLength;
2008 ev->evPtr = ptr;
2009 }
2010
2011 /*
2012 ================
2013 Com_GetSystemEvent
2014
2015 ================
2016 */
2017 sysEvent_t Com_GetSystemEvent( void )
2018 {
2019 sysEvent_t ev;
2020 char *s;
2021
2022 // return if we have data
2023 if ( eventHead > eventTail )
2024 {
2025 eventTail++;
2026 return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
2027 }
2028
2029 // check for console commands
2030 s = Sys_ConsoleInput();
2031 if ( s )
2032 {
2033 char *b;
2034 int len;
2035
2036 len = strlen( s ) + 1;
2037 b = Z_Malloc( len );
2038 strcpy( b, s );
2039 Com_QueueEvent( 0, SE_CONSOLE, 0, 0, len, b );
2040 }
2041
2042 // return if we have data
2043 if ( eventHead > eventTail )
2044 {
2045 eventTail++;
2046 return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
2047 }
2048
2049 // create an empty event to return
2050 memset( &ev, 0, sizeof( ev ) );
2051 ev.evTime = Sys_Milliseconds();
2052
2053 return ev;
2054 }
2055
2056 /*
2057 =================
2058 Com_GetRealEvent
2059 =================
2060 */
2061 sysEvent_t Com_GetRealEvent( void ) {
2062 int r;
2063 sysEvent_t ev;
2064
2065 // either get an event from the system or the journal file
2066 if ( com_journal->integer == 2 ) {
2067 r = FS_Read( &ev, sizeof(ev), com_journalFile );
2068 if ( r != sizeof(ev) ) {
2069 Com_Error( ERR_FATAL, "Error reading from journal file" );
2070 }
2071 if ( ev.evPtrLength ) {
2072 ev.evPtr = Z_Malloc( ev.evPtrLength );
2073 r = FS_Read( ev.evPtr, ev.evPtrLength, com_journalFile );
2074 if ( r != ev.evPtrLength ) {
2075 Com_Error( ERR_FATAL, "Error reading from journal file" );
2076 }
2077 }
2078 } else {
2079 ev = Com_GetSystemEvent();
2080
2081 // write the journal value out if needed
2082 if ( com_journal->integer == 1 ) {
2083 r = FS_Write( &ev, sizeof(ev), com_journalFile );
2084 if ( r != sizeof(ev) ) {
2085 Com_Error( ERR_FATAL, "Error writing to journal file" );
2086 }
2087 if ( ev.evPtrLength ) {
2088 r = FS_Write( ev.evPtr, ev.evPtrLength, com_journalFile );
2089 if ( r != ev.evPtrLength ) {
2090 Com_Error( ERR_FATAL, "Error writing to journal file" );
2091 }
2092 }
2093 }
2094 }
2095
2096 return ev;
2097 }
2098
2099
2100 /*
2101 =================
2102 Com_InitPushEvent
2103 =================
2104 */
2105 void Com_InitPushEvent( void ) {
2106 // clear the static buffer array
2107 // this requires SE_NONE to be accepted as a valid but NOP event
2108 memset( com_pushedEvents, 0, sizeof(com_pushedEvents) );
2109 // reset counters while we are at it
2110 // beware: GetEvent might still return an SE_NONE from the buffer
2111 com_pushedEventsHead = 0;
2112 com_pushedEventsTail = 0;
2113 }
2114
2115
2116 /*
2117 =================
2118 Com_PushEvent
2119 =================
2120 */
2121 void Com_PushEvent( sysEvent_t *event ) {
2122 sysEvent_t *ev;
2123 static int printedWarning = 0;
2124
2125 ev = &com_pushedEvents[ com_pushedEventsHead & (MAX_PUSHED_EVENTS-1) ];
2126
2127 if ( com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS ) {
2128
2129 // don't print the warning constantly, or it can give time for more...
2130 if ( !printedWarning ) {
2131 printedWarning = qtrue;
2132 Com_Printf( "WARNING: Com_PushEvent overflow\n" );
2133 }
2134
2135 if ( ev->evPtr ) {
2136 Z_Free( ev->evPtr );
2137 }
2138 com_pushedEventsTail++;
2139 } else {
2140 printedWarning = qfalse;
2141 }
2142
2143 *ev = *event;
2144 com_pushedEventsHead++;
2145 }
2146
2147 /*
2148 =================
2149 Com_GetEvent
2150 =================
2151 */
2152 sysEvent_t Com_GetEvent( void ) {
2153 if ( com_pushedEventsHead > com_pushedEventsTail ) {
2154 com_pushedEventsTail++;
2155 return com_pushedEvents[ (com_pushedEventsTail-1) & (MAX_PUSHED_EVENTS-1) ];
2156 }
2157 return Com_GetRealEvent();
2158 }
2159
2160 /*
2161 =================
2162 Com_RunAndTimeServerPacket
2163 =================
2164 */
2165 void Com_RunAndTimeServerPacket( netadr_t *evFrom, msg_t *buf ) {
2166 int t1, t2, msec;
2167
2168 t1 = 0;
2169
2170 if ( com_speeds->integer ) {
2171 t1 = Sys_Milliseconds ();
2172 }
2173
2174 SV_PacketEvent( *evFrom, buf );
2175
2176 if ( com_speeds->integer ) {
2177 t2 = Sys_Milliseconds ();
2178 msec = t2 - t1;
2179 if ( com_speeds->integer == 3 ) {
2180 Com_Printf( "SV_PacketEvent time: %i\n", msec );
2181 }
2182 }
2183 }
2184
2185 /*
2186 =================
2187 Com_EventLoop
2188
2189 Returns last event time
2190 =================
2191 */
2192 int Com_EventLoop( void ) {
2193 sysEvent_t ev;
2194 netadr_t evFrom;
2195 byte bufData[MAX_MSGLEN];
2196 msg_t buf;
2197
2198 MSG_Init( &buf, bufData, sizeof( bufData ) );
2199
2200 while ( 1 ) {
2201 ev = Com_GetEvent();
2202
2203 // if no more events are available
2204 if ( ev.evType == SE_NONE ) {
2205 // manually send packet events for the loopback channel
2206 while ( NET_GetLoopPacket( NS_CLIENT, &evFrom, &buf ) ) {
2207 CL_PacketEvent( evFrom, &buf );
2208 }
2209
2210 while ( NET_GetLoopPacket( NS_SERVER, &evFrom, &buf ) ) {
2211 // if the server just shut down, flush the events
2212 if ( com_sv_running->integer ) {
2213 Com_RunAndTimeServerPacket( &evFrom, &buf );
2214 }
2215 }
2216
2217 return ev.evTime;
2218 }
2219
2220
2221 switch(ev.evType)
2222 {
2223 case SE_KEY:
2224 CL_KeyEvent( ev.evValue, ev.evValue2, ev.evTime );
2225 break;
2226 case SE_CHAR:
2227 CL_CharEvent( ev.evValue );
2228 break;
2229 case SE_MOUSE:
2230 CL_MouseEvent( ev.evValue, ev.evValue2, ev.evTime );
2231 break;
2232 case SE_JOYSTICK_AXIS:
2233 CL_JoystickEvent( ev.evValue, ev.evValue2, ev.evTime );
2234 break;
2235 case SE_CONSOLE:
2236 Cbuf_AddText( (char *)ev.evPtr );
2237 Cbuf_AddText( "\n" );
2238 break;
2239 default:
2240 Com_Error( ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType );
2241 break;
2242 }
2243
2244 // free any block data
2245 if ( ev.evPtr ) {
2246 Z_Free( ev.evPtr );
2247 }
2248 }
2249
2250 return 0; // never reached
2251 }
2252
2253 /*
2254 ================
2255 Com_Milliseconds
2256
2257 Can be used for profiling, but will be journaled accurately
2258 ================
2259 */
2260 int Com_Milliseconds (void) {
2261 sysEvent_t ev;
2262
2263 // get events and push them until we get a null event with the current time
2264 do {
2265
2266 ev = Com_GetRealEvent();
2267 if ( ev.evType != SE_NONE ) {
2268 Com_PushEvent( &ev );
2269 }
2270 } while ( ev.evType != SE_NONE );
2271
2272 return ev.evTime;
2273 }
2274
2275 //============================================================================
2276
2277 /*
2278 =============
2279 Com_Error_f
2280
2281 Just throw a fatal error to
2282 test error shutdown procedures
2283 =============
2284 */
2285 static void Q_NO_RETURN Com_Error_f (void) {
2286 if ( Cmd_Argc() > 1 ) {
2287 Com_Error( ERR_DROP, "Testing drop error" );
2288 } else {
2289 Com_Error( ERR_FATAL, "Testing fatal error" );
2290 }
2291 }
2292
2293
2294 /*
2295 =============
2296 Com_Freeze_f
2297
2298 Just freeze in place for a given number of seconds to test
2299 error recovery
2300 =============
2301 */
2302 static void Com_Freeze_f (void) {
2303 float s;
2304 int start, now;
2305
2306 if ( Cmd_Argc() != 2 ) {
2307 Com_Printf( "freeze <seconds>\n" );
2308 return;
2309 }
2310 s = atof( Cmd_Argv(1) );
2311
2312 start = Com_Milliseconds();
2313
2314 while ( 1 ) {
2315 now = Com_Milliseconds();
2316 if ( ( now - start ) * 0.001 > s ) {
2317 break;
2318 }
2319 }
2320 }
2321
2322 /*
2323 =================
2324 Com_Crash_f
2325
2326 A way to force a bus error for development reasons
2327 =================
2328 */
2329 static void Com_Crash_f( void ) {
2330 * ( volatile int * ) 0 = 0x12345678;
2331 }
2332
2333 /*
2334 ==================
2335 Com_Setenv_f
2336
2337 For controlling environment variables
2338 ==================
2339 */
2340 void Com_Setenv_f(void)
2341 {
2342 int argc = Cmd_Argc();
2343 char *arg1 = Cmd_Argv(1);
2344
2345 if(argc > 2)
2346 {
2347 char *arg2 = Cmd_ArgsFrom(2);
2348
2349 Sys_SetEnv(arg1, arg2);
2350 }
2351 else if(argc == 2)
2352 {
2353 char *env = getenv(arg1);
2354
2355 if(env)
2356 Com_Printf("%s=%s\n", arg1, env);
2357 else
2358 Com_Printf("%s undefined\n", arg1);
2359 }
2360 }
2361
2362 /*
2363 ==================
2364 Com_ExecuteCfg
2365
2366 For controlling environment variables
2367 ==================
2368 */
2369
2370 void Com_ExecuteCfg(void)
2371 {
2372 Cbuf_ExecuteText(EXEC_NOW, "exec default.cfg\n");
2373 Cbuf_Execute(); // Always execute after exec to prevent text buffer overflowing
2374
2375 if(!Com_SafeMode())
2376 {
2377 // skip the q3config.cfg and autoexec.cfg if "safe" is on the command line
2378 Cbuf_ExecuteText(EXEC_NOW, "exec " Q3CONFIG_CFG "\n");
2379 Cbuf_Execute();
2380 Cbuf_ExecuteText(EXEC_NOW, "exec autoexec.cfg\n");
2381 Cbuf_Execute();
2382 }
2383 }
2384
2385 /*
2386 ==================
2387 Com_GameRestart
2388
2389 Change to a new mod properly with cleaning up cvars before switching.
2390 ==================
2391 */
2392
2393 void Com_GameRestart(int checksumFeed, qboolean disconnect)
2394 {
2395 // make sure no recursion can be triggered
2396 if(!com_gameRestarting && com_fullyInitialized)
2397 {
2398 com_gameRestarting = qtrue;
2399 com_gameClientRestarting = com_cl_running->integer;
2400
2401 // Kill server if we have one
2402 if(com_sv_running->integer)
2403 SV_Shutdown("Game directory changed");
2404
2405 if(com_gameClientRestarting)
2406 {
2407 if(disconnect)
2408 CL_Disconnect(qfalse);
2409
2410 CL_Shutdown("Game directory changed", disconnect, qfalse);
2411 }
2412
2413 FS_Restart(checksumFeed);
2414
2415 // Clean out any user and VM created cvars
2416 Cvar_Restart(qtrue);
2417 Com_ExecuteCfg();
2418
2419 if(disconnect)
2420 {
2421 // We don't want to change any network settings if gamedir
2422 // change was triggered by a connect to server because the
2423 // new network settings might make the connection fail.
2424 NET_Restart_f();
2425 }
2426
2427 if(com_gameClientRestarting)
2428 {
2429 CL_Init();
2430 CL_StartHunkUsers(qfalse);
2431 }
2432
2433 com_gameRestarting = qfalse;
2434 com_gameClientRestarting = qfalse;
2435 }
2436 }
2437
2438 /*
2439 ==================
2440 Com_GameRestart_f
2441
2442 Expose possibility to change current running mod to the user
2443 ==================
2444 */
2445
2446 void Com_GameRestart_f(void)
2447 {
2448 Cvar_Set("fs_game", Cmd_Argv(1));
2449
2450 Com_GameRestart(0, qtrue);
2451 }
2452
2453 #ifndef STANDALONE
2454
2455 // TTimo: centralizing the cl_cdkey stuff after I discovered a buffer overflow problem with the dedicated server version
2456 // not sure it's necessary to have different defaults for regular and dedicated, but I don't want to risk it
2457 // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=470
2458 #ifndef DEDICATED
2459 char cl_cdkey[34] = " ";
2460 #else
2461 char cl_cdkey[34] = "123456789";
2462 #endif
2463
2464 /*
2465 =================
2466 Com_ReadCDKey
2467 =================
2468 */
2469 qboolean CL_CDKeyValidate( const char *key, const char *checksum );
2470 void Com_ReadCDKey( const char *filename ) {
2471 fileHandle_t f;
2472 char buffer[33];
2473 char fbuffer[MAX_OSPATH];
2474
2475 Com_sprintf(fbuffer, sizeof(fbuffer), "%s/q3key", filename);
2476
2477 FS_BaseDir_FOpenFileRead( fbuffer, &f );
2478 if ( !f ) {
2479 Com_Memset( cl_cdkey, '\0', 17 );
2480 return;
2481 }
2482
2483 Com_Memset( buffer, 0, sizeof(buffer) );
2484
2485 FS_Read( buffer, 16, f );
2486 FS_FCloseFile( f );
2487
2488 if (CL_CDKeyValidate(buffer, NULL)) {
2489 Q_strncpyz( cl_cdkey, buffer, 17 );
2490 } else {
2491 Com_Memset( cl_cdkey, '\0', 17 );
2492 }
2493 }
2494
2495 /*
2496 =================
2497 Com_AppendCDKey
2498 =================
2499 */
2500 void Com_AppendCDKey( const char *filename ) {
2501 fileHandle_t f;
2502 char buffer[33];
2503 char fbuffer[MAX_OSPATH];
2504
2505 Com_sprintf(fbuffer, sizeof(fbuffer), "%s/q3key", filename);
2506
2507 FS_BaseDir_FOpenFileRead( fbuffer, &f );
2508 if (!f) {
2509 Com_Memset( &cl_cdkey[16], '\0', 17 );
2510 return;
2511 }
2512
2513 Com_Memset( buffer, 0, sizeof(buffer) );
2514
2515 FS_Read( buffer, 16, f );
2516 FS_FCloseFile( f );
2517
2518 if (CL_CDKeyValidate(buffer, NULL)) {
2519 strcat( &cl_cdkey[16], buffer );
2520 } else {
2521 Com_Memset( &cl_cdkey[16], '\0', 17 );
2522 }
2523 }
2524
2525 #ifndef DEDICATED
2526 /*
2527 =================
2528 Com_WriteCDKey
2529 =================
2530 */
2531 static void Com_WriteCDKey( const char *filename, const char *ikey ) {
2532 fileHandle_t f;
2533 char fbuffer[MAX_OSPATH];
2534 char key[17];
2535 #ifndef _WIN32
2536 mode_t savedumask;
2537 #endif
2538
2539
2540 Com_sprintf(fbuffer, sizeof(fbuffer), "%s/q3key", filename);
2541
2542
2543 Q_strncpyz( key, ikey, 17 );
2544
2545 if(!CL_CDKeyValidate(key, NULL) ) {
2546 return;
2547 }
2548
2549 #ifndef _WIN32
2550 savedumask = umask(0077);
2551 #endif
2552 f = FS_BaseDir_FOpenFileWrite_HomeState( fbuffer );
2553 if ( !f ) {
2554 Com_Printf ("Couldn't write CD key to %s.\n", fbuffer );
2555 goto out;
2556 }
2557
2558 FS_Write( key, 16, f );
2559
2560 FS_Printf( f, "\n// generated by " PRODUCT_NAME ", do not modify\r\n" );
2561 FS_Printf( f, "// Do not give this file to ANYONE.\r\n" );
2562 FS_Printf( f, "// id Software and Activision will NOT ask you to send this file to them.\r\n");
2563
2564 FS_FCloseFile( f );
2565 out:
2566 #ifndef _WIN32
2567 umask(savedumask);
2568 #else
2569 ;
2570 #endif
2571 }
2572 #endif
2573
2574 #endif // STANDALONE
2575
2576 static void Com_DetectAltivec(void)
2577 {
2578 // Only detect if user hasn't forcibly disabled it.
2579 if (com_altivec->integer) {
2580 static qboolean altivec = qfalse;
2581 static qboolean detected = qfalse;
2582 if (!detected) {
2583 altivec = !!( Sys_GetProcessorFeatures( ) & CF_ALTIVEC );
2584 detected = qtrue;
2585 }
2586
2587 if (!altivec) {
2588 Cvar_Set( "com_altivec", "0" ); // we don't have it! Disable support!
2589 }
2590 }
2591 }
2592
2593 /*
2594 =================
2595 Com_DetectSSE
2596 Find out whether we have SSE support for Q_ftol function
2597 =================
2598 */
2599
2600 #if id386 || idx64
2601
2602 static void Com_DetectSSE(void)
2603 {
2604 #if !idx64
2605 cpuFeatures_t feat;
2606
2607 feat = Sys_GetProcessorFeatures();
2608
2609 if(feat & CF_SSE)
2610 {
2611 if(feat & CF_SSE2)
2612 Q_SnapVector = qsnapvectorsse;
2613 else
2614 Q_SnapVector = qsnapvectorx87;
2615
2616 Q_ftol = qftolsse;
2617 #endif
2618 Q_VMftol = qvmftolsse;
2619
2620 Com_Printf("SSE instruction set enabled\n");
2621 #if !idx64
2622 }
2623 else
2624 {
2625 Q_ftol = qftolx87;
2626 Q_VMftol = qvmftolx87;
2627 Q_SnapVector = qsnapvectorx87;
2628
2629 Com_Printf("SSE instruction set not available\n");
2630 }
2631 #endif
2632 }
2633
2634 #else
2635
2636 #define Com_DetectSSE()
2637
2638 #endif
2639
2640 /*
2641 =================
2642 Com_InitRand
2643 Seed the random number generator, if possible with an OS supplied random seed.
2644 =================
2645 */
2646 static void Com_InitRand(void)
2647 {
2648 unsigned int seed;
2649
2650 if(Sys_RandomBytes((byte *) &seed, sizeof(seed)))
2651 srand(seed);
2652 else
2653 srand(time(NULL));
2654 }
2655
2656 /*
2657 =================
2658 Com_Init
2659 =================
2660 */
2661 void Com_Init( char *commandLine ) {
2662 char *s;
2663 int qport;
2664
2665 Com_Printf( "%s %s %s\n", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
2666
2667 if ( setjmp (abortframe) ) {
2668 Sys_Error ("Error during initialization");
2669 }
2670
2671 // Clear queues
2672 Com_Memset( &eventQueue[ 0 ], 0, MAX_QUEUED_EVENTS * sizeof( sysEvent_t ) );
2673
2674 // initialize the weak pseudo-random number generator for use later.
2675 Com_InitRand();
2676
2677 // do this before anything else decides to push events
2678 Com_InitPushEvent();
2679
2680 Com_InitSmallZoneMemory();
2681 Cvar_Init ();
2682
2683 // prepare enough of the subsystems to handle
2684 // cvar and command buffer management
2685 Com_ParseCommandLine( commandLine );
2686
2687 // Swap_Init ();
2688 Cbuf_Init ();
2689
2690 Com_DetectSSE();
2691
2692 // override anything from the config files with command line args
2693 Com_StartupVariable( NULL );
2694
2695 Com_InitZoneMemory();
2696 Cmd_Init ();
2697
2698 // get the developer cvar set as early as possible
2699 com_developer = Cvar_Get("developer", "0", CVAR_TEMP);
2700
2701 // done early so bind command exists
2702 CL_InitKeyCommands();
2703
2704 com_standalone = Cvar_Get("com_standalone", "0", CVAR_ROM);
2705 com_basegame = Cvar_Get("com_basegame", BASEGAME, CVAR_INIT);
2706 com_homepath = Cvar_Get("com_homepath", "", CVAR_INIT|CVAR_PROTECTED);
2707
2708 FS_InitFilesystem ();
2709
2710 Com_InitJournaling();
2711
2712 // Add some commands here already so users can use them from config files
2713 Cmd_AddCommand ("setenv", Com_Setenv_f);
2714 if (com_developer && com_developer->integer)
2715 {
2716 Cmd_AddCommand ("error", Com_Error_f);
2717 Cmd_AddCommand ("crash", Com_Crash_f);
2718 Cmd_AddCommand ("freeze", Com_Freeze_f);
2719 }
2720 Cmd_AddCommand ("quit", Com_Quit_f);
2721 Cmd_AddCommand ("changeVectors", MSG_ReportChangeVectors_f );
2722 Cmd_AddCommand ("writeconfig", Com_WriteConfig_f );
2723 Cmd_SetCommandCompletionFunc( "writeconfig", Cmd_CompleteCfgName );
2724 Cmd_AddCommand("game_restart", Com_GameRestart_f);
2725
2726 Com_ExecuteCfg();
2727
2728 // override anything from the config files with command line args
2729 Com_StartupVariable( NULL );
2730
2731 // get dedicated here for proper hunk megs initialization
2732 #ifdef DEDICATED
2733 com_dedicated = Cvar_Get ("dedicated", "1", CVAR_INIT);
2734 Cvar_CheckRange( com_dedicated, 1, 2, qtrue );
2735 #else
2736 com_dedicated = Cvar_Get ("dedicated", "0", CVAR_LATCH);
2737 Cvar_CheckRange( com_dedicated, 0, 2, qtrue );
2738 #endif
2739 // allocate the stack based hunk allocator
2740 Com_InitHunkMemory();
2741
2742 // if any archived cvars are modified after this, we will trigger a writing
2743 // of the config file
2744 cvar_modifiedFlags &= ~CVAR_ARCHIVE;
2745
2746 //
2747 // init commands and vars
2748 //
2749 com_altivec = Cvar_Get ("com_altivec", "1", CVAR_ARCHIVE);
2750 #ifdef __EMSCRIPTEN__
2751 // Under Emscripten the browser handles throttling the frame rate.
2752 // Manual framerate throttling interacts poorly with Emscripten's
2753 // browser-driven event loop. So default throttling to off.
2754 com_maxfps = Cvar_Get ("com_maxfps", "0", CVAR_ARCHIVE);
2755 #else
2756 com_maxfps = Cvar_Get ("com_maxfps", "85", CVAR_ARCHIVE);
2757 #endif
2758 com_blood = Cvar_Get ("com_blood", "1", CVAR_ARCHIVE);
2759
2760 com_logfile = Cvar_Get ("logfile", "0", CVAR_TEMP );
2761
2762 com_timescale = Cvar_Get ("timescale", "1", CVAR_CHEAT | CVAR_SYSTEMINFO );
2763 com_fixedtime = Cvar_Get ("fixedtime", "0", CVAR_CHEAT);
2764 com_showtrace = Cvar_Get ("com_showtrace", "0", CVAR_CHEAT);
2765 com_speeds = Cvar_Get ("com_speeds", "0", 0);
2766 com_timedemo = Cvar_Get ("timedemo", "0", CVAR_CHEAT);
2767 com_cameraMode = Cvar_Get ("com_cameraMode", "0", CVAR_CHEAT);
2768
2769 cl_paused = Cvar_Get ("cl_paused", "0", CVAR_ROM);
2770 sv_paused = Cvar_Get ("sv_paused", "0", CVAR_ROM);
2771 cl_packetdelay = Cvar_Get ("cl_packetdelay", "0", CVAR_CHEAT);
2772 sv_packetdelay = Cvar_Get ("sv_packetdelay", "0", CVAR_CHEAT);
2773 com_sv_running = Cvar_Get ("sv_running", "0", CVAR_ROM);
2774 com_cl_running = Cvar_Get ("cl_running", "0", CVAR_ROM);
2775 com_buildScript = Cvar_Get( "com_buildScript", "0", 0 );
2776 com_ansiColor = Cvar_Get( "com_ansiColor", "0", CVAR_ARCHIVE );
2777
2778 com_unfocused = Cvar_Get( "com_unfocused", "0", CVAR_ROM );
2779 com_maxfpsUnfocused = Cvar_Get( "com_maxfpsUnfocused", "0", CVAR_ARCHIVE );
2780 com_minimized = Cvar_Get( "com_minimized", "0", CVAR_ROM );
2781 com_maxfpsMinimized = Cvar_Get( "com_maxfpsMinimized", "0", CVAR_ARCHIVE );
2782 com_abnormalExit = Cvar_Get( "com_abnormalExit", "0", CVAR_ROM );
2783 com_busyWait = Cvar_Get("com_busyWait", "0", CVAR_ARCHIVE);
2784 Cvar_Get("com_errorMessage", "", CVAR_ROM | CVAR_NORESTART);
2785
2786 #ifdef CINEMATICS_INTRO
2787 com_introPlayed = Cvar_Get( "com_introplayed", "0", CVAR_ARCHIVE);
2788 #endif
2789
2790 s = va("%s %s %s", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
2791 com_version = Cvar_Get ("version", s, CVAR_ROM | CVAR_SERVERINFO );
2792 com_gamename = Cvar_Get("com_gamename", GAMENAME_FOR_MASTER, CVAR_SERVERINFO | CVAR_INIT);
2793 com_protocol = Cvar_Get("com_protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_INIT);
2794 #ifdef LEGACY_PROTOCOL
2795 com_legacyprotocol = Cvar_Get("com_legacyprotocol", va("%i", PROTOCOL_LEGACY_VERSION), CVAR_INIT);
2796
2797 // Keep for compatibility with old mods / mods that haven't updated yet.
2798 if(com_legacyprotocol->integer > 0)
2799 Cvar_Get("protocol", com_legacyprotocol->string, CVAR_ROM);
2800 else
2801 #endif
2802 Cvar_Get("protocol", com_protocol->string, CVAR_ROM);
2803
2804 #ifndef DEDICATED
2805 con_autochat = Cvar_Get("con_autochat", "1", CVAR_ARCHIVE);
2806 #endif
2807
2808 Sys_Init();
2809
2810 Sys_InitPIDFile( FS_GetCurrentGameDir() );
2811
2812 // Pick a random port value
2813 Com_RandomBytes( (byte*)&qport, sizeof(int) );
2814 Netchan_Init( qport & 0xffff );
2815
2816 VM_Init();
2817 SV_Init();
2818
2819 com_dedicated->modified = qfalse;
2820 #ifndef DEDICATED
2821 CL_Init();
2822 #endif
2823
2824 // set com_frameTime so that if a map is started on the
2825 // command line it will still be able to count on com_frameTime
2826 // being random enough for a serverid
2827 com_frameTime = Com_Milliseconds();
2828
2829 // add + commands from command line
2830 if ( !Com_AddStartupCommands() ) {
2831 // if the user didn't give any commands, run default action
2832 if ( !com_dedicated->integer ) {
2833 #ifdef CINEMATICS_LOGO
2834 Cbuf_AddText ("cinematic " CINEMATICS_LOGO "\n");
2835 #endif
2836 #ifdef CINEMATICS_INTRO
2837 if( !com_introPlayed->integer ) {
2838 Cvar_Set( com_introPlayed->name, "1" );
2839 Cvar_Set( "nextmap", "cinematic " CINEMATICS_INTRO );
2840 }
2841 #endif
2842 }
2843 }
2844
2845 // start in full screen ui mode
2846 Cvar_Set("r_uiFullScreen", "1");
2847
2848 CL_StartHunkUsers( qfalse );
2849
2850 // make sure single player is off by default
2851 Cvar_Set("ui_singlePlayerActive", "0");
2852
2853 com_fullyInitialized = qtrue;
2854
2855 // always set the cvar, but only print the info if it makes sense.
2856 Com_DetectAltivec();
2857 #if idppc
2858 Com_Printf ("Altivec support is %s\n", com_altivec->integer ? "enabled" : "disabled");
2859 #endif
2860
2861 com_pipefile = Cvar_Get( "com_pipefile", "", CVAR_ARCHIVE|CVAR_LATCH );
2862 if( com_pipefile->string[0] )
2863 {
2864 pipefile = FS_FCreateOpenPipeFile( com_pipefile->string );
2865 }
2866
2867 Com_Printf ("--- Common Initialization Complete ---\n");
2868 }
2869
2870 /*
2871 ===============
2872 Com_ReadFromPipe
2873
2874 Read whatever is in com_pipefile, if anything, and execute it
2875 ===============
2876 */
2877 void Com_ReadFromPipe( void )
2878 {
2879 static char buf[MAX_STRING_CHARS];
2880 static int accu = 0;
2881 int read;
2882
2883 if( !pipefile )
2884 return;
2885
2886 while( ( read = FS_Read( buf + accu, sizeof( buf ) - accu - 1, pipefile ) ) > 0 )
2887 {
2888 char *brk = NULL;
2889 int i;
2890
2891 for( i = accu; i < accu + read; ++i )
2892 {
2893 if( buf[ i ] == '\0' )
2894 buf[ i ] = '\n';
2895 if( buf[ i ] == '\n' || buf[ i ] == '\r' )
2896 brk = &buf[ i + 1 ];
2897 }
2898 buf[ accu + read ] = '\0';
2899
2900 accu += read;
2901
2902 if( brk )
2903 {
2904 char tmp = *brk;
2905 *brk = '\0';
2906 Cbuf_ExecuteText( EXEC_APPEND, buf );
2907 *brk = tmp;
2908
2909 accu -= brk - buf;
2910 memmove( buf, brk, accu + 1 );
2911 }
2912 else if( accu >= sizeof( buf ) - 1 ) // full
2913 {
2914 Cbuf_ExecuteText( EXEC_APPEND, buf );
2915 accu = 0;
2916 }
2917 }
2918 }
2919
2920
2921 //==================================================================
2922
2923 void Com_WriteConfigToFile( const char *filename ) {
2924 fileHandle_t f;
2925
2926 f = FS_FOpenFileWrite_HomeConfig( filename );
2927 if ( !f ) {
2928 Com_Printf ("Couldn't write %s.\n", filename );
2929 return;
2930 }
2931
2932 FS_Printf (f, "// generated by " PRODUCT_NAME ", do not modify\n");
2933 Key_WriteBindings (f);
2934 Cvar_WriteVariables (f);
2935 FS_FCloseFile( f );
2936 }
2937
2938
2939 /*
2940 ===============
2941 Com_WriteConfiguration
2942
2943 Writes key bindings and archived cvars to config file if modified
2944 ===============
2945 */
2946 void Com_WriteConfiguration( void ) {
2947 // if we are quiting without fully initializing, make sure
2948 // we don't write out anything
2949 if ( !com_fullyInitialized ) {
2950 return;
2951 }
2952
2953 if ( !(cvar_modifiedFlags & CVAR_ARCHIVE ) ) {
2954 return;
2955 }
2956 cvar_modifiedFlags &= ~CVAR_ARCHIVE;
2957
2958 Com_WriteConfigToFile( Q3CONFIG_CFG );
2959
2960 // not needed for dedicated or standalone
2961 #if !defined(DEDICATED) && !defined(STANDALONE)
2962 if(!com_standalone->integer)
2963 {
2964 const char *gamedir;
2965 gamedir = Cvar_VariableString( "fs_game" );
2966 if (UI_usesUniqueCDKey() && gamedir[0] != 0) {
2967 Com_WriteCDKey( gamedir, &cl_cdkey[16] );
2968 } else {
2969 Com_WriteCDKey( BASEGAME, cl_cdkey );
2970 }
2971 }
2972 #endif
2973 }
2974
2975
2976 /*
2977 ===============
2978 Com_WriteConfig_f
2979
2980 Write the config file to a specific name
2981 ===============
2982 */
2983 void Com_WriteConfig_f( void ) {
2984 char filename[MAX_QPATH];
2985
2986 if ( Cmd_Argc() != 2 ) {
2987 Com_Printf( "Usage: writeconfig <filename>\n" );
2988 return;
2989 }
2990
2991 Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
2992 COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
2993
2994 if (!COM_CompareExtension(filename, ".cfg"))
2995 {
2996 Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n");
2997 return;
2998 }
2999
3000 Com_Printf( "Writing %s.\n", filename );
3001 Com_WriteConfigToFile( filename );
3002 }
3003
3004 /*
3005 ================
3006 Com_ModifyMsec
3007 ================
3008 */
3009 int Com_ModifyMsec( int msec ) {
3010 int clampTime;
3011
3012 //
3013 // modify time for debugging values
3014 //
3015 if ( com_fixedtime->integer ) {
3016 msec = com_fixedtime->integer;
3017 } else if ( com_timescale->value ) {
3018 msec *= com_timescale->value;
3019 } else if (com_cameraMode->integer) {
3020 msec *= com_timescale->value;
3021 }
3022
3023 // don't let it scale below 1 msec
3024 if ( msec < 1 && com_timescale->value) {
3025 msec = 1;
3026 }
3027
3028 if ( com_dedicated->integer ) {
3029 // dedicated servers don't want to clamp for a much longer
3030 // period, because it would mess up all the client's views
3031 // of time.
3032 if (com_sv_running->integer && msec > 500)
3033 Com_Printf( "Hitch warning: %i msec frame time\n", msec );
3034
3035 clampTime = 5000;
3036 } else
3037 if ( !com_sv_running->integer ) {
3038 // clients of remote servers do not want to clamp time, because
3039 // it would skew their view of the server's time temporarily
3040 clampTime = 5000;
3041 } else {
3042 // for local single player gaming
3043 // we may want to clamp the time to prevent players from
3044 // flying off edges when something hitches.
3045 clampTime = 200;
3046 }
3047
3048 if ( msec > clampTime ) {
3049 msec = clampTime;
3050 }
3051
3052 return msec;
3053 }
3054
3055 /*
3056 =================
3057 Com_TimeVal
3058 =================
3059 */
3060
3061 int Com_TimeVal(int minMsec)
3062 {
3063 int timeVal;
3064
3065 timeVal = Sys_Milliseconds() - com_frameTime;
3066
3067 if(timeVal >= minMsec)
3068 timeVal = 0;
3069 else
3070 timeVal = minMsec - timeVal;
3071
3072 return timeVal;
3073 }
3074
3075 /*
3076 =================
3077 Com_Frame
3078 =================
3079 */
3080 void Com_Frame( void ) {
3081
3082 int msec, minMsec;
3083 int timeVal, timeValSV;
3084 static int lastTime = 0, bias = 0;
3085
3086 int timeBeforeFirstEvents;
3087 int timeBeforeServer;
3088 int timeBeforeEvents;
3089 int timeBeforeClient;
3090 int timeAfter;
3091
3092
3093 if ( setjmp (abortframe) ) {
3094 return; // an ERR_DROP was thrown
3095 }
3096
3097 timeBeforeFirstEvents =0;
3098 timeBeforeServer =0;
3099 timeBeforeEvents =0;
3100 timeBeforeClient = 0;
3101 timeAfter = 0;
3102
3103 // write config file if anything changed
3104 Com_WriteConfiguration();
3105
3106 //
3107 // main event loop
3108 //
3109 if ( com_speeds->integer ) {
3110 timeBeforeFirstEvents = Sys_Milliseconds ();
3111 }
3112
3113 // Figure out how much time we have
3114 if(!com_timedemo->integer)
3115 {
3116 if(com_dedicated->integer)
3117 minMsec = SV_FrameMsec();
3118 else
3119 {
3120 if(com_minimized->integer && com_maxfpsMinimized->integer > 0)
3121 minMsec = 1000 / com_maxfpsMinimized->integer;
3122 else if(com_unfocused->integer && com_maxfpsUnfocused->integer > 0)
3123 minMsec = 1000 / com_maxfpsUnfocused->integer;
3124 else if(com_maxfps->integer > 0)
3125 minMsec = 1000 / com_maxfps->integer;
3126 else
3127 minMsec = 1;
3128
3129 timeVal = com_frameTime - lastTime;
3130 bias += timeVal - minMsec;
3131
3132 if(bias > minMsec)
3133 bias = minMsec;
3134
3135 // Adjust minMsec if previous frame took too long to render so
3136 // that framerate is stable at the requested value.
3137 minMsec -= bias;
3138 }
3139 }
3140 else
3141 minMsec = 1;
3142
3143 do
3144 {
3145 if(com_sv_running->integer)
3146 {
3147 timeValSV = SV_SendQueuedPackets();
3148
3149 timeVal = Com_TimeVal(minMsec);
3150
3151 if(timeValSV < timeVal)
3152 timeVal = timeValSV;
3153 }
3154 else
3155 timeVal = Com_TimeVal(minMsec);
3156
3157 if(com_busyWait->integer || timeVal < 1)
3158 NET_Sleep(0);
3159 else
3160 NET_Sleep(timeVal - 1);
3161 } while(Com_TimeVal(minMsec));
3162
3163 IN_Frame();
3164
3165 lastTime = com_frameTime;
3166 com_frameTime = Com_EventLoop();
3167
3168 msec = com_frameTime - lastTime;
3169
3170 Cbuf_Execute ();
3171
3172 if (com_altivec->modified)
3173 {
3174 Com_DetectAltivec();
3175 com_altivec->modified = qfalse;
3176 }
3177
3178 // mess with msec if needed
3179 msec = Com_ModifyMsec(msec);
3180
3181 //
3182 // server side
3183 //
3184 if ( com_speeds->integer ) {
3185 timeBeforeServer = Sys_Milliseconds ();
3186 }
3187
3188 SV_Frame( msec );
3189
3190 // if "dedicated" has been modified, start up
3191 // or shut down the client system.
3192 // Do this after the server may have started,
3193 // but before the client tries to auto-connect
3194 if ( com_dedicated->modified ) {
3195 // get the latched value
3196 Cvar_Get( "dedicated", "0", 0 );
3197 com_dedicated->modified = qfalse;
3198 if ( !com_dedicated->integer ) {
3199 SV_Shutdown( "dedicated set to 0" );
3200 CL_FlushMemory();
3201 }
3202 }
3203
3204 #ifndef DEDICATED
3205 //
3206 // client system
3207 //
3208 //
3209 // run event loop a second time to get server to client packets
3210 // without a frame of latency
3211 //
3212 if ( com_speeds->integer ) {
3213 timeBeforeEvents = Sys_Milliseconds ();
3214 }
3215 Com_EventLoop();
3216 Cbuf_Execute ();
3217
3218
3219 //
3220 // client side
3221 //
3222 if ( com_speeds->integer ) {
3223 timeBeforeClient = Sys_Milliseconds ();
3224 }
3225
3226 CL_Frame( msec );
3227
3228 if ( com_speeds->integer ) {
3229 timeAfter = Sys_Milliseconds ();
3230 }
3231 #else
3232 if ( com_speeds->integer ) {
3233 timeAfter = Sys_Milliseconds ();
3234 timeBeforeEvents = timeAfter;
3235 timeBeforeClient = timeAfter;
3236 }
3237 #endif
3238
3239
3240 NET_FlushPacketQueue();
3241
3242 //
3243 // report timing information
3244 //
3245 if ( com_speeds->integer ) {
3246 int all, sv, ev, cl;
3247
3248 all = timeAfter - timeBeforeServer;
3249 sv = timeBeforeEvents - timeBeforeServer;
3250 ev = timeBeforeServer - timeBeforeFirstEvents + timeBeforeClient - timeBeforeEvents;
3251 cl = timeAfter - timeBeforeClient;
3252 sv -= time_game;
3253 cl -= time_frontend + time_backend;
3254
3255 Com_Printf ("frame:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i rf:%3i bk:%3i\n",
3256 com_frameNumber, all, sv, ev, cl, time_game, time_frontend, time_backend );
3257 }
3258
3259 //
3260 // trace optimization tracking
3261 //
3262 if ( com_showtrace->integer ) {
3263
3264 extern int c_traces, c_brush_traces, c_patch_traces;
3265 extern int c_pointcontents;
3266
3267 Com_Printf ("%4i traces (%ib %ip) %4i points\n", c_traces,
3268 c_brush_traces, c_patch_traces, c_pointcontents);
3269 c_traces = 0;
3270 c_brush_traces = 0;
3271 c_patch_traces = 0;
3272 c_pointcontents = 0;
3273 }
3274
3275 Com_ReadFromPipe( );
3276
3277 com_frameNumber++;
3278 }
3279
3280 /*
3281 =================
3282 Com_Shutdown
3283 =================
3284 */
3285 void Com_Shutdown (void) {
3286 if (logfile) {
3287 FS_FCloseFile (logfile);
3288 logfile = 0;
3289 }
3290
3291 if ( com_journalFile ) {
3292 FS_FCloseFile( com_journalFile );
3293 com_journalFile = 0;
3294 }
3295
3296 if( pipefile ) {
3297 FS_FCloseFile( pipefile );
3298 FS_Remove_HomeData( com_pipefile->string );
3299 }
3300
3301 }
3302
3303 /*
3304 ===========================================
3305 command line completion
3306 ===========================================
3307 */
3308
3309 /*
3310 ==================
3311 Field_Clear
3312 ==================
3313 */
3314 void Field_Clear( field_t *edit ) {
3315 memset(edit->buffer, 0, MAX_EDIT_LINE);
3316 edit->cursor = 0;
3317 edit->scroll = 0;
3318 }
3319
3320 static const char *completionString;
3321 static char shortestMatch[MAX_TOKEN_CHARS];
3322 static int matchCount;
3323 // field we are working on, passed to Field_AutoComplete(&g_consoleCommand for instance)
3324 static field_t *completionField;
3325
3326 /*
3327 ===============
3328 FindMatches
3329
3330 ===============
3331 */
3332 static void FindMatches( const char *s ) {
3333 int i;
3334
3335 if ( Q_stricmpn( s, completionString, strlen( completionString ) ) ) {
3336 return;
3337 }
3338 matchCount++;
3339 if ( matchCount == 1 ) {
3340 Q_strncpyz( shortestMatch, s, sizeof( shortestMatch ) );
3341 return;
3342 }
3343
3344 // cut shortestMatch to the amount common with s
3345 for ( i = 0 ; shortestMatch[i] ; i++ ) {
3346 if ( i >= strlen( s ) ) {
3347 shortestMatch[i] = 0;
3348 break;
3349 }
3350
3351 if ( tolower(shortestMatch[i]) != tolower(s[i]) ) {
3352 shortestMatch[i] = 0;
3353 }
3354 }
3355 }
3356
3357 /*
3358 ===============
3359 PrintMatches
3360
3361 ===============
3362 */
3363 static void PrintMatches( const char *s ) {
3364 if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
3365 Com_Printf( " %s\n", s );
3366 }
3367 }
3368
3369 /*
3370 ===============
3371 PrintCvarMatches
3372
3373 ===============
3374 */
3375 static void PrintCvarMatches( const char *s ) {
3376 char value[ TRUNCATE_LENGTH ];
3377
3378 if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
3379 Com_TruncateLongString( value, Cvar_VariableString( s ) );
3380 Com_Printf( " %s = \"%s\"\n", s, value );
3381 }
3382 }
3383
3384 /*
3385 ===============
3386 Field_FindFirstSeparator
3387 ===============
3388 */
3389 static char *Field_FindFirstSeparator( char *s )
3390 {
3391 int i;
3392
3393 for( i = 0; i < strlen( s ); i++ )
3394 {
3395 if( s[ i ] == ';' )
3396 return &s[ i ];
3397 }
3398
3399 return NULL;
3400 }
3401
3402 /*
3403 ===============
3404 Field_Complete
3405 ===============
3406 */
3407 static qboolean Field_Complete( void )
3408 {
3409 int completionOffset;
3410
3411 if( matchCount == 0 )
3412 return qtrue;
3413
3414 completionOffset = strlen( completionField->buffer ) - strlen( completionString );
3415
3416 Q_strncpyz( &completionField->buffer[ completionOffset ], shortestMatch,
3417 sizeof( completionField->buffer ) - completionOffset );
3418
3419 completionField->cursor = strlen( completionField->buffer );
3420
3421 if( matchCount == 1 )
3422 {
3423 Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
3424 completionField->cursor++;
3425 return qtrue;
3426 }
3427
3428 Com_Printf( "]%s\n", completionField->buffer );
3429
3430 return qfalse;
3431 }
3432
3433 #ifndef DEDICATED
3434 /*
3435 ===============
3436 Field_CompleteKeyname
3437 ===============
3438 */
3439 void Field_CompleteKeyname( void )
3440 {
3441 matchCount = 0;
3442 shortestMatch[ 0 ] = 0;
3443
3444 Key_KeynameCompletion( FindMatches );
3445
3446 if( !Field_Complete( ) )
3447 Key_KeynameCompletion( PrintMatches );
3448 }
3449 #endif
3450
3451 /*
3452 ===============
3453 Field_CompleteFilename
3454 ===============
3455 */
3456 void Field_CompleteFilename( const char *dir, const char *ext,
3457 char *filter, qboolean stripExt,
3458 qboolean allowNonPureFilesOnDisk )
3459 {
3460 matchCount = 0;
3461 shortestMatch[ 0 ] = 0;
3462
3463 FS_FilenameCompletion( dir, ext, filter, stripExt, FindMatches, allowNonPureFilesOnDisk );
3464
3465 if( !Field_Complete( ) )
3466 FS_FilenameCompletion( dir, ext, filter, stripExt, PrintMatches, allowNonPureFilesOnDisk );
3467 }
3468
3469 /*
3470 ===============
3471 Field_CompleteCommand
3472 ===============
3473 */
3474 void Field_CompleteCommand( char *cmd,
3475 qboolean doCommands, qboolean doCvars )
3476 {
3477 int completionArgument = 0;
3478
3479 // Skip leading whitespace and quotes
3480 cmd = Com_SkipCharset( cmd, " \"" );
3481
3482 Cmd_TokenizeStringIgnoreQuotes( cmd );
3483 completionArgument = Cmd_Argc( );
3484
3485 // If there is trailing whitespace on the cmd
3486 if( *( cmd + strlen( cmd ) - 1 ) == ' ' )
3487 {
3488 completionString = "";
3489 completionArgument++;
3490 }
3491 else
3492 completionString = Cmd_Argv( completionArgument - 1 );
3493
3494 #ifndef DEDICATED
3495 // add a '\' to the start of the buffer if it might be sent as chat otherwise
3496 if( con_autochat->integer && completionField->buffer[ 0 ] &&
3497 completionField->buffer[ 0 ] != '\\' )
3498 {
3499 if( completionField->buffer[ 0 ] != '/' )
3500 {
3501 // Buffer is full, refuse to complete
3502 if( strlen( completionField->buffer ) + 1 >=
3503 sizeof( completionField->buffer ) )
3504 return;
3505
3506 memmove( &completionField->buffer[ 1 ],
3507 &completionField->buffer[ 0 ],
3508 strlen( completionField->buffer ) + 1 );
3509 completionField->cursor++;
3510 }
3511
3512 completionField->buffer[ 0 ] = '\\';
3513 }
3514 #endif
3515
3516 if( completionArgument > 1 )
3517 {
3518 const char *baseCmd = Cmd_Argv( 0 );
3519 char *p;
3520
3521 #ifndef DEDICATED
3522 // This should always be true
3523 if( baseCmd[ 0 ] == '\\' || baseCmd[ 0 ] == '/' )
3524 baseCmd++;
3525 #endif
3526
3527 if( ( p = Field_FindFirstSeparator( cmd ) ) )
3528 Field_CompleteCommand( p + 1, qtrue, qtrue ); // Compound command
3529 else
3530 Cmd_CompleteArgument( baseCmd, cmd, completionArgument );
3531 }
3532 else
3533 {
3534 if( completionString[0] == '\\' || completionString[0] == '/' )
3535 completionString++;
3536
3537 matchCount = 0;
3538 shortestMatch[ 0 ] = 0;
3539
3540 if( strlen( completionString ) == 0 )
3541 return;
3542
3543 if( doCommands )
3544 Cmd_CommandCompletion( FindMatches );
3545
3546 if( doCvars )
3547 Cvar_CommandCompletion( FindMatches );
3548
3549 if( !Field_Complete( ) )
3550 {
3551 // run through again, printing matches
3552 if( doCommands )
3553 Cmd_CommandCompletion( PrintMatches );
3554
3555 if( doCvars )
3556 Cvar_CommandCompletion( PrintCvarMatches );
3557 }
3558 }
3559 }
3560
3561 /*
3562 ===============
3563 Field_AutoComplete
3564
3565 Perform Tab expansion
3566 ===============
3567 */
3568 void Field_AutoComplete( field_t *field )
3569 {
3570 completionField = field;
3571
3572 Field_CompleteCommand( completionField->buffer, qtrue, qtrue );
3573 }
3574
3575 /*
3576 ==================
3577 Com_RandomBytes
3578
3579 fills string array with len random bytes, preferably from the OS randomizer
3580 ==================
3581 */
3582 void Com_RandomBytes( byte *string, int len )
3583 {
3584 int i;
3585
3586 if( Sys_RandomBytes( string, len ) )
3587 return;
3588
3589 Com_Printf( "Com_RandomBytes: using weak randomization\n" );
3590 for( i = 0; i < len; i++ )
3591 string[i] = (unsigned char)( rand() % 256 );
3592 }
3593
3594
3595 /*
3596 ==================
3597 Com_IsVoipTarget
3598
3599 Returns non-zero if given clientNum is enabled in voipTargets, zero otherwise.
3600 If clientNum is negative return if any bit is set.
3601 ==================
3602 */
3603 qboolean Com_IsVoipTarget(uint8_t *voipTargets, int voipTargetsSize, int clientNum)
3604 {
3605 int index;
3606 if(clientNum < 0)
3607 {
3608 for(index = 0; index < voipTargetsSize; index++)
3609 {
3610 if(voipTargets[index])
3611 return qtrue;
3612 }
3613
3614 return qfalse;
3615 }
3616
3617 index = clientNum >> 3;
3618
3619 if(index < voipTargetsSize)
3620 return (voipTargets[index] & (1 << (clientNum & 0x07)));
3621
3622 return qfalse;
3623 }
3624
3625 /*
3626 ===============
3627 Field_CompletePlayerName
3628 ===============
3629 */
3630 static qboolean Field_CompletePlayerNameFinal( qboolean whitespace )
3631 {
3632 int completionOffset;
3633
3634 if( matchCount == 0 )
3635 return qtrue;
3636
3637 completionOffset = strlen( completionField->buffer ) - strlen( completionString );
3638
3639 Q_strncpyz( &completionField->buffer[ completionOffset ], shortestMatch,
3640 sizeof( completionField->buffer ) - completionOffset );
3641
3642 completionField->cursor = strlen( completionField->buffer );
3643
3644 if( matchCount == 1 && whitespace )
3645 {
3646 Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
3647 completionField->cursor++;
3648 return qtrue;
3649 }
3650
3651 return qfalse;
3652 }
3653
3654 static void Name_PlayerNameCompletion( const char **names, int nameCount, void(*callback)(const char *s) )
3655 {
3656 int i;
3657
3658 for( i = 0; i < nameCount; i++ ) {
3659 callback( names[ i ] );
3660 }
3661 }
3662
3663 qboolean Com_FieldStringToPlayerName( char *name, int length, const char *rawname )
3664 {
3665 char hex[5];
3666 int i;
3667 int ch;
3668
3669 if( name == NULL || rawname == NULL )
3670 return qfalse;
3671
3672 if( length <= 0 )
3673 return qtrue;
3674
3675 for( i = 0; *rawname && i + 1 <= length; rawname++, i++ ) {
3676 if( *rawname == '\\' ) {
3677 Q_strncpyz( hex, rawname + 1, sizeof(hex) );
3678 ch = Com_HexStrToInt( hex );
3679 if( ch > -1 ) {
3680 name[i] = ch;
3681 rawname += 4; //hex string length, 0xXX
3682 } else {
3683 name[i] = *rawname;
3684 }
3685 } else {
3686 name[i] = *rawname;
3687 }
3688 }
3689 name[i] = '\0';
3690
3691 return qtrue;
3692 }
3693
3694 qboolean Com_PlayerNameToFieldString( char *str, int length, const char *name )
3695 {
3696 const char *p;
3697 int i;
3698 int x1, x2;
3699
3700 if( str == NULL || name == NULL )
3701 return qfalse;
3702
3703 if( length <= 0 )
3704 return qtrue;
3705
3706 *str = '\0';
3707 p = name;
3708
3709 for( i = 0; *p != '\0'; i++, p++ )
3710 {
3711 if( i + 1 >= length )
3712 break;
3713
3714 if( *p <= ' ' )
3715 {
3716 if( i + 5 + 1 >= length )
3717 break;
3718
3719 x1 = *p >> 4;
3720 x2 = *p & 15;
3721
3722 str[i+0] = '\\';
3723 str[i+1] = '0';
3724 str[i+2] = 'x';
3725 str[i+3] = x1 > 9 ? x1 - 10 + 'a' : x1 + '0';
3726 str[i+4] = x2 > 9 ? x2 - 10 + 'a' : x2 + '0';
3727
3728 i += 4;
3729 } else {
3730 str[i] = *p;
3731 }
3732 }
3733 str[i] = '\0';
3734
3735 return qtrue;
3736 }
3737
3738 void Field_CompletePlayerName( const char **names, int nameCount )
3739 {
3740 qboolean whitespace;
3741
3742 matchCount = 0;
3743 shortestMatch[ 0 ] = 0;
3744
3745 if( nameCount <= 0 )
3746 return;
3747
3748 Name_PlayerNameCompletion( names, nameCount, FindMatches );
3749
3750 if( completionString[0] == '\0' )
3751 {
3752 Com_PlayerNameToFieldString( shortestMatch, sizeof( shortestMatch ), names[ 0 ] );
3753 }
3754
3755 //allow to tab player names
3756 //if full player name switch to next player name
3757 if( completionString[0] != '\0'
3758 && Q_stricmp( shortestMatch, completionString ) == 0
3759 && nameCount > 1 )
3760 {
3761 int i;
3762
3763 for( i = 0; i < nameCount; i++ ) {
3764 if( Q_stricmp( names[ i ], completionString ) == 0 )
3765 {
3766 i++;
3767 if( i >= nameCount )
3768 {
3769 i = 0;
3770 }
3771
3772 Com_PlayerNameToFieldString( shortestMatch, sizeof( shortestMatch ), names[ i ] );
3773 break;
3774 }
3775 }
3776 }
3777
3778 if( matchCount > 1 )
3779 {
3780 Com_Printf( "]%s\n", completionField->buffer );
3781
3782 Name_PlayerNameCompletion( names, nameCount, PrintMatches );
3783 }
3784
3785 whitespace = nameCount == 1? qtrue: qfalse;
3786 if( !Field_CompletePlayerNameFinal( whitespace ) )
3787 {
3788
3789 }
3790 }
3791
3792 int QDECL Com_strCompare( const void *a, const void *b )
3793 {
3794 const char **pa = (const char **)a;
3795 const char **pb = (const char **)b;
3796 return strcmp( *pa, *pb );
3797 }