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