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