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