]> git.xonotic.org Git - xonotic/darkplaces.git/blob - cmd.c
added sv_threaded cvar, the server can now be moved to another thread
[xonotic/darkplaces.git] / cmd.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // cmd.c -- Quake script command processing module
21
22 #include "quakedef.h"
23 #include "thread.h"
24
25 typedef struct cmdalias_s
26 {
27         struct cmdalias_s *next;
28         char name[MAX_ALIAS_NAME];
29         char *value;
30         qboolean initstate; // indicates this command existed at init
31         char *initialvalue; // backup copy of value at init
32 } cmdalias_t;
33
34 static cmdalias_t *cmd_alias;
35
36 static qboolean cmd_wait;
37
38 static mempool_t *cmd_mempool;
39
40 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
41 static int cmd_tokenizebufferpos = 0;
42
43 //=============================================================================
44
45 /*
46 ============
47 Cmd_Wait_f
48
49 Causes execution of the remainder of the command buffer to be delayed until
50 next frame.  This allows commands like:
51 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
52 ============
53 */
54 static void Cmd_Wait_f (void)
55 {
56         cmd_wait = true;
57 }
58
59 typedef struct cmddeferred_s
60 {
61         struct cmddeferred_s *next;
62         char *value;
63         double time;
64 } cmddeferred_t;
65
66 static cmddeferred_t *cmd_deferred_list = NULL;
67
68 /*
69 ============
70 Cmd_Defer_f
71
72 Cause a command to be executed after a delay.
73 ============
74 */
75 static void Cmd_Defer_f (void)
76 {
77         if(Cmd_Argc() == 1)
78         {
79                 double time = Sys_DoubleTime();
80                 cmddeferred_t *next = cmd_deferred_list;
81                 if(!next)
82                         Con_Printf("No commands are pending.\n");
83                 while(next)
84                 {
85                         Con_Printf("-> In %9.2f: %s\n", next->time-time, next->value);
86                         next = next->next;
87                 }
88         } else if(Cmd_Argc() == 2 && !strcasecmp("clear", Cmd_Argv(1)))
89         {
90                 while(cmd_deferred_list)
91                 {
92                         cmddeferred_t *cmd = cmd_deferred_list;
93                         cmd_deferred_list = cmd->next;
94                         Mem_Free(cmd->value);
95                         Mem_Free(cmd);
96                 }
97         } else if(Cmd_Argc() == 3)
98         {
99                 const char *value = Cmd_Argv(2);
100                 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
101                 size_t len = strlen(value);
102
103                 defcmd->time = Sys_DoubleTime() + atof(Cmd_Argv(1));
104                 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
105                 memcpy(defcmd->value, value, len+1);
106                 defcmd->next = NULL;
107
108                 if(cmd_deferred_list)
109                 {
110                         cmddeferred_t *next = cmd_deferred_list;
111                         while(next->next)
112                                 next = next->next;
113                         next->next = defcmd;
114                 } else
115                         cmd_deferred_list = defcmd;
116                 /* Stupid me... this changes the order... so commands with the same delay go blub :S
117                   defcmd->next = cmd_deferred_list;
118                   cmd_deferred_list = defcmd;*/
119         } else {
120                 Con_Printf("usage: defer <seconds> <command>\n"
121                            "       defer clear\n");
122                 return;
123         }
124 }
125
126 /*
127 ============
128 Cmd_Centerprint_f
129
130 Print something to the center of the screen using SCR_Centerprint
131 ============
132 */
133 static void Cmd_Centerprint_f (void)
134 {
135         char msg[MAX_INPUTLINE];
136         unsigned int i, c, p;
137         c = Cmd_Argc();
138         if(c >= 2)
139         {
140                 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
141                 for(i = 2; i < c; ++i)
142                 {
143                         strlcat(msg, " ", sizeof(msg));
144                         strlcat(msg, Cmd_Argv(i), sizeof(msg));
145                 }
146                 c = strlen(msg);
147                 for(p = 0, i = 0; i < c; ++i)
148                 {
149                         if(msg[i] == '\\')
150                         {
151                                 if(msg[i+1] == 'n')
152                                         msg[p++] = '\n';
153                                 else if(msg[i+1] == '\\')
154                                         msg[p++] = '\\';
155                                 else {
156                                         msg[p++] = '\\';
157                                         msg[p++] = msg[i+1];
158                                 }
159                                 ++i;
160                         } else {
161                                 msg[p++] = msg[i];
162                         }
163                 }
164                 msg[p] = '\0';
165                 SCR_CenterPrint(msg);
166         }
167 }
168
169 /*
170 =============================================================================
171
172                                                 COMMAND BUFFER
173
174 =============================================================================
175 */
176
177 static sizebuf_t        cmd_text;
178 static unsigned char            cmd_text_buf[CMDBUFSIZE];
179 void *cmd_text_mutex = NULL;
180
181 static void Cbuf_LockThreadMutex(void)
182 {
183         if (cmd_text_mutex)
184                 Thread_LockMutex(cmd_text_mutex);
185 }
186
187 static void Cbuf_UnlockThreadMutex(void)
188 {
189         if (cmd_text_mutex)
190                 Thread_UnlockMutex(cmd_text_mutex);
191 }
192
193 /*
194 ============
195 Cbuf_AddText
196
197 Adds command text at the end of the buffer
198 ============
199 */
200 void Cbuf_AddText (const char *text)
201 {
202         int             l;
203
204         l = (int)strlen(text);
205
206         Cbuf_LockThreadMutex();
207         if (cmd_text.cursize + l >= cmd_text.maxsize)
208                 Con_Print("Cbuf_AddText: overflow\n");
209         else
210                 SZ_Write(&cmd_text, (const unsigned char *)text, (int)strlen (text));
211         Cbuf_UnlockThreadMutex();
212 }
213
214
215 /*
216 ============
217 Cbuf_InsertText
218
219 Adds command text immediately after the current command
220 Adds a \n to the text
221 FIXME: actually change the command buffer to do less copying
222 ============
223 */
224 void Cbuf_InsertText (const char *text)
225 {
226         char    *temp;
227         int             templen;
228
229         Cbuf_LockThreadMutex();
230
231         // copy off any commands still remaining in the exec buffer
232         templen = cmd_text.cursize;
233         if (templen)
234         {
235                 temp = (char *)Mem_Alloc (tempmempool, templen);
236                 memcpy (temp, cmd_text.data, templen);
237                 SZ_Clear (&cmd_text);
238         }
239         else
240                 temp = NULL;
241
242         // add the entire text of the file
243         Cbuf_AddText (text);
244
245         // add the copied off data
246         if (temp != NULL)
247         {
248                 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
249                 Mem_Free (temp);
250         }
251
252         Cbuf_UnlockThreadMutex();
253 }
254
255 /*
256 ============
257 Cbuf_Execute_Deferred --blub
258 ============
259 */
260 void Cbuf_Execute_Deferred (void)
261 {
262         cmddeferred_t *cmd, *prev;
263         double time = Sys_DoubleTime();
264         prev = NULL;
265         cmd = cmd_deferred_list;
266         while(cmd)
267         {
268                 if(cmd->time <= time)
269                 {
270                         Cbuf_AddText(cmd->value);
271                         Cbuf_AddText(";\n");
272                         Mem_Free(cmd->value);
273
274                         if(prev) {
275                                 prev->next = cmd->next;
276                                 Mem_Free(cmd);
277                                 cmd = prev->next;
278                         } else {
279                                 cmd_deferred_list = cmd->next;
280                                 Mem_Free(cmd);
281                                 cmd = cmd_deferred_list;
282                         }
283                         continue;
284                 }
285                 prev = cmd;
286                 cmd = cmd->next;
287         }
288 }
289
290 /*
291 ============
292 Cbuf_Execute
293 ============
294 */
295 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
296 void Cbuf_Execute (void)
297 {
298         int i;
299         char *text;
300         char line[MAX_INPUTLINE];
301         char preprocessed[MAX_INPUTLINE];
302         char *firstchar;
303         qboolean quotes;
304         char *comment;
305
306         Cbuf_LockThreadMutex();
307         SV_LockThreadMutex();
308
309         // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
310         cmd_tokenizebufferpos = 0;
311
312         Cbuf_Execute_Deferred();
313         while (cmd_text.cursize)
314         {
315 // find a \n or ; line break
316                 text = (char *)cmd_text.data;
317
318                 quotes = false;
319                 comment = NULL;
320                 for (i=0 ; i < cmd_text.cursize ; i++)
321                 {
322                         if(!comment)
323                         {
324                                 if (text[i] == '"')
325                                         quotes = !quotes;
326
327                                 if(quotes)
328                                 {
329                                         // make sure i doesn't get > cursize which causes a negative
330                                         // size in memmove, which is fatal --blub
331                                         if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
332                                                 i++;
333                                 }
334                                 else
335                                 {
336                                         if(text[i] == '/' && text[i + 1] == '/' && (i == 0 || ISWHITESPACE(text[i-1])))
337                                                 comment = &text[i];
338                                         if(text[i] == ';')
339                                                 break;  // don't break if inside a quoted string or comment
340                                 }
341                         }
342
343                         if (text[i] == '\r' || text[i] == '\n')
344                                 break;
345                 }
346
347                 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
348                 if(i >= MAX_INPUTLINE)
349                 {
350                         Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
351                         line[0] = 0;
352                 }
353                 else
354                 {
355                         memcpy (line, text, comment ? (comment - text) : i);
356                         line[comment ? (comment - text) : i] = 0;
357                 }
358
359 // delete the text from the command buffer and move remaining commands down
360 // this is necessary because commands (exec, alias) can insert data at the
361 // beginning of the text buffer
362
363                 if (i == cmd_text.cursize)
364                         cmd_text.cursize = 0;
365                 else
366                 {
367                         i++;
368                         cmd_text.cursize -= i;
369                         memmove (cmd_text.data, text+i, cmd_text.cursize);
370                 }
371
372 // execute the command line
373                 firstchar = line;
374                 while(*firstchar && ISWHITESPACE(*firstchar))
375                         ++firstchar;
376                 if(
377                         (strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5]))
378                         &&
379                         (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4]))
380                         &&
381                         (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7]))
382                 )
383                 {
384                         Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
385                         Cmd_ExecuteString (preprocessed, src_command, false);
386                 }
387                 else
388                 {
389                         Cmd_ExecuteString (line, src_command, false);
390                 }
391
392                 if (cmd_wait)
393                 {       // skip out while text still remains in buffer, leaving it
394                         // for next frame
395                         cmd_wait = false;
396                         break;
397                 }
398         }
399
400         SV_UnlockThreadMutex();
401         Cbuf_UnlockThreadMutex();
402 }
403
404 /*
405 ==============================================================================
406
407                                                 SCRIPT COMMANDS
408
409 ==============================================================================
410 */
411
412 /*
413 ===============
414 Cmd_StuffCmds_f
415
416 Adds command line parameters as script statements
417 Commands lead with a +, and continue until a - or another +
418 quake +prog jctest.qp +cmd amlev1
419 quake -nosound +cmd amlev1
420 ===============
421 */
422 qboolean host_stuffcmdsrun = false;
423 void Cmd_StuffCmds_f (void)
424 {
425         int             i, j, l;
426         // this is for all commandline options combined (and is bounds checked)
427         char    build[MAX_INPUTLINE];
428
429         if (Cmd_Argc () != 1)
430         {
431                 Con_Print("stuffcmds : execute command line parameters\n");
432                 return;
433         }
434
435         // no reason to run the commandline arguments twice
436         if (host_stuffcmdsrun)
437                 return;
438
439         host_stuffcmdsrun = true;
440         build[0] = 0;
441         l = 0;
442         for (i = 0;i < com_argc;i++)
443         {
444                 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9') && l + strlen(com_argv[i]) - 1 <= sizeof(build) - 1)
445                 {
446                         j = 1;
447                         while (com_argv[i][j])
448                                 build[l++] = com_argv[i][j++];
449                         i++;
450                         for (;i < com_argc;i++)
451                         {
452                                 if (!com_argv[i])
453                                         continue;
454                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
455                                         break;
456                                 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
457                                         break;
458                                 build[l++] = ' ';
459                                 if (strchr(com_argv[i], ' '))
460                                         build[l++] = '\"';
461                                 for (j = 0;com_argv[i][j];j++)
462                                         build[l++] = com_argv[i][j];
463                                 if (strchr(com_argv[i], ' '))
464                                         build[l++] = '\"';
465                         }
466                         build[l++] = '\n';
467                         i--;
468                 }
469         }
470         // now terminate the combined string and prepend it to the command buffer
471         // we already reserved space for the terminator
472         build[l++] = 0;
473         Cbuf_InsertText (build);
474 }
475
476 static void Cmd_Exec(const char *filename)
477 {
478         char *f;
479         qboolean isdefaultcfg = strlen(filename) >= 11 && !strcmp(filename + strlen(filename) - 11, "default.cfg");
480
481         if (!strcmp(filename, "config.cfg"))
482         {
483                 filename = CONFIGFILENAME;
484                 if (COM_CheckParm("-noconfig"))
485                         return; // don't execute config.cfg
486         }
487
488         f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
489         if (!f)
490         {
491                 Con_Printf("couldn't exec %s\n",filename);
492                 return;
493         }
494         Con_Printf("execing %s\n",filename);
495
496         // if executing default.cfg for the first time, lock the cvar defaults
497         // it may seem backwards to insert this text BEFORE the default.cfg
498         // but Cbuf_InsertText inserts before, so this actually ends up after it.
499         if (isdefaultcfg)
500                 Cbuf_InsertText("\ncvar_lockdefaults\n");
501
502         // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
503         // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
504         Cbuf_InsertText ("\n");
505         Cbuf_InsertText (f);
506         Mem_Free(f);
507
508         if (isdefaultcfg)
509         {
510                 // special defaults for specific games go here, these execute before default.cfg
511                 // Nehahra pushable crates malfunction in some levels if this is on
512                 // Nehahra NPC AI is confused by blowupfallenzombies
513                 if (gamemode == GAME_NEHAHRA)
514                         Cbuf_InsertText("\nsv_gameplayfix_upwardvelocityclearsongroundflag 0\nsv_gameplayfix_blowupfallenzombies 0\n\n");
515                 // hipnotic mission pack has issues in their 'friendly monster' ai, which seem to attempt to attack themselves for some reason when findradius() returns non-solid entities.
516                 // hipnotic mission pack has issues with bobbing water entities 'jittering' between different heights on alternate frames at the default 0.0138889 ticrate, 0.02 avoids this issue
517                 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
518                 if (gamemode == GAME_HIPNOTIC)
519                         Cbuf_InsertText("\nsv_gameplayfix_blowupfallenzombies 0\nsys_ticrate 0.02\nsv_gameplayfix_slidemoveprojectiles 0\n\n");
520                 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
521                 if (gamemode == GAME_ROGUE)
522                         Cbuf_InsertText("\nsv_gameplayfix_findradiusdistancetobox 0\n\n");
523                 if (gamemode == GAME_NEXUIZ)
524                         Cbuf_InsertText("\nsv_gameplayfix_q2airaccelerate 1\nsv_gameplayfix_stepmultipletimes 1\n\n");
525                 if (gamemode == GAME_TENEBRAE)
526                         Cbuf_InsertText("\nr_shadow_gloss 2\nr_shadow_bumpscale_basetexture 4\n\n");
527                 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
528                 if (gamemode == GAME_STEELSTORM)
529                         Cbuf_InsertText("\ncl_csqc_generatemousemoveevents 0\n\n");
530         }
531 }
532
533 /*
534 ===============
535 Cmd_Exec_f
536 ===============
537 */
538 static void Cmd_Exec_f (void)
539 {
540         fssearch_t *s;
541         int i;
542
543         if (Cmd_Argc () != 2)
544         {
545                 Con_Print("exec <filename> : execute a script file\n");
546                 return;
547         }
548
549         s = FS_Search(Cmd_Argv(1), true, true);
550         if(!s || !s->numfilenames)
551         {
552                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
553                 return;
554         }
555
556         for(i = 0; i < s->numfilenames; ++i)
557                 Cmd_Exec(s->filenames[i]);
558
559         FS_FreeSearch(s);
560 }
561
562
563 /*
564 ===============
565 Cmd_Echo_f
566
567 Just prints the rest of the line to the console
568 ===============
569 */
570 static void Cmd_Echo_f (void)
571 {
572         int             i;
573
574         for (i=1 ; i<Cmd_Argc() ; i++)
575                 Con_Printf("%s ",Cmd_Argv(i));
576         Con_Print("\n");
577 }
578
579 // DRESK - 5/14/06
580 // Support Doom3-style Toggle Console Command
581 /*
582 ===============
583 Cmd_Toggle_f
584
585 Toggles a specified console variable amongst the values specified (default is 0 and 1)
586 ===============
587 */
588 static void Cmd_Toggle_f(void)
589 {
590         // Acquire Number of Arguments
591         int nNumArgs = Cmd_Argc();
592
593         if(nNumArgs == 1)
594                 // No Arguments Specified; Print Usage
595                 Con_Print("Toggle Console Variable - Usage\n  toggle <variable> - toggles between 0 and 1\n  toggle <variable> <value> - toggles between 0 and <value>\n  toggle <variable> [string 1] [string 2]...[string n] - cycles through all strings\n");
596         else
597         { // Correct Arguments Specified
598                 // Acquire Potential CVar
599                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
600
601                 if(cvCVar != NULL)
602                 { // Valid CVar
603                         if(nNumArgs == 2)
604                         { // Default Usage
605                                 if(cvCVar->integer)
606                                         Cvar_SetValueQuick(cvCVar, 0);
607                                 else
608                                         Cvar_SetValueQuick(cvCVar, 1);
609                         }
610                         else
611                         if(nNumArgs == 3)
612                         { // 0 and Specified Usage
613                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
614                                         // CVar is Specified Value; // Reset to 0
615                                         Cvar_SetValueQuick(cvCVar, 0);
616                                 else
617                                 if(cvCVar->integer == 0)
618                                         // CVar is 0; Specify Value
619                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
620                                 else
621                                         // CVar does not match; Reset to 0
622                                         Cvar_SetValueQuick(cvCVar, 0);
623                         }
624                         else
625                         { // Variable Values Specified
626                                 int nCnt;
627                                 int bFound = 0;
628
629                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
630                                 { // Cycle through Values
631                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
632                                         { // Current Value Located; Increment to Next
633                                                 if( (nCnt + 1) == nNumArgs)
634                                                         // Max Value Reached; Reset
635                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
636                                                 else
637                                                         // Next Value
638                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
639
640                                                 // End Loop
641                                                 nCnt = nNumArgs;
642                                                 // Assign Found
643                                                 bFound = 1;
644                                         }
645                                 }
646                                 if(!bFound)
647                                         // Value not Found; Reset to Original
648                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
649                         }
650
651                 }
652                 else
653                 { // Invalid CVar
654                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
655                 }
656         }
657 }
658
659 /*
660 ===============
661 Cmd_Alias_f
662
663 Creates a new command that executes a command string (possibly ; seperated)
664 ===============
665 */
666 static void Cmd_Alias_f (void)
667 {
668         cmdalias_t      *a;
669         char            cmd[MAX_INPUTLINE];
670         int                     i, c;
671         const char              *s;
672         size_t          alloclen;
673
674         if (Cmd_Argc() == 1)
675         {
676                 Con_Print("Current alias commands:\n");
677                 for (a = cmd_alias ; a ; a=a->next)
678                         Con_Printf("%s : %s", a->name, a->value);
679                 return;
680         }
681
682         s = Cmd_Argv(1);
683         if (strlen(s) >= MAX_ALIAS_NAME)
684         {
685                 Con_Print("Alias name is too long\n");
686                 return;
687         }
688
689         // if the alias already exists, reuse it
690         for (a = cmd_alias ; a ; a=a->next)
691         {
692                 if (!strcmp(s, a->name))
693                 {
694                         Z_Free (a->value);
695                         break;
696                 }
697         }
698
699         if (!a)
700         {
701                 cmdalias_t *prev, *current;
702
703                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
704                 strlcpy (a->name, s, sizeof (a->name));
705                 // insert it at the right alphanumeric position
706                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
707                         ;
708                 if( prev ) {
709                         prev->next = a;
710                 } else {
711                         cmd_alias = a;
712                 }
713                 a->next = current;
714         }
715
716
717 // copy the rest of the command line
718         cmd[0] = 0;             // start out with a null string
719         c = Cmd_Argc();
720         for (i=2 ; i < c ; i++)
721         {
722                 if (i != 2)
723                         strlcat (cmd, " ", sizeof (cmd));
724                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
725         }
726         strlcat (cmd, "\n", sizeof (cmd));
727
728         alloclen = strlen (cmd) + 1;
729         if(alloclen >= 2)
730                 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
731         a->value = (char *)Z_Malloc (alloclen);
732         memcpy (a->value, cmd, alloclen);
733 }
734
735 /*
736 ===============
737 Cmd_UnAlias_f
738
739 Remove existing aliases.
740 ===============
741 */
742 static void Cmd_UnAlias_f (void)
743 {
744         cmdalias_t      *a, *p;
745         int i;
746         const char *s;
747
748         if(Cmd_Argc() == 1)
749         {
750                 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
751                 return;
752         }
753
754         for(i = 1; i < Cmd_Argc(); ++i)
755         {
756                 s = Cmd_Argv(i);
757                 p = NULL;
758                 for(a = cmd_alias; a; p = a, a = a->next)
759                 {
760                         if(!strcmp(s, a->name))
761                         {
762                                 if (a->initstate) // we can not remove init aliases
763                                         continue;
764                                 if(a == cmd_alias)
765                                         cmd_alias = a->next;
766                                 if(p)
767                                         p->next = a->next;
768                                 Z_Free(a->value);
769                                 Z_Free(a);
770                                 break;
771                         }
772                 }
773                 if(!a)
774                         Con_Printf("unalias: %s alias not found\n", s);
775         }
776 }
777
778 /*
779 =============================================================================
780
781                                         COMMAND EXECUTION
782
783 =============================================================================
784 */
785
786 typedef struct cmd_function_s
787 {
788         struct cmd_function_s *next;
789         const char *name;
790         const char *description;
791         xcommand_t consolefunction;
792         xcommand_t clientfunction;
793         qboolean csqcfunc;
794         qboolean initstate; // indicates this command existed at init
795 } cmd_function_t;
796
797 static int cmd_argc;
798 static const char *cmd_argv[MAX_ARGS];
799 static const char *cmd_null_string = "";
800 static const char *cmd_args;
801 cmd_source_t cmd_source;
802
803
804 static cmd_function_t *cmd_functions;           // possible commands to execute
805
806 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
807 {
808         cvar_t *cvar;
809         long argno;
810         char *endptr;
811
812         if(is_multiple)
813                 *is_multiple = false;
814
815         if(!varname || !*varname)
816                 return NULL;
817
818         if(alias)
819         {
820                 if(!strcmp(varname, "*"))
821                 {
822                         if(is_multiple)
823                                 *is_multiple = true;
824                         return Cmd_Args();
825                 }
826                 else if(!strcmp(varname, "#"))
827                 {
828                         return va("%d", Cmd_Argc());
829                 }
830                 else if(varname[strlen(varname) - 1] == '-')
831                 {
832                         argno = strtol(varname, &endptr, 10);
833                         if(endptr == varname + strlen(varname) - 1)
834                         {
835                                 // whole string is a number, apart from the -
836                                 const char *p = Cmd_Args();
837                                 for(; argno > 1; --argno)
838                                         if(!COM_ParseToken_Console(&p))
839                                                 break;
840                                 if(p)
841                                 {
842                                         if(is_multiple)
843                                                 *is_multiple = true;
844
845                                         // kill pre-argument whitespace
846                                         for (;*p && ISWHITESPACE(*p);p++)
847                                                 ;
848
849                                         return p;
850                                 }
851                         }
852                 }
853                 else
854                 {
855                         argno = strtol(varname, &endptr, 10);
856                         if(*endptr == 0)
857                         {
858                                 // whole string is a number
859                                 // NOTE: we already made sure we don't have an empty cvar name!
860                                 if(argno >= 0 && argno < Cmd_Argc())
861                                         return Cmd_Argv(argno);
862                         }
863                 }
864         }
865
866         if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
867                 return cvar->string;
868
869         return NULL;
870 }
871
872 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qboolean putquotes)
873 {
874         qboolean quote_quot = !!strchr(quoteset, '"');
875         qboolean quote_backslash = !!strchr(quoteset, '\\');
876         qboolean quote_dollar = !!strchr(quoteset, '$');
877
878         if(putquotes)
879         {
880                 if(outlen <= 2)
881                 {
882                         *out++ = 0;
883                         return false;
884                 }
885                 *out++ = '"'; --outlen;
886                 --outlen;
887         }
888
889         while(*in)
890         {
891                 if(*in == '"' && quote_quot)
892                 {
893                         if(outlen <= 2)
894                                 goto fail;
895                         *out++ = '\\'; --outlen;
896                         *out++ = '"'; --outlen;
897                 }
898                 else if(*in == '\\' && quote_backslash)
899                 {
900                         if(outlen <= 2)
901                                 goto fail;
902                         *out++ = '\\'; --outlen;
903                         *out++ = '\\'; --outlen;
904                 }
905                 else if(*in == '$' && quote_dollar)
906                 {
907                         if(outlen <= 2)
908                                 goto fail;
909                         *out++ = '$'; --outlen;
910                         *out++ = '$'; --outlen;
911                 }
912                 else
913                 {
914                         if(outlen <= 1)
915                                 goto fail;
916                         *out++ = *in; --outlen;
917                 }
918                 ++in;
919         }
920         if(putquotes)
921                 *out++ = '"';
922         *out++ = 0;
923         return true;
924 fail:
925         if(putquotes)
926                 *out++ = '"';
927         *out++ = 0;
928         return false;
929 }
930
931 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
932 {
933         static char varname[MAX_INPUTLINE];
934         static char varval[MAX_INPUTLINE];
935         const char *varstr;
936         char *varfunc;
937 static char asis[] = "asis"; // just to suppress const char warnings
938
939         if(varlen >= MAX_INPUTLINE)
940                 varlen = MAX_INPUTLINE - 1;
941         memcpy(varname, var, varlen);
942         varname[varlen] = 0;
943         varfunc = strchr(varname, ' ');
944
945         if(varfunc)
946         {
947                 *varfunc = 0;
948                 ++varfunc;
949         }
950
951         if(*var == 0)
952         {
953                 // empty cvar name?
954                 return NULL;
955         }
956
957         varstr = NULL;
958
959         if(varname[0] == '$')
960                 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
961         else
962         {
963                 qboolean is_multiple = false;
964                 // Exception: $* and $n- don't use the quoted form by default
965                 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
966                 if(is_multiple)
967                         if(!varfunc)
968                                 varfunc = asis;
969         }
970
971         if(!varstr)
972         {
973                 if(alias)
974                         Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
975                 else
976                         Con_Printf("Warning: Could not expand $%s\n", varname);
977                 return NULL;
978         }
979
980         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
981         {
982                 // quote it so it can be used inside double quotes
983                 // we just need to replace " by \", and of course, double backslashes
984                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
985                 return varval;
986         }
987         else if(!strcmp(varfunc, "asis"))
988         {
989                 return varstr;
990         }
991         else
992                 Con_Printf("Unknown variable function %s\n", varfunc);
993
994         return varstr;
995 }
996
997 /*
998 Cmd_PreprocessString
999
1000 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1001 */
1002 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
1003         const char *in;
1004         size_t eat, varlen;
1005         unsigned outlen;
1006         const char *val;
1007
1008         // don't crash if there's no room in the outtext buffer
1009         if( maxoutlen == 0 ) {
1010                 return;
1011         }
1012         maxoutlen--; // because of \0
1013
1014         in = intext;
1015         outlen = 0;
1016
1017         while( *in && outlen < maxoutlen ) {
1018                 if( *in == '$' ) {
1019                         // this is some kind of expansion, see what comes after the $
1020                         in++;
1021
1022                         // The console does the following preprocessing:
1023                         //
1024                         // - $$ is transformed to a single dollar sign.
1025                         // - $var or ${var} are expanded to the contents of the named cvar,
1026                         //   with quotation marks and backslashes quoted so it can safely
1027                         //   be used inside quotation marks (and it should always be used
1028                         //   that way)
1029                         // - ${var asis} inserts the cvar value as is, without doing this
1030                         //   quoting
1031                         // - prefix the cvar name with a dollar sign to do indirection;
1032                         //   for example, if $x has the value timelimit, ${$x} will return
1033                         //   the value of $timelimit
1034                         // - when expanding an alias, the special variable name $* refers
1035                         //   to all alias parameters, and a number refers to that numbered
1036                         //   alias parameter, where the name of the alias is $0, the first
1037                         //   parameter is $1 and so on; as a special case, $* inserts all
1038                         //   parameters, without extra quoting, so one can use $* to just
1039                         //   pass all parameters around. All parameters starting from $n
1040                         //   can be referred to as $n- (so $* is equivalent to $1-).
1041                         //
1042                         // Note: when expanding an alias, cvar expansion is done in the SAME step
1043                         // as alias expansion so that alias parameters or cvar values containing
1044                         // dollar signs have no unwanted bad side effects. However, this needs to
1045                         // be accounted for when writing complex aliases. For example,
1046                         //   alias foo "set x NEW; echo $x"
1047                         // actually expands to
1048                         //   "set x NEW; echo OLD"
1049                         // and will print OLD! To work around this, use a second alias:
1050                         //   alias foo "set x NEW; foo2"
1051                         //   alias foo2 "echo $x"
1052                         //
1053                         // Also note: lines starting with alias are exempt from cvar expansion.
1054                         // If you want cvar expansion, write "alias" instead:
1055                         //
1056                         //   set x 1
1057                         //   alias foo "echo $x"
1058                         //   "alias" bar "echo $x"
1059                         //   set x 2
1060                         //
1061                         // foo will print 2, because the variable $x will be expanded when the alias
1062                         // gets expanded. bar will print 1, because the variable $x was expanded
1063                         // at definition time. foo can be equivalently defined as
1064                         //
1065                         //   "alias" foo "echo $$x"
1066                         //
1067                         // because at definition time, $$ will get replaced to a single $.
1068
1069                         if( *in == '$' ) {
1070                                 val = "$";
1071                                 eat = 1;
1072                         } else if(*in == '{') {
1073                                 varlen = strcspn(in + 1, "}");
1074                                 if(in[varlen + 1] == '}')
1075                                 {
1076                                         val = Cmd_GetCvarValue(in + 1, varlen, alias);
1077                                         eat = varlen + 2;
1078                                 }
1079                                 else
1080                                 {
1081                                         // ran out of data?
1082                                         val = NULL;
1083                                         eat = varlen + 1;
1084                                 }
1085                         } else {
1086                                 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1087                                 val = Cmd_GetCvarValue(in, varlen, alias);
1088                                 eat = varlen;
1089                         }
1090                         if(val)
1091                         {
1092                                 // insert the cvar value
1093                                 while(*val && outlen < maxoutlen)
1094                                         outtext[outlen++] = *val++;
1095                                 in += eat;
1096                         }
1097                         else
1098                         {
1099                                 // copy the unexpanded text
1100                                 outtext[outlen++] = '$';
1101                                 while(eat && outlen < maxoutlen)
1102                                 {
1103                                         outtext[outlen++] = *in++;
1104                                         --eat;
1105                                 }
1106                         }
1107                 }
1108                 else 
1109                         outtext[outlen++] = *in++;
1110         }
1111         outtext[outlen] = 0;
1112 }
1113
1114 /*
1115 ============
1116 Cmd_ExecuteAlias
1117
1118 Called for aliases and fills in the alias into the cbuffer
1119 ============
1120 */
1121 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1122 {
1123         static char buffer[ MAX_INPUTLINE ];
1124         static char buffer2[ MAX_INPUTLINE ];
1125         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1126         // insert at start of command buffer, so that aliases execute in order
1127         // (fixes bug introduced by Black on 20050705)
1128
1129         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1130         // have to make sure that no second variable expansion takes place, otherwise
1131         // alias parameters containing dollar signs can have bad effects.
1132         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1133         Cbuf_InsertText( buffer2 );
1134 }
1135
1136 /*
1137 ========
1138 Cmd_List
1139
1140         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1141         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1142
1143 ========
1144 */
1145 static void Cmd_List_f (void)
1146 {
1147         cmd_function_t *cmd;
1148         const char *partial;
1149         size_t len;
1150         int count;
1151         qboolean ispattern;
1152
1153         if (Cmd_Argc() > 1)
1154         {
1155                 partial = Cmd_Argv (1);
1156                 len = strlen(partial);
1157         }
1158         else
1159         {
1160                 partial = NULL;
1161                 len = 0;
1162         }
1163
1164         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1165
1166         count = 0;
1167         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1168         {
1169                 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1170                         continue;
1171                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1172                 count++;
1173         }
1174
1175         if (len)
1176         {
1177                 if(ispattern)
1178                         Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1179                 else
1180                         Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1181         }
1182         else
1183                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1184 }
1185
1186 static void Cmd_Apropos_f(void)
1187 {
1188         cmd_function_t *cmd;
1189         cvar_t *cvar;
1190         cmdalias_t *alias;
1191         const char *partial;
1192         int count;
1193         qboolean ispattern;
1194
1195         if (Cmd_Argc() > 1)
1196                 partial = Cmd_Args();
1197         else
1198         {
1199                 Con_Printf("usage: apropos <string>\n");
1200                 return;
1201         }
1202
1203         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1204         if(!ispattern)
1205                 partial = va("*%s*", partial);
1206
1207         count = 0;
1208         for (cvar = cvar_vars; cvar; cvar = cvar->next)
1209         {
1210                 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1211                 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1212                         continue;
1213                 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1214                 count++;
1215         }
1216         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1217         {
1218                 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1219                 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1220                         continue;
1221                 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1222                 count++;
1223         }
1224         for (alias = cmd_alias; alias; alias = alias->next)
1225         {
1226                 // procede here a bit differently as an alias value always got a final \n
1227                 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1228                 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1229                         continue;
1230                 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1231                 count++;
1232         }
1233         Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1234 }
1235
1236 /*
1237 ============
1238 Cmd_Init
1239 ============
1240 */
1241 void Cmd_Init (void)
1242 {
1243         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1244         // space for commands and script files
1245         cmd_text.data = cmd_text_buf;
1246         cmd_text.maxsize = sizeof(cmd_text_buf);
1247         cmd_text.cursize = 0;
1248
1249         if (Thread_HasThreads())
1250                 cmd_text_mutex = Thread_CreateMutex();
1251 }
1252
1253 void Cmd_Init_Commands (void)
1254 {
1255 //
1256 // register our commands
1257 //
1258         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1259         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1260         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1261         Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $X (being X a number), $* for all parameters, $X- for all parameters starting from $X). Without arguments show the list of all alias");
1262         Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1263         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1264         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1265         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1266         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1267         Cmd_AddCommand ("unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1268 #ifdef FILLALLCVARSWITHRUBBISH
1269         Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1270 #endif /* FILLALLCVARSWITHRUBBISH */
1271
1272         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1273         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1274         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1275         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1276         Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1277
1278         Cmd_AddCommand ("cvar_lockdefaults", Cvar_LockDefaults_f, "stores the current values of all cvars into their default values, only used once during startup after parsing default.cfg");
1279         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1280         Cmd_AddCommand ("cvar_resettodefaults_nosaveonly", Cvar_ResetToDefaults_NoSaveOnly_f, "sets all non-saved cvars to their locked default values (variables that will not be saved to config.cfg)");
1281         Cmd_AddCommand ("cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
1282
1283         Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1284         Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1285
1286         // DRESK - 5/14/06
1287         // Support Doom3-style Toggle Command
1288         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1289 }
1290
1291 /*
1292 ============
1293 Cmd_Shutdown
1294 ============
1295 */
1296 void Cmd_Shutdown(void)
1297 {
1298         if (cmd_text_mutex)
1299                 Thread_DestroyMutex(cmd_text_mutex);
1300         cmd_text_mutex = NULL;
1301
1302         Mem_FreePool(&cmd_mempool);
1303 }
1304
1305 /*
1306 ============
1307 Cmd_Argc
1308 ============
1309 */
1310 int             Cmd_Argc (void)
1311 {
1312         return cmd_argc;
1313 }
1314
1315 /*
1316 ============
1317 Cmd_Argv
1318 ============
1319 */
1320 const char *Cmd_Argv (int arg)
1321 {
1322         if (arg >= cmd_argc )
1323                 return cmd_null_string;
1324         return cmd_argv[arg];
1325 }
1326
1327 /*
1328 ============
1329 Cmd_Args
1330 ============
1331 */
1332 const char *Cmd_Args (void)
1333 {
1334         return cmd_args;
1335 }
1336
1337
1338 /*
1339 ============
1340 Cmd_TokenizeString
1341
1342 Parses the given string into command line tokens.
1343 ============
1344 */
1345 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1346 static void Cmd_TokenizeString (const char *text)
1347 {
1348         int l;
1349
1350         cmd_argc = 0;
1351         cmd_args = NULL;
1352
1353         while (1)
1354         {
1355                 // skip whitespace up to a /n
1356                 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1357                         text++;
1358
1359                 // line endings:
1360                 // UNIX: \n
1361                 // Mac: \r
1362                 // Windows: \r\n
1363                 if (*text == '\n' || *text == '\r')
1364                 {
1365                         // a newline separates commands in the buffer
1366                         if (*text == '\r' && text[1] == '\n')
1367                                 text++;
1368                         text++;
1369                         break;
1370                 }
1371
1372                 if (!*text)
1373                         return;
1374
1375                 if (cmd_argc == 1)
1376                         cmd_args = text;
1377
1378                 if (!COM_ParseToken_Console(&text))
1379                         return;
1380
1381                 if (cmd_argc < MAX_ARGS)
1382                 {
1383                         l = (int)strlen(com_token) + 1;
1384                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1385                         {
1386                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1387                                 break;
1388                         }
1389                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1390                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1391                         cmd_tokenizebufferpos += l;
1392                         cmd_argc++;
1393                 }
1394         }
1395 }
1396
1397
1398 /*
1399 ============
1400 Cmd_AddCommand
1401 ============
1402 */
1403 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1404 {
1405         cmd_function_t *cmd;
1406         cmd_function_t *prev, *current;
1407
1408 // fail if the command is a variable name
1409         if (Cvar_FindVar( cmd_name ))
1410         {
1411                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1412                 return;
1413         }
1414
1415 // fail if the command already exists
1416         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1417         {
1418                 if (!strcmp (cmd_name, cmd->name))
1419                 {
1420                         if (consolefunction || clientfunction)
1421                         {
1422                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1423                                 return;
1424                         }
1425                         else    //[515]: csqc
1426                         {
1427                                 cmd->csqcfunc = true;
1428                                 return;
1429                         }
1430                 }
1431         }
1432
1433         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1434         cmd->name = cmd_name;
1435         cmd->consolefunction = consolefunction;
1436         cmd->clientfunction = clientfunction;
1437         cmd->description = description;
1438         if(!consolefunction && !clientfunction)                 //[515]: csqc
1439                 cmd->csqcfunc = true;
1440         cmd->next = cmd_functions;
1441
1442 // insert it at the right alphanumeric position
1443         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1444                 ;
1445         if( prev ) {
1446                 prev->next = cmd;
1447         } else {
1448                 cmd_functions = cmd;
1449         }
1450         cmd->next = current;
1451 }
1452
1453 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1454 {
1455         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1456 }
1457
1458 /*
1459 ============
1460 Cmd_Exists
1461 ============
1462 */
1463 qboolean Cmd_Exists (const char *cmd_name)
1464 {
1465         cmd_function_t  *cmd;
1466
1467         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1468                 if (!strcmp (cmd_name,cmd->name))
1469                         return true;
1470
1471         return false;
1472 }
1473
1474
1475 /*
1476 ============
1477 Cmd_CompleteCommand
1478 ============
1479 */
1480 const char *Cmd_CompleteCommand (const char *partial)
1481 {
1482         cmd_function_t *cmd;
1483         size_t len;
1484
1485         len = strlen(partial);
1486
1487         if (!len)
1488                 return NULL;
1489
1490 // check functions
1491         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1492                 if (!strncasecmp(partial, cmd->name, len))
1493                         return cmd->name;
1494
1495         return NULL;
1496 }
1497
1498 /*
1499         Cmd_CompleteCountPossible
1500
1501         New function for tab-completion system
1502         Added by EvilTypeGuy
1503         Thanks to Fett erich@heintz.com
1504         Thanks to taniwha
1505
1506 */
1507 int Cmd_CompleteCountPossible (const char *partial)
1508 {
1509         cmd_function_t *cmd;
1510         size_t len;
1511         int h;
1512
1513         h = 0;
1514         len = strlen(partial);
1515
1516         if (!len)
1517                 return 0;
1518
1519         // Loop through the command list and count all partial matches
1520         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1521                 if (!strncasecmp(partial, cmd->name, len))
1522                         h++;
1523
1524         return h;
1525 }
1526
1527 /*
1528         Cmd_CompleteBuildList
1529
1530         New function for tab-completion system
1531         Added by EvilTypeGuy
1532         Thanks to Fett erich@heintz.com
1533         Thanks to taniwha
1534
1535 */
1536 const char **Cmd_CompleteBuildList (const char *partial)
1537 {
1538         cmd_function_t *cmd;
1539         size_t len = 0;
1540         size_t bpos = 0;
1541         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1542         const char **buf;
1543
1544         len = strlen(partial);
1545         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1546         // Loop through the alias list and print all matches
1547         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1548                 if (!strncasecmp(partial, cmd->name, len))
1549                         buf[bpos++] = cmd->name;
1550
1551         buf[bpos] = NULL;
1552         return buf;
1553 }
1554
1555 // written by LordHavoc
1556 void Cmd_CompleteCommandPrint (const char *partial)
1557 {
1558         cmd_function_t *cmd;
1559         size_t len = strlen(partial);
1560         // Loop through the command list and print all matches
1561         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1562                 if (!strncasecmp(partial, cmd->name, len))
1563                         Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
1564 }
1565
1566 /*
1567         Cmd_CompleteAlias
1568
1569         New function for tab-completion system
1570         Added by EvilTypeGuy
1571         Thanks to Fett erich@heintz.com
1572         Thanks to taniwha
1573
1574 */
1575 const char *Cmd_CompleteAlias (const char *partial)
1576 {
1577         cmdalias_t *alias;
1578         size_t len;
1579
1580         len = strlen(partial);
1581
1582         if (!len)
1583                 return NULL;
1584
1585         // Check functions
1586         for (alias = cmd_alias; alias; alias = alias->next)
1587                 if (!strncasecmp(partial, alias->name, len))
1588                         return alias->name;
1589
1590         return NULL;
1591 }
1592
1593 // written by LordHavoc
1594 void Cmd_CompleteAliasPrint (const char *partial)
1595 {
1596         cmdalias_t *alias;
1597         size_t len = strlen(partial);
1598         // Loop through the alias list and print all matches
1599         for (alias = cmd_alias; alias; alias = alias->next)
1600                 if (!strncasecmp(partial, alias->name, len))
1601                         Con_Printf("^5%s^7: %s", alias->name, alias->value);
1602 }
1603
1604
1605 /*
1606         Cmd_CompleteAliasCountPossible
1607
1608         New function for tab-completion system
1609         Added by EvilTypeGuy
1610         Thanks to Fett erich@heintz.com
1611         Thanks to taniwha
1612
1613 */
1614 int Cmd_CompleteAliasCountPossible (const char *partial)
1615 {
1616         cmdalias_t      *alias;
1617         size_t          len;
1618         int                     h;
1619
1620         h = 0;
1621
1622         len = strlen(partial);
1623
1624         if (!len)
1625                 return 0;
1626
1627         // Loop through the command list and count all partial matches
1628         for (alias = cmd_alias; alias; alias = alias->next)
1629                 if (!strncasecmp(partial, alias->name, len))
1630                         h++;
1631
1632         return h;
1633 }
1634
1635 /*
1636         Cmd_CompleteAliasBuildList
1637
1638         New function for tab-completion system
1639         Added by EvilTypeGuy
1640         Thanks to Fett erich@heintz.com
1641         Thanks to taniwha
1642
1643 */
1644 const char **Cmd_CompleteAliasBuildList (const char *partial)
1645 {
1646         cmdalias_t *alias;
1647         size_t len = 0;
1648         size_t bpos = 0;
1649         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1650         const char **buf;
1651
1652         len = strlen(partial);
1653         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1654         // Loop through the alias list and print all matches
1655         for (alias = cmd_alias; alias; alias = alias->next)
1656                 if (!strncasecmp(partial, alias->name, len))
1657                         buf[bpos++] = alias->name;
1658
1659         buf[bpos] = NULL;
1660         return buf;
1661 }
1662
1663 void Cmd_ClearCsqcFuncs (void)
1664 {
1665         cmd_function_t *cmd;
1666         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1667                 cmd->csqcfunc = false;
1668 }
1669
1670 qboolean CL_VM_ConsoleCommand (const char *cmd);
1671 /*
1672 ============
1673 Cmd_ExecuteString
1674
1675 A complete command line has been parsed, so try to execute it
1676 FIXME: lookupnoadd the token to speed search?
1677 ============
1678 */
1679 void Cmd_ExecuteString (const char *text, cmd_source_t src, qboolean lockmutex)
1680 {
1681         int oldpos;
1682         int found;
1683         cmd_function_t *cmd;
1684         cmdalias_t *a;
1685
1686         if (lockmutex)
1687                 Cbuf_LockThreadMutex();
1688         oldpos = cmd_tokenizebufferpos;
1689         cmd_source = src;
1690         found = false;
1691
1692         Cmd_TokenizeString (text);
1693
1694 // execute the command line
1695         if (!Cmd_Argc())
1696                 goto done; // no tokens
1697
1698 // check functions
1699         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1700         {
1701                 if (!strcasecmp (cmd_argv[0],cmd->name))
1702                 {
1703                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1704                                 goto done;
1705                         switch (src)
1706                         {
1707                         case src_command:
1708                                 if (cmd->consolefunction)
1709                                         cmd->consolefunction ();
1710                                 else if (cmd->clientfunction)
1711                                 {
1712                                         if (cls.state == ca_connected)
1713                                         {
1714                                                 // forward remote commands to the server for execution
1715                                                 Cmd_ForwardToServer();
1716                                         }
1717                                         else
1718                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1719                                 }
1720                                 else
1721                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1722                                 found = true;
1723                                 goto command_found;
1724                         case src_client:
1725                                 if (cmd->clientfunction)
1726                                 {
1727                                         cmd->clientfunction ();
1728                                         goto done;
1729                                 }
1730                                 break;
1731                         }
1732                         break;
1733                 }
1734         }
1735 command_found:
1736
1737         // if it's a client command and no command was found, say so.
1738         if (cmd_source == src_client)
1739         {
1740                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1741                 goto done;
1742         }
1743
1744 // check alias
1745         for (a=cmd_alias ; a ; a=a->next)
1746         {
1747                 if (!strcasecmp (cmd_argv[0], a->name))
1748                 {
1749                         Cmd_ExecuteAlias(a);
1750                         goto done;
1751                 }
1752         }
1753
1754         if(found) // if the command was hooked and found, all is good
1755                 goto done;
1756
1757 // check cvars
1758         if (!Cvar_Command () && host_framecount > 0)
1759                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1760
1761 done:
1762         cmd_tokenizebufferpos = oldpos;
1763         if (lockmutex)
1764                 Cbuf_UnlockThreadMutex();
1765 }
1766
1767
1768 /*
1769 ===================
1770 Cmd_ForwardStringToServer
1771
1772 Sends an entire command string over to the server, unprocessed
1773 ===================
1774 */
1775 void Cmd_ForwardStringToServer (const char *s)
1776 {
1777         char temp[128];
1778         if (cls.state != ca_connected)
1779         {
1780                 Con_Printf("Can't \"%s\", not connected\n", s);
1781                 return;
1782         }
1783
1784         if (!cls.netcon)
1785                 return;
1786
1787         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1788         // attention, it has been eradicated from here, its only (former) use in
1789         // all of darkplaces.
1790         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1791                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1792         else
1793                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1794         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1795         {
1796                 // say/say_team commands can replace % character codes with status info
1797                 while (*s)
1798                 {
1799                         if (*s == '%' && s[1])
1800                         {
1801                                 // handle proquake message macros
1802                                 temp[0] = 0;
1803                                 switch (s[1])
1804                                 {
1805                                 case 'l': // current location
1806                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1807                                         break;
1808                                 case 'h': // current health
1809                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1810                                         break;
1811                                 case 'a': // current armor
1812                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1813                                         break;
1814                                 case 'x': // current rockets
1815                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1816                                         break;
1817                                 case 'c': // current cells
1818                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1819                                         break;
1820                                 // silly proquake macros
1821                                 case 'd': // loc at last death
1822                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1823                                         break;
1824                                 case 't': // current time
1825                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1826                                         break;
1827                                 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1828                                         if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1829                                                 dpsnprintf(temp, sizeof(temp), "I need RL");
1830                                         else if (!cl.stats[STAT_ROCKETS])
1831                                                 dpsnprintf(temp, sizeof(temp), "I need rockets");
1832                                         else
1833                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
1834                                         break;
1835                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1836                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
1837                                         {
1838                                                 if (temp[0])
1839                                                         strlcat(temp, " ", sizeof(temp));
1840                                                 strlcat(temp, "quad", sizeof(temp));
1841                                         }
1842                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1843                                         {
1844                                                 if (temp[0])
1845                                                         strlcat(temp, " ", sizeof(temp));
1846                                                 strlcat(temp, "pent", sizeof(temp));
1847                                         }
1848                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1849                                         {
1850                                                 if (temp[0])
1851                                                         strlcat(temp, " ", sizeof(temp));
1852                                                 strlcat(temp, "eyes", sizeof(temp));
1853                                         }
1854                                         break;
1855                                 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1856                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1857                                                 strlcat(temp, "SSG", sizeof(temp));
1858                                         strlcat(temp, ":", sizeof(temp));
1859                                         if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1860                                                 strlcat(temp, "NG", sizeof(temp));
1861                                         strlcat(temp, ":", sizeof(temp));
1862                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1863                                                 strlcat(temp, "SNG", sizeof(temp));
1864                                         strlcat(temp, ":", sizeof(temp));
1865                                         if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1866                                                 strlcat(temp, "GL", sizeof(temp));
1867                                         strlcat(temp, ":", sizeof(temp));
1868                                         if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1869                                                 strlcat(temp, "RL", sizeof(temp));
1870                                         strlcat(temp, ":", sizeof(temp));
1871                                         if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1872                                                 strlcat(temp, "LG", sizeof(temp));
1873                                         break;
1874                                 default:
1875                                         // not a recognized macro, print it as-is...
1876                                         temp[0] = s[0];
1877                                         temp[1] = s[1];
1878                                         temp[2] = 0;
1879                                         break;
1880                                 }
1881                                 // write the resulting text
1882                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1883                                 s += 2;
1884                                 continue;
1885                         }
1886                         MSG_WriteByte(&cls.netcon->message, *s);
1887                         s++;
1888                 }
1889                 MSG_WriteByte(&cls.netcon->message, 0);
1890         }
1891         else // any other command is passed on as-is
1892                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1893 }
1894
1895 /*
1896 ===================
1897 Cmd_ForwardToServer
1898
1899 Sends the entire command line over to the server
1900 ===================
1901 */
1902 void Cmd_ForwardToServer (void)
1903 {
1904         const char *s;
1905         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1906         {
1907                 // we want to strip off "cmd", so just send the args
1908                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1909         }
1910         else
1911         {
1912                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1913                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1914         }
1915         // don't send an empty forward message if the user tries "cmd" by itself
1916         if (!s || !*s)
1917                 return;
1918         Cmd_ForwardStringToServer(s);
1919 }
1920
1921
1922 /*
1923 ================
1924 Cmd_CheckParm
1925
1926 Returns the position (1 to argc-1) in the command's argument list
1927 where the given parameter apears, or 0 if not present
1928 ================
1929 */
1930
1931 int Cmd_CheckParm (const char *parm)
1932 {
1933         int i;
1934
1935         if (!parm)
1936         {
1937                 Con_Printf ("Cmd_CheckParm: NULL");
1938                 return 0;
1939         }
1940
1941         for (i = 1; i < Cmd_Argc (); i++)
1942                 if (!strcasecmp (parm, Cmd_Argv (i)))
1943                         return i;
1944
1945         return 0;
1946 }
1947
1948
1949
1950 void Cmd_SaveInitState(void)
1951 {
1952         cmd_function_t *f;
1953         cmdalias_t *a;
1954         for (f = cmd_functions;f;f = f->next)
1955                 f->initstate = true;
1956         for (a = cmd_alias;a;a = a->next)
1957         {
1958                 a->initstate = true;
1959                 a->initialvalue = Mem_strdup(zonemempool, a->value);
1960         }
1961         Cvar_SaveInitState();
1962 }
1963
1964 void Cmd_RestoreInitState(void)
1965 {
1966         cmd_function_t *f, **fp;
1967         cmdalias_t *a, **ap;
1968         for (fp = &cmd_functions;(f = *fp);)
1969         {
1970                 if (f->initstate)
1971                         fp = &f->next;
1972                 else
1973                 {
1974                         // destroy this command, it didn't exist at init
1975                         Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
1976                         *fp = f->next;
1977                         Z_Free(f);
1978                 }
1979         }
1980         for (ap = &cmd_alias;(a = *ap);)
1981         {
1982                 if (a->initstate)
1983                 {
1984                         // restore this alias, it existed at init
1985                         if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
1986                         {
1987                                 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
1988                                 if (a->value)
1989                                         Z_Free(a->value);
1990                                 a->value = Mem_strdup(zonemempool, a->initialvalue);
1991                         }
1992                         ap = &a->next;
1993                 }
1994                 else
1995                 {
1996                         // free this alias, it didn't exist at init...
1997                         Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
1998                         *ap = a->next;
1999                         if (a->value)
2000                                 Z_Free(a->value);
2001                         Z_Free(a);
2002                 }
2003         }
2004         Cvar_RestoreInitState();
2005 }