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 Q_strlwr(buffer);
2489
2490 if (CL_CDKeyValidate(buffer, NULL)) {
2491 Q_strncpyz( cl_cdkey, buffer, 17 );
2492 } else {
2493 Com_Memset( cl_cdkey, '\0', 17 );
2494 }
2495 }
2496
2497 /*
2498 =================
2499 Com_AppendCDKey
2500 =================
2501 */
2502 void Com_AppendCDKey( const char *filename ) {
2503 fileHandle_t f;
2504 char buffer[33];
2505 char fbuffer[MAX_OSPATH];
2506
2507 Com_sprintf(fbuffer, sizeof(fbuffer), "%s/q3key", filename);
2508
2509 FS_BaseDir_FOpenFileRead( fbuffer, &f );
2510 if (!f) {
2511 Com_Memset( &cl_cdkey[16], '\0', 17 );
2512 return;
2513 }
2514
2515 Com_Memset( buffer, 0, sizeof(buffer) );
2516
2517 FS_Read( buffer, 16, f );
2518 FS_FCloseFile( f );
2519
2520 if (CL_CDKeyValidate(buffer, NULL)) {
2521 strcat( &cl_cdkey[16], buffer );
2522 } else {
2523 Com_Memset( &cl_cdkey[16], '\0', 17 );
2524 }
2525 }
2526
2527 #ifndef DEDICATED
2528 /*
2529 =================
2530 Com_WriteCDKey
2531 =================
2532 */
2533 static void Com_WriteCDKey( const char *filename, const char *ikey ) {
2534 fileHandle_t f;
2535 char fbuffer[MAX_OSPATH];
2536 char key[17];
2537 #ifndef _WIN32
2538 mode_t savedumask;
2539 #endif
2540
2541
2542 Com_sprintf(fbuffer, sizeof(fbuffer), "%s/q3key", filename);
2543
2544
2545 Q_strncpyz( key, ikey, 17 );
2546
2547 if(!CL_CDKeyValidate(key, NULL) ) {
2548 return;
2549 }
2550
2551 #ifndef _WIN32
2552 savedumask = umask(0077);
2553 #endif
2554 f = FS_BaseDir_FOpenFileWrite_HomeState( fbuffer );
2555 if ( !f ) {
2556 Com_Printf ("Couldn't write CD key to %s.\n", fbuffer );
2557 goto out;
2558 }
2559
2560 Q_strlwr(key);
2561
2562 FS_Write( key, 16, f );
2563
2564 FS_Printf( f, "\n// generated by " PRODUCT_NAME ", do not modify\r\n" );
2565 FS_Printf( f, "// Do not give this file to ANYONE.\r\n" );
2566 FS_Printf( f, "// id Software and Activision will NOT ask you to send this file to them.\r\n");
2567
2568 FS_FCloseFile( f );
2569 out:
2570 #ifndef _WIN32
2571 umask(savedumask);
2572 #else
2573 ;
2574 #endif
2575 }
2576 #endif
2577
2578 #endif // STANDALONE
2579
2580 static void Com_DetectAltivec(void)
2581 {
2582 // Only detect if user hasn't forcibly disabled it.
2583 if (com_altivec->integer) {
2584 static qboolean altivec = qfalse;
2585 static qboolean detected = qfalse;
2586 if (!detected) {
2587 altivec = !!( Sys_GetProcessorFeatures( ) & CF_ALTIVEC );
2588 detected = qtrue;
2589 }
2590
2591 if (!altivec) {
2592 Cvar_Set( "com_altivec", "0" ); // we don't have it! Disable support!
2593 }
2594 }
2595 }
2596
2597 /*
2598 =================
2599 Com_DetectSSE
2600 Find out whether we have SSE support for Q_ftol function
2601 =================
2602 */
2603
2604 #if id386 || idx64
2605
2606 static void Com_DetectSSE(void)
2607 {
2608 #if !idx64
2609 cpuFeatures_t feat;
2610
2611 feat = Sys_GetProcessorFeatures();
2612
2613 if(feat & CF_SSE)
2614 {
2615 if(feat & CF_SSE2)
2616 Q_SnapVector = qsnapvectorsse;
2617 else
2618 Q_SnapVector = qsnapvectorx87;
2619
2620 Q_ftol = qftolsse;
2621 #endif
2622 Q_VMftol = qvmftolsse;
2623
2624 Com_Printf("SSE instruction set enabled\n");
2625 #if !idx64
2626 }
2627 else
2628 {
2629 Q_ftol = qftolx87;
2630 Q_VMftol = qvmftolx87;
2631 Q_SnapVector = qsnapvectorx87;
2632
2633 Com_Printf("SSE instruction set not available\n");
2634 }
2635 #endif
2636 }
2637
2638 #else
2639
2640 #define Com_DetectSSE()
2641
2642 #endif
2643
2644 /*
2645 =================
2646 Com_InitRand
2647 Seed the random number generator, if possible with an OS supplied random seed.
2648 =================
2649 */
2650 static void Com_InitRand(void)
2651 {
2652 unsigned int seed;
2653
2654 if(Sys_RandomBytes((byte *) &seed, sizeof(seed)))
2655 srand(seed);
2656 else
2657 srand(time(NULL));
2658 }
2659
2660 /*
2661 =================
2662 Com_Init
2663 =================
2664 */
2665 void Com_Init( char *commandLine ) {
2666 char *s;
2667 int qport;
2668
2669 Com_Printf( "%s %s %s\n", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
2670
2671 if ( setjmp (abortframe) ) {
2672 Sys_Error ("Error during initialization");
2673 }
2674
2675 // Clear queues
2676 Com_Memset( &eventQueue[ 0 ], 0, MAX_QUEUED_EVENTS * sizeof( sysEvent_t ) );
2677
2678 // initialize the weak pseudo-random number generator for use later.
2679 Com_InitRand();
2680
2681 // do this before anything else decides to push events
2682 Com_InitPushEvent();
2683
2684 Com_InitSmallZoneMemory();
2685 Cvar_Init ();
2686
2687 // prepare enough of the subsystems to handle
2688 // cvar and command buffer management
2689 Com_ParseCommandLine( commandLine );
2690
2691 // Swap_Init ();
2692 Cbuf_Init ();
2693
2694 Com_DetectSSE();
2695
2696 // override anything from the config files with command line args
2697 Com_StartupVariable( NULL );
2698
2699 Com_InitZoneMemory();
2700 Cmd_Init ();
2701
2702 // get the developer cvar set as early as possible
2703 com_developer = Cvar_Get("developer", "0", CVAR_TEMP);
2704
2705 // done early so bind command exists
2706 CL_InitKeyCommands();
2707
2708 com_standalone = Cvar_Get("com_standalone", "0", CVAR_ROM);
2709 com_basegame = Cvar_Get("com_basegame", BASEGAME, CVAR_INIT);
2710 com_homepath = Cvar_Get("com_homepath", "", CVAR_INIT|CVAR_PROTECTED);
2711
2712 FS_InitFilesystem ();
2713
2714 Com_InitJournaling();
2715
2716 // Add some commands here already so users can use them from config files
2717 Cmd_AddCommand ("setenv", Com_Setenv_f);
2718 if (com_developer && com_developer->integer)
2719 {
2720 Cmd_AddCommand ("error", Com_Error_f);
2721 Cmd_AddCommand ("crash", Com_Crash_f);
2722 Cmd_AddCommand ("freeze", Com_Freeze_f);
2723 }
2724 Cmd_AddCommand ("quit", Com_Quit_f);
2725 Cmd_AddCommand ("changeVectors", MSG_ReportChangeVectors_f );
2726 Cmd_AddCommand ("writeconfig", Com_WriteConfig_f );
2727 Cmd_SetCommandCompletionFunc( "writeconfig", Cmd_CompleteCfgName );
2728 Cmd_AddCommand("game_restart", Com_GameRestart_f);
2729
2730 Com_ExecuteCfg();
2731
2732 // override anything from the config files with command line args
2733 Com_StartupVariable( NULL );
2734
2735 // get dedicated here for proper hunk megs initialization
2736 #ifdef DEDICATED
2737 com_dedicated = Cvar_Get ("dedicated", "1", CVAR_INIT);
2738 Cvar_CheckRange( com_dedicated, 1, 2, qtrue );
2739 #else
2740 com_dedicated = Cvar_Get ("dedicated", "0", CVAR_LATCH);
2741 Cvar_CheckRange( com_dedicated, 0, 2, qtrue );
2742 #endif
2743 // allocate the stack based hunk allocator
2744 Com_InitHunkMemory();
2745
2746 // if any archived cvars are modified after this, we will trigger a writing
2747 // of the config file
2748 cvar_modifiedFlags &= ~CVAR_ARCHIVE;
2749
2750 //
2751 // init commands and vars
2752 //
2753 com_altivec = Cvar_Get ("com_altivec", "1", CVAR_ARCHIVE);
2754 #ifdef __EMSCRIPTEN__
2755 // Under Emscripten the browser handles throttling the frame rate.
2756 // Manual framerate throttling interacts poorly with Emscripten's
2757 // browser-driven event loop. So default throttling to off.
2758 com_maxfps = Cvar_Get ("com_maxfps", "0", CVAR_ARCHIVE);
2759 #else
2760 com_maxfps = Cvar_Get ("com_maxfps", "85", CVAR_ARCHIVE);
2761 #endif
2762 com_blood = Cvar_Get ("com_blood", "1", CVAR_ARCHIVE);
2763
2764 com_logfile = Cvar_Get ("logfile", "0", CVAR_TEMP );
2765
2766 com_timescale = Cvar_Get ("timescale", "1", CVAR_CHEAT | CVAR_SYSTEMINFO );
2767 com_fixedtime = Cvar_Get ("fixedtime", "0", CVAR_CHEAT);
2768 com_showtrace = Cvar_Get ("com_showtrace", "0", CVAR_CHEAT);
2769 com_speeds = Cvar_Get ("com_speeds", "0", 0);
2770 com_timedemo = Cvar_Get ("timedemo", "0", CVAR_CHEAT);
2771 com_cameraMode = Cvar_Get ("com_cameraMode", "0", CVAR_CHEAT);
2772
2773 cl_paused = Cvar_Get ("cl_paused", "0", CVAR_ROM);
2774 sv_paused = Cvar_Get ("sv_paused", "0", CVAR_ROM);
2775 cl_packetdelay = Cvar_Get ("cl_packetdelay", "0", CVAR_CHEAT);
2776 sv_packetdelay = Cvar_Get ("sv_packetdelay", "0", CVAR_CHEAT);
2777 com_sv_running = Cvar_Get ("sv_running", "0", CVAR_ROM);
2778 com_cl_running = Cvar_Get ("cl_running", "0", CVAR_ROM);
2779 com_buildScript = Cvar_Get( "com_buildScript", "0", 0 );
2780 com_ansiColor = Cvar_Get( "com_ansiColor", "0", CVAR_ARCHIVE );
2781
2782 com_unfocused = Cvar_Get( "com_unfocused", "0", CVAR_ROM );
2783 com_maxfpsUnfocused = Cvar_Get( "com_maxfpsUnfocused", "0", CVAR_ARCHIVE );
2784 com_minimized = Cvar_Get( "com_minimized", "0", CVAR_ROM );
2785 com_maxfpsMinimized = Cvar_Get( "com_maxfpsMinimized", "0", CVAR_ARCHIVE );
2786 com_abnormalExit = Cvar_Get( "com_abnormalExit", "0", CVAR_ROM );
2787 com_busyWait = Cvar_Get("com_busyWait", "0", CVAR_ARCHIVE);
2788 Cvar_Get("com_errorMessage", "", CVAR_ROM | CVAR_NORESTART);
2789
2790 #ifdef CINEMATICS_INTRO
2791 com_introPlayed = Cvar_Get( "com_introplayed", "0", CVAR_ARCHIVE);
2792 #endif
2793
2794 s = va("%s %s %s", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
2795 com_version = Cvar_Get ("version", s, CVAR_ROM | CVAR_SERVERINFO );
2796 com_gamename = Cvar_Get("com_gamename", GAMENAME_FOR_MASTER, CVAR_SERVERINFO | CVAR_INIT);
2797 com_protocol = Cvar_Get("com_protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_INIT);
2798 #ifdef LEGACY_PROTOCOL
2799 com_legacyprotocol = Cvar_Get("com_legacyprotocol", va("%i", PROTOCOL_LEGACY_VERSION), CVAR_INIT);
2800
2801 // Keep for compatibility with old mods / mods that haven't updated yet.
2802 if(com_legacyprotocol->integer > 0)
2803 Cvar_Get("protocol", com_legacyprotocol->string, CVAR_ROM);
2804 else
2805 #endif
2806 Cvar_Get("protocol", com_protocol->string, CVAR_ROM);
2807
2808 #ifndef DEDICATED
2809 con_autochat = Cvar_Get("con_autochat", "1", CVAR_ARCHIVE);
2810 #endif
2811
2812 Sys_Init();
2813
2814 Sys_InitPIDFile( FS_GetCurrentGameDir() );
2815
2816 // Pick a random port value
2817 Com_RandomBytes( (byte*)&qport, sizeof(int) );
2818 Netchan_Init( qport & 0xffff );
2819
2820 VM_Init();
2821 SV_Init();
2822
2823 com_dedicated->modified = qfalse;
2824 #ifndef DEDICATED
2825 CL_Init();
2826 #endif
2827
2828 // set com_frameTime so that if a map is started on the
2829 // command line it will still be able to count on com_frameTime
2830 // being random enough for a serverid
2831 com_frameTime = Com_Milliseconds();
2832
2833 // add + commands from command line
2834 if ( !Com_AddStartupCommands() ) {
2835 // if the user didn't give any commands, run default action
2836 if ( !com_dedicated->integer ) {
2837 #ifdef CINEMATICS_LOGO
2838 Cbuf_AddText ("cinematic " CINEMATICS_LOGO "\n");
2839 #endif
2840 #ifdef CINEMATICS_INTRO
2841 if( !com_introPlayed->integer ) {
2842 Cvar_Set( com_introPlayed->name, "1" );
2843 Cvar_Set( "nextmap", "cinematic " CINEMATICS_INTRO );
2844 }
2845 #endif
2846 }
2847 }
2848
2849 // start in full screen ui mode
2850 Cvar_Set("r_uiFullScreen", "1");
2851
2852 CL_StartHunkUsers( qfalse );
2853
2854 // make sure single player is off by default
2855 Cvar_Set("ui_singlePlayerActive", "0");
2856
2857 com_fullyInitialized = qtrue;
2858
2859 // always set the cvar, but only print the info if it makes sense.
2860 Com_DetectAltivec();
2861 #if idppc
2862 Com_Printf ("Altivec support is %s\n", com_altivec->integer ? "enabled" : "disabled");
2863 #endif
2864
2865 com_pipefile = Cvar_Get( "com_pipefile", "", CVAR_ARCHIVE|CVAR_LATCH );
2866 if( com_pipefile->string[0] )
2867 {
2868 pipefile = FS_FCreateOpenPipeFile( com_pipefile->string );
2869 }
2870
2871 Com_Printf ("--- Common Initialization Complete ---\n");
2872 }
2873
2874 /*
2875 ===============
2876 Com_ReadFromPipe
2877
2878 Read whatever is in com_pipefile, if anything, and execute it
2879 ===============
2880 */
2881 void Com_ReadFromPipe( void )
2882 {
2883 static char buf[MAX_STRING_CHARS];
2884 static int accu = 0;
2885 int read;
2886
2887 if( !pipefile )
2888 return;
2889
2890 while( ( read = FS_Read( buf + accu, sizeof( buf ) - accu - 1, pipefile ) ) > 0 )
2891 {
2892 char *brk = NULL;
2893 int i;
2894
2895 for( i = accu; i < accu + read; ++i )
2896 {
2897 if( buf[ i ] == '\0' )
2898 buf[ i ] = '\n';
2899 if( buf[ i ] == '\n' || buf[ i ] == '\r' )
2900 brk = &buf[ i + 1 ];
2901 }
2902 buf[ accu + read ] = '\0';
2903
2904 accu += read;
2905
2906 if( brk )
2907 {
2908 char tmp = *brk;
2909 *brk = '\0';
2910 Cbuf_ExecuteText( EXEC_APPEND, buf );
2911 *brk = tmp;
2912
2913 accu -= brk - buf;
2914 memmove( buf, brk, accu + 1 );
2915 }
2916 else if( accu >= sizeof( buf ) - 1 ) // full
2917 {
2918 Cbuf_ExecuteText( EXEC_APPEND, buf );
2919 accu = 0;
2920 }
2921 }
2922 }
2923
2924
2925 //==================================================================
2926
2927 void Com_WriteConfigToFile( const char *filename ) {
2928 fileHandle_t f;
2929
2930 f = FS_FOpenFileWrite_HomeConfig( filename );
2931 if ( !f ) {
2932 Com_Printf ("Couldn't write %s.\n", filename );
2933 return;
2934 }
2935
2936 FS_Printf (f, "// generated by " PRODUCT_NAME ", do not modify\n");
2937 Key_WriteBindings (f);
2938 Cvar_WriteVariables (f);
2939 FS_FCloseFile( f );
2940 }
2941
2942
2943 /*
2944 ===============
2945 Com_WriteConfiguration
2946
2947 Writes key bindings and archived cvars to config file if modified
2948 ===============
2949 */
2950 void Com_WriteConfiguration( void ) {
2951 // if we are quiting without fully initializing, make sure
2952 // we don't write out anything
2953 if ( !com_fullyInitialized ) {
2954 return;
2955 }
2956
2957 if ( !(cvar_modifiedFlags & CVAR_ARCHIVE ) ) {
2958 return;
2959 }
2960 cvar_modifiedFlags &= ~CVAR_ARCHIVE;
2961
2962 Com_WriteConfigToFile( Q3CONFIG_CFG );
2963
2964 // not needed for dedicated or standalone
2965 #if !defined(DEDICATED) && !defined(STANDALONE)
2966 if(!com_standalone->integer)
2967 {
2968 const char *gamedir;
2969 gamedir = Cvar_VariableString( "fs_game" );
2970 if (UI_usesUniqueCDKey() && gamedir[0] != 0) {
2971 Com_WriteCDKey( gamedir, &cl_cdkey[16] );
2972 } else {
2973 Com_WriteCDKey( BASEGAME, cl_cdkey );
2974 }
2975 }
2976 #endif
2977 }
2978
2979
2980 /*
2981 ===============
2982 Com_WriteConfig_f
2983
2984 Write the config file to a specific name
2985 ===============
2986 */
2987 void Com_WriteConfig_f( void ) {
2988 char filename[MAX_QPATH];
2989
2990 if ( Cmd_Argc() != 2 ) {
2991 Com_Printf( "Usage: writeconfig <filename>\n" );
2992 return;
2993 }
2994
2995 Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
2996 COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
2997
2998 if (!COM_CompareExtension(filename, ".cfg"))
2999 {
3000 Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n");
3001 return;
3002 }
3003
3004 Com_Printf( "Writing %s.\n", filename );
3005 Com_WriteConfigToFile( filename );
3006 }
3007
3008 /*
3009 ================
3010 Com_ModifyMsec
3011 ================
3012 */
3013 int Com_ModifyMsec( int msec ) {
3014 int clampTime;
3015
3016 //
3017 // modify time for debugging values
3018 //
3019 if ( com_fixedtime->integer ) {
3020 msec = com_fixedtime->integer;
3021 } else if ( com_timescale->value ) {
3022 msec *= com_timescale->value;
3023 } else if (com_cameraMode->integer) {
3024 msec *= com_timescale->value;
3025 }
3026
3027 // don't let it scale below 1 msec
3028 if ( msec < 1 && com_timescale->value) {
3029 msec = 1;
3030 }
3031
3032 if ( com_dedicated->integer ) {
3033 // dedicated servers don't want to clamp for a much longer
3034 // period, because it would mess up all the client's views
3035 // of time.
3036 if (com_sv_running->integer && msec > 500)
3037 Com_Printf( "Hitch warning: %i msec frame time\n", msec );
3038
3039 clampTime = 5000;
3040 } else
3041 if ( !com_sv_running->integer ) {
3042 // clients of remote servers do not want to clamp time, because
3043 // it would skew their view of the server's time temporarily
3044 clampTime = 5000;
3045 } else {
3046 // for local single player gaming
3047 // we may want to clamp the time to prevent players from
3048 // flying off edges when something hitches.
3049 clampTime = 200;
3050 }
3051
3052 if ( msec > clampTime ) {
3053 msec = clampTime;
3054 }
3055
3056 return msec;
3057 }
3058
3059 /*
3060 =================
3061 Com_TimeVal
3062 =================
3063 */
3064
3065 int Com_TimeVal(int minMsec)
3066 {
3067 int timeVal;
3068
3069 timeVal = Sys_Milliseconds() - com_frameTime;
3070
3071 if(timeVal >= minMsec)
3072 timeVal = 0;
3073 else
3074 timeVal = minMsec - timeVal;
3075
3076 return timeVal;
3077 }
3078
3079 /*
3080 =================
3081 Com_Frame
3082 =================
3083 */
3084 void Com_Frame( void ) {
3085
3086 int msec, minMsec;
3087 int timeVal, timeValSV;
3088 static int lastTime = 0, bias = 0;
3089
3090 int timeBeforeFirstEvents;
3091 int timeBeforeServer;
3092 int timeBeforeEvents;
3093 int timeBeforeClient;
3094 int timeAfter;
3095
3096
3097 if ( setjmp (abortframe) ) {
3098 return; // an ERR_DROP was thrown
3099 }
3100
3101 timeBeforeFirstEvents =0;
3102 timeBeforeServer =0;
3103 timeBeforeEvents =0;
3104 timeBeforeClient = 0;
3105 timeAfter = 0;
3106
3107 // write config file if anything changed
3108 Com_WriteConfiguration();
3109
3110 //
3111 // main event loop
3112 //
3113 if ( com_speeds->integer ) {
3114 timeBeforeFirstEvents = Sys_Milliseconds ();
3115 }
3116
3117 // Figure out how much time we have
3118 if(!com_timedemo->integer)
3119 {
3120 if(com_dedicated->integer)
3121 minMsec = SV_FrameMsec();
3122 else
3123 {
3124 if(com_minimized->integer && com_maxfpsMinimized->integer > 0)
3125 minMsec = 1000 / com_maxfpsMinimized->integer;
3126 else if(com_unfocused->integer && com_maxfpsUnfocused->integer > 0)
3127 minMsec = 1000 / com_maxfpsUnfocused->integer;
3128 else if(com_maxfps->integer > 0)
3129 minMsec = 1000 / com_maxfps->integer;
3130 else
3131 minMsec = 1;
3132
3133 timeVal = com_frameTime - lastTime;
3134 bias += timeVal - minMsec;
3135
3136 if(bias > minMsec)
3137 bias = minMsec;
3138
3139 // Adjust minMsec if previous frame took too long to render so
3140 // that framerate is stable at the requested value.
3141 minMsec -= bias;
3142 }
3143 }
3144 else
3145 minMsec = 1;
3146
3147 do
3148 {
3149 if(com_sv_running->integer)
3150 {
3151 timeValSV = SV_SendQueuedPackets();
3152
3153 timeVal = Com_TimeVal(minMsec);
3154
3155 if(timeValSV < timeVal)
3156 timeVal = timeValSV;
3157 }
3158 else
3159 timeVal = Com_TimeVal(minMsec);
3160
3161 if(com_busyWait->integer || timeVal < 1)
3162 NET_Sleep(0);
3163 else
3164 NET_Sleep(timeVal - 1);
3165 } while(Com_TimeVal(minMsec));
3166
3167 IN_Frame();
3168
3169 lastTime = com_frameTime;
3170 com_frameTime = Com_EventLoop();
3171
3172 msec = com_frameTime - lastTime;
3173
3174 Cbuf_Execute ();
3175
3176 if (com_altivec->modified)
3177 {
3178 Com_DetectAltivec();
3179 com_altivec->modified = qfalse;
3180 }
3181
3182 // mess with msec if needed
3183 msec = Com_ModifyMsec(msec);
3184
3185 //
3186 // server side
3187 //
3188 if ( com_speeds->integer ) {
3189 timeBeforeServer = Sys_Milliseconds ();
3190 }
3191
3192 SV_Frame( msec );
3193
3194 // if "dedicated" has been modified, start up
3195 // or shut down the client system.
3196 // Do this after the server may have started,
3197 // but before the client tries to auto-connect
3198 if ( com_dedicated->modified ) {
3199 // get the latched value
3200 Cvar_Get( "dedicated", "0", 0 );
3201 com_dedicated->modified = qfalse;
3202 if ( !com_dedicated->integer ) {
3203 SV_Shutdown( "dedicated set to 0" );
3204 CL_FlushMemory();
3205 }
3206 }
3207
3208 #ifndef DEDICATED
3209 //
3210 // client system
3211 //
3212 //
3213 // run event loop a second time to get server to client packets
3214 // without a frame of latency
3215 //
3216 if ( com_speeds->integer ) {
3217 timeBeforeEvents = Sys_Milliseconds ();
3218 }
3219 Com_EventLoop();
3220 Cbuf_Execute ();
3221
3222
3223 //
3224 // client side
3225 //
3226 if ( com_speeds->integer ) {
3227 timeBeforeClient = Sys_Milliseconds ();
3228 }
3229
3230 CL_Frame( msec );
3231
3232 if ( com_speeds->integer ) {
3233 timeAfter = Sys_Milliseconds ();
3234 }
3235 #else
3236 if ( com_speeds->integer ) {
3237 timeAfter = Sys_Milliseconds ();
3238 timeBeforeEvents = timeAfter;
3239 timeBeforeClient = timeAfter;
3240 }
3241 #endif
3242
3243
3244 NET_FlushPacketQueue();
3245
3246 //
3247 // report timing information
3248 //
3249 if ( com_speeds->integer ) {
3250 int all, sv, ev, cl;
3251
3252 all = timeAfter - timeBeforeServer;
3253 sv = timeBeforeEvents - timeBeforeServer;
3254 ev = timeBeforeServer - timeBeforeFirstEvents + timeBeforeClient - timeBeforeEvents;
3255 cl = timeAfter - timeBeforeClient;
3256 sv -= time_game;
3257 cl -= time_frontend + time_backend;
3258
3259 Com_Printf ("frame:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i rf:%3i bk:%3i\n",
3260 com_frameNumber, all, sv, ev, cl, time_game, time_frontend, time_backend );
3261 }
3262
3263 //
3264 // trace optimization tracking
3265 //
3266 if ( com_showtrace->integer ) {
3267
3268 extern int c_traces, c_brush_traces, c_patch_traces;
3269 extern int c_pointcontents;
3270
3271 Com_Printf ("%4i traces (%ib %ip) %4i points\n", c_traces,
3272 c_brush_traces, c_patch_traces, c_pointcontents);
3273 c_traces = 0;
3274 c_brush_traces = 0;
3275 c_patch_traces = 0;
3276 c_pointcontents = 0;
3277 }
3278
3279 Com_ReadFromPipe( );
3280
3281 com_frameNumber++;
3282 }
3283
3284 /*
3285 =================
3286 Com_Shutdown
3287 =================
3288 */
3289 void Com_Shutdown (void) {
3290 if (logfile) {
3291 FS_FCloseFile (logfile);
3292 logfile = 0;
3293 }
3294
3295 if ( com_journalFile ) {
3296 FS_FCloseFile( com_journalFile );
3297 com_journalFile = 0;
3298 }
3299
3300 if( pipefile ) {
3301 FS_FCloseFile( pipefile );
3302 FS_Remove_HomeData( com_pipefile->string );
3303 }
3304
3305 }
3306
3307 /*
3308 ===========================================
3309 command line completion
3310 ===========================================
3311 */
3312
3313 /*
3314 ==================
3315 Field_Clear
3316 ==================
3317 */
3318 void Field_Clear( field_t *edit ) {
3319 memset(edit->buffer, 0, MAX_EDIT_LINE);
3320 edit->cursor = 0;
3321 edit->scroll = 0;
3322 }
3323
3324 static const char *completionString;
3325 static char shortestMatch[MAX_TOKEN_CHARS];
3326 static int matchCount;
3327 // field we are working on, passed to Field_AutoComplete(&g_consoleCommand for instance)
3328 static field_t *completionField;
3329
3330 /*
3331 ===============
3332 FindMatches
3333
3334 ===============
3335 */
3336 static void FindMatches( const char *s ) {
3337 int i;
3338
3339 if ( Q_stricmpn( s, completionString, strlen( completionString ) ) ) {
3340 return;
3341 }
3342 matchCount++;
3343 if ( matchCount == 1 ) {
3344 Q_strncpyz( shortestMatch, s, sizeof( shortestMatch ) );
3345 return;
3346 }
3347
3348 // cut shortestMatch to the amount common with s
3349 for ( i = 0 ; shortestMatch[i] ; i++ ) {
3350 if ( i >= strlen( s ) ) {
3351 shortestMatch[i] = 0;
3352 break;
3353 }
3354
3355 if ( tolower(shortestMatch[i]) != tolower(s[i]) ) {
3356 shortestMatch[i] = 0;
3357 }
3358 }
3359 }
3360
3361 /*
3362 ===============
3363 PrintMatches
3364
3365 ===============
3366 */
3367 static void PrintMatches( const char *s ) {
3368 if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
3369 Com_Printf( " %s\n", s );
3370 }
3371 }
3372
3373 /*
3374 ===============
3375 PrintCvarMatches
3376
3377 ===============
3378 */
3379 static void PrintCvarMatches( const char *s ) {
3380 char value[ TRUNCATE_LENGTH ];
3381
3382 if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
3383 Com_TruncateLongString( value, Cvar_VariableString( s ) );
3384 Com_Printf( " %s = \"%s\"\n", s, value );
3385 }
3386 }
3387
3388 /*
3389 ===============
3390 Field_FindFirstSeparator
3391 ===============
3392 */
3393 static char *Field_FindFirstSeparator( char *s )
3394 {
3395 int i;
3396
3397 for( i = 0; i < strlen( s ); i++ )
3398 {
3399 if( s[ i ] == ';' )
3400 return &s[ i ];
3401 }
3402
3403 return NULL;
3404 }
3405
3406 /*
3407 ===============
3408 Field_Complete
3409 ===============
3410 */
3411 static qboolean Field_Complete( void )
3412 {
3413 int completionOffset;
3414
3415 if( matchCount == 0 )
3416 return qtrue;
3417
3418 completionOffset = strlen( completionField->buffer ) - strlen( completionString );
3419
3420 Q_strncpyz( &completionField->buffer[ completionOffset ], shortestMatch,
3421 sizeof( completionField->buffer ) - completionOffset );
3422
3423 completionField->cursor = strlen( completionField->buffer );
3424
3425 if( matchCount == 1 )
3426 {
3427 Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
3428 completionField->cursor++;
3429 return qtrue;
3430 }
3431
3432 Com_Printf( "]%s\n", completionField->buffer );
3433
3434 return qfalse;
3435 }
3436
3437 #ifndef DEDICATED
3438 /*
3439 ===============
3440 Field_CompleteKeyname
3441 ===============
3442 */
3443 void Field_CompleteKeyname( void )
3444 {
3445 matchCount = 0;
3446 shortestMatch[ 0 ] = 0;
3447
3448 Key_KeynameCompletion( FindMatches );
3449
3450 if( !Field_Complete( ) )
3451 Key_KeynameCompletion( PrintMatches );
3452 }
3453 #endif
3454
3455 /*
3456 ===============
3457 Field_CompleteFilename
3458 ===============
3459 */
3460 void Field_CompleteFilename( const char *dir, const char *ext,
3461 char *filter, qboolean stripExt,
3462 qboolean allowNonPureFilesOnDisk )
3463 {
3464 matchCount = 0;
3465 shortestMatch[ 0 ] = 0;
3466
3467 FS_FilenameCompletion( dir, ext, filter, stripExt, FindMatches, allowNonPureFilesOnDisk );
3468
3469 if( !Field_Complete( ) )
3470 FS_FilenameCompletion( dir, ext, filter, stripExt, PrintMatches, allowNonPureFilesOnDisk );
3471 }
3472
3473 /*
3474 ===============
3475 Field_CompleteCommand
3476 ===============
3477 */
3478 void Field_CompleteCommand( char *cmd,
3479 qboolean doCommands, qboolean doCvars )
3480 {
3481 int completionArgument = 0;
3482
3483 // Skip leading whitespace and quotes
3484 cmd = Com_SkipCharset( cmd, " \"" );
3485
3486 Cmd_TokenizeStringIgnoreQuotes( cmd );
3487 completionArgument = Cmd_Argc( );
3488
3489 // If there is trailing whitespace on the cmd
3490 if( *( cmd + strlen( cmd ) - 1 ) == ' ' )
3491 {
3492 completionString = "";
3493 completionArgument++;
3494 }
3495 else
3496 completionString = Cmd_Argv( completionArgument - 1 );
3497
3498 #ifndef DEDICATED
3499 // add a '\' to the start of the buffer if it might be sent as chat otherwise
3500 if( con_autochat->integer && completionField->buffer[ 0 ] &&
3501 completionField->buffer[ 0 ] != '\\' )
3502 {
3503 if( completionField->buffer[ 0 ] != '/' )
3504 {
3505 // Buffer is full, refuse to complete
3506 if( strlen( completionField->buffer ) + 1 >=
3507 sizeof( completionField->buffer ) )
3508 return;
3509
3510 memmove( &completionField->buffer[ 1 ],
3511 &completionField->buffer[ 0 ],
3512 strlen( completionField->buffer ) + 1 );
3513 completionField->cursor++;
3514 }
3515
3516 completionField->buffer[ 0 ] = '\\';
3517 }
3518 #endif
3519
3520 if( completionArgument > 1 )
3521 {
3522 const char *baseCmd = Cmd_Argv( 0 );
3523 char *p;
3524
3525 #ifndef DEDICATED
3526 // This should always be true
3527 if( baseCmd[ 0 ] == '\\' || baseCmd[ 0 ] == '/' )
3528 baseCmd++;
3529 #endif
3530
3531 if( ( p = Field_FindFirstSeparator( cmd ) ) )
3532 Field_CompleteCommand( p + 1, qtrue, qtrue ); // Compound command
3533 else
3534 Cmd_CompleteArgument( baseCmd, cmd, completionArgument );
3535 }
3536 else
3537 {
3538 if( completionString[0] == '\\' || completionString[0] == '/' )
3539 completionString++;
3540
3541 matchCount = 0;
3542 shortestMatch[ 0 ] = 0;
3543
3544 if( strlen( completionString ) == 0 )
3545 return;
3546
3547 if( doCommands )
3548 Cmd_CommandCompletion( FindMatches );
3549
3550 if( doCvars )
3551 Cvar_CommandCompletion( FindMatches );
3552
3553 if( !Field_Complete( ) )
3554 {
3555 // run through again, printing matches
3556 if( doCommands )
3557 Cmd_CommandCompletion( PrintMatches );
3558
3559 if( doCvars )
3560 Cvar_CommandCompletion( PrintCvarMatches );
3561 }
3562 }
3563 }
3564
3565 /*
3566 ===============
3567 Field_AutoComplete
3568
3569 Perform Tab expansion
3570 ===============
3571 */
3572 void Field_AutoComplete( field_t *field )
3573 {
3574 completionField = field;
3575
3576 Field_CompleteCommand( completionField->buffer, qtrue, qtrue );
3577 }
3578
3579 /*
3580 ==================
3581 Com_RandomBytes
3582
3583 fills string array with len random bytes, preferably from the OS randomizer
3584 ==================
3585 */
3586 void Com_RandomBytes( byte *string, int len )
3587 {
3588 int i;
3589
3590 if( Sys_RandomBytes( string, len ) )
3591 return;
3592
3593 Com_Printf( "Com_RandomBytes: using weak randomization\n" );
3594 for( i = 0; i < len; i++ )
3595 string[i] = (unsigned char)( rand() % 256 );
3596 }
3597
3598
3599 /*
3600 ==================
3601 Com_IsVoipTarget
3602
3603 Returns non-zero if given clientNum is enabled in voipTargets, zero otherwise.
3604 If clientNum is negative return if any bit is set.
3605 ==================
3606 */
3607 qboolean Com_IsVoipTarget(uint8_t *voipTargets, int voipTargetsSize, int clientNum)
3608 {
3609 int index;
3610 if(clientNum < 0)
3611 {
3612 for(index = 0; index < voipTargetsSize; index++)
3613 {
3614 if(voipTargets[index])
3615 return qtrue;
3616 }
3617
3618 return qfalse;
3619 }
3620
3621 index = clientNum >> 3;
3622
3623 if(index < voipTargetsSize)
3624 return (voipTargets[index] & (1 << (clientNum & 0x07)));
3625
3626 return qfalse;
3627 }
3628
3629 /*
3630 ===============
3631 Field_CompletePlayerName
3632 ===============
3633 */
3634 static qboolean Field_CompletePlayerNameFinal( qboolean whitespace )
3635 {
3636 int completionOffset;
3637
3638 if( matchCount == 0 )
3639 return qtrue;
3640
3641 completionOffset = strlen( completionField->buffer ) - strlen( completionString );
3642
3643 Q_strncpyz( &completionField->buffer[ completionOffset ], shortestMatch,
3644 sizeof( completionField->buffer ) - completionOffset );
3645
3646 completionField->cursor = strlen( completionField->buffer );
3647
3648 if( matchCount == 1 && whitespace )
3649 {
3650 Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
3651 completionField->cursor++;
3652 return qtrue;
3653 }
3654
3655 return qfalse;
3656 }
3657
3658 static void Name_PlayerNameCompletion( const char **names, int nameCount, void(*callback)(const char *s) )
3659 {
3660 int i;
3661
3662 for( i = 0; i < nameCount; i++ ) {
3663 callback( names[ i ] );
3664 }
3665 }
3666
3667 qboolean Com_FieldStringToPlayerName( char *name, int length, const char *rawname )
3668 {
3669 char hex[5];
3670 int i;
3671 int ch;
3672
3673 if( name == NULL || rawname == NULL )
3674 return qfalse;
3675
3676 if( length <= 0 )
3677 return qtrue;
3678
3679 for( i = 0; *rawname && i + 1 <= length; rawname++, i++ ) {
3680 if( *rawname == '\\' ) {
3681 Q_strncpyz( hex, rawname + 1, sizeof(hex) );
3682 ch = Com_HexStrToInt( hex );
3683 if( ch > -1 ) {
3684 name[i] = ch;
3685 rawname += 4; //hex string length, 0xXX
3686 } else {
3687 name[i] = *rawname;
3688 }
3689 } else {
3690 name[i] = *rawname;
3691 }
3692 }
3693 name[i] = '\0';
3694
3695 return qtrue;
3696 }
3697
3698 qboolean Com_PlayerNameToFieldString( char *str, int length, const char *name )
3699 {
3700 const char *p;
3701 int i;
3702 int x1, x2;
3703
3704 if( str == NULL || name == NULL )
3705 return qfalse;
3706
3707 if( length <= 0 )
3708 return qtrue;
3709
3710 *str = '\0';
3711 p = name;
3712
3713 for( i = 0; *p != '\0'; i++, p++ )
3714 {
3715 if( i + 1 >= length )
3716 break;
3717
3718 if( *p <= ' ' )
3719 {
3720 if( i + 5 + 1 >= length )
3721 break;
3722
3723 x1 = *p >> 4;
3724 x2 = *p & 15;
3725
3726 str[i+0] = '\\';
3727 str[i+1] = '0';
3728 str[i+2] = 'x';
3729 str[i+3] = x1 > 9 ? x1 - 10 + 'a' : x1 + '0';
3730 str[i+4] = x2 > 9 ? x2 - 10 + 'a' : x2 + '0';
3731
3732 i += 4;
3733 } else {
3734 str[i] = *p;
3735 }
3736 }
3737 str[i] = '\0';
3738
3739 return qtrue;
3740 }
3741
3742 void Field_CompletePlayerName( const char **names, int nameCount )
3743 {
3744 qboolean whitespace;
3745
3746 matchCount = 0;
3747 shortestMatch[ 0 ] = 0;
3748
3749 if( nameCount <= 0 )
3750 return;
3751
3752 Name_PlayerNameCompletion( names, nameCount, FindMatches );
3753
3754 if( completionString[0] == '\0' )
3755 {
3756 Com_PlayerNameToFieldString( shortestMatch, sizeof( shortestMatch ), names[ 0 ] );
3757 }
3758
3759 //allow to tab player names
3760 //if full player name switch to next player name
3761 if( completionString[0] != '\0'
3762 && Q_stricmp( shortestMatch, completionString ) == 0
3763 && nameCount > 1 )
3764 {
3765 int i;
3766
3767 for( i = 0; i < nameCount; i++ ) {
3768 if( Q_stricmp( names[ i ], completionString ) == 0 )
3769 {
3770 i++;
3771 if( i >= nameCount )
3772 {
3773 i = 0;
3774 }
3775
3776 Com_PlayerNameToFieldString( shortestMatch, sizeof( shortestMatch ), names[ i ] );
3777 break;
3778 }
3779 }
3780 }
3781
3782 if( matchCount > 1 )
3783 {
3784 Com_Printf( "]%s\n", completionField->buffer );
3785
3786 Name_PlayerNameCompletion( names, nameCount, PrintMatches );
3787 }
3788
3789 whitespace = nameCount == 1? qtrue: qfalse;
3790 if( !Field_CompletePlayerNameFinal( whitespace ) )
3791 {
3792
3793 }
3794 }
3795
3796 int QDECL Com_strCompare( const void *a, const void *b )
3797 {
3798 const char **pa = (const char **)a;
3799 const char **pb = (const char **)b;
3800 return strcmp( *pa, *pb );
3801 }