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 void Cbuf_ParseText(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool allowpending);
78 static void Cbuf_LinkString(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool leavepending, unsigned int cmdsize);
79 static void Cmd_Defer_f (cmd_state_t *cmd)
82 cmd_buf_t *cbuf = cmd->cbuf;
85 if(Cmd_Argc(cmd) == 1)
87 if(List_Is_Empty(&cbuf->deferred))
88 Con_Printf("No commands are pending.\n");
91 List_For_Each_Entry(current, &cbuf->deferred, cmd_input_t, list)
92 Con_Printf("-> In %9.2f: %s\n", current->delay, current->text);
95 else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
97 while(!List_Is_Empty(&cbuf->deferred))
99 cbuf->size -= List_Entry(cbuf->deferred.next, cmd_input_t, list)->length;
100 List_Move_Tail(cbuf->deferred.next, &cbuf->free);
103 else if(Cmd_Argc(cmd) == 3 && (cmdsize = strlen(Cmd_Argv(cmd, 2))) )
107 Cbuf_LinkString(cmd, &cbuf->deferred, NULL, Cmd_Argv(cmd, 2), false, cmdsize);
108 List_Entry(cbuf->deferred.prev, cmd_input_t, list)->delay = atof(Cmd_Argv(cmd, 1));
114 Con_Printf("usage: defer <seconds> <command>\n"
121 =============================================================================
125 * The Quake command-line is super basic. It can be entered in the console
126 * or in config files. A semicolon is used to terminate a command and chain
127 * them together. Otherwise, a newline delineates command input.
129 * In most engines, the Quake command-line is a simple linear text buffer that
130 * is parsed when it executes. In Darkplaces, we use a linked list of command
131 * input and parse the input on the spot.
133 * This was done because Darkplaces allows multiple command interpreters on the
134 * same thread. Previously, each interpreter maintained its own buffer and this
135 * caused problems related to execution order, and maintaining a single simple
136 * buffer for all interpreters makes it non-trivial to keep track of which
137 * command should execute on which interpreter.
139 =============================================================================
146 Returns an existing buffer node for appending or reuse, or allocates a new one
149 static cmd_input_t *Cbuf_NodeGet(cmd_buf_t *cbuf, cmd_input_t *existing)
152 if(existing && existing->pending)
154 else if(!List_Is_Empty(&cbuf->free))
156 node = List_Entry(cbuf->free.next, cmd_input_t, list);
157 node->length = node->pending = 0;
161 node = (cmd_input_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_input_t));
162 node->list.prev = node->list.next = &node->list;
163 node->size = node->length = node->pending = 0;
172 Copies a command string into a buffer node.
173 The input should not be null-terminated, the output will be.
176 static void Cbuf_LinkString(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool leavepending, unsigned int cmdsize)
178 cmd_buf_t *cbuf = cmd->cbuf;
179 cmd_input_t *node = Cbuf_NodeGet(cbuf, existing);
180 unsigned int offset = node->length; // > 0 if(pending)
182 // node will match existing if its text was pending continuation
186 List_Move_Tail(&node->list, head);
189 node->length += cmdsize;
190 if(node->size < node->length)
192 node->text = (char *)Mem_Realloc(cbuf_mempool, node->text, node->length + 1);
193 node->size = node->length;
195 cbuf->size += cmdsize;
197 dp_ustr2stp(&node->text[offset], node->length + 1, text, cmdsize);
198 //Con_Printf("^5Cbuf_LinkString(): %s `^7%s^5`\n", node->pending ? "append" : "new", &node->text[offset]);
199 node->pending = leavepending;
206 Parses text to isolate command strings for linking into the buffer
207 separators: \n \r or unquoted and uncommented ';'
210 static void Cbuf_ParseText(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool allowpending)
212 unsigned int cmdsize = 0, start = 0, pos;
213 qbool quotes = false, comment = false;
215 for (pos = 0; text[pos]; ++pos)
220 if (comment || quotes)
225 quotes = false; // matches div0-stable
228 Cbuf_LinkString(cmd, head, existing, &text[start], false, cmdsize);
231 else if (existing && existing->pending) // all I got was this lousy \n
232 existing->pending = false;
233 continue; // don't increment cmdsize
236 if (!quotes && text[pos + 1] == '/' && (pos == 0 || ISWHITESPACE(text[pos - 1])))
240 if (!comment && (pos == 0 || text[pos - 1] != '\\'))
253 if (cmdsize) // the line didn't end yet but we do have a string
254 Cbuf_LinkString(cmd, head, existing, &text[start], allowpending, cmdsize);
261 Adds command text at the end of the buffer
264 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
266 size_t l = strlen(text);
267 cmd_buf_t *cbuf = cmd->cbuf;
268 llist_t llist = {&llist, &llist};
270 if (cbuf->size + l > cbuf->maxsize)
272 Con_Printf(CON_WARN "Cbuf_AddText: input too large, %luKB ought to be enough for anybody.\n", (unsigned long)(cbuf->maxsize / 1024));
278 // If the string terminates but the (last) line doesn't, the node will be left in the pending state (to be continued).
279 Cbuf_ParseText(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(cbuf->start.prev, cmd_input_t, list)), text, true);
280 List_Splice_Tail(&llist, &cbuf->start);
289 Adds command text immediately after the current command
292 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
294 cmd_buf_t *cbuf = cmd->cbuf;
295 llist_t llist = {&llist, &llist};
296 size_t l = strlen(text);
298 if (cbuf->size + l > cbuf->maxsize)
300 Con_Printf(CON_WARN "Cbuf_InsertText: input too large, %luKB ought to be enough for anybody.\n", (unsigned long)(cbuf->maxsize / 1024));
306 // bones_was_here assertion: when prepending to the buffer it never makes sense to leave node(s) in the `pending` state,
307 // it would have been impossible to append to such text later in the old raw text buffer,
308 // and allowing it causes bugs when .cfg files lack \n at EOF (see: https://gitlab.com/xonotic/darkplaces/-/issues/378).
309 Cbuf_ParseText(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(cbuf->start.next, cmd_input_t, list)), text, false);
310 List_Splice(&llist, &cbuf->start);
317 Cbuf_Execute_Deferred --blub
320 static void Cbuf_Execute_Deferred (cmd_buf_t *cbuf)
322 cmd_input_t *current, *n;
325 if (host.realtime - cbuf->deferred_oldtime < 0 || host.realtime - cbuf->deferred_oldtime > 1800)
326 cbuf->deferred_oldtime = host.realtime;
327 eat = host.realtime - cbuf->deferred_oldtime;
330 cbuf->deferred_oldtime = host.realtime;
332 List_For_Each_Entry_Safe(current, n, &cbuf->deferred, cmd_input_t, list)
334 current->delay -= eat;
335 if(current->delay <= 0)
337 Cbuf_AddText(current->source, current->text); // parse deferred string and append its cmdstring(s)
338 List_Entry(cbuf->start.prev, cmd_input_t, list)->pending = false; // faster than div0-stable's Cbuf_AddText(";\n");
339 List_Move_Tail(¤t->list, &cbuf->free); // make deferred string memory available for reuse
340 cbuf->size -= current->length;
350 extern qbool prvm_runawaycheck;
351 void Cbuf_Execute (cmd_buf_t *cbuf)
353 cmd_input_t *current;
356 // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
357 cbuf->tokenizebufferpos = 0;
359 while (!List_Is_Empty(&cbuf->start))
362 * Delete the text from the command buffer and move remaining
363 * commands down. This is necessary because commands (exec, alias)
364 * can insert data at the beginning of the text buffer
366 current = List_Entry(cbuf->start.next, cmd_input_t, list);
369 * Assume we're rolling with the current command-line and
370 * always set this false because alias expansion or cbuf insertion
371 * without a newline may set this true, and cause weirdness.
373 current->pending = false;
375 Cmd_PreprocessAndExecuteString(current->source, current->text, current->length, src_local, false);
376 cbuf->size -= current->length;
377 // Recycle memory so using WASD doesn't cause a malloc and free
378 List_Move_Tail(¤t->list, &cbuf->free);
383 * Skip out while text still remains in
384 * buffer, leaving it for next frame
390 if (++i == 1000000 && prvm_runawaycheck)
392 Con_Printf(CON_WARN "Cbuf_Execute: runaway loop counter hit limit of %d commands, clearing command buffers!\n", i);
402 Add them exactly as if they had been typed at the console
405 static void Cbuf_Frame_Input(void)
409 if ((line = Sys_ConsoleInput()))
411 // bones_was_here: prepending allows a loop such as `alias foo "bar; wait; foo"; foo`
412 // to be broken with an alias or unalias command
413 Cbuf_InsertText(cmd_local, line);
417 void Cbuf_Frame(cmd_buf_t *cbuf)
419 // check for commands typed to the host
422 // R_TimeReport("preconsole");
424 // execute commands queued with the defer command
425 Cbuf_Execute_Deferred(cbuf);
428 SV_LockThreadMutex();
430 SV_UnlockThreadMutex();
433 // R_TimeReport("console");
436 void Cbuf_Clear(cmd_buf_t *cbuf)
438 while (!List_Is_Empty(&cbuf->start))
439 List_Move_Tail(cbuf->start.next, &cbuf->free);
440 while (!List_Is_Empty(&cbuf->deferred))
441 List_Move_Tail(cbuf->deferred.next, &cbuf->free);
446 ==============================================================================
450 ==============================================================================
457 Adds command line parameters as script statements
458 Commands lead with a +, and continue until a - or another +
459 quake +prog jctest.qp +cmd amlev1
460 quake -nosound +cmd amlev1
463 static void Cmd_StuffCmds_f (cmd_state_t *cmd)
466 // this is for all commandline options combined (and is bounds checked)
467 char build[MAX_INPUTLINE];
469 if (Cmd_Argc (cmd) != 1)
471 Con_Print("stuffcmds : execute command line parameters\n");
475 // no reason to run the commandline arguments twice
476 if (host_stuffcmdsrun)
479 host_stuffcmdsrun = true;
482 for (i = 0;i < sys.argc;i++)
484 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)
487 while (sys.argv[i][j])
488 build[l++] = sys.argv[i][j++];
490 for (;i < sys.argc;i++)
494 if ((sys.argv[i][0] == '+' || sys.argv[i][0] == '-') && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9'))
496 if (l + strlen(sys.argv[i]) + 4 > sizeof(build) - 1)
499 if (strchr(sys.argv[i], ' '))
501 for (j = 0;sys.argv[i][j];j++)
502 build[l++] = sys.argv[i][j];
503 if (strchr(sys.argv[i], ' '))
510 // now terminate the combined string and prepend it to the command buffer
511 // we already reserved space for the terminator
513 Cbuf_InsertText (cmd, build);
516 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
519 size_t filenameLen = strlen(filename);
521 !strcmp(filename, "default.cfg") ||
522 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
524 if (!strcmp(filename, "config.cfg"))
526 filename = CONFIGFILENAME;
527 if (Sys_CheckParm("-noconfig"))
528 return; // don't execute config.cfg
531 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
534 Con_Printf(CON_WARN "couldn't exec %s\n",filename);
537 Con_Printf("execing %s\n",filename);
539 // if executing default.cfg for the first time, lock the cvar defaults
540 // it may seem backwards to insert this text BEFORE the default.cfg
541 // but Cbuf_InsertText inserts before, so this actually ends up after it.
543 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
545 Cbuf_InsertText (cmd, f);
550 // special defaults for specific games go here, these execute before default.cfg
551 // Nehahra pushable crates malfunction in some levels if this is on
552 // Nehahra NPC AI is confused by blowupfallenzombies
556 Cbuf_InsertText(cmd, "\n"
557 "sv_gameplayfix_blowupfallenzombies 0\n"
558 "sv_gameplayfix_findradiusdistancetobox 0\n"
559 "sv_gameplayfix_grenadebouncedownslopes 0\n"
560 "sv_gameplayfix_slidemoveprojectiles 0\n"
561 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
562 "sv_gameplayfix_setmodelrealbox 0\n"
563 "sv_gameplayfix_droptofloorstartsolid 0\n"
564 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
565 "sv_gameplayfix_noairborncorpse 0\n"
566 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
567 "sv_gameplayfix_easierwaterjump 0\n"
568 "sv_gameplayfix_delayprojectiles 0\n"
569 "sv_gameplayfix_multiplethinksperframe 0\n"
570 "sv_gameplayfix_fixedcheckwatertransition 0\n"
571 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
572 "sv_gameplayfix_swiminbmodels 0\n"
573 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
574 "sys_ticrate 0.01388889\n"
576 "r_shadow_bumpscale_basetexture 0\n"
577 "csqc_polygons_defaultmaterial_nocullface 0\n"
581 Cbuf_InsertText(cmd, "\n"
582 "sv_gameplayfix_blowupfallenzombies 0\n"
583 "sv_gameplayfix_findradiusdistancetobox 0\n"
584 "sv_gameplayfix_grenadebouncedownslopes 0\n"
585 "sv_gameplayfix_slidemoveprojectiles 0\n"
586 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
587 "sv_gameplayfix_setmodelrealbox 0\n"
588 "sv_gameplayfix_droptofloorstartsolid 0\n"
589 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
590 "sv_gameplayfix_noairborncorpse 0\n"
591 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
592 "sv_gameplayfix_easierwaterjump 0\n"
593 "sv_gameplayfix_delayprojectiles 0\n"
594 "sv_gameplayfix_multiplethinksperframe 0\n"
595 "sv_gameplayfix_fixedcheckwatertransition 0\n"
596 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
597 "sv_gameplayfix_swiminbmodels 0\n"
598 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
599 "sys_ticrate 0.01388889\n"
601 "r_shadow_bumpscale_basetexture 0\n"
602 "csqc_polygons_defaultmaterial_nocullface 0\n"
605 // 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.
606 // 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
607 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
610 Cbuf_InsertText(cmd, "\n"
611 "sv_gameplayfix_blowupfallenzombies 0\n"
612 "sv_gameplayfix_findradiusdistancetobox 0\n"
613 "sv_gameplayfix_grenadebouncedownslopes 0\n"
614 "sv_gameplayfix_slidemoveprojectiles 0\n"
615 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
616 "sv_gameplayfix_setmodelrealbox 0\n"
617 "sv_gameplayfix_droptofloorstartsolid 0\n"
618 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
619 "sv_gameplayfix_noairborncorpse 0\n"
620 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
621 "sv_gameplayfix_easierwaterjump 0\n"
622 "sv_gameplayfix_delayprojectiles 0\n"
623 "sv_gameplayfix_multiplethinksperframe 0\n"
624 "sv_gameplayfix_fixedcheckwatertransition 0\n"
625 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
626 "sv_gameplayfix_swiminbmodels 0\n"
627 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
630 "r_shadow_bumpscale_basetexture 0\n"
631 "csqc_polygons_defaultmaterial_nocullface 0\n"
634 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
636 Cbuf_InsertText(cmd, "\n"
637 "sv_gameplayfix_blowupfallenzombies 0\n"
638 "sv_gameplayfix_findradiusdistancetobox 0\n"
639 "sv_gameplayfix_grenadebouncedownslopes 0\n"
640 "sv_gameplayfix_slidemoveprojectiles 0\n"
641 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
642 "sv_gameplayfix_setmodelrealbox 0\n"
643 "sv_gameplayfix_droptofloorstartsolid 0\n"
644 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
645 "sv_gameplayfix_noairborncorpse 0\n"
646 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
647 "sv_gameplayfix_easierwaterjump 0\n"
648 "sv_gameplayfix_delayprojectiles 0\n"
649 "sv_gameplayfix_multiplethinksperframe 0\n"
650 "sv_gameplayfix_fixedcheckwatertransition 0\n"
651 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
652 "sv_gameplayfix_swiminbmodels 0\n"
653 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
654 "sys_ticrate 0.01388889\n"
656 "r_shadow_bumpscale_basetexture 0\n"
657 "csqc_polygons_defaultmaterial_nocullface 0\n"
661 Cbuf_InsertText(cmd, "\n"
662 "sv_gameplayfix_blowupfallenzombies 0\n"
663 "sv_gameplayfix_findradiusdistancetobox 0\n"
664 "sv_gameplayfix_grenadebouncedownslopes 0\n"
665 "sv_gameplayfix_slidemoveprojectiles 0\n"
666 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
667 "sv_gameplayfix_setmodelrealbox 0\n"
668 "sv_gameplayfix_droptofloorstartsolid 0\n"
669 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
670 "sv_gameplayfix_noairborncorpse 0\n"
671 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
672 "sv_gameplayfix_easierwaterjump 0\n"
673 "sv_gameplayfix_delayprojectiles 0\n"
674 "sv_gameplayfix_multiplethinksperframe 0\n"
675 "sv_gameplayfix_fixedcheckwatertransition 0\n"
676 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
677 "sv_gameplayfix_swiminbmodels 0\n"
678 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
679 "sys_ticrate 0.01388889\n"
681 "r_shadow_bumpscale_basetexture 4\n"
682 "csqc_polygons_defaultmaterial_nocullface 0\n"
686 Cbuf_InsertText(cmd, "\n"
687 "sv_gameplayfix_blowupfallenzombies 1\n"
688 "sv_gameplayfix_findradiusdistancetobox 1\n"
689 "sv_gameplayfix_grenadebouncedownslopes 1\n"
690 "sv_gameplayfix_slidemoveprojectiles 1\n"
691 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
692 "sv_gameplayfix_setmodelrealbox 1\n"
693 "sv_gameplayfix_droptofloorstartsolid 1\n"
694 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
695 "sv_gameplayfix_noairborncorpse 1\n"
696 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
697 "sv_gameplayfix_easierwaterjump 1\n"
698 "sv_gameplayfix_delayprojectiles 1\n"
699 "sv_gameplayfix_multiplethinksperframe 1\n"
700 "sv_gameplayfix_fixedcheckwatertransition 1\n"
701 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
702 "sv_gameplayfix_swiminbmodels 1\n"
703 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
704 "sys_ticrate 0.01388889\n"
705 "sv_gameplayfix_q2airaccelerate 1\n"
706 "sv_gameplayfix_stepmultipletimes 1\n"
707 "csqc_polygons_defaultmaterial_nocullface 1\n"
708 "con_chatsound_team_mask 13\n"
712 case GAME_VORETOURNAMENT:
713 // 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
714 Cbuf_InsertText(cmd, "\n"
715 "csqc_polygons_defaultmaterial_nocullface 1\n"
716 "con_chatsound_team_mask 13\n"
718 "mod_q1bsp_zero_hullsize_cutoff 8.03125\n"
721 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
722 case GAME_STEELSTORM:
723 Cbuf_InsertText(cmd, "\n"
724 "sv_gameplayfix_blowupfallenzombies 1\n"
725 "sv_gameplayfix_findradiusdistancetobox 1\n"
726 "sv_gameplayfix_grenadebouncedownslopes 1\n"
727 "sv_gameplayfix_slidemoveprojectiles 1\n"
728 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
729 "sv_gameplayfix_setmodelrealbox 1\n"
730 "sv_gameplayfix_droptofloorstartsolid 1\n"
731 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
732 "sv_gameplayfix_noairborncorpse 1\n"
733 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
734 "sv_gameplayfix_easierwaterjump 1\n"
735 "sv_gameplayfix_delayprojectiles 1\n"
736 "sv_gameplayfix_multiplethinksperframe 1\n"
737 "sv_gameplayfix_fixedcheckwatertransition 1\n"
738 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
739 "sv_gameplayfix_swiminbmodels 1\n"
740 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
741 "sys_ticrate 0.01388889\n"
742 "cl_csqc_generatemousemoveevents 0\n"
743 "csqc_polygons_defaultmaterial_nocullface 1\n"
747 Cbuf_InsertText(cmd, "\n"
748 "sv_gameplayfix_blowupfallenzombies 1\n"
749 "sv_gameplayfix_findradiusdistancetobox 1\n"
750 "sv_gameplayfix_grenadebouncedownslopes 1\n"
751 "sv_gameplayfix_slidemoveprojectiles 1\n"
752 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
753 "sv_gameplayfix_setmodelrealbox 1\n"
754 "sv_gameplayfix_droptofloorstartsolid 1\n"
755 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
756 "sv_gameplayfix_noairborncorpse 1\n"
757 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
758 "sv_gameplayfix_easierwaterjump 1\n"
759 "sv_gameplayfix_delayprojectiles 1\n"
760 "sv_gameplayfix_multiplethinksperframe 1\n"
761 "sv_gameplayfix_fixedcheckwatertransition 1\n"
762 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
763 "sv_gameplayfix_swiminbmodels 1\n"
764 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
765 "sys_ticrate 0.01388889\n"
766 "csqc_polygons_defaultmaterial_nocullface 0\n"
778 static void Cmd_Exec_f (cmd_state_t *cmd)
783 if (Cmd_Argc(cmd) != 2)
785 Con_Print("exec <filename> : execute a script file\n");
789 s = FS_Search(Cmd_Argv(cmd, 1), true, true, NULL);
790 if(!s || !s->numfilenames)
792 Con_Printf(CON_WARN "couldn't exec %s\n",Cmd_Argv(cmd, 1));
796 for(i = 0; i < s->numfilenames; ++i)
797 Cmd_Exec(cmd, s->filenames[i]);
807 Just prints the rest of the line to the console
810 static void Cmd_Echo_f (cmd_state_t *cmd)
814 for (i=1 ; i<Cmd_Argc(cmd) ; i++)
815 Con_Printf("%s ",Cmd_Argv(cmd, i));
820 // Support Doom3-style Toggle Console Command
825 Toggles a specified console variable amongst the values specified (default is 0 and 1)
828 static void Cmd_Toggle_f(cmd_state_t *cmd)
830 // Acquire Number of Arguments
831 int nNumArgs = Cmd_Argc(cmd);
834 // No Arguments Specified; Print Usage
835 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");
837 { // Correct Arguments Specified
838 // Acquire Potential CVar
839 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
846 Cvar_SetValueQuick(cvCVar, 0);
848 Cvar_SetValueQuick(cvCVar, 1);
852 { // 0 and Specified Usage
853 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
854 // CVar is Specified Value; // Reset to 0
855 Cvar_SetValueQuick(cvCVar, 0);
857 if(cvCVar->integer == 0)
858 // CVar is 0; Specify Value
859 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
861 // CVar does not match; Reset to 0
862 Cvar_SetValueQuick(cvCVar, 0);
865 { // Variable Values Specified
869 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
870 { // Cycle through Values
871 if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
872 { // Current Value Located; Increment to Next
873 if( (nCnt + 1) == nNumArgs)
874 // Max Value Reached; Reset
875 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
878 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
887 // Value not Found; Reset to Original
888 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
894 Con_Printf(CON_WARN "ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
903 Creates a new command that executes a command string (possibly ; seperated)
906 static void Cmd_Alias_f (cmd_state_t *cmd)
909 char line[MAX_INPUTLINE];
914 if (Cmd_Argc(cmd) == 1)
916 Con_Print("Current alias commands:\n");
917 for (a = cmd->userdefined->alias ; a ; a=a->next)
918 Con_Printf("%s : %s", a->name, a->value);
922 s = Cmd_Argv(cmd, 1);
923 if (strlen(s) >= MAX_ALIAS_NAME)
925 Con_Print(CON_WARN "Alias name is too long\n");
929 // if the alias already exists, reuse it
930 for (a = cmd->userdefined->alias ; a ; a=a->next)
932 if (!strcmp(s, a->name))
941 cmd_alias_t *prev, *current;
943 a = (cmd_alias_t *)Z_Malloc (sizeof(cmd_alias_t));
944 dp_strlcpy (a->name, s, sizeof (a->name));
945 // insert it at the right alphanumeric position
946 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
951 cmd->userdefined->alias = a;
957 // copy the rest of the command line
958 line[0] = 0; // start out with a null string
960 for (i=2 ; i < c ; i++)
963 dp_strlcat (line, " ", sizeof (line));
964 dp_strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
966 dp_strlcat (line, "\n", sizeof (line));
968 alloclen = strlen (line) + 1;
970 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
971 a->value = (char *)Z_Malloc (alloclen);
972 memcpy (a->value, line, alloclen);
979 Remove existing aliases.
982 static void Cmd_UnAlias_f (cmd_state_t *cmd)
988 if(Cmd_Argc(cmd) == 1)
990 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
994 for(i = 1; i < Cmd_Argc(cmd); ++i)
996 s = Cmd_Argv(cmd, i);
998 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
1000 if(!strcmp(s, a->name))
1002 if (a->initstate) // we can not remove init aliases
1004 if(a == cmd->userdefined->alias)
1005 cmd->userdefined->alias = a->next;
1014 Con_Printf("unalias: %s alias not found\n", s);
1019 =============================================================================
1023 =============================================================================
1026 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmd_alias_t *alias, qbool *is_multiple)
1031 static char vabuf[1024]; // cmd_mutex
1034 *is_multiple = false;
1036 if(!varname || !*varname)
1041 if(!strcmp(varname, "*"))
1044 *is_multiple = true;
1045 return Cmd_Args(cmd);
1047 else if(!strcmp(varname, "#"))
1049 return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
1051 else if(varname[strlen(varname) - 1] == '-')
1053 argno = strtol(varname, &endptr, 10);
1054 if(endptr == varname + strlen(varname) - 1)
1056 // whole string is a number, apart from the -
1057 const char *p = Cmd_Args(cmd);
1058 for(; argno > 1; --argno)
1059 if(!COM_ParseToken_Console(&p))
1064 *is_multiple = true;
1066 // kill pre-argument whitespace
1067 for (;*p && ISWHITESPACE(*p);p++)
1076 argno = strtol(varname, &endptr, 10);
1079 // whole string is a number
1080 // NOTE: we already made sure we don't have an empty cvar name!
1081 if(argno >= 0 && argno < Cmd_Argc(cmd))
1082 return Cmd_Argv(cmd, argno);
1087 if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CF_PRIVATE))
1088 return cvar->string;
1093 qbool Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qbool putquotes)
1095 qbool quote_quot = !!strchr(quoteset, '"');
1096 qbool quote_backslash = !!strchr(quoteset, '\\');
1097 qbool quote_dollar = !!strchr(quoteset, '$');
1106 *out++ = '"'; --outlen;
1112 if(*in == '"' && quote_quot)
1116 *out++ = '\\'; --outlen;
1117 *out++ = '"'; --outlen;
1119 else if(*in == '\\' && quote_backslash)
1123 *out++ = '\\'; --outlen;
1124 *out++ = '\\'; --outlen;
1126 else if(*in == '$' && quote_dollar)
1130 *out++ = '$'; --outlen;
1131 *out++ = '$'; --outlen;
1137 *out++ = *in; --outlen;
1152 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmd_alias_t *alias)
1154 static char varname[MAX_INPUTLINE]; // cmd_mutex
1155 static char varval[MAX_INPUTLINE]; // cmd_mutex
1156 const char *varstr = NULL;
1158 qbool required = false;
1159 qbool optional = false;
1160 static char asis[] = "asis"; // just to suppress const char warnings
1162 if(varlen >= MAX_INPUTLINE)
1163 varlen = MAX_INPUTLINE - 1;
1164 memcpy(varname, var, varlen);
1165 varname[varlen] = 0;
1166 varfunc = strchr(varname, ' ');
1178 Con_Printf(CON_WARN "Warning: Could not expand $ in alias %s\n", alias->name);
1180 Con_Printf(CON_WARN "Warning: Could not expand $\n");
1188 while((p = strchr(varfunc, '?')))
1191 memmove(p, p+1, strlen(p)); // with final NUL
1194 while((p = strchr(varfunc, '!')))
1197 memmove(p, p+1, strlen(p)); // with final NUL
1200 while((p = strchr(varfunc, ' ')))
1202 memmove(p, p+1, strlen(p)); // with final NUL
1204 // if no function is left, NULL it
1209 if(varname[0] == '$')
1210 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1213 qbool is_multiple = false;
1214 // Exception: $* and $n- don't use the quoted form by default
1215 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1226 Con_Printf(CON_ERROR "Error: Could not expand $%s in alias %s\n", varname, alias->name);
1228 Con_Printf(CON_ERROR "Error: Could not expand $%s\n", varname);
1238 Con_Printf(CON_WARN "Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1240 Con_Printf(CON_WARN "Warning: Could not expand $%s\n", varname);
1241 dpsnprintf(varval, sizeof(varval), "$%s", varname);
1246 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1248 // quote it so it can be used inside double quotes
1249 // we just need to replace " by \", and of course, double backslashes
1250 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1253 else if(!strcmp(varfunc, "asis"))
1258 Con_Printf("Unknown variable function %s\n", varfunc);
1264 Cmd_PreprocessString
1266 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1267 Returns the number of bytes written to *outtext excluding the \0 terminator.
1269 static size_t Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias)
1276 // don't crash if there's no room in the outtext buffer
1277 if( maxoutlen == 0 ) {
1280 maxoutlen--; // because of \0
1285 while( *in && outlen < maxoutlen ) {
1287 // this is some kind of expansion, see what comes after the $
1290 // The console does the following preprocessing:
1292 // - $$ is transformed to a single dollar sign.
1293 // - $var or ${var} are expanded to the contents of the named cvar,
1294 // with quotation marks and backslashes quoted so it can safely
1295 // be used inside quotation marks (and it should always be used
1297 // - ${var asis} inserts the cvar value as is, without doing this
1299 // - ${var ?} silently expands to the empty string if
1300 // $var does not exist
1301 // - ${var !} fails expansion and executes nothing if
1302 // $var does not exist
1303 // - prefix the cvar name with a dollar sign to do indirection;
1304 // for example, if $x has the value timelimit, ${$x} will return
1305 // the value of $timelimit
1306 // - when expanding an alias, the special variable name $* refers
1307 // to all alias parameters, and a number refers to that numbered
1308 // alias parameter, where the name of the alias is $0, the first
1309 // parameter is $1 and so on; as a special case, $* inserts all
1310 // parameters, without extra quoting, so one can use $* to just
1311 // pass all parameters around. All parameters starting from $n
1312 // can be referred to as $n- (so $* is equivalent to $1-).
1313 // - ${* q} and ${n- q} force quoting anyway
1315 // Note: when expanding an alias, cvar expansion is done in the SAME step
1316 // as alias expansion so that alias parameters or cvar values containing
1317 // dollar signs have no unwanted bad side effects. However, this needs to
1318 // be accounted for when writing complex aliases. For example,
1319 // alias foo "set x NEW; echo $x"
1320 // actually expands to
1321 // "set x NEW; echo OLD"
1322 // and will print OLD! To work around this, use a second alias:
1323 // alias foo "set x NEW; foo2"
1324 // alias foo2 "echo $x"
1326 // Also note: lines starting with alias are exempt from cvar expansion.
1327 // If you want cvar expansion, write "alias" instead:
1330 // alias foo "echo $x"
1331 // "alias" bar "echo $x"
1334 // foo will print 2, because the variable $x will be expanded when the alias
1335 // gets expanded. bar will print 1, because the variable $x was expanded
1336 // at definition time. foo can be equivalently defined as
1338 // "alias" foo "echo $$x"
1340 // because at definition time, $$ will get replaced to a single $.
1345 } else if(*in == '{') {
1346 varlen = strcspn(in + 1, "}");
1347 if(in[varlen + 1] == '}')
1349 val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1361 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1362 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1369 // insert the cvar value
1370 while(*val && outlen < maxoutlen)
1371 outtext[outlen++] = *val++;
1376 // copy the unexpanded text
1377 outtext[outlen++] = '$';
1378 while(eat && outlen < maxoutlen)
1380 outtext[outlen++] = *in++;
1386 outtext[outlen++] = *in++;
1388 outtext[outlen] = '\0';
1396 Called for aliases and fills in the alias into the cbuffer
1399 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmd_alias_t *alias)
1401 static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1402 static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1403 qbool ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1406 // insert at start of command buffer, so that aliases execute in order
1407 // (fixes bug introduced by Black on 20050705)
1409 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1410 // have to make sure that no second variable expansion takes place, otherwise
1411 // alias parameters containing dollar signs can have bad effects.
1412 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1413 Cbuf_InsertText(cmd, buffer2);
1416 void Cmd_PreprocessAndExecuteString(cmd_state_t *cmd, const char *text, size_t textlen, cmd_source_t src, qbool lockmutex)
1418 char preprocessed[MAX_INPUTLINE];
1419 size_t preprocessed_len;
1420 const char *firstchar;
1423 while(*firstchar && ISWHITESPACE(*firstchar))
1425 if((strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5]))
1426 && (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4]))
1427 && (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7])))
1429 if((preprocessed_len = Cmd_PreprocessString(cmd, text, preprocessed, sizeof(preprocessed), NULL)))
1430 Cmd_ExecuteString(cmd, preprocessed, preprocessed_len, src, lockmutex);
1433 Cmd_ExecuteString(cmd, text, textlen, src, lockmutex);
1440 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1441 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1445 static void Cmd_List_f (cmd_state_t *cmd)
1447 cmd_function_t *func;
1448 const char *partial;
1453 if (Cmd_Argc(cmd) > 1)
1455 partial = Cmd_Argv(cmd, 1);
1456 len = strlen(partial);
1457 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1467 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1469 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1471 Con_Printf("%s : %s\n", func->name, func->description);
1474 for (func = cmd->engine_functions; func; func = func->next)
1476 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1478 Con_Printf("%s : %s\n", func->name, func->description);
1485 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1487 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1490 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1493 static void Cmd_Apropos_f(cmd_state_t *cmd)
1495 cmd_function_t *func;
1498 const char *partial;
1503 if (Cmd_Argc(cmd) > 1)
1504 partial = Cmd_Args(cmd);
1507 Con_Printf("usage: %s <string>\n",Cmd_Argv(cmd, 0));
1511 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1513 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1516 for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1518 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1519 matchpattern_with_separator(cvar->description, partial, true, "", false))
1521 Con_Printf ("cvar ");
1522 Cvar_PrintHelp(cvar, cvar->name, true);
1525 for (char **cvar_alias = cvar->aliases; cvar_alias && *cvar_alias; cvar_alias++)
1527 if (matchpattern_with_separator(*cvar_alias, partial, true, "", false))
1529 Con_Printf ("cvar ");
1530 Cvar_PrintHelp(cvar, *cvar_alias, true);
1535 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1537 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1538 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1540 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1543 for (func = cmd->engine_functions; func; func = func->next)
1545 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1546 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1548 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1551 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1553 // procede here a bit differently as an alias value always got a final \n
1554 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1555 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1557 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1560 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1563 static cmd_state_t *Cmd_AddInterpreter(cmd_buf_t *cbuf, cvar_state_t *cvars, unsigned cvars_flagsmask, unsigned cmds_flagsmask, cmd_userdefined_t *userdefined)
1565 cmd_state_t *cmd = (cmd_state_t *)Mem_Alloc(tempmempool, sizeof(cmd_state_t));
1567 cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1568 // space for commands and script files
1570 cmd->null_string = "";
1573 cmd->cvars_flagsmask = cvars_flagsmask;
1574 cmd->cmd_flagsmask = cmds_flagsmask;
1575 cmd->userdefined = userdefined;
1588 unsigned cvars_flagsmask, cmds_flagsmask;
1590 cbuf_mempool = Mem_AllocPool("Command buffer", 0, NULL);
1591 cbuf = (cmd_buf_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_buf_t));
1592 cbuf->maxsize = CMDBUFSIZE;
1593 cbuf->lock = Thread_CreateMutex();
1597 cbuf->start.prev = cbuf->start.next = &(cbuf->start);
1598 cbuf->deferred.prev = cbuf->deferred.next = &(cbuf->deferred);
1599 cbuf->free.prev = cbuf->free.next = &(cbuf->free);
1601 // FIXME: Get rid of cmd_iter_all eventually. This is just a hack to reduce the amount of work to make the interpreters dynamic.
1602 cmd_iter_all = (cmd_iter_t *)Mem_Alloc(tempmempool, sizeof(cmd_iter_t) * 3);
1605 if (cls.state == ca_dedicated)
1607 cvars_flagsmask = CF_SERVER;
1608 cmds_flagsmask = CF_SERVER | CF_SERVER_FROM_CLIENT;
1612 cvars_flagsmask = CF_CLIENT | CF_SERVER;
1613 cmds_flagsmask = CF_CLIENT | CF_SERVER | CF_CLIENT_FROM_SERVER | CF_SERVER_FROM_CLIENT;
1615 cmd_iter_all[0].cmd = cmd_local = Cmd_AddInterpreter(cbuf, &cvars_all, cvars_flagsmask, cmds_flagsmask, &cmd_userdefined_all);
1616 cmd_local->Handle = Cmd_CL_Callback;
1618 // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1619 cmd_iter_all[1].cmd = cmd_serverfromclient = Cmd_AddInterpreter(cbuf, &cvars_null, 0, CF_SERVER_FROM_CLIENT | CF_USERINFO, &cmd_userdefined_null);
1620 cmd_serverfromclient->Handle = Cmd_SV_Callback;
1622 cmd_iter_all[2].cmd = NULL;
1624 // register our commands
1626 // client-only commands
1627 Cmd_AddCommand(CF_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1629 // maintenance commands used for upkeep of cvars and saved configs
1630 Cmd_AddCommand(CF_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1631 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");
1632 Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1633 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)");
1634 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)");
1636 // general console commands used in multiple environments
1637 Cmd_AddCommand(CF_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1638 Cmd_AddCommand(CF_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1639 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");
1640 Cmd_AddCommand(CF_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1641 Cmd_AddCommand(CF_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1642 Cmd_AddCommand(CF_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1643 Cmd_AddCommand(CF_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1645 #ifdef FILLALLCVARSWITHRUBBISH
1646 Cmd_AddCommand(CF_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1647 #endif /* FILLALLCVARSWITHRUBBISH */
1649 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1650 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1651 Cmd_AddCommand(CF_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1652 Cmd_AddCommand(CF_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1653 Cmd_AddCommand(CF_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1654 Cmd_AddCommand(CF_SHARED, "find", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1656 Cmd_AddCommand(CF_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1659 // Support Doom3-style Toggle Command
1660 Cmd_AddCommand(CF_SHARED | CF_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1668 void Cmd_Shutdown(void)
1670 cmd_iter_t *cmd_iter;
1671 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1673 cmd_state_t *cmd = cmd_iter->cmd;
1675 if (cmd->cbuf->lock)
1677 // we usually have this locked when we get here from Host_Quit_f
1678 Cbuf_Unlock(cmd->cbuf);
1681 Mem_FreePool(&cmd->mempool);
1689 Parses the given string into command line tokens.
1690 Takes a null terminated string. Does not need to be /n terminated.
1693 // AK: This function should only be called from ExecuteString because the current design is a bit of an hack
1694 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1700 cmd->cmdline = NULL;
1704 // skip whitespace up to a /n
1705 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1712 if (*text == '\n' || *text == '\r')
1714 // a newline separates commands in the buffer
1715 if (*text == '\r' && text[1] == '\n')
1725 cmd->cmdline = text;
1729 if (!COM_ParseToken_Console(&text))
1732 if (cmd->argc < MAX_ARGS)
1734 l = (int)strlen(com_token) + 1;
1735 if (cmd->cbuf->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1737 Con_Printf(CON_WARN "Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1740 memcpy (cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos, com_token, l);
1741 cmd->argv[cmd->argc] = cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos;
1742 cmd->cbuf->tokenizebufferpos += l;
1754 void Cmd_AddCommand(unsigned flags, const char *cmd_name, xcommand_t function, const char *description)
1756 cmd_function_t *func;
1757 cmd_function_t *prev, *current;
1761 for (i = 0; i < 2; i++)
1763 cmd = cmd_iter_all[i].cmd;
1764 if (flags & cmd->cmd_flagsmask)
1766 // fail if the command is a variable name
1767 if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1769 Con_Printf(CON_WARN "Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1775 // fail if the command already exists in this interpreter
1776 for (func = cmd->engine_functions; func; func = func->next)
1778 if (!strcmp(cmd_name, func->name))
1780 Con_Printf(CON_WARN "Cmd_AddCommand: %s already defined\n", cmd_name);
1785 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1786 func->flags = flags;
1787 func->name = cmd_name;
1788 func->function = function;
1789 func->description = description;
1790 func->next = cmd->engine_functions;
1792 // insert it at the right alphanumeric position
1793 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1799 cmd->engine_functions = func;
1801 func->next = current;
1805 // mark qcfunc if the function already exists in the qc_functions list
1806 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1808 if (!strcmp(cmd_name, func->name))
1810 func->qcfunc = true; //[515]: csqc
1815 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1816 func->flags = flags;
1817 func->name = cmd_name;
1818 func->function = function;
1819 func->description = description;
1820 func->qcfunc = true; //[515]: csqc
1821 func->next = cmd->userdefined->qc_functions;
1823 // bones_was_here: if this QC command overrides an engine command, store its pointer
1824 // to avoid doing this search at invocation if QC declines to handle this command.
1825 for (cmd_function_t *f = cmd->engine_functions; f; f = f->next)
1827 if (!strcmp(cmd_name, f->name))
1829 Con_DPrintf("Adding QC override of engine command %s\n", cmd_name);
1830 func->overridden = f;
1835 // insert it at the right alphanumeric position
1836 for (prev = NULL, current = cmd->userdefined->qc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1842 cmd->userdefined->qc_functions = func;
1844 func->next = current;
1855 qbool Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1857 cmd_function_t *func;
1859 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1860 if (!strcmp(cmd_name, func->name))
1863 for (func=cmd->engine_functions ; func ; func=func->next)
1864 if (!strcmp (cmd_name,func->name))
1876 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1878 cmd_function_t *func;
1881 len = strlen(partial);
1887 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1888 if (!strncasecmp(partial, func->name, len))
1891 for (func = cmd->engine_functions; func; func = func->next)
1892 if (!strncasecmp(partial, func->name, len))
1899 Cmd_CompleteCountPossible
1901 New function for tab-completion system
1902 Added by EvilTypeGuy
1903 Thanks to Fett erich@heintz.com
1907 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1909 cmd_function_t *func;
1914 len = strlen(partial);
1919 // Loop through the command list and count all partial matches
1920 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1921 if (!strncasecmp(partial, func->name, len))
1924 for (func = cmd->engine_functions; func; func = func->next)
1925 if (!strncasecmp(partial, func->name, len))
1932 Cmd_CompleteBuildList
1934 New function for tab-completion system
1935 Added by EvilTypeGuy
1936 Thanks to Fett erich@heintz.com
1940 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
1942 cmd_function_t *func;
1945 size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
1948 len = strlen(partial);
1949 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1950 // Loop through the functions lists and print all matches
1951 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1952 if (!strncasecmp(partial, func->name, len))
1953 buf[bpos++] = func->name;
1954 for (func = cmd->engine_functions; func; func = func->next)
1955 if (!strncasecmp(partial, func->name, len))
1956 buf[bpos++] = func->name;
1962 // written by LadyHavoc
1963 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
1965 cmd_function_t *func;
1966 size_t len = strlen(partial);
1967 // Loop through the command list and print all matches
1968 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1969 if (!strncasecmp(partial, func->name, len))
1970 Con_Printf("^2%s^7: %s\n", func->name, func->description);
1971 for (func = cmd->engine_functions; func; func = func->next)
1972 if (!strncasecmp(partial, func->name, len))
1973 Con_Printf("^2%s^7: %s\n", func->name, func->description);
1979 New function for tab-completion system
1980 Added by EvilTypeGuy
1981 Thanks to Fett erich@heintz.com
1985 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
1990 len = strlen(partial);
1996 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1997 if (!strncasecmp(partial, alias->name, len))
2003 // written by LadyHavoc
2004 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
2007 size_t len = strlen(partial);
2008 // Loop through the alias list and print all matches
2009 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2010 if (!strncasecmp(partial, alias->name, len))
2011 Con_Printf("^5%s^7: %s", alias->name, alias->value);
2016 Cmd_CompleteAliasCountPossible
2018 New function for tab-completion system
2019 Added by EvilTypeGuy
2020 Thanks to Fett erich@heintz.com
2024 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
2032 len = strlen(partial);
2037 // Loop through the command list and count all partial matches
2038 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2039 if (!strncasecmp(partial, alias->name, len))
2046 Cmd_CompleteAliasBuildList
2048 New function for tab-completion system
2049 Added by EvilTypeGuy
2050 Thanks to Fett erich@heintz.com
2054 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
2059 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
2062 len = strlen(partial);
2063 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2064 // Loop through the alias list and print all matches
2065 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2066 if (!strncasecmp(partial, alias->name, len))
2067 buf[bpos++] = alias->name;
2073 // TODO: Make this more generic?
2074 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2076 cmd_function_t *func;
2077 cmd_function_t **next = &cmd->userdefined->qc_functions;
2087 extern cvar_t sv_cheats;
2090 * Cloudwalk FIXME: This idea sounded great in my head but...
2091 * How do we handle commands that can be received by the client,
2092 * but which the server can also execute locally?
2094 * If we create a callback where the engine will forward to server
2095 * but try to execute the command locally if it's dedicated,
2096 * we're back to intermixing client and server code which I'm
2097 * trying to avoid. There's no other way I can think of to
2098 * implement that behavior that doesn't involve an #ifdef, or
2099 * making a mess of hooks.
2101 qbool Cmd_Callback(cmd_state_t *cmd, cmd_function_t *func)
2104 func->function(cmd);
2106 Con_Printf(CON_WARN "Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2110 qbool Cmd_CL_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, size_t textlen, cmd_source_t src)
2112 // TODO: Assign these functions to QC commands directly?
2115 if(((func->flags & CF_CLIENT) && CL_VM_ConsoleCommand(text, textlen)) ||
2116 ((func->flags & CF_SERVER) && SV_VM_ConsoleCommand(text, textlen)))
2119 if (func->overridden) // If this QC command overrides an engine command,
2120 func = func->overridden; // fall back to that command.
2122 if (func->flags & CF_SERVER_FROM_CLIENT)
2124 if(host_isclient.integer)
2126 CL_ForwardToServer_f(cmd);
2129 else if(!(func->flags & CF_SERVER))
2131 Con_Printf(CON_WARN "Cannot execute client commands from a dedicated server console.\n");
2135 return Cmd_Callback(cmd, func);
2138 qbool Cmd_SV_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, size_t textlen, cmd_source_t src)
2140 if(func->qcfunc && (func->flags & CF_SERVER))
2141 return SV_VM_ConsoleCommand(text, textlen);
2142 else if (src == src_client)
2144 if((func->flags & CF_CHEAT) && !sv_cheats.integer)
2145 SV_ClientPrintf(CON_WARN "No cheats allowed. The server must have sv_cheats set to 1\n");
2147 func->function(cmd);
2157 A complete command line has been parsed, so try to execute it
2158 FIXME: lookupnoadd the token to speed search?
2161 void Cmd_ExecuteString(cmd_state_t *cmd, const char *text, size_t textlen, cmd_source_t src, qbool lockmutex)
2164 cmd_function_t *func;
2168 Cbuf_Lock(cmd->cbuf);
2169 oldpos = cmd->cbuf->tokenizebufferpos;
2172 Cmd_TokenizeString (cmd, text);
2174 // execute the command line
2176 goto done; // no tokens
2179 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2180 if (!strcasecmp(cmd->argv[0], func->name))
2181 if(cmd->Handle(cmd, func, text, textlen, src))
2182 goto functions_done;
2184 for (func = cmd->engine_functions; func; func=func->next)
2185 if (!strcasecmp (cmd->argv[0], func->name))
2186 if(cmd->Handle(cmd, func, text, textlen, src))
2187 goto functions_done;
2190 // If it's a client command and wasn't found and handled, say so.
2191 // Also don't let clients call server aliases.
2192 if (cmd->source == src_client)
2195 Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2200 // Execute any alias with the same name as a command after the command.
2201 for (a=cmd->userdefined->alias ; a ; a=a->next)
2203 if (!strcasecmp (cmd->argv[0], a->name))
2205 Cmd_ExecuteAlias(cmd, a);
2210 // If the command was found and handled don't try to handle it as a cvar.
2215 // Xonotic is still maintained so we don't want to hide problems from getting fixed
2216 if (!Cvar_Command(cmd) && (host.framecount > 0 || gamemode == GAME_XONOTIC))
2217 Con_Printf(CON_WARN "Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2219 cmd->cbuf->tokenizebufferpos = oldpos;
2221 Cbuf_Unlock(cmd->cbuf);
2228 Returns the position (1 to argc-1) in the command's argument list
2229 where the given parameter apears, or 0 if not present
2233 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2239 Con_Printf(CON_WARN "Cmd_CheckParm: NULL");
2243 for (i = 1; i < Cmd_Argc (cmd); i++)
2244 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2252 void Cmd_SaveInitState(void)
2254 cmd_iter_t *cmd_iter;
2255 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2257 cmd_state_t *cmd = cmd_iter->cmd;
2260 for (f = cmd->userdefined->qc_functions; f; f = f->next)
2261 f->initstate = true;
2262 for (f = cmd->engine_functions; f; f = f->next)
2263 f->initstate = true;
2264 for (a = cmd->userdefined->alias; a; a = a->next)
2266 a->initstate = true;
2267 a->initialvalue = Mem_strdup(zonemempool, a->value);
2270 Cvar_SaveInitState(&cvars_all);
2273 void Cmd_RestoreInitState(void)
2275 cmd_iter_t *cmd_iter;
2276 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2278 cmd_state_t *cmd = cmd_iter->cmd;
2279 cmd_function_t *f, **fp;
2280 cmd_alias_t *a, **ap;
2281 for (fp = &cmd->userdefined->qc_functions; (f = *fp);)
2287 // destroy this command, it didn't exist at init
2288 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2293 for (fp = &cmd->engine_functions; (f = *fp);)
2299 // destroy this command, it didn't exist at init
2300 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2305 for (ap = &cmd->userdefined->alias; (a = *ap);)
2309 // restore this alias, it existed at init
2310 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2312 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2315 a->value = Mem_strdup(zonemempool, a->initialvalue);
2321 // free this alias, it didn't exist at init...
2322 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2330 Cvar_RestoreInitState(&cvars_all);
2333 void Cmd_NoOperation_f(cmd_state_t *cmd)