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_local;
26 cmd_state_t *cmd_serverfromclient;
28 cmd_userdefined_t cmd_userdefined_all;
29 cmd_userdefined_t cmd_userdefined_null;
31 typedef struct cmd_iter_s {
36 static cmd_iter_t *cmd_iter_all;
38 mempool_t *cbuf_mempool;
40 // we only run the +whatever commandline arguments once
41 qbool host_stuffcmdsrun = false;
43 //=============================================================================
45 void Cbuf_Lock(cmd_buf_t *cbuf)
47 Thread_LockMutex(cbuf->lock);
50 void Cbuf_Unlock(cmd_buf_t *cbuf)
52 Thread_UnlockMutex(cbuf->lock);
60 Causes execution of the remainder of the command buffer to be delayed until
61 next frame. This allows commands like:
62 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
65 static void Cmd_Wait_f (cmd_state_t *cmd)
67 cmd->cbuf->wait = true;
74 Cause a command to be executed after a delay.
77 static cmd_input_t *Cbuf_LinkGet(cmd_buf_t *cbuf, cmd_input_t *existing);
78 static void Cmd_Defer_f (cmd_state_t *cmd)
81 cmd_buf_t *cbuf = cmd->cbuf;
83 if(Cmd_Argc(cmd) == 1)
85 if(List_Is_Empty(&cbuf->deferred))
86 Con_Printf("No commands are pending.\n");
90 List_For_Each(pos, &cbuf->deferred)
92 current = List_Entry(*pos, cmd_input_t, list);
93 Con_Printf("-> In %9.2f: %s\n", current->delay, current->text);
97 else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
99 while(!List_Is_Empty(&cbuf->deferred))
100 List_Move_Tail(cbuf->deferred.next, &cbuf->free);
102 else if(Cmd_Argc(cmd) == 3)
104 const char *text = Cmd_Argv(cmd, 2);
105 current = Cbuf_LinkGet(cbuf, NULL);
106 current->length = strlen(text);
107 current->source = cmd;
108 current->delay = atof(Cmd_Argv(cmd, 1));
110 if(current->size < current->length)
112 current->text = (char *)Mem_Realloc(cbuf_mempool, current->text, current->length + 1);
113 current->size = current->length;
116 strlcpy(current->text, text, current->length + 1);
118 List_Move_Tail(¤t->list, &cbuf->deferred);
122 Con_Printf("usage: defer <seconds> <command>\n"
132 Print something to the center of the screen using SCR_Centerprint
135 static void Cmd_Centerprint_f (cmd_state_t *cmd)
137 char msg[MAX_INPUTLINE];
138 unsigned int i, c, p;
142 strlcpy(msg, Cmd_Argv(cmd,1), sizeof(msg));
143 for(i = 2; i < c; ++i)
145 strlcat(msg, " ", sizeof(msg));
146 strlcat(msg, Cmd_Argv(cmd, i), sizeof(msg));
148 c = (unsigned int)strlen(msg);
149 for(p = 0, i = 0; i < c; ++i)
155 else if(msg[i+1] == '\\')
167 SCR_CenterPrint(msg);
172 =============================================================================
176 =============================================================================
179 static cmd_input_t *Cbuf_LinkGet(cmd_buf_t *cbuf, cmd_input_t *existing)
181 cmd_input_t *ret = NULL;
182 if(existing && existing->pending)
184 else if(!List_Is_Empty(&cbuf->free))
186 ret = List_Entry(*cbuf->free.next, cmd_input_t, list);
188 ret->pending = false;
193 static cmd_input_t *Cmd_AllocInputNode(void)
195 cmd_input_t *node = (cmd_input_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_input_t));
196 node->list.prev = node->list.next = &node->list;
197 node->size = node->length = node->pending = 0;
201 static size_t Cmd_ParseInput (cmd_input_t **output, char **input)
203 size_t pos, cmdsize = 0, start = 0;
204 qbool command = false, lookahead = false;
205 qbool quotes = false, comment = false;
206 qbool escaped = false;
209 * The Quake command-line is super basic. It can be entered in the console
210 * or in config files. A semicolon is used to terminate a command and chain
211 * them together. Otherwise, a newline delineates command input.
213 * In most engines, the Quake command-line is a simple linear text buffer that
214 * is parsed when it executes. In Darkplaces, we use a linked list of command
215 * input and parse the input on the spot.
217 * This was done because Darkplaces allows multiple command interpreters on the
218 * same thread. Previously, each interpreter maintained its own buffer and this
219 * caused problems related to execution order, and maintaining a single simple
220 * buffer for all interpreters makes it non-trivial to keep track of which
221 * command should execute on which interpreter.
224 // Run until command and lookahead are both true, or until we run out of input.
225 for (pos = 0; (*input)[pos]; pos++)
227 // Look for newlines and semicolons. Ignore semicolons in quotes.
228 switch((*input)[pos])
236 if(!comment) // Not a newline so far. Still not a valid command yet.
238 if(!quotes && (*input)[pos] == ';') // Ignore semicolons in quotes.
240 else if (ISCOMMENT((*input), pos)) // Comments
255 switch((*input)[pos])
264 if (!escaped && quotes)
273 if(cmdsize && !command)
276 if(command && lookahead)
285 *output = Cmd_AllocInputNode();
287 if((*output)->pending)
288 offset = (*output)->length;
290 (*output)->length += cmdsize;
292 if((*output)->size < (*output)->length)
294 (*output)->text = (char *)Mem_Realloc(cbuf_mempool, (*output)->text, (*output)->length + 1);
295 (*output)->size = (*output)->length;
298 strlcpy(&(*output)->text[offset], &(*input)[start], cmdsize + 1);
299 (*output)->pending = !lookahead;
302 // Set input to its new position. Can be NULL.
303 *input = &(*input)[pos];
308 // Cloudwalk: Not happy with this, but it works.
309 static void Cbuf_LinkCreate(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text)
311 char *in = (char *)&text[0];
312 cmd_buf_t *cbuf = cmd->cbuf;
313 size_t totalsize = 0, newsize = 0;
314 cmd_input_t *current = NULL;
316 // Slide the pointer down until we reach the end
319 current = Cbuf_LinkGet(cbuf, existing);
320 newsize = Cmd_ParseInput(¤t, &in);
325 if(current != existing)
327 current->source = cmd;
328 List_Move_Tail(¤t->list, head);
331 totalsize += newsize;
333 else if (current == existing && !totalsize)
334 current->pending = false;
338 cbuf->size += totalsize;
345 Adds command text at the end of the buffer
348 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
350 size_t l = strlen(text);
351 cmd_buf_t *cbuf = cmd->cbuf;
352 llist_t llist = {&llist, &llist};
356 if (cbuf->maxsize - cbuf->size <= l)
357 Con_Print("Cbuf_AddText: overflow\n");
360 Cbuf_LinkCreate(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(*cbuf->start.prev, cmd_input_t, list)), text);
361 if(!List_Is_Empty(&llist))
362 List_Splice_Tail(&llist, &cbuf->start);
371 Adds command text immediately after the current command
372 FIXME: actually change the command buffer to do less copying
375 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
377 cmd_buf_t *cbuf = cmd->cbuf;
378 llist_t llist = {&llist, &llist};
379 size_t l = strlen(text);
383 // we need to memmove the existing text and stuff this in before it...
384 if (cbuf->size + l >= cbuf->maxsize)
385 Con_Print("Cbuf_InsertText: overflow\n");
388 Cbuf_LinkCreate(cmd, &llist, List_Entry(*cbuf->start.next, cmd_input_t, list), text);
389 if(!List_Is_Empty(&llist))
390 List_Splice(&llist, &cbuf->start);
398 Cbuf_Execute_Deferred --blub
401 static void Cbuf_Execute_Deferred (cmd_buf_t *cbuf)
404 cmd_input_t *current;
407 if (host.realtime - cbuf->deferred_oldtime < 0 || host.realtime - cbuf->deferred_oldtime > 1800)
408 cbuf->deferred_oldtime = host.realtime;
409 eat = host.realtime - cbuf->deferred_oldtime;
410 if (eat < (1.0 / 120.0))
412 cbuf->deferred_oldtime = host.realtime;
414 List_For_Each(pos, &cbuf->deferred)
416 current = List_Entry(*pos, cmd_input_t, list);
417 current->delay -= eat;
418 if(current->delay <= 0)
420 cbuf->size += current->length;
421 List_Move(pos, &cbuf->start);
422 // We must return and come back next frame or the engine will freeze. Fragile... like glass :3
433 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias );
434 void Cbuf_Execute (cmd_buf_t *cbuf)
436 cmd_input_t *current;
437 char preprocessed[MAX_INPUTLINE];
440 // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
441 cbuf->tokenizebufferpos = 0;
443 while (!List_Is_Empty(&cbuf->start))
446 * Delete the text from the command buffer and move remaining
447 * commands down. This is necessary because commands (exec, alias)
448 * can insert data at the beginning of the text buffer
450 current = List_Entry(*cbuf->start.next, cmd_input_t, list);
452 // Recycle memory so using WASD doesn't cause a malloc and free
453 List_Move_Tail(¤t->list, &cbuf->free);
456 * Assume we're rolling with the current command-line and
457 * always set this false because alias expansion or cbuf insertion
458 * without a newline may set this true, and cause weirdness.
460 current->pending = false;
462 cbuf->size -= current->length;
464 firstchar = current->text;
465 while(*firstchar && ISWHITESPACE(*firstchar))
467 if((strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5])) &&
468 (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4])) &&
469 (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7])))
471 if(Cmd_PreprocessString(current->source, current->text, preprocessed, sizeof(preprocessed), NULL ))
472 Cmd_ExecuteString(current->source, preprocessed, src_local, false);
476 Cmd_ExecuteString (current->source, current->text, src_local, false);
484 * Skip out while text still remains in
485 * buffer, leaving it for next frame
497 Add them exactly as if they had been typed at the console
500 static void Cbuf_Frame_Input(void)
504 while ((line = Sys_ConsoleInput()))
505 Cbuf_AddText(cmd_local, line);
508 void Cbuf_Frame(cmd_buf_t *cbuf)
510 // check for commands typed to the host
513 // R_TimeReport("preconsole");
515 // execute commands queued with the defer command
516 Cbuf_Execute_Deferred(cbuf);
519 SV_LockThreadMutex();
521 SV_UnlockThreadMutex();
524 // R_TimeReport("console");
528 ==============================================================================
532 ==============================================================================
539 Adds command line parameters as script statements
540 Commands lead with a +, and continue until a - or another +
541 quake +prog jctest.qp +cmd amlev1
542 quake -nosound +cmd amlev1
545 static void Cmd_StuffCmds_f (cmd_state_t *cmd)
548 // this is for all commandline options combined (and is bounds checked)
549 char build[MAX_INPUTLINE];
551 if (Cmd_Argc (cmd) != 1)
553 Con_Print("stuffcmds : execute command line parameters\n");
557 // no reason to run the commandline arguments twice
558 if (host_stuffcmdsrun)
561 host_stuffcmdsrun = true;
564 for (i = 0;i < sys.argc;i++)
566 if (sys.argv[i] && sys.argv[i][0] == '+' && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9') && l + strlen(sys.argv[i]) - 1 <= sizeof(build) - 1)
569 while (sys.argv[i][j])
570 build[l++] = sys.argv[i][j++];
572 for (;i < sys.argc;i++)
576 if ((sys.argv[i][0] == '+' || sys.argv[i][0] == '-') && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9'))
578 if (l + strlen(sys.argv[i]) + 4 > sizeof(build) - 1)
581 if (strchr(sys.argv[i], ' '))
583 for (j = 0;sys.argv[i][j];j++)
584 build[l++] = sys.argv[i][j];
585 if (strchr(sys.argv[i], ' '))
592 // now terminate the combined string and prepend it to the command buffer
593 // we already reserved space for the terminator
595 Cbuf_InsertText (cmd, build);
598 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
601 size_t filenameLen = strlen(filename);
603 !strcmp(filename, "default.cfg") ||
604 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
606 if (!strcmp(filename, "config.cfg"))
608 filename = CONFIGFILENAME;
609 if (Sys_CheckParm("-noconfig"))
610 return; // don't execute config.cfg
613 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
616 Con_Printf("couldn't exec %s\n",filename);
619 Con_Printf("execing %s\n",filename);
621 // if executing default.cfg for the first time, lock the cvar defaults
622 // it may seem backwards to insert this text BEFORE the default.cfg
623 // but Cbuf_InsertText inserts before, so this actually ends up after it.
625 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
627 Cbuf_InsertText (cmd, f);
632 // special defaults for specific games go here, these execute before default.cfg
633 // Nehahra pushable crates malfunction in some levels if this is on
634 // Nehahra NPC AI is confused by blowupfallenzombies
638 Cbuf_InsertText(cmd, "\n"
639 "sv_gameplayfix_blowupfallenzombies 0\n"
640 "sv_gameplayfix_findradiusdistancetobox 0\n"
641 "sv_gameplayfix_grenadebouncedownslopes 0\n"
642 "sv_gameplayfix_slidemoveprojectiles 0\n"
643 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
644 "sv_gameplayfix_setmodelrealbox 0\n"
645 "sv_gameplayfix_droptofloorstartsolid 0\n"
646 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
647 "sv_gameplayfix_noairborncorpse 0\n"
648 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
649 "sv_gameplayfix_easierwaterjump 0\n"
650 "sv_gameplayfix_delayprojectiles 0\n"
651 "sv_gameplayfix_multiplethinksperframe 0\n"
652 "sv_gameplayfix_fixedcheckwatertransition 0\n"
653 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
654 "sv_gameplayfix_swiminbmodels 0\n"
655 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
656 "sys_ticrate 0.01388889\n"
658 "r_shadow_bumpscale_basetexture 0\n"
659 "csqc_polygons_defaultmaterial_nocullface 0\n"
663 Cbuf_InsertText(cmd, "\n"
664 "sv_gameplayfix_blowupfallenzombies 0\n"
665 "sv_gameplayfix_findradiusdistancetobox 0\n"
666 "sv_gameplayfix_grenadebouncedownslopes 0\n"
667 "sv_gameplayfix_slidemoveprojectiles 0\n"
668 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
669 "sv_gameplayfix_setmodelrealbox 0\n"
670 "sv_gameplayfix_droptofloorstartsolid 0\n"
671 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
672 "sv_gameplayfix_noairborncorpse 0\n"
673 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
674 "sv_gameplayfix_easierwaterjump 0\n"
675 "sv_gameplayfix_delayprojectiles 0\n"
676 "sv_gameplayfix_multiplethinksperframe 0\n"
677 "sv_gameplayfix_fixedcheckwatertransition 0\n"
678 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
679 "sv_gameplayfix_swiminbmodels 0\n"
680 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
681 "sys_ticrate 0.01388889\n"
683 "r_shadow_bumpscale_basetexture 0\n"
684 "csqc_polygons_defaultmaterial_nocullface 0\n"
687 // 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.
688 // 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
689 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
692 Cbuf_InsertText(cmd, "\n"
693 "sv_gameplayfix_blowupfallenzombies 0\n"
694 "sv_gameplayfix_findradiusdistancetobox 0\n"
695 "sv_gameplayfix_grenadebouncedownslopes 0\n"
696 "sv_gameplayfix_slidemoveprojectiles 0\n"
697 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
698 "sv_gameplayfix_setmodelrealbox 0\n"
699 "sv_gameplayfix_droptofloorstartsolid 0\n"
700 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
701 "sv_gameplayfix_noairborncorpse 0\n"
702 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
703 "sv_gameplayfix_easierwaterjump 0\n"
704 "sv_gameplayfix_delayprojectiles 0\n"
705 "sv_gameplayfix_multiplethinksperframe 0\n"
706 "sv_gameplayfix_fixedcheckwatertransition 0\n"
707 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
708 "sv_gameplayfix_swiminbmodels 0\n"
709 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
712 "r_shadow_bumpscale_basetexture 0\n"
713 "csqc_polygons_defaultmaterial_nocullface 0\n"
716 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
718 Cbuf_InsertText(cmd, "\n"
719 "sv_gameplayfix_blowupfallenzombies 0\n"
720 "sv_gameplayfix_findradiusdistancetobox 0\n"
721 "sv_gameplayfix_grenadebouncedownslopes 0\n"
722 "sv_gameplayfix_slidemoveprojectiles 0\n"
723 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
724 "sv_gameplayfix_setmodelrealbox 0\n"
725 "sv_gameplayfix_droptofloorstartsolid 0\n"
726 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
727 "sv_gameplayfix_noairborncorpse 0\n"
728 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
729 "sv_gameplayfix_easierwaterjump 0\n"
730 "sv_gameplayfix_delayprojectiles 0\n"
731 "sv_gameplayfix_multiplethinksperframe 0\n"
732 "sv_gameplayfix_fixedcheckwatertransition 0\n"
733 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
734 "sv_gameplayfix_swiminbmodels 0\n"
735 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
736 "sys_ticrate 0.01388889\n"
738 "r_shadow_bumpscale_basetexture 0\n"
739 "csqc_polygons_defaultmaterial_nocullface 0\n"
743 Cbuf_InsertText(cmd, "\n"
744 "sv_gameplayfix_blowupfallenzombies 0\n"
745 "sv_gameplayfix_findradiusdistancetobox 0\n"
746 "sv_gameplayfix_grenadebouncedownslopes 0\n"
747 "sv_gameplayfix_slidemoveprojectiles 0\n"
748 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
749 "sv_gameplayfix_setmodelrealbox 0\n"
750 "sv_gameplayfix_droptofloorstartsolid 0\n"
751 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
752 "sv_gameplayfix_noairborncorpse 0\n"
753 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
754 "sv_gameplayfix_easierwaterjump 0\n"
755 "sv_gameplayfix_delayprojectiles 0\n"
756 "sv_gameplayfix_multiplethinksperframe 0\n"
757 "sv_gameplayfix_fixedcheckwatertransition 0\n"
758 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
759 "sv_gameplayfix_swiminbmodels 0\n"
760 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
761 "sys_ticrate 0.01388889\n"
763 "r_shadow_bumpscale_basetexture 4\n"
764 "csqc_polygons_defaultmaterial_nocullface 0\n"
768 Cbuf_InsertText(cmd, "\n"
769 "sv_gameplayfix_blowupfallenzombies 1\n"
770 "sv_gameplayfix_findradiusdistancetobox 1\n"
771 "sv_gameplayfix_grenadebouncedownslopes 1\n"
772 "sv_gameplayfix_slidemoveprojectiles 1\n"
773 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
774 "sv_gameplayfix_setmodelrealbox 1\n"
775 "sv_gameplayfix_droptofloorstartsolid 1\n"
776 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
777 "sv_gameplayfix_noairborncorpse 1\n"
778 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
779 "sv_gameplayfix_easierwaterjump 1\n"
780 "sv_gameplayfix_delayprojectiles 1\n"
781 "sv_gameplayfix_multiplethinksperframe 1\n"
782 "sv_gameplayfix_fixedcheckwatertransition 1\n"
783 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
784 "sv_gameplayfix_swiminbmodels 1\n"
785 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
786 "sys_ticrate 0.01388889\n"
787 "sv_gameplayfix_q2airaccelerate 1\n"
788 "sv_gameplayfix_stepmultipletimes 1\n"
789 "csqc_polygons_defaultmaterial_nocullface 1\n"
790 "con_chatsound_team_mask 13\n"
794 case GAME_VORETOURNAMENT:
795 // 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
796 Cbuf_InsertText(cmd, "\n"
797 "csqc_polygons_defaultmaterial_nocullface 1\n"
798 "con_chatsound_team_mask 13\n"
799 "sv_gameplayfix_customstats 1\n"
802 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
803 case GAME_STEELSTORM:
804 Cbuf_InsertText(cmd, "\n"
805 "sv_gameplayfix_blowupfallenzombies 1\n"
806 "sv_gameplayfix_findradiusdistancetobox 1\n"
807 "sv_gameplayfix_grenadebouncedownslopes 1\n"
808 "sv_gameplayfix_slidemoveprojectiles 1\n"
809 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
810 "sv_gameplayfix_setmodelrealbox 1\n"
811 "sv_gameplayfix_droptofloorstartsolid 1\n"
812 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
813 "sv_gameplayfix_noairborncorpse 1\n"
814 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
815 "sv_gameplayfix_easierwaterjump 1\n"
816 "sv_gameplayfix_delayprojectiles 1\n"
817 "sv_gameplayfix_multiplethinksperframe 1\n"
818 "sv_gameplayfix_fixedcheckwatertransition 1\n"
819 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
820 "sv_gameplayfix_swiminbmodels 1\n"
821 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
822 "sys_ticrate 0.01388889\n"
823 "cl_csqc_generatemousemoveevents 0\n"
824 "csqc_polygons_defaultmaterial_nocullface 1\n"
828 Cbuf_InsertText(cmd, "\n"
829 "sv_gameplayfix_blowupfallenzombies 1\n"
830 "sv_gameplayfix_findradiusdistancetobox 1\n"
831 "sv_gameplayfix_grenadebouncedownslopes 1\n"
832 "sv_gameplayfix_slidemoveprojectiles 1\n"
833 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
834 "sv_gameplayfix_setmodelrealbox 1\n"
835 "sv_gameplayfix_droptofloorstartsolid 1\n"
836 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
837 "sv_gameplayfix_noairborncorpse 1\n"
838 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
839 "sv_gameplayfix_easierwaterjump 1\n"
840 "sv_gameplayfix_delayprojectiles 1\n"
841 "sv_gameplayfix_multiplethinksperframe 1\n"
842 "sv_gameplayfix_fixedcheckwatertransition 1\n"
843 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
844 "sv_gameplayfix_swiminbmodels 1\n"
845 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
846 "sys_ticrate 0.01388889\n"
847 "csqc_polygons_defaultmaterial_nocullface 0\n"
859 static void Cmd_Exec_f (cmd_state_t *cmd)
864 if (Cmd_Argc(cmd) != 2)
866 Con_Print("exec <filename> : execute a script file\n");
870 s = FS_Search(Cmd_Argv(cmd, 1), true, true, NULL);
871 if(!s || !s->numfilenames)
873 Con_Printf("couldn't exec %s\n",Cmd_Argv(cmd, 1));
877 for(i = 0; i < s->numfilenames; ++i)
878 Cmd_Exec(cmd, s->filenames[i]);
888 Just prints the rest of the line to the console
891 static void Cmd_Echo_f (cmd_state_t *cmd)
895 for (i=1 ; i<Cmd_Argc(cmd) ; i++)
896 Con_Printf("%s ",Cmd_Argv(cmd, i));
901 // Support Doom3-style Toggle Console Command
906 Toggles a specified console variable amongst the values specified (default is 0 and 1)
909 static void Cmd_Toggle_f(cmd_state_t *cmd)
911 // Acquire Number of Arguments
912 int nNumArgs = Cmd_Argc(cmd);
915 // No Arguments Specified; Print Usage
916 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");
918 { // Correct Arguments Specified
919 // Acquire Potential CVar
920 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
927 Cvar_SetValueQuick(cvCVar, 0);
929 Cvar_SetValueQuick(cvCVar, 1);
933 { // 0 and Specified Usage
934 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
935 // CVar is Specified Value; // Reset to 0
936 Cvar_SetValueQuick(cvCVar, 0);
938 if(cvCVar->integer == 0)
939 // CVar is 0; Specify Value
940 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
942 // CVar does not match; Reset to 0
943 Cvar_SetValueQuick(cvCVar, 0);
946 { // Variable Values Specified
950 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
951 { // Cycle through Values
952 if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
953 { // Current Value Located; Increment to Next
954 if( (nCnt + 1) == nNumArgs)
955 // Max Value Reached; Reset
956 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
959 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
968 // Value not Found; Reset to Original
969 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
975 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
984 Creates a new command that executes a command string (possibly ; seperated)
987 static void Cmd_Alias_f (cmd_state_t *cmd)
990 char line[MAX_INPUTLINE];
995 if (Cmd_Argc(cmd) == 1)
997 Con_Print("Current alias commands:\n");
998 for (a = cmd->userdefined->alias ; a ; a=a->next)
999 Con_Printf("%s : %s", a->name, a->value);
1003 s = Cmd_Argv(cmd, 1);
1004 if (strlen(s) >= MAX_ALIAS_NAME)
1006 Con_Print("Alias name is too long\n");
1010 // if the alias already exists, reuse it
1011 for (a = cmd->userdefined->alias ; a ; a=a->next)
1013 if (!strcmp(s, a->name))
1022 cmd_alias_t *prev, *current;
1024 a = (cmd_alias_t *)Z_Malloc (sizeof(cmd_alias_t));
1025 strlcpy (a->name, s, sizeof (a->name));
1026 // insert it at the right alphanumeric position
1027 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
1032 cmd->userdefined->alias = a;
1038 // copy the rest of the command line
1039 line[0] = 0; // start out with a null string
1041 for (i=2 ; i < c ; i++)
1044 strlcat (line, " ", sizeof (line));
1045 strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
1047 strlcat (line, "\n", sizeof (line));
1049 alloclen = strlen (line) + 1;
1051 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
1052 a->value = (char *)Z_Malloc (alloclen);
1053 memcpy (a->value, line, alloclen);
1060 Remove existing aliases.
1063 static void Cmd_UnAlias_f (cmd_state_t *cmd)
1069 if(Cmd_Argc(cmd) == 1)
1071 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1075 for(i = 1; i < Cmd_Argc(cmd); ++i)
1077 s = Cmd_Argv(cmd, i);
1079 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
1081 if(!strcmp(s, a->name))
1083 if (a->initstate) // we can not remove init aliases
1085 if(a == cmd->userdefined->alias)
1086 cmd->userdefined->alias = a->next;
1095 Con_Printf("unalias: %s alias not found\n", s);
1100 =============================================================================
1104 =============================================================================
1107 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmd_alias_t *alias, qbool *is_multiple)
1112 static char vabuf[1024]; // cmd_mutex
1115 *is_multiple = false;
1117 if(!varname || !*varname)
1122 if(!strcmp(varname, "*"))
1125 *is_multiple = true;
1126 return Cmd_Args(cmd);
1128 else if(!strcmp(varname, "#"))
1130 return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
1132 else if(varname[strlen(varname) - 1] == '-')
1134 argno = strtol(varname, &endptr, 10);
1135 if(endptr == varname + strlen(varname) - 1)
1137 // whole string is a number, apart from the -
1138 const char *p = Cmd_Args(cmd);
1139 for(; argno > 1; --argno)
1140 if(!COM_ParseToken_Console(&p))
1145 *is_multiple = true;
1147 // kill pre-argument whitespace
1148 for (;*p && ISWHITESPACE(*p);p++)
1157 argno = strtol(varname, &endptr, 10);
1160 // whole string is a number
1161 // NOTE: we already made sure we don't have an empty cvar name!
1162 if(argno >= 0 && argno < Cmd_Argc(cmd))
1163 return Cmd_Argv(cmd, argno);
1168 if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CF_PRIVATE))
1169 return cvar->string;
1174 qbool Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qbool putquotes)
1176 qbool quote_quot = !!strchr(quoteset, '"');
1177 qbool quote_backslash = !!strchr(quoteset, '\\');
1178 qbool quote_dollar = !!strchr(quoteset, '$');
1187 *out++ = '"'; --outlen;
1193 if(*in == '"' && quote_quot)
1197 *out++ = '\\'; --outlen;
1198 *out++ = '"'; --outlen;
1200 else if(*in == '\\' && quote_backslash)
1204 *out++ = '\\'; --outlen;
1205 *out++ = '\\'; --outlen;
1207 else if(*in == '$' && quote_dollar)
1211 *out++ = '$'; --outlen;
1212 *out++ = '$'; --outlen;
1218 *out++ = *in; --outlen;
1233 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmd_alias_t *alias)
1235 static char varname[MAX_INPUTLINE]; // cmd_mutex
1236 static char varval[MAX_INPUTLINE]; // cmd_mutex
1237 const char *varstr = NULL;
1239 qbool required = false;
1240 qbool optional = false;
1241 static char asis[] = "asis"; // just to suppress const char warnings
1243 if(varlen >= MAX_INPUTLINE)
1244 varlen = MAX_INPUTLINE - 1;
1245 memcpy(varname, var, varlen);
1246 varname[varlen] = 0;
1247 varfunc = strchr(varname, ' ');
1259 Con_Printf(CON_WARN "Warning: Could not expand $ in alias %s\n", alias->name);
1261 Con_Printf(CON_WARN "Warning: Could not expand $\n");
1269 while((p = strchr(varfunc, '?')))
1272 memmove(p, p+1, strlen(p)); // with final NUL
1275 while((p = strchr(varfunc, '!')))
1278 memmove(p, p+1, strlen(p)); // with final NUL
1281 while((p = strchr(varfunc, ' ')))
1283 memmove(p, p+1, strlen(p)); // with final NUL
1285 // if no function is left, NULL it
1290 if(varname[0] == '$')
1291 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1294 qbool is_multiple = false;
1295 // Exception: $* and $n- don't use the quoted form by default
1296 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1307 Con_Printf(CON_ERROR "Error: Could not expand $%s in alias %s\n", varname, alias->name);
1309 Con_Printf(CON_ERROR "Error: Could not expand $%s\n", varname);
1319 Con_Printf(CON_WARN "Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1321 Con_Printf(CON_WARN "Warning: Could not expand $%s\n", varname);
1322 dpsnprintf(varval, sizeof(varval), "$%s", varname);
1327 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1329 // quote it so it can be used inside double quotes
1330 // we just need to replace " by \", and of course, double backslashes
1331 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1334 else if(!strcmp(varfunc, "asis"))
1339 Con_Printf("Unknown variable function %s\n", varfunc);
1345 Cmd_PreprocessString
1347 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1349 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias ) {
1355 // don't crash if there's no room in the outtext buffer
1356 if( maxoutlen == 0 ) {
1359 maxoutlen--; // because of \0
1364 while( *in && outlen < maxoutlen ) {
1366 // this is some kind of expansion, see what comes after the $
1369 // The console does the following preprocessing:
1371 // - $$ is transformed to a single dollar sign.
1372 // - $var or ${var} are expanded to the contents of the named cvar,
1373 // with quotation marks and backslashes quoted so it can safely
1374 // be used inside quotation marks (and it should always be used
1376 // - ${var asis} inserts the cvar value as is, without doing this
1378 // - ${var ?} silently expands to the empty string if
1379 // $var does not exist
1380 // - ${var !} fails expansion and executes nothing if
1381 // $var does not exist
1382 // - prefix the cvar name with a dollar sign to do indirection;
1383 // for example, if $x has the value timelimit, ${$x} will return
1384 // the value of $timelimit
1385 // - when expanding an alias, the special variable name $* refers
1386 // to all alias parameters, and a number refers to that numbered
1387 // alias parameter, where the name of the alias is $0, the first
1388 // parameter is $1 and so on; as a special case, $* inserts all
1389 // parameters, without extra quoting, so one can use $* to just
1390 // pass all parameters around. All parameters starting from $n
1391 // can be referred to as $n- (so $* is equivalent to $1-).
1392 // - ${* q} and ${n- q} force quoting anyway
1394 // Note: when expanding an alias, cvar expansion is done in the SAME step
1395 // as alias expansion so that alias parameters or cvar values containing
1396 // dollar signs have no unwanted bad side effects. However, this needs to
1397 // be accounted for when writing complex aliases. For example,
1398 // alias foo "set x NEW; echo $x"
1399 // actually expands to
1400 // "set x NEW; echo OLD"
1401 // and will print OLD! To work around this, use a second alias:
1402 // alias foo "set x NEW; foo2"
1403 // alias foo2 "echo $x"
1405 // Also note: lines starting with alias are exempt from cvar expansion.
1406 // If you want cvar expansion, write "alias" instead:
1409 // alias foo "echo $x"
1410 // "alias" bar "echo $x"
1413 // foo will print 2, because the variable $x will be expanded when the alias
1414 // gets expanded. bar will print 1, because the variable $x was expanded
1415 // at definition time. foo can be equivalently defined as
1417 // "alias" foo "echo $$x"
1419 // because at definition time, $$ will get replaced to a single $.
1424 } else if(*in == '{') {
1425 varlen = strcspn(in + 1, "}");
1426 if(in[varlen + 1] == '}')
1428 val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1440 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1441 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1448 // insert the cvar value
1449 while(*val && outlen < maxoutlen)
1450 outtext[outlen++] = *val++;
1455 // copy the unexpanded text
1456 outtext[outlen++] = '$';
1457 while(eat && outlen < maxoutlen)
1459 outtext[outlen++] = *in++;
1465 outtext[outlen++] = *in++;
1467 outtext[outlen] = 0;
1475 Called for aliases and fills in the alias into the cbuffer
1478 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmd_alias_t *alias)
1480 static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1481 static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1482 qbool ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1485 // insert at start of command buffer, so that aliases execute in order
1486 // (fixes bug introduced by Black on 20050705)
1488 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1489 // have to make sure that no second variable expansion takes place, otherwise
1490 // alias parameters containing dollar signs can have bad effects.
1491 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1492 Cbuf_InsertText(cmd, buffer2);
1499 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1500 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1504 static void Cmd_List_f (cmd_state_t *cmd)
1506 cmd_function_t *func;
1507 const char *partial;
1512 if (Cmd_Argc(cmd) > 1)
1514 partial = Cmd_Argv(cmd, 1);
1515 len = strlen(partial);
1516 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1526 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1528 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1530 Con_Printf("%s : %s\n", func->name, func->description);
1533 for (func = cmd->engine_functions; func; func = func->next)
1535 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1537 Con_Printf("%s : %s\n", func->name, func->description);
1544 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1546 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1549 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1552 static void Cmd_Apropos_f(cmd_state_t *cmd)
1554 cmd_function_t *func;
1557 const char *partial;
1562 if (Cmd_Argc(cmd) > 1)
1563 partial = Cmd_Args(cmd);
1566 Con_Printf("usage: %s <string>\n",Cmd_Argv(cmd, 0));
1570 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1572 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1575 for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1577 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1578 matchpattern_with_separator(cvar->description, partial, true, "", false))
1580 Con_Printf ("cvar ");
1581 Cvar_PrintHelp(cvar, cvar->name, true);
1584 for (int i = 0; i < cvar->aliasindex; i++)
1586 if (matchpattern_with_separator(cvar->aliases[i], partial, true, "", false))
1588 Con_Printf ("cvar ");
1589 Cvar_PrintHelp(cvar, cvar->aliases[i], true);
1594 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1596 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1597 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1599 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1602 for (func = cmd->engine_functions; func; func = func->next)
1604 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1605 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1607 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1610 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1612 // procede here a bit differently as an alias value always got a final \n
1613 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1614 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1616 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1619 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1622 static cmd_state_t *Cmd_AddInterpreter(cmd_buf_t *cbuf, cvar_state_t *cvars, int cvars_flagsmask, int cmds_flagsmask, cmd_userdefined_t *userdefined)
1624 cmd_state_t *cmd = (cmd_state_t *)Mem_Alloc(tempmempool, sizeof(cmd_state_t));
1626 cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1627 // space for commands and script files
1629 cmd->null_string = "";
1632 cmd->cvars_flagsmask = cvars_flagsmask;
1633 cmd->cmd_flags = cmds_flagsmask;
1634 cmd->userdefined = userdefined;
1647 cbuf_mempool = Mem_AllocPool("Command buffer", 0, NULL);
1648 cbuf = (cmd_buf_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_buf_t));
1649 cbuf->maxsize = 655360;
1650 cbuf->lock = Thread_CreateMutex();
1654 cbuf->start.prev = cbuf->start.next = &(cbuf->start);
1655 cbuf->deferred.prev = cbuf->deferred.next = &(cbuf->deferred);
1656 cbuf->free.prev = cbuf->free.next = &(cbuf->free);
1658 // FIXME: Get rid of cmd_iter_all eventually. This is just a hack to reduce the amount of work to make the interpreters dynamic.
1659 cmd_iter_all = (cmd_iter_t *)Mem_Alloc(tempmempool, sizeof(cmd_iter_t) * 3);
1662 cmd_iter_all[0].cmd = cmd_local = Cmd_AddInterpreter(cbuf, &cvars_all, CF_CLIENT | CF_SERVER, CF_CLIENT | CF_CLIENT_FROM_SERVER | CF_SERVER_FROM_CLIENT, &cmd_userdefined_all);
1663 cmd_local->Handle = Cmd_CL_Callback;
1664 cmd_local->NotFound = NULL;
1666 // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1667 cmd_iter_all[1].cmd = cmd_serverfromclient = Cmd_AddInterpreter(cbuf, &cvars_null, 0, CF_SERVER_FROM_CLIENT | CF_USERINFO, &cmd_userdefined_null);
1668 cmd_serverfromclient->Handle = Cmd_SV_Callback;
1669 cmd_serverfromclient->NotFound = Cmd_SV_NotFound;
1671 cmd_iter_all[2].cmd = NULL;
1673 // register our commands
1675 // client-only commands
1676 Cmd_AddCommand(CF_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1677 Cmd_AddCommand(CF_CLIENT, "cprint", Cmd_Centerprint_f, "print something at the screen center");
1679 // maintenance commands used for upkeep of cvars and saved configs
1680 Cmd_AddCommand(CF_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1681 Cmd_AddCommand(CF_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");
1682 Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1683 Cmd_AddCommand(CF_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)");
1684 Cmd_AddCommand(CF_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)");
1686 // general console commands used in multiple environments
1687 Cmd_AddCommand(CF_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1688 Cmd_AddCommand(CF_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1689 Cmd_AddCommand(CF_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");
1690 Cmd_AddCommand(CF_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1691 Cmd_AddCommand(CF_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1692 Cmd_AddCommand(CF_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1693 Cmd_AddCommand(CF_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1695 #ifdef FILLALLCVARSWITHRUBBISH
1696 Cmd_AddCommand(CF_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1697 #endif /* FILLALLCVARSWITHRUBBISH */
1699 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1700 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1701 Cmd_AddCommand(CF_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1702 Cmd_AddCommand(CF_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1703 Cmd_AddCommand(CF_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1704 Cmd_AddCommand(CF_SHARED, "find", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1706 Cmd_AddCommand(CF_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1709 // Support Doom3-style Toggle Command
1710 Cmd_AddCommand(CF_SHARED | CF_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1718 void Cmd_Shutdown(void)
1720 cmd_iter_t *cmd_iter;
1721 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1723 cmd_state_t *cmd = cmd_iter->cmd;
1725 if (cmd->cbuf->lock)
1727 // we usually have this locked when we get here from Host_Quit_f
1728 Cbuf_Unlock(cmd->cbuf);
1731 Mem_FreePool(&cmd->mempool);
1740 int Cmd_Argc (cmd_state_t *cmd)
1750 const char *Cmd_Argv(cmd_state_t *cmd, int arg)
1752 if (arg >= cmd->argc )
1753 return cmd->null_string;
1754 return cmd->argv[arg];
1762 const char *Cmd_Args (cmd_state_t *cmd)
1771 Parses the given string into command line tokens.
1774 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1775 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1781 cmd->cmdline = NULL;
1785 // skip whitespace up to a /n
1786 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1793 if (*text == '\n' || *text == '\r')
1795 // a newline separates commands in the buffer
1796 if (*text == '\r' && text[1] == '\n')
1806 cmd->cmdline = text;
1810 if (!COM_ParseToken_Console(&text))
1813 if (cmd->argc < MAX_ARGS)
1815 l = (int)strlen(com_token) + 1;
1816 if (cmd->cbuf->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1818 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1821 memcpy (cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos, com_token, l);
1822 cmd->argv[cmd->argc] = cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos;
1823 cmd->cbuf->tokenizebufferpos += l;
1835 void Cmd_AddCommand(int flags, const char *cmd_name, xcommand_t function, const char *description)
1837 cmd_function_t *func;
1838 cmd_function_t *prev, *current;
1842 for (i = 0; i < 2; i++)
1844 cmd = cmd_iter_all[i].cmd;
1845 if (flags & cmd->cmd_flags)
1847 // fail if the command is a variable name
1848 if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1850 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1856 // fail if the command already exists in this interpreter
1857 for (func = cmd->engine_functions; func; func = func->next)
1859 if (!strcmp(cmd_name, func->name))
1861 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1866 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1867 func->flags = flags;
1868 func->name = cmd_name;
1869 func->function = function;
1870 func->description = description;
1871 func->next = cmd->engine_functions;
1873 // insert it at the right alphanumeric position
1874 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1880 cmd->engine_functions = func;
1882 func->next = current;
1886 // mark qcfunc if the function already exists in the qc_functions list
1887 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1889 if (!strcmp(cmd_name, func->name))
1891 func->qcfunc = true; //[515]: csqc
1897 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1898 func->flags = flags;
1899 func->name = cmd_name;
1900 func->function = function;
1901 func->description = description;
1902 func->qcfunc = true; //[515]: csqc
1903 func->next = cmd->userdefined->qc_functions;
1905 // insert it at the right alphanumeric position
1906 for (prev = NULL, current = cmd->userdefined->qc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1912 cmd->userdefined->qc_functions = func;
1914 func->next = current;
1925 qbool Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1927 cmd_function_t *func;
1929 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1930 if (!strcmp(cmd_name, func->name))
1933 for (func=cmd->engine_functions ; func ; func=func->next)
1934 if (!strcmp (cmd_name,func->name))
1946 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1948 cmd_function_t *func;
1951 len = strlen(partial);
1957 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1958 if (!strncasecmp(partial, func->name, len))
1961 for (func = cmd->engine_functions; func; func = func->next)
1962 if (!strncasecmp(partial, func->name, len))
1969 Cmd_CompleteCountPossible
1971 New function for tab-completion system
1972 Added by EvilTypeGuy
1973 Thanks to Fett erich@heintz.com
1977 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1979 cmd_function_t *func;
1984 len = strlen(partial);
1989 // Loop through the command list and count all partial matches
1990 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1991 if (!strncasecmp(partial, func->name, len))
1994 for (func = cmd->engine_functions; func; func = func->next)
1995 if (!strncasecmp(partial, func->name, len))
2002 Cmd_CompleteBuildList
2004 New function for tab-completion system
2005 Added by EvilTypeGuy
2006 Thanks to Fett erich@heintz.com
2010 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
2012 cmd_function_t *func;
2015 size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
2018 len = strlen(partial);
2019 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2020 // Loop through the functions lists and print all matches
2021 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2022 if (!strncasecmp(partial, func->name, len))
2023 buf[bpos++] = func->name;
2024 for (func = cmd->engine_functions; func; func = func->next)
2025 if (!strncasecmp(partial, func->name, len))
2026 buf[bpos++] = func->name;
2032 // written by LadyHavoc
2033 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
2035 cmd_function_t *func;
2036 size_t len = strlen(partial);
2037 // Loop through the command list and print all matches
2038 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2039 if (!strncasecmp(partial, func->name, len))
2040 Con_Printf("^2%s^7: %s\n", func->name, func->description);
2041 for (func = cmd->engine_functions; func; func = func->next)
2042 if (!strncasecmp(partial, func->name, len))
2043 Con_Printf("^2%s^7: %s\n", func->name, func->description);
2049 New function for tab-completion system
2050 Added by EvilTypeGuy
2051 Thanks to Fett erich@heintz.com
2055 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
2060 len = strlen(partial);
2066 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2067 if (!strncasecmp(partial, alias->name, len))
2073 // written by LadyHavoc
2074 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
2077 size_t len = strlen(partial);
2078 // Loop through the alias list and print all matches
2079 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2080 if (!strncasecmp(partial, alias->name, len))
2081 Con_Printf("^5%s^7: %s", alias->name, alias->value);
2086 Cmd_CompleteAliasCountPossible
2088 New function for tab-completion system
2089 Added by EvilTypeGuy
2090 Thanks to Fett erich@heintz.com
2094 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
2102 len = strlen(partial);
2107 // Loop through the command list and count all partial matches
2108 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2109 if (!strncasecmp(partial, alias->name, len))
2116 Cmd_CompleteAliasBuildList
2118 New function for tab-completion system
2119 Added by EvilTypeGuy
2120 Thanks to Fett erich@heintz.com
2124 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
2129 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
2132 len = strlen(partial);
2133 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2134 // Loop through the alias list and print all matches
2135 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2136 if (!strncasecmp(partial, alias->name, len))
2137 buf[bpos++] = alias->name;
2143 // TODO: Make this more generic?
2144 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2146 cmd_function_t *func;
2147 cmd_function_t **next = &cmd->userdefined->qc_functions;
2157 extern cvar_t sv_cheats;
2160 * Cloudwalk FIXME: This idea sounded great in my head but...
2161 * How do we handle commands that can be received by the client,
2162 * but which the server can also execute locally?
2164 * If we create a callback where the engine will forward to server
2165 * but try to execute the command locally if it's dedicated,
2166 * we're back to intermixing client and server code which I'm
2167 * trying to avoid. There's no other way I can think of to
2168 * implement that behavior that doesn't involve an #ifdef, or
2169 * making a mess of hooks.
2171 qbool Cmd_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2174 func->function(cmd);
2176 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2180 qbool Cmd_CL_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2182 // TODO: Assign these functions to QC commands directly?
2185 if(((func->flags & CF_CLIENT) && CL_VM_ConsoleCommand(text)) ||
2186 ((func->flags & CF_SERVER) && SV_VM_ConsoleCommand(text)))
2189 if (func->flags & CF_SERVER_FROM_CLIENT)
2191 if(host_isclient.integer)
2193 CL_ForwardToServer_f(cmd);
2196 else if(!(func->flags & CF_SERVER))
2198 Con_Printf("Cannot execute client commands from a dedicated server console.\n");
2202 return Cmd_Callback(cmd, func, text, src);
2205 qbool Cmd_SV_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2207 if(func->qcfunc && (func->flags & CF_SERVER))
2208 return SV_VM_ConsoleCommand(text);
2209 else if (src == src_client)
2211 if((func->flags & CF_CHEAT) && !sv_cheats.integer)
2212 SV_ClientPrintf("No cheats allowed. The server must have sv_cheats set to 1\n");
2214 func->function(cmd);
2220 qbool Cmd_SV_NotFound(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2222 if (cmd->source == src_client)
2224 Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2233 A complete command line has been parsed, so try to execute it
2234 FIXME: lookupnoadd the token to speed search?
2237 void Cmd_ExecuteString (cmd_state_t *cmd, const char *text, cmd_source_t src, qbool lockmutex)
2240 cmd_function_t *func;
2243 Cbuf_Lock(cmd->cbuf);
2244 oldpos = cmd->cbuf->tokenizebufferpos;
2247 Cmd_TokenizeString (cmd, text);
2249 // execute the command line
2251 goto done; // no tokens
2254 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2256 if (!strcasecmp(cmd->argv[0], func->name))
2258 if(cmd->Handle(cmd, func, text, src))
2263 for (func = cmd->engine_functions; func; func=func->next)
2265 if (!strcasecmp (cmd->argv[0], func->name))
2267 if(cmd->Handle(cmd, func, text, src))
2272 // if it's a client command and no command was found, say so.
2275 if(cmd->NotFound(cmd, func, text, src))
2280 for (a=cmd->userdefined->alias ; a ; a=a->next)
2282 if (!strcasecmp (cmd->argv[0], a->name))
2284 Cmd_ExecuteAlias(cmd, a);
2290 if (!Cvar_Command(cmd) && host.framecount > 0)
2291 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2293 cmd->cbuf->tokenizebufferpos = oldpos;
2295 Cbuf_Unlock(cmd->cbuf);
2302 Returns the position (1 to argc-1) in the command's argument list
2303 where the given parameter apears, or 0 if not present
2307 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2313 Con_Printf ("Cmd_CheckParm: NULL");
2317 for (i = 1; i < Cmd_Argc (cmd); i++)
2318 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2326 void Cmd_SaveInitState(void)
2328 cmd_iter_t *cmd_iter;
2329 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2331 cmd_state_t *cmd = cmd_iter->cmd;
2334 for (f = cmd->userdefined->qc_functions; f; f = f->next)
2335 f->initstate = true;
2336 for (f = cmd->engine_functions; f; f = f->next)
2337 f->initstate = true;
2338 for (a = cmd->userdefined->alias; a; a = a->next)
2340 a->initstate = true;
2341 a->initialvalue = Mem_strdup(zonemempool, a->value);
2344 Cvar_SaveInitState(&cvars_all);
2347 void Cmd_RestoreInitState(void)
2349 cmd_iter_t *cmd_iter;
2350 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2352 cmd_state_t *cmd = cmd_iter->cmd;
2353 cmd_function_t *f, **fp;
2354 cmd_alias_t *a, **ap;
2355 for (fp = &cmd->userdefined->qc_functions; (f = *fp);)
2361 // destroy this command, it didn't exist at init
2362 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2367 for (fp = &cmd->engine_functions; (f = *fp);)
2373 // destroy this command, it didn't exist at init
2374 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2379 for (ap = &cmd->userdefined->alias; (a = *ap);)
2383 // restore this alias, it existed at init
2384 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2386 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2389 a->value = Mem_strdup(zonemempool, a->initialvalue);
2395 // free this alias, it didn't exist at init...
2396 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2404 Cvar_RestoreInitState(&cvars_all);