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