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