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