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