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