]> icculus.org git repositories - divverent/darkplaces.git/blob - cmd.c
Added return to standard color coding in the "Player entered the game" and "Client...
[divverent/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
24 #define MAX_ALIAS_NAME  32
25 // this is the largest script file that can be executed in one step
26 // LordHavoc: inreased this from 8192 to 32768
27 #define CMDBUFSIZE 32768
28 // maximum number of parameters to a command
29 #define MAX_ARGS 80
30 // maximum tokenizable commandline length (counting NUL terminations)
31 #define CMD_TOKENIZELENGTH (MAX_INPUTLINE + 80)
32
33 typedef struct cmdalias_s
34 {
35         struct cmdalias_s *next;
36         char name[MAX_ALIAS_NAME];
37         char *value;
38 } cmdalias_t;
39
40 static cmdalias_t *cmd_alias;
41
42 static qboolean cmd_wait;
43
44 static mempool_t *cmd_mempool;
45
46 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
47 static int cmd_tokenizebufferpos = 0;
48
49 //=============================================================================
50
51 /*
52 ============
53 Cmd_Wait_f
54
55 Causes execution of the remainder of the command buffer to be delayed until
56 next frame.  This allows commands like:
57 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
58 ============
59 */
60 static void Cmd_Wait_f (void)
61 {
62         cmd_wait = true;
63 }
64
65 /*
66 =============================================================================
67
68                                                 COMMAND BUFFER
69
70 =============================================================================
71 */
72
73 static sizebuf_t        cmd_text;
74 static unsigned char            cmd_text_buf[CMDBUFSIZE];
75
76 /*
77 ============
78 Cbuf_AddText
79
80 Adds command text at the end of the buffer
81 ============
82 */
83 void Cbuf_AddText (const char *text)
84 {
85         int             l;
86
87         l = (int)strlen (text);
88
89         if (cmd_text.cursize + l >= cmd_text.maxsize)
90         {
91                 Con_Print("Cbuf_AddText: overflow\n");
92                 return;
93         }
94
95         SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
96 }
97
98
99 /*
100 ============
101 Cbuf_InsertText
102
103 Adds command text immediately after the current command
104 Adds a \n to the text
105 FIXME: actually change the command buffer to do less copying
106 ============
107 */
108 void Cbuf_InsertText (const char *text)
109 {
110         char    *temp;
111         int             templen;
112
113         // copy off any commands still remaining in the exec buffer
114         templen = cmd_text.cursize;
115         if (templen)
116         {
117                 temp = (char *)Mem_Alloc (tempmempool, templen);
118                 memcpy (temp, cmd_text.data, templen);
119                 SZ_Clear (&cmd_text);
120         }
121         else
122                 temp = NULL;
123
124         // add the entire text of the file
125         Cbuf_AddText (text);
126
127         // add the copied off data
128         if (temp != NULL)
129         {
130                 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
131                 Mem_Free (temp);
132         }
133 }
134
135 /*
136 ============
137 Cbuf_Execute
138 ============
139 */
140 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
141 void Cbuf_Execute (void)
142 {
143         int i;
144         char *text;
145         char line[MAX_INPUTLINE];
146         char preprocessed[MAX_INPUTLINE];
147         int quotes;
148
149         // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
150         cmd_tokenizebufferpos = 0;
151
152         while (cmd_text.cursize)
153         {
154 // find a \n or ; line break
155                 text = (char *)cmd_text.data;
156
157                 quotes = 0;
158                 for (i=0 ; i< cmd_text.cursize ; i++)
159                 {
160                         if (text[i] == '"')
161                                 quotes ^= 1;
162                         if ( !quotes &&  text[i] == ';')
163                                 break;  // don't break if inside a quoted string
164                         if (text[i] == '\r' || text[i] == '\n')
165                                 break;
166                 }
167
168                 memcpy (line, text, i);
169                 line[i] = 0;
170
171 // delete the text from the command buffer and move remaining commands down
172 // this is necessary because commands (exec, alias) can insert data at the
173 // beginning of the text buffer
174
175                 if (i == cmd_text.cursize)
176                         cmd_text.cursize = 0;
177                 else
178                 {
179                         i++;
180                         cmd_text.cursize -= i;
181                         memcpy (cmd_text.data, text+i, cmd_text.cursize);
182                 }
183
184 // execute the command line
185                 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
186                 Cmd_ExecuteString (preprocessed, src_command);
187
188                 if (cmd_wait)
189                 {       // skip out while text still remains in buffer, leaving it
190                         // for next frame
191                         cmd_wait = false;
192                         break;
193                 }
194         }
195 }
196
197 /*
198 ==============================================================================
199
200                                                 SCRIPT COMMANDS
201
202 ==============================================================================
203 */
204
205 /*
206 ===============
207 Cmd_StuffCmds_f
208
209 Adds command line parameters as script statements
210 Commands lead with a +, and continue until a - or another +
211 quake +prog jctest.qp +cmd amlev1
212 quake -nosound +cmd amlev1
213 ===============
214 */
215 qboolean host_stuffcmdsrun = false;
216 void Cmd_StuffCmds_f (void)
217 {
218         int             i, j, l;
219         // this is for all commandline options combined (and is bounds checked)
220         char    build[MAX_INPUTLINE];
221
222         if (Cmd_Argc () != 1)
223         {
224                 Con_Print("stuffcmds : execute command line parameters\n");
225                 return;
226         }
227
228         // no reason to run the commandline arguments twice
229         if (host_stuffcmdsrun)
230                 return;
231
232         host_stuffcmdsrun = true;
233         build[0] = 0;
234         l = 0;
235         for (i = 0;i < com_argc;i++)
236         {
237                 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)
238                 {
239                         j = 1;
240                         while (com_argv[i][j])
241                                 build[l++] = com_argv[i][j++];
242                         i++;
243                         for (;i < com_argc;i++)
244                         {
245                                 if (!com_argv[i])
246                                         continue;
247                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
248                                         break;
249                                 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
250                                         break;
251                                 build[l++] = ' ';
252                                 if (strchr(com_argv[i], ' '))
253                                         build[l++] = '\"';
254                                 for (j = 0;com_argv[i][j];j++)
255                                         build[l++] = com_argv[i][j];
256                                 if (strchr(com_argv[i], ' '))
257                                         build[l++] = '\"';
258                         }
259                         build[l++] = '\n';
260                         i--;
261                 }
262         }
263         // now terminate the combined string and prepend it to the command buffer
264         // we already reserved space for the terminator
265         build[l++] = 0;
266         Cbuf_InsertText (build);
267 }
268
269
270 /*
271 ===============
272 Cmd_Exec_f
273 ===============
274 */
275 static void Cmd_Exec_f (void)
276 {
277         char *f;
278
279         if (Cmd_Argc () != 2)
280         {
281                 Con_Print("exec <filename> : execute a script file\n");
282                 return;
283         }
284
285         f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
286         if (!f)
287         {
288                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
289                 return;
290         }
291         Con_DPrintf("execing %s\n",Cmd_Argv(1));
292
293         // if executing default.cfg for the first time, lock the cvar defaults
294         // it may seem backwards to insert this text BEFORE the default.cfg
295         // but Cbuf_InsertText inserts before, so this actually ends up after it.
296         if (!strcmp(Cmd_Argv(1), "default.cfg"))
297                 Cbuf_InsertText("\ncvar_lockdefaults\n");
298
299         // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
300         // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
301         Cbuf_InsertText ("\n");
302         Cbuf_InsertText (f);
303         Mem_Free(f);
304 }
305
306
307 /*
308 ===============
309 Cmd_Echo_f
310
311 Just prints the rest of the line to the console
312 ===============
313 */
314 static void Cmd_Echo_f (void)
315 {
316         int             i;
317
318         for (i=1 ; i<Cmd_Argc() ; i++)
319                 Con_Printf("%s ",Cmd_Argv(i));
320         Con_Print("\n");
321 }
322
323 // DRESK - 4/24/07
324 /*
325 ===============
326 Cmd_ModelIndexList_f
327
328 List all models in the model index
329 ===============
330 */
331 static void Cmd_ModelIndexList_f(void)
332 {
333         int nModelIndexCnt = 3;
334
335         while(cl.model_precache[nModelIndexCnt])
336         { // Valid Model
337                 Con_Printf("%i : %s\n", nModelIndexCnt, cl.model_precache[nModelIndexCnt]->name);
338                 nModelIndexCnt++;
339         }
340 }
341
342 // DRESK - 5/14/06
343 // Support Doom3-style Toggle Console Command
344 /*
345 ===============
346 Cmd_Toggle_f
347
348 Toggles a specified console variable amongst the values specified (default is 0 and 1)
349 ===============
350 */
351 static void Cmd_Toggle_f(void)
352 {
353         // Acquire Number of Arguments
354         int nNumArgs = Cmd_Argc();
355
356         if(nNumArgs == 1)
357                 // No Arguments Specified; Print Usage
358                 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");
359         else
360         { // Correct Arguments Specified
361                 // Acquire Potential CVar
362                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
363
364                 if(cvCVar != NULL)
365                 { // Valid CVar
366                         if(nNumArgs == 2)
367                         { // Default Usage
368                                 if(cvCVar->integer)
369                                         Cvar_SetValueQuick(cvCVar, 0);
370                                 else
371                                         Cvar_SetValueQuick(cvCVar, 1);
372                         }
373                         else
374                         if(nNumArgs == 3)
375                         { // 0 and Specified Usage
376                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
377                                         // CVar is Specified Value; // Reset to 0
378                                         Cvar_SetValueQuick(cvCVar, 0);
379                                 else
380                                 if(cvCVar->integer == 0)
381                                         // CVar is 0; Specify Value
382                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
383                                 else
384                                         // CVar does not match; Reset to 0
385                                         Cvar_SetValueQuick(cvCVar, 0);
386                         }
387                         else
388                         { // Variable Values Specified
389                                 int nCnt;
390                                 int bFound = 0;
391
392                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
393                                 { // Cycle through Values
394                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
395                                         { // Current Value Located; Increment to Next
396                                                 if( (nCnt + 1) == nNumArgs)
397                                                         // Max Value Reached; Reset
398                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
399                                                 else
400                                                         // Next Value
401                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
402
403                                                 // End Loop
404                                                 nCnt = nNumArgs;
405                                                 // Assign Found
406                                                 bFound = 1;
407                                         }
408                                 }
409                                 if(!bFound)
410                                         // Value not Found; Reset to Original
411                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
412                         }
413
414                 }
415                 else
416                 { // Invalid CVar
417                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(2) );
418                 }
419         }
420 }
421
422 /*
423 ===============
424 Cmd_Alias_f
425
426 Creates a new command that executes a command string (possibly ; seperated)
427 ===============
428 */
429 static void Cmd_Alias_f (void)
430 {
431         cmdalias_t      *a;
432         char            cmd[MAX_INPUTLINE];
433         int                     i, c;
434         const char              *s;
435         size_t          alloclen;
436
437         if (Cmd_Argc() == 1)
438         {
439                 Con_Print("Current alias commands:\n");
440                 for (a = cmd_alias ; a ; a=a->next)
441                         Con_Printf("%s : %s\n", a->name, a->value);
442                 return;
443         }
444
445         s = Cmd_Argv(1);
446         if (strlen(s) >= MAX_ALIAS_NAME)
447         {
448                 Con_Print("Alias name is too long\n");
449                 return;
450         }
451
452         // if the alias already exists, reuse it
453         for (a = cmd_alias ; a ; a=a->next)
454         {
455                 if (!strcmp(s, a->name))
456                 {
457                         Z_Free (a->value);
458                         break;
459                 }
460         }
461
462         if (!a)
463         {
464                 cmdalias_t *prev, *current;
465
466                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
467                 strlcpy (a->name, s, sizeof (a->name));
468                 // insert it at the right alphanumeric position
469                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
470                         ;
471                 if( prev ) {
472                         prev->next = a;
473                 } else {
474                         cmd_alias = a;
475                 }
476                 a->next = current;
477         }
478
479
480 // copy the rest of the command line
481         cmd[0] = 0;             // start out with a null string
482         c = Cmd_Argc();
483         for (i=2 ; i< c ; i++)
484         {
485                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
486                 if (i != c)
487                         strlcat (cmd, " ", sizeof (cmd));
488         }
489         strlcat (cmd, "\n", sizeof (cmd));
490
491         alloclen = strlen (cmd) + 1;
492         a->value = (char *)Z_Malloc (alloclen);
493         memcpy (a->value, cmd, alloclen);
494 }
495
496 /*
497 =============================================================================
498
499                                         COMMAND EXECUTION
500
501 =============================================================================
502 */
503
504 typedef struct cmd_function_s
505 {
506         struct cmd_function_s *next;
507         const char *name;
508         const char *description;
509         xcommand_t consolefunction;
510         xcommand_t clientfunction;
511         qboolean csqcfunc;
512 } cmd_function_t;
513
514 static int cmd_argc;
515 static const char *cmd_argv[MAX_ARGS];
516 static const char *cmd_null_string = "";
517 static const char *cmd_args;
518 cmd_source_t cmd_source;
519
520
521 static cmd_function_t *cmd_functions;           // possible commands to execute
522
523 /*
524 Cmd_PreprocessString
525
526 Preprocesses strings and replaces $*, $param#, $cvar accordingly
527 */
528 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
529         const char *in;
530         unsigned outlen;
531         int inquote;
532
533         // don't crash if there's no room in the outtext buffer
534         if( maxoutlen == 0 ) {
535                 return;
536         }
537         maxoutlen--; // because of \0
538
539         in = intext;
540         outlen = 0;
541         inquote = 0;
542
543         while( *in && outlen < maxoutlen ) {
544                 if( *in == '$' && !inquote ) {
545                         // this is some kind of expansion, see what comes after the $
546                         in++;
547                         // replacements that can always be used:
548                         // $$ is replaced with $, to allow escaping $
549                         // $<cvarname> is replaced with the contents of the cvar
550                         //
551                         // the following can be used in aliases only:
552                         // $* is replaced with all formal parameters (including name of the alias - this probably is not desirable)
553                         // $0 is replaced with the name of this alias
554                         // $<number> is replaced with an argument to this alias (or copied as-is if no such parameter exists), can be multiple digits
555                         if( *in == '$' ) {
556                                 outtext[outlen++] = *in++;
557                         } else if( *in == '*' && alias ) {
558                                 const char *linein = Cmd_Args();
559
560                                 // include all parameters
561                                 if (linein) {
562                                         while( *linein && outlen < maxoutlen ) {
563                                                 outtext[outlen++] = *linein++;
564                                         }
565                                 }
566
567                                 in++;
568                         } else if( '0' <= *in && *in <= '9' && alias ) {
569                                 char *nexttoken;
570                                 int argnum;
571
572                                 argnum = strtol( in, &nexttoken, 10 );
573
574                                 if( 0 <= argnum && argnum < Cmd_Argc() ) {
575                                         const char *param = Cmd_Argv( argnum );
576                                         while( *param && outlen < maxoutlen ) {
577                                                 outtext[outlen++] = *param++;
578                                         }
579                                         in = nexttoken;
580                                 } else if( argnum >= Cmd_Argc() ) {
581                                         Con_Printf( "Warning: Not enough parameters passed to alias '%s', at least %i expected:\n    %s\n", alias->name, argnum, alias->value );
582                                         outtext[outlen++] = '$';
583                                 }
584                         } else {
585                                 cvar_t *cvar;
586                                 const char *tempin = in;
587
588                                 COM_ParseTokenConsole( &tempin );
589                                 // don't expand rcon_password or similar cvars (CVAR_PRIVATE flag)
590                                 if ((cvar = Cvar_FindVar(&com_token[0])) && !(cvar->flags & CVAR_PRIVATE)) {
591                                         const char *cvarcontent = cvar->string;
592                                         while( *cvarcontent && outlen < maxoutlen ) {
593                                                 outtext[outlen++] = *cvarcontent++;
594                                         }
595                                         in = tempin;
596                                 } else {
597                                         if( alias ) {
598                                                 Con_Printf( "Warning: could not find cvar %s when expanding alias %s\n    %s\n", com_token, alias->name, alias->value );
599                                         } else {
600                                                 Con_Printf( "Warning: could not find cvar %s\n", com_token );
601                                         }
602                                         outtext[outlen++] = '$';
603                                 }
604                         }
605                 } else {
606                         if( *in == '"' ) {
607                                 inquote ^= 1;
608                         }
609                         outtext[outlen++] = *in++;
610                 }
611         }
612         outtext[outlen] = 0;
613 }
614
615 /*
616 ============
617 Cmd_ExecuteAlias
618
619 Called for aliases and fills in the alias into the cbuffer
620 ============
621 */
622 static void Cmd_ExecuteAlias (cmdalias_t *alias)
623 {
624         static char buffer[ MAX_INPUTLINE + 2 ];
625         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
626         // insert at start of command buffer, so that aliases execute in order
627         // (fixes bug introduced by Black on 20050705)
628         Cbuf_InsertText( buffer );
629 }
630
631 /*
632 ========
633 Cmd_List
634
635         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
636         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
637
638 ========
639 */
640 static void Cmd_List_f (void)
641 {
642         cmd_function_t *cmd;
643         const char *partial;
644         int len, count;
645
646         if (Cmd_Argc() > 1)
647         {
648                 partial = Cmd_Argv (1);
649                 len = (int)strlen(partial);
650         }
651         else
652         {
653                 partial = NULL;
654                 len = 0;
655         }
656
657         count = 0;
658         for (cmd = cmd_functions; cmd; cmd = cmd->next)
659         {
660                 if (partial && strncmp(partial, cmd->name, len))
661                         continue;
662                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
663                 count++;
664         }
665
666         if (partial)
667                 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
668         else
669                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
670 }
671
672 /*
673 ============
674 Cmd_Init
675 ============
676 */
677 void Cmd_Init (void)
678 {
679         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
680         // space for commands and script files
681         cmd_text.data = cmd_text_buf;
682         cmd_text.maxsize = sizeof(cmd_text_buf);
683         cmd_text.cursize = 0;
684 }
685
686 void Cmd_Init_Commands (void)
687 {
688 //
689 // register our commands
690 //
691         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
692         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
693         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
694         Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
695         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
696         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
697         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
698         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
699
700         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
701         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
702         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
703         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
704
705         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");
706         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
707         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)");
708         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)");
709
710         // DRESK - 5/14/06
711         // Support Doom3-style Toggle Command
712         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
713         // Add Model Index List Command
714         Cmd_AddCommand("modelindexlist", Cmd_ModelIndexList_f, "lists all models in the modelindex");
715 }
716
717 /*
718 ============
719 Cmd_Shutdown
720 ============
721 */
722 void Cmd_Shutdown(void)
723 {
724         Mem_FreePool(&cmd_mempool);
725 }
726
727 /*
728 ============
729 Cmd_Argc
730 ============
731 */
732 int             Cmd_Argc (void)
733 {
734         return cmd_argc;
735 }
736
737 /*
738 ============
739 Cmd_Argv
740 ============
741 */
742 const char *Cmd_Argv (int arg)
743 {
744         if (arg >= cmd_argc )
745                 return cmd_null_string;
746         return cmd_argv[arg];
747 }
748
749 /*
750 ============
751 Cmd_Args
752 ============
753 */
754 const char *Cmd_Args (void)
755 {
756         return cmd_args;
757 }
758
759
760 /*
761 ============
762 Cmd_TokenizeString
763
764 Parses the given string into command line tokens.
765 ============
766 */
767 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
768 static void Cmd_TokenizeString (const char *text)
769 {
770         int l;
771
772         cmd_argc = 0;
773         cmd_args = NULL;
774
775         while (1)
776         {
777                 // skip whitespace up to a /n
778                 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
779                         text++;
780
781                 // line endings:
782                 // UNIX: \n
783                 // Mac: \r
784                 // Windows: \r\n
785                 if (*text == '\n' || *text == '\r')
786                 {
787                         // a newline separates commands in the buffer
788                         if (*text == '\r' && text[1] == '\n')
789                                 text++;
790                         text++;
791                         break;
792                 }
793
794                 if (!*text)
795                         return;
796
797                 if (cmd_argc == 1)
798                         cmd_args = text;
799
800                 if (!COM_ParseTokenConsole(&text))
801                         return;
802
803                 if (cmd_argc < MAX_ARGS)
804                 {
805                         l = (int)strlen(com_token) + 1;
806                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
807                         {
808                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
809                                 break;
810                         }
811                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
812                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
813                         cmd_tokenizebufferpos += l;
814                         cmd_argc++;
815                 }
816         }
817 }
818
819
820 /*
821 ============
822 Cmd_AddCommand
823 ============
824 */
825 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
826 {
827         cmd_function_t *cmd;
828         cmd_function_t *prev, *current;
829
830 // fail if the command is a variable name
831         if (Cvar_FindVar( cmd_name ))
832         {
833                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
834                 return;
835         }
836
837 // fail if the command already exists
838         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
839         {
840                 if (!strcmp (cmd_name, cmd->name))
841                 {
842                         if (consolefunction || clientfunction)
843                         {
844                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
845                                 return;
846                         }
847                         else    //[515]: csqc
848                         {
849                                 cmd->csqcfunc = true;
850                                 return;
851                         }
852                 }
853         }
854
855         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
856         cmd->name = cmd_name;
857         cmd->consolefunction = consolefunction;
858         cmd->clientfunction = clientfunction;
859         cmd->description = description;
860         if(!consolefunction && !clientfunction)                 //[515]: csqc
861                 cmd->csqcfunc = true;
862         cmd->next = cmd_functions;
863
864 // insert it at the right alphanumeric position
865         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
866                 ;
867         if( prev ) {
868                 prev->next = cmd;
869         } else {
870                 cmd_functions = cmd;
871         }
872         cmd->next = current;
873 }
874
875 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
876 {
877         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
878 }
879
880 /*
881 ============
882 Cmd_Exists
883 ============
884 */
885 qboolean Cmd_Exists (const char *cmd_name)
886 {
887         cmd_function_t  *cmd;
888
889         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
890                 if (!strcmp (cmd_name,cmd->name))
891                         return true;
892
893         return false;
894 }
895
896
897 /*
898 ============
899 Cmd_CompleteCommand
900 ============
901 */
902 const char *Cmd_CompleteCommand (const char *partial)
903 {
904         cmd_function_t *cmd;
905         size_t len;
906
907         len = strlen(partial);
908
909         if (!len)
910                 return NULL;
911
912 // check functions
913         for (cmd = cmd_functions; cmd; cmd = cmd->next)
914                 if (!strncasecmp(partial, cmd->name, len))
915                         return cmd->name;
916
917         return NULL;
918 }
919
920 /*
921         Cmd_CompleteCountPossible
922
923         New function for tab-completion system
924         Added by EvilTypeGuy
925         Thanks to Fett erich@heintz.com
926         Thanks to taniwha
927
928 */
929 int Cmd_CompleteCountPossible (const char *partial)
930 {
931         cmd_function_t *cmd;
932         size_t len;
933         int h;
934
935         h = 0;
936         len = strlen(partial);
937
938         if (!len)
939                 return 0;
940
941         // Loop through the command list and count all partial matches
942         for (cmd = cmd_functions; cmd; cmd = cmd->next)
943                 if (!strncasecmp(partial, cmd->name, len))
944                         h++;
945
946         return h;
947 }
948
949 /*
950         Cmd_CompleteBuildList
951
952         New function for tab-completion system
953         Added by EvilTypeGuy
954         Thanks to Fett erich@heintz.com
955         Thanks to taniwha
956
957 */
958 const char **Cmd_CompleteBuildList (const char *partial)
959 {
960         cmd_function_t *cmd;
961         size_t len = 0;
962         size_t bpos = 0;
963         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
964         const char **buf;
965
966         len = strlen(partial);
967         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
968         // Loop through the alias list and print all matches
969         for (cmd = cmd_functions; cmd; cmd = cmd->next)
970                 if (!strncasecmp(partial, cmd->name, len))
971                         buf[bpos++] = cmd->name;
972
973         buf[bpos] = NULL;
974         return buf;
975 }
976
977 // written by LordHavoc
978 void Cmd_CompleteCommandPrint (const char *partial)
979 {
980         cmd_function_t *cmd;
981         size_t len = strlen(partial);
982         // Loop through the command list and print all matches
983         for (cmd = cmd_functions; cmd; cmd = cmd->next)
984                 if (!strncasecmp(partial, cmd->name, len))
985                         Con_Printf("%s : %s\n", cmd->name, cmd->description);
986 }
987
988 /*
989         Cmd_CompleteAlias
990
991         New function for tab-completion system
992         Added by EvilTypeGuy
993         Thanks to Fett erich@heintz.com
994         Thanks to taniwha
995
996 */
997 const char *Cmd_CompleteAlias (const char *partial)
998 {
999         cmdalias_t *alias;
1000         size_t len;
1001
1002         len = strlen(partial);
1003
1004         if (!len)
1005                 return NULL;
1006
1007         // Check functions
1008         for (alias = cmd_alias; alias; alias = alias->next)
1009                 if (!strncasecmp(partial, alias->name, len))
1010                         return alias->name;
1011
1012         return NULL;
1013 }
1014
1015 // written by LordHavoc
1016 void Cmd_CompleteAliasPrint (const char *partial)
1017 {
1018         cmdalias_t *alias;
1019         size_t len = strlen(partial);
1020         // Loop through the alias list and print all matches
1021         for (alias = cmd_alias; alias; alias = alias->next)
1022                 if (!strncasecmp(partial, alias->name, len))
1023                         Con_Printf("%s : %s\n", alias->name, alias->value);
1024 }
1025
1026
1027 /*
1028         Cmd_CompleteAliasCountPossible
1029
1030         New function for tab-completion system
1031         Added by EvilTypeGuy
1032         Thanks to Fett erich@heintz.com
1033         Thanks to taniwha
1034
1035 */
1036 int Cmd_CompleteAliasCountPossible (const char *partial)
1037 {
1038         cmdalias_t      *alias;
1039         size_t          len;
1040         int                     h;
1041
1042         h = 0;
1043
1044         len = strlen(partial);
1045
1046         if (!len)
1047                 return 0;
1048
1049         // Loop through the command list and count all partial matches
1050         for (alias = cmd_alias; alias; alias = alias->next)
1051                 if (!strncasecmp(partial, alias->name, len))
1052                         h++;
1053
1054         return h;
1055 }
1056
1057 /*
1058         Cmd_CompleteAliasBuildList
1059
1060         New function for tab-completion system
1061         Added by EvilTypeGuy
1062         Thanks to Fett erich@heintz.com
1063         Thanks to taniwha
1064
1065 */
1066 const char **Cmd_CompleteAliasBuildList (const char *partial)
1067 {
1068         cmdalias_t *alias;
1069         size_t len = 0;
1070         size_t bpos = 0;
1071         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1072         const char **buf;
1073
1074         len = strlen(partial);
1075         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1076         // Loop through the alias list and print all matches
1077         for (alias = cmd_alias; alias; alias = alias->next)
1078                 if (!strncasecmp(partial, alias->name, len))
1079                         buf[bpos++] = alias->name;
1080
1081         buf[bpos] = NULL;
1082         return buf;
1083 }
1084
1085 void Cmd_ClearCsqcFuncs (void)
1086 {
1087         cmd_function_t *cmd;
1088         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1089                 cmd->csqcfunc = false;
1090 }
1091
1092 qboolean CL_VM_ConsoleCommand (const char *cmd);
1093 /*
1094 ============
1095 Cmd_ExecuteString
1096
1097 A complete command line has been parsed, so try to execute it
1098 FIXME: lookupnoadd the token to speed search?
1099 ============
1100 */
1101 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1102 {
1103         int oldpos;
1104         cmd_function_t *cmd;
1105         cmdalias_t *a;
1106
1107         oldpos = cmd_tokenizebufferpos;
1108         cmd_source = src;
1109
1110         Cmd_TokenizeString (text);
1111
1112 // execute the command line
1113         if (!Cmd_Argc())
1114         {
1115                 cmd_tokenizebufferpos = oldpos;
1116                 return;         // no tokens
1117         }
1118
1119 // check functions
1120         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1121         {
1122                 if (!strcasecmp (cmd_argv[0],cmd->name))
1123                 {
1124                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1125                                 return;
1126                         switch (src)
1127                         {
1128                         case src_command:
1129                                 if (cmd->consolefunction)
1130                                         cmd->consolefunction ();
1131                                 else if (cmd->clientfunction)
1132                                 {
1133                                         if (cls.state == ca_connected)
1134                                         {
1135                                                 // forward remote commands to the server for execution
1136                                                 Cmd_ForwardToServer();
1137                                         }
1138                                         else
1139                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1140                                 }
1141                                 else
1142                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1143                                 cmd_tokenizebufferpos = oldpos;
1144                                 return;
1145                         case src_client:
1146                                 if (cmd->clientfunction)
1147                                 {
1148                                         cmd->clientfunction ();
1149                                         cmd_tokenizebufferpos = oldpos;
1150                                         return;
1151                                 }
1152                                 break;
1153                         }
1154                         break;
1155                 }
1156         }
1157
1158         // if it's a client command and no command was found, say so.
1159         if (cmd_source == src_client)
1160         {
1161                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1162                 return;
1163         }
1164
1165 // check alias
1166         for (a=cmd_alias ; a ; a=a->next)
1167         {
1168                 if (!strcasecmp (cmd_argv[0], a->name))
1169                 {
1170                         Cmd_ExecuteAlias(a);
1171                         cmd_tokenizebufferpos = oldpos;
1172                         return;
1173                 }
1174         }
1175
1176 // check cvars
1177         if (!Cvar_Command () && host_framecount > 0)
1178                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1179
1180         cmd_tokenizebufferpos = oldpos;
1181 }
1182
1183
1184 /*
1185 ===================
1186 Cmd_ForwardStringToServer
1187
1188 Sends an entire command string over to the server, unprocessed
1189 ===================
1190 */
1191 void Cmd_ForwardStringToServer (const char *s)
1192 {
1193         char temp[128];
1194         if (cls.state != ca_connected)
1195         {
1196                 Con_Printf("Can't \"%s\", not connected\n", s);
1197                 return;
1198         }
1199
1200         if (!cls.netcon)
1201                 return;
1202
1203         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1204         // attention, it has been eradicated from here, its only (former) use in
1205         // all of darkplaces.
1206         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1207                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1208         else
1209                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1210         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1211         {
1212                 // say/say_team commands can replace % character codes with status info
1213                 while (*s)
1214                 {
1215                         if (*s == '%' && s[1])
1216                         {
1217                                 // handle proquake message macros
1218                                 temp[0] = 0;
1219                                 switch (s[1])
1220                                 {
1221                                 case 'l': // current location
1222                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1223                                         break;
1224                                 case 'h': // current health
1225                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1226                                         break;
1227                                 case 'a': // current armor
1228                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1229                                         break;
1230                                 case 'x': // current rockets
1231                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1232                                         break;
1233                                 case 'c': // current cells
1234                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1235                                         break;
1236                                 // silly proquake macros
1237                                 case 'd': // loc at last death
1238                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1239                                         break;
1240                                 case 't': // current time
1241                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1242                                         break;
1243                                 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1244                                         if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1245                                                 dpsnprintf(temp, sizeof(temp), "I need RL");
1246                                         else if (!cl.stats[STAT_ROCKETS])
1247                                                 dpsnprintf(temp, sizeof(temp), "I need rockets");
1248                                         else
1249                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
1250                                         break;
1251                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1252                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
1253                                         {
1254                                                 if (temp[0])
1255                                                         strlcat(temp, " ", sizeof(temp));
1256                                                 strlcat(temp, "quad", sizeof(temp));
1257                                         }
1258                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1259                                         {
1260                                                 if (temp[0])
1261                                                         strlcat(temp, " ", sizeof(temp));
1262                                                 strlcat(temp, "pent", sizeof(temp));
1263                                         }
1264                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1265                                         {
1266                                                 if (temp[0])
1267                                                         strlcat(temp, " ", sizeof(temp));
1268                                                 strlcat(temp, "eyes", sizeof(temp));
1269                                         }
1270                                         break;
1271                                 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1272                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1273                                                 strlcat(temp, "SSG", sizeof(temp));
1274                                         strlcat(temp, ":", sizeof(temp));
1275                                         if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1276                                                 strlcat(temp, "NG", sizeof(temp));
1277                                         strlcat(temp, ":", sizeof(temp));
1278                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1279                                                 strlcat(temp, "SNG", sizeof(temp));
1280                                         strlcat(temp, ":", sizeof(temp));
1281                                         if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1282                                                 strlcat(temp, "GL", sizeof(temp));
1283                                         strlcat(temp, ":", sizeof(temp));
1284                                         if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1285                                                 strlcat(temp, "RL", sizeof(temp));
1286                                         strlcat(temp, ":", sizeof(temp));
1287                                         if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1288                                                 strlcat(temp, "LG", sizeof(temp));
1289                                         break;
1290                                 default:
1291                                         // not a recognized macro, print it as-is...
1292                                         temp[0] = s[0];
1293                                         temp[1] = s[1];
1294                                         temp[2] = 0;
1295                                         break;
1296                                 }
1297                                 // write the resulting text
1298                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1299                                 s += 2;
1300                                 continue;
1301                         }
1302                         MSG_WriteByte(&cls.netcon->message, *s);
1303                         s++;
1304                 }
1305                 MSG_WriteByte(&cls.netcon->message, 0);
1306         }
1307         else // any other command is passed on as-is
1308                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1309 }
1310
1311 /*
1312 ===================
1313 Cmd_ForwardToServer
1314
1315 Sends the entire command line over to the server
1316 ===================
1317 */
1318 void Cmd_ForwardToServer (void)
1319 {
1320         const char *s;
1321         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1322         {
1323                 // we want to strip off "cmd", so just send the args
1324                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1325         }
1326         else
1327         {
1328                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1329                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1330         }
1331         // don't send an empty forward message if the user tries "cmd" by itself
1332         if (!s || !*s)
1333                 return;
1334         Cmd_ForwardStringToServer(s);
1335 }
1336
1337
1338 /*
1339 ================
1340 Cmd_CheckParm
1341
1342 Returns the position (1 to argc-1) in the command's argument list
1343 where the given parameter apears, or 0 if not present
1344 ================
1345 */
1346
1347 int Cmd_CheckParm (const char *parm)
1348 {
1349         int i;
1350
1351         if (!parm)
1352         {
1353                 Con_Printf ("Cmd_CheckParm: NULL");
1354                 return 0;
1355         }
1356
1357         for (i = 1; i < Cmd_Argc (); i++)
1358                 if (!strcasecmp (parm, Cmd_Argv (i)))
1359                         return i;
1360
1361         return 0;
1362 }
1363