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