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