]> git.xonotic.org Git - xonotic/darkplaces.git/blob - cmd.c
CONTRIBUTING: Fix typos
[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                 // Nehahra pushable crates malfunction in some levels if this is on
552                 // Nehahra NPC AI is confused by blowupfallenzombies
553                 switch(gamemode)
554                 {
555                 case GAME_NORMAL:
556                         Cbuf_InsertText(cmd, "\n"
557 "sv_gameplayfix_blowupfallenzombies 0\n"
558 "sv_gameplayfix_findradiusdistancetobox 0\n"
559 "sv_gameplayfix_grenadebouncedownslopes 0\n"
560 "sv_gameplayfix_slidemoveprojectiles 0\n"
561 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
562 "sv_gameplayfix_setmodelrealbox 0\n"
563 "sv_gameplayfix_droptofloorstartsolid 0\n"
564 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
565 "sv_gameplayfix_noairborncorpse 0\n"
566 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
567 "sv_gameplayfix_easierwaterjump 0\n"
568 "sv_gameplayfix_delayprojectiles 0\n"
569 "sv_gameplayfix_multiplethinksperframe 0\n"
570 "sv_gameplayfix_fixedcheckwatertransition 0\n"
571 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
572 "sv_gameplayfix_swiminbmodels 0\n"
573 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
574 "sys_ticrate 0.01388889\n"
575 "r_shadow_gloss 1\n"
576 "r_shadow_bumpscale_basetexture 0\n"
577 "csqc_polygons_defaultmaterial_nocullface 0\n"
578                                 );
579                         break;
580                 case GAME_NEHAHRA:
581                         Cbuf_InsertText(cmd, "\n"
582 "sv_gameplayfix_blowupfallenzombies 0\n"
583 "sv_gameplayfix_findradiusdistancetobox 0\n"
584 "sv_gameplayfix_grenadebouncedownslopes 0\n"
585 "sv_gameplayfix_slidemoveprojectiles 0\n"
586 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
587 "sv_gameplayfix_setmodelrealbox 0\n"
588 "sv_gameplayfix_droptofloorstartsolid 0\n"
589 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
590 "sv_gameplayfix_noairborncorpse 0\n"
591 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
592 "sv_gameplayfix_easierwaterjump 0\n"
593 "sv_gameplayfix_delayprojectiles 0\n"
594 "sv_gameplayfix_multiplethinksperframe 0\n"
595 "sv_gameplayfix_fixedcheckwatertransition 0\n"
596 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
597 "sv_gameplayfix_swiminbmodels 0\n"
598 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
599 "sys_ticrate 0.01388889\n"
600 "r_shadow_gloss 1\n"
601 "r_shadow_bumpscale_basetexture 0\n"
602 "csqc_polygons_defaultmaterial_nocullface 0\n"
603                                 );
604                         break;
605                 // hipnotic mission pack has issues in their 'friendly monster' ai, which seem to attempt to attack themselves for some reason when findradius() returns non-solid entities.
606                 // hipnotic mission pack has issues with bobbing water entities 'jittering' between different heights on alternate frames at the default 0.0138889 ticrate, 0.02 avoids this issue
607                 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
608                 case GAME_HIPNOTIC:
609                 case GAME_QUOTH:
610                         Cbuf_InsertText(cmd, "\n"
611 "sv_gameplayfix_blowupfallenzombies 0\n"
612 "sv_gameplayfix_findradiusdistancetobox 0\n"
613 "sv_gameplayfix_grenadebouncedownslopes 0\n"
614 "sv_gameplayfix_slidemoveprojectiles 0\n"
615 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
616 "sv_gameplayfix_setmodelrealbox 0\n"
617 "sv_gameplayfix_droptofloorstartsolid 0\n"
618 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
619 "sv_gameplayfix_noairborncorpse 0\n"
620 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
621 "sv_gameplayfix_easierwaterjump 0\n"
622 "sv_gameplayfix_delayprojectiles 0\n"
623 "sv_gameplayfix_multiplethinksperframe 0\n"
624 "sv_gameplayfix_fixedcheckwatertransition 0\n"
625 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
626 "sv_gameplayfix_swiminbmodels 0\n"
627 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
628 "sys_ticrate 0.02\n"
629 "r_shadow_gloss 1\n"
630 "r_shadow_bumpscale_basetexture 0\n"
631 "csqc_polygons_defaultmaterial_nocullface 0\n"
632                                 );
633                         break;
634                 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
635                 // 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
636                 // 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.
637                 case GAME_ROGUE:
638                         Cbuf_InsertText(cmd, "\n"
639 "mod_q1bsp_traceoutofsolid 0\n"
640 "sv_gameplayfix_blowupfallenzombies 0\n"
641 "sv_gameplayfix_findradiusdistancetobox 0\n"
642 "sv_gameplayfix_grenadebouncedownslopes 0\n"
643 "sv_gameplayfix_slidemoveprojectiles 0\n"
644 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
645 "sv_gameplayfix_setmodelrealbox 0\n"
646 "sv_gameplayfix_droptofloorstartsolid 0\n"
647 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
648 "sv_gameplayfix_noairborncorpse 0\n"
649 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
650 "sv_gameplayfix_easierwaterjump 0\n"
651 "sv_gameplayfix_delayprojectiles 0\n"
652 "sv_gameplayfix_multiplethinksperframe 0\n"
653 "sv_gameplayfix_fixedcheckwatertransition 0\n"
654 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
655 "sv_gameplayfix_swiminbmodels 0\n"
656 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
657 "sys_ticrate 0.01388889\n"
658 "r_shadow_gloss 1\n"
659 "r_shadow_bumpscale_basetexture 0\n"
660 "csqc_polygons_defaultmaterial_nocullface 0\n"
661                                 );
662                         break;
663                 case GAME_TENEBRAE:
664                         Cbuf_InsertText(cmd, "\n"
665 "sv_gameplayfix_blowupfallenzombies 0\n"
666 "sv_gameplayfix_findradiusdistancetobox 0\n"
667 "sv_gameplayfix_grenadebouncedownslopes 0\n"
668 "sv_gameplayfix_slidemoveprojectiles 0\n"
669 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
670 "sv_gameplayfix_setmodelrealbox 0\n"
671 "sv_gameplayfix_droptofloorstartsolid 0\n"
672 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
673 "sv_gameplayfix_noairborncorpse 0\n"
674 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
675 "sv_gameplayfix_easierwaterjump 0\n"
676 "sv_gameplayfix_delayprojectiles 0\n"
677 "sv_gameplayfix_multiplethinksperframe 0\n"
678 "sv_gameplayfix_fixedcheckwatertransition 0\n"
679 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
680 "sv_gameplayfix_swiminbmodels 0\n"
681 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
682 "sys_ticrate 0.01388889\n"
683 "r_shadow_gloss 2\n"
684 "r_shadow_bumpscale_basetexture 4\n"
685 "csqc_polygons_defaultmaterial_nocullface 0\n"
686                                 );
687                         break;
688                 case GAME_NEXUIZ:
689                         Cbuf_InsertText(cmd, "\n"
690 "sv_gameplayfix_blowupfallenzombies 1\n"
691 "sv_gameplayfix_findradiusdistancetobox 1\n"
692 "sv_gameplayfix_grenadebouncedownslopes 1\n"
693 "sv_gameplayfix_slidemoveprojectiles 1\n"
694 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
695 "sv_gameplayfix_setmodelrealbox 1\n"
696 "sv_gameplayfix_droptofloorstartsolid 1\n"
697 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
698 "sv_gameplayfix_noairborncorpse 1\n"
699 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
700 "sv_gameplayfix_easierwaterjump 1\n"
701 "sv_gameplayfix_delayprojectiles 1\n"
702 "sv_gameplayfix_multiplethinksperframe 1\n"
703 "sv_gameplayfix_fixedcheckwatertransition 1\n"
704 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
705 "sv_gameplayfix_swiminbmodels 1\n"
706 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
707 "sys_ticrate 0.01388889\n"
708 "sv_gameplayfix_q2airaccelerate 1\n"
709 "sv_gameplayfix_stepmultipletimes 1\n"
710 "csqc_polygons_defaultmaterial_nocullface 1\n"
711 "con_chatsound_team_mask 13\n"
712                                 );
713                         break;
714                 case GAME_XONOTIC:
715                 case GAME_VORETOURNAMENT:
716                         // 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
717                         Cbuf_InsertText(cmd, "\n"
718 "csqc_polygons_defaultmaterial_nocullface 1\n"
719 "con_chatsound_team_mask 13\n"
720 "sv_qcstats 1\n"
721 "mod_q1bsp_zero_hullsize_cutoff 8.03125\n"
722                                 );
723                         break;
724                 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
725                 case GAME_STEELSTORM:
726                         Cbuf_InsertText(cmd, "\n"
727 "sv_gameplayfix_blowupfallenzombies 1\n"
728 "sv_gameplayfix_findradiusdistancetobox 1\n"
729 "sv_gameplayfix_grenadebouncedownslopes 1\n"
730 "sv_gameplayfix_slidemoveprojectiles 1\n"
731 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
732 "sv_gameplayfix_setmodelrealbox 1\n"
733 "sv_gameplayfix_droptofloorstartsolid 1\n"
734 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
735 "sv_gameplayfix_noairborncorpse 1\n"
736 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
737 "sv_gameplayfix_easierwaterjump 1\n"
738 "sv_gameplayfix_delayprojectiles 1\n"
739 "sv_gameplayfix_multiplethinksperframe 1\n"
740 "sv_gameplayfix_fixedcheckwatertransition 1\n"
741 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
742 "sv_gameplayfix_swiminbmodels 1\n"
743 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
744 "sys_ticrate 0.01388889\n"
745 "cl_csqc_generatemousemoveevents 0\n"
746 "csqc_polygons_defaultmaterial_nocullface 1\n"
747                                 );
748                         break;
749                 case GAME_QUAKE15:
750                         Cbuf_InsertText(cmd, "\n"
751 "sv_gameplayfix_impactbeforeonground 1\n"
752 "sv_gameplayfix_unstickentities 1\n"
753                         );
754                         break;
755                 default:
756                         Cbuf_InsertText(cmd, "\n"
757 "sv_gameplayfix_blowupfallenzombies 1\n"
758 "sv_gameplayfix_findradiusdistancetobox 1\n"
759 "sv_gameplayfix_grenadebouncedownslopes 1\n"
760 "sv_gameplayfix_slidemoveprojectiles 1\n"
761 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
762 "sv_gameplayfix_setmodelrealbox 1\n"
763 "sv_gameplayfix_droptofloorstartsolid 1\n"
764 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
765 "sv_gameplayfix_noairborncorpse 1\n"
766 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
767 "sv_gameplayfix_easierwaterjump 1\n"
768 "sv_gameplayfix_delayprojectiles 1\n"
769 "sv_gameplayfix_multiplethinksperframe 1\n"
770 "sv_gameplayfix_fixedcheckwatertransition 1\n"
771 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
772 "sv_gameplayfix_swiminbmodels 1\n"
773 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
774 "sys_ticrate 0.01388889\n"
775 "csqc_polygons_defaultmaterial_nocullface 0\n"
776                                 );
777                         break;
778                 }
779         }
780 }
781
782 /*
783 ===============
784 Cmd_Exec_f
785 ===============
786 */
787 static void Cmd_Exec_f (cmd_state_t *cmd)
788 {
789         fssearch_t *s;
790         int i;
791
792         if (Cmd_Argc(cmd) != 2)
793         {
794                 Con_Print("exec <filename> : execute a script file\n");
795                 return;
796         }
797
798         s = FS_Search(Cmd_Argv(cmd, 1), true, true, NULL);
799         if(!s || !s->numfilenames)
800         {
801                 Con_Printf(CON_WARN "couldn't exec %s\n",Cmd_Argv(cmd, 1));
802                 return;
803         }
804
805         for(i = 0; i < s->numfilenames; ++i)
806                 Cmd_Exec(cmd, s->filenames[i]);
807
808         FS_FreeSearch(s);
809 }
810
811
812 /*
813 ===============
814 Cmd_Echo_f
815
816 Just prints the rest of the line to the console
817 ===============
818 */
819 static void Cmd_Echo_f (cmd_state_t *cmd)
820 {
821         int             i;
822
823         for (i=1 ; i<Cmd_Argc(cmd) ; i++)
824                 Con_Printf("%s ",Cmd_Argv(cmd, i));
825         Con_Print("\n");
826 }
827
828 // DRESK - 5/14/06
829 // Support Doom3-style Toggle Console Command
830 /*
831 ===============
832 Cmd_Toggle_f
833
834 Toggles a specified console variable amongst the values specified (default is 0 and 1)
835 ===============
836 */
837 static void Cmd_Toggle_f(cmd_state_t *cmd)
838 {
839         // Acquire Number of Arguments
840         int nNumArgs = Cmd_Argc(cmd);
841
842         if(nNumArgs == 1)
843                 // No Arguments Specified; Print Usage
844                 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");
845         else
846         { // Correct Arguments Specified
847                 // Acquire Potential CVar
848                 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
849
850                 if(cvCVar != NULL)
851                 { // Valid CVar
852                         if(nNumArgs == 2)
853                         { // Default Usage
854                                 if(cvCVar->integer)
855                                         Cvar_SetValueQuick(cvCVar, 0);
856                                 else
857                                         Cvar_SetValueQuick(cvCVar, 1);
858                         }
859                         else
860                         if(nNumArgs == 3)
861                         { // 0 and Specified Usage
862                                 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
863                                         // CVar is Specified Value; // Reset to 0
864                                         Cvar_SetValueQuick(cvCVar, 0);
865                                 else
866                                 if(cvCVar->integer == 0)
867                                         // CVar is 0; Specify Value
868                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
869                                 else
870                                         // CVar does not match; Reset to 0
871                                         Cvar_SetValueQuick(cvCVar, 0);
872                         }
873                         else
874                         { // Variable Values Specified
875                                 int nCnt;
876                                 int bFound = 0;
877
878                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
879                                 { // Cycle through Values
880                                         if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
881                                         { // Current Value Located; Increment to Next
882                                                 if( (nCnt + 1) == nNumArgs)
883                                                         // Max Value Reached; Reset
884                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
885                                                 else
886                                                         // Next Value
887                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
888
889                                                 // End Loop
890                                                 nCnt = nNumArgs;
891                                                 // Assign Found
892                                                 bFound = 1;
893                                         }
894                                 }
895                                 if(!bFound)
896                                         // Value not Found; Reset to Original
897                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
898                         }
899
900                 }
901                 else
902                 { // Invalid CVar
903                         Con_Printf(CON_WARN "ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
904                 }
905         }
906 }
907
908 /*
909 ===============
910 Cmd_Alias_f
911
912 Creates a new command that executes a command string (possibly ; seperated)
913 ===============
914 */
915 static void Cmd_Alias_f (cmd_state_t *cmd)
916 {
917         cmd_alias_t     *a;
918         char            line[MAX_INPUTLINE];
919         int                     i, c;
920         const char              *s;
921         size_t          alloclen;
922
923         if (Cmd_Argc(cmd) == 1)
924         {
925                 Con_Print("Current alias commands:\n");
926                 for (a = cmd->userdefined->alias ; a ; a=a->next)
927                         Con_Printf("%s : %s", a->name, a->value);
928                 return;
929         }
930
931         s = Cmd_Argv(cmd, 1);
932         if (strlen(s) >= MAX_ALIAS_NAME)
933         {
934                 Con_Print(CON_WARN "Alias name is too long\n");
935                 return;
936         }
937
938         // if the alias already exists, reuse it
939         for (a = cmd->userdefined->alias ; a ; a=a->next)
940         {
941                 if (!strcmp(s, a->name))
942                 {
943                         Z_Free (a->value);
944                         break;
945                 }
946         }
947
948         if (!a)
949         {
950                 cmd_alias_t *prev, *current;
951
952                 a = (cmd_alias_t *)Z_Malloc (sizeof(cmd_alias_t));
953                 dp_strlcpy (a->name, s, sizeof (a->name));
954                 // insert it at the right alphanumeric position
955                 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
956                         ;
957                 if( prev ) {
958                         prev->next = a;
959                 } else {
960                         cmd->userdefined->alias = a;
961                 }
962                 a->next = current;
963         }
964
965
966 // copy the rest of the command line
967         line[0] = 0;            // start out with a null string
968         c = Cmd_Argc(cmd);
969         for (i=2 ; i < c ; i++)
970         {
971                 if (i != 2)
972                         dp_strlcat (line, " ", sizeof (line));
973                 dp_strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
974         }
975         dp_strlcat (line, "\n", sizeof (line));
976
977         alloclen = strlen (line) + 1;
978         if(alloclen >= 2)
979                 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
980         a->value = (char *)Z_Malloc (alloclen);
981         memcpy (a->value, line, alloclen);
982 }
983
984 /*
985 ===============
986 Cmd_UnAlias_f
987
988 Remove existing aliases.
989 ===============
990 */
991 static void Cmd_UnAlias_f (cmd_state_t *cmd)
992 {
993         cmd_alias_t     *a, *p;
994         int i;
995         const char *s;
996
997         if(Cmd_Argc(cmd) == 1)
998         {
999                 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1000                 return;
1001         }
1002
1003         for(i = 1; i < Cmd_Argc(cmd); ++i)
1004         {
1005                 s = Cmd_Argv(cmd, i);
1006                 p = NULL;
1007                 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
1008                 {
1009                         if(!strcmp(s, a->name))
1010                         {
1011                                 if (a->initstate) // we can not remove init aliases
1012                                         continue;
1013                                 if(a == cmd->userdefined->alias)
1014                                         cmd->userdefined->alias = a->next;
1015                                 if(p)
1016                                         p->next = a->next;
1017                                 Z_Free(a->value);
1018                                 Z_Free(a);
1019                                 break;
1020                         }
1021                 }
1022                 if(!a)
1023                         Con_Printf("unalias: %s alias not found\n", s);
1024         }
1025 }
1026
1027 /*
1028 =============================================================================
1029
1030                                         COMMAND EXECUTION
1031
1032 =============================================================================
1033 */
1034
1035 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmd_alias_t *alias, qbool *is_multiple)
1036 {
1037         cvar_t *cvar;
1038         long argno;
1039         char *endptr;
1040         static char vabuf[1024]; // cmd_mutex
1041
1042         if(is_multiple)
1043                 *is_multiple = false;
1044
1045         if(!varname || !*varname)
1046                 return NULL;
1047
1048         if(alias)
1049         {
1050                 if(!strcmp(varname, "*"))
1051                 {
1052                         if(is_multiple)
1053                                 *is_multiple = true;
1054                         return Cmd_Args(cmd);
1055                 }
1056                 else if(!strcmp(varname, "#"))
1057                 {
1058                         return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
1059                 }
1060                 else if(varname[strlen(varname) - 1] == '-')
1061                 {
1062                         argno = strtol(varname, &endptr, 10);
1063                         if(endptr == varname + strlen(varname) - 1)
1064                         {
1065                                 // whole string is a number, apart from the -
1066                                 const char *p = Cmd_Args(cmd);
1067                                 for(; argno > 1; --argno)
1068                                         if(!COM_ParseToken_Console(&p))
1069                                                 break;
1070                                 if(p)
1071                                 {
1072                                         if(is_multiple)
1073                                                 *is_multiple = true;
1074
1075                                         // kill pre-argument whitespace
1076                                         for (;*p && ISWHITESPACE(*p);p++)
1077                                                 ;
1078
1079                                         return p;
1080                                 }
1081                         }
1082                 }
1083                 else
1084                 {
1085                         argno = strtol(varname, &endptr, 10);
1086                         if(*endptr == 0)
1087                         {
1088                                 // whole string is a number
1089                                 // NOTE: we already made sure we don't have an empty cvar name!
1090                                 if(argno >= 0 && argno < Cmd_Argc(cmd))
1091                                         return Cmd_Argv(cmd, argno);
1092                         }
1093                 }
1094         }
1095
1096         if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CF_PRIVATE))
1097                 return cvar->string;
1098
1099         return NULL;
1100 }
1101
1102 qbool Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qbool putquotes)
1103 {
1104         qbool quote_quot = !!strchr(quoteset, '"');
1105         qbool quote_backslash = !!strchr(quoteset, '\\');
1106         qbool quote_dollar = !!strchr(quoteset, '$');
1107
1108         if(putquotes)
1109         {
1110                 if(outlen <= 2)
1111                 {
1112                         *out++ = 0;
1113                         return false;
1114                 }
1115                 *out++ = '"'; --outlen;
1116                 --outlen;
1117         }
1118
1119         while(*in)
1120         {
1121                 if(*in == '"' && quote_quot)
1122                 {
1123                         if(outlen <= 2)
1124                                 goto fail;
1125                         *out++ = '\\'; --outlen;
1126                         *out++ = '"'; --outlen;
1127                 }
1128                 else if(*in == '\\' && quote_backslash)
1129                 {
1130                         if(outlen <= 2)
1131                                 goto fail;
1132                         *out++ = '\\'; --outlen;
1133                         *out++ = '\\'; --outlen;
1134                 }
1135                 else if(*in == '$' && quote_dollar)
1136                 {
1137                         if(outlen <= 2)
1138                                 goto fail;
1139                         *out++ = '$'; --outlen;
1140                         *out++ = '$'; --outlen;
1141                 }
1142                 else
1143                 {
1144                         if(outlen <= 1)
1145                                 goto fail;
1146                         *out++ = *in; --outlen;
1147                 }
1148                 ++in;
1149         }
1150         if(putquotes)
1151                 *out++ = '"';
1152         *out++ = 0;
1153         return true;
1154 fail:
1155         if(putquotes)
1156                 *out++ = '"';
1157         *out++ = 0;
1158         return false;
1159 }
1160
1161 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmd_alias_t *alias)
1162 {
1163         static char varname[MAX_INPUTLINE]; // cmd_mutex
1164         static char varval[MAX_INPUTLINE]; // cmd_mutex
1165         const char *varstr = NULL;
1166         char *varfunc;
1167         qbool required = false;
1168         qbool optional = false;
1169         static char asis[] = "asis"; // just to suppress const char warnings
1170
1171         if(varlen >= MAX_INPUTLINE)
1172                 varlen = MAX_INPUTLINE - 1;
1173         memcpy(varname, var, varlen);
1174         varname[varlen] = 0;
1175         varfunc = strchr(varname, ' ');
1176
1177         if(varfunc)
1178         {
1179                 *varfunc = 0;
1180                 ++varfunc;
1181         }
1182
1183         if(*var == 0)
1184         {
1185                 // empty cvar name?
1186                 if(alias)
1187                         Con_Printf(CON_WARN "Warning: Could not expand $ in alias %s\n", alias->name);
1188                 else
1189                         Con_Printf(CON_WARN "Warning: Could not expand $\n");
1190                 return "$";
1191         }
1192
1193         if(varfunc)
1194         {
1195                 char *p;
1196                 // ? means optional
1197                 while((p = strchr(varfunc, '?')))
1198                 {
1199                         optional = true;
1200                         memmove(p, p+1, strlen(p)); // with final NUL
1201                 }
1202                 // ! means required
1203                 while((p = strchr(varfunc, '!')))
1204                 {
1205                         required = true;
1206                         memmove(p, p+1, strlen(p)); // with final NUL
1207                 }
1208                 // kill spaces
1209                 while((p = strchr(varfunc, ' ')))
1210                 {
1211                         memmove(p, p+1, strlen(p)); // with final NUL
1212                 }
1213                 // if no function is left, NULL it
1214                 if(!*varfunc)
1215                         varfunc = NULL;
1216         }
1217
1218         if(varname[0] == '$')
1219                 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1220         else
1221         {
1222                 qbool is_multiple = false;
1223                 // Exception: $* and $n- don't use the quoted form by default
1224                 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1225                 if(is_multiple)
1226                         if(!varfunc)
1227                                 varfunc = asis;
1228         }
1229
1230         if(!varstr)
1231         {
1232                 if(required)
1233                 {
1234                         if(alias)
1235                                 Con_Printf(CON_ERROR "Error: Could not expand $%s in alias %s\n", varname, alias->name);
1236                         else
1237                                 Con_Printf(CON_ERROR "Error: Could not expand $%s\n", varname);
1238                         return NULL;
1239                 }
1240                 else if(optional)
1241                 {
1242                         return "";
1243                 }
1244                 else
1245                 {
1246                         if(alias)
1247                                 Con_Printf(CON_WARN "Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1248                         else
1249                                 Con_Printf(CON_WARN "Warning: Could not expand $%s\n", varname);
1250                         dpsnprintf(varval, sizeof(varval), "$%s", varname);
1251                         return varval;
1252                 }
1253         }
1254
1255         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1256         {
1257                 // quote it so it can be used inside double quotes
1258                 // we just need to replace " by \", and of course, double backslashes
1259                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1260                 return varval;
1261         }
1262         else if(!strcmp(varfunc, "asis"))
1263         {
1264                 return varstr;
1265         }
1266         else
1267                 Con_Printf("Unknown variable function %s\n", varfunc);
1268
1269         return varstr;
1270 }
1271
1272 /**
1273 Cmd_PreprocessString
1274
1275 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1276 Returns the number of bytes written to *outtext excluding the \0 terminator.
1277 */
1278 static size_t Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias)
1279 {
1280         const char *in;
1281         size_t eat, varlen;
1282         unsigned outlen;
1283         const char *val;
1284
1285         // don't crash if there's no room in the outtext buffer
1286         if( maxoutlen == 0 ) {
1287                 return 0;
1288         }
1289         maxoutlen--; // because of \0
1290
1291         in = intext;
1292         outlen = 0;
1293
1294         while( *in && outlen < maxoutlen ) {
1295                 if( *in == '$' ) {
1296                         // this is some kind of expansion, see what comes after the $
1297                         in++;
1298
1299                         // The console does the following preprocessing:
1300                         //
1301                         // - $$ is transformed to a single dollar sign.
1302                         // - $var or ${var} are expanded to the contents of the named cvar,
1303                         //   with quotation marks and backslashes quoted so it can safely
1304                         //   be used inside quotation marks (and it should always be used
1305                         //   that way)
1306                         // - ${var asis} inserts the cvar value as is, without doing this
1307                         //   quoting
1308                         // - ${var ?} silently expands to the empty string if
1309                         //   $var does not exist
1310                         // - ${var !} fails expansion and executes nothing if
1311                         //   $var does not exist
1312                         // - prefix the cvar name with a dollar sign to do indirection;
1313                         //   for example, if $x has the value timelimit, ${$x} will return
1314                         //   the value of $timelimit
1315                         // - when expanding an alias, the special variable name $* refers
1316                         //   to all alias parameters, and a number refers to that numbered
1317                         //   alias parameter, where the name of the alias is $0, the first
1318                         //   parameter is $1 and so on; as a special case, $* inserts all
1319                         //   parameters, without extra quoting, so one can use $* to just
1320                         //   pass all parameters around. All parameters starting from $n
1321                         //   can be referred to as $n- (so $* is equivalent to $1-).
1322                         // - ${* q} and ${n- q} force quoting anyway
1323                         //
1324                         // Note: when expanding an alias, cvar expansion is done in the SAME step
1325                         // as alias expansion so that alias parameters or cvar values containing
1326                         // dollar signs have no unwanted bad side effects. However, this needs to
1327                         // be accounted for when writing complex aliases. For example,
1328                         //   alias foo "set x NEW; echo $x"
1329                         // actually expands to
1330                         //   "set x NEW; echo OLD"
1331                         // and will print OLD! To work around this, use a second alias:
1332                         //   alias foo "set x NEW; foo2"
1333                         //   alias foo2 "echo $x"
1334                         //
1335                         // Also note: lines starting with alias are exempt from cvar expansion.
1336                         // If you want cvar expansion, write "alias" instead:
1337                         //
1338                         //   set x 1
1339                         //   alias foo "echo $x"
1340                         //   "alias" bar "echo $x"
1341                         //   set x 2
1342                         //
1343                         // foo will print 2, because the variable $x will be expanded when the alias
1344                         // gets expanded. bar will print 1, because the variable $x was expanded
1345                         // at definition time. foo can be equivalently defined as
1346                         //
1347                         //   "alias" foo "echo $$x"
1348                         //
1349                         // because at definition time, $$ will get replaced to a single $.
1350
1351                         if( *in == '$' ) {
1352                                 val = "$";
1353                                 eat = 1;
1354                         } else if(*in == '{') {
1355                                 varlen = strcspn(in + 1, "}");
1356                                 if(in[varlen + 1] == '}')
1357                                 {
1358                                         val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1359                                         if(!val)
1360                                                 return 0;
1361                                         eat = varlen + 2;
1362                                 }
1363                                 else
1364                                 {
1365                                         // ran out of data?
1366                                         val = NULL;
1367                                         eat = varlen + 1;
1368                                 }
1369                         } else {
1370                                 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1371                                 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1372                                 if(!val)
1373                                         return 0;
1374                                 eat = varlen;
1375                         }
1376                         if(val)
1377                         {
1378                                 // insert the cvar value
1379                                 while(*val && outlen < maxoutlen)
1380                                         outtext[outlen++] = *val++;
1381                                 in += eat;
1382                         }
1383                         else
1384                         {
1385                                 // copy the unexpanded text
1386                                 outtext[outlen++] = '$';
1387                                 while(eat && outlen < maxoutlen)
1388                                 {
1389                                         outtext[outlen++] = *in++;
1390                                         --eat;
1391                                 }
1392                         }
1393                 }
1394                 else 
1395                         outtext[outlen++] = *in++;
1396         }
1397         outtext[outlen] = '\0';
1398         return outlen;
1399 }
1400
1401 /*
1402 ============
1403 Cmd_ExecuteAlias
1404
1405 Called for aliases and fills in the alias into the cbuffer
1406 ============
1407 */
1408 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmd_alias_t *alias)
1409 {
1410         static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1411         static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1412         qbool ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1413         if(!ret)
1414                 return;
1415         // insert at start of command buffer, so that aliases execute in order
1416         // (fixes bug introduced by Black on 20050705)
1417
1418         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1419         // have to make sure that no second variable expansion takes place, otherwise
1420         // alias parameters containing dollar signs can have bad effects.
1421         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1422         Cbuf_InsertText(cmd, buffer2);
1423 }
1424
1425 void Cmd_PreprocessAndExecuteString(cmd_state_t *cmd, const char *text, size_t textlen, cmd_source_t src, qbool lockmutex)
1426 {
1427         char preprocessed[MAX_INPUTLINE];
1428         size_t preprocessed_len;
1429         const char *firstchar;
1430
1431         firstchar = text;
1432         while(*firstchar && ISWHITESPACE(*firstchar))
1433                 ++firstchar;
1434         if((strncmp(firstchar, "alias", 5)   || !ISWHITESPACE(firstchar[5]))
1435         && (strncmp(firstchar, "bind", 4)    || !ISWHITESPACE(firstchar[4]))
1436         && (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7])))
1437         {
1438                 if((preprocessed_len = Cmd_PreprocessString(cmd, text, preprocessed, sizeof(preprocessed), NULL)))
1439                         Cmd_ExecuteString(cmd, preprocessed, preprocessed_len, src, lockmutex);
1440         }
1441         else
1442                 Cmd_ExecuteString(cmd, text, textlen, src, lockmutex);
1443 }
1444
1445 /*
1446 ========
1447 Cmd_List
1448
1449         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1450         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1451
1452 ========
1453 */
1454 static void Cmd_List_f (cmd_state_t *cmd)
1455 {
1456         cmd_function_t *func;
1457         const char *partial;
1458         size_t len;
1459         int count;
1460         qbool ispattern;
1461
1462         if (Cmd_Argc(cmd) > 1)
1463         {
1464                 partial = Cmd_Argv(cmd, 1);
1465                 len = strlen(partial);
1466                 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1467         }
1468         else
1469         {
1470                 partial = NULL;
1471                 len = 0;
1472                 ispattern = false;
1473         }
1474
1475         count = 0;
1476         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1477         {
1478                 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1479                         continue;
1480                 Con_Printf("%s : %s\n", func->name, func->description);
1481                 count++;
1482         }
1483         for (func = cmd->engine_functions; func; func = func->next)
1484         {
1485                 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1486                         continue;
1487                 Con_Printf("%s : %s\n", func->name, func->description);
1488                 count++;
1489         }
1490
1491         if (len)
1492         {
1493                 if(ispattern)
1494                         Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1495                 else
1496                         Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1497         }
1498         else
1499                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1500 }
1501
1502 static void Cmd_Apropos_f(cmd_state_t *cmd)
1503 {
1504         cmd_function_t *func;
1505         cvar_t *cvar;
1506         cmd_alias_t *alias;
1507         const char *partial;
1508         int count;
1509         qbool ispattern;
1510         char vabuf[1024];
1511
1512         if (Cmd_Argc(cmd) > 1)
1513                 partial = Cmd_Args(cmd);
1514         else
1515         {
1516                 Con_Printf("usage: %s <string>\n",Cmd_Argv(cmd, 0));
1517                 return;
1518         }
1519
1520         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1521         if(!ispattern)
1522                 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1523
1524         count = 0;
1525         for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1526         {
1527                 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1528                     matchpattern_with_separator(cvar->description, partial, true, "", false))
1529                 {
1530                         Con_Printf ("cvar ");
1531                         Cvar_PrintHelp(cvar, cvar->name, true);
1532                         count++;
1533                 }
1534                 for (char **cvar_alias = cvar->aliases; cvar_alias && *cvar_alias; cvar_alias++)
1535                 {
1536                         if (matchpattern_with_separator(*cvar_alias, partial, true, "", false))
1537                         {
1538                                 Con_Printf ("cvar ");
1539                                 Cvar_PrintHelp(cvar, *cvar_alias, true);
1540                                 count++;
1541                         }
1542                 }
1543         }
1544         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1545         {
1546                 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1547                         if (!matchpattern_with_separator(func->description, partial, true, "", false))
1548                                 continue;
1549                 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1550                 count++;
1551         }
1552         for (func = cmd->engine_functions; func; func = func->next)
1553         {
1554                 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1555                 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1556                         continue;
1557                 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1558                 count++;
1559         }
1560         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1561         {
1562                 // procede here a bit differently as an alias value always got a final \n
1563                 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1564                 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1565                         continue;
1566                 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1567                 count++;
1568         }
1569         Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1570 }
1571
1572 static cmd_state_t *Cmd_AddInterpreter(cmd_buf_t *cbuf, cvar_state_t *cvars, unsigned cvars_flagsmask, unsigned cmds_flagsmask, cmd_userdefined_t *userdefined)
1573 {
1574         cmd_state_t *cmd = (cmd_state_t *)Mem_Alloc(tempmempool, sizeof(cmd_state_t));
1575         
1576         cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1577         // space for commands and script files
1578         cmd->cbuf = cbuf;
1579         cmd->null_string = "";
1580
1581         cmd->cvars = cvars;
1582         cmd->cvars_flagsmask = cvars_flagsmask;
1583         cmd->cmd_flagsmask = cmds_flagsmask;
1584         cmd->userdefined = userdefined;
1585
1586         return cmd;
1587 }
1588
1589 /*
1590 ============
1591 Cmd_Init
1592 ============
1593 */
1594 void Cmd_Init(void)
1595 {
1596         cmd_buf_t *cbuf;
1597         unsigned cvars_flagsmask, cmds_flagsmask;
1598
1599         cbuf_mempool = Mem_AllocPool("Command buffer", 0, NULL);
1600         cbuf = (cmd_buf_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_buf_t));
1601         cbuf->maxsize = CMDBUFSIZE;
1602         cbuf->lock = Thread_CreateMutex();
1603         cbuf->wait = false;
1604         host.cbuf = cbuf;
1605
1606         cbuf->start.prev = cbuf->start.next = &(cbuf->start);
1607         cbuf->deferred.prev = cbuf->deferred.next = &(cbuf->deferred);
1608         cbuf->free.prev = cbuf->free.next = &(cbuf->free);
1609
1610         // FIXME: Get rid of cmd_iter_all eventually. This is just a hack to reduce the amount of work to make the interpreters dynamic.
1611         cmd_iter_all = (cmd_iter_t *)Mem_Alloc(tempmempool, sizeof(cmd_iter_t) * 3);
1612
1613         // local console
1614         if (cls.state == ca_dedicated)
1615         {
1616                 cvars_flagsmask = CF_SERVER;
1617                 cmds_flagsmask = CF_SERVER | CF_SERVER_FROM_CLIENT;
1618         }
1619         else
1620         {
1621                 cvars_flagsmask = CF_CLIENT | CF_SERVER;
1622                 cmds_flagsmask = CF_CLIENT | CF_SERVER | CF_CLIENT_FROM_SERVER | CF_SERVER_FROM_CLIENT;
1623         }
1624         cmd_iter_all[0].cmd = cmd_local = Cmd_AddInterpreter(cbuf, &cvars_all, cvars_flagsmask, cmds_flagsmask, &cmd_userdefined_all);
1625         cmd_local->Handle = Cmd_CL_Callback;
1626
1627         // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1628         cmd_iter_all[1].cmd = cmd_serverfromclient = Cmd_AddInterpreter(cbuf, &cvars_null, 0, CF_SERVER_FROM_CLIENT | CF_USERINFO, &cmd_userdefined_null);
1629         cmd_serverfromclient->Handle = Cmd_SV_Callback;
1630
1631         cmd_iter_all[2].cmd = NULL;
1632 //
1633 // register our commands
1634 //
1635         // client-only commands
1636         Cmd_AddCommand(CF_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1637
1638         // maintenance commands used for upkeep of cvars and saved configs
1639         Cmd_AddCommand(CF_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1640         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");
1641         Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1642         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)");
1643         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)");
1644
1645         // general console commands used in multiple environments
1646         Cmd_AddCommand(CF_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1647         Cmd_AddCommand(CF_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1648         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");
1649         Cmd_AddCommand(CF_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1650         Cmd_AddCommand(CF_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1651         Cmd_AddCommand(CF_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1652         Cmd_AddCommand(CF_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1653
1654 #ifdef FILLALLCVARSWITHRUBBISH
1655         Cmd_AddCommand(CF_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1656 #endif /* FILLALLCVARSWITHRUBBISH */
1657
1658         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1659         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1660         Cmd_AddCommand(CF_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1661         Cmd_AddCommand(CF_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1662         Cmd_AddCommand(CF_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1663         Cmd_AddCommand(CF_SHARED, "find", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1664
1665         Cmd_AddCommand(CF_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1666
1667         // DRESK - 5/14/06
1668         // Support Doom3-style Toggle Command
1669         Cmd_AddCommand(CF_SHARED | CF_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1670 }
1671
1672 /*
1673 ============
1674 Cmd_Shutdown
1675 ============
1676 */
1677 void Cmd_Shutdown(void)
1678 {
1679         cmd_iter_t *cmd_iter;
1680         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1681         {
1682                 cmd_state_t *cmd = cmd_iter->cmd;
1683
1684                 if (cmd->cbuf->lock)
1685                 {
1686                         // we usually have this locked when we get here from Host_Quit_f
1687                         Cbuf_Unlock(cmd->cbuf);
1688                 }
1689
1690                 Mem_FreePool(&cmd->mempool);
1691         }
1692 }
1693
1694 /*
1695 ============
1696 Cmd_TokenizeString
1697
1698 Parses the given string into command line tokens.
1699 Takes a null terminated string.  Does not need to be /n terminated.
1700 ============
1701 */
1702 // AK: This function should only be called from ExecuteString because the current design is a bit of an hack
1703 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1704 {
1705         int l;
1706
1707         cmd->argc = 0;
1708         cmd->args = NULL;
1709         cmd->cmdline = NULL;
1710
1711         while (1)
1712         {
1713                 // skip whitespace up to a /n
1714                 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1715                         text++;
1716
1717                 // line endings:
1718                 // UNIX: \n
1719                 // Mac: \r
1720                 // Windows: \r\n
1721                 if (*text == '\n' || *text == '\r')
1722                 {
1723                         // a newline separates commands in the buffer
1724                         if (*text == '\r' && text[1] == '\n')
1725                                 text++;
1726                         text++;
1727                         break;
1728                 }
1729
1730                 if (!*text)
1731                         return;
1732
1733                 if(!cmd->argc)
1734                         cmd->cmdline = text;
1735                 if (cmd->argc == 1)
1736                         cmd->args = text;
1737
1738                 if (!COM_ParseToken_Console(&text))
1739                         return;
1740
1741                 if (cmd->argc < MAX_ARGS)
1742                 {
1743                         l = (int)strlen(com_token) + 1;
1744                         if (cmd->cbuf->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1745                         {
1746                                 Con_Printf(CON_WARN "Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1747                                 break;
1748                         }
1749                         memcpy (cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos, com_token, l);
1750                         cmd->argv[cmd->argc] = cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos;
1751                         cmd->cbuf->tokenizebufferpos += l;
1752                         cmd->argc++;
1753                 }
1754         }
1755 }
1756
1757
1758 /*
1759 ============
1760 Cmd_AddCommand
1761 ============
1762 */
1763 void Cmd_AddCommand(unsigned flags, const char *cmd_name, xcommand_t function, const char *description)
1764 {
1765         cmd_function_t *func;
1766         cmd_function_t *prev, *current;
1767         cmd_state_t *cmd;
1768         int i;
1769
1770         for (i = 0; i < 2; i++)
1771         {
1772                 cmd = cmd_iter_all[i].cmd;
1773                 if (flags & cmd->cmd_flagsmask)
1774                 {
1775                         // fail if the command is a variable name
1776                         if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1777                         {
1778                                 Con_Printf(CON_WARN "Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1779                                 return;
1780                         }
1781
1782                         if (function)
1783                         {
1784                                 // fail if the command already exists in this interpreter
1785                                 for (func = cmd->engine_functions; func; func = func->next)
1786                                 {
1787                                         if (!strcmp(cmd_name, func->name))
1788                                         {
1789                                                 Con_Printf(CON_WARN "Cmd_AddCommand: %s already defined\n", cmd_name);
1790                                                 continue;
1791                                         }
1792                                 }
1793
1794                                 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1795                                 func->flags = flags;
1796                                 func->name = cmd_name;
1797                                 func->function = function;
1798                                 func->description = description;
1799                                 func->next = cmd->engine_functions;
1800
1801                                 // insert it at the right alphanumeric position
1802                                 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1803                                         ;
1804                                 if (prev) {
1805                                         prev->next = func;
1806                                 }
1807                                 else {
1808                                         cmd->engine_functions = func;
1809                                 }
1810                                 func->next = current;
1811                         }
1812                         else
1813                         {
1814                                 // mark qcfunc if the function already exists in the qc_functions list
1815                                 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1816                                 {
1817                                         if (!strcmp(cmd_name, func->name))
1818                                         {
1819                                                 func->qcfunc = true; //[515]: csqc
1820                                                 continue;
1821                                         }
1822                                 }
1823
1824                                 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1825                                 func->flags = flags;
1826                                 func->name = cmd_name;
1827                                 func->function = function;
1828                                 func->description = description;
1829                                 func->qcfunc = true; //[515]: csqc
1830                                 func->next = cmd->userdefined->qc_functions;
1831
1832                                 // bones_was_here: if this QC command overrides an engine command, store its pointer
1833                                 // to avoid doing this search at invocation if QC declines to handle this command.
1834                                 for (cmd_function_t *f = cmd->engine_functions; f; f = f->next)
1835                                 {
1836                                         if (!strcmp(cmd_name, f->name))
1837                                         {
1838                                                 Con_DPrintf("Adding QC override of engine command %s\n", cmd_name);
1839                                                 func->overridden = f;
1840                                                 break;
1841                                         }
1842                                 }
1843
1844                                 // insert it at the right alphanumeric position
1845                                 for (prev = NULL, current = cmd->userdefined->qc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1846                                         ;
1847                                 if (prev) {
1848                                         prev->next = func;
1849                                 }
1850                                 else {
1851                                         cmd->userdefined->qc_functions = func;
1852                                 }
1853                                 func->next = current;
1854                         }
1855                 }
1856         }
1857 }
1858
1859 /*
1860 ============
1861 Cmd_Exists
1862 ============
1863 */
1864 qbool Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1865 {
1866         cmd_function_t  *func;
1867
1868         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1869                 if (!strcmp(cmd_name, func->name))
1870                         return true;
1871
1872         for (func=cmd->engine_functions ; func ; func=func->next)
1873                 if (!strcmp (cmd_name,func->name))
1874                         return true;
1875
1876         return false;
1877 }
1878
1879
1880 /*
1881 ============
1882 Cmd_CompleteCommand
1883 ============
1884 */
1885 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1886 {
1887         cmd_function_t *func;
1888         size_t len;
1889
1890         len = strlen(partial);
1891
1892         if (!len)
1893                 return NULL;
1894
1895 // check functions
1896         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1897                 if (!strncasecmp(partial, func->name, len))
1898                         return func->name;
1899
1900         for (func = cmd->engine_functions; func; func = func->next)
1901                 if (!strncasecmp(partial, func->name, len))
1902                         return func->name;
1903
1904         return NULL;
1905 }
1906
1907 /*
1908         Cmd_CompleteCountPossible
1909
1910         New function for tab-completion system
1911         Added by EvilTypeGuy
1912         Thanks to Fett erich@heintz.com
1913         Thanks to taniwha
1914
1915 */
1916 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1917 {
1918         cmd_function_t *func;
1919         size_t len;
1920         int h;
1921
1922         h = 0;
1923         len = strlen(partial);
1924
1925         if (!len)
1926                 return 0;
1927
1928         // Loop through the command list and count all partial matches
1929         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1930                 if (!strncasecmp(partial, func->name, len))
1931                         h++;
1932
1933         for (func = cmd->engine_functions; func; func = func->next)
1934                 if (!strncasecmp(partial, func->name, len))
1935                         h++;
1936
1937         return h;
1938 }
1939
1940 /*
1941         Cmd_CompleteBuildList
1942
1943         New function for tab-completion system
1944         Added by EvilTypeGuy
1945         Thanks to Fett erich@heintz.com
1946         Thanks to taniwha
1947
1948 */
1949 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
1950 {
1951         cmd_function_t *func;
1952         size_t len = 0;
1953         size_t bpos = 0;
1954         size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
1955         const char **buf;
1956
1957         len = strlen(partial);
1958         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1959         // Loop through the functions lists and print all matches
1960         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1961                 if (!strncasecmp(partial, func->name, len))
1962                         buf[bpos++] = func->name;
1963         for (func = cmd->engine_functions; func; func = func->next)
1964                 if (!strncasecmp(partial, func->name, len))
1965                         buf[bpos++] = func->name;
1966
1967         buf[bpos] = NULL;
1968         return buf;
1969 }
1970
1971 // written by LadyHavoc
1972 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
1973 {
1974         cmd_function_t *func;
1975         size_t len = strlen(partial);
1976         // Loop through the command list and print all matches
1977         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1978                 if (!strncasecmp(partial, func->name, len))
1979                         Con_Printf("^2%s^7: %s\n", func->name, func->description);
1980         for (func = cmd->engine_functions; func; func = func->next)
1981                 if (!strncasecmp(partial, func->name, len))
1982                         Con_Printf("^2%s^7: %s\n", func->name, func->description);
1983 }
1984
1985 /*
1986         Cmd_CompleteAlias
1987
1988         New function for tab-completion system
1989         Added by EvilTypeGuy
1990         Thanks to Fett erich@heintz.com
1991         Thanks to taniwha
1992
1993 */
1994 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
1995 {
1996         cmd_alias_t *alias;
1997         size_t len;
1998
1999         len = strlen(partial);
2000
2001         if (!len)
2002                 return NULL;
2003
2004         // Check functions
2005         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2006                 if (!strncasecmp(partial, alias->name, len))
2007                         return alias->name;
2008
2009         return NULL;
2010 }
2011
2012 // written by LadyHavoc
2013 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
2014 {
2015         cmd_alias_t *alias;
2016         size_t len = strlen(partial);
2017         // Loop through the alias list and print all matches
2018         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2019                 if (!strncasecmp(partial, alias->name, len))
2020                         Con_Printf("^5%s^7: %s", alias->name, alias->value);
2021 }
2022
2023
2024 /*
2025         Cmd_CompleteAliasCountPossible
2026
2027         New function for tab-completion system
2028         Added by EvilTypeGuy
2029         Thanks to Fett erich@heintz.com
2030         Thanks to taniwha
2031
2032 */
2033 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
2034 {
2035         cmd_alias_t     *alias;
2036         size_t          len;
2037         int                     h;
2038
2039         h = 0;
2040
2041         len = strlen(partial);
2042
2043         if (!len)
2044                 return 0;
2045
2046         // Loop through the command list and count all partial matches
2047         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2048                 if (!strncasecmp(partial, alias->name, len))
2049                         h++;
2050
2051         return h;
2052 }
2053
2054 /*
2055         Cmd_CompleteAliasBuildList
2056
2057         New function for tab-completion system
2058         Added by EvilTypeGuy
2059         Thanks to Fett erich@heintz.com
2060         Thanks to taniwha
2061
2062 */
2063 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
2064 {
2065         cmd_alias_t *alias;
2066         size_t len = 0;
2067         size_t bpos = 0;
2068         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
2069         const char **buf;
2070
2071         len = strlen(partial);
2072         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2073         // Loop through the alias list and print all matches
2074         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2075                 if (!strncasecmp(partial, alias->name, len))
2076                         buf[bpos++] = alias->name;
2077
2078         buf[bpos] = NULL;
2079         return buf;
2080 }
2081
2082 // TODO: Make this more generic?
2083 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2084 {
2085         cmd_function_t *func;
2086         cmd_function_t **next = &cmd->userdefined->qc_functions;
2087         
2088         while(*next)
2089         {
2090                 func = *next;
2091                 *next = func->next;
2092                 Z_Free(func);
2093         }
2094 }
2095
2096 extern cvar_t sv_cheats;
2097
2098 /*
2099  * Cloudwalk FIXME: This idea sounded great in my head but...
2100  * How do we handle commands that can be received by the client,
2101  * but which the server can also execute locally?
2102  * 
2103  * If we create a callback where the engine will forward to server
2104  * but try to execute the command locally if it's dedicated,
2105  * we're back to intermixing client and server code which I'm
2106  * trying to avoid. There's no other way I can think of to
2107  * implement that behavior that doesn't involve an #ifdef, or
2108  * making a mess of hooks.
2109  */
2110 qbool Cmd_Callback(cmd_state_t *cmd, cmd_function_t *func)
2111 {
2112         if (func->function)
2113                 func->function(cmd);
2114         else
2115                 Con_Printf(CON_WARN "Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2116         return true;
2117 }
2118
2119 qbool Cmd_CL_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, size_t textlen, cmd_source_t src)
2120 {
2121         // TODO: Assign these functions to QC commands directly?
2122         if(func->qcfunc)
2123         {
2124                 if(((func->flags & CF_CLIENT) && CL_VM_ConsoleCommand(text, textlen)) ||
2125                    ((func->flags & CF_SERVER) && SV_VM_ConsoleCommand(text, textlen)))
2126                         return true;
2127
2128                 if (func->overridden) // If this QC command overrides an engine command,
2129                         func = func->overridden; // fall back to that command.
2130         }
2131         if (func->flags & CF_SERVER_FROM_CLIENT)
2132         {
2133                 if(host_isclient.integer)
2134                 {
2135                         CL_ForwardToServer_f(cmd);
2136                         return true;
2137                 }
2138                 else if(!(func->flags & CF_SERVER))
2139                 {
2140                         Con_Printf(CON_WARN "Cannot execute client commands from a dedicated server console.\n");
2141                         return true;
2142                 }
2143         }
2144         return Cmd_Callback(cmd, func);
2145 }
2146
2147 qbool Cmd_SV_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, size_t textlen, cmd_source_t src)
2148 {
2149         if(func->qcfunc && (func->flags & CF_SERVER))
2150                 return SV_VM_ConsoleCommand(text, textlen);
2151         else if (src == src_client)
2152         {
2153                 if((func->flags & CF_CHEAT) && !sv_cheats.integer)
2154                         SV_ClientPrintf(CON_WARN "No cheats allowed. The server must have sv_cheats set to 1\n");
2155                 else
2156                         func->function(cmd);
2157                 return true;
2158         }
2159         return false;
2160 }
2161
2162 /*
2163 ============
2164 Cmd_ExecuteString
2165
2166 A complete command line has been parsed, so try to execute it
2167 FIXME: lookupnoadd the token to speed search?
2168 ============
2169 */
2170 void Cmd_ExecuteString(cmd_state_t *cmd, const char *text, size_t textlen, cmd_source_t src, qbool lockmutex)
2171 {
2172         int oldpos;
2173         cmd_function_t *func;
2174         cmd_alias_t *a;
2175
2176         if (lockmutex)
2177                 Cbuf_Lock(cmd->cbuf);
2178         oldpos = cmd->cbuf->tokenizebufferpos;
2179         cmd->source = src;
2180
2181         Cmd_TokenizeString (cmd, text);
2182
2183 // execute the command line
2184         if (!Cmd_Argc(cmd))
2185                 goto done; // no tokens
2186
2187 // check functions
2188         for (func = cmd->userdefined->qc_functions; func; func = func->next)
2189                 if (!strcasecmp(cmd->argv[0], func->name))
2190                         if(cmd->Handle(cmd, func, text, textlen, src))
2191                                 goto functions_done;
2192
2193         for (func = cmd->engine_functions; func; func=func->next)
2194                 if (!strcasecmp (cmd->argv[0], func->name))
2195                         if(cmd->Handle(cmd, func, text, textlen, src))
2196                                 goto functions_done;
2197
2198 functions_done:
2199         // If it's a client command and wasn't found and handled, say so.
2200         // Also don't let clients call server aliases.
2201         if (cmd->source == src_client)
2202         {
2203                 if (!func)
2204                         Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2205                 goto done;
2206         }
2207
2208 // check alias
2209         // Execute any alias with the same name as a command after the command.
2210         for (a=cmd->userdefined->alias ; a ; a=a->next)
2211         {
2212                 if (!strcasecmp (cmd->argv[0], a->name))
2213                 {
2214                         Cmd_ExecuteAlias(cmd, a);
2215                         goto done;
2216                 }
2217         }
2218
2219         // If the command was found and handled don't try to handle it as a cvar.
2220         if (func)
2221                 goto done;
2222
2223 // check cvars
2224         // Xonotic is still maintained so we don't want to hide problems from getting fixed
2225         if (!Cvar_Command(cmd) && (host.framecount > 0 || gamemode == GAME_XONOTIC))
2226                 Con_Printf(CON_WARN "Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2227 done:
2228         cmd->cbuf->tokenizebufferpos = oldpos;
2229         if (lockmutex)
2230                 Cbuf_Unlock(cmd->cbuf);
2231 }
2232
2233 /*
2234 ================
2235 Cmd_CheckParm
2236
2237 Returns the position (1 to argc-1) in the command's argument list
2238 where the given parameter apears, or 0 if not present
2239 ================
2240 */
2241
2242 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2243 {
2244         int i;
2245
2246         if (!parm)
2247         {
2248                 Con_Printf(CON_WARN "Cmd_CheckParm: NULL");
2249                 return 0;
2250         }
2251
2252         for (i = 1; i < Cmd_Argc (cmd); i++)
2253                 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2254                         return i;
2255
2256         return 0;
2257 }
2258
2259
2260
2261 void Cmd_SaveInitState(void)
2262 {
2263         cmd_iter_t *cmd_iter;
2264         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2265         {
2266                 cmd_state_t *cmd = cmd_iter->cmd;
2267                 cmd_function_t *f;
2268                 cmd_alias_t *a;
2269                 for (f = cmd->userdefined->qc_functions; f; f = f->next)
2270                         f->initstate = true;
2271                 for (f = cmd->engine_functions; f; f = f->next)
2272                         f->initstate = true;
2273                 for (a = cmd->userdefined->alias; a; a = a->next)
2274                 {
2275                         a->initstate = true;
2276                         a->initialvalue = Mem_strdup(zonemempool, a->value);
2277                 }
2278         }
2279         Cvar_SaveInitState(&cvars_all);
2280 }
2281
2282 void Cmd_RestoreInitState(void)
2283 {
2284         cmd_iter_t *cmd_iter;
2285         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2286         {
2287                 cmd_state_t *cmd = cmd_iter->cmd;
2288                 cmd_function_t *f, **fp;
2289                 cmd_alias_t *a, **ap;
2290                 for (fp = &cmd->userdefined->qc_functions; (f = *fp);)
2291                 {
2292                         if (f->initstate)
2293                                 fp = &f->next;
2294                         else
2295                         {
2296                                 // destroy this command, it didn't exist at init
2297                                 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2298                                 *fp = f->next;
2299                                 Z_Free(f);
2300                         }
2301                 }
2302                 for (fp = &cmd->engine_functions; (f = *fp);)
2303                 {
2304                         if (f->initstate)
2305                                 fp = &f->next;
2306                         else
2307                         {
2308                                 // destroy this command, it didn't exist at init
2309                                 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2310                                 *fp = f->next;
2311                                 Z_Free(f);
2312                         }
2313                 }
2314                 for (ap = &cmd->userdefined->alias; (a = *ap);)
2315                 {
2316                         if (a->initstate)
2317                         {
2318                                 // restore this alias, it existed at init
2319                                 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2320                                 {
2321                                         Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2322                                         if (a->value)
2323                                                 Z_Free(a->value);
2324                                         a->value = Mem_strdup(zonemempool, a->initialvalue);
2325                                 }
2326                                 ap = &a->next;
2327                         }
2328                         else
2329                         {
2330                                 // free this alias, it didn't exist at init...
2331                                 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2332                                 *ap = a->next;
2333                                 if (a->value)
2334                                         Z_Free(a->value);
2335                                 Z_Free(a);
2336                         }
2337                 }
2338         }
2339         Cvar_RestoreInitState(&cvars_all);
2340 }
2341
2342 void Cmd_NoOperation_f(cmd_state_t *cmd)
2343 {
2344 }