2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // cmd.c -- Quake script command processing module
25 cmd_state_t cmd_client;
26 cmd_state_t cmd_server;
27 cmd_state_t cmd_serverfromclient;
29 cmd_userdefined_t cmd_userdefined_all;
30 cmd_userdefined_t cmd_userdefined_null;
32 typedef struct cmd_iter_s {
37 static cmd_iter_t cmd_iter_all[] = {
40 {&cmd_serverfromclient},
45 // we only run the +whatever commandline arguments once
46 qboolean host_stuffcmdsrun = false;
48 //=============================================================================
50 void Cbuf_Lock(cmd_state_t *cmd)
52 Thread_AtomicLock(&cmd->text_lock);
55 void Cbuf_Unlock(cmd_state_t *cmd)
57 Thread_AtomicUnlock(&cmd->text_lock);
65 Causes execution of the remainder of the command buffer to be delayed until
66 next frame. This allows commands like:
67 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
70 static void Cmd_Wait_f (cmd_state_t *cmd)
79 Cause a command to be executed after a delay.
82 static void Cmd_Defer_f (cmd_state_t *cmd)
84 if(Cmd_Argc(cmd) == 1)
86 cmddeferred_t *next = cmd->deferred_list;
88 Con_Printf("No commands are pending.\n");
91 Con_Printf("-> In %9.2f: %s\n", next->delay, next->value);
94 } else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
96 while(cmd->deferred_list)
98 cmddeferred_t *defcmd = cmd->deferred_list;
99 cmd->deferred_list = defcmd->next;
100 Mem_Free(defcmd->value);
103 } else if(Cmd_Argc(cmd) == 3)
105 const char *value = Cmd_Argv(cmd, 2);
106 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
107 size_t len = strlen(value);
109 defcmd->delay = atof(Cmd_Argv(cmd, 1));
110 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
111 memcpy(defcmd->value, value, len+1);
114 if(cmd->deferred_list)
116 cmddeferred_t *next = cmd->deferred_list;
121 cmd->deferred_list = defcmd;
122 /* Stupid me... this changes the order... so commands with the same delay go blub :S
123 defcmd->next = cmd_deferred_list;
124 cmd_deferred_list = defcmd;*/
126 Con_Printf("usage: defer <seconds> <command>\n"
136 Print something to the center of the screen using SCR_Centerprint
139 static void Cmd_Centerprint_f (cmd_state_t *cmd)
141 char msg[MAX_INPUTLINE];
142 unsigned int i, c, p;
146 strlcpy(msg, Cmd_Argv(cmd,1), sizeof(msg));
147 for(i = 2; i < c; ++i)
149 strlcat(msg, " ", sizeof(msg));
150 strlcat(msg, Cmd_Argv(cmd, i), sizeof(msg));
152 c = (unsigned int)strlen(msg);
153 for(p = 0, i = 0; i < c; ++i)
159 else if(msg[i+1] == '\\')
171 SCR_CenterPrint(msg);
176 =============================================================================
180 =============================================================================
187 Adds command text at the end of the buffer
190 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
194 l = (int)strlen(text);
197 if (cmd->text.maxsize - cmd->text.cursize <= l)
198 Con_Print("Cbuf_AddText: overflow\n");
200 SZ_Write(&cmd->text, (const unsigned char *)text, l);
209 Adds command text immediately after the current command
210 Adds a \n to the text
211 FIXME: actually change the command buffer to do less copying
214 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
216 size_t l = strlen(text);
218 // we need to memmove the existing text and stuff this in before it...
219 if (cmd->text.cursize + l >= (size_t)cmd->text.maxsize)
220 Con_Print("Cbuf_InsertText: overflow\n");
223 // we don't have a SZ_Prepend, so...
224 memmove(cmd->text.data + l, cmd->text.data, cmd->text.cursize);
225 cmd->text.cursize += (int)l;
226 memcpy(cmd->text.data, text, l);
233 Cbuf_Execute_Deferred --blub
236 static void Cbuf_Execute_Deferred (cmd_state_t *cmd)
238 cmddeferred_t *defcmd, *prev;
240 if (realtime - cmd->deferred_oldrealtime < 0 || realtime - cmd->deferred_oldrealtime > 1800) cmd->deferred_oldrealtime = realtime;
241 eat = realtime - cmd->deferred_oldrealtime;
242 if (eat < (1.0 / 120.0))
244 cmd->deferred_oldrealtime = realtime;
246 defcmd = cmd->deferred_list;
249 defcmd->delay -= eat;
250 if(defcmd->delay <= 0)
252 Cbuf_AddText(cmd, defcmd->value);
253 Cbuf_AddText(cmd, ";\n");
254 Mem_Free(defcmd->value);
257 prev->next = defcmd->next;
261 cmd->deferred_list = defcmd->next;
263 defcmd = cmd->deferred_list;
268 defcmd = defcmd->next;
277 static qboolean Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
278 void Cbuf_Execute (cmd_state_t *cmd)
282 char line[MAX_INPUTLINE];
283 char preprocessed[MAX_INPUTLINE];
288 // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
289 cmd->tokenizebufferpos = 0;
291 while (cmd->text.cursize)
293 // find a \n or ; line break
294 text = (char *)cmd->text.data;
298 for (i=0 ; i < cmd->text.cursize ; i++)
307 // make sure i doesn't get > cursize which causes a negative
308 // size in memmove, which is fatal --blub
309 if (i < (cmd->text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
314 if(text[i] == '/' && text[i + 1] == '/' && (i == 0 || ISWHITESPACE(text[i-1])))
317 break; // don't break if inside a quoted string or comment
321 if (text[i] == '\r' || text[i] == '\n')
325 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
326 if(i >= MAX_INPUTLINE)
328 Con_Warnf("Warning: console input buffer had an overlong line. Ignored.\n");
333 memcpy (line, text, comment ? (comment - text) : i);
334 line[comment ? (comment - text) : i] = 0;
337 // delete the text from the command buffer and move remaining commands down
338 // this is necessary because commands (exec, alias) can insert data at the
339 // beginning of the text buffer
341 if (i == cmd->text.cursize)
342 cmd->text.cursize = 0;
346 cmd->text.cursize -= i;
347 memmove (cmd->text.data, text+i, cmd->text.cursize);
350 // execute the command line
352 while(*firstchar && ISWHITESPACE(*firstchar))
355 (strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5]))
357 (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4]))
359 (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7]))
362 if(Cmd_PreprocessString( cmd, line, preprocessed, sizeof(preprocessed), NULL ))
363 Cmd_ExecuteString (cmd, preprocessed, src_command, false);
367 Cmd_ExecuteString (cmd, line, src_command, false);
371 { // skip out while text still remains in buffer, leaving it
379 void Cbuf_Frame(cmd_state_t *cmd)
381 Cbuf_Execute_Deferred(cmd);
382 if (cmd->text.cursize)
384 SV_LockThreadMutex();
386 SV_UnlockThreadMutex();
391 ==============================================================================
395 ==============================================================================
398 extern qboolean host_init;
404 Adds command line parameters as script statements
405 Commands lead with a +, and continue until a - or another +
406 quake +prog jctest.qp +cmd amlev1
407 quake -nosound +cmd amlev1
410 static void Cmd_StuffCmds_f (cmd_state_t *cmd)
413 // this is for all commandline options combined (and is bounds checked)
414 char build[MAX_INPUTLINE];
416 // come back later so we don't crash
420 if (Cmd_Argc (cmd) != 1)
422 Con_Print("stuffcmds : execute command line parameters\n");
426 // no reason to run the commandline arguments twice
427 if (host_stuffcmdsrun)
430 host_stuffcmdsrun = true;
433 for (i = 0;i < com_argc;i++)
435 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)
438 while (com_argv[i][j])
439 build[l++] = com_argv[i][j++];
441 for (;i < com_argc;i++)
445 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
447 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
450 if (strchr(com_argv[i], ' '))
452 for (j = 0;com_argv[i][j];j++)
453 build[l++] = com_argv[i][j];
454 if (strchr(com_argv[i], ' '))
461 // now terminate the combined string and prepend it to the command buffer
462 // we already reserved space for the terminator
464 Cbuf_InsertText (cmd, build);
467 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
470 size_t filenameLen = strlen(filename);
471 qboolean isdefaultcfg =
472 !strcmp(filename, "default.cfg") ||
473 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
475 if (!strcmp(filename, "config.cfg"))
477 filename = CONFIGFILENAME;
478 if (COM_CheckParm("-noconfig"))
479 return; // don't execute config.cfg
482 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
485 Con_Printf("couldn't exec %s\n",filename);
488 Con_Printf("execing %s\n",filename);
490 // if executing default.cfg for the first time, lock the cvar defaults
491 // it may seem backwards to insert this text BEFORE the default.cfg
492 // but Cbuf_InsertText inserts before, so this actually ends up after it.
494 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
496 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
497 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
498 Cbuf_InsertText (cmd, "\n");
499 Cbuf_InsertText (cmd, f);
504 // special defaults for specific games go here, these execute before default.cfg
505 // Nehahra pushable crates malfunction in some levels if this is on
506 // Nehahra NPC AI is confused by blowupfallenzombies
510 Cbuf_InsertText(cmd, "\n"
511 "sv_gameplayfix_blowupfallenzombies 0\n"
512 "sv_gameplayfix_findradiusdistancetobox 0\n"
513 "sv_gameplayfix_grenadebouncedownslopes 0\n"
514 "sv_gameplayfix_slidemoveprojectiles 0\n"
515 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
516 "sv_gameplayfix_setmodelrealbox 0\n"
517 "sv_gameplayfix_droptofloorstartsolid 0\n"
518 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
519 "sv_gameplayfix_noairborncorpse 0\n"
520 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
521 "sv_gameplayfix_easierwaterjump 0\n"
522 "sv_gameplayfix_delayprojectiles 0\n"
523 "sv_gameplayfix_multiplethinksperframe 0\n"
524 "sv_gameplayfix_fixedcheckwatertransition 0\n"
525 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
526 "sv_gameplayfix_swiminbmodels 0\n"
527 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
528 "sys_ticrate 0.01388889\n"
530 "r_shadow_bumpscale_basetexture 0\n"
531 "csqc_polygons_defaultmaterial_nocullface 0\n"
535 Cbuf_InsertText(cmd, "\n"
536 "sv_gameplayfix_blowupfallenzombies 0\n"
537 "sv_gameplayfix_findradiusdistancetobox 0\n"
538 "sv_gameplayfix_grenadebouncedownslopes 0\n"
539 "sv_gameplayfix_slidemoveprojectiles 0\n"
540 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
541 "sv_gameplayfix_setmodelrealbox 0\n"
542 "sv_gameplayfix_droptofloorstartsolid 0\n"
543 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
544 "sv_gameplayfix_noairborncorpse 0\n"
545 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
546 "sv_gameplayfix_easierwaterjump 0\n"
547 "sv_gameplayfix_delayprojectiles 0\n"
548 "sv_gameplayfix_multiplethinksperframe 0\n"
549 "sv_gameplayfix_fixedcheckwatertransition 0\n"
550 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
551 "sv_gameplayfix_swiminbmodels 0\n"
552 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
553 "sys_ticrate 0.01388889\n"
555 "r_shadow_bumpscale_basetexture 0\n"
556 "csqc_polygons_defaultmaterial_nocullface 0\n"
559 // hipnotic mission pack has issues in their 'friendly monster' ai, which seem to attempt to attack themselves for some reason when findradius() returns non-solid entities.
560 // hipnotic mission pack has issues with bobbing water entities 'jittering' between different heights on alternate frames at the default 0.0138889 ticrate, 0.02 avoids this issue
561 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
564 Cbuf_InsertText(cmd, "\n"
565 "sv_gameplayfix_blowupfallenzombies 0\n"
566 "sv_gameplayfix_findradiusdistancetobox 0\n"
567 "sv_gameplayfix_grenadebouncedownslopes 0\n"
568 "sv_gameplayfix_slidemoveprojectiles 0\n"
569 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
570 "sv_gameplayfix_setmodelrealbox 0\n"
571 "sv_gameplayfix_droptofloorstartsolid 0\n"
572 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
573 "sv_gameplayfix_noairborncorpse 0\n"
574 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
575 "sv_gameplayfix_easierwaterjump 0\n"
576 "sv_gameplayfix_delayprojectiles 0\n"
577 "sv_gameplayfix_multiplethinksperframe 0\n"
578 "sv_gameplayfix_fixedcheckwatertransition 0\n"
579 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
580 "sv_gameplayfix_swiminbmodels 0\n"
581 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
584 "r_shadow_bumpscale_basetexture 0\n"
585 "csqc_polygons_defaultmaterial_nocullface 0\n"
588 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
590 Cbuf_InsertText(cmd, "\n"
591 "sv_gameplayfix_blowupfallenzombies 0\n"
592 "sv_gameplayfix_findradiusdistancetobox 0\n"
593 "sv_gameplayfix_grenadebouncedownslopes 0\n"
594 "sv_gameplayfix_slidemoveprojectiles 0\n"
595 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
596 "sv_gameplayfix_setmodelrealbox 0\n"
597 "sv_gameplayfix_droptofloorstartsolid 0\n"
598 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
599 "sv_gameplayfix_noairborncorpse 0\n"
600 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
601 "sv_gameplayfix_easierwaterjump 0\n"
602 "sv_gameplayfix_delayprojectiles 0\n"
603 "sv_gameplayfix_multiplethinksperframe 0\n"
604 "sv_gameplayfix_fixedcheckwatertransition 0\n"
605 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
606 "sv_gameplayfix_swiminbmodels 0\n"
607 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
608 "sys_ticrate 0.01388889\n"
610 "r_shadow_bumpscale_basetexture 0\n"
611 "csqc_polygons_defaultmaterial_nocullface 0\n"
615 Cbuf_InsertText(cmd, "\n"
616 "sv_gameplayfix_blowupfallenzombies 0\n"
617 "sv_gameplayfix_findradiusdistancetobox 0\n"
618 "sv_gameplayfix_grenadebouncedownslopes 0\n"
619 "sv_gameplayfix_slidemoveprojectiles 0\n"
620 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
621 "sv_gameplayfix_setmodelrealbox 0\n"
622 "sv_gameplayfix_droptofloorstartsolid 0\n"
623 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
624 "sv_gameplayfix_noairborncorpse 0\n"
625 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
626 "sv_gameplayfix_easierwaterjump 0\n"
627 "sv_gameplayfix_delayprojectiles 0\n"
628 "sv_gameplayfix_multiplethinksperframe 0\n"
629 "sv_gameplayfix_fixedcheckwatertransition 0\n"
630 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
631 "sv_gameplayfix_swiminbmodels 0\n"
632 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
633 "sys_ticrate 0.01388889\n"
635 "r_shadow_bumpscale_basetexture 4\n"
636 "csqc_polygons_defaultmaterial_nocullface 0\n"
640 Cbuf_InsertText(cmd, "\n"
641 "sv_gameplayfix_blowupfallenzombies 1\n"
642 "sv_gameplayfix_findradiusdistancetobox 1\n"
643 "sv_gameplayfix_grenadebouncedownslopes 1\n"
644 "sv_gameplayfix_slidemoveprojectiles 1\n"
645 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
646 "sv_gameplayfix_setmodelrealbox 1\n"
647 "sv_gameplayfix_droptofloorstartsolid 1\n"
648 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
649 "sv_gameplayfix_noairborncorpse 1\n"
650 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
651 "sv_gameplayfix_easierwaterjump 1\n"
652 "sv_gameplayfix_delayprojectiles 1\n"
653 "sv_gameplayfix_multiplethinksperframe 1\n"
654 "sv_gameplayfix_fixedcheckwatertransition 1\n"
655 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
656 "sv_gameplayfix_swiminbmodels 1\n"
657 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
658 "sys_ticrate 0.01388889\n"
659 "sv_gameplayfix_q2airaccelerate 1\n"
660 "sv_gameplayfix_stepmultipletimes 1\n"
661 "csqc_polygons_defaultmaterial_nocullface 1\n"
662 "con_chatsound_team_mask 13\n"
666 case GAME_VORETOURNAMENT:
667 // compatibility for versions prior to 2020-05-25, this can be overridden in newer versions to get the default behavior and be consistent with FTEQW engine
668 Cbuf_InsertText(cmd, "\n"
669 "csqc_polygons_defaultmaterial_nocullface 1\n"
670 "con_chatsound_team_mask 13\n"
673 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
674 case GAME_STEELSTORM:
675 Cbuf_InsertText(cmd, "\n"
676 "sv_gameplayfix_blowupfallenzombies 1\n"
677 "sv_gameplayfix_findradiusdistancetobox 1\n"
678 "sv_gameplayfix_grenadebouncedownslopes 1\n"
679 "sv_gameplayfix_slidemoveprojectiles 1\n"
680 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
681 "sv_gameplayfix_setmodelrealbox 1\n"
682 "sv_gameplayfix_droptofloorstartsolid 1\n"
683 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
684 "sv_gameplayfix_noairborncorpse 1\n"
685 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
686 "sv_gameplayfix_easierwaterjump 1\n"
687 "sv_gameplayfix_delayprojectiles 1\n"
688 "sv_gameplayfix_multiplethinksperframe 1\n"
689 "sv_gameplayfix_fixedcheckwatertransition 1\n"
690 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
691 "sv_gameplayfix_swiminbmodels 1\n"
692 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
693 "sys_ticrate 0.01388889\n"
694 "cl_csqc_generatemousemoveevents 0\n"
695 "csqc_polygons_defaultmaterial_nocullface 1\n"
699 Cbuf_InsertText(cmd, "\n"
700 "sv_gameplayfix_blowupfallenzombies 1\n"
701 "sv_gameplayfix_findradiusdistancetobox 1\n"
702 "sv_gameplayfix_grenadebouncedownslopes 1\n"
703 "sv_gameplayfix_slidemoveprojectiles 1\n"
704 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
705 "sv_gameplayfix_setmodelrealbox 1\n"
706 "sv_gameplayfix_droptofloorstartsolid 1\n"
707 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
708 "sv_gameplayfix_noairborncorpse 1\n"
709 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
710 "sv_gameplayfix_easierwaterjump 1\n"
711 "sv_gameplayfix_delayprojectiles 1\n"
712 "sv_gameplayfix_multiplethinksperframe 1\n"
713 "sv_gameplayfix_fixedcheckwatertransition 1\n"
714 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
715 "sv_gameplayfix_swiminbmodels 1\n"
716 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
717 "sys_ticrate 0.01388889\n"
718 "csqc_polygons_defaultmaterial_nocullface 0\n"
730 static void Cmd_Exec_f (cmd_state_t *cmd)
735 if (Cmd_Argc(cmd) != 2)
737 Con_Print("exec <filename> : execute a script file\n");
741 s = FS_Search(Cmd_Argv(cmd, 1), true, true);
742 if(!s || !s->numfilenames)
744 Con_Printf("couldn't exec %s\n",Cmd_Argv(cmd, 1));
748 for(i = 0; i < s->numfilenames; ++i)
749 Cmd_Exec(cmd, s->filenames[i]);
759 Just prints the rest of the line to the console
762 static void Cmd_Echo_f (cmd_state_t *cmd)
766 for (i=1 ; i<Cmd_Argc(cmd) ; i++)
767 Con_Printf("%s ",Cmd_Argv(cmd, i));
772 // Support Doom3-style Toggle Console Command
777 Toggles a specified console variable amongst the values specified (default is 0 and 1)
780 static void Cmd_Toggle_f(cmd_state_t *cmd)
782 // Acquire Number of Arguments
783 int nNumArgs = Cmd_Argc(cmd);
786 // No Arguments Specified; Print Usage
787 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");
789 { // Correct Arguments Specified
790 // Acquire Potential CVar
791 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
798 Cvar_SetValueQuick(cvCVar, 0);
800 Cvar_SetValueQuick(cvCVar, 1);
804 { // 0 and Specified Usage
805 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
806 // CVar is Specified Value; // Reset to 0
807 Cvar_SetValueQuick(cvCVar, 0);
809 if(cvCVar->integer == 0)
810 // CVar is 0; Specify Value
811 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
813 // CVar does not match; Reset to 0
814 Cvar_SetValueQuick(cvCVar, 0);
817 { // Variable Values Specified
821 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
822 { // Cycle through Values
823 if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
824 { // Current Value Located; Increment to Next
825 if( (nCnt + 1) == nNumArgs)
826 // Max Value Reached; Reset
827 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
830 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
839 // Value not Found; Reset to Original
840 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
846 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
855 Creates a new command that executes a command string (possibly ; seperated)
858 static void Cmd_Alias_f (cmd_state_t *cmd)
861 char line[MAX_INPUTLINE];
866 if (Cmd_Argc(cmd) == 1)
868 Con_Print("Current alias commands:\n");
869 for (a = cmd->userdefined->alias ; a ; a=a->next)
870 Con_Printf("%s : %s", a->name, a->value);
874 s = Cmd_Argv(cmd, 1);
875 if (strlen(s) >= MAX_ALIAS_NAME)
877 Con_Print("Alias name is too long\n");
881 // if the alias already exists, reuse it
882 for (a = cmd->userdefined->alias ; a ; a=a->next)
884 if (!strcmp(s, a->name))
893 cmdalias_t *prev, *current;
895 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
896 strlcpy (a->name, s, sizeof (a->name));
897 // insert it at the right alphanumeric position
898 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
903 cmd->userdefined->alias = a;
909 // copy the rest of the command line
910 line[0] = 0; // start out with a null string
912 for (i=2 ; i < c ; i++)
915 strlcat (line, " ", sizeof (line));
916 strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
918 strlcat (line, "\n", sizeof (line));
920 alloclen = strlen (line) + 1;
922 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
923 a->value = (char *)Z_Malloc (alloclen);
924 memcpy (a->value, line, alloclen);
931 Remove existing aliases.
934 static void Cmd_UnAlias_f (cmd_state_t *cmd)
940 if(Cmd_Argc(cmd) == 1)
942 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
946 for(i = 1; i < Cmd_Argc(cmd); ++i)
948 s = Cmd_Argv(cmd, i);
950 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
952 if(!strcmp(s, a->name))
954 if (a->initstate) // we can not remove init aliases
956 if(a == cmd->userdefined->alias)
957 cmd->userdefined->alias = a->next;
966 Con_Printf("unalias: %s alias not found\n", s);
971 =============================================================================
975 =============================================================================
978 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmdalias_t *alias, qboolean *is_multiple)
983 static char vabuf[1024]; // cmd_mutex
986 *is_multiple = false;
988 if(!varname || !*varname)
993 if(!strcmp(varname, "*"))
997 return Cmd_Args(cmd);
999 else if(!strcmp(varname, "#"))
1001 return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
1003 else if(varname[strlen(varname) - 1] == '-')
1005 argno = strtol(varname, &endptr, 10);
1006 if(endptr == varname + strlen(varname) - 1)
1008 // whole string is a number, apart from the -
1009 const char *p = Cmd_Args(cmd);
1010 for(; argno > 1; --argno)
1011 if(!COM_ParseToken_Console(&p))
1016 *is_multiple = true;
1018 // kill pre-argument whitespace
1019 for (;*p && ISWHITESPACE(*p);p++)
1028 argno = strtol(varname, &endptr, 10);
1031 // whole string is a number
1032 // NOTE: we already made sure we don't have an empty cvar name!
1033 if(argno >= 0 && argno < Cmd_Argc(cmd))
1034 return Cmd_Argv(cmd, argno);
1039 if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CVAR_PRIVATE))
1040 return cvar->string;
1045 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qboolean putquotes)
1047 qboolean quote_quot = !!strchr(quoteset, '"');
1048 qboolean quote_backslash = !!strchr(quoteset, '\\');
1049 qboolean quote_dollar = !!strchr(quoteset, '$');
1058 *out++ = '"'; --outlen;
1064 if(*in == '"' && quote_quot)
1068 *out++ = '\\'; --outlen;
1069 *out++ = '"'; --outlen;
1071 else if(*in == '\\' && quote_backslash)
1075 *out++ = '\\'; --outlen;
1076 *out++ = '\\'; --outlen;
1078 else if(*in == '$' && quote_dollar)
1082 *out++ = '$'; --outlen;
1083 *out++ = '$'; --outlen;
1089 *out++ = *in; --outlen;
1104 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmdalias_t *alias)
1106 static char varname[MAX_INPUTLINE]; // cmd_mutex
1107 static char varval[MAX_INPUTLINE]; // cmd_mutex
1108 const char *varstr = NULL;
1110 qboolean required = false;
1111 qboolean optional = false;
1112 static char asis[] = "asis"; // just to suppress const char warnings
1114 if(varlen >= MAX_INPUTLINE)
1115 varlen = MAX_INPUTLINE - 1;
1116 memcpy(varname, var, varlen);
1117 varname[varlen] = 0;
1118 varfunc = strchr(varname, ' ');
1130 Con_Warnf("Warning: Could not expand $ in alias %s\n", alias->name);
1132 Con_Warnf("Warning: Could not expand $\n");
1140 while((p = strchr(varfunc, '?')))
1143 memmove(p, p+1, strlen(p)); // with final NUL
1146 while((p = strchr(varfunc, '!')))
1149 memmove(p, p+1, strlen(p)); // with final NUL
1152 while((p = strchr(varfunc, ' ')))
1154 memmove(p, p+1, strlen(p)); // with final NUL
1156 // if no function is left, NULL it
1161 if(varname[0] == '$')
1162 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1165 qboolean is_multiple = false;
1166 // Exception: $* and $n- don't use the quoted form by default
1167 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1178 Con_Errorf("Error: Could not expand $%s in alias %s\n", varname, alias->name);
1180 Con_Errorf("Error: Could not expand $%s\n", varname);
1190 Con_Warnf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1192 Con_Warnf("Warning: Could not expand $%s\n", varname);
1193 dpsnprintf(varval, sizeof(varval), "$%s", varname);
1198 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1200 // quote it so it can be used inside double quotes
1201 // we just need to replace " by \", and of course, double backslashes
1202 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1205 else if(!strcmp(varfunc, "asis"))
1210 Con_Printf("Unknown variable function %s\n", varfunc);
1216 Cmd_PreprocessString
1218 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1220 static qboolean Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
1226 // don't crash if there's no room in the outtext buffer
1227 if( maxoutlen == 0 ) {
1230 maxoutlen--; // because of \0
1235 while( *in && outlen < maxoutlen ) {
1237 // this is some kind of expansion, see what comes after the $
1240 // The console does the following preprocessing:
1242 // - $$ is transformed to a single dollar sign.
1243 // - $var or ${var} are expanded to the contents of the named cvar,
1244 // with quotation marks and backslashes quoted so it can safely
1245 // be used inside quotation marks (and it should always be used
1247 // - ${var asis} inserts the cvar value as is, without doing this
1249 // - ${var ?} silently expands to the empty string if
1250 // $var does not exist
1251 // - ${var !} fails expansion and executes nothing if
1252 // $var does not exist
1253 // - prefix the cvar name with a dollar sign to do indirection;
1254 // for example, if $x has the value timelimit, ${$x} will return
1255 // the value of $timelimit
1256 // - when expanding an alias, the special variable name $* refers
1257 // to all alias parameters, and a number refers to that numbered
1258 // alias parameter, where the name of the alias is $0, the first
1259 // parameter is $1 and so on; as a special case, $* inserts all
1260 // parameters, without extra quoting, so one can use $* to just
1261 // pass all parameters around. All parameters starting from $n
1262 // can be referred to as $n- (so $* is equivalent to $1-).
1263 // - ${* q} and ${n- q} force quoting anyway
1265 // Note: when expanding an alias, cvar expansion is done in the SAME step
1266 // as alias expansion so that alias parameters or cvar values containing
1267 // dollar signs have no unwanted bad side effects. However, this needs to
1268 // be accounted for when writing complex aliases. For example,
1269 // alias foo "set x NEW; echo $x"
1270 // actually expands to
1271 // "set x NEW; echo OLD"
1272 // and will print OLD! To work around this, use a second alias:
1273 // alias foo "set x NEW; foo2"
1274 // alias foo2 "echo $x"
1276 // Also note: lines starting with alias are exempt from cvar expansion.
1277 // If you want cvar expansion, write "alias" instead:
1280 // alias foo "echo $x"
1281 // "alias" bar "echo $x"
1284 // foo will print 2, because the variable $x will be expanded when the alias
1285 // gets expanded. bar will print 1, because the variable $x was expanded
1286 // at definition time. foo can be equivalently defined as
1288 // "alias" foo "echo $$x"
1290 // because at definition time, $$ will get replaced to a single $.
1295 } else if(*in == '{') {
1296 varlen = strcspn(in + 1, "}");
1297 if(in[varlen + 1] == '}')
1299 val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1311 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1312 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1319 // insert the cvar value
1320 while(*val && outlen < maxoutlen)
1321 outtext[outlen++] = *val++;
1326 // copy the unexpanded text
1327 outtext[outlen++] = '$';
1328 while(eat && outlen < maxoutlen)
1330 outtext[outlen++] = *in++;
1336 outtext[outlen++] = *in++;
1338 outtext[outlen] = 0;
1346 Called for aliases and fills in the alias into the cbuffer
1349 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmdalias_t *alias)
1351 static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1352 static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1353 qboolean ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1356 // insert at start of command buffer, so that aliases execute in order
1357 // (fixes bug introduced by Black on 20050705)
1359 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1360 // have to make sure that no second variable expansion takes place, otherwise
1361 // alias parameters containing dollar signs can have bad effects.
1362 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1363 Cbuf_InsertText(cmd, buffer2);
1370 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1371 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1375 static void Cmd_List_f (cmd_state_t *cmd)
1377 cmd_function_t *func;
1378 const char *partial;
1383 if (Cmd_Argc(cmd) > 1)
1385 partial = Cmd_Argv(cmd, 1);
1386 len = strlen(partial);
1387 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1397 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1399 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1401 Con_Printf("%s : %s\n", func->name, func->description);
1404 for (func = cmd->engine_functions; func; func = func->next)
1406 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1408 Con_Printf("%s : %s\n", func->name, func->description);
1415 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1417 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1420 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1423 static void Cmd_Apropos_f(cmd_state_t *cmd)
1425 cmd_function_t *func;
1428 const char *partial;
1433 if (Cmd_Argc(cmd) > 1)
1434 partial = Cmd_Args(cmd);
1437 Con_Printf("usage: apropos <string>\n");
1441 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1443 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1446 for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1448 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1449 matchpattern_with_separator(cvar->description, partial, true, "", false))
1451 Con_Printf ("cvar ");
1452 Cvar_PrintHelp(cvar, cvar->name, true);
1455 for (int i = 0; i < cvar->aliasindex; i++)
1457 if (matchpattern_with_separator(cvar->aliases[i], partial, true, "", false))
1459 Con_Printf ("cvar ");
1460 Cvar_PrintHelp(cvar, cvar->aliases[i], true);
1465 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1467 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1468 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1470 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1473 for (func = cmd->engine_functions; func; func = func->next)
1475 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1476 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1478 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1481 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1483 // procede here a bit differently as an alias value always got a final \n
1484 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1485 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1487 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1490 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1500 cmd_iter_t *cmd_iter;
1501 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1503 cmd_state_t *cmd = cmd_iter->cmd;
1504 cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1505 // space for commands and script files
1506 cmd->text.data = cmd->text_buf;
1507 cmd->text.maxsize = sizeof(cmd->text_buf);
1508 cmd->text.cursize = 0;
1509 cmd->null_string = "";
1511 // client console can see server cvars because the user may start a server
1512 cmd_client.cvars = &cvars_all;
1513 cmd_client.cvars_flagsmask = CVAR_CLIENT | CVAR_SERVER;
1514 cmd_client.userdefined = &cmd_userdefined_all;
1515 // dedicated server console can only see server cvars, there is no client
1516 cmd_server.cvars = &cvars_all;
1517 cmd_server.cvars_flagsmask = CVAR_SERVER;
1518 cmd_server.userdefined = &cmd_userdefined_all;
1519 // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1520 cmd_serverfromclient.cvars = &cvars_null;
1521 cmd_serverfromclient.cvars_flagsmask = 0;
1522 cmd_serverfromclient.userdefined = &cmd_userdefined_null;
1525 void Cmd_Init_Commands(qboolean dedicated_server)
1528 // register our commands
1530 // client-only commands
1531 Cmd_AddCommand(CMD_CLIENT | CMD_CLIENT_FROM_SERVER, "cmd", Cmd_ForwardToServer_f, "send a console commandline to the server (used by some mods)");
1532 Cmd_AddCommand(CMD_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1533 Cmd_AddCommand(CMD_CLIENT, "cprint", Cmd_Centerprint_f, "print something at the screen center");
1535 // maintenance commands used for upkeep of cvars and saved configs
1536 Cmd_AddCommand(CMD_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1537 Cmd_AddCommand(CMD_SHARED, "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");
1538 Cmd_AddCommand(CMD_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1539 Cmd_AddCommand(CMD_SHARED, "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)");
1540 Cmd_AddCommand(CMD_SHARED, "cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
1542 // general console commands used in multiple environments
1543 Cmd_AddCommand(CMD_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1544 Cmd_AddCommand(CMD_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1545 Cmd_AddCommand(CMD_SHARED, "alias",Cmd_Alias_f, "create a script function (parameters are passed in as $X (being X a number), $* for all parameters, $X- for all parameters starting from $X). Without arguments show the list of all alias");
1546 Cmd_AddCommand(CMD_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1547 Cmd_AddCommand(CMD_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1548 Cmd_AddCommand(CMD_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1549 Cmd_AddCommand(CMD_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1551 #ifdef FILLALLCVARSWITHRUBBISH
1552 Cmd_AddCommand(CMD_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1553 #endif /* FILLALLCVARSWITHRUBBISH */
1555 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1556 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1557 Cmd_AddCommand(CMD_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1558 Cmd_AddCommand(CMD_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1559 Cmd_AddCommand(CMD_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1561 Cmd_AddCommand(CMD_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1564 // Support Doom3-style Toggle Command
1565 Cmd_AddCommand(CMD_SHARED | CMD_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1573 void Cmd_Shutdown(void)
1575 cmd_iter_t *cmd_iter;
1576 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1578 cmd_state_t *cmd = cmd_iter->cmd;
1582 // we usually have this locked when we get here from Host_Quit_f
1586 Mem_FreePool(&cmd->mempool);
1595 int Cmd_Argc (cmd_state_t *cmd)
1605 const char *Cmd_Argv(cmd_state_t *cmd, int arg)
1607 if (arg >= cmd->argc )
1608 return cmd->null_string;
1609 return cmd->argv[arg];
1617 const char *Cmd_Args (cmd_state_t *cmd)
1627 Parses the given string into command line tokens.
1630 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1631 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1640 // skip whitespace up to a /n
1641 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1648 if (*text == '\n' || *text == '\r')
1650 // a newline separates commands in the buffer
1651 if (*text == '\r' && text[1] == '\n')
1663 if (!COM_ParseToken_Console(&text))
1666 if (cmd->argc < MAX_ARGS)
1668 l = (int)strlen(com_token) + 1;
1669 if (cmd->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1671 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1674 memcpy (cmd->tokenizebuffer + cmd->tokenizebufferpos, com_token, l);
1675 cmd->argv[cmd->argc] = cmd->tokenizebuffer + cmd->tokenizebufferpos;
1676 cmd->tokenizebufferpos += l;
1688 void Cmd_AddCommand(int flags, const char *cmd_name, xcommand_t function, const char *description)
1690 cmd_function_t *func;
1691 cmd_function_t *prev, *current;
1693 xcommand_t function_actual;
1696 for (i = 1; i < (1<<8); i *= 2)
1698 function_actual = function;
1699 if ((i == CMD_CLIENT) && (flags & i))
1703 function_actual = Cmd_ForwardToServer_f;
1705 else if ((i == CMD_SERVER) && (flags & i))
1707 else if ((i == 8) && (flags & i)) // CMD_SERVER_FROM_CLIENT
1708 cmd = &cmd_serverfromclient;
1712 // fail if the command is a variable name
1713 if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1715 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1719 if (function_actual)
1721 // fail if the command already exists in this interpreter
1722 for (func = cmd->engine_functions; func; func = func->next)
1724 if (!strcmp(cmd_name, func->name))
1726 // Allow overriding forward to server
1727 if(func->function == Cmd_ForwardToServer_f && (func->flags & 8))
1731 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1732 goto nested_continue;
1737 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1738 func->flags = flags;
1739 func->name = cmd_name;
1740 func->function = function_actual;
1741 func->description = description;
1742 func->next = cmd->engine_functions;
1744 // insert it at the right alphanumeric position
1745 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1751 cmd->engine_functions = func;
1753 func->next = current;
1757 // mark csqcfunc if the function already exists in the csqc_functions list
1758 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1760 if (!strcmp(cmd_name, func->name))
1762 func->csqcfunc = true; //[515]: csqc
1768 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1769 func->name = cmd_name;
1770 func->function = function_actual;
1771 func->description = description;
1772 func->csqcfunc = true; //[515]: csqc
1773 func->next = cmd->userdefined->csqc_functions;
1775 // insert it at the right alphanumeric position
1776 for (prev = NULL, current = cmd->userdefined->csqc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1782 cmd->userdefined->csqc_functions = func;
1784 func->next = current;
1796 qboolean Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1798 cmd_function_t *func;
1800 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1801 if (!strcmp(cmd_name, func->name))
1804 for (func=cmd->engine_functions ; func ; func=func->next)
1805 if (!strcmp (cmd_name,func->name))
1817 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1819 cmd_function_t *func;
1822 len = strlen(partial);
1828 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1829 if (!strncasecmp(partial, func->name, len))
1832 for (func = cmd->engine_functions; func; func = func->next)
1833 if (!strncasecmp(partial, func->name, len))
1840 Cmd_CompleteCountPossible
1842 New function for tab-completion system
1843 Added by EvilTypeGuy
1844 Thanks to Fett erich@heintz.com
1848 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1850 cmd_function_t *func;
1855 len = strlen(partial);
1860 // Loop through the command list and count all partial matches
1861 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1862 if (!strncasecmp(partial, func->name, len))
1865 for (func = cmd->engine_functions; func; func = func->next)
1866 if (!strncasecmp(partial, func->name, len))
1873 Cmd_CompleteBuildList
1875 New function for tab-completion system
1876 Added by EvilTypeGuy
1877 Thanks to Fett erich@heintz.com
1881 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
1883 cmd_function_t *func;
1886 size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
1889 len = strlen(partial);
1890 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1891 // Loop through the functions lists and print all matches
1892 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1893 if (!strncasecmp(partial, func->name, len))
1894 buf[bpos++] = func->name;
1895 for (func = cmd->engine_functions; func; func = func->next)
1896 if (!strncasecmp(partial, func->name, len))
1897 buf[bpos++] = func->name;
1903 // written by LadyHavoc
1904 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
1906 cmd_function_t *func;
1907 size_t len = strlen(partial);
1908 // Loop through the command list and print all matches
1909 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1910 if (!strncasecmp(partial, func->name, len))
1911 Con_Printf("^2%s^7: %s\n", func->name, func->description);
1912 for (func = cmd->engine_functions; func; func = func->next)
1913 if (!strncasecmp(partial, func->name, len))
1914 Con_Printf("^2%s^7: %s\n", func->name, func->description);
1920 New function for tab-completion system
1921 Added by EvilTypeGuy
1922 Thanks to Fett erich@heintz.com
1926 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
1931 len = strlen(partial);
1937 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1938 if (!strncasecmp(partial, alias->name, len))
1944 // written by LadyHavoc
1945 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
1948 size_t len = strlen(partial);
1949 // Loop through the alias list and print all matches
1950 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1951 if (!strncasecmp(partial, alias->name, len))
1952 Con_Printf("^5%s^7: %s", alias->name, alias->value);
1957 Cmd_CompleteAliasCountPossible
1959 New function for tab-completion system
1960 Added by EvilTypeGuy
1961 Thanks to Fett erich@heintz.com
1965 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
1973 len = strlen(partial);
1978 // Loop through the command list and count all partial matches
1979 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1980 if (!strncasecmp(partial, alias->name, len))
1987 Cmd_CompleteAliasBuildList
1989 New function for tab-completion system
1990 Added by EvilTypeGuy
1991 Thanks to Fett erich@heintz.com
1995 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
2000 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
2003 len = strlen(partial);
2004 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2005 // Loop through the alias list and print all matches
2006 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2007 if (!strncasecmp(partial, alias->name, len))
2008 buf[bpos++] = alias->name;
2014 // TODO: Make this more generic?
2015 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2017 cmd_function_t *func;
2018 cmd_function_t **next = &cmd->userdefined->csqc_functions;
2028 extern cvar_t sv_cheats;
2034 A complete command line has been parsed, so try to execute it
2035 FIXME: lookupnoadd the token to speed search?
2038 void Cmd_ExecuteString (cmd_state_t *cmd, const char *text, cmd_source_t src, qboolean lockmutex)
2041 cmd_function_t *func;
2045 oldpos = cmd->tokenizebufferpos;
2048 Cmd_TokenizeString (cmd, text);
2050 // execute the command line
2052 goto done; // no tokens
2055 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
2057 if (!strcasecmp(cmd->argv[0], func->name))
2059 if (func->csqcfunc && CL_VM_ConsoleCommand(text)) //[515]: csqc
2065 for (func = cmd->engine_functions; func; func=func->next)
2067 if (!strcasecmp (cmd->argv[0], func->name))
2073 func->function(cmd);
2075 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2080 if((func->flags & CMD_CHEAT) && !sv_cheats.integer)
2081 SV_ClientPrintf("No cheats allowed. The server must have sv_cheats set to 1\n");
2082 func->function(cmd);
2090 // if it's a client command and no command was found, say so.
2091 if (cmd->source == src_client)
2093 Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2098 for (a=cmd->userdefined->alias ; a ; a=a->next)
2100 if (!strcasecmp (cmd->argv[0], a->name))
2102 Cmd_ExecuteAlias(cmd, a);
2108 if (!Cvar_Command(cmd) && host_framecount > 0)
2109 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2111 cmd->tokenizebufferpos = oldpos;
2119 Cmd_ForwardStringToServer
2121 Sends an entire command string over to the server, unprocessed
2124 void Cmd_ForwardStringToServer (const char *s)
2127 if (cls.state != ca_connected)
2129 Con_Printf("Can't \"%s\", not connected\n", s);
2136 // LadyHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
2137 // attention, it has been eradicated from here, its only (former) use in
2138 // all of darkplaces.
2139 if (cls.protocol == PROTOCOL_QUAKEWORLD)
2140 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
2142 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
2143 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
2145 // say/say_team commands can replace % character codes with status info
2148 if (*s == '%' && s[1])
2150 // handle proquake message macros
2154 case 'l': // current location
2155 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
2157 case 'h': // current health
2158 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
2160 case 'a': // current armor
2161 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
2163 case 'x': // current rockets
2164 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
2166 case 'c': // current cells
2167 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
2169 // silly proquake macros
2170 case 'd': // loc at last death
2171 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
2173 case 't': // current time
2174 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
2176 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
2177 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
2178 dpsnprintf(temp, sizeof(temp), "I need RL");
2179 else if (!cl.stats[STAT_ROCKETS])
2180 dpsnprintf(temp, sizeof(temp), "I need rockets");
2182 dpsnprintf(temp, sizeof(temp), "I have RL");
2184 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
2185 if (cl.stats[STAT_ITEMS] & IT_QUAD)
2188 strlcat(temp, " ", sizeof(temp));
2189 strlcat(temp, "quad", sizeof(temp));
2191 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
2194 strlcat(temp, " ", sizeof(temp));
2195 strlcat(temp, "pent", sizeof(temp));
2197 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
2200 strlcat(temp, " ", sizeof(temp));
2201 strlcat(temp, "eyes", sizeof(temp));
2204 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
2205 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
2206 strlcat(temp, "SSG", sizeof(temp));
2207 strlcat(temp, ":", sizeof(temp));
2208 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
2209 strlcat(temp, "NG", sizeof(temp));
2210 strlcat(temp, ":", sizeof(temp));
2211 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
2212 strlcat(temp, "SNG", sizeof(temp));
2213 strlcat(temp, ":", sizeof(temp));
2214 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
2215 strlcat(temp, "GL", sizeof(temp));
2216 strlcat(temp, ":", sizeof(temp));
2217 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
2218 strlcat(temp, "RL", sizeof(temp));
2219 strlcat(temp, ":", sizeof(temp));
2220 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
2221 strlcat(temp, "LG", sizeof(temp));
2224 // not a recognized macro, print it as-is...
2230 // write the resulting text
2231 SZ_Write(&cls.netcon->message, (unsigned char *)temp, (int)strlen(temp));
2235 MSG_WriteByte(&cls.netcon->message, *s);
2238 MSG_WriteByte(&cls.netcon->message, 0);
2240 else // any other command is passed on as-is
2241 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
2248 Sends the entire command line over to the server
2251 void Cmd_ForwardToServer_f (cmd_state_t *cmd)
2255 if (!strcasecmp(Cmd_Argv(cmd, 0), "cmd"))
2257 // we want to strip off "cmd", so just send the args
2258 s = Cmd_Argc(cmd) > 1 ? Cmd_Args(cmd) : "";
2262 // we need to keep the command name, so send Cmd_Argv(cmd, 0), a space and then Cmd_Args(cmd)
2263 s = va(vabuf, sizeof(vabuf), "%s %s", Cmd_Argv(cmd, 0), Cmd_Argc(cmd) > 1 ? Cmd_Args(cmd) : "");
2265 // don't send an empty forward message if the user tries "cmd" by itself
2268 Cmd_ForwardStringToServer(s);
2276 Returns the position (1 to argc-1) in the command's argument list
2277 where the given parameter apears, or 0 if not present
2281 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2287 Con_Printf ("Cmd_CheckParm: NULL");
2291 for (i = 1; i < Cmd_Argc (cmd); i++)
2292 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2300 void Cmd_SaveInitState(void)
2302 cmd_iter_t *cmd_iter;
2303 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2305 cmd_state_t *cmd = cmd_iter->cmd;
2308 for (f = cmd->userdefined->csqc_functions; f; f = f->next)
2309 f->initstate = true;
2310 for (f = cmd->engine_functions; f; f = f->next)
2311 f->initstate = true;
2312 for (a = cmd->userdefined->alias; a; a = a->next)
2314 a->initstate = true;
2315 a->initialvalue = Mem_strdup(zonemempool, a->value);
2318 Cvar_SaveInitState(&cvars_all);
2321 void Cmd_RestoreInitState(void)
2323 cmd_iter_t *cmd_iter;
2324 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2326 cmd_state_t *cmd = cmd_iter->cmd;
2327 cmd_function_t *f, **fp;
2328 cmdalias_t *a, **ap;
2329 for (fp = &cmd->userdefined->csqc_functions; (f = *fp);)
2335 // destroy this command, it didn't exist at init
2336 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2341 for (fp = &cmd->engine_functions; (f = *fp);)
2347 // destroy this command, it didn't exist at init
2348 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2353 for (ap = &cmd->userdefined->alias; (a = *ap);)
2357 // restore this alias, it existed at init
2358 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2360 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2363 a->value = Mem_strdup(zonemempool, a->initialvalue);
2369 // free this alias, it didn't exist at init...
2370 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2378 Cvar_RestoreInitState(&cvars_all);