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