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