]> icculus.org git repositories - divverent/darkplaces.git/blob - cmd.c
cleaned up almost all direct indexing of matrix4x4_t structures to go through proper...
[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 per command, and bounds checked (no buffer overflows)
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         host_stuffcmdsrun = true;
229         for (i = 0;i < com_argc;i++)
230         {
231                 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
232                 {
233                         l = 0;
234                         j = 1;
235                         while (com_argv[i][j])
236                                 build[l++] = com_argv[i][j++];
237                         i++;
238                         for (;i < com_argc;i++)
239                         {
240                                 if (!com_argv[i])
241                                         continue;
242                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
243                                         break;
244                                 if (l + strlen(com_argv[i]) + 5 > sizeof(build))
245                                         break;
246                                 build[l++] = ' ';
247                                 build[l++] = '\"';
248                                 for (j = 0;com_argv[i][j];j++)
249                                         build[l++] = com_argv[i][j];
250                                 build[l++] = '\"';
251                         }
252                         build[l++] = '\n';
253                         build[l++] = 0;
254                         Cbuf_InsertText (build);
255                         i--;
256                 }
257         }
258 }
259
260
261 /*
262 ===============
263 Cmd_Exec_f
264 ===============
265 */
266 static void Cmd_Exec_f (void)
267 {
268         char *f;
269
270         if (Cmd_Argc () != 2)
271         {
272                 Con_Print("exec <filename> : execute a script file\n");
273                 return;
274         }
275
276         f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
277         if (!f)
278         {
279                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
280                 return;
281         }
282         Con_DPrintf("execing %s\n",Cmd_Argv(1));
283
284         // if executing default.cfg for the first time, lock the cvar defaults
285         // it may seem backwards to insert this text BEFORE the default.cfg
286         // but Cbuf_InsertText inserts before, so this actually ends up after it.
287         if (!strcmp(Cmd_Argv(1), "default.cfg"))
288                 Cbuf_InsertText("\ncvar_lockdefaults\n");
289
290         Cbuf_InsertText (f);
291         Mem_Free(f);
292 }
293
294
295 /*
296 ===============
297 Cmd_Echo_f
298
299 Just prints the rest of the line to the console
300 ===============
301 */
302 static void Cmd_Echo_f (void)
303 {
304         int             i;
305
306         for (i=1 ; i<Cmd_Argc() ; i++)
307                 Con_Printf("%s ",Cmd_Argv(i));
308         Con_Print("\n");
309 }
310
311 // DRESK - 5/14/06
312 // Support Doom3-style Toggle Console Command
313 /*
314 ===============
315 Cmd_Toggle_f
316
317 Toggles a specified console variable amongst the values specified (default is 0 and 1)
318 ===============
319 */
320 static void Cmd_Toggle_f(void)
321 {
322         // Acquire Number of Arguments
323         int nNumArgs = Cmd_Argc();
324
325         if(nNumArgs == 1)
326                 // No Arguments Specified; Print Usage
327                 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");
328         else
329         { // Correct Arguments Specified
330                 // Acquire Potential CVar
331                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
332
333                 if(cvCVar != NULL)
334                 { // Valid CVar
335                         if(nNumArgs == 2)
336                         { // Default Usage
337                                 if(cvCVar->integer)
338                                         Cvar_SetValueQuick(cvCVar, 0);
339                                 else
340                                         Cvar_SetValueQuick(cvCVar, 1);
341                         }
342                         else
343                         if(nNumArgs == 3)
344                         { // 0 and Specified Usage
345                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
346                                         // CVar is Specified Value; // Reset to 0
347                                         Cvar_SetValueQuick(cvCVar, 0);
348                                 else
349                                 if(cvCVar->integer == 0)
350                                         // CVar is 0; Specify Value
351                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
352                                 else
353                                         // CVar does not match; Reset to 0
354                                         Cvar_SetValueQuick(cvCVar, 0);
355                         }
356                         else
357                         { // Variable Values Specified
358                                 int nCnt;
359                                 int bFound = 0;
360
361                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
362                                 { // Cycle through Values
363                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
364                                         { // Current Value Located; Increment to Next
365                                                 if( (nCnt + 1) == nNumArgs)
366                                                         // Max Value Reached; Reset
367                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
368                                                 else
369                                                         // Next Value
370                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
371
372                                                 // End Loop
373                                                 nCnt = nNumArgs;
374                                                 // Assign Found
375                                                 bFound = 1;
376                                         }
377                                 }
378                                 if(!bFound)
379                                         // Value not Found; Reset to Original
380                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
381                         }
382
383                 }
384                 else
385                 { // Invalid CVar
386                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(2) );
387                 }
388         }
389 }
390
391 /*
392 ===============
393 Cmd_Alias_f
394
395 Creates a new command that executes a command string (possibly ; seperated)
396 ===============
397 */
398 static void Cmd_Alias_f (void)
399 {
400         cmdalias_t      *a;
401         char            cmd[MAX_INPUTLINE];
402         int                     i, c;
403         const char              *s;
404         size_t          alloclen;
405
406         if (Cmd_Argc() == 1)
407         {
408                 Con_Print("Current alias commands:\n");
409                 for (a = cmd_alias ; a ; a=a->next)
410                         Con_Printf("%s : %s\n", a->name, a->value);
411                 return;
412         }
413
414         s = Cmd_Argv(1);
415         if (strlen(s) >= MAX_ALIAS_NAME)
416         {
417                 Con_Print("Alias name is too long\n");
418                 return;
419         }
420
421         // if the alias already exists, reuse it
422         for (a = cmd_alias ; a ; a=a->next)
423         {
424                 if (!strcmp(s, a->name))
425                 {
426                         Z_Free (a->value);
427                         break;
428                 }
429         }
430
431         if (!a)
432         {
433                 cmdalias_t *prev, *current;
434
435                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
436                 strlcpy (a->name, s, sizeof (a->name));
437                 // insert it at the right alphanumeric position
438                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
439                         ;
440                 if( prev ) {
441                         prev->next = a;
442                 } else {
443                         cmd_alias = a;
444                 }
445                 a->next = current;
446         }
447
448
449 // copy the rest of the command line
450         cmd[0] = 0;             // start out with a null string
451         c = Cmd_Argc();
452         for (i=2 ; i< c ; i++)
453         {
454                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
455                 if (i != c)
456                         strlcat (cmd, " ", sizeof (cmd));
457         }
458         strlcat (cmd, "\n", sizeof (cmd));
459
460         alloclen = strlen (cmd) + 1;
461         a->value = (char *)Z_Malloc (alloclen);
462         memcpy (a->value, cmd, alloclen);
463 }
464
465 /*
466 =============================================================================
467
468                                         COMMAND EXECUTION
469
470 =============================================================================
471 */
472
473 typedef struct cmd_function_s
474 {
475         struct cmd_function_s *next;
476         const char *name;
477         const char *description;
478         xcommand_t function;
479         qboolean csqcfunc;
480 } cmd_function_t;
481
482 static int cmd_argc;
483 static const char *cmd_argv[MAX_ARGS];
484 static const char *cmd_null_string = "";
485 static const char *cmd_args;
486 cmd_source_t cmd_source;
487
488
489 static cmd_function_t *cmd_functions;           // possible commands to execute
490
491 /*
492 Cmd_PreprocessString
493
494 Preprocesses strings and replaces $*, $param#, $cvar accordingly
495 */
496 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
497         const char *in;
498         unsigned outlen;
499         int inquote;
500
501         // don't crash if there's no room in the outtext buffer
502         if( maxoutlen == 0 ) {
503                 return;
504         }
505         maxoutlen--; // because of \0
506
507         in = intext;
508         outlen = 0;
509         inquote = 0;
510
511         while( *in && outlen < maxoutlen ) {
512                 if( *in == '$' && !inquote ) {
513                         // this is some kind of expansion, see what comes after the $
514                         in++;
515                         // replacements that can always be used:
516                         // $$ is replaced with $, to allow escaping $
517                         // $<cvarname> is replaced with the contents of the cvar
518                         //
519                         // the following can be used in aliases only:
520                         // $* is replaced with all formal parameters (including name of the alias - this probably is not desirable)
521                         // $0 is replaced with the name of this alias
522                         // $<number> is replaced with an argument to this alias (or copied as-is if no such parameter exists), can be multiple digits
523                         if( *in == '$' ) {
524                                 outtext[outlen++] = *in++;
525                         } else if( *in == '*' && alias ) {
526                                 const char *linein = Cmd_Args();
527
528                                 // include all parameters
529                                 if (linein) {
530                                         while( *linein && outlen < maxoutlen ) {
531                                                 outtext[outlen++] = *linein++;
532                                         }
533                                 }
534
535                                 in++;
536                         } else if( '0' <= *in && *in <= '9' && alias ) {
537                                 char *nexttoken;
538                                 int argnum;
539
540                                 argnum = strtol( in, &nexttoken, 10 );
541
542                                 if( 0 <= argnum && argnum < Cmd_Argc() ) {
543                                         const char *param = Cmd_Argv( argnum );
544                                         while( *param && outlen < maxoutlen ) {
545                                                 outtext[outlen++] = *param++;
546                                         }
547                                         in = nexttoken;
548                                 } else if( argnum >= Cmd_Argc() ) {
549                                         Con_Printf( "Warning: Not enough parameters passed to alias '%s', at least %i expected:\n    %s\n", alias->name, argnum, alias->value );
550                                         outtext[outlen++] = '$';
551                                 }
552                         } else {
553                                 cvar_t *cvar;
554                                 const char *tempin = in;
555
556                                 COM_ParseTokenConsole( &tempin );
557                                 // don't expand rcon_password or similar cvars (CVAR_PRIVATE flag)
558                                 if ((cvar = Cvar_FindVar(&com_token[0])) && !(cvar->flags & CVAR_PRIVATE)) {
559                                         const char *cvarcontent = cvar->string;
560                                         while( *cvarcontent && outlen < maxoutlen ) {
561                                                 outtext[outlen++] = *cvarcontent++;
562                                         }
563                                         in = tempin;
564                                 } else {
565                                         if( alias ) {
566                                                 Con_Printf( "Warning: could not find cvar %s when expanding alias %s\n    %s\n", com_token, alias->name, alias->value );
567                                         } else {
568                                                 Con_Printf( "Warning: could not find cvar %s\n", com_token );
569                                         }
570                                         outtext[outlen++] = '$';
571                                 }
572                         }
573                 } else {
574                         if( *in == '"' ) {
575                                 inquote ^= 1;
576                         }
577                         outtext[outlen++] = *in++;
578                 }
579         }
580         outtext[outlen] = 0;
581 }
582
583 /*
584 ============
585 Cmd_ExecuteAlias
586
587 Called for aliases and fills in the alias into the cbuffer
588 ============
589 */
590 static void Cmd_ExecuteAlias (cmdalias_t *alias)
591 {
592         static char buffer[ MAX_INPUTLINE + 2 ];
593         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
594         // insert at start of command buffer, so that aliases execute in order
595         // (fixes bug introduced by Black on 20050705)
596         Cbuf_InsertText( buffer );
597 }
598
599 /*
600 ========
601 Cmd_List
602
603         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
604         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
605
606 ========
607 */
608 static void Cmd_List_f (void)
609 {
610         cmd_function_t *cmd;
611         const char *partial;
612         int len, count;
613
614         if (Cmd_Argc() > 1)
615         {
616                 partial = Cmd_Argv (1);
617                 len = (int)strlen(partial);
618         }
619         else
620         {
621                 partial = NULL;
622                 len = 0;
623         }
624
625         count = 0;
626         for (cmd = cmd_functions; cmd; cmd = cmd->next)
627         {
628                 if (partial && strncmp(partial, cmd->name, len))
629                         continue;
630                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
631                 count++;
632         }
633
634         if (partial)
635                 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
636         else
637                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
638 }
639
640 /*
641 ============
642 Cmd_Init
643 ============
644 */
645 void Cmd_Init (void)
646 {
647         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
648         // space for commands and script files
649         cmd_text.data = cmd_text_buf;
650         cmd_text.maxsize = sizeof(cmd_text_buf);
651         cmd_text.cursize = 0;
652 }
653
654 void Cmd_Init_Commands (void)
655 {
656 //
657 // register our commands
658 //
659         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
660         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
661         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
662         Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
663         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
664         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
665         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
666         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
667
668         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
669         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
670         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
671         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
672
673         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");
674         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
675         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)");
676         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)");
677
678         // DRESK - 5/14/06
679         // Support Doom3-style Toggle Command
680         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
681 }
682
683 /*
684 ============
685 Cmd_Shutdown
686 ============
687 */
688 void Cmd_Shutdown(void)
689 {
690         Mem_FreePool(&cmd_mempool);
691 }
692
693 /*
694 ============
695 Cmd_Argc
696 ============
697 */
698 int             Cmd_Argc (void)
699 {
700         return cmd_argc;
701 }
702
703 /*
704 ============
705 Cmd_Argv
706 ============
707 */
708 const char *Cmd_Argv (int arg)
709 {
710         if (arg >= cmd_argc )
711                 return cmd_null_string;
712         return cmd_argv[arg];
713 }
714
715 /*
716 ============
717 Cmd_Args
718 ============
719 */
720 const char *Cmd_Args (void)
721 {
722         return cmd_args;
723 }
724
725
726 /*
727 ============
728 Cmd_TokenizeString
729
730 Parses the given string into command line tokens.
731 ============
732 */
733 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
734 static void Cmd_TokenizeString (const char *text)
735 {
736         int l;
737
738         cmd_argc = 0;
739         cmd_args = NULL;
740
741         while (1)
742         {
743                 // skip whitespace up to a /n
744                 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
745                         text++;
746
747                 // line endings:
748                 // UNIX: \n
749                 // Mac: \r
750                 // Windows: \r\n
751                 if (*text == '\n' || *text == '\r')
752                 {
753                         // a newline separates commands in the buffer
754                         if (*text == '\r' && text[1] == '\n')
755                                 text++;
756                         text++;
757                         break;
758                 }
759
760                 if (!*text)
761                         return;
762
763                 if (cmd_argc == 1)
764                         cmd_args = text;
765
766                 if (!COM_ParseTokenConsole(&text))
767                         return;
768
769                 if (cmd_argc < MAX_ARGS)
770                 {
771                         l = (int)strlen(com_token) + 1;
772                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
773                         {
774                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
775                                 break;
776                         }
777                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
778                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
779                         cmd_tokenizebufferpos += l;
780                         cmd_argc++;
781                 }
782         }
783 }
784
785
786 /*
787 ============
788 Cmd_AddCommand
789 ============
790 */
791 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
792 {
793         cmd_function_t *cmd;
794         cmd_function_t *prev, *current;
795
796 // fail if the command is a variable name
797         if (Cvar_FindVar( cmd_name ))
798         {
799                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
800                 return;
801         }
802
803 // fail if the command already exists
804         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
805         {
806                 if (!strcmp (cmd_name, cmd->name))
807                 {
808                         if (function)
809                         {
810                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
811                                 return;
812                         }
813                         else    //[515]: csqc
814                         {
815                                 cmd->csqcfunc = true;
816                                 return;
817                         }
818                 }
819         }
820
821         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
822         cmd->name = cmd_name;
823         cmd->function = function;
824         cmd->description = description;
825         if(!function)                   //[515]: csqc
826                 cmd->csqcfunc = true;
827         cmd->next = cmd_functions;
828
829 // insert it at the right alphanumeric position
830         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
831                 ;
832         if( prev ) {
833                 prev->next = cmd;
834         } else {
835                 cmd_functions = cmd;
836         }
837         cmd->next = current;
838 }
839
840 /*
841 ============
842 Cmd_Exists
843 ============
844 */
845 qboolean Cmd_Exists (const char *cmd_name)
846 {
847         cmd_function_t  *cmd;
848
849         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
850                 if (!strcmp (cmd_name,cmd->name))
851                         return true;
852
853         return false;
854 }
855
856
857 /*
858 ============
859 Cmd_CompleteCommand
860 ============
861 */
862 const char *Cmd_CompleteCommand (const char *partial)
863 {
864         cmd_function_t *cmd;
865         size_t len;
866
867         len = strlen(partial);
868
869         if (!len)
870                 return NULL;
871
872 // check functions
873         for (cmd = cmd_functions; cmd; cmd = cmd->next)
874                 if (!strncasecmp(partial, cmd->name, len))
875                         return cmd->name;
876
877         return NULL;
878 }
879
880 /*
881         Cmd_CompleteCountPossible
882
883         New function for tab-completion system
884         Added by EvilTypeGuy
885         Thanks to Fett erich@heintz.com
886         Thanks to taniwha
887
888 */
889 int Cmd_CompleteCountPossible (const char *partial)
890 {
891         cmd_function_t *cmd;
892         size_t len;
893         int h;
894
895         h = 0;
896         len = strlen(partial);
897
898         if (!len)
899                 return 0;
900
901         // Loop through the command list and count all partial matches
902         for (cmd = cmd_functions; cmd; cmd = cmd->next)
903                 if (!strncasecmp(partial, cmd->name, len))
904                         h++;
905
906         return h;
907 }
908
909 /*
910         Cmd_CompleteBuildList
911
912         New function for tab-completion system
913         Added by EvilTypeGuy
914         Thanks to Fett erich@heintz.com
915         Thanks to taniwha
916
917 */
918 const char **Cmd_CompleteBuildList (const char *partial)
919 {
920         cmd_function_t *cmd;
921         size_t len = 0;
922         size_t bpos = 0;
923         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
924         const char **buf;
925
926         len = strlen(partial);
927         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
928         // Loop through the alias list and print all matches
929         for (cmd = cmd_functions; cmd; cmd = cmd->next)
930                 if (!strncasecmp(partial, cmd->name, len))
931                         buf[bpos++] = cmd->name;
932
933         buf[bpos] = NULL;
934         return buf;
935 }
936
937 // written by LordHavoc
938 void Cmd_CompleteCommandPrint (const char *partial)
939 {
940         cmd_function_t *cmd;
941         size_t len = strlen(partial);
942         // Loop through the command list and print all matches
943         for (cmd = cmd_functions; cmd; cmd = cmd->next)
944                 if (!strncasecmp(partial, cmd->name, len))
945                         Con_Printf("%s : %s\n", cmd->name, cmd->description);
946 }
947
948 /*
949         Cmd_CompleteAlias
950
951         New function for tab-completion system
952         Added by EvilTypeGuy
953         Thanks to Fett erich@heintz.com
954         Thanks to taniwha
955
956 */
957 const char *Cmd_CompleteAlias (const char *partial)
958 {
959         cmdalias_t *alias;
960         size_t len;
961
962         len = strlen(partial);
963
964         if (!len)
965                 return NULL;
966
967         // Check functions
968         for (alias = cmd_alias; alias; alias = alias->next)
969                 if (!strncasecmp(partial, alias->name, len))
970                         return alias->name;
971
972         return NULL;
973 }
974
975 // written by LordHavoc
976 void Cmd_CompleteAliasPrint (const char *partial)
977 {
978         cmdalias_t *alias;
979         size_t len = strlen(partial);
980         // Loop through the alias list and print all matches
981         for (alias = cmd_alias; alias; alias = alias->next)
982                 if (!strncasecmp(partial, alias->name, len))
983                         Con_Printf("%s : %s\n", alias->name, alias->value);
984 }
985
986
987 /*
988         Cmd_CompleteAliasCountPossible
989
990         New function for tab-completion system
991         Added by EvilTypeGuy
992         Thanks to Fett erich@heintz.com
993         Thanks to taniwha
994
995 */
996 int Cmd_CompleteAliasCountPossible (const char *partial)
997 {
998         cmdalias_t      *alias;
999         size_t          len;
1000         int                     h;
1001
1002         h = 0;
1003
1004         len = strlen(partial);
1005
1006         if (!len)
1007                 return 0;
1008
1009         // Loop through the command list and count all partial matches
1010         for (alias = cmd_alias; alias; alias = alias->next)
1011                 if (!strncasecmp(partial, alias->name, len))
1012                         h++;
1013
1014         return h;
1015 }
1016
1017 /*
1018         Cmd_CompleteAliasBuildList
1019
1020         New function for tab-completion system
1021         Added by EvilTypeGuy
1022         Thanks to Fett erich@heintz.com
1023         Thanks to taniwha
1024
1025 */
1026 const char **Cmd_CompleteAliasBuildList (const char *partial)
1027 {
1028         cmdalias_t *alias;
1029         size_t len = 0;
1030         size_t bpos = 0;
1031         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1032         const char **buf;
1033
1034         len = strlen(partial);
1035         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1036         // Loop through the alias list and print all matches
1037         for (alias = cmd_alias; alias; alias = alias->next)
1038                 if (!strncasecmp(partial, alias->name, len))
1039                         buf[bpos++] = alias->name;
1040
1041         buf[bpos] = NULL;
1042         return buf;
1043 }
1044
1045 void Cmd_ClearCsqcFuncs (void)
1046 {
1047         cmd_function_t *cmd;
1048         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1049                 cmd->csqcfunc = false;
1050 }
1051
1052 qboolean CL_VM_ConsoleCommand (const char *cmd);
1053 /*
1054 ============
1055 Cmd_ExecuteString
1056
1057 A complete command line has been parsed, so try to execute it
1058 FIXME: lookupnoadd the token to speed search?
1059 ============
1060 */
1061 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1062 {
1063         int oldpos;
1064         cmd_function_t *cmd;
1065         cmdalias_t *a;
1066
1067         oldpos = cmd_tokenizebufferpos;
1068         cmd_source = src;
1069
1070         Cmd_TokenizeString (text);
1071
1072 // execute the command line
1073         if (!Cmd_Argc())
1074         {
1075                 cmd_tokenizebufferpos = oldpos;
1076                 return;         // no tokens
1077         }
1078
1079 // check functions
1080         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1081         {
1082                 if (!strcasecmp (cmd_argv[0],cmd->name))
1083                 {
1084                         if(cmd->function && !cmd->csqcfunc)
1085                                 cmd->function ();
1086                         else
1087                                 if(CL_VM_ConsoleCommand (text)) //[515]: csqc
1088                                         return;
1089                                 else
1090                                         if(cmd->function)
1091                                                 cmd->function ();
1092                         cmd_tokenizebufferpos = oldpos;
1093                         return;
1094                 }
1095         }
1096
1097 // check alias
1098         for (a=cmd_alias ; a ; a=a->next)
1099         {
1100                 if (!strcasecmp (cmd_argv[0], a->name))
1101                 {
1102                         Cmd_ExecuteAlias(a);
1103                         cmd_tokenizebufferpos = oldpos;
1104                         return;
1105                 }
1106         }
1107
1108 // check cvars
1109         if (!Cvar_Command () && host_framecount > 0)
1110                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1111
1112         cmd_tokenizebufferpos = oldpos;
1113 }
1114
1115
1116 /*
1117 ===================
1118 Cmd_ForwardStringToServer
1119
1120 Sends an entire command string over to the server, unprocessed
1121 ===================
1122 */
1123 void Cmd_ForwardStringToServer (const char *s)
1124 {
1125         if (cls.state != ca_connected)
1126         {
1127                 Con_Printf("Can't \"%s\", not connected\n", s);
1128                 return;
1129         }
1130
1131         if (!cls.netcon)
1132                 return;
1133
1134         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1135         // attention, it has been eradicated from here, its only (former) use in
1136         // all of darkplaces.
1137         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1138                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1139         else
1140                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1141         SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1142 }
1143
1144 /*
1145 ===================
1146 Cmd_ForwardToServer
1147
1148 Sends the entire command line over to the server
1149 ===================
1150 */
1151 void Cmd_ForwardToServer (void)
1152 {
1153         const char *s;
1154         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1155         {
1156                 // we want to strip off "cmd", so just send the args
1157                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1158         }
1159         else
1160         {
1161                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1162                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1163         }
1164         // don't send an empty forward message if the user tries "cmd" by itself
1165         if (!s || !*s)
1166                 return;
1167         Cmd_ForwardStringToServer(s);
1168 }
1169
1170
1171 /*
1172 ================
1173 Cmd_CheckParm
1174
1175 Returns the position (1 to argc-1) in the command's argument list
1176 where the given parameter apears, or 0 if not present
1177 ================
1178 */
1179
1180 int Cmd_CheckParm (const char *parm)
1181 {
1182         int i;
1183
1184         if (!parm)
1185         {
1186                 Con_Printf ("Cmd_CheckParm: NULL");
1187                 return 0;
1188         }
1189
1190         for (i = 1; i < Cmd_Argc (); i++)
1191                 if (!strcasecmp (parm, Cmd_Argv (i)))
1192                         return i;
1193
1194         return 0;
1195 }
1196