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_NodeGet(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");
89 List_For_Each_Entry(current, &cbuf->deferred, cmd_input_t, list)
90 Con_Printf("-> In %9.2f: %s\n", current->delay, current->text);
93 else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
95 while(!List_Is_Empty(&cbuf->deferred))
96 List_Move_Tail(cbuf->deferred.next, &cbuf->free);
98 else if(Cmd_Argc(cmd) == 3)
100 const char *text = Cmd_Argv(cmd, 2);
101 current = Cbuf_NodeGet(cbuf, NULL);
102 current->length = strlen(text);
103 current->source = cmd;
104 current->delay = atof(Cmd_Argv(cmd, 1));
106 if(current->size < current->length)
108 current->text = (char *)Mem_Realloc(cbuf_mempool, current->text, current->length + 1);
109 current->size = current->length;
112 strlcpy(current->text, text, current->length + 1);
114 List_Move_Tail(¤t->list, &cbuf->deferred);
118 Con_Printf("usage: defer <seconds> <command>\n"
128 Print something to the center of the screen using SCR_Centerprint
131 static void Cmd_Centerprint_f (cmd_state_t *cmd)
133 char msg[MAX_INPUTLINE];
134 unsigned int i, c, p;
138 strlcpy(msg, Cmd_Argv(cmd,1), sizeof(msg));
139 for(i = 2; i < c; ++i)
141 strlcat(msg, " ", sizeof(msg));
142 strlcat(msg, Cmd_Argv(cmd, i), sizeof(msg));
144 c = (unsigned int)strlen(msg);
145 for(p = 0, i = 0; i < c; ++i)
151 else if(msg[i+1] == '\\')
163 SCR_CenterPrint(msg);
168 =============================================================================
172 * The Quake command-line is super basic. It can be entered in the console
173 * or in config files. A semicolon is used to terminate a command and chain
174 * them together. Otherwise, a newline delineates command input.
176 * In most engines, the Quake command-line is a simple linear text buffer that
177 * is parsed when it executes. In Darkplaces, we use a linked list of command
178 * input and parse the input on the spot.
180 * This was done because Darkplaces allows multiple command interpreters on the
181 * same thread. Previously, each interpreter maintained its own buffer and this
182 * caused problems related to execution order, and maintaining a single simple
183 * buffer for all interpreters makes it non-trivial to keep track of which
184 * command should execute on which interpreter.
186 =============================================================================
193 Returns an existing buffer node for appending or reuse, or allocates a new one
196 static cmd_input_t *Cbuf_NodeGet(cmd_buf_t *cbuf, cmd_input_t *existing)
199 if(existing && existing->pending)
201 else if(!List_Is_Empty(&cbuf->free))
203 node = List_Entry(cbuf->free.next, cmd_input_t, list);
204 node->length = node->pending = 0;
208 node = (cmd_input_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_input_t));
209 node->list.prev = node->list.next = &node->list;
210 node->size = node->length = node->pending = 0;
219 Copies a command string into a buffer node
222 static void Cbuf_LinkString(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool leavepending, unsigned int cmdsize)
224 cmd_buf_t *cbuf = cmd->cbuf;
225 cmd_input_t *node = Cbuf_NodeGet(cbuf, existing);
226 unsigned int offset = node->length; // > 0 if(pending)
228 // node will match existing if its text was pending continuation
232 List_Move_Tail(&node->list, head);
235 node->length += cmdsize;
236 if(node->size < node->length)
238 node->text = (char *)Mem_Realloc(cbuf_mempool, node->text, node->length + 1);
239 node->size = node->length;
241 cbuf->size += cmdsize;
243 strlcpy(&node->text[offset], text, cmdsize + 1); // always sets the last char to \0
244 //Con_Printf("^5Cbuf_LinkString(): %s `^7%s^5`\n", node->pending ? "append" : "new", &node->text[offset]);
245 node->pending = leavepending;
252 Parses text to isolate command strings for linking into the buffer
253 separators: \n \r or unquoted and uncommented ';'
256 static void Cbuf_ParseText(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool allowpending)
258 unsigned int cmdsize = 0, start = 0, pos;
259 qbool quotes = false, comment = false;
261 for (pos = 0; text[pos]; ++pos)
266 if (comment || quotes)
271 quotes = false; // matches div0-stable
274 Cbuf_LinkString(cmd, head, existing, &text[start], false, cmdsize);
277 else if (existing && existing->pending) // all I got was this lousy \n
278 existing->pending = false;
279 continue; // don't increment cmdsize
282 if (!quotes && text[pos + 1] == '/' && (pos == 0 || ISWHITESPACE(text[pos - 1])))
286 if (!comment && (pos == 0 || text[pos - 1] != '\\'))
299 if (cmdsize) // the line didn't end yet but we do have a string
300 Cbuf_LinkString(cmd, head, existing, &text[start], allowpending, cmdsize);
307 Adds command text at the end of the buffer
310 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
312 size_t l = strlen(text);
313 cmd_buf_t *cbuf = cmd->cbuf;
314 llist_t llist = {&llist, &llist};
318 if (cbuf->maxsize - cbuf->size <= l)
319 Con_Print("Cbuf_AddText: overflow\n");
322 // If the string terminates but the (last) line doesn't, the node will be left in the pending state (to be continued).
323 Cbuf_ParseText(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(cbuf->start.prev, cmd_input_t, list)), text, true);
324 List_Splice_Tail(&llist, &cbuf->start);
333 Adds command text immediately after the current command
336 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
338 cmd_buf_t *cbuf = cmd->cbuf;
339 llist_t llist = {&llist, &llist};
340 size_t l = strlen(text);
344 if (cbuf->size + l >= cbuf->maxsize)
345 Con_Print("Cbuf_InsertText: overflow\n");
348 // bones_was_here assertion: when prepending to the buffer it never makes sense to leave node(s) in the `pending` state,
349 // it would have been impossible to append to such text later in the old raw text buffer,
350 // and allowing it causes bugs when .cfg files lack \n at EOF (see: https://gitlab.com/xonotic/darkplaces/-/issues/378).
351 Cbuf_ParseText(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(cbuf->start.next, cmd_input_t, list)), text, false);
352 List_Splice(&llist, &cbuf->start);
360 Cbuf_Execute_Deferred --blub
363 static void Cbuf_Execute_Deferred (cmd_buf_t *cbuf)
365 cmd_input_t *current;
368 if (host.realtime - cbuf->deferred_oldtime < 0 || host.realtime - cbuf->deferred_oldtime > 1800)
369 cbuf->deferred_oldtime = host.realtime;
370 eat = host.realtime - cbuf->deferred_oldtime;
371 if (eat < (1.0 / 120.0))
373 cbuf->deferred_oldtime = host.realtime;
375 List_For_Each_Entry(current, &cbuf->deferred, cmd_input_t, list)
377 current->delay -= eat;
378 if(current->delay <= 0)
380 cbuf->size += current->length;
381 List_Move(¤t->list, &cbuf->start);
382 // We must return and come back next frame or the engine will freeze. Fragile... like glass :3
393 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias );
394 void Cbuf_Execute (cmd_buf_t *cbuf)
396 cmd_input_t *current;
397 char preprocessed[MAX_INPUTLINE];
400 // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
401 cbuf->tokenizebufferpos = 0;
403 while (!List_Is_Empty(&cbuf->start))
406 * Delete the text from the command buffer and move remaining
407 * commands down. This is necessary because commands (exec, alias)
408 * can insert data at the beginning of the text buffer
410 current = List_Entry(cbuf->start.next, cmd_input_t, list);
412 // Recycle memory so using WASD doesn't cause a malloc and free
413 List_Move_Tail(¤t->list, &cbuf->free);
416 * Assume we're rolling with the current command-line and
417 * always set this false because alias expansion or cbuf insertion
418 * without a newline may set this true, and cause weirdness.
420 current->pending = false;
422 cbuf->size -= current->length;
424 firstchar = current->text;
425 while(*firstchar && ISWHITESPACE(*firstchar))
427 if((strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5])) &&
428 (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4])) &&
429 (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7])))
431 if(Cmd_PreprocessString(current->source, current->text, preprocessed, sizeof(preprocessed), NULL ))
432 Cmd_ExecuteString(current->source, preprocessed, src_local, false);
436 Cmd_ExecuteString (current->source, current->text, src_local, false);
444 * Skip out while text still remains in
445 * buffer, leaving it for next frame
457 Add them exactly as if they had been typed at the console
460 static void Cbuf_Frame_Input(void)
464 while ((line = Sys_ConsoleInput()))
465 Cbuf_AddText(cmd_local, line);
468 void Cbuf_Frame(cmd_buf_t *cbuf)
470 // check for commands typed to the host
473 // R_TimeReport("preconsole");
475 // execute commands queued with the defer command
476 Cbuf_Execute_Deferred(cbuf);
479 SV_LockThreadMutex();
481 SV_UnlockThreadMutex();
484 // R_TimeReport("console");
488 ==============================================================================
492 ==============================================================================
499 Adds command line parameters as script statements
500 Commands lead with a +, and continue until a - or another +
501 quake +prog jctest.qp +cmd amlev1
502 quake -nosound +cmd amlev1
505 static void Cmd_StuffCmds_f (cmd_state_t *cmd)
508 // this is for all commandline options combined (and is bounds checked)
509 char build[MAX_INPUTLINE];
511 if (Cmd_Argc (cmd) != 1)
513 Con_Print("stuffcmds : execute command line parameters\n");
517 // no reason to run the commandline arguments twice
518 if (host_stuffcmdsrun)
521 host_stuffcmdsrun = true;
524 for (i = 0;i < sys.argc;i++)
526 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)
529 while (sys.argv[i][j])
530 build[l++] = sys.argv[i][j++];
532 for (;i < sys.argc;i++)
536 if ((sys.argv[i][0] == '+' || sys.argv[i][0] == '-') && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9'))
538 if (l + strlen(sys.argv[i]) + 4 > sizeof(build) - 1)
541 if (strchr(sys.argv[i], ' '))
543 for (j = 0;sys.argv[i][j];j++)
544 build[l++] = sys.argv[i][j];
545 if (strchr(sys.argv[i], ' '))
552 // now terminate the combined string and prepend it to the command buffer
553 // we already reserved space for the terminator
555 Cbuf_InsertText (cmd, build);
558 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
561 size_t filenameLen = strlen(filename);
563 !strcmp(filename, "default.cfg") ||
564 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
566 if (!strcmp(filename, "config.cfg"))
568 filename = CONFIGFILENAME;
569 if (Sys_CheckParm("-noconfig"))
570 return; // don't execute config.cfg
573 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
576 Con_Printf("couldn't exec %s\n",filename);
579 Con_Printf("execing %s\n",filename);
581 // if executing default.cfg for the first time, lock the cvar defaults
582 // it may seem backwards to insert this text BEFORE the default.cfg
583 // but Cbuf_InsertText inserts before, so this actually ends up after it.
585 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
587 Cbuf_InsertText (cmd, f);
592 // special defaults for specific games go here, these execute before default.cfg
593 // Nehahra pushable crates malfunction in some levels if this is on
594 // Nehahra NPC AI is confused by blowupfallenzombies
598 Cbuf_InsertText(cmd, "\n"
599 "sv_gameplayfix_blowupfallenzombies 0\n"
600 "sv_gameplayfix_findradiusdistancetobox 0\n"
601 "sv_gameplayfix_grenadebouncedownslopes 0\n"
602 "sv_gameplayfix_slidemoveprojectiles 0\n"
603 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
604 "sv_gameplayfix_setmodelrealbox 0\n"
605 "sv_gameplayfix_droptofloorstartsolid 0\n"
606 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
607 "sv_gameplayfix_noairborncorpse 0\n"
608 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
609 "sv_gameplayfix_easierwaterjump 0\n"
610 "sv_gameplayfix_delayprojectiles 0\n"
611 "sv_gameplayfix_multiplethinksperframe 0\n"
612 "sv_gameplayfix_fixedcheckwatertransition 0\n"
613 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
614 "sv_gameplayfix_swiminbmodels 0\n"
615 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
616 "sys_ticrate 0.01388889\n"
618 "r_shadow_bumpscale_basetexture 0\n"
619 "csqc_polygons_defaultmaterial_nocullface 0\n"
623 Cbuf_InsertText(cmd, "\n"
624 "sv_gameplayfix_blowupfallenzombies 0\n"
625 "sv_gameplayfix_findradiusdistancetobox 0\n"
626 "sv_gameplayfix_grenadebouncedownslopes 0\n"
627 "sv_gameplayfix_slidemoveprojectiles 0\n"
628 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
629 "sv_gameplayfix_setmodelrealbox 0\n"
630 "sv_gameplayfix_droptofloorstartsolid 0\n"
631 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
632 "sv_gameplayfix_noairborncorpse 0\n"
633 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
634 "sv_gameplayfix_easierwaterjump 0\n"
635 "sv_gameplayfix_delayprojectiles 0\n"
636 "sv_gameplayfix_multiplethinksperframe 0\n"
637 "sv_gameplayfix_fixedcheckwatertransition 0\n"
638 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
639 "sv_gameplayfix_swiminbmodels 0\n"
640 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
641 "sys_ticrate 0.01388889\n"
643 "r_shadow_bumpscale_basetexture 0\n"
644 "csqc_polygons_defaultmaterial_nocullface 0\n"
647 // 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.
648 // 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
649 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
652 Cbuf_InsertText(cmd, "\n"
653 "sv_gameplayfix_blowupfallenzombies 0\n"
654 "sv_gameplayfix_findradiusdistancetobox 0\n"
655 "sv_gameplayfix_grenadebouncedownslopes 0\n"
656 "sv_gameplayfix_slidemoveprojectiles 0\n"
657 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
658 "sv_gameplayfix_setmodelrealbox 0\n"
659 "sv_gameplayfix_droptofloorstartsolid 0\n"
660 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
661 "sv_gameplayfix_noairborncorpse 0\n"
662 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
663 "sv_gameplayfix_easierwaterjump 0\n"
664 "sv_gameplayfix_delayprojectiles 0\n"
665 "sv_gameplayfix_multiplethinksperframe 0\n"
666 "sv_gameplayfix_fixedcheckwatertransition 0\n"
667 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
668 "sv_gameplayfix_swiminbmodels 0\n"
669 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
672 "r_shadow_bumpscale_basetexture 0\n"
673 "csqc_polygons_defaultmaterial_nocullface 0\n"
676 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
678 Cbuf_InsertText(cmd, "\n"
679 "sv_gameplayfix_blowupfallenzombies 0\n"
680 "sv_gameplayfix_findradiusdistancetobox 0\n"
681 "sv_gameplayfix_grenadebouncedownslopes 0\n"
682 "sv_gameplayfix_slidemoveprojectiles 0\n"
683 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
684 "sv_gameplayfix_setmodelrealbox 0\n"
685 "sv_gameplayfix_droptofloorstartsolid 0\n"
686 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
687 "sv_gameplayfix_noairborncorpse 0\n"
688 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
689 "sv_gameplayfix_easierwaterjump 0\n"
690 "sv_gameplayfix_delayprojectiles 0\n"
691 "sv_gameplayfix_multiplethinksperframe 0\n"
692 "sv_gameplayfix_fixedcheckwatertransition 0\n"
693 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
694 "sv_gameplayfix_swiminbmodels 0\n"
695 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
696 "sys_ticrate 0.01388889\n"
698 "r_shadow_bumpscale_basetexture 0\n"
699 "csqc_polygons_defaultmaterial_nocullface 0\n"
703 Cbuf_InsertText(cmd, "\n"
704 "sv_gameplayfix_blowupfallenzombies 0\n"
705 "sv_gameplayfix_findradiusdistancetobox 0\n"
706 "sv_gameplayfix_grenadebouncedownslopes 0\n"
707 "sv_gameplayfix_slidemoveprojectiles 0\n"
708 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
709 "sv_gameplayfix_setmodelrealbox 0\n"
710 "sv_gameplayfix_droptofloorstartsolid 0\n"
711 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
712 "sv_gameplayfix_noairborncorpse 0\n"
713 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
714 "sv_gameplayfix_easierwaterjump 0\n"
715 "sv_gameplayfix_delayprojectiles 0\n"
716 "sv_gameplayfix_multiplethinksperframe 0\n"
717 "sv_gameplayfix_fixedcheckwatertransition 0\n"
718 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
719 "sv_gameplayfix_swiminbmodels 0\n"
720 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
721 "sys_ticrate 0.01388889\n"
723 "r_shadow_bumpscale_basetexture 4\n"
724 "csqc_polygons_defaultmaterial_nocullface 0\n"
728 Cbuf_InsertText(cmd, "\n"
729 "sv_gameplayfix_blowupfallenzombies 1\n"
730 "sv_gameplayfix_findradiusdistancetobox 1\n"
731 "sv_gameplayfix_grenadebouncedownslopes 1\n"
732 "sv_gameplayfix_slidemoveprojectiles 1\n"
733 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
734 "sv_gameplayfix_setmodelrealbox 1\n"
735 "sv_gameplayfix_droptofloorstartsolid 1\n"
736 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
737 "sv_gameplayfix_noairborncorpse 1\n"
738 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
739 "sv_gameplayfix_easierwaterjump 1\n"
740 "sv_gameplayfix_delayprojectiles 1\n"
741 "sv_gameplayfix_multiplethinksperframe 1\n"
742 "sv_gameplayfix_fixedcheckwatertransition 1\n"
743 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
744 "sv_gameplayfix_swiminbmodels 1\n"
745 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
746 "sys_ticrate 0.01388889\n"
747 "sv_gameplayfix_q2airaccelerate 1\n"
748 "sv_gameplayfix_stepmultipletimes 1\n"
749 "csqc_polygons_defaultmaterial_nocullface 1\n"
750 "con_chatsound_team_mask 13\n"
754 case GAME_VORETOURNAMENT:
755 // 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
756 Cbuf_InsertText(cmd, "\n"
757 "csqc_polygons_defaultmaterial_nocullface 1\n"
758 "con_chatsound_team_mask 13\n"
759 "sv_gameplayfix_customstats 1\n"
760 "mod_q1bsp_zero_hullsize_cutoff 8.03125\n"
763 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
764 case GAME_STEELSTORM:
765 Cbuf_InsertText(cmd, "\n"
766 "sv_gameplayfix_blowupfallenzombies 1\n"
767 "sv_gameplayfix_findradiusdistancetobox 1\n"
768 "sv_gameplayfix_grenadebouncedownslopes 1\n"
769 "sv_gameplayfix_slidemoveprojectiles 1\n"
770 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
771 "sv_gameplayfix_setmodelrealbox 1\n"
772 "sv_gameplayfix_droptofloorstartsolid 1\n"
773 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
774 "sv_gameplayfix_noairborncorpse 1\n"
775 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
776 "sv_gameplayfix_easierwaterjump 1\n"
777 "sv_gameplayfix_delayprojectiles 1\n"
778 "sv_gameplayfix_multiplethinksperframe 1\n"
779 "sv_gameplayfix_fixedcheckwatertransition 1\n"
780 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
781 "sv_gameplayfix_swiminbmodels 1\n"
782 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
783 "sys_ticrate 0.01388889\n"
784 "cl_csqc_generatemousemoveevents 0\n"
785 "csqc_polygons_defaultmaterial_nocullface 1\n"
789 Cbuf_InsertText(cmd, "\n"
790 "sv_gameplayfix_blowupfallenzombies 1\n"
791 "sv_gameplayfix_findradiusdistancetobox 1\n"
792 "sv_gameplayfix_grenadebouncedownslopes 1\n"
793 "sv_gameplayfix_slidemoveprojectiles 1\n"
794 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
795 "sv_gameplayfix_setmodelrealbox 1\n"
796 "sv_gameplayfix_droptofloorstartsolid 1\n"
797 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
798 "sv_gameplayfix_noairborncorpse 1\n"
799 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
800 "sv_gameplayfix_easierwaterjump 1\n"
801 "sv_gameplayfix_delayprojectiles 1\n"
802 "sv_gameplayfix_multiplethinksperframe 1\n"
803 "sv_gameplayfix_fixedcheckwatertransition 1\n"
804 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
805 "sv_gameplayfix_swiminbmodels 1\n"
806 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
807 "sys_ticrate 0.01388889\n"
808 "csqc_polygons_defaultmaterial_nocullface 0\n"
820 static void Cmd_Exec_f (cmd_state_t *cmd)
825 if (Cmd_Argc(cmd) != 2)
827 Con_Print("exec <filename> : execute a script file\n");
831 s = FS_Search(Cmd_Argv(cmd, 1), true, true, NULL);
832 if(!s || !s->numfilenames)
834 Con_Printf("couldn't exec %s\n",Cmd_Argv(cmd, 1));
838 for(i = 0; i < s->numfilenames; ++i)
839 Cmd_Exec(cmd, s->filenames[i]);
849 Just prints the rest of the line to the console
852 static void Cmd_Echo_f (cmd_state_t *cmd)
856 for (i=1 ; i<Cmd_Argc(cmd) ; i++)
857 Con_Printf("%s ",Cmd_Argv(cmd, i));
862 // Support Doom3-style Toggle Console Command
867 Toggles a specified console variable amongst the values specified (default is 0 and 1)
870 static void Cmd_Toggle_f(cmd_state_t *cmd)
872 // Acquire Number of Arguments
873 int nNumArgs = Cmd_Argc(cmd);
876 // No Arguments Specified; Print Usage
877 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");
879 { // Correct Arguments Specified
880 // Acquire Potential CVar
881 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
888 Cvar_SetValueQuick(cvCVar, 0);
890 Cvar_SetValueQuick(cvCVar, 1);
894 { // 0 and Specified Usage
895 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
896 // CVar is Specified Value; // Reset to 0
897 Cvar_SetValueQuick(cvCVar, 0);
899 if(cvCVar->integer == 0)
900 // CVar is 0; Specify Value
901 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
903 // CVar does not match; Reset to 0
904 Cvar_SetValueQuick(cvCVar, 0);
907 { // Variable Values Specified
911 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
912 { // Cycle through Values
913 if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
914 { // Current Value Located; Increment to Next
915 if( (nCnt + 1) == nNumArgs)
916 // Max Value Reached; Reset
917 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
920 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
929 // Value not Found; Reset to Original
930 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
936 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
945 Creates a new command that executes a command string (possibly ; seperated)
948 static void Cmd_Alias_f (cmd_state_t *cmd)
951 char line[MAX_INPUTLINE];
956 if (Cmd_Argc(cmd) == 1)
958 Con_Print("Current alias commands:\n");
959 for (a = cmd->userdefined->alias ; a ; a=a->next)
960 Con_Printf("%s : %s", a->name, a->value);
964 s = Cmd_Argv(cmd, 1);
965 if (strlen(s) >= MAX_ALIAS_NAME)
967 Con_Print("Alias name is too long\n");
971 // if the alias already exists, reuse it
972 for (a = cmd->userdefined->alias ; a ; a=a->next)
974 if (!strcmp(s, a->name))
983 cmd_alias_t *prev, *current;
985 a = (cmd_alias_t *)Z_Malloc (sizeof(cmd_alias_t));
986 strlcpy (a->name, s, sizeof (a->name));
987 // insert it at the right alphanumeric position
988 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
993 cmd->userdefined->alias = a;
999 // copy the rest of the command line
1000 line[0] = 0; // start out with a null string
1002 for (i=2 ; i < c ; i++)
1005 strlcat (line, " ", sizeof (line));
1006 strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
1008 strlcat (line, "\n", sizeof (line));
1010 alloclen = strlen (line) + 1;
1012 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
1013 a->value = (char *)Z_Malloc (alloclen);
1014 memcpy (a->value, line, alloclen);
1021 Remove existing aliases.
1024 static void Cmd_UnAlias_f (cmd_state_t *cmd)
1030 if(Cmd_Argc(cmd) == 1)
1032 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1036 for(i = 1; i < Cmd_Argc(cmd); ++i)
1038 s = Cmd_Argv(cmd, i);
1040 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
1042 if(!strcmp(s, a->name))
1044 if (a->initstate) // we can not remove init aliases
1046 if(a == cmd->userdefined->alias)
1047 cmd->userdefined->alias = a->next;
1056 Con_Printf("unalias: %s alias not found\n", s);
1061 =============================================================================
1065 =============================================================================
1068 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmd_alias_t *alias, qbool *is_multiple)
1073 static char vabuf[1024]; // cmd_mutex
1076 *is_multiple = false;
1078 if(!varname || !*varname)
1083 if(!strcmp(varname, "*"))
1086 *is_multiple = true;
1087 return Cmd_Args(cmd);
1089 else if(!strcmp(varname, "#"))
1091 return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
1093 else if(varname[strlen(varname) - 1] == '-')
1095 argno = strtol(varname, &endptr, 10);
1096 if(endptr == varname + strlen(varname) - 1)
1098 // whole string is a number, apart from the -
1099 const char *p = Cmd_Args(cmd);
1100 for(; argno > 1; --argno)
1101 if(!COM_ParseToken_Console(&p))
1106 *is_multiple = true;
1108 // kill pre-argument whitespace
1109 for (;*p && ISWHITESPACE(*p);p++)
1118 argno = strtol(varname, &endptr, 10);
1121 // whole string is a number
1122 // NOTE: we already made sure we don't have an empty cvar name!
1123 if(argno >= 0 && argno < Cmd_Argc(cmd))
1124 return Cmd_Argv(cmd, argno);
1129 if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CF_PRIVATE))
1130 return cvar->string;
1135 qbool Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qbool putquotes)
1137 qbool quote_quot = !!strchr(quoteset, '"');
1138 qbool quote_backslash = !!strchr(quoteset, '\\');
1139 qbool quote_dollar = !!strchr(quoteset, '$');
1148 *out++ = '"'; --outlen;
1154 if(*in == '"' && quote_quot)
1158 *out++ = '\\'; --outlen;
1159 *out++ = '"'; --outlen;
1161 else if(*in == '\\' && quote_backslash)
1165 *out++ = '\\'; --outlen;
1166 *out++ = '\\'; --outlen;
1168 else if(*in == '$' && quote_dollar)
1172 *out++ = '$'; --outlen;
1173 *out++ = '$'; --outlen;
1179 *out++ = *in; --outlen;
1194 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmd_alias_t *alias)
1196 static char varname[MAX_INPUTLINE]; // cmd_mutex
1197 static char varval[MAX_INPUTLINE]; // cmd_mutex
1198 const char *varstr = NULL;
1200 qbool required = false;
1201 qbool optional = false;
1202 static char asis[] = "asis"; // just to suppress const char warnings
1204 if(varlen >= MAX_INPUTLINE)
1205 varlen = MAX_INPUTLINE - 1;
1206 memcpy(varname, var, varlen);
1207 varname[varlen] = 0;
1208 varfunc = strchr(varname, ' ');
1220 Con_Printf(CON_WARN "Warning: Could not expand $ in alias %s\n", alias->name);
1222 Con_Printf(CON_WARN "Warning: Could not expand $\n");
1230 while((p = strchr(varfunc, '?')))
1233 memmove(p, p+1, strlen(p)); // with final NUL
1236 while((p = strchr(varfunc, '!')))
1239 memmove(p, p+1, strlen(p)); // with final NUL
1242 while((p = strchr(varfunc, ' ')))
1244 memmove(p, p+1, strlen(p)); // with final NUL
1246 // if no function is left, NULL it
1251 if(varname[0] == '$')
1252 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1255 qbool is_multiple = false;
1256 // Exception: $* and $n- don't use the quoted form by default
1257 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1268 Con_Printf(CON_ERROR "Error: Could not expand $%s in alias %s\n", varname, alias->name);
1270 Con_Printf(CON_ERROR "Error: Could not expand $%s\n", varname);
1280 Con_Printf(CON_WARN "Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1282 Con_Printf(CON_WARN "Warning: Could not expand $%s\n", varname);
1283 dpsnprintf(varval, sizeof(varval), "$%s", varname);
1288 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1290 // quote it so it can be used inside double quotes
1291 // we just need to replace " by \", and of course, double backslashes
1292 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1295 else if(!strcmp(varfunc, "asis"))
1300 Con_Printf("Unknown variable function %s\n", varfunc);
1306 Cmd_PreprocessString
1308 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1310 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias ) {
1316 // don't crash if there's no room in the outtext buffer
1317 if( maxoutlen == 0 ) {
1320 maxoutlen--; // because of \0
1325 while( *in && outlen < maxoutlen ) {
1327 // this is some kind of expansion, see what comes after the $
1330 // The console does the following preprocessing:
1332 // - $$ is transformed to a single dollar sign.
1333 // - $var or ${var} are expanded to the contents of the named cvar,
1334 // with quotation marks and backslashes quoted so it can safely
1335 // be used inside quotation marks (and it should always be used
1337 // - ${var asis} inserts the cvar value as is, without doing this
1339 // - ${var ?} silently expands to the empty string if
1340 // $var does not exist
1341 // - ${var !} fails expansion and executes nothing if
1342 // $var does not exist
1343 // - prefix the cvar name with a dollar sign to do indirection;
1344 // for example, if $x has the value timelimit, ${$x} will return
1345 // the value of $timelimit
1346 // - when expanding an alias, the special variable name $* refers
1347 // to all alias parameters, and a number refers to that numbered
1348 // alias parameter, where the name of the alias is $0, the first
1349 // parameter is $1 and so on; as a special case, $* inserts all
1350 // parameters, without extra quoting, so one can use $* to just
1351 // pass all parameters around. All parameters starting from $n
1352 // can be referred to as $n- (so $* is equivalent to $1-).
1353 // - ${* q} and ${n- q} force quoting anyway
1355 // Note: when expanding an alias, cvar expansion is done in the SAME step
1356 // as alias expansion so that alias parameters or cvar values containing
1357 // dollar signs have no unwanted bad side effects. However, this needs to
1358 // be accounted for when writing complex aliases. For example,
1359 // alias foo "set x NEW; echo $x"
1360 // actually expands to
1361 // "set x NEW; echo OLD"
1362 // and will print OLD! To work around this, use a second alias:
1363 // alias foo "set x NEW; foo2"
1364 // alias foo2 "echo $x"
1366 // Also note: lines starting with alias are exempt from cvar expansion.
1367 // If you want cvar expansion, write "alias" instead:
1370 // alias foo "echo $x"
1371 // "alias" bar "echo $x"
1374 // foo will print 2, because the variable $x will be expanded when the alias
1375 // gets expanded. bar will print 1, because the variable $x was expanded
1376 // at definition time. foo can be equivalently defined as
1378 // "alias" foo "echo $$x"
1380 // because at definition time, $$ will get replaced to a single $.
1385 } else if(*in == '{') {
1386 varlen = strcspn(in + 1, "}");
1387 if(in[varlen + 1] == '}')
1389 val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1401 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1402 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1409 // insert the cvar value
1410 while(*val && outlen < maxoutlen)
1411 outtext[outlen++] = *val++;
1416 // copy the unexpanded text
1417 outtext[outlen++] = '$';
1418 while(eat && outlen < maxoutlen)
1420 outtext[outlen++] = *in++;
1426 outtext[outlen++] = *in++;
1428 outtext[outlen] = 0;
1436 Called for aliases and fills in the alias into the cbuffer
1439 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmd_alias_t *alias)
1441 static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1442 static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1443 qbool ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1446 // insert at start of command buffer, so that aliases execute in order
1447 // (fixes bug introduced by Black on 20050705)
1449 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1450 // have to make sure that no second variable expansion takes place, otherwise
1451 // alias parameters containing dollar signs can have bad effects.
1452 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1453 Cbuf_InsertText(cmd, buffer2);
1460 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1461 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1465 static void Cmd_List_f (cmd_state_t *cmd)
1467 cmd_function_t *func;
1468 const char *partial;
1473 if (Cmd_Argc(cmd) > 1)
1475 partial = Cmd_Argv(cmd, 1);
1476 len = strlen(partial);
1477 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1487 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1489 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1491 Con_Printf("%s : %s\n", func->name, func->description);
1494 for (func = cmd->engine_functions; func; func = func->next)
1496 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1498 Con_Printf("%s : %s\n", func->name, func->description);
1505 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1507 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1510 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1513 static void Cmd_Apropos_f(cmd_state_t *cmd)
1515 cmd_function_t *func;
1518 const char *partial;
1523 if (Cmd_Argc(cmd) > 1)
1524 partial = Cmd_Args(cmd);
1527 Con_Printf("usage: %s <string>\n",Cmd_Argv(cmd, 0));
1531 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1533 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1536 for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1538 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1539 matchpattern_with_separator(cvar->description, partial, true, "", false))
1541 Con_Printf ("cvar ");
1542 Cvar_PrintHelp(cvar, cvar->name, true);
1545 for (char **cvar_alias = cvar->aliases; cvar_alias && *cvar_alias; cvar_alias++)
1547 if (matchpattern_with_separator(*cvar_alias, partial, true, "", false))
1549 Con_Printf ("cvar ");
1550 Cvar_PrintHelp(cvar, *cvar_alias, true);
1555 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1557 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1558 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1560 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1563 for (func = cmd->engine_functions; func; func = func->next)
1565 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1566 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1568 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1571 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1573 // procede here a bit differently as an alias value always got a final \n
1574 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1575 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1577 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1580 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1583 static cmd_state_t *Cmd_AddInterpreter(cmd_buf_t *cbuf, cvar_state_t *cvars, int cvars_flagsmask, int cmds_flagsmask, cmd_userdefined_t *userdefined)
1585 cmd_state_t *cmd = (cmd_state_t *)Mem_Alloc(tempmempool, sizeof(cmd_state_t));
1587 cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1588 // space for commands and script files
1590 cmd->null_string = "";
1593 cmd->cvars_flagsmask = cvars_flagsmask;
1594 cmd->cmd_flags = cmds_flagsmask;
1595 cmd->userdefined = userdefined;
1608 cbuf_mempool = Mem_AllocPool("Command buffer", 0, NULL);
1609 cbuf = (cmd_buf_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_buf_t));
1610 cbuf->maxsize = CMDBUFSIZE;
1611 cbuf->lock = Thread_CreateMutex();
1615 cbuf->start.prev = cbuf->start.next = &(cbuf->start);
1616 cbuf->deferred.prev = cbuf->deferred.next = &(cbuf->deferred);
1617 cbuf->free.prev = cbuf->free.next = &(cbuf->free);
1619 // FIXME: Get rid of cmd_iter_all eventually. This is just a hack to reduce the amount of work to make the interpreters dynamic.
1620 cmd_iter_all = (cmd_iter_t *)Mem_Alloc(tempmempool, sizeof(cmd_iter_t) * 3);
1623 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);
1624 cmd_local->Handle = Cmd_CL_Callback;
1625 cmd_local->NotFound = NULL;
1627 // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1628 cmd_iter_all[1].cmd = cmd_serverfromclient = Cmd_AddInterpreter(cbuf, &cvars_null, 0, CF_SERVER_FROM_CLIENT | CF_USERINFO, &cmd_userdefined_null);
1629 cmd_serverfromclient->Handle = Cmd_SV_Callback;
1630 cmd_serverfromclient->NotFound = Cmd_SV_NotFound;
1632 cmd_iter_all[2].cmd = NULL;
1634 // register our commands
1636 // client-only commands
1637 Cmd_AddCommand(CF_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1638 Cmd_AddCommand(CF_CLIENT, "cprint", Cmd_Centerprint_f, "print something at the screen center");
1640 // maintenance commands used for upkeep of cvars and saved configs
1641 Cmd_AddCommand(CF_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1642 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");
1643 Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1644 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)");
1645 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)");
1647 // general console commands used in multiple environments
1648 Cmd_AddCommand(CF_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1649 Cmd_AddCommand(CF_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1650 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");
1651 Cmd_AddCommand(CF_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1652 Cmd_AddCommand(CF_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1653 Cmd_AddCommand(CF_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1654 Cmd_AddCommand(CF_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1656 #ifdef FILLALLCVARSWITHRUBBISH
1657 Cmd_AddCommand(CF_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1658 #endif /* FILLALLCVARSWITHRUBBISH */
1660 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1661 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1662 Cmd_AddCommand(CF_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1663 Cmd_AddCommand(CF_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1664 Cmd_AddCommand(CF_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1665 Cmd_AddCommand(CF_SHARED, "find", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1667 Cmd_AddCommand(CF_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1670 // Support Doom3-style Toggle Command
1671 Cmd_AddCommand(CF_SHARED | CF_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1679 void Cmd_Shutdown(void)
1681 cmd_iter_t *cmd_iter;
1682 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1684 cmd_state_t *cmd = cmd_iter->cmd;
1686 if (cmd->cbuf->lock)
1688 // we usually have this locked when we get here from Host_Quit_f
1689 Cbuf_Unlock(cmd->cbuf);
1692 Mem_FreePool(&cmd->mempool);
1701 int Cmd_Argc (cmd_state_t *cmd)
1711 const char *Cmd_Argv(cmd_state_t *cmd, int arg)
1713 if (arg >= cmd->argc )
1714 return cmd->null_string;
1715 return cmd->argv[arg];
1723 const char *Cmd_Args (cmd_state_t *cmd)
1732 Parses the given string into command line tokens.
1735 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1736 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1742 cmd->cmdline = NULL;
1746 // skip whitespace up to a /n
1747 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1754 if (*text == '\n' || *text == '\r')
1756 // a newline separates commands in the buffer
1757 if (*text == '\r' && text[1] == '\n')
1767 cmd->cmdline = text;
1771 if (!COM_ParseToken_Console(&text))
1774 if (cmd->argc < MAX_ARGS)
1776 l = (int)strlen(com_token) + 1;
1777 if (cmd->cbuf->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1779 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1782 memcpy (cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos, com_token, l);
1783 cmd->argv[cmd->argc] = cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos;
1784 cmd->cbuf->tokenizebufferpos += l;
1796 void Cmd_AddCommand(int flags, const char *cmd_name, xcommand_t function, const char *description)
1798 cmd_function_t *func;
1799 cmd_function_t *prev, *current;
1803 for (i = 0; i < 2; i++)
1805 cmd = cmd_iter_all[i].cmd;
1806 if (flags & cmd->cmd_flags)
1808 // fail if the command is a variable name
1809 if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1811 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1817 // fail if the command already exists in this interpreter
1818 for (func = cmd->engine_functions; func; func = func->next)
1820 if (!strcmp(cmd_name, func->name))
1822 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1827 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1828 func->flags = flags;
1829 func->name = cmd_name;
1830 func->function = function;
1831 func->description = description;
1832 func->next = cmd->engine_functions;
1834 // insert it at the right alphanumeric position
1835 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1841 cmd->engine_functions = func;
1843 func->next = current;
1847 // mark qcfunc if the function already exists in the qc_functions list
1848 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1850 if (!strcmp(cmd_name, func->name))
1852 func->qcfunc = true; //[515]: csqc
1857 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1858 func->flags = flags;
1859 func->name = cmd_name;
1860 func->function = function;
1861 func->description = description;
1862 func->qcfunc = true; //[515]: csqc
1863 func->next = cmd->userdefined->qc_functions;
1865 // bones_was_here: if this QC command overrides an engine command, store its pointer
1866 // to avoid doing this search at invocation if QC declines to handle this command.
1867 for (cmd_function_t *f = cmd->engine_functions; f; f = f->next)
1869 if (!strcmp(cmd_name, f->name))
1871 Con_DPrintf("Adding QC override of engine command %s\n", cmd_name);
1872 func->overridden = f;
1877 // insert it at the right alphanumeric position
1878 for (prev = NULL, current = cmd->userdefined->qc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1884 cmd->userdefined->qc_functions = func;
1886 func->next = current;
1897 qbool Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1899 cmd_function_t *func;
1901 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1902 if (!strcmp(cmd_name, func->name))
1905 for (func=cmd->engine_functions ; func ; func=func->next)
1906 if (!strcmp (cmd_name,func->name))
1918 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1920 cmd_function_t *func;
1923 len = strlen(partial);
1929 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1930 if (!strncasecmp(partial, func->name, len))
1933 for (func = cmd->engine_functions; func; func = func->next)
1934 if (!strncasecmp(partial, func->name, len))
1941 Cmd_CompleteCountPossible
1943 New function for tab-completion system
1944 Added by EvilTypeGuy
1945 Thanks to Fett erich@heintz.com
1949 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1951 cmd_function_t *func;
1956 len = strlen(partial);
1961 // Loop through the command list and count all partial matches
1962 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1963 if (!strncasecmp(partial, func->name, len))
1966 for (func = cmd->engine_functions; func; func = func->next)
1967 if (!strncasecmp(partial, func->name, len))
1974 Cmd_CompleteBuildList
1976 New function for tab-completion system
1977 Added by EvilTypeGuy
1978 Thanks to Fett erich@heintz.com
1982 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
1984 cmd_function_t *func;
1987 size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
1990 len = strlen(partial);
1991 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1992 // Loop through the functions lists and print all matches
1993 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1994 if (!strncasecmp(partial, func->name, len))
1995 buf[bpos++] = func->name;
1996 for (func = cmd->engine_functions; func; func = func->next)
1997 if (!strncasecmp(partial, func->name, len))
1998 buf[bpos++] = func->name;
2004 // written by LadyHavoc
2005 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
2007 cmd_function_t *func;
2008 size_t len = strlen(partial);
2009 // Loop through the command list and print all matches
2010 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2011 if (!strncasecmp(partial, func->name, len))
2012 Con_Printf("^2%s^7: %s\n", func->name, func->description);
2013 for (func = cmd->engine_functions; func; func = func->next)
2014 if (!strncasecmp(partial, func->name, len))
2015 Con_Printf("^2%s^7: %s\n", func->name, func->description);
2021 New function for tab-completion system
2022 Added by EvilTypeGuy
2023 Thanks to Fett erich@heintz.com
2027 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
2032 len = strlen(partial);
2038 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2039 if (!strncasecmp(partial, alias->name, len))
2045 // written by LadyHavoc
2046 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
2049 size_t len = strlen(partial);
2050 // Loop through the alias list and print all matches
2051 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2052 if (!strncasecmp(partial, alias->name, len))
2053 Con_Printf("^5%s^7: %s", alias->name, alias->value);
2058 Cmd_CompleteAliasCountPossible
2060 New function for tab-completion system
2061 Added by EvilTypeGuy
2062 Thanks to Fett erich@heintz.com
2066 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
2074 len = strlen(partial);
2079 // Loop through the command list and count all partial matches
2080 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2081 if (!strncasecmp(partial, alias->name, len))
2088 Cmd_CompleteAliasBuildList
2090 New function for tab-completion system
2091 Added by EvilTypeGuy
2092 Thanks to Fett erich@heintz.com
2096 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
2101 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
2104 len = strlen(partial);
2105 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2106 // Loop through the alias list and print all matches
2107 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2108 if (!strncasecmp(partial, alias->name, len))
2109 buf[bpos++] = alias->name;
2115 // TODO: Make this more generic?
2116 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2118 cmd_function_t *func;
2119 cmd_function_t **next = &cmd->userdefined->qc_functions;
2129 extern cvar_t sv_cheats;
2132 * Cloudwalk FIXME: This idea sounded great in my head but...
2133 * How do we handle commands that can be received by the client,
2134 * but which the server can also execute locally?
2136 * If we create a callback where the engine will forward to server
2137 * but try to execute the command locally if it's dedicated,
2138 * we're back to intermixing client and server code which I'm
2139 * trying to avoid. There's no other way I can think of to
2140 * implement that behavior that doesn't involve an #ifdef, or
2141 * making a mess of hooks.
2143 qbool Cmd_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2146 func->function(cmd);
2148 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2152 qbool Cmd_CL_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2154 // TODO: Assign these functions to QC commands directly?
2157 if(((func->flags & CF_CLIENT) && CL_VM_ConsoleCommand(text)) ||
2158 ((func->flags & CF_SERVER) && SV_VM_ConsoleCommand(text)))
2161 if (func->overridden) // If this QC command overrides an engine command,
2162 func = func->overridden; // fall back to that command.
2164 if (func->flags & CF_SERVER_FROM_CLIENT)
2166 if(host_isclient.integer)
2168 CL_ForwardToServer_f(cmd);
2171 else if(!(func->flags & CF_SERVER))
2173 Con_Printf("Cannot execute client commands from a dedicated server console.\n");
2177 return Cmd_Callback(cmd, func, text, src);
2180 qbool Cmd_SV_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2182 if(func->qcfunc && (func->flags & CF_SERVER))
2183 return SV_VM_ConsoleCommand(text);
2184 else if (src == src_client)
2186 if((func->flags & CF_CHEAT) && !sv_cheats.integer)
2187 SV_ClientPrintf("No cheats allowed. The server must have sv_cheats set to 1\n");
2189 func->function(cmd);
2195 qbool Cmd_SV_NotFound(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2197 if (cmd->source == src_client)
2199 Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2208 A complete command line has been parsed, so try to execute it
2209 FIXME: lookupnoadd the token to speed search?
2212 void Cmd_ExecuteString (cmd_state_t *cmd, const char *text, cmd_source_t src, qbool lockmutex)
2215 cmd_function_t *func;
2218 Cbuf_Lock(cmd->cbuf);
2219 oldpos = cmd->cbuf->tokenizebufferpos;
2222 Cmd_TokenizeString (cmd, text);
2224 // execute the command line
2226 goto done; // no tokens
2229 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2231 if (!strcasecmp(cmd->argv[0], func->name))
2233 if(cmd->Handle(cmd, func, text, src))
2238 for (func = cmd->engine_functions; func; func=func->next)
2240 if (!strcasecmp (cmd->argv[0], func->name))
2242 if(cmd->Handle(cmd, func, text, src))
2247 // if it's a client command and no command was found, say so.
2250 if(cmd->NotFound(cmd, func, text, src))
2255 for (a=cmd->userdefined->alias ; a ; a=a->next)
2257 if (!strcasecmp (cmd->argv[0], a->name))
2259 Cmd_ExecuteAlias(cmd, a);
2265 if (!Cvar_Command(cmd) && host.framecount > 0)
2266 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2268 cmd->cbuf->tokenizebufferpos = oldpos;
2270 Cbuf_Unlock(cmd->cbuf);
2277 Returns the position (1 to argc-1) in the command's argument list
2278 where the given parameter apears, or 0 if not present
2282 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2288 Con_Printf ("Cmd_CheckParm: NULL");
2292 for (i = 1; i < Cmd_Argc (cmd); i++)
2293 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2301 void Cmd_SaveInitState(void)
2303 cmd_iter_t *cmd_iter;
2304 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2306 cmd_state_t *cmd = cmd_iter->cmd;
2309 for (f = cmd->userdefined->qc_functions; f; f = f->next)
2310 f->initstate = true;
2311 for (f = cmd->engine_functions; f; f = f->next)
2312 f->initstate = true;
2313 for (a = cmd->userdefined->alias; a; a = a->next)
2315 a->initstate = true;
2316 a->initialvalue = Mem_strdup(zonemempool, a->value);
2319 Cvar_SaveInitState(&cvars_all);
2322 void Cmd_RestoreInitState(void)
2324 cmd_iter_t *cmd_iter;
2325 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2327 cmd_state_t *cmd = cmd_iter->cmd;
2328 cmd_function_t *f, **fp;
2329 cmd_alias_t *a, **ap;
2330 for (fp = &cmd->userdefined->qc_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 (fp = &cmd->engine_functions; (f = *fp);)
2348 // destroy this command, it didn't exist at init
2349 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2354 for (ap = &cmd->userdefined->alias; (a = *ap);)
2358 // restore this alias, it existed at init
2359 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2361 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2364 a->value = Mem_strdup(zonemempool, a->initialvalue);
2370 // free this alias, it didn't exist at init...
2371 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2379 Cvar_RestoreInitState(&cvars_all);
2382 void Cmd_NoOperation_f(cmd_state_t *cmd)