]> git.xonotic.org Git - xonotic/darkplaces.git/blob - cmd.c
110378ffcbb6c44af376bc749b9a14924cb80a24
[xonotic/darkplaces.git] / cmd.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
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.
8
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.
12
13 See the GNU General Public License for more details.
14
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.
18
19 */
20 // cmd.c -- Quake script command processing module
21
22 #include "quakedef.h"
23 #include "thread.h"
24
25 cmd_state_t *cmd_local;
26 cmd_state_t *cmd_serverfromclient;
27
28 cmd_userdefined_t cmd_userdefined_all;
29 cmd_userdefined_t cmd_userdefined_null;
30
31 typedef struct cmd_iter_s {
32         cmd_state_t *cmd;
33 }
34 cmd_iter_t;
35
36 static cmd_iter_t *cmd_iter_all;
37
38 mempool_t *cbuf_mempool;
39
40 // we only run the +whatever commandline arguments once
41 qbool host_stuffcmdsrun = false;
42
43 //=============================================================================
44
45 void Cbuf_Lock(cmd_buf_t *cbuf)
46 {
47         Thread_LockMutex(cbuf->lock);
48 }
49
50 void Cbuf_Unlock(cmd_buf_t *cbuf)
51 {
52         Thread_UnlockMutex(cbuf->lock);
53 }
54
55
56 /*
57 ============
58 Cmd_Wait_f
59
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"
63 ============
64 */
65 static void Cmd_Wait_f (cmd_state_t *cmd)
66 {
67         cmd->cbuf->wait = true;
68 }
69
70 /*
71 ============
72 Cmd_Defer_f
73
74 Cause a command to be executed after a delay.
75 ============
76 */
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)
80 {
81         cmd_input_t *current;
82         cmd_buf_t *cbuf = cmd->cbuf;
83         unsigned int cmdsize;
84
85         if(Cmd_Argc(cmd) == 1)
86         {
87                 if(List_Is_Empty(&cbuf->deferred))
88                         Con_Printf("No commands are pending.\n");
89                 else
90                 {
91                         List_For_Each_Entry(current, &cbuf->deferred, cmd_input_t, list)
92                                 Con_Printf("-> In %9.2f: %s\n", current->delay, current->text);
93                 }
94         }
95         else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
96         {
97                 while(!List_Is_Empty(&cbuf->deferred))
98                 {
99                         cbuf->size -= List_Entry(cbuf->deferred.next, cmd_input_t, list)->length;
100                         List_Move_Tail(cbuf->deferred.next, &cbuf->free);
101                 }
102         }
103         else if(Cmd_Argc(cmd) == 3 && (cmdsize = strlen(Cmd_Argv(cmd, 2))) )
104         {
105                 Cbuf_Lock(cbuf);
106
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));
109
110                 Cbuf_Unlock(cbuf);
111         }
112         else
113         {
114                 Con_Printf("usage: defer <seconds> <command>\n"
115                            "       defer clear\n");
116                 return;
117         }
118 }
119
120 /*
121 =============================================================================
122
123                                                 COMMAND BUFFER
124
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.
128  *
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.
132  *
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.
138
139 =============================================================================
140 */
141
142 /*
143 ============
144 Cbuf_NodeGet
145
146 Returns an existing buffer node for appending or reuse, or allocates a new one
147 ============
148 */
149 static cmd_input_t *Cbuf_NodeGet(cmd_buf_t *cbuf, cmd_input_t *existing)
150 {
151         cmd_input_t *node;
152         if(existing && existing->pending)
153                 node = existing;
154         else if(!List_Is_Empty(&cbuf->free))
155         {
156                 node = List_Entry(cbuf->free.next, cmd_input_t, list);
157                 node->length = node->pending = 0;
158         }
159         else
160         {
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;
164         }
165         return node;
166 }
167
168 /*
169 ============
170 Cbuf_LinkString
171
172 Copies a command string into a buffer node.
173 The input should not be null-terminated, the output will be.
174 ============
175 */
176 static void Cbuf_LinkString(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool leavepending, unsigned int cmdsize)
177 {
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)
181
182         // node will match existing if its text was pending continuation
183         if(node != existing)
184         {
185                 node->source = cmd;
186                 List_Move_Tail(&node->list, head);
187         }
188
189         node->length += cmdsize;
190         if(node->size < node->length)
191         {
192                 node->text = (char *)Mem_Realloc(cbuf_mempool, node->text, node->length + 1);
193                 node->size = node->length;
194         }
195         cbuf->size += cmdsize;
196
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;
200 }
201
202 /*
203 ============
204 Cbuf_ParseText
205
206 Parses text to isolate command strings for linking into the buffer
207 separators: \n \r or unquoted and uncommented ';'
208 ============
209 */
210 static void Cbuf_ParseText(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool allowpending)
211 {
212         unsigned int cmdsize = 0, start = 0, pos;
213         qbool quotes = false, comment = false;
214
215         for (pos = 0; text[pos]; ++pos)
216         {
217                 switch(text[pos])
218                 {
219                         case ';':
220                                 if (comment || quotes)
221                                         break;
222                         case '\r':
223                         case '\n':
224                                 comment = false;
225                                 quotes = false; // matches div0-stable
226                                 if (cmdsize)
227                                 {
228                                         Cbuf_LinkString(cmd, head, existing, &text[start], false, cmdsize);
229                                         cmdsize = 0;
230                                 }
231                                 else if (existing && existing->pending) // all I got was this lousy \n
232                                         existing->pending = false;
233                                 continue; // don't increment cmdsize
234
235                         case '/':
236                                 if (!quotes && text[pos + 1] == '/' && (pos == 0 || ISWHITESPACE(text[pos - 1])))
237                                         comment = true;
238                                 break;
239                         case '"':
240                                 if (!comment && (pos == 0 || text[pos - 1] != '\\'))
241                                         quotes = !quotes;
242                                 break;
243                 }
244
245                 if (!comment)
246                 {
247                         if (!cmdsize)
248                                 start = pos;
249                         ++cmdsize;
250                 }
251         }
252
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);
255 }
256
257 /*
258 ============
259 Cbuf_AddText
260
261 Adds command text at the end of the buffer
262 ============
263 */
264 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
265 {
266         size_t l = strlen(text);
267         cmd_buf_t *cbuf = cmd->cbuf;
268         llist_t llist = {&llist, &llist};
269
270         if (cbuf->size + l > cbuf->maxsize)
271         {
272                 Con_Printf(CON_WARN "Cbuf_AddText: input too large, %luKB ought to be enough for anybody.\n", (unsigned long)(cbuf->maxsize / 1024));
273                 return;
274         }
275
276         Cbuf_Lock(cbuf);
277
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);
281
282         Cbuf_Unlock(cbuf);
283 }
284
285 /*
286 ============
287 Cbuf_InsertText
288
289 Adds command text immediately after the current command
290 ============
291 */
292 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
293 {
294         cmd_buf_t *cbuf = cmd->cbuf;
295         llist_t llist = {&llist, &llist};
296         size_t l = strlen(text);
297
298         if (cbuf->size + l > cbuf->maxsize)
299         {
300                 Con_Printf(CON_WARN "Cbuf_InsertText: input too large, %luKB ought to be enough for anybody.\n", (unsigned long)(cbuf->maxsize / 1024));
301                 return;
302         }
303
304         Cbuf_Lock(cbuf);
305
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);
311
312         Cbuf_Unlock(cbuf);
313 }
314
315 /*
316 ============
317 Cbuf_Execute_Deferred --blub
318 ============
319 */
320 static void Cbuf_Execute_Deferred (cmd_buf_t *cbuf)
321 {
322         cmd_input_t *current, *n;
323         vec_t eat;
324
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;
328         if (eat < 1.0/128.0)
329                 return;
330         cbuf->deferred_oldtime = host.realtime;
331
332         List_For_Each_Entry_Safe(current, n, &cbuf->deferred, cmd_input_t, list)
333         {
334                 current->delay -= eat;
335                 if(current->delay <= 0)
336                 {
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(&current->list, &cbuf->free); // make deferred string memory available for reuse
340                         cbuf->size -= current->length;
341                 }
342         }
343 }
344
345 /*
346 ============
347 Cbuf_Execute
348 ============
349 */
350 extern qbool prvm_runawaycheck;
351 void Cbuf_Execute (cmd_buf_t *cbuf)
352 {
353         cmd_input_t *current;
354         unsigned int i = 0;
355
356         // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
357         cbuf->tokenizebufferpos = 0;
358
359         while (!List_Is_Empty(&cbuf->start))
360         {
361                 /*
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
365                  */
366                 current = List_Entry(cbuf->start.next, cmd_input_t, list);
367
368                 /*
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.
372                  */
373                 current->pending = false;
374
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(&current->list, &cbuf->free);
379
380                 if (cbuf->wait)
381                 {
382                         /*
383                          * Skip out while text still remains in
384                          * buffer, leaving it for next frame
385                          */
386                         cbuf->wait = false;
387                         break;
388                 }
389
390                 if (++i == 1000000 && prvm_runawaycheck)
391                 {
392                         Con_Printf(CON_WARN "Cbuf_Execute: runaway loop counter hit limit of %d commands, clearing command buffers!\n", i);
393                         Cbuf_Clear(cbuf);
394                 }
395         }
396 }
397
398 /*
399 ===================
400 Cbuf_Frame_Input
401
402 Add them exactly as if they had been typed at the console
403 ===================
404 */
405 static void Cbuf_Frame_Input(void)
406 {
407         char *line;
408
409         if ((line = Sys_ConsoleInput()))
410         {
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);
414         }
415 }
416
417 void Cbuf_Frame(cmd_buf_t *cbuf)
418 {
419         // check for commands typed to the host
420         Cbuf_Frame_Input();
421
422 //      R_TimeReport("preconsole");
423
424         // execute commands queued with the defer command
425         Cbuf_Execute_Deferred(cbuf);
426         if (cbuf->size)
427         {
428                 SV_LockThreadMutex();
429                 Cbuf_Execute(cbuf);
430                 SV_UnlockThreadMutex();
431         }
432
433 //      R_TimeReport("console");
434 }
435
436 void Cbuf_Clear(cmd_buf_t *cbuf)
437 {
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);
442         cbuf->size = 0;
443 }
444
445 /*
446 ==============================================================================
447
448                                                 SCRIPT COMMANDS
449
450 ==============================================================================
451 */
452
453 /*
454 ===============
455 Cmd_StuffCmds_f
456
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
461 ===============
462 */
463 static void Cmd_StuffCmds_f (cmd_state_t *cmd)
464 {
465         int             i, j, l;
466         // this is for all commandline options combined (and is bounds checked)
467         char    build[MAX_INPUTLINE];
468
469         if (Cmd_Argc (cmd) != 1)
470         {
471                 Con_Print("stuffcmds : execute command line parameters\n");
472                 return;
473         }
474
475         // no reason to run the commandline arguments twice
476         if (host_stuffcmdsrun)
477                 return;
478
479         host_stuffcmdsrun = true;
480         build[0] = 0;
481         l = 0;
482         for (i = 0;i < sys.argc;i++)
483         {
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)
485                 {
486                         j = 1;
487                         while (sys.argv[i][j])
488                                 build[l++] = sys.argv[i][j++];
489                         i++;
490                         for (;i < sys.argc;i++)
491                         {
492                                 if (!sys.argv[i])
493                                         continue;
494                                 if ((sys.argv[i][0] == '+' || sys.argv[i][0] == '-') && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9'))
495                                         break;
496                                 if (l + strlen(sys.argv[i]) + 4 > sizeof(build) - 1)
497                                         break;
498                                 build[l++] = ' ';
499                                 if (strchr(sys.argv[i], ' '))
500                                         build[l++] = '\"';
501                                 for (j = 0;sys.argv[i][j];j++)
502                                         build[l++] = sys.argv[i][j];
503                                 if (strchr(sys.argv[i], ' '))
504                                         build[l++] = '\"';
505                         }
506                         build[l++] = '\n';
507                         i--;
508                 }
509         }
510         // now terminate the combined string and prepend it to the command buffer
511         // we already reserved space for the terminator
512         build[l++] = 0;
513         Cbuf_InsertText (cmd, build);
514 }
515
516 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
517 {
518         char *f;
519         size_t filenameLen = strlen(filename);
520         qbool isdefaultcfg =
521                 !strcmp(filename, "default.cfg") ||
522                 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
523
524         if (!strcmp(filename, "config.cfg"))
525         {
526                 filename = CONFIGFILENAME;
527                 if (Sys_CheckParm("-noconfig"))
528                         return; // don't execute config.cfg
529         }
530
531         f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
532         if (!f)
533         {
534                 Con_Printf(CON_WARN "couldn't exec %s\n",filename);
535                 return;
536         }
537         Con_Printf("execing %s\n",filename);
538
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.
542         if (isdefaultcfg)
543                 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
544
545         Cbuf_InsertText (cmd, f);
546         Mem_Free(f);
547
548         if (isdefaultcfg)
549         {
550                 // special defaults for specific games go here, these execute before default.cfg
551                 // and after gamegroup defaults (see below)
552                 switch(gamemode)
553                 {
554                 case GAME_NEHAHRA:
555                         Cbuf_InsertText(cmd, "\n"
556 // Nehahra pushable crates malfunction in some levels if this is on
557 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
558 // Nehahra NPC AI is confused by blowupfallenzombies
559 "sv_gameplayfix_blowupfallenzombies 0\n"
560                                 );
561                         break;
562                 case GAME_HIPNOTIC:
563                 case GAME_QUOTH:
564                         Cbuf_InsertText(cmd, "\n"
565 // 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.
566 "sv_gameplayfix_blowupfallenzombies 0\n"
567 // 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
568 "sys_ticrate 0.02\n"
569 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
570 "sv_gameplayfix_slidemoveprojectiles 0\n"
571                                 );
572                         break;
573                 case GAME_ROGUE:
574                         Cbuf_InsertText(cmd, "\n"
575 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
576 "sv_gameplayfix_blowupfallenzombies 0\n"
577 // On r2m3 3 of the 4 monster_lava_man are placed in solid clips so droptofloor() moves them to a lower level if tracebox can
578 // move them out of solid, if it can't they're stuck (original behaviour), only proper fix is to move them with a .ent file.
579 "mod_q1bsp_traceoutofsolid 0\n"
580                                 );
581                         break;
582                 case GAME_TENEBRAE:
583                         Cbuf_InsertText(cmd, "\n"
584 "r_shadow_gloss 2\n"
585 "r_shadow_bumpscale_basetexture 4\n"
586                                 );
587                         break;
588                 case GAME_NEXUIZ:
589                         Cbuf_InsertText(cmd, "\n"
590 "sv_gameplayfix_q2airaccelerate 1\n"
591 "sv_gameplayfix_stepmultipletimes 1\n"
592 "csqc_polygons_defaultmaterial_nocullface 1\n"
593 "con_chatsound_team_mask 13\n"
594                                 );
595                         break;
596                 case GAME_XONOTIC:
597                 case GAME_VORETOURNAMENT:
598                         Cbuf_InsertText(cmd, "\n"
599 // 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
600 "csqc_polygons_defaultmaterial_nocullface 1\n"
601 "con_chatsound_team_mask 13\n"
602 "sv_qcstats 1\n"
603 "mod_q1bsp_zero_hullsize_cutoff 8.03125\n"
604                                 );
605                         break;
606                 case GAME_STEELSTORM:
607                         Cbuf_InsertText(cmd, "\n"
608 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
609 "cl_csqc_generatemousemoveevents 0\n"
610 "csqc_polygons_defaultmaterial_nocullface 1\n"
611                                 );
612                         break;
613                 case GAME_QUAKE15:
614                         Cbuf_InsertText(cmd, "\n"
615 // Corpses slide around without this bug from old DP versions
616 "sv_gameplayfix_impactbeforeonground 1\n"
617 // Reduce likelihood of incorrectly placed corpses sinking into the ground
618 "sv_gameplayfix_unstickentities 1\n"
619                         );
620                         break;
621                 case GAME_AD:
622                         Cbuf_InsertText(cmd, "\n"
623 // Arcane Dimensions V1.80 Patch 1 assumes engines that don't pass values to CSQC_Init() are DP,
624 // instead of doing a workaround there we can give it what it really wants (fixes offscreen HUD).
625 "csqc_lowres 1\n"
626                         );
627                         break;
628                 default:
629                         break;
630                 }
631
632                 // special defaults for game groups go here, these execute before the specific games above
633                 switch (com_startupgamegroup)
634                 {
635                 case GAME_NORMAL: // id1 Quake and its mods
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                                 );
655                         break;
656                 default:
657                         break;
658                 }
659         }
660 }
661
662 /*
663 ===============
664 Cmd_Exec_f
665 ===============
666 */
667 static void Cmd_Exec_f (cmd_state_t *cmd)
668 {
669         fssearch_t *s;
670         int i;
671
672         if (Cmd_Argc(cmd) != 2)
673         {
674                 Con_Print("exec <filename> : execute a script file\n");
675                 return;
676         }
677
678         s = FS_Search(Cmd_Argv(cmd, 1), true, true, NULL);
679         if(!s || !s->numfilenames)
680         {
681                 Con_Printf(CON_WARN "couldn't exec %s\n",Cmd_Argv(cmd, 1));
682                 return;
683         }
684
685         for(i = 0; i < s->numfilenames; ++i)
686                 Cmd_Exec(cmd, s->filenames[i]);
687
688         FS_FreeSearch(s);
689 }
690
691
692 /*
693 ===============
694 Cmd_Echo_f
695
696 Just prints the rest of the line to the console
697 ===============
698 */
699 static void Cmd_Echo_f (cmd_state_t *cmd)
700 {
701         int             i;
702
703         for (i=1 ; i<Cmd_Argc(cmd) ; i++)
704                 Con_Printf("%s ",Cmd_Argv(cmd, i));
705         Con_Print("\n");
706 }
707
708 // DRESK - 5/14/06
709 // Support Doom3-style Toggle Console Command
710 /*
711 ===============
712 Cmd_Toggle_f
713
714 Toggles a specified console variable amongst the values specified (default is 0 and 1)
715 ===============
716 */
717 static void Cmd_Toggle_f(cmd_state_t *cmd)
718 {
719         // Acquire Number of Arguments
720         int nNumArgs = Cmd_Argc(cmd);
721
722         if(nNumArgs == 1)
723                 // No Arguments Specified; Print Usage
724                 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");
725         else
726         { // Correct Arguments Specified
727                 // Acquire Potential CVar
728                 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
729
730                 if(cvCVar != NULL)
731                 { // Valid CVar
732                         if(nNumArgs == 2)
733                         { // Default Usage
734                                 if(cvCVar->integer)
735                                         Cvar_SetValueQuick(cvCVar, 0);
736                                 else
737                                         Cvar_SetValueQuick(cvCVar, 1);
738                         }
739                         else
740                         if(nNumArgs == 3)
741                         { // 0 and Specified Usage
742                                 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
743                                         // CVar is Specified Value; // Reset to 0
744                                         Cvar_SetValueQuick(cvCVar, 0);
745                                 else
746                                 if(cvCVar->integer == 0)
747                                         // CVar is 0; Specify Value
748                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
749                                 else
750                                         // CVar does not match; Reset to 0
751                                         Cvar_SetValueQuick(cvCVar, 0);
752                         }
753                         else
754                         { // Variable Values Specified
755                                 int nCnt;
756                                 int bFound = 0;
757
758                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
759                                 { // Cycle through Values
760                                         if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
761                                         { // Current Value Located; Increment to Next
762                                                 if( (nCnt + 1) == nNumArgs)
763                                                         // Max Value Reached; Reset
764                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
765                                                 else
766                                                         // Next Value
767                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
768
769                                                 // End Loop
770                                                 nCnt = nNumArgs;
771                                                 // Assign Found
772                                                 bFound = 1;
773                                         }
774                                 }
775                                 if(!bFound)
776                                         // Value not Found; Reset to Original
777                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
778                         }
779
780                 }
781                 else
782                 { // Invalid CVar
783                         Con_Printf(CON_WARN "ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
784                 }
785         }
786 }
787
788 /*
789 ===============
790 Cmd_Alias_f
791
792 Creates a new command that executes a command string (possibly ; seperated)
793 ===============
794 */
795 static void Cmd_Alias_f (cmd_state_t *cmd)
796 {
797         cmd_alias_t     *a;
798         char            line[MAX_INPUTLINE];
799         int                     i, c;
800         const char              *s;
801         size_t          alloclen;
802
803         if (Cmd_Argc(cmd) == 1)
804         {
805                 Con_Print("Current alias commands:\n");
806                 for (a = cmd->userdefined->alias ; a ; a=a->next)
807                         Con_Printf("%s : %s", a->name, a->value);
808                 return;
809         }
810
811         s = Cmd_Argv(cmd, 1);
812         if (strlen(s) >= MAX_ALIAS_NAME)
813         {
814                 Con_Print(CON_WARN "Alias name is too long\n");
815                 return;
816         }
817
818         // if the alias already exists, reuse it
819         for (a = cmd->userdefined->alias ; a ; a=a->next)
820         {
821                 if (!strcmp(s, a->name))
822                 {
823                         Z_Free (a->value);
824                         break;
825                 }
826         }
827
828         if (!a)
829         {
830                 cmd_alias_t *prev, *current;
831
832                 a = (cmd_alias_t *)Z_Malloc (sizeof(cmd_alias_t));
833                 dp_strlcpy (a->name, s, sizeof (a->name));
834                 // insert it at the right alphanumeric position
835                 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
836                         ;
837                 if( prev ) {
838                         prev->next = a;
839                 } else {
840                         cmd->userdefined->alias = a;
841                 }
842                 a->next = current;
843         }
844
845
846 // copy the rest of the command line
847         line[0] = 0;            // start out with a null string
848         c = Cmd_Argc(cmd);
849         for (i=2 ; i < c ; i++)
850         {
851                 if (i != 2)
852                         dp_strlcat (line, " ", sizeof (line));
853                 dp_strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
854         }
855         dp_strlcat (line, "\n", sizeof (line));
856
857         alloclen = strlen (line) + 1;
858         if(alloclen >= 2)
859                 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
860         a->value = (char *)Z_Malloc (alloclen);
861         memcpy (a->value, line, alloclen);
862 }
863
864 /*
865 ===============
866 Cmd_UnAlias_f
867
868 Remove existing aliases.
869 ===============
870 */
871 static void Cmd_UnAlias_f (cmd_state_t *cmd)
872 {
873         cmd_alias_t     *a, *p;
874         int i;
875         const char *s;
876
877         if(Cmd_Argc(cmd) == 1)
878         {
879                 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
880                 return;
881         }
882
883         for(i = 1; i < Cmd_Argc(cmd); ++i)
884         {
885                 s = Cmd_Argv(cmd, i);
886                 p = NULL;
887                 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
888                 {
889                         if(!strcmp(s, a->name))
890                         {
891                                 if (a->initstate) // we can not remove init aliases
892                                         continue;
893                                 if(a == cmd->userdefined->alias)
894                                         cmd->userdefined->alias = a->next;
895                                 if(p)
896                                         p->next = a->next;
897                                 Z_Free(a->value);
898                                 Z_Free(a);
899                                 break;
900                         }
901                 }
902                 if(!a)
903                         Con_Printf("unalias: %s alias not found\n", s);
904         }
905 }
906
907 /*
908 =============================================================================
909
910                                         COMMAND EXECUTION
911
912 =============================================================================
913 */
914
915 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmd_alias_t *alias, qbool *is_multiple)
916 {
917         cvar_t *cvar;
918         long argno;
919         char *endptr;
920         static char vabuf[1024]; // cmd_mutex
921
922         if(is_multiple)
923                 *is_multiple = false;
924
925         if(!varname || !*varname)
926                 return NULL;
927
928         if(alias)
929         {
930                 if(!strcmp(varname, "*"))
931                 {
932                         if(is_multiple)
933                                 *is_multiple = true;
934                         return Cmd_Args(cmd);
935                 }
936                 else if(!strcmp(varname, "#"))
937                 {
938                         return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
939                 }
940                 else if(varname[strlen(varname) - 1] == '-')
941                 {
942                         argno = strtol(varname, &endptr, 10);
943                         if(endptr == varname + strlen(varname) - 1)
944                         {
945                                 // whole string is a number, apart from the -
946                                 const char *p = Cmd_Args(cmd);
947                                 for(; argno > 1; --argno)
948                                         if(!COM_ParseToken_Console(&p))
949                                                 break;
950                                 if(p)
951                                 {
952                                         if(is_multiple)
953                                                 *is_multiple = true;
954
955                                         // kill pre-argument whitespace
956                                         for (;*p && ISWHITESPACE(*p);p++)
957                                                 ;
958
959                                         return p;
960                                 }
961                         }
962                 }
963                 else
964                 {
965                         argno = strtol(varname, &endptr, 10);
966                         if(*endptr == 0)
967                         {
968                                 // whole string is a number
969                                 // NOTE: we already made sure we don't have an empty cvar name!
970                                 if(argno >= 0 && argno < Cmd_Argc(cmd))
971                                         return Cmd_Argv(cmd, argno);
972                         }
973                 }
974         }
975
976         if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CF_PRIVATE))
977                 return cvar->string;
978
979         return NULL;
980 }
981
982 qbool Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qbool putquotes)
983 {
984         qbool quote_quot = !!strchr(quoteset, '"');
985         qbool quote_backslash = !!strchr(quoteset, '\\');
986         qbool quote_dollar = !!strchr(quoteset, '$');
987
988         if(putquotes)
989         {
990                 if(outlen <= 2)
991                 {
992                         *out++ = 0;
993                         return false;
994                 }
995                 *out++ = '"'; --outlen;
996                 --outlen;
997         }
998
999         while(*in)
1000         {
1001                 if(*in == '"' && quote_quot)
1002                 {
1003                         if(outlen <= 2)
1004                                 goto fail;
1005                         *out++ = '\\'; --outlen;
1006                         *out++ = '"'; --outlen;
1007                 }
1008                 else if(*in == '\\' && quote_backslash)
1009                 {
1010                         if(outlen <= 2)
1011                                 goto fail;
1012                         *out++ = '\\'; --outlen;
1013                         *out++ = '\\'; --outlen;
1014                 }
1015                 else if(*in == '$' && quote_dollar)
1016                 {
1017                         if(outlen <= 2)
1018                                 goto fail;
1019                         *out++ = '$'; --outlen;
1020                         *out++ = '$'; --outlen;
1021                 }
1022                 else
1023                 {
1024                         if(outlen <= 1)
1025                                 goto fail;
1026                         *out++ = *in; --outlen;
1027                 }
1028                 ++in;
1029         }
1030         if(putquotes)
1031                 *out++ = '"';
1032         *out++ = 0;
1033         return true;
1034 fail:
1035         if(putquotes)
1036                 *out++ = '"';
1037         *out++ = 0;
1038         return false;
1039 }
1040
1041 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmd_alias_t *alias)
1042 {
1043         static char varname[MAX_INPUTLINE]; // cmd_mutex
1044         static char varval[MAX_INPUTLINE]; // cmd_mutex
1045         const char *varstr = NULL;
1046         char *varfunc;
1047         qbool required = false;
1048         qbool optional = false;
1049         static char asis[] = "asis"; // just to suppress const char warnings
1050
1051         if(varlen >= MAX_INPUTLINE)
1052                 varlen = MAX_INPUTLINE - 1;
1053         memcpy(varname, var, varlen);
1054         varname[varlen] = 0;
1055         varfunc = strchr(varname, ' ');
1056
1057         if(varfunc)
1058         {
1059                 *varfunc = 0;
1060                 ++varfunc;
1061         }
1062
1063         if(*var == 0)
1064         {
1065                 // empty cvar name?
1066                 if(alias)
1067                         Con_Printf(CON_WARN "Warning: Could not expand $ in alias %s\n", alias->name);
1068                 else
1069                         Con_Printf(CON_WARN "Warning: Could not expand $\n");
1070                 return "$";
1071         }
1072
1073         if(varfunc)
1074         {
1075                 char *p;
1076                 // ? means optional
1077                 while((p = strchr(varfunc, '?')))
1078                 {
1079                         optional = true;
1080                         memmove(p, p+1, strlen(p)); // with final NUL
1081                 }
1082                 // ! means required
1083                 while((p = strchr(varfunc, '!')))
1084                 {
1085                         required = true;
1086                         memmove(p, p+1, strlen(p)); // with final NUL
1087                 }
1088                 // kill spaces
1089                 while((p = strchr(varfunc, ' ')))
1090                 {
1091                         memmove(p, p+1, strlen(p)); // with final NUL
1092                 }
1093                 // if no function is left, NULL it
1094                 if(!*varfunc)
1095                         varfunc = NULL;
1096         }
1097
1098         if(varname[0] == '$')
1099                 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1100         else
1101         {
1102                 qbool is_multiple = false;
1103                 // Exception: $* and $n- don't use the quoted form by default
1104                 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1105                 if(is_multiple)
1106                         if(!varfunc)
1107                                 varfunc = asis;
1108         }
1109
1110         if(!varstr)
1111         {
1112                 if(required)
1113                 {
1114                         if(alias)
1115                                 Con_Printf(CON_ERROR "Error: Could not expand $%s in alias %s\n", varname, alias->name);
1116                         else
1117                                 Con_Printf(CON_ERROR "Error: Could not expand $%s\n", varname);
1118                         return NULL;
1119                 }
1120                 else if(optional)
1121                 {
1122                         return "";
1123                 }
1124                 else
1125                 {
1126                         if(alias)
1127                                 Con_Printf(CON_WARN "Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1128                         else
1129                                 Con_Printf(CON_WARN "Warning: Could not expand $%s\n", varname);
1130                         dpsnprintf(varval, sizeof(varval), "$%s", varname);
1131                         return varval;
1132                 }
1133         }
1134
1135         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1136         {
1137                 // quote it so it can be used inside double quotes
1138                 // we just need to replace " by \", and of course, double backslashes
1139                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1140                 return varval;
1141         }
1142         else if(!strcmp(varfunc, "asis"))
1143         {
1144                 return varstr;
1145         }
1146         else
1147                 Con_Printf("Unknown variable function %s\n", varfunc);
1148
1149         return varstr;
1150 }
1151
1152 /**
1153 Cmd_PreprocessString
1154
1155 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1156 Returns the number of bytes written to *outtext excluding the \0 terminator.
1157 */
1158 static size_t Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias)
1159 {
1160         const char *in;
1161         size_t eat, varlen;
1162         unsigned outlen;
1163         const char *val;
1164
1165         // don't crash if there's no room in the outtext buffer
1166         if( maxoutlen == 0 ) {
1167                 return 0;
1168         }
1169         maxoutlen--; // because of \0
1170
1171         in = intext;
1172         outlen = 0;
1173
1174         while( *in && outlen < maxoutlen ) {
1175                 if( *in == '$' ) {
1176                         // this is some kind of expansion, see what comes after the $
1177                         in++;
1178
1179                         // The console does the following preprocessing:
1180                         //
1181                         // - $$ is transformed to a single dollar sign.
1182                         // - $var or ${var} are expanded to the contents of the named cvar,
1183                         //   with quotation marks and backslashes quoted so it can safely
1184                         //   be used inside quotation marks (and it should always be used
1185                         //   that way)
1186                         // - ${var asis} inserts the cvar value as is, without doing this
1187                         //   quoting
1188                         // - ${var ?} silently expands to the empty string if
1189                         //   $var does not exist
1190                         // - ${var !} fails expansion and executes nothing if
1191                         //   $var does not exist
1192                         // - prefix the cvar name with a dollar sign to do indirection;
1193                         //   for example, if $x has the value timelimit, ${$x} will return
1194                         //   the value of $timelimit
1195                         // - when expanding an alias, the special variable name $* refers
1196                         //   to all alias parameters, and a number refers to that numbered
1197                         //   alias parameter, where the name of the alias is $0, the first
1198                         //   parameter is $1 and so on; as a special case, $* inserts all
1199                         //   parameters, without extra quoting, so one can use $* to just
1200                         //   pass all parameters around. All parameters starting from $n
1201                         //   can be referred to as $n- (so $* is equivalent to $1-).
1202                         // - ${* q} and ${n- q} force quoting anyway
1203                         //
1204                         // Note: when expanding an alias, cvar expansion is done in the SAME step
1205                         // as alias expansion so that alias parameters or cvar values containing
1206                         // dollar signs have no unwanted bad side effects. However, this needs to
1207                         // be accounted for when writing complex aliases. For example,
1208                         //   alias foo "set x NEW; echo $x"
1209                         // actually expands to
1210                         //   "set x NEW; echo OLD"
1211                         // and will print OLD! To work around this, use a second alias:
1212                         //   alias foo "set x NEW; foo2"
1213                         //   alias foo2 "echo $x"
1214                         //
1215                         // Also note: lines starting with alias are exempt from cvar expansion.
1216                         // If you want cvar expansion, write "alias" instead:
1217                         //
1218                         //   set x 1
1219                         //   alias foo "echo $x"
1220                         //   "alias" bar "echo $x"
1221                         //   set x 2
1222                         //
1223                         // foo will print 2, because the variable $x will be expanded when the alias
1224                         // gets expanded. bar will print 1, because the variable $x was expanded
1225                         // at definition time. foo can be equivalently defined as
1226                         //
1227                         //   "alias" foo "echo $$x"
1228                         //
1229                         // because at definition time, $$ will get replaced to a single $.
1230
1231                         if( *in == '$' ) {
1232                                 val = "$";
1233                                 eat = 1;
1234                         } else if(*in == '{') {
1235                                 varlen = strcspn(in + 1, "}");
1236                                 if(in[varlen + 1] == '}')
1237                                 {
1238                                         val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1239                                         if(!val)
1240                                                 return 0;
1241                                         eat = varlen + 2;
1242                                 }
1243                                 else
1244                                 {
1245                                         // ran out of data?
1246                                         val = NULL;
1247                                         eat = varlen + 1;
1248                                 }
1249                         } else {
1250                                 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1251                                 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1252                                 if(!val)
1253                                         return 0;
1254                                 eat = varlen;
1255                         }
1256                         if(val)
1257                         {
1258                                 // insert the cvar value
1259                                 while(*val && outlen < maxoutlen)
1260                                         outtext[outlen++] = *val++;
1261                                 in += eat;
1262                         }
1263                         else
1264                         {
1265                                 // copy the unexpanded text
1266                                 outtext[outlen++] = '$';
1267                                 while(eat && outlen < maxoutlen)
1268                                 {
1269                                         outtext[outlen++] = *in++;
1270                                         --eat;
1271                                 }
1272                         }
1273                 }
1274                 else 
1275                         outtext[outlen++] = *in++;
1276         }
1277         outtext[outlen] = '\0';
1278         return outlen;
1279 }
1280
1281 /*
1282 ============
1283 Cmd_ExecuteAlias
1284
1285 Called for aliases and fills in the alias into the cbuffer
1286 ============
1287 */
1288 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmd_alias_t *alias)
1289 {
1290         static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1291         static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1292         qbool ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1293         if(!ret)
1294                 return;
1295         // insert at start of command buffer, so that aliases execute in order
1296         // (fixes bug introduced by Black on 20050705)
1297
1298         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1299         // have to make sure that no second variable expansion takes place, otherwise
1300         // alias parameters containing dollar signs can have bad effects.
1301         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1302         Cbuf_InsertText(cmd, buffer2);
1303 }
1304
1305 void Cmd_PreprocessAndExecuteString(cmd_state_t *cmd, const char *text, size_t textlen, cmd_source_t src, qbool lockmutex)
1306 {
1307         char preprocessed[MAX_INPUTLINE];
1308         size_t preprocessed_len;
1309         const char *firstchar;
1310
1311         firstchar = text;
1312         while(*firstchar && ISWHITESPACE(*firstchar))
1313                 ++firstchar;
1314         if((strncmp(firstchar, "alias", 5)   || !ISWHITESPACE(firstchar[5]))
1315         && (strncmp(firstchar, "bind", 4)    || !ISWHITESPACE(firstchar[4]))
1316         && (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7])))
1317         {
1318                 if((preprocessed_len = Cmd_PreprocessString(cmd, text, preprocessed, sizeof(preprocessed), NULL)))
1319                         Cmd_ExecuteString(cmd, preprocessed, preprocessed_len, src, lockmutex);
1320         }
1321         else
1322                 Cmd_ExecuteString(cmd, text, textlen, src, lockmutex);
1323 }
1324
1325 /*
1326 ========
1327 Cmd_List
1328
1329         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1330         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1331
1332 ========
1333 */
1334 static void Cmd_List_f (cmd_state_t *cmd)
1335 {
1336         cmd_function_t *func;
1337         const char *partial;
1338         size_t len;
1339         int count;
1340         qbool ispattern;
1341
1342         if (Cmd_Argc(cmd) > 1)
1343         {
1344                 partial = Cmd_Argv(cmd, 1);
1345                 len = strlen(partial);
1346                 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1347         }
1348         else
1349         {
1350                 partial = NULL;
1351                 len = 0;
1352                 ispattern = false;
1353         }
1354
1355         count = 0;
1356         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1357         {
1358                 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1359                         continue;
1360                 Con_Printf("%s : %s\n", func->name, func->description);
1361                 count++;
1362         }
1363         for (func = cmd->engine_functions; func; func = func->next)
1364         {
1365                 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1366                         continue;
1367                 Con_Printf("%s : %s\n", func->name, func->description);
1368                 count++;
1369         }
1370
1371         if (len)
1372         {
1373                 if(ispattern)
1374                         Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1375                 else
1376                         Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1377         }
1378         else
1379                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1380 }
1381
1382 static void Cmd_Apropos_f(cmd_state_t *cmd)
1383 {
1384         cmd_function_t *func;
1385         cvar_t *cvar;
1386         cmd_alias_t *alias;
1387         const char *partial;
1388         int count;
1389         qbool ispattern;
1390         char vabuf[1024];
1391
1392         if (Cmd_Argc(cmd) > 1)
1393                 partial = Cmd_Args(cmd);
1394         else
1395         {
1396                 Con_Printf("usage: %s <string>\n",Cmd_Argv(cmd, 0));
1397                 return;
1398         }
1399
1400         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1401         if(!ispattern)
1402                 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1403
1404         count = 0;
1405         for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1406         {
1407                 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1408                     matchpattern_with_separator(cvar->description, partial, true, "", false))
1409                 {
1410                         Con_Printf ("cvar ");
1411                         Cvar_PrintHelp(cvar, cvar->name, true);
1412                         count++;
1413                 }
1414                 for (char **cvar_alias = cvar->aliases; cvar_alias && *cvar_alias; cvar_alias++)
1415                 {
1416                         if (matchpattern_with_separator(*cvar_alias, partial, true, "", false))
1417                         {
1418                                 Con_Printf ("cvar ");
1419                                 Cvar_PrintHelp(cvar, *cvar_alias, true);
1420                                 count++;
1421                         }
1422                 }
1423         }
1424         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1425         {
1426                 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1427                         if (!matchpattern_with_separator(func->description, partial, true, "", false))
1428                                 continue;
1429                 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1430                 count++;
1431         }
1432         for (func = cmd->engine_functions; func; func = func->next)
1433         {
1434                 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1435                 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1436                         continue;
1437                 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1438                 count++;
1439         }
1440         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1441         {
1442                 // procede here a bit differently as an alias value always got a final \n
1443                 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1444                 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1445                         continue;
1446                 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1447                 count++;
1448         }
1449         Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1450 }
1451
1452 static cmd_state_t *Cmd_AddInterpreter(cmd_buf_t *cbuf, cvar_state_t *cvars, unsigned cvars_flagsmask, unsigned cmds_flagsmask, cmd_userdefined_t *userdefined)
1453 {
1454         cmd_state_t *cmd = (cmd_state_t *)Mem_Alloc(tempmempool, sizeof(cmd_state_t));
1455         
1456         cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1457         // space for commands and script files
1458         cmd->cbuf = cbuf;
1459         cmd->null_string = "";
1460
1461         cmd->cvars = cvars;
1462         cmd->cvars_flagsmask = cvars_flagsmask;
1463         cmd->cmd_flagsmask = cmds_flagsmask;
1464         cmd->userdefined = userdefined;
1465
1466         return cmd;
1467 }
1468
1469 /*
1470 ============
1471 Cmd_Init
1472 ============
1473 */
1474 void Cmd_Init(void)
1475 {
1476         cmd_buf_t *cbuf;
1477         unsigned cvars_flagsmask, cmds_flagsmask;
1478
1479         cbuf_mempool = Mem_AllocPool("Command buffer", 0, NULL);
1480         cbuf = (cmd_buf_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_buf_t));
1481         cbuf->maxsize = CMDBUFSIZE;
1482         cbuf->lock = Thread_CreateMutex();
1483         cbuf->wait = false;
1484         host.cbuf = cbuf;
1485
1486         cbuf->start.prev = cbuf->start.next = &(cbuf->start);
1487         cbuf->deferred.prev = cbuf->deferred.next = &(cbuf->deferred);
1488         cbuf->free.prev = cbuf->free.next = &(cbuf->free);
1489
1490         // FIXME: Get rid of cmd_iter_all eventually. This is just a hack to reduce the amount of work to make the interpreters dynamic.
1491         cmd_iter_all = (cmd_iter_t *)Mem_Alloc(tempmempool, sizeof(cmd_iter_t) * 3);
1492
1493         // local console
1494         if (cls.state == ca_dedicated)
1495         {
1496                 cvars_flagsmask = CF_SERVER;
1497                 cmds_flagsmask = CF_SERVER | CF_SERVER_FROM_CLIENT;
1498         }
1499         else
1500         {
1501                 cvars_flagsmask = CF_CLIENT | CF_SERVER;
1502                 cmds_flagsmask = CF_CLIENT | CF_SERVER | CF_CLIENT_FROM_SERVER | CF_SERVER_FROM_CLIENT;
1503         }
1504         cmd_iter_all[0].cmd = cmd_local = Cmd_AddInterpreter(cbuf, &cvars_all, cvars_flagsmask, cmds_flagsmask, &cmd_userdefined_all);
1505         cmd_local->Handle = Cmd_CL_Callback;
1506
1507         // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1508         cmd_iter_all[1].cmd = cmd_serverfromclient = Cmd_AddInterpreter(cbuf, &cvars_null, 0, CF_SERVER_FROM_CLIENT | CF_USERINFO, &cmd_userdefined_null);
1509         cmd_serverfromclient->Handle = Cmd_SV_Callback;
1510
1511         cmd_iter_all[2].cmd = NULL;
1512 //
1513 // register our commands
1514 //
1515         // client-only commands
1516         Cmd_AddCommand(CF_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1517
1518         // maintenance commands used for upkeep of cvars and saved configs
1519         Cmd_AddCommand(CF_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1520         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");
1521         Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1522         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)");
1523         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)");
1524
1525         // general console commands used in multiple environments
1526         Cmd_AddCommand(CF_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1527         Cmd_AddCommand(CF_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1528         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");
1529         Cmd_AddCommand(CF_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1530         Cmd_AddCommand(CF_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1531         Cmd_AddCommand(CF_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1532         Cmd_AddCommand(CF_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1533
1534 #ifdef FILLALLCVARSWITHRUBBISH
1535         Cmd_AddCommand(CF_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1536 #endif /* FILLALLCVARSWITHRUBBISH */
1537
1538         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1539         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1540         Cmd_AddCommand(CF_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1541         Cmd_AddCommand(CF_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1542         Cmd_AddCommand(CF_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1543         Cmd_AddCommand(CF_SHARED, "find", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1544
1545         Cmd_AddCommand(CF_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1546
1547         // DRESK - 5/14/06
1548         // Support Doom3-style Toggle Command
1549         Cmd_AddCommand(CF_SHARED | CF_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1550 }
1551
1552 /*
1553 ============
1554 Cmd_Shutdown
1555 ============
1556 */
1557 void Cmd_Shutdown(void)
1558 {
1559         cmd_iter_t *cmd_iter;
1560         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1561         {
1562                 cmd_state_t *cmd = cmd_iter->cmd;
1563
1564                 if (cmd->cbuf->lock)
1565                 {
1566                         // we usually have this locked when we get here from Host_Quit_f
1567                         Cbuf_Unlock(cmd->cbuf);
1568                 }
1569
1570                 Mem_FreePool(&cmd->mempool);
1571         }
1572 }
1573
1574 /*
1575 ============
1576 Cmd_TokenizeString
1577
1578 Parses the given string into command line tokens.
1579 Takes a null terminated string.  Does not need to be /n terminated.
1580 ============
1581 */
1582 // AK: This function should only be called from ExecuteString because the current design is a bit of an hack
1583 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1584 {
1585         int l;
1586
1587         cmd->argc = 0;
1588         cmd->args = NULL;
1589         cmd->cmdline = NULL;
1590
1591         while (1)
1592         {
1593                 // skip whitespace up to a /n
1594                 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1595                         text++;
1596
1597                 // line endings:
1598                 // UNIX: \n
1599                 // Mac: \r
1600                 // Windows: \r\n
1601                 if (*text == '\n' || *text == '\r')
1602                 {
1603                         // a newline separates commands in the buffer
1604                         if (*text == '\r' && text[1] == '\n')
1605                                 text++;
1606                         text++;
1607                         break;
1608                 }
1609
1610                 if (!*text)
1611                         return;
1612
1613                 if(!cmd->argc)
1614                         cmd->cmdline = text;
1615                 if (cmd->argc == 1)
1616                         cmd->args = text;
1617
1618                 if (!COM_ParseToken_Console(&text))
1619                         return;
1620
1621                 if (cmd->argc < MAX_ARGS)
1622                 {
1623                         l = (int)strlen(com_token) + 1;
1624                         if (cmd->cbuf->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1625                         {
1626                                 Con_Printf(CON_WARN "Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1627                                 break;
1628                         }
1629                         memcpy (cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos, com_token, l);
1630                         cmd->argv[cmd->argc] = cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos;
1631                         cmd->cbuf->tokenizebufferpos += l;
1632                         cmd->argc++;
1633                 }
1634         }
1635 }
1636
1637
1638 /*
1639 ============
1640 Cmd_AddCommand
1641 ============
1642 */
1643 void Cmd_AddCommand(unsigned flags, const char *cmd_name, xcommand_t function, const char *description)
1644 {
1645         cmd_function_t *func;
1646         cmd_function_t *prev, *current;
1647         cmd_state_t *cmd;
1648         int i;
1649
1650         for (i = 0; i < 2; i++)
1651         {
1652                 cmd = cmd_iter_all[i].cmd;
1653                 if (flags & cmd->cmd_flagsmask)
1654                 {
1655                         // fail if the command is a variable name
1656                         if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1657                         {
1658                                 Con_Printf(CON_WARN "Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1659                                 return;
1660                         }
1661
1662                         if (function)
1663                         {
1664                                 // fail if the command already exists in this interpreter
1665                                 for (func = cmd->engine_functions; func; func = func->next)
1666                                 {
1667                                         if (!strcmp(cmd_name, func->name))
1668                                         {
1669                                                 Con_Printf(CON_WARN "Cmd_AddCommand: %s already defined\n", cmd_name);
1670                                                 continue;
1671                                         }
1672                                 }
1673
1674                                 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1675                                 func->flags = flags;
1676                                 func->name = cmd_name;
1677                                 func->function = function;
1678                                 func->description = description;
1679                                 func->next = cmd->engine_functions;
1680
1681                                 // insert it at the right alphanumeric position
1682                                 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1683                                         ;
1684                                 if (prev) {
1685                                         prev->next = func;
1686                                 }
1687                                 else {
1688                                         cmd->engine_functions = func;
1689                                 }
1690                                 func->next = current;
1691                         }
1692                         else
1693                         {
1694                                 // mark qcfunc if the function already exists in the qc_functions list
1695                                 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1696                                 {
1697                                         if (!strcmp(cmd_name, func->name))
1698                                         {
1699                                                 func->qcfunc = true; //[515]: csqc
1700                                                 continue;
1701                                         }
1702                                 }
1703
1704                                 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1705                                 func->flags = flags;
1706                                 func->name = cmd_name;
1707                                 func->function = function;
1708                                 func->description = description;
1709                                 func->qcfunc = true; //[515]: csqc
1710                                 func->next = cmd->userdefined->qc_functions;
1711
1712                                 // bones_was_here: if this QC command overrides an engine command, store its pointer
1713                                 // to avoid doing this search at invocation if QC declines to handle this command.
1714                                 for (cmd_function_t *f = cmd->engine_functions; f; f = f->next)
1715                                 {
1716                                         if (!strcmp(cmd_name, f->name))
1717                                         {
1718                                                 Con_DPrintf("Adding QC override of engine command %s\n", cmd_name);
1719                                                 func->overridden = f;
1720                                                 break;
1721                                         }
1722                                 }
1723
1724                                 // insert it at the right alphanumeric position
1725                                 for (prev = NULL, current = cmd->userdefined->qc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1726                                         ;
1727                                 if (prev) {
1728                                         prev->next = func;
1729                                 }
1730                                 else {
1731                                         cmd->userdefined->qc_functions = func;
1732                                 }
1733                                 func->next = current;
1734                         }
1735                 }
1736         }
1737 }
1738
1739 /*
1740 ============
1741 Cmd_Exists
1742 ============
1743 */
1744 qbool Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1745 {
1746         cmd_function_t  *func;
1747
1748         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1749                 if (!strcmp(cmd_name, func->name))
1750                         return true;
1751
1752         for (func=cmd->engine_functions ; func ; func=func->next)
1753                 if (!strcmp (cmd_name,func->name))
1754                         return true;
1755
1756         return false;
1757 }
1758
1759
1760 /*
1761 ============
1762 Cmd_CompleteCommand
1763 ============
1764 */
1765 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1766 {
1767         cmd_function_t *func;
1768         size_t len;
1769
1770         len = strlen(partial);
1771
1772         if (!len)
1773                 return NULL;
1774
1775 // check functions
1776         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1777                 if (!strncasecmp(partial, func->name, len))
1778                         return func->name;
1779
1780         for (func = cmd->engine_functions; func; func = func->next)
1781                 if (!strncasecmp(partial, func->name, len))
1782                         return func->name;
1783
1784         return NULL;
1785 }
1786
1787 /*
1788         Cmd_CompleteCountPossible
1789
1790         New function for tab-completion system
1791         Added by EvilTypeGuy
1792         Thanks to Fett erich@heintz.com
1793         Thanks to taniwha
1794
1795 */
1796 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1797 {
1798         cmd_function_t *func;
1799         size_t len;
1800         int h;
1801
1802         h = 0;
1803         len = strlen(partial);
1804
1805         if (!len)
1806                 return 0;
1807
1808         // Loop through the command list and count all partial matches
1809         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1810                 if (!strncasecmp(partial, func->name, len))
1811                         h++;
1812
1813         for (func = cmd->engine_functions; func; func = func->next)
1814                 if (!strncasecmp(partial, func->name, len))
1815                         h++;
1816
1817         return h;
1818 }
1819
1820 /*
1821         Cmd_CompleteBuildList
1822
1823         New function for tab-completion system
1824         Added by EvilTypeGuy
1825         Thanks to Fett erich@heintz.com
1826         Thanks to taniwha
1827
1828 */
1829 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
1830 {
1831         cmd_function_t *func;
1832         size_t len = 0;
1833         size_t bpos = 0;
1834         size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
1835         const char **buf;
1836
1837         len = strlen(partial);
1838         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1839         // Loop through the functions lists and print all matches
1840         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1841                 if (!strncasecmp(partial, func->name, len))
1842                         buf[bpos++] = func->name;
1843         for (func = cmd->engine_functions; func; func = func->next)
1844                 if (!strncasecmp(partial, func->name, len))
1845                         buf[bpos++] = func->name;
1846
1847         buf[bpos] = NULL;
1848         return buf;
1849 }
1850
1851 // written by LadyHavoc
1852 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
1853 {
1854         cmd_function_t *func;
1855         size_t len = strlen(partial);
1856         // Loop through the command list and print all matches
1857         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1858                 if (!strncasecmp(partial, func->name, len))
1859                         Con_Printf("^2%s^7: %s\n", func->name, func->description);
1860         for (func = cmd->engine_functions; func; func = func->next)
1861                 if (!strncasecmp(partial, func->name, len))
1862                         Con_Printf("^2%s^7: %s\n", func->name, func->description);
1863 }
1864
1865 /*
1866         Cmd_CompleteAlias
1867
1868         New function for tab-completion system
1869         Added by EvilTypeGuy
1870         Thanks to Fett erich@heintz.com
1871         Thanks to taniwha
1872
1873 */
1874 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
1875 {
1876         cmd_alias_t *alias;
1877         size_t len;
1878
1879         len = strlen(partial);
1880
1881         if (!len)
1882                 return NULL;
1883
1884         // Check functions
1885         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1886                 if (!strncasecmp(partial, alias->name, len))
1887                         return alias->name;
1888
1889         return NULL;
1890 }
1891
1892 // written by LadyHavoc
1893 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
1894 {
1895         cmd_alias_t *alias;
1896         size_t len = strlen(partial);
1897         // Loop through the alias list and print all matches
1898         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1899                 if (!strncasecmp(partial, alias->name, len))
1900                         Con_Printf("^5%s^7: %s", alias->name, alias->value);
1901 }
1902
1903
1904 /*
1905         Cmd_CompleteAliasCountPossible
1906
1907         New function for tab-completion system
1908         Added by EvilTypeGuy
1909         Thanks to Fett erich@heintz.com
1910         Thanks to taniwha
1911
1912 */
1913 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
1914 {
1915         cmd_alias_t     *alias;
1916         size_t          len;
1917         int                     h;
1918
1919         h = 0;
1920
1921         len = strlen(partial);
1922
1923         if (!len)
1924                 return 0;
1925
1926         // Loop through the command list and count all partial matches
1927         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1928                 if (!strncasecmp(partial, alias->name, len))
1929                         h++;
1930
1931         return h;
1932 }
1933
1934 /*
1935         Cmd_CompleteAliasBuildList
1936
1937         New function for tab-completion system
1938         Added by EvilTypeGuy
1939         Thanks to Fett erich@heintz.com
1940         Thanks to taniwha
1941
1942 */
1943 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
1944 {
1945         cmd_alias_t *alias;
1946         size_t len = 0;
1947         size_t bpos = 0;
1948         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
1949         const char **buf;
1950
1951         len = strlen(partial);
1952         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1953         // Loop through the alias list and print all matches
1954         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1955                 if (!strncasecmp(partial, alias->name, len))
1956                         buf[bpos++] = alias->name;
1957
1958         buf[bpos] = NULL;
1959         return buf;
1960 }
1961
1962 // TODO: Make this more generic?
1963 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
1964 {
1965         cmd_function_t *func;
1966         cmd_function_t **next = &cmd->userdefined->qc_functions;
1967         
1968         while(*next)
1969         {
1970                 func = *next;
1971                 *next = func->next;
1972                 Z_Free(func);
1973         }
1974 }
1975
1976 extern cvar_t sv_cheats;
1977
1978 /*
1979  * Cloudwalk FIXME: This idea sounded great in my head but...
1980  * How do we handle commands that can be received by the client,
1981  * but which the server can also execute locally?
1982  * 
1983  * If we create a callback where the engine will forward to server
1984  * but try to execute the command locally if it's dedicated,
1985  * we're back to intermixing client and server code which I'm
1986  * trying to avoid. There's no other way I can think of to
1987  * implement that behavior that doesn't involve an #ifdef, or
1988  * making a mess of hooks.
1989  */
1990 qbool Cmd_Callback(cmd_state_t *cmd, cmd_function_t *func)
1991 {
1992         if (func->function)
1993                 func->function(cmd);
1994         else
1995                 Con_Printf(CON_WARN "Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
1996         return true;
1997 }
1998
1999 qbool Cmd_CL_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, size_t textlen, cmd_source_t src)
2000 {
2001         // TODO: Assign these functions to QC commands directly?
2002         if(func->qcfunc)
2003         {
2004                 if(((func->flags & CF_CLIENT) && CL_VM_ConsoleCommand(text, textlen)) ||
2005                    ((func->flags & CF_SERVER) && SV_VM_ConsoleCommand(text, textlen)))
2006                         return true;
2007
2008                 if (func->overridden) // If this QC command overrides an engine command,
2009                         func = func->overridden; // fall back to that command.
2010         }
2011         if (func->flags & CF_SERVER_FROM_CLIENT)
2012         {
2013                 if(host_isclient.integer)
2014                 {
2015                         CL_ForwardToServer_f(cmd);
2016                         return true;
2017                 }
2018                 else if(!(func->flags & CF_SERVER))
2019                 {
2020                         Con_Printf(CON_WARN "Cannot execute client commands from a dedicated server console.\n");
2021                         return true;
2022                 }
2023         }
2024         return Cmd_Callback(cmd, func);
2025 }
2026
2027 qbool Cmd_SV_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, size_t textlen, cmd_source_t src)
2028 {
2029         if(func->qcfunc && (func->flags & CF_SERVER))
2030                 return SV_VM_ConsoleCommand(text, textlen);
2031         else if (src == src_client)
2032         {
2033                 if((func->flags & CF_CHEAT) && !sv_cheats.integer)
2034                         SV_ClientPrintf(CON_WARN "No cheats allowed. The server must have sv_cheats set to 1\n");
2035                 else
2036                         func->function(cmd);
2037                 return true;
2038         }
2039         return false;
2040 }
2041
2042 /*
2043 ============
2044 Cmd_ExecuteString
2045
2046 A complete command line has been parsed, so try to execute it
2047 FIXME: lookupnoadd the token to speed search?
2048 ============
2049 */
2050 void Cmd_ExecuteString(cmd_state_t *cmd, const char *text, size_t textlen, cmd_source_t src, qbool lockmutex)
2051 {
2052         int oldpos;
2053         cmd_function_t *func;
2054         cmd_alias_t *a;
2055
2056         if (lockmutex)
2057                 Cbuf_Lock(cmd->cbuf);
2058         oldpos = cmd->cbuf->tokenizebufferpos;
2059         cmd->source = src;
2060
2061         Cmd_TokenizeString (cmd, text);
2062
2063 // execute the command line
2064         if (!Cmd_Argc(cmd))
2065                 goto done; // no tokens
2066
2067 // check functions
2068         for (func = cmd->userdefined->qc_functions; func; func = func->next)
2069                 if (!strcasecmp(cmd->argv[0], func->name))
2070                         if(cmd->Handle(cmd, func, text, textlen, src))
2071                                 goto functions_done;
2072
2073         for (func = cmd->engine_functions; func; func=func->next)
2074                 if (!strcasecmp (cmd->argv[0], func->name))
2075                         if(cmd->Handle(cmd, func, text, textlen, src))
2076                                 goto functions_done;
2077
2078 functions_done:
2079         // If it's a client command and wasn't found and handled, say so.
2080         // Also don't let clients call server aliases.
2081         if (cmd->source == src_client)
2082         {
2083                 if (!func)
2084                         Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2085                 goto done;
2086         }
2087
2088 // check alias
2089         // Execute any alias with the same name as a command after the command.
2090         for (a=cmd->userdefined->alias ; a ; a=a->next)
2091         {
2092                 if (!strcasecmp (cmd->argv[0], a->name))
2093                 {
2094                         Cmd_ExecuteAlias(cmd, a);
2095                         goto done;
2096                 }
2097         }
2098
2099         // If the command was found and handled don't try to handle it as a cvar.
2100         if (func)
2101                 goto done;
2102
2103 // check cvars
2104         // Xonotic is still maintained so we don't want to hide problems from getting fixed
2105         if (!Cvar_Command(cmd) && (host.framecount > 0 || gamemode == GAME_XONOTIC))
2106                 Con_Printf(CON_WARN "Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2107 done:
2108         cmd->cbuf->tokenizebufferpos = oldpos;
2109         if (lockmutex)
2110                 Cbuf_Unlock(cmd->cbuf);
2111 }
2112
2113 /*
2114 ================
2115 Cmd_CheckParm
2116
2117 Returns the position (1 to argc-1) in the command's argument list
2118 where the given parameter apears, or 0 if not present
2119 ================
2120 */
2121
2122 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2123 {
2124         int i;
2125
2126         if (!parm)
2127         {
2128                 Con_Printf(CON_WARN "Cmd_CheckParm: NULL");
2129                 return 0;
2130         }
2131
2132         for (i = 1; i < Cmd_Argc (cmd); i++)
2133                 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2134                         return i;
2135
2136         return 0;
2137 }
2138
2139
2140
2141 void Cmd_SaveInitState(void)
2142 {
2143         cmd_iter_t *cmd_iter;
2144         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2145         {
2146                 cmd_state_t *cmd = cmd_iter->cmd;
2147                 cmd_function_t *f;
2148                 cmd_alias_t *a;
2149                 for (f = cmd->userdefined->qc_functions; f; f = f->next)
2150                         f->initstate = true;
2151                 for (f = cmd->engine_functions; f; f = f->next)
2152                         f->initstate = true;
2153                 for (a = cmd->userdefined->alias; a; a = a->next)
2154                 {
2155                         a->initstate = true;
2156                         a->initialvalue = Mem_strdup(zonemempool, a->value);
2157                 }
2158         }
2159         Cvar_SaveInitState(&cvars_all);
2160 }
2161
2162 void Cmd_RestoreInitState(void)
2163 {
2164         cmd_iter_t *cmd_iter;
2165         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2166         {
2167                 cmd_state_t *cmd = cmd_iter->cmd;
2168                 cmd_function_t *f, **fp;
2169                 cmd_alias_t *a, **ap;
2170                 for (fp = &cmd->userdefined->qc_functions; (f = *fp);)
2171                 {
2172                         if (f->initstate)
2173                                 fp = &f->next;
2174                         else
2175                         {
2176                                 // destroy this command, it didn't exist at init
2177                                 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2178                                 *fp = f->next;
2179                                 Z_Free(f);
2180                         }
2181                 }
2182                 for (fp = &cmd->engine_functions; (f = *fp);)
2183                 {
2184                         if (f->initstate)
2185                                 fp = &f->next;
2186                         else
2187                         {
2188                                 // destroy this command, it didn't exist at init
2189                                 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2190                                 *fp = f->next;
2191                                 Z_Free(f);
2192                         }
2193                 }
2194                 for (ap = &cmd->userdefined->alias; (a = *ap);)
2195                 {
2196                         if (a->initstate)
2197                         {
2198                                 // restore this alias, it existed at init
2199                                 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2200                                 {
2201                                         Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2202                                         if (a->value)
2203                                                 Z_Free(a->value);
2204                                         a->value = Mem_strdup(zonemempool, a->initialvalue);
2205                                 }
2206                                 ap = &a->next;
2207                         }
2208                         else
2209                         {
2210                                 // free this alias, it didn't exist at init...
2211                                 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2212                                 *ap = a->next;
2213                                 if (a->value)
2214                                         Z_Free(a->value);
2215                                 Z_Free(a);
2216                         }
2217                 }
2218         }
2219         Cvar_RestoreInitState(&cvars_all);
2220 }
2221
2222 void Cmd_NoOperation_f(cmd_state_t *cmd)
2223 {
2224 }