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