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_clientfromserver;
27 cmd_state_t cmd_server;
28 cmd_state_t cmd_serverfromclient;
30 cmd_userdefined_t cmd_userdefined_all;
31 cmd_userdefined_t cmd_userdefined_null;
33 typedef struct cmd_iter_s {
38 static cmd_iter_t cmd_iter_all[] = {
40 {&cmd_clientfromserver},
42 {&cmd_serverfromclient},
47 // we only run the +whatever commandline arguments once
48 qboolean host_stuffcmdsrun = false;
50 //=============================================================================
52 void Cbuf_Lock(cmd_state_t *cmd)
54 Thread_AtomicLock(&cmd->text_lock);
57 void Cbuf_Unlock(cmd_state_t *cmd)
59 Thread_AtomicUnlock(&cmd->text_lock);
67 Causes execution of the remainder of the command buffer to be delayed until
68 next frame. This allows commands like:
69 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
72 static void Cmd_Wait_f (cmd_state_t *cmd)
81 Cause a command to be executed after a delay.
84 static void Cmd_Defer_f (cmd_state_t *cmd)
86 if(Cmd_Argc(cmd) == 1)
88 cmddeferred_t *next = cmd->deferred_list;
90 Con_Printf("No commands are pending.\n");
93 Con_Printf("-> In %9.2f: %s\n", next->delay, next->value);
96 } else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
98 while(cmd->deferred_list)
100 cmddeferred_t *defcmd = cmd->deferred_list;
101 cmd->deferred_list = defcmd->next;
102 Mem_Free(defcmd->value);
105 } else if(Cmd_Argc(cmd) == 3)
107 const char *value = Cmd_Argv(cmd, 2);
108 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
109 size_t len = strlen(value);
111 defcmd->delay = atof(Cmd_Argv(cmd, 1));
112 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
113 memcpy(defcmd->value, value, len+1);
116 if(cmd->deferred_list)
118 cmddeferred_t *next = cmd->deferred_list;
123 cmd->deferred_list = defcmd;
124 /* Stupid me... this changes the order... so commands with the same delay go blub :S
125 defcmd->next = cmd_deferred_list;
126 cmd_deferred_list = defcmd;*/
128 Con_Printf("usage: defer <seconds> <command>\n"
138 Print something to the center of the screen using SCR_Centerprint
141 static void Cmd_Centerprint_f (cmd_state_t *cmd)
143 char msg[MAX_INPUTLINE];
144 unsigned int i, c, p;
148 strlcpy(msg, Cmd_Argv(cmd,1), sizeof(msg));
149 for(i = 2; i < c; ++i)
151 strlcat(msg, " ", sizeof(msg));
152 strlcat(msg, Cmd_Argv(cmd, i), sizeof(msg));
154 c = (unsigned int)strlen(msg);
155 for(p = 0, i = 0; i < c; ++i)
161 else if(msg[i+1] == '\\')
173 SCR_CenterPrint(msg);
178 =============================================================================
182 =============================================================================
189 Adds command text at the end of the buffer
192 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
196 l = (int)strlen(text);
199 if (cmd->text.maxsize - cmd->text.cursize <= l)
200 Con_Print("Cbuf_AddText: overflow\n");
202 SZ_Write(&cmd->text, (const unsigned char *)text, l);
211 Adds command text immediately after the current command
212 Adds a \n to the text
213 FIXME: actually change the command buffer to do less copying
216 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
218 size_t l = strlen(text);
220 // we need to memmove the existing text and stuff this in before it...
221 if (cmd->text.cursize + l >= (size_t)cmd->text.maxsize)
222 Con_Print("Cbuf_InsertText: overflow\n");
225 // we don't have a SZ_Prepend, so...
226 memmove(cmd->text.data + l, cmd->text.data, cmd->text.cursize);
227 cmd->text.cursize += (int)l;
228 memcpy(cmd->text.data, text, l);
235 Cbuf_Execute_Deferred --blub
238 static void Cbuf_Execute_Deferred (cmd_state_t *cmd)
240 cmddeferred_t *defcmd, *prev;
242 if (realtime - cmd->deferred_oldrealtime < 0 || realtime - cmd->deferred_oldrealtime > 1800) cmd->deferred_oldrealtime = realtime;
243 eat = realtime - cmd->deferred_oldrealtime;
244 if (eat < (1.0 / 120.0))
246 cmd->deferred_oldrealtime = realtime;
248 defcmd = cmd->deferred_list;
251 defcmd->delay -= eat;
252 if(defcmd->delay <= 0)
254 Cbuf_AddText(cmd, defcmd->value);
255 Cbuf_AddText(cmd, ";\n");
256 Mem_Free(defcmd->value);
259 prev->next = defcmd->next;
263 cmd->deferred_list = defcmd->next;
265 defcmd = cmd->deferred_list;
270 defcmd = defcmd->next;
279 static qboolean Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
280 void Cbuf_Execute (cmd_state_t *cmd)
284 char line[MAX_INPUTLINE];
285 char preprocessed[MAX_INPUTLINE];
290 // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
291 cmd->tokenizebufferpos = 0;
293 while (cmd->text.cursize)
295 // find a \n or ; line break
296 text = (char *)cmd->text.data;
300 for (i=0 ; i < cmd->text.cursize ; i++)
309 // make sure i doesn't get > cursize which causes a negative
310 // size in memmove, which is fatal --blub
311 if (i < (cmd->text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
316 if(text[i] == '/' && text[i + 1] == '/' && (i == 0 || ISWHITESPACE(text[i-1])))
319 break; // don't break if inside a quoted string or comment
323 if (text[i] == '\r' || text[i] == '\n')
327 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
328 if(i >= MAX_INPUTLINE)
330 Con_Warnf("Warning: console input buffer had an overlong line. Ignored.\n");
335 memcpy (line, text, comment ? (comment - text) : i);
336 line[comment ? (comment - text) : i] = 0;
339 // delete the text from the command buffer and move remaining commands down
340 // this is necessary because commands (exec, alias) can insert data at the
341 // beginning of the text buffer
343 if (i == cmd->text.cursize)
344 cmd->text.cursize = 0;
348 cmd->text.cursize -= i;
349 memmove (cmd->text.data, text+i, cmd->text.cursize);
352 // execute the command line
354 while(*firstchar && ISWHITESPACE(*firstchar))
357 (strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5]))
359 (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4]))
361 (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7]))
364 if(Cmd_PreprocessString( cmd, line, preprocessed, sizeof(preprocessed), NULL ))
365 Cmd_ExecuteString (cmd, preprocessed, src_command, false);
369 Cmd_ExecuteString (cmd, line, src_command, false);
373 { // skip out while text still remains in buffer, leaving it
381 void Cbuf_Frame(cmd_state_t *cmd)
383 Cbuf_Execute_Deferred(cmd);
384 if (cmd->text.cursize)
386 SV_LockThreadMutex();
388 SV_UnlockThreadMutex();
393 ==============================================================================
397 ==============================================================================
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 if (Cmd_Argc (cmd) != 1)
418 Con_Print("stuffcmds : execute command line parameters\n");
422 // no reason to run the commandline arguments twice
423 if (host_stuffcmdsrun)
426 host_stuffcmdsrun = true;
429 for (i = 0;i < com_argc;i++)
431 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9') && l + strlen(com_argv[i]) - 1 <= sizeof(build) - 1)
434 while (com_argv[i][j])
435 build[l++] = com_argv[i][j++];
437 for (;i < com_argc;i++)
441 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
443 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
446 if (strchr(com_argv[i], ' '))
448 for (j = 0;com_argv[i][j];j++)
449 build[l++] = com_argv[i][j];
450 if (strchr(com_argv[i], ' '))
457 // now terminate the combined string and prepend it to the command buffer
458 // we already reserved space for the terminator
460 Cbuf_InsertText (cmd, build);
463 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
466 size_t filenameLen = strlen(filename);
467 qboolean isdefaultcfg =
468 !strcmp(filename, "default.cfg") ||
469 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
471 if (!strcmp(filename, "config.cfg"))
473 filename = CONFIGFILENAME;
474 if (COM_CheckParm("-noconfig"))
475 return; // don't execute config.cfg
478 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
481 Con_Printf("couldn't exec %s\n",filename);
484 Con_Printf("execing %s\n",filename);
486 // if executing default.cfg for the first time, lock the cvar defaults
487 // it may seem backwards to insert this text BEFORE the default.cfg
488 // but Cbuf_InsertText inserts before, so this actually ends up after it.
490 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
492 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
493 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
494 Cbuf_InsertText (cmd, "\n");
495 Cbuf_InsertText (cmd, f);
500 // special defaults for specific games go here, these execute before default.cfg
501 // Nehahra pushable crates malfunction in some levels if this is on
502 // Nehahra NPC AI is confused by blowupfallenzombies
506 Cbuf_InsertText(cmd, "\n"
507 "sv_gameplayfix_blowupfallenzombies 0\n"
508 "sv_gameplayfix_findradiusdistancetobox 0\n"
509 "sv_gameplayfix_grenadebouncedownslopes 0\n"
510 "sv_gameplayfix_slidemoveprojectiles 0\n"
511 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
512 "sv_gameplayfix_setmodelrealbox 0\n"
513 "sv_gameplayfix_droptofloorstartsolid 0\n"
514 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
515 "sv_gameplayfix_noairborncorpse 0\n"
516 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
517 "sv_gameplayfix_easierwaterjump 0\n"
518 "sv_gameplayfix_delayprojectiles 0\n"
519 "sv_gameplayfix_multiplethinksperframe 0\n"
520 "sv_gameplayfix_fixedcheckwatertransition 0\n"
521 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
522 "sv_gameplayfix_swiminbmodels 0\n"
523 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
524 "sys_ticrate 0.01388889\n"
526 "r_shadow_bumpscale_basetexture 0\n"
527 "csqc_polygons_defaultmaterial_nocullface 0\n"
531 Cbuf_InsertText(cmd, "\n"
532 "sv_gameplayfix_blowupfallenzombies 0\n"
533 "sv_gameplayfix_findradiusdistancetobox 0\n"
534 "sv_gameplayfix_grenadebouncedownslopes 0\n"
535 "sv_gameplayfix_slidemoveprojectiles 0\n"
536 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
537 "sv_gameplayfix_setmodelrealbox 0\n"
538 "sv_gameplayfix_droptofloorstartsolid 0\n"
539 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
540 "sv_gameplayfix_noairborncorpse 0\n"
541 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
542 "sv_gameplayfix_easierwaterjump 0\n"
543 "sv_gameplayfix_delayprojectiles 0\n"
544 "sv_gameplayfix_multiplethinksperframe 0\n"
545 "sv_gameplayfix_fixedcheckwatertransition 0\n"
546 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
547 "sv_gameplayfix_swiminbmodels 0\n"
548 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
549 "sys_ticrate 0.01388889\n"
551 "r_shadow_bumpscale_basetexture 0\n"
552 "csqc_polygons_defaultmaterial_nocullface 0\n"
555 // 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.
556 // 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
557 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
560 Cbuf_InsertText(cmd, "\n"
561 "sv_gameplayfix_blowupfallenzombies 0\n"
562 "sv_gameplayfix_findradiusdistancetobox 0\n"
563 "sv_gameplayfix_grenadebouncedownslopes 0\n"
564 "sv_gameplayfix_slidemoveprojectiles 0\n"
565 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
566 "sv_gameplayfix_setmodelrealbox 0\n"
567 "sv_gameplayfix_droptofloorstartsolid 0\n"
568 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
569 "sv_gameplayfix_noairborncorpse 0\n"
570 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
571 "sv_gameplayfix_easierwaterjump 0\n"
572 "sv_gameplayfix_delayprojectiles 0\n"
573 "sv_gameplayfix_multiplethinksperframe 0\n"
574 "sv_gameplayfix_fixedcheckwatertransition 0\n"
575 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
576 "sv_gameplayfix_swiminbmodels 0\n"
577 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
580 "r_shadow_bumpscale_basetexture 0\n"
581 "csqc_polygons_defaultmaterial_nocullface 0\n"
584 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
586 Cbuf_InsertText(cmd, "\n"
587 "sv_gameplayfix_blowupfallenzombies 0\n"
588 "sv_gameplayfix_findradiusdistancetobox 0\n"
589 "sv_gameplayfix_grenadebouncedownslopes 0\n"
590 "sv_gameplayfix_slidemoveprojectiles 0\n"
591 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
592 "sv_gameplayfix_setmodelrealbox 0\n"
593 "sv_gameplayfix_droptofloorstartsolid 0\n"
594 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
595 "sv_gameplayfix_noairborncorpse 0\n"
596 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
597 "sv_gameplayfix_easierwaterjump 0\n"
598 "sv_gameplayfix_delayprojectiles 0\n"
599 "sv_gameplayfix_multiplethinksperframe 0\n"
600 "sv_gameplayfix_fixedcheckwatertransition 0\n"
601 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
602 "sv_gameplayfix_swiminbmodels 0\n"
603 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
604 "sys_ticrate 0.01388889\n"
606 "r_shadow_bumpscale_basetexture 0\n"
607 "csqc_polygons_defaultmaterial_nocullface 0\n"
611 Cbuf_InsertText(cmd, "\n"
612 "sv_gameplayfix_blowupfallenzombies 0\n"
613 "sv_gameplayfix_findradiusdistancetobox 0\n"
614 "sv_gameplayfix_grenadebouncedownslopes 0\n"
615 "sv_gameplayfix_slidemoveprojectiles 0\n"
616 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
617 "sv_gameplayfix_setmodelrealbox 0\n"
618 "sv_gameplayfix_droptofloorstartsolid 0\n"
619 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
620 "sv_gameplayfix_noairborncorpse 0\n"
621 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
622 "sv_gameplayfix_easierwaterjump 0\n"
623 "sv_gameplayfix_delayprojectiles 0\n"
624 "sv_gameplayfix_multiplethinksperframe 0\n"
625 "sv_gameplayfix_fixedcheckwatertransition 0\n"
626 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
627 "sv_gameplayfix_swiminbmodels 0\n"
628 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
629 "sys_ticrate 0.01388889\n"
631 "r_shadow_bumpscale_basetexture 4\n"
632 "csqc_polygons_defaultmaterial_nocullface 0\n"
636 Cbuf_InsertText(cmd, "\n"
637 "sv_gameplayfix_blowupfallenzombies 1\n"
638 "sv_gameplayfix_findradiusdistancetobox 1\n"
639 "sv_gameplayfix_grenadebouncedownslopes 1\n"
640 "sv_gameplayfix_slidemoveprojectiles 1\n"
641 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
642 "sv_gameplayfix_setmodelrealbox 1\n"
643 "sv_gameplayfix_droptofloorstartsolid 1\n"
644 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
645 "sv_gameplayfix_noairborncorpse 1\n"
646 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
647 "sv_gameplayfix_easierwaterjump 1\n"
648 "sv_gameplayfix_delayprojectiles 1\n"
649 "sv_gameplayfix_multiplethinksperframe 1\n"
650 "sv_gameplayfix_fixedcheckwatertransition 1\n"
651 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
652 "sv_gameplayfix_swiminbmodels 1\n"
653 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
654 "sys_ticrate 0.01388889\n"
655 "sv_gameplayfix_q2airaccelerate 1\n"
656 "sv_gameplayfix_stepmultipletimes 1\n"
657 "csqc_polygons_defaultmaterial_nocullface 1\n"
661 case GAME_VORETOURNAMENT:
662 // 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
663 Cbuf_InsertText(cmd, "\n"
664 "csqc_polygons_defaultmaterial_nocullface 1\n"
667 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
668 case GAME_STEELSTORM:
669 Cbuf_InsertText(cmd, "\n"
670 "sv_gameplayfix_blowupfallenzombies 1\n"
671 "sv_gameplayfix_findradiusdistancetobox 1\n"
672 "sv_gameplayfix_grenadebouncedownslopes 1\n"
673 "sv_gameplayfix_slidemoveprojectiles 1\n"
674 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
675 "sv_gameplayfix_setmodelrealbox 1\n"
676 "sv_gameplayfix_droptofloorstartsolid 1\n"
677 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
678 "sv_gameplayfix_noairborncorpse 1\n"
679 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
680 "sv_gameplayfix_easierwaterjump 1\n"
681 "sv_gameplayfix_delayprojectiles 1\n"
682 "sv_gameplayfix_multiplethinksperframe 1\n"
683 "sv_gameplayfix_fixedcheckwatertransition 1\n"
684 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
685 "sv_gameplayfix_swiminbmodels 1\n"
686 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
687 "sys_ticrate 0.01388889\n"
688 "cl_csqc_generatemousemoveevents 0\n"
689 "csqc_polygons_defaultmaterial_nocullface 1\n"
693 Cbuf_InsertText(cmd, "\n"
694 "sv_gameplayfix_blowupfallenzombies 1\n"
695 "sv_gameplayfix_findradiusdistancetobox 1\n"
696 "sv_gameplayfix_grenadebouncedownslopes 1\n"
697 "sv_gameplayfix_slidemoveprojectiles 1\n"
698 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
699 "sv_gameplayfix_setmodelrealbox 1\n"
700 "sv_gameplayfix_droptofloorstartsolid 1\n"
701 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
702 "sv_gameplayfix_noairborncorpse 1\n"
703 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
704 "sv_gameplayfix_easierwaterjump 1\n"
705 "sv_gameplayfix_delayprojectiles 1\n"
706 "sv_gameplayfix_multiplethinksperframe 1\n"
707 "sv_gameplayfix_fixedcheckwatertransition 1\n"
708 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
709 "sv_gameplayfix_swiminbmodels 1\n"
710 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
711 "sys_ticrate 0.01388889\n"
712 "csqc_polygons_defaultmaterial_nocullface 0\n"
724 static void Cmd_Exec_f (cmd_state_t *cmd)
729 if (Cmd_Argc(cmd) != 2)
731 Con_Print("exec <filename> : execute a script file\n");
735 s = FS_Search(Cmd_Argv(cmd, 1), true, true);
736 if(!s || !s->numfilenames)
738 Con_Printf("couldn't exec %s\n",Cmd_Argv(cmd, 1));
742 for(i = 0; i < s->numfilenames; ++i)
743 Cmd_Exec(cmd, s->filenames[i]);
753 Just prints the rest of the line to the console
756 static void Cmd_Echo_f (cmd_state_t *cmd)
760 for (i=1 ; i<Cmd_Argc(cmd) ; i++)
761 Con_Printf("%s ",Cmd_Argv(cmd, i));
766 // Support Doom3-style Toggle Console Command
771 Toggles a specified console variable amongst the values specified (default is 0 and 1)
774 static void Cmd_Toggle_f(cmd_state_t *cmd)
776 // Acquire Number of Arguments
777 int nNumArgs = Cmd_Argc(cmd);
780 // No Arguments Specified; Print Usage
781 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");
783 { // Correct Arguments Specified
784 // Acquire Potential CVar
785 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
792 Cvar_SetValueQuick(cvCVar, 0);
794 Cvar_SetValueQuick(cvCVar, 1);
798 { // 0 and Specified Usage
799 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
800 // CVar is Specified Value; // Reset to 0
801 Cvar_SetValueQuick(cvCVar, 0);
803 if(cvCVar->integer == 0)
804 // CVar is 0; Specify Value
805 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
807 // CVar does not match; Reset to 0
808 Cvar_SetValueQuick(cvCVar, 0);
811 { // Variable Values Specified
815 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
816 { // Cycle through Values
817 if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
818 { // Current Value Located; Increment to Next
819 if( (nCnt + 1) == nNumArgs)
820 // Max Value Reached; Reset
821 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
824 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
833 // Value not Found; Reset to Original
834 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
840 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
849 Creates a new command that executes a command string (possibly ; seperated)
852 static void Cmd_Alias_f (cmd_state_t *cmd)
855 char line[MAX_INPUTLINE];
860 if (Cmd_Argc(cmd) == 1)
862 Con_Print("Current alias commands:\n");
863 for (a = cmd->userdefined->alias ; a ; a=a->next)
864 Con_Printf("%s : %s", a->name, a->value);
868 s = Cmd_Argv(cmd, 1);
869 if (strlen(s) >= MAX_ALIAS_NAME)
871 Con_Print("Alias name is too long\n");
875 // if the alias already exists, reuse it
876 for (a = cmd->userdefined->alias ; a ; a=a->next)
878 if (!strcmp(s, a->name))
887 cmdalias_t *prev, *current;
889 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
890 strlcpy (a->name, s, sizeof (a->name));
891 // insert it at the right alphanumeric position
892 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
897 cmd->userdefined->alias = a;
903 // copy the rest of the command line
904 line[0] = 0; // start out with a null string
906 for (i=2 ; i < c ; i++)
909 strlcat (line, " ", sizeof (line));
910 strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
912 strlcat (line, "\n", sizeof (line));
914 alloclen = strlen (line) + 1;
916 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
917 a->value = (char *)Z_Malloc (alloclen);
918 memcpy (a->value, line, alloclen);
925 Remove existing aliases.
928 static void Cmd_UnAlias_f (cmd_state_t *cmd)
934 if(Cmd_Argc(cmd) == 1)
936 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
940 for(i = 1; i < Cmd_Argc(cmd); ++i)
942 s = Cmd_Argv(cmd, i);
944 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
946 if(!strcmp(s, a->name))
948 if (a->initstate) // we can not remove init aliases
950 if(a == cmd->userdefined->alias)
951 cmd->userdefined->alias = a->next;
960 Con_Printf("unalias: %s alias not found\n", s);
965 =============================================================================
969 =============================================================================
972 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmdalias_t *alias, qboolean *is_multiple)
977 static char vabuf[1024]; // cmd_mutex
980 *is_multiple = false;
982 if(!varname || !*varname)
987 if(!strcmp(varname, "*"))
991 return Cmd_Args(cmd);
993 else if(!strcmp(varname, "#"))
995 return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
997 else if(varname[strlen(varname) - 1] == '-')
999 argno = strtol(varname, &endptr, 10);
1000 if(endptr == varname + strlen(varname) - 1)
1002 // whole string is a number, apart from the -
1003 const char *p = Cmd_Args(cmd);
1004 for(; argno > 1; --argno)
1005 if(!COM_ParseToken_Console(&p))
1010 *is_multiple = true;
1012 // kill pre-argument whitespace
1013 for (;*p && ISWHITESPACE(*p);p++)
1022 argno = strtol(varname, &endptr, 10);
1025 // whole string is a number
1026 // NOTE: we already made sure we don't have an empty cvar name!
1027 if(argno >= 0 && argno < Cmd_Argc(cmd))
1028 return Cmd_Argv(cmd, argno);
1033 if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CVAR_PRIVATE))
1034 return cvar->string;
1039 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qboolean putquotes)
1041 qboolean quote_quot = !!strchr(quoteset, '"');
1042 qboolean quote_backslash = !!strchr(quoteset, '\\');
1043 qboolean quote_dollar = !!strchr(quoteset, '$');
1052 *out++ = '"'; --outlen;
1058 if(*in == '"' && quote_quot)
1062 *out++ = '\\'; --outlen;
1063 *out++ = '"'; --outlen;
1065 else if(*in == '\\' && quote_backslash)
1069 *out++ = '\\'; --outlen;
1070 *out++ = '\\'; --outlen;
1072 else if(*in == '$' && quote_dollar)
1076 *out++ = '$'; --outlen;
1077 *out++ = '$'; --outlen;
1083 *out++ = *in; --outlen;
1098 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmdalias_t *alias)
1100 static char varname[MAX_INPUTLINE]; // cmd_mutex
1101 static char varval[MAX_INPUTLINE]; // cmd_mutex
1102 const char *varstr = NULL;
1104 qboolean required = false;
1105 qboolean optional = false;
1106 static char asis[] = "asis"; // just to suppress const char warnings
1108 if(varlen >= MAX_INPUTLINE)
1109 varlen = MAX_INPUTLINE - 1;
1110 memcpy(varname, var, varlen);
1111 varname[varlen] = 0;
1112 varfunc = strchr(varname, ' ');
1124 Con_Warnf("Warning: Could not expand $ in alias %s\n", alias->name);
1126 Con_Warnf("Warning: Could not expand $\n");
1134 while((p = strchr(varfunc, '?')))
1137 memmove(p, p+1, strlen(p)); // with final NUL
1140 while((p = strchr(varfunc, '!')))
1143 memmove(p, p+1, strlen(p)); // with final NUL
1146 while((p = strchr(varfunc, ' ')))
1148 memmove(p, p+1, strlen(p)); // with final NUL
1150 // if no function is left, NULL it
1155 if(varname[0] == '$')
1156 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1159 qboolean is_multiple = false;
1160 // Exception: $* and $n- don't use the quoted form by default
1161 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1172 Con_Errorf("Error: Could not expand $%s in alias %s\n", varname, alias->name);
1174 Con_Errorf("Error: Could not expand $%s\n", varname);
1184 Con_Warnf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1186 Con_Warnf("Warning: Could not expand $%s\n", varname);
1187 dpsnprintf(varval, sizeof(varval), "$%s", varname);
1192 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1194 // quote it so it can be used inside double quotes
1195 // we just need to replace " by \", and of course, double backslashes
1196 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1199 else if(!strcmp(varfunc, "asis"))
1204 Con_Printf("Unknown variable function %s\n", varfunc);
1210 Cmd_PreprocessString
1212 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1214 static qboolean Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
1220 // don't crash if there's no room in the outtext buffer
1221 if( maxoutlen == 0 ) {
1224 maxoutlen--; // because of \0
1229 while( *in && outlen < maxoutlen ) {
1231 // this is some kind of expansion, see what comes after the $
1234 // The console does the following preprocessing:
1236 // - $$ is transformed to a single dollar sign.
1237 // - $var or ${var} are expanded to the contents of the named cvar,
1238 // with quotation marks and backslashes quoted so it can safely
1239 // be used inside quotation marks (and it should always be used
1241 // - ${var asis} inserts the cvar value as is, without doing this
1243 // - ${var ?} silently expands to the empty string if
1244 // $var does not exist
1245 // - ${var !} fails expansion and executes nothing if
1246 // $var does not exist
1247 // - prefix the cvar name with a dollar sign to do indirection;
1248 // for example, if $x has the value timelimit, ${$x} will return
1249 // the value of $timelimit
1250 // - when expanding an alias, the special variable name $* refers
1251 // to all alias parameters, and a number refers to that numbered
1252 // alias parameter, where the name of the alias is $0, the first
1253 // parameter is $1 and so on; as a special case, $* inserts all
1254 // parameters, without extra quoting, so one can use $* to just
1255 // pass all parameters around. All parameters starting from $n
1256 // can be referred to as $n- (so $* is equivalent to $1-).
1257 // - ${* q} and ${n- q} force quoting anyway
1259 // Note: when expanding an alias, cvar expansion is done in the SAME step
1260 // as alias expansion so that alias parameters or cvar values containing
1261 // dollar signs have no unwanted bad side effects. However, this needs to
1262 // be accounted for when writing complex aliases. For example,
1263 // alias foo "set x NEW; echo $x"
1264 // actually expands to
1265 // "set x NEW; echo OLD"
1266 // and will print OLD! To work around this, use a second alias:
1267 // alias foo "set x NEW; foo2"
1268 // alias foo2 "echo $x"
1270 // Also note: lines starting with alias are exempt from cvar expansion.
1271 // If you want cvar expansion, write "alias" instead:
1274 // alias foo "echo $x"
1275 // "alias" bar "echo $x"
1278 // foo will print 2, because the variable $x will be expanded when the alias
1279 // gets expanded. bar will print 1, because the variable $x was expanded
1280 // at definition time. foo can be equivalently defined as
1282 // "alias" foo "echo $$x"
1284 // because at definition time, $$ will get replaced to a single $.
1289 } else if(*in == '{') {
1290 varlen = strcspn(in + 1, "}");
1291 if(in[varlen + 1] == '}')
1293 val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1305 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1306 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1313 // insert the cvar value
1314 while(*val && outlen < maxoutlen)
1315 outtext[outlen++] = *val++;
1320 // copy the unexpanded text
1321 outtext[outlen++] = '$';
1322 while(eat && outlen < maxoutlen)
1324 outtext[outlen++] = *in++;
1330 outtext[outlen++] = *in++;
1332 outtext[outlen] = 0;
1340 Called for aliases and fills in the alias into the cbuffer
1343 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmdalias_t *alias)
1345 static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1346 static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1347 qboolean ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1350 // insert at start of command buffer, so that aliases execute in order
1351 // (fixes bug introduced by Black on 20050705)
1353 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1354 // have to make sure that no second variable expansion takes place, otherwise
1355 // alias parameters containing dollar signs can have bad effects.
1356 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1357 Cbuf_InsertText(cmd, buffer2);
1364 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1365 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1369 static void Cmd_List_f (cmd_state_t *cmd)
1371 cmd_function_t *func;
1372 const char *partial;
1377 if (Cmd_Argc(cmd) > 1)
1379 partial = Cmd_Argv(cmd, 1);
1380 len = strlen(partial);
1381 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1391 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1393 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1395 Con_Printf("%s : %s\n", func->name, func->description);
1398 for (func = cmd->engine_functions; func; func = func->next)
1400 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1402 Con_Printf("%s : %s\n", func->name, func->description);
1409 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1411 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1414 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1417 static void Cmd_Apropos_f(cmd_state_t *cmd)
1419 cmd_function_t *func;
1422 const char *partial;
1427 if (Cmd_Argc(cmd) > 1)
1428 partial = Cmd_Args(cmd);
1431 Con_Printf("usage: apropos <string>\n");
1435 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1437 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1440 for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1442 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1443 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1445 Con_Printf ("cvar ");
1446 Cvar_PrintHelp(cvar, true);
1449 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1451 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1452 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1454 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1457 for (func = cmd->engine_functions; func; func = func->next)
1459 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1460 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1462 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1465 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1467 // procede here a bit differently as an alias value always got a final \n
1468 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1469 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1471 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1474 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1484 cmd_iter_t *cmd_iter;
1485 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1487 cmd_state_t *cmd = cmd_iter->cmd;
1488 cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1489 // space for commands and script files
1490 cmd->text.data = cmd->text_buf;
1491 cmd->text.maxsize = sizeof(cmd->text_buf);
1492 cmd->text.cursize = 0;
1493 cmd->null_string = "";
1495 // client console can see server cvars because the user may start a server
1496 cmd_client.cvars = &cvars_all;
1497 cmd_client.cvars_flagsmask = CVAR_CLIENT | CVAR_SERVER;
1498 cmd_client.userdefined = &cmd_userdefined_all;
1499 // stuffcmd from server has access to the reasonable client things, but it probably doesn't need to access the client's server-only cvars
1500 cmd_clientfromserver.cvars = &cvars_all;
1501 cmd_clientfromserver.cvars_flagsmask = CVAR_CLIENT;
1502 cmd_clientfromserver.userdefined = &cmd_userdefined_all;
1503 // dedicated server console can only see server cvars, there is no client
1504 cmd_server.cvars = &cvars_all;
1505 cmd_server.cvars_flagsmask = CVAR_SERVER;
1506 cmd_server.userdefined = &cmd_userdefined_all;
1507 // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1508 cmd_serverfromclient.cvars = &cvars_null;
1509 cmd_serverfromclient.cvars_flagsmask = 0;
1510 cmd_serverfromclient.userdefined = &cmd_userdefined_null;
1513 void Cmd_Init_Commands(qboolean dedicated_server)
1516 // register our commands
1518 // client-only commands
1519 Cmd_AddCommand(&cmd_client, "cmd", Cmd_ForwardToServer_f, "send a console commandline to the server (used by some mods)");
1520 Cmd_AddCommand(&cmd_clientfromserver, "cmd", Cmd_ForwardToServer_f, "send a console commandline to the server (used by some mods)");
1521 Cmd_AddCommand(&cmd_client, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1522 Cmd_AddCommand(&cmd_client, "cprint", Cmd_Centerprint_f, "print something at the screen center");
1524 // maintenance commands used for upkeep of cvars and saved configs
1525 Cmd_AddCommand(&cmd_client, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1526 Cmd_AddCommand(&cmd_client, "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");
1527 Cmd_AddCommand(&cmd_client, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1528 Cmd_AddCommand(&cmd_client, "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)");
1529 Cmd_AddCommand(&cmd_client, "cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
1530 Cmd_AddCommand(&cmd_server, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1531 Cmd_AddCommand(&cmd_server, "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");
1532 Cmd_AddCommand(&cmd_server, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1533 Cmd_AddCommand(&cmd_server, "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)");
1534 Cmd_AddCommand(&cmd_server, "cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
1536 // general console commands used in multiple environments
1537 Cmd_AddCommand(&cmd_client, "exec", Cmd_Exec_f, "execute a script file");
1538 Cmd_AddCommand(&cmd_client, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1539 Cmd_AddCommand(&cmd_client, "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");
1540 Cmd_AddCommand(&cmd_client, "unalias",Cmd_UnAlias_f, "remove an alias");
1541 Cmd_AddCommand(&cmd_client, "set", Cvar_Set_f, "create or change the value of a console variable");
1542 Cmd_AddCommand(&cmd_client, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1543 Cmd_AddCommand(&cmd_client, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1544 Cmd_AddCommand(&cmd_clientfromserver, "exec", Cmd_Exec_f, "execute a script file");
1545 Cmd_AddCommand(&cmd_clientfromserver, "echo", Cmd_Echo_f, "print a message to the console (useful in scripts)");
1546 Cmd_AddCommand(&cmd_clientfromserver, "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");
1547 Cmd_AddCommand(&cmd_clientfromserver, "unalias", Cmd_UnAlias_f, "remove an alias");
1548 Cmd_AddCommand(&cmd_clientfromserver, "set", Cvar_Set_f, "create or change the value of a console variable");
1549 Cmd_AddCommand(&cmd_clientfromserver, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1550 Cmd_AddCommand(&cmd_clientfromserver, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1551 Cmd_AddCommand(&cmd_server, "exec", Cmd_Exec_f, "execute a script file");
1552 Cmd_AddCommand(&cmd_server, "echo", Cmd_Echo_f, "print a message to the console (useful in scripts)");
1553 Cmd_AddCommand(&cmd_server, "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");
1554 Cmd_AddCommand(&cmd_server, "unalias", Cmd_UnAlias_f, "remove an alias");
1555 Cmd_AddCommand(&cmd_server, "set", Cvar_Set_f, "create or change the value of a console variable");
1556 Cmd_AddCommand(&cmd_server, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1557 Cmd_AddCommand(&cmd_server, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1559 #ifdef FILLALLCVARSWITHRUBBISH
1560 Cmd_AddCommand(&cmd_client, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1561 Cmd_AddCommand(&cmd_server, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1562 #endif /* FILLALLCVARSWITHRUBBISH */
1564 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1565 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1566 Cmd_AddCommand(&cmd_client, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1567 Cmd_AddCommand(&cmd_client, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1568 Cmd_AddCommand(&cmd_client, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1569 Cmd_AddCommand(&cmd_server, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1570 Cmd_AddCommand(&cmd_server, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1571 Cmd_AddCommand(&cmd_server, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1573 Cmd_AddCommand(&cmd_client, "defer", Cmd_Defer_f, "execute a command in the future");
1574 Cmd_AddCommand(&cmd_server, "defer", Cmd_Defer_f, "execute a command in the future");
1577 // Support Doom3-style Toggle Command
1578 Cmd_AddCommand(&cmd_client, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1579 Cmd_AddCommand(&cmd_server, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1580 Cmd_AddCommand(&cmd_clientfromserver, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1588 void Cmd_Shutdown(void)
1590 cmd_iter_t *cmd_iter;
1591 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1593 cmd_state_t *cmd = cmd_iter->cmd;
1597 // we usually have this locked when we get here from Host_Quit_f
1601 Mem_FreePool(&cmd->mempool);
1610 int Cmd_Argc (cmd_state_t *cmd)
1620 const char *Cmd_Argv(cmd_state_t *cmd, int arg)
1622 if (arg >= cmd->argc )
1623 return cmd->null_string;
1624 return cmd->argv[arg];
1632 const char *Cmd_Args (cmd_state_t *cmd)
1642 Parses the given string into command line tokens.
1645 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1646 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1655 // skip whitespace up to a /n
1656 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1663 if (*text == '\n' || *text == '\r')
1665 // a newline separates commands in the buffer
1666 if (*text == '\r' && text[1] == '\n')
1678 if (!COM_ParseToken_Console(&text))
1681 if (cmd->argc < MAX_ARGS)
1683 l = (int)strlen(com_token) + 1;
1684 if (cmd->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1686 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1689 memcpy (cmd->tokenizebuffer + cmd->tokenizebufferpos, com_token, l);
1690 cmd->argv[cmd->argc] = cmd->tokenizebuffer + cmd->tokenizebufferpos;
1691 cmd->tokenizebufferpos += l;
1703 void Cmd_AddCommand(cmd_state_t *cmd, const char *cmd_name, xcommand_t function, const char *description)
1705 cmd_function_t *func;
1706 cmd_function_t *prev, *current;
1708 // fail if the command is a variable name
1709 if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1711 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1717 // fail if the command already exists in this interpreter
1718 for (func = cmd->engine_functions; func; func = func->next)
1720 if (!strcmp(cmd_name, func->name))
1722 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1727 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1728 func->name = cmd_name;
1729 func->function = function;
1730 func->description = description;
1731 func->next = cmd->engine_functions;
1733 // insert it at the right alphanumeric position
1734 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1740 cmd->engine_functions = func;
1742 func->next = current;
1746 // mark csqcfunc if the function already exists in the csqc_functions list
1747 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1749 if (!strcmp(cmd_name, func->name))
1751 func->csqcfunc = true; //[515]: csqc
1757 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1758 func->name = cmd_name;
1759 func->function = function;
1760 func->description = description;
1761 func->csqcfunc = true; //[515]: csqc
1762 func->next = cmd->userdefined->csqc_functions;
1764 // insert it at the right alphanumeric position
1765 for (prev = NULL, current = cmd->userdefined->csqc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1771 cmd->userdefined->csqc_functions = func;
1773 func->next = current;
1782 qboolean Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1784 cmd_function_t *func;
1786 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1787 if (!strcmp(cmd_name, func->name))
1790 for (func=cmd->engine_functions ; func ; func=func->next)
1791 if (!strcmp (cmd_name,func->name))
1803 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1805 cmd_function_t *func;
1808 len = strlen(partial);
1814 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1815 if (!strncasecmp(partial, func->name, len))
1818 for (func = cmd->engine_functions; func; func = func->next)
1819 if (!strncasecmp(partial, func->name, len))
1826 Cmd_CompleteCountPossible
1828 New function for tab-completion system
1829 Added by EvilTypeGuy
1830 Thanks to Fett erich@heintz.com
1834 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1836 cmd_function_t *func;
1841 len = strlen(partial);
1846 // Loop through the command list and count all partial matches
1847 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1848 if (!strncasecmp(partial, func->name, len))
1851 for (func = cmd->engine_functions; func; func = func->next)
1852 if (!strncasecmp(partial, func->name, len))
1859 Cmd_CompleteBuildList
1861 New function for tab-completion system
1862 Added by EvilTypeGuy
1863 Thanks to Fett erich@heintz.com
1867 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
1869 cmd_function_t *func;
1872 size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
1875 len = strlen(partial);
1876 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1877 // Loop through the functions lists and print all matches
1878 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1879 if (!strncasecmp(partial, func->name, len))
1880 buf[bpos++] = func->name;
1881 for (func = cmd->engine_functions; func; func = func->next)
1882 if (!strncasecmp(partial, func->name, len))
1883 buf[bpos++] = func->name;
1889 // written by LadyHavoc
1890 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
1892 cmd_function_t *func;
1893 size_t len = strlen(partial);
1894 // Loop through the command list and print all matches
1895 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
1896 if (!strncasecmp(partial, func->name, len))
1897 Con_Printf("^2%s^7: %s\n", func->name, func->description);
1898 for (func = cmd->engine_functions; func; func = func->next)
1899 if (!strncasecmp(partial, func->name, len))
1900 Con_Printf("^2%s^7: %s\n", func->name, func->description);
1906 New function for tab-completion system
1907 Added by EvilTypeGuy
1908 Thanks to Fett erich@heintz.com
1912 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
1917 len = strlen(partial);
1923 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1924 if (!strncasecmp(partial, alias->name, len))
1930 // written by LadyHavoc
1931 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
1934 size_t len = strlen(partial);
1935 // Loop through the alias list and print all matches
1936 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1937 if (!strncasecmp(partial, alias->name, len))
1938 Con_Printf("^5%s^7: %s", alias->name, alias->value);
1943 Cmd_CompleteAliasCountPossible
1945 New function for tab-completion system
1946 Added by EvilTypeGuy
1947 Thanks to Fett erich@heintz.com
1951 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
1959 len = strlen(partial);
1964 // Loop through the command list and count all partial matches
1965 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1966 if (!strncasecmp(partial, alias->name, len))
1973 Cmd_CompleteAliasBuildList
1975 New function for tab-completion system
1976 Added by EvilTypeGuy
1977 Thanks to Fett erich@heintz.com
1981 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
1986 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
1989 len = strlen(partial);
1990 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1991 // Loop through the alias list and print all matches
1992 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1993 if (!strncasecmp(partial, alias->name, len))
1994 buf[bpos++] = alias->name;
2000 // TODO: Make this more generic?
2001 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2003 cmd_function_t *func;
2004 cmd_function_t **next = &cmd->userdefined->csqc_functions;
2018 A complete command line has been parsed, so try to execute it
2019 FIXME: lookupnoadd the token to speed search?
2022 extern hook_t *csqc_concmd;
2024 void Cmd_ExecuteString (cmd_state_t *cmd, const char *text, cmd_source_t src, qboolean lockmutex)
2027 cmd_function_t *func;
2031 oldpos = cmd->tokenizebufferpos;
2034 Cmd_TokenizeString (cmd, text);
2036 // execute the command line
2038 goto done; // no tokens
2041 for (func = cmd->userdefined->csqc_functions; func; func = func->next)
2043 if (!strcasecmp(cmd->argv[0], func->name))
2045 if (func->csqcfunc && Hook_Call(csqc_concmd, text)->bval) //[515]: csqc
2051 for (func = cmd->engine_functions; func; func=func->next)
2053 if (!strcasecmp (cmd->argv[0], func->name))
2059 func->function(cmd);
2061 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2066 func->function(cmd);
2074 // if it's a client command and no command was found, say so.
2075 if (cmd->source == src_client)
2077 Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2082 for (a=cmd->userdefined->alias ; a ; a=a->next)
2084 if (!strcasecmp (cmd->argv[0], a->name))
2086 Cmd_ExecuteAlias(cmd, a);
2092 if (!Cvar_Command(cmd) && host_framecount > 0) {
2093 if (cmd == &cmd_clientfromserver) {
2094 Con_Printf("Server tried to execute \"%s\"\n", Cmd_Argv(cmd, 0));
2096 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2100 cmd->tokenizebufferpos = oldpos;
2108 Cmd_ForwardStringToServer
2110 Sends an entire command string over to the server, unprocessed
2113 void Cmd_ForwardStringToServer (const char *s)
2116 if (cls.state != ca_connected)
2118 Con_Printf("Can't \"%s\", not connected\n", s);
2125 // LadyHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
2126 // attention, it has been eradicated from here, its only (former) use in
2127 // all of darkplaces.
2128 if (cls.protocol == PROTOCOL_QUAKEWORLD)
2129 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
2131 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
2132 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
2134 // say/say_team commands can replace % character codes with status info
2137 if (*s == '%' && s[1])
2139 // handle proquake message macros
2143 case 'l': // current location
2144 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
2146 case 'h': // current health
2147 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
2149 case 'a': // current armor
2150 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
2152 case 'x': // current rockets
2153 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
2155 case 'c': // current cells
2156 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
2158 // silly proquake macros
2159 case 'd': // loc at last death
2160 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
2162 case 't': // current time
2163 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
2165 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
2166 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
2167 dpsnprintf(temp, sizeof(temp), "I need RL");
2168 else if (!cl.stats[STAT_ROCKETS])
2169 dpsnprintf(temp, sizeof(temp), "I need rockets");
2171 dpsnprintf(temp, sizeof(temp), "I have RL");
2173 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
2174 if (cl.stats[STAT_ITEMS] & IT_QUAD)
2177 strlcat(temp, " ", sizeof(temp));
2178 strlcat(temp, "quad", sizeof(temp));
2180 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
2183 strlcat(temp, " ", sizeof(temp));
2184 strlcat(temp, "pent", sizeof(temp));
2186 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
2189 strlcat(temp, " ", sizeof(temp));
2190 strlcat(temp, "eyes", sizeof(temp));
2193 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
2194 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
2195 strlcat(temp, "SSG", sizeof(temp));
2196 strlcat(temp, ":", sizeof(temp));
2197 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
2198 strlcat(temp, "NG", sizeof(temp));
2199 strlcat(temp, ":", sizeof(temp));
2200 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
2201 strlcat(temp, "SNG", sizeof(temp));
2202 strlcat(temp, ":", sizeof(temp));
2203 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
2204 strlcat(temp, "GL", sizeof(temp));
2205 strlcat(temp, ":", sizeof(temp));
2206 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
2207 strlcat(temp, "RL", sizeof(temp));
2208 strlcat(temp, ":", sizeof(temp));
2209 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
2210 strlcat(temp, "LG", sizeof(temp));
2213 // not a recognized macro, print it as-is...
2219 // write the resulting text
2220 SZ_Write(&cls.netcon->message, (unsigned char *)temp, (int)strlen(temp));
2224 MSG_WriteByte(&cls.netcon->message, *s);
2227 MSG_WriteByte(&cls.netcon->message, 0);
2229 else // any other command is passed on as-is
2230 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
2237 Sends the entire command line over to the server
2240 void Cmd_ForwardToServer_f (cmd_state_t *cmd)
2244 if (!strcasecmp(Cmd_Argv(cmd, 0), "cmd"))
2246 // we want to strip off "cmd", so just send the args
2247 s = Cmd_Argc(cmd) > 1 ? Cmd_Args(cmd) : "";
2251 // we need to keep the command name, so send Cmd_Argv(cmd, 0), a space and then Cmd_Args(cmd)
2252 s = va(vabuf, sizeof(vabuf), "%s %s", Cmd_Argv(cmd, 0), Cmd_Argc(cmd) > 1 ? Cmd_Args(cmd) : "");
2254 // don't send an empty forward message if the user tries "cmd" by itself
2257 Cmd_ForwardStringToServer(s);
2265 Returns the position (1 to argc-1) in the command's argument list
2266 where the given parameter apears, or 0 if not present
2270 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2276 Con_Printf ("Cmd_CheckParm: NULL");
2280 for (i = 1; i < Cmd_Argc (cmd); i++)
2281 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2289 void Cmd_SaveInitState(void)
2291 cmd_iter_t *cmd_iter;
2292 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2294 cmd_state_t *cmd = cmd_iter->cmd;
2297 for (f = cmd->userdefined->csqc_functions; f; f = f->next)
2298 f->initstate = true;
2299 for (f = cmd->engine_functions; f; f = f->next)
2300 f->initstate = true;
2301 for (a = cmd->userdefined->alias; a; a = a->next)
2303 a->initstate = true;
2304 a->initialvalue = Mem_strdup(zonemempool, a->value);
2307 Cvar_SaveInitState(&cvars_all);
2310 void Cmd_RestoreInitState(void)
2312 cmd_iter_t *cmd_iter;
2313 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2315 cmd_state_t *cmd = cmd_iter->cmd;
2316 cmd_function_t *f, **fp;
2317 cmdalias_t *a, **ap;
2318 for (fp = &cmd->userdefined->csqc_functions; (f = *fp);)
2324 // destroy this command, it didn't exist at init
2325 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2330 for (fp = &cmd->engine_functions; (f = *fp);)
2336 // destroy this command, it didn't exist at init
2337 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2342 for (ap = &cmd->userdefined->alias; (a = *ap);)
2346 // restore this alias, it existed at init
2347 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2349 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2352 a->value = Mem_strdup(zonemempool, a->initialvalue);
2358 // free this alias, it didn't exist at init...
2359 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2367 Cvar_RestoreInitState(&cvars_all);