command.c 56.5 KB
Newer Older
Alam Ed Arias committed
1 2 3
// SONIC ROBO BLAST 2
//-----------------------------------------------------------------------------
// Copyright (C) 1998-2000 by DooM Legacy Team.
James R. committed
4
// Copyright (C) 1999-2020 by Sonic Team Junior.
Alam Ed Arias committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
//
// This program is free software distributed under the
// terms of the GNU General Public License, version 2.
// See the 'LICENSE' file for more details.
//-----------------------------------------------------------------------------
/// \file  command.c
/// \brief Parse and execute commands from console input/scripts and remote server
///
///        Handles console variables, which is a simplified version
///        of commands, each consvar can have a function called when
///        it is modified.. thus it acts nearly as commands.
///
///        code shamelessly inspired by the QuakeC sources, thanks Id :)

#include "doomdef.h"
#include "doomstat.h"
#include "command.h"
#include "console.h"
#include "z_zone.h"
#include "m_menu.h"
#include "m_misc.h"
#include "m_fixed.h"
#include "m_argv.h"
#include "byteptr.h"
#include "p_saveg.h"
#include "g_game.h" // for player_names
#include "d_netcmd.h"
#include "hu_stuff.h"
#include "p_setup.h"
#include "lua_script.h"
35
#include "d_netfil.h" // findfile
Alam Ed Arias committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

//========
// protos.
//========
static boolean COM_Exists(const char *com_name);
static void COM_ExecuteString(char *com_text);

static void COM_Alias_f(void);
static void COM_Echo_f(void);
static void COM_CEcho_f(void);
static void COM_CEchoFlags_f(void);
static void COM_CEchoDuration_f(void);
static void COM_Exec_f(void);
static void COM_Wait_f(void);
static void COM_Help_f(void);
static void COM_Toggle_f(void);
52
static void COM_Add_f(void);
Alam Ed Arias committed
53

54
static void CV_EnforceExecVersion(void);
55
static boolean CV_FilterVarByVersion(consvar_t *v, const char *valstr);
Alam Ed Arias committed
56
static boolean CV_Command(void);
James R. committed
57
consvar_t *CV_FindVar(const char *name);
Alam Ed Arias committed
58
static const char *CV_StringValue(const char *var_name);
59

Alam Ed Arias committed
60
static consvar_t *consvar_vars; // list of registered console variables
61
static UINT16     consvar_number_of_netids = 0;
Alam Ed Arias committed
62

63 64 65
#ifdef OLD22DEMOCOMPAT
static old_demo_var_t *consvar_old_demo_vars;
#endif
Alam Ed Arias committed
66 67 68 69

static char com_token[1024];
static char *COM_Parse(char *data);

70 71
static char * COM_Purge (char *text, int *lenp);

Alam Ed Arias committed
72 73 74 75 76
CV_PossibleValue_t CV_OnOff[] = {{0, "Off"}, {1, "On"}, {0, NULL}};
CV_PossibleValue_t CV_YesNo[] = {{0, "No"}, {1, "Yes"}, {0, NULL}};
CV_PossibleValue_t CV_Unsigned[] = {{0, "MIN"}, {999999999, "MAX"}, {0, NULL}};
CV_PossibleValue_t CV_Natural[] = {{1, "MIN"}, {999999999, "MAX"}, {0, NULL}};

77
// Filter consvars by EXECVERSION
78 79
// First implementation is 26 (2.1.21), so earlier configs default at 25 (2.1.20)
// Also set CV_HIDEN during runtime, after config is loaded
80 81
static boolean execversion_enabled = false;
consvar_t cv_execversion = {"execversion","25",CV_CALL,CV_Unsigned, CV_EnforceExecVersion, 0, NULL, NULL, 0, 0, NULL};
82 83 84 85 86 87 88

// for default joyaxis detection
static boolean joyaxis_default = false;
static boolean joyaxis2_default = false;
static INT32 joyaxis_count = 0;
static INT32 joyaxis2_count = 0;

colette committed
89
#define COM_BUF_SIZE (32<<10) // command buffer size
90
#define MAX_ALIAS_RECURSION 100 // max recursion allowed for aliases
Alam Ed Arias committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

static INT32 com_wait; // one command per frame (for cmd sequences)

// command aliases
//
typedef struct cmdalias_s
{
	struct cmdalias_s *next;
	char *name;
	char *value; // the command string to replace the alias
} cmdalias_t;

static cmdalias_t *com_alias; // aliases list

// =========================================================================
//                            COMMAND BUFFER
// =========================================================================

static vsbuf_t com_text; // variable sized buffer

111 112 113 114
/** Purges control characters out of some text.
  *
  * \param s The text.
  * \param np Optionally a pointer to fill with the new string length.
e  
James R. committed
115
  * \return The text.
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  * \sa COM_ExecuteString
  */
static char *
COM_Purge (char *s, int *np)
{
	char *t;
	char *p;
	int n;
	n = strlen(s);
	t = s + n + 1;
	p = s;
	while (( p = strchr(p, '\033') ))
	{
		memmove(p, &p[1], t - p - 1);
		n--;
	}
	if (np)
		(*np) = n;
	return s;
}

Alam Ed Arias committed
137 138 139
/** Adds text into the command buffer for later execution.
  *
  * \param ptext The text to add.
140
  * \sa COM_BufInsertTextEx
Alam Ed Arias committed
141
  */
142
void COM_BufAddTextEx(const char *ptext, int flags)
Alam Ed Arias committed
143
{
144 145
	int l;
	char *text;
Alam Ed Arias committed
146

147
	text = COM_Purge(Z_StrDup(ptext), &l);
Alam Ed Arias committed
148

149
	if (com_text.cursize + 2 + l >= com_text.maxsize)
Alam Ed Arias committed
150 151 152 153
	{
		CONS_Alert(CONS_WARNING, M_GetText("Command buffer full!\n"));
		return;
	}
154 155 156 157

	VS_WriteEx(&com_text, text, l, flags);

	Z_Free(text);
Alam Ed Arias committed
158 159 160 161 162
}

/** Adds command text and executes it immediately.
  *
  * \param ptext The text to execute. A newline is automatically added.
163
  * \sa COM_BufAddTextEx
Alam Ed Arias committed
164
  */
165
void COM_BufInsertTextEx(const char *ptext, int flags)
Alam Ed Arias committed
166 167 168 169 170 171 172 173 174 175 176 177 178
{
	char *temp = NULL;
	size_t templen;

	// copy off any commands still remaining in the exec buffer
	templen = com_text.cursize;
	if (templen)
	{
		temp = M_Memcpy(ZZ_Alloc(templen), com_text.data, templen);
		VS_Clear(&com_text);
	}

	// add the entire text of the file (or alias)
179
	COM_BufAddTextEx(ptext, flags);
Alam Ed Arias committed
180 181 182 183 184 185 186 187 188 189
	COM_BufExecute(); // do it right away

	// add the copied off data
	if (templen)
	{
		VS_Write(&com_text, temp, templen);
		Z_Free(temp);
	}
}

190 191 192 193 194 195 196 197 198 199 200 201 202 203
/** Progress the wait timer and flush waiting console commands when ready.
  */
void
COM_BufTicker(void)
{
	if (com_wait)
	{
		com_wait--;
		return;
	}

	COM_BufExecute();
}

Alam Ed Arias committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
/** Flushes (executes) console commands in the buffer.
  */
void COM_BufExecute(void)
{
	size_t i;
	char *ptext;
	char line[1024] = "";
	INT32 quotes;

	while (com_text.cursize)
	{
		// find a '\n' or; line break
		ptext = (char *)com_text.data;

		quotes = 0;
		for (i = 0; i < com_text.cursize; i++)
		{
			if (ptext[i] == '\"' && !quotes && i > 0 && ptext[i-1] != ' ') // Malformed command
				break;
			if (ptext[i] == '\"')
				quotes++;
			if (!(quotes & 1) && ptext[i] == ';')
				break; // don't break if inside a quoted string
			if (ptext[i] == '\n' || ptext[i] == '\r')
				break;
		}

		M_Memcpy(line, ptext, i);
		line[i] = 0;

		// flush the command text from the command buffer, _BEFORE_
		// executing, to avoid that 'recursive' aliases overflow the
		// command text buffer, in that case, new commands are inserted
		// at the beginning, in place of the actual, so it doesn't
		// overflow
		if (i == com_text.cursize)
			// the last command was just flushed
			com_text.cursize = 0;
		else
		{
			i++;
			com_text.cursize -= i;
			//memcpy(ptext, ptext+i, com_text.cursize); // Use memmove if the memory areas do overlap.
			memmove(ptext, ptext+i, com_text.cursize);
		}

		// execute the command line
		COM_ExecuteString(line);

		// delay following commands if a wait was encountered
		if (com_wait)
		{
			com_wait--;
			break;
		}
	}
}

/** Executes a string immediately.  Used for skirting around WAIT commands.
  */
void COM_ImmedExecute(const char *ptext)
{
	size_t i = 0, j = 0;
	char line[1024] = "";
	INT32 quotes;

	while (i < strlen(ptext))
	{

		quotes = 0;
		for (j = 0; i < strlen(ptext); i++,j++)
		{
			if (ptext[i] == '\"' && !quotes && i > 0 && ptext[i-1] != ' ') // Malformed command
				return;
			if (ptext[i] == '\"')
				quotes++;
			// don't break if inside a quoted string
			if ((!(quotes & 1) && ptext[i] == ';') || ptext[i] == '\n' || ptext[i] == '\r')
				break;
		}

		memcpy(line, ptext+(i-j), j);
		line[j] = 0;

		// execute the command line
		COM_ExecuteString(line);

		i++; // move to next character
	}
}

// =========================================================================
//                            COMMAND EXECUTION
// =========================================================================

typedef struct xcommand_s
{
	const char *name;
	struct xcommand_s *next;
	com_func_t function;
} xcommand_t;

static xcommand_t *com_commands = NULL; // current commands

#define MAX_ARGS 80
static size_t com_argc;
static char *com_argv[MAX_ARGS];
static const char *com_null_string = "";
static char *com_args = NULL; // current command args or NULL
313
static int com_flags;
Alam Ed Arias committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

static void Got_NetVar(UINT8 **p, INT32 playernum);

/** Initializes command buffer and adds basic commands.
  */
void COM_Init(void)
{
	// allocate command buffer
	VS_Alloc(&com_text, COM_BUF_SIZE);

	// add standard commands
	COM_AddCommand("alias", COM_Alias_f);
	COM_AddCommand("echo", COM_Echo_f);
	COM_AddCommand("cecho", COM_CEcho_f);
	COM_AddCommand("cechoflags", COM_CEchoFlags_f);
	COM_AddCommand("cechoduration", COM_CEchoDuration_f);
	COM_AddCommand("exec", COM_Exec_f);
	COM_AddCommand("wait", COM_Wait_f);
	COM_AddCommand("help", COM_Help_f);
	COM_AddCommand("toggle", COM_Toggle_f);
334
	COM_AddCommand("add", COM_Add_f);
Alam Ed Arias committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
	RegisterNetXCmd(XD_NETVAR, Got_NetVar);
}

/** Gets a console command argument count.
  *
  * \return Number of arguments for the last command.
  * \sa COM_Argv
  */
size_t COM_Argc(void)
{
	return com_argc;
}

/** Gets a console command argument.
  *
  * \param arg Index of the argument (0 to COM_Argc() - 1).
  * \return String pointer to the indicated argument.
  * \sa COM_Argc, COM_Args
  */
const char *COM_Argv(size_t arg)
{
	if (arg >= com_argc || (signed)arg < 0)
		return com_null_string;
	return com_argv[arg];
}

/** Gets all console command arguments.
  *
  * \return String pointer to all arguments for the last command.
  * \sa COM_Argv
  */
char *COM_Args(void)
{
	return com_args;
}

/** Checks if a parameter was passed to a console command.
  *
  * \param check The parameter to look for, e.g. "-noerror".
  * \return The index of the argument containing the parameter,
  *         or 0 if the parameter was not found.
  */
size_t COM_CheckParm(const char *check)
{
	size_t i;

	for (i = 1; i < com_argc; i++)
		if (!strcasecmp(check, com_argv[i]))
			return i;
	return 0;
}

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
/** \brief COM_CheckParm, but checks only the start of each argument.
  *        E.g. checking for "-no" would match "-noerror" too.
  */
size_t COM_CheckPartialParm(const char *check)
{
	int  len;
	size_t i;

	len = strlen(check);

	for (i = 1; i < com_argc; i++)
	{
		if (strncasecmp(check, com_argv[i], len) == 0)
			return i;
	}
	return 0;
}

/** Find the first argument that starts with a hyphen (-).
  * \return The index of the argument, or 0
  *         if there are no such arguments.
  */
size_t COM_FirstOption(void)
{
	size_t i;

	for (i = 1; i < com_argc; i++)
	{
		if (com_argv[i][0] == '-')/* options start with a hyphen */
			return i;
	}
	return 0;
}

Alam Ed Arias committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
/** Parses a string into command-line tokens.
  *
  * \param ptext A null-terminated string. Does not need to be
  *             newline-terminated.
  */
static void COM_TokenizeString(char *ptext)
{
	size_t i;

	// Clear the args from the last string.
	for (i = 0; i < com_argc; i++)
		Z_Free(com_argv[i]);

	com_argc = 0;
	com_args = NULL;
436
	com_flags = 0;
Alam Ed Arias committed
437 438 439 440 441

	while (com_argc < MAX_ARGS)
	{
		// Skip whitespace up to a newline.
		while (*ptext != '\0' && *ptext <= ' ' && *ptext != '\n')
442 443 444 445 446 447 448 449 450
		{
			if (ptext[0] == '\033')
			{
				com_flags = (unsigned)ptext[1];
				ptext += 2;
			}
			else
				ptext++;
		}
Alam Ed Arias committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

		// A newline means end of command in buffer,
		// thus end of this command's args too.
		if (*ptext == '\n' || *ptext == '\0')
			break;

		if (com_argc == 1)
			com_args = ptext;

		ptext = COM_Parse(ptext);
		if (ptext == NULL)
			break;

		com_argv[com_argc] = Z_StrDup(com_token);
		com_argc++;
	}
}

/** Adds a console command.
  *
  * \param name Name of the command.
  * \param func Function called when the command is run.
  */
void COM_AddCommand(const char *name, com_func_t func)
{
	xcommand_t *cmd;

	// fail if the command is a variable name
	if (CV_StringValue(name)[0] != '\0')
	{
		I_Error("%s is a variable name\n", name);
		return;
	}

	// fail if the command already exists
	for (cmd = com_commands; cmd; cmd = cmd->next)
	{
		if (!stricmp(name, cmd->name)) //case insensitive now that we have lower and uppercase!
		{
Alam Ed Arias committed
490 491 492 493 494 495 496
			// don't I_Error for Lua commands
			// Lua commands can replace game commands, and they have priority.
			// BUT, if for some reason we screwed up and made two console commands with the same name,
			// it's good to have this here so we find out.
			if (cmd->function != COM_Lua_f)
				I_Error("Command %s already exists\n", name);

Alam Ed Arias committed
497 498 499 500 501 502 503 504 505 506 507
			return;
		}
	}

	cmd = ZZ_Alloc(sizeof *cmd);
	cmd->name = name;
	cmd->function = func;
	cmd->next = com_commands;
	com_commands = cmd;
}

Alam Ed Arias committed
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
/** Adds a console command for Lua.
  * No I_Errors allowed; return a negative code instead.
  *
  * \param name Name of the command.
  */
int COM_AddLuaCommand(const char *name)
{
	xcommand_t *cmd;

	// fail if the command is a variable name
	if (CV_StringValue(name)[0] != '\0')
		return -1;

	// command already exists
	for (cmd = com_commands; cmd; cmd = cmd->next)
	{
		if (!stricmp(name, cmd->name)) //case insensitive now that we have lower and uppercase!
		{
			// replace the built in command.
			cmd->function = COM_Lua_f;
			return 1;
		}
	}

	// Add a new command.
	cmd = ZZ_Alloc(sizeof *cmd);
	cmd->name = name;
	cmd->function = COM_Lua_f;
	cmd->next = com_commands;
	com_commands = cmd;
	return 0;
}

Alam Ed Arias committed
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
/** Tests if a command exists.
  *
  * \param com_name Name to test for.
  * \return True if a command by the given name exists.
  */
static boolean COM_Exists(const char *com_name)
{
	xcommand_t *cmd;

	for (cmd = com_commands; cmd; cmd = cmd->next)
		if (!stricmp(com_name, cmd->name))
			return true;

	return false;
}

/** Does command completion for the console.
  *
  * \param partial The partial name of the command (potentially).
  * \param skips   Number of commands to skip.
  * \return The complete command name, or NULL.
  * \sa CV_CompleteVar
  */
const char *COM_CompleteCommand(const char *partial, INT32 skips)
{
	xcommand_t *cmd;
	size_t len;

	len = strlen(partial);

	if (!len)
		return NULL;

	// check functions
	for (cmd = com_commands; cmd; cmd = cmd->next)
		if (!strncmp(partial, cmd->name, len))
			if (!skips--)
				return cmd->name;

	return NULL;
}

/** Parses a single line of text into arguments and tries to execute it.
  * The text can come from the command buffer, a remote client, or stdin.
  *
  * \param ptext A single line of text.
  */
static void COM_ExecuteString(char *ptext)
{
	xcommand_t *cmd;
	cmdalias_t *a;
592
	static INT32 recursion = 0; // detects recursion and stops it if it goes too far
Alam Ed Arias committed
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614

	COM_TokenizeString(ptext);

	// execute the command line
	if (COM_Argc() == 0)
		return; // no tokens

	// check functions
	for (cmd = com_commands; cmd; cmd = cmd->next)
	{
		if (!stricmp(com_argv[0], cmd->name)) //case insensitive now that we have lower and uppercase!
		{
			cmd->function();
			return;
		}
	}

	// check aliases
	for (a = com_alias; a; a = a->next)
	{
		if (!stricmp(com_argv[0], a->name))
		{
615 616
			if (recursion > MAX_ALIAS_RECURSION)
				CONS_Alert(CONS_WARNING, M_GetText("Alias recursion cycle detected!\n"));
617 618 619 620 621
			else
			{ // Monster Iestyn: keep track of how many levels of recursion we're in
				recursion++;
				COM_BufInsertText(a->value);
				recursion--;
622
			}
Alam Ed Arias committed
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
			return;
		}
	}

	// check cvars
	// Hurdler: added at Ebola's request ;)
	// (don't flood the console in software mode with bad gr_xxx command)
	if (!CV_Command() && con_destlines)
		CONS_Printf(M_GetText("Unknown command '%s'\n"), COM_Argv(0));
}

// =========================================================================
//                            SCRIPT COMMANDS
// =========================================================================

/** Creates a command name that replaces another command.
  */
static void COM_Alias_f(void)
{
	cmdalias_t *a;
	char cmd[1024];
	size_t i, c;

	if (COM_Argc() < 3)
	{
		CONS_Printf(M_GetText("alias <name> <command>: create a shortcut command that executes other command(s)\n"));
		return;
	}

	a = ZZ_Alloc(sizeof *a);
	a->next = com_alias;
	com_alias = a;

	a->name = Z_StrDup(COM_Argv(1));

	// copy the rest of the command line
	cmd[0] = 0; // start out with a null string
	c = COM_Argc();
	for (i = 2; i < c; i++)
	{
		strcat(cmd, COM_Argv(i));
		if (i != c)
			strcat(cmd, " ");
	}
	strcat(cmd, "\n");

	a->value = Z_StrDup(cmd);
}

/** Prints a line of text to the console.
  */
static void COM_Echo_f(void)
{
	size_t i;

	for (i = 1; i < COM_Argc(); i++)
		CONS_Printf("%s ", COM_Argv(i));
	CONS_Printf("\n");
}

/** Displays text on the center of the screen for a short time.
  */
static void COM_CEcho_f(void)
{
	size_t i;
	char cechotext[1024] = "";

	for (i = 1; i < COM_Argc(); i++)
	{
		strncat(cechotext, COM_Argv(i), sizeof(cechotext)-1);
		strncat(cechotext, " ", sizeof(cechotext)-1);
	}

	cechotext[sizeof(cechotext) - 1] = '\0';

	HU_DoCEcho(cechotext);
}

/** Sets drawing flags for the CECHO command.
  */
static void COM_CEchoFlags_f(void)
{
	if (COM_Argc() > 1)
	{
		const char *arg = COM_Argv(1);

		if (arg[0] && arg[0] == '0' &&
			arg[1] && arg[1] == 'x') // Use hexadecimal!
			HU_SetCEchoFlags(axtoi(arg+2));
		else
			HU_SetCEchoFlags(atoi(arg));
	}
	else
Alam Ed Arias committed
716
		CONS_Printf(M_GetText("cechoflags <flags>: set CEcho flags, prepend with 0x to use hexadecimal\n"));
Alam Ed Arias committed
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
}

/** Sets the duration for CECHO commands to stay on the screen
  */
static void COM_CEchoDuration_f(void)
{
	if (COM_Argc() > 1)
		HU_SetCEchoDuration(atoi(COM_Argv(1)));
}

/** Executes a script file.
  */
static void COM_Exec_f(void)
{
	UINT8 *buf = NULL;
732
	char filename[256];
Alam Ed Arias committed
733 734 735 736 737 738 739 740

	if (COM_Argc() < 2 || COM_Argc() > 3)
	{
		CONS_Printf(M_GetText("exec <filename>: run a script file\n"));
		return;
	}

	// load file
741
	// Try with Argv passed verbatim first, for back compat
Alam Ed Arias committed
742 743 744 745
	FIL_ReadFile(COM_Argv(1), &buf);

	if (!buf)
	{
746 747 748 749 750 751 752 753 754 755 756 757
		// Now try by searching the file path
		// filename is modified with the full found path
		strcpy(filename, COM_Argv(1));
		if (findfile(filename, NULL, true) != FS_NOTFOUND)
			FIL_ReadFile(filename, &buf);

		if (!buf)
		{
			if (!COM_CheckParm("-noerror"))
				CONS_Printf(M_GetText("couldn't execute file %s\n"), COM_Argv(1));
			return;
		}
Alam Ed Arias committed
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
	}

	if (!COM_CheckParm("-silent"))
		CONS_Printf(M_GetText("executing %s\n"), COM_Argv(1));

	// insert text file into the command buffer
	COM_BufAddText((char *)buf);
	COM_BufAddText("\n");

	// free buffer
	Z_Free(buf);
}

/** Delays execution of the rest of the commands until the next frame.
  * Allows sequences of commands like "jump; fire; backward".
  */
static void COM_Wait_f(void)
{
	if (COM_Argc() > 1)
		com_wait = atoi(COM_Argv(1));
	else
		com_wait = 1; // 1 frame
}

/** Prints help on variables and commands.
  */
static void COM_Help_f(void)
{
	xcommand_t *cmd;
	consvar_t *cvar;
	INT32 i = 0;

	if (COM_Argc() > 1)
	{
toaster committed
792 793
		const char *help = COM_Argv(1);
		cvar = CV_FindVar(help);
Alam Ed Arias committed
794 795
		if (cvar)
		{
toaster committed
796 797 798
			boolean floatmode = false;
			const char *cvalue = NULL;
			CONS_Printf("\x82""Variable %s:\n", cvar->name);
Alam Ed Arias committed
799 800 801 802
			CONS_Printf(M_GetText("  flags :"));
			if (cvar->flags & CV_SAVE)
				CONS_Printf("AUTOSAVE ");
			if (cvar->flags & CV_FLOAT)
toaster committed
803
			{
Alam Ed Arias committed
804
				CONS_Printf("FLOAT ");
toaster committed
805 806
				floatmode = true;
			}
Alam Ed Arias committed
807 808 809 810 811 812 813 814 815
			if (cvar->flags & CV_NETVAR)
				CONS_Printf("NETVAR ");
			if (cvar->flags & CV_CALL)
				CONS_Printf("ACTION ");
			if (cvar->flags & CV_CHEAT)
				CONS_Printf("CHEAT ");
			CONS_Printf("\n");
			if (cvar->PossibleValue)
			{
toaster committed
816 817 818 819 820
				CONS_Printf(" Possible values:\n");
				if (cvar->PossibleValue == CV_YesNo)
					CONS_Printf("  Yes or No (On or Off, 1 or 0)\n");
				else if (cvar->PossibleValue == CV_OnOff)
					CONS_Printf("  On or Off (Yes or No, 1 or 0)\n");
Alam Ed Arias committed
821 822
				else
				{
823 824 825
#define MINVAL 0
#define MAXVAL 1
					if (!stricmp(cvar->PossibleValue[MINVAL].strvalue, "MIN"))
toaster committed
826 827
					{
						if (floatmode)
828 829 830 831 832 833 834
						{
							float fu = FIXED_TO_FLOAT(cvar->PossibleValue[MINVAL].value);
							float ck = FIXED_TO_FLOAT(cvar->PossibleValue[MAXVAL].value);
							CONS_Printf("  range from %ld%s to %ld%s\n",
									(long)fu, M_Ftrim(fu),
									(long)ck, M_Ftrim(ck));
						}
toaster committed
835
						else
836 837 838
							CONS_Printf("  range from %d to %d\n", cvar->PossibleValue[MINVAL].value,
								cvar->PossibleValue[MAXVAL].value);
						i = MAXVAL+1;
toaster committed
839
					}
840 841
#undef MINVAL
#undef MAXVAL
toaster committed
842 843

					//CONS_Printf(M_GetText("  possible value : %s\n"), cvar->name);
Alam Ed Arias committed
844 845
					while (cvar->PossibleValue[i].strvalue)
					{
toaster committed
846 847 848 849 850 851
						if (floatmode)
							CONS_Printf("  %-2f : %s\n", FIXED_TO_FLOAT(cvar->PossibleValue[i].value),
								cvar->PossibleValue[i].strvalue);
						else
							CONS_Printf("  %-2d : %s\n", cvar->PossibleValue[i].value,
								cvar->PossibleValue[i].strvalue);
Alam Ed Arias committed
852 853 854 855 856 857
						if (cvar->PossibleValue[i].value == cvar->value)
							cvalue = cvar->PossibleValue[i].strvalue;
						i++;
					}
				}
			}
toaster committed
858 859 860 861 862

			if (cvalue)
				CONS_Printf(" Current value: %s\n", cvalue);
			else if (cvar->string)
				CONS_Printf(" Current value: %s\n", cvar->string);
Alam Ed Arias committed
863
			else
toaster committed
864
				CONS_Printf(" Current value: %d\n", cvar->value);
Alam Ed Arias committed
865 866
		}
		else
toaster committed
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
		{
			for (cmd = com_commands; cmd; cmd = cmd->next)
			{
				if (strcmp(cmd->name, help))
					continue;

				CONS_Printf("\x82""Command %s:\n", cmd->name);
				CONS_Printf("  help is not available for commands");
				CONS_Printf("\x82""\nCheck wiki.srb2.org for more or try typing <name> without arguments\n");
				return;
			}

			CONS_Printf("No exact match, searching...\n");

			// variables
			CONS_Printf("\x82""Variables:\n");
			for (cvar = consvar_vars; cvar; cvar = cvar->next)
			{
				if ((cvar->flags & CV_NOSHOWHELP) || (!strstr(cvar->name, help)))
					continue;
				CONS_Printf("%s ", cvar->name);
				i++;
			}

			// commands
			CONS_Printf("\x82""\nCommands:\n");
			for (cmd = com_commands; cmd; cmd = cmd->next)
			{
				if (!strstr(cmd->name, help))
					continue;
				CONS_Printf("%s ",cmd->name);
				i++;
			}

			CONS_Printf("\x82""\nCheck wiki.srb2.org for more or type help <command or variable>\n");

			CONS_Debug(DBG_GAMELOGIC, "\x87Total : %d\n", i);
		}
		return;
Alam Ed Arias committed
906 907 908
	}
	else
	{
toaster committed
909 910 911
		// variables
		CONS_Printf("\x82""Variables:\n");
		for (cvar = consvar_vars; cvar; cvar = cvar->next)
Alam Ed Arias committed
912
		{
toaster committed
913 914 915
			if (cvar->flags & CV_NOSHOWHELP)
				continue;
			CONS_Printf("%s ", cvar->name);
Alam Ed Arias committed
916 917 918
			i++;
		}

toaster committed
919 920 921
		// commands
		CONS_Printf("\x82""\nCommands:\n");
		for (cmd = com_commands; cmd; cmd = cmd->next)
Alam Ed Arias committed
922
		{
toaster committed
923
			CONS_Printf("%s ",cmd->name);
Alam Ed Arias committed
924 925 926
			i++;
		}

toaster committed
927
		CONS_Printf("\x82""\nCheck wiki.srb2.org for more or type help <command or variable>\n");
Alam Ed Arias committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963

		CONS_Debug(DBG_GAMELOGIC, "\x82Total : %d\n", i);
	}
}

/** Toggles a console variable. Useful for on/off values.
  *
  * This works on on/off, yes/no values only
  */
static void COM_Toggle_f(void)
{
	consvar_t *cvar;

	if (COM_Argc() != 2)
	{
		CONS_Printf(M_GetText("Toggle <cvar_name>: Toggle the value of a cvar\n"));
		return;
	}
	cvar = CV_FindVar(COM_Argv(1));
	if (!cvar)
	{
		CONS_Alert(CONS_NOTICE, M_GetText("%s is not a cvar\n"), COM_Argv(1));
		return;
	}

	if (!(cvar->PossibleValue == CV_YesNo || cvar->PossibleValue == CV_OnOff))
	{
		CONS_Alert(CONS_NOTICE, M_GetText("%s is not a boolean value\n"), COM_Argv(1));
		return;
	}

	// netcvar don't change imediately
	cvar->flags |= CV_SHOWMODIFONETIME;
	CV_AddValue(cvar, +1);
}

964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
/** Command variant of CV_AddValue
  */
static void COM_Add_f(void)
{
	consvar_t *cvar;

	if (COM_Argc() != 3)
	{
		CONS_Printf(M_GetText("Add <cvar_name> <value>: Add to the value of a cvar. Negative values work too!\n"));
		return;
	}
	cvar = CV_FindVar(COM_Argv(1));
	if (!cvar)
	{
		CONS_Alert(CONS_NOTICE, M_GetText("%s is not a cvar\n"), COM_Argv(1));
		return;
	}

982
	if (( cvar->flags & CV_FLOAT ))
983 984 985 986
	{
		float n =FIXED_TO_FLOAT (cvar->value) + atof(COM_Argv(2));
		CV_Set(cvar, va("%ld%s", (long)n, M_Ftrim(n)));
	}
987 988
	else
		CV_AddValue(cvar, atoi(COM_Argv(2)));
989 990
}

Alam Ed Arias committed
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
// =========================================================================
//                      VARIABLE SIZE BUFFERS
// =========================================================================

/** Initializes a variable size buffer.
  *
  * \param buf      Buffer to initialize.
  * \param initsize Initial size for the buffer.
  */
void VS_Alloc(vsbuf_t *buf, size_t initsize)
{
#define VSBUFMINSIZE 256
	if (initsize < VSBUFMINSIZE)
		initsize = VSBUFMINSIZE;
	buf->data = Z_Malloc(initsize, PU_STATIC, NULL);
	buf->maxsize = initsize;
	buf->cursize = 0;
#undef VSBUFMINSIZE
}

/** Frees a variable size buffer.
  *
  * \param buf Buffer to free.
  */
void VS_Free(vsbuf_t *buf)
{
	buf->cursize = 0;
}

/** Clears a variable size buffer.
  *
  * \param buf Buffer to clear.
  */
void VS_Clear(vsbuf_t *buf)
{
	buf->cursize = 0;
}

/** Makes sure a variable size buffer has enough space for data of a
  * certain length.
  *
  * \param buf    The buffer. It is enlarged if necessary.
  * \param length The length of data we need to add.
  * \return Pointer to where the new data can go.
  */
void *VS_GetSpace(vsbuf_t *buf, size_t length)
{
	void *data;

	if (buf->cursize + length > buf->maxsize)
	{
		if (!buf->allowoverflow)
			I_Error("overflow 111");

		if (length > buf->maxsize)
			I_Error("overflow l%s 112", sizeu1(length));

		buf->overflowed = true;
		CONS_Printf("VS buffer overflow");
		VS_Clear(buf);
	}

	data = buf->data + buf->cursize;
	buf->cursize += length;

	return data;
}

/** Copies data to the end of a variable size buffer.
  *
  * \param buf    The buffer.
  * \param data   The data to copy.
  * \param length The length of the data.
  * \sa VS_Print
  */
void VS_Write(vsbuf_t *buf, const void *data, size_t length)
{
	M_Memcpy(VS_GetSpace(buf, length), data, length);
}

1071 1072 1073 1074 1075 1076 1077 1078 1079
void VS_WriteEx(vsbuf_t *buf, const void *data, size_t length, int flags)
{
	char *p;
	p = VS_GetSpace(buf, 2 + length);
	p[0] = '\033';
	p[1] = flags;
	M_Memcpy(&p[2], data, length);
}

Alam Ed Arias committed
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
/** Prints text in a variable buffer. Like VS_Write() plus a
  * trailing NUL.
  *
  * \param buf  The buffer.
  * \param data The NUL-terminated string.
  * \sa VS_Write
  */
void VS_Print(vsbuf_t *buf, const char *data)
{
	size_t len;

	len = strlen(data) + 1;

	if (buf->data[buf->cursize-1])
		M_Memcpy((UINT8 *)VS_GetSpace(buf, len), data, len); // no trailing 0
	else
		M_Memcpy((UINT8 *)VS_GetSpace(buf, len-1) - 1, data, len); // write over trailing 0
}

// =========================================================================
//
//                           CONSOLE VARIABLES
//
//   console variables are a simple way of changing variables of the game
//   through the console or code, at run time.
//
//   console vars acts like simplified commands, because a function can be
//   attached to them, and called whenever a console var is modified
//
// =========================================================================

static const char *cv_null_string = "";

/** Searches if a variable has been registered.
  *
  * \param name Variable to search for.
  * \return Pointer to the variable if found, or NULL.
  * \sa CV_FindNetVar
  */
James R. committed
1119
consvar_t *CV_FindVar(const char *name)
Alam Ed Arias committed
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
{
	consvar_t *cvar;

	for (cvar = consvar_vars; cvar; cvar = cvar->next)
		if (!stricmp(name,cvar->name))
			return cvar;

	return NULL;
}

1130 1131 1132 1133 1134
#ifdef OLD22DEMOCOMPAT
/** Builds a unique Net Variable identifier number, which was used
  * in network packets and demos instead of the full name.
  *
  * This function only still exists to keep compatibility with old demos.
Alam Ed Arias committed
1135 1136 1137 1138
  *
  * \param s Name of the variable.
  * \return A new unique identifier.
  */
1139
static inline UINT16 CV_ComputeOldDemoID(const char *s)
Alam Ed Arias committed
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
{
	UINT16 ret = 0, i = 0;
	static UINT16 premiers[16] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53};

	while (*s)
	{
		ret = (UINT16)(ret + (*s)*premiers[i]);
		s++;
		i = (UINT16)((i+1) % 16);
	}
	return ret;
}

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
/** Finds a net variable based on its old style hash. If a hash collides, a
  * warning is printed and this function returns NULL.
  *
  * \param chk The variable's old style hash.
  * \return A pointer to the variable itself if found, or NULL.
  */
static old_demo_var_t *CV_FindOldDemoVar(UINT16 chk)
{
	old_demo_var_t *demovar;

	for (demovar = consvar_old_demo_vars; demovar; demovar = demovar->next)
	{
		if (demovar->checksum == chk)
1166 1167 1168 1169 1170 1171 1172 1173
		{
			if (demovar->collides)
			{
				CONS_Alert(CONS_WARNING,
						"Old demo netvar id %hu is a collision\n", chk);
				return NULL;
			}

1174
			return demovar;
1175
		}
1176 1177 1178 1179 1180 1181
	}

	return NULL;
}
#endif/*OLD22DEMOCOMPAT*/

Alam Ed Arias committed
1182 1183 1184 1185 1186 1187 1188 1189 1190
/** Finds a net variable based on its identifier number.
  *
  * \param netid The variable's identifier number.
  * \return A pointer to the variable itself if found, or NULL.
  */
static consvar_t *CV_FindNetVar(UINT16 netid)
{
	consvar_t *cvar;

1191
	if (netid >= consvar_number_of_netids)
1192 1193
		return NULL;

Alam Ed Arias committed
1194 1195 1196 1197 1198 1199 1200 1201 1202
	for (cvar = consvar_vars; cvar; cvar = cvar->next)
		if (cvar->netid == netid)
			return cvar;

	return NULL;
}

static void Setvalue(consvar_t *var, const char *valstr, boolean stealth);

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
#ifdef OLD22DEMOCOMPAT
/* Sets up a netvar for compatibility with old demos. */
static void CV_RegisterOldDemoVar(consvar_t *variable)
{
	old_demo_var_t *demovar;
	UINT16 old_demo_id;

	old_demo_id = CV_ComputeOldDemoID(variable->name);

	demovar = CV_FindOldDemoVar(old_demo_id);

	if (demovar)
		demovar->collides = true;
	else
	{
		demovar = ZZ_Calloc(sizeof *demovar);

		demovar->checksum = old_demo_id;
		demovar->cvar = variable;

		demovar->next = consvar_old_demo_vars;
		consvar_old_demo_vars = demovar;
	}
}
#endif

Alam Ed Arias committed
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
/** Registers a variable for later use from the console.
  *
  * \param variable The variable to register.
  */
void CV_RegisterVar(consvar_t *variable)
{
	// first check to see if it has already been defined
	if (CV_FindVar(variable->name))
	{
		CONS_Printf(M_GetText("Variable %s is already defined\n"), variable->name);
		return;
	}

	// check for overlap with a command
	if (COM_Exists(variable->name))
	{
		CONS_Printf(M_GetText("%s is a command name\n"), variable->name);
		return;
	}

	// check net variables
	if (variable->flags & CV_NETVAR)
	{
1252 1253 1254 1255 1256
		variable->netid = consvar_number_of_netids++;

		/* in case of overflow... */
		if (variable->netid > consvar_number_of_netids)
			I_Error("Way too many netvars");
1257 1258 1259 1260

#ifdef OLD22DEMOCOMPAT
		CV_RegisterOldDemoVar(variable);
#endif
Alam Ed Arias committed
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
	}

	// link the variable in
	if (!(variable->flags & CV_HIDEN))
	{
		variable->next = consvar_vars;
		consvar_vars = variable;
	}
	variable->string = variable->zstring = NULL;
	variable->changed = 0; // new variable has not been modified by the user

#ifdef PARANOIA
	if ((variable->flags & CV_NOINIT) && !(variable->flags & CV_CALL))
		I_Error("variable %s has CV_NOINIT without CV_CALL\n", variable->name);
	if ((variable->flags & CV_CALL) && !variable->func)
		I_Error("variable %s has CV_CALL without a function\n", variable->name);
#endif

	if (variable->flags & CV_NOINIT)
		variable->flags &= ~CV_CALL;

	Setvalue(variable, variable->defaultvalue, false);

	if (variable->flags & CV_NOINIT)
		variable->flags |= CV_CALL;

	// the SetValue will set this bit
	variable->flags &= ~CV_MODIFIED;
}

/** Finds the string value of a console variable.
  *
  * \param var_name The variable's name.
  * \return The string value or "" if the variable is not found.
  */
static const char *CV_StringValue(const char *var_name)
{
	consvar_t *var;

	var = CV_FindVar(var_name);
	if (!var)
		return cv_null_string;
	return var->string;
}

/** Completes the name of a console variable.
  *
  * \param partial The partial name of the variable (potentially).
  * \param skips   Number of variables to skip.
  * \return The complete variable name, or NULL.
  * \sa COM_CompleteCommand
  */
const char *CV_CompleteVar(char *partial, INT32 skips)
{
	consvar_t *cvar;
	size_t len;

	len = strlen(partial);

	if (!len)
		return NULL;

	// check variables
	for (cvar = consvar_vars; cvar; cvar = cvar->next)
		if (!strncmp(partial, cvar->name, len))
			if (!skips--)
				return cvar->name;

	return NULL;
}

/** Sets a value to a variable with less checking. Only for internal use.
  *
  * \param var    Variable to set.
  * \param valstr String value for the variable.
  */
static void Setvalue(consvar_t *var, const char *valstr, boolean stealth)
{
	boolean override = false;
	INT32 overrideval = 0;

	// If we want messages informing us if cheats have been enabled or disabled,
	// we need to rework the consvars a little bit.  This call crashes the game
	// on load because not all variables will be registered at that time.
/*	boolean prevcheats = false;
	if (var->flags & CV_CHEAT)
		prevcheats = CV_CheatsEnabled(); */

	if (var->PossibleValue)
	{
Alam Ed Arias committed
1351 1352 1353 1354 1355
		INT32 v;

		if (var->flags & CV_FLOAT)
		{
			double d = atof(valstr);
1356
			if (fpclassify(d) == FP_ZERO && valstr[0] != '0')
Alam Ed Arias committed
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
				v = INT32_MIN;
			else
				v = (INT32)(d * FRACUNIT);
		}
		else
		{
			v = atoi(valstr);
			if (!v && valstr[0] != '0')
				v = INT32_MIN; // Invalid integer trigger
		}
Alam Ed Arias committed
1367 1368 1369

		if (var->PossibleValue[0].strvalue && !stricmp(var->PossibleValue[0].strvalue, "MIN")) // bounded cvar
		{
1370 1371
#define MINVAL 0
#define MAXVAL 1
Alam Ed Arias committed
1372 1373
			INT32 i;
#ifdef PARANOIA
1374
			if (!var->PossibleValue[MAXVAL].strvalue)
Alam Ed Arias committed
1375 1376
				I_Error("Bounded cvar \"%s\" without maximum!\n", var->name);
#endif
Alam Ed Arias committed
1377

1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
			// search for other
			for (i = MAXVAL+1; var->PossibleValue[i].strvalue; i++)
				if (v == var->PossibleValue[i].value || !stricmp(var->PossibleValue[i].strvalue, valstr))
				{
					var->value = var->PossibleValue[i].value;
					var->string = var->PossibleValue[i].strvalue;
					goto finish;
				}


			if ((v != INT32_MIN && v < var->PossibleValue[MINVAL].value) || !stricmp(valstr, "MIN"))
Alam Ed Arias committed
1389
			{
1390 1391
				v = var->PossibleValue[MINVAL].value;
				valstr = var->PossibleValue[MINVAL].strvalue;
Alam Ed Arias committed
1392 1393 1394
				override = true;
				overrideval = v;
			}
1395
			else if ((v != INT32_MIN && v > var->PossibleValue[MAXVAL].value) || !stricmp(valstr, "MAX"))
Alam Ed Arias committed
1396
			{
1397 1398
				v = var->PossibleValue[MAXVAL].value;
				valstr = var->PossibleValue[MAXVAL].strvalue;
Alam Ed Arias committed
1399 1400 1401
				override = true;
				overrideval = v;
			}
Alam Ed Arias committed
1402 1403
			if (v == INT32_MIN)
				goto badinput;
1404 1405
#undef MINVAL
#undef MAXVAL
Alam Ed Arias committed
1406 1407 1408 1409 1410 1411 1412 1413 1414
		}
		else
		{
			INT32 i;

			// check first strings
			for (i = 0; var->PossibleValue[i].strvalue; i++)
				if (!stricmp(var->PossibleValue[i].strvalue, valstr))
					goto found;
Alam Ed Arias committed
1415
			if (v != INT32_MIN)
Alam Ed Arias committed
1416
			{
Alam Ed Arias committed
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
				// check INT32 now
				for (i = 0; var->PossibleValue[i].strvalue; i++)
					if (v == var->PossibleValue[i].value)
						goto found;
			}
			// Not found ... but wait, there's hope!
			if (var->PossibleValue == CV_OnOff || var->PossibleValue == CV_YesNo)
			{
				overrideval = -1;
				if (!stricmp(valstr, "on") || !stricmp(valstr, "yes"))
					overrideval = 1;
				else if (!stricmp(valstr, "off") || !stricmp(valstr, "no"))
					overrideval = 0;

				if (overrideval != -1)
Alam Ed Arias committed
1432 1433
				{
					for (i = 0; var->PossibleValue[i].strvalue; i++)
Alam Ed Arias committed
1434
						if (overrideval == var->PossibleValue[i].value)
Alam Ed Arias committed
1435 1436 1437 1438 1439
							goto found;
				}
			}

			// ...or not.
Alam Ed Arias committed
1440
			goto badinput;
Alam Ed Arias committed
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
found:
			var->value = var->PossibleValue[i].value;
			var->string = var->PossibleValue[i].strvalue;
			goto finish;
		}
	}

	// free the old value string
	Z_Free(var->zstring);

	var->string = var->zstring = Z_StrDup(valstr);

Alam Ed Arias committed
1453 1454 1455
	if (override)
		var->value = overrideval;
	else if (var->flags & CV_FLOAT)
Alam Ed Arias committed
1456 1457 1458 1459 1460
	{
		double d = atof(var->string);
		var->value = (INT32)(d * FRACUNIT);
	}
	else
1461 1462
	{
		if (var == &cv_forceskin)
1463
		{
1464
			var->value = R_SkinAvailable(var->string);
1465
			if (!R_SkinUsable(-1, var->value))
1466 1467
				var->value = -1;
		}
1468 1469 1470
		else
			var->value = atoi(var->string);
	}
Alam Ed Arias committed
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488

finish:
	// See the note above.
/* 	if (var->flags & CV_CHEAT)
	{
		boolean newcheats = CV_CheatsEnabled();

		if (!prevcheats && newcheats)
			CONS_Printf(M_GetText("Cheats have been enabled.\n"));
		else if (prevcheats && !newcheats)
			CONS_Printf(M_GetText("Cheats have been disabled.\n"));
	} */

	if (var->flags & CV_SHOWMODIFONETIME || var->flags & CV_SHOWMODIF)
	{
		CONS_Printf(M_GetText("%s set to %s\n"), var->name, var->string);
		var->flags &= ~CV_SHOWMODIFONETIME;
	}
1489 1490 1491 1492
	else // display message in debug file only
	{
		DEBFILE(va("%s set to %s\n", var->name, var->string));
	}
Alam Ed Arias committed
1493 1494 1495 1496 1497
	var->flags |= CV_MODIFIED;
	// raise 'on change' code
	LUA_CVarChanged(var->name); // let consolelib know what cvar this is.
	if (var->flags & CV_CALL && !stealth)
		var->func();
Alam Ed Arias committed
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509

	return;

// landing point for possiblevalue failures
badinput:

	if (var != &cv_nextmap) // Suppress errors for cv_nextmap
		CONS_Printf(M_GetText("\"%s\" is not a possible value for \"%s\"\n"), valstr, var->name);

	// default value not valid... ?!
	if (var->defaultvalue == valstr)
		I_Error("Variable %s default value \"%s\" is not a possible value\n", var->name, var->defaultvalue);
Alam Ed Arias committed
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
}

//
// Use XD_NETVAR argument:
//      2 byte for variable identification
//      then the value of the variable followed with a 0 byte (like str)
//

static boolean serverloading = false;

1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
static consvar_t *
ReadNetVar (UINT8 **p, char **return_value, boolean *return_stealth)
{
	UINT16  netid;
	char   *val;
	boolean stealth;

	consvar_t *cvar;

	netid   = READUINT16 (*p);
	val     = (char *)*p;
	SKIPSTRING (*p);
	stealth = READUINT8  (*p);

	cvar = CV_FindNetVar(netid);

	if (cvar)
	{
		(*return_value)   = val;
		(*return_stealth) = stealth;

		DEBFILE(va("Netvar received: %s [netid=%d] value %s\n", cvar->name, netid, val));
	}
	else
		CONS_Alert(CONS_WARNING, "Netvar not found with netid %hu\n", netid);

	return cvar;
}

1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
#ifdef OLD22DEMOCOMPAT
static consvar_t *
ReadOldDemoVar (UINT8 **p, char **return_value, boolean *return_stealth)
{
	UINT16  id;
	char   *val;
	boolean stealth;

	old_demo_var_t *demovar;

	id      = READUINT16 (*p);
	val     = (char *)*p;
	SKIPSTRING (*p);
	stealth = READUINT8  (*p);

	demovar = CV_FindOldDemoVar(id);

	if (demovar)
	{
		(*return_value)   = val;
		(*return_stealth) = stealth;

		return demovar->cvar;
	}
	else
	{
		CONS_Alert(CONS_WARNING, "Netvar not found with old demo id %hu\n", id);
		return NULL;
	}
}
#endif/*OLD22DEMOCOMPAT*/

1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
static consvar_t *
ReadDemoVar (UINT8 **p, char **return_value, boolean *return_stealth)
{
	char   *name;
	char   *val;
	boolean stealth;

	consvar_t *cvar;

	name    = (char *)*p;
	SKIPSTRING (*p);
	val     = (char *)*p;
	SKIPSTRING (*p);
	stealth = READUINT8  (*p);

	cvar = CV_FindVar(name);

	if (cvar)
	{
		(*return_value)   = val;
		(*return_stealth) = stealth;
	}
	else
		CONS_Alert(CONS_WARNING, "Netvar not found with name %s\n", name);

	return cvar;
}

Alam Ed Arias committed
1609 1610 1611 1612
static void Got_NetVar(UINT8 **p, INT32 playernum)
{
	consvar_t *cvar;
	char *svalue;
1613
	boolean stealth;
Alam Ed Arias committed
1614

wolfs committed
1615
	if (playernum != serverplayer && !IsPlayerAdmin(playernum) && !serverloading)
Alam Ed Arias committed
1616 1617 1618 1619
	{
		// not from server or remote admin, must be hacked/buggy client
		CONS_Alert(CONS_WARNING, M_GetText("Illegal netvar command received from %s\n"), player_names[playernum]);
		if (server)
1620
			SendKick(playernum, KICK_MSG_CON_FAIL | KICK_MSG_KEEP_BODY);
Alam Ed Arias committed
1621 1622 1623
		return;
	}

1624
	cvar = ReadNetVar(p, &svalue, &stealth);
Alam Ed Arias committed
1625

1626 1627
	if (cvar)
		Setvalue(cvar, svalue, stealth);
Alam Ed Arias committed
1628 1629
}

1630
void CV_SaveVars(UINT8 **p, boolean in_demo)
Alam Ed Arias committed
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
{
	consvar_t *cvar;
	UINT8 *count_p = *p;
	UINT16 count = 0;

	// send only changed cvars ...
	// the client will reset all netvars to default before loading
	WRITEUINT16(*p, 0x0000);
	for (cvar = consvar_vars; cvar; cvar = cvar->next)
		if ((cvar->flags & CV_NETVAR) && !CV_IsSetToDefault(cvar))
		{
1642 1643 1644 1645
			if (in_demo)
				WRITESTRING(*p, cvar->name);
			else
				WRITEUINT16(*p, cvar->netid);
Alam Ed Arias committed
1646 1647 1648 1649 1650 1651 1652
			WRITESTRING(*p, cvar->string);
			WRITEUINT8(*p, false);
			++count;
		}
	WRITEUINT16(count_p, count);
}

1653 1654
static void CV_LoadVars(UINT8 **p,
		consvar_t *(*got)(UINT8 **p, char **ret_value, boolean *ret_stealth))
Alam Ed Arias committed
1655 1656 1657 1658
{
	consvar_t *cvar;
	UINT16 count;

1659 1660 1661
	char *val;
	boolean stealth;

Alam Ed Arias committed
1662 1663 1664 1665 1666 1667 1668 1669 1670
	// prevent "invalid command received"
	serverloading = true;

	for (cvar = consvar_vars; cvar; cvar = cvar->next)
		if (cvar->flags & CV_NETVAR)
			Setvalue(cvar, cvar->defaultvalue, true);

	count = READUINT16(*p);
	while (count--)
1671 1672 1673 1674 1675 1676
	{
		cvar = (*got)(p, &val, &stealth);

		if (cvar)
			Setvalue(cvar, val, stealth);
	}
Alam Ed Arias committed
1677 1678 1679 1680

	serverloading = false;
}

1681 1682 1683 1684 1685
void CV_LoadNetVars(UINT8 **p)
{
	CV_LoadVars(p, ReadNetVar);
}

1686 1687 1688 1689 1690 1691 1692
#ifdef OLD22DEMOCOMPAT
void CV_LoadOldDemoVars(UINT8 **p)
{
	CV_LoadVars(p, ReadOldDemoVar);
}
#endif

1693 1694 1695 1696 1697
void CV_LoadDemoVars(UINT8 **p)
{
	CV_LoadVars(p, ReadDemoVar);
}

Alam Ed Arias committed
1698 1699
static void CV_SetCVar(consvar_t *var, const char *value, boolean stealth);

Alam Ed Arias committed
1700 1701 1702 1703 1704 1705 1706
void CV_ResetCheatNetVars(void)
{
	consvar_t *cvar;

	// Stealthset everything back to default.
	for (cvar = consvar_vars; cvar; cvar = cvar->next)
		if (cvar->flags & CV_CHEAT)
Alam Ed Arias committed
1707
			CV_SetCVar(cvar, cvar->defaultvalue, true);
Alam Ed Arias committed
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
}

// Returns true if the variable's current value is its default value
boolean CV_IsSetToDefault(consvar_t *v)
{
	return (!(strcmp(v->defaultvalue, v->string)));
}

// If any cheats CVars are not at their default settings, return true.
// Else return false.
// This returns a UINT8 because I'm too lazy to deal with the packet structure.
// Deal with it. =P
UINT8 CV_CheatsEnabled(void)
{
	consvar_t *cvar;

	for (cvar = consvar_vars; cvar; cvar = cvar->next)
		if ((cvar->flags & CV_CHEAT) && strcmp(cvar->defaultvalue, cvar->string))
			return 1;
	return 0;
}

/** Sets a value to a variable, performing some checks and calling the
  * callback function if there is one.
  * Does as if "<varname> <value>" is entered at the console.
  *
  * \param var   The variable.
  * \param value The string value.
  * \sa CV_StealthSet, CV_SetValue
  */
static void CV_SetCVar(consvar_t *var, const char *value, boolean stealth)
{
#ifdef PARANOIA
	if (!var)
		I_Error("CV_Set: no variable\n");
	if (!var->string)
		I_Error("CV_Set: %s no string set!\n", var->name);
#endif
	if (!var || !var->string || !value || !stricmp(var->string, value))
		return; // no changes

	if (var->flags & CV_NETVAR)
	{
		// send the value of the variable
1752
		UINT8 buf[128];
Alam Ed Arias committed
1753
		UINT8 *p = buf;
1754
		if (!(server || (addedtogame && IsPlayerAdmin(consoleplayer))))
Alam Ed Arias committed
1755 1756 1757 1758 1759
		{
			CONS_Printf(M_GetText("Only the server or admin can change: %s %s\n"), var->name, var->string);
			return;
		}

1760 1761 1762
		if (var == &cv_forceskin)
		{
			INT32 skin = R_SkinAvailable(value);
1763
			if ((stricmp(value, "None")) && ((skin == -1) || !R_SkinUsable(-1, skin)))
1764 1765 1766 1767 1768 1769
			{
				CONS_Printf("Please provide a valid skin name (\"None\" disables).\n");
				return;
			}
		}

Alam Ed Arias committed
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
		// Only add to netcmd buffer if in a netgame, otherwise, just change it.
		if (netgame || multiplayer)
		{
			WRITEUINT16(p, var->netid);
			WRITESTRING(p, value);
			WRITEUINT8(p, stealth);

			SendNetXCmd(XD_NETVAR, buf, p-buf);
		}
		else
			Setvalue(var, value, stealth);
	}
	else
		if ((var->flags & CV_NOTINNET) && netgame)
		{
			CONS_Printf(M_GetText("This variable can't be changed while in netgame: %s %s\n"), var->name, var->string);
			return;
		}
		else
			Setvalue(var, value, stealth);
}

/** Sets a value to a variable without calling its callback function.
  *
  * \param var   The variable.
  * \param value The string value.
  * \sa CV_Set, CV_StealthSetValue
  */
void CV_StealthSet(consvar_t *var, const char *value)
{
	CV_SetCVar(var, value, true);
}

1803 1804 1805 1806 1807 1808 1809 1810 1811
/** Sets a numeric value to a variable, sometimes calling its callback
  * function.
  *
  * \param var   The variable.
  * \param value The numeric value, converted to a string before setting.
  * \param stealth Do we call the callback function or not?
  */
static void CV_SetValueMaybeStealth(consvar_t *var, INT32 value, boolean stealth)
{
Alam Ed Arias committed
1812
	char val[SKINNAMESIZE+1];
1813 1814 1815

	if (var == &cv_forceskin) // Special handling.
	{
Alam Ed Arias committed
1816
		const char *tmpskin = NULL;
1817
		if ((value < 0) || (value >= numskins))
Alam Ed Arias committed
1818
			tmpskin = "None";
1819
		else
Alam Ed Arias committed
1820 1821
			tmpskin = skins[value].name;
		strncpy(val, tmpskin, SKINNAMESIZE);
1822 1823 1824 1825 1826 1827 1828
	}
	else
		sprintf(val, "%d", value);

	CV_SetCVar(var, val, stealth);
}

Alam Ed Arias committed
1829 1830 1831 1832 1833 1834 1835 1836 1837
/** Sets a numeric value to a variable without calling its callback
  * function.
  *
  * \param var   The variable.
  * \param value The numeric value, converted to a string before setting.
  * \sa CV_SetValue, CV_StealthSet
  */
void CV_StealthSetValue(consvar_t *var, INT32 value)
{
1838
	CV_SetValueMaybeStealth(var, value, true);
Alam Ed Arias committed
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
}

// New wrapper for what used to be CV_Set()
void CV_Set(consvar_t *var, const char *value)
{
	CV_SetCVar(var, value, false);
}

/** Sets a numeric value to a variable, performing some checks and
  * calling the callback function if there is one.
  *
  * \param var   The variable.
  * \param value The numeric value, converted to a string before setting.
  * \sa CV_Set, CV_StealthSetValue
  */
void CV_SetValue(consvar_t *var, INT32 value)
{
1856
	CV_SetValueMaybeStealth(var, value, false);
Alam Ed Arias committed
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
}

/** Adds a value to a console variable.
  * Used to increment and decrement variables from the menu.
  * Contains special cases to handle pointlimit in some multiplayer modes,
  * map number for game hosting, etc.
  *
  * \param var       The variable to add to.
  * \param increment The change in the variable; can be negative for a
  *                  decrement.
  * \sa CV_SetValue
  */
void CV_AddValue(consvar_t *var, INT32 increment)
{
	INT32 newvalue, max;

1873 1874 1875
	if (!increment)
		return;

Alam Ed Arias committed
1876
	// count pointlimit better
Alam Ed Arias committed
1877
	if (var == &cv_pointlimit && (gametype == GT_MATCH))
Alam Ed Arias committed
1878
		increment *= 50;
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891

	if (var == &cv_forceskin) // Special handling.
	{
		INT32 oldvalue = var->value;
		newvalue = oldvalue;
		do
		{
			newvalue += increment;
			if (newvalue < -1)
				newvalue = (numskins - 1);
			else if (newvalue >= numskins)
				newvalue = -1;
		} while ((oldvalue != newvalue)
1892
				&& !(R_SkinUsable(-1, newvalue)));
1893 1894 1895
	}
	else
		newvalue = var->value + increment;
Alam Ed Arias committed
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933

	if (var->PossibleValue)
	{
		if (var == &cv_nextmap)
		{
			// Special case for the nextmap variable, used only directly from the menu
			INT32 oldvalue = var->value - 1, gt;
			gt = cv_newgametype.value;
			{
				newvalue = var->value - 1;
				do
				{
					if(increment > 0) // Going up!
					{
						newvalue++;
						if (newvalue == NUMMAPS)
							newvalue = 0;
					}
					else // Going down!
					{
						newvalue--;
						if (newvalue == -1)
							newvalue = NUMMAPS-1;
					}

					if (newvalue == oldvalue)
						gt = -1; // don't loop forever if there's none of a certain gametype

					if(!mapheaderinfo[newvalue])
						continue; // Don't allocate the header.  That just makes memory usage skyrocket.

				} while (newvalue != oldvalue && !M_CanShowLevelInList(newvalue, gt));

				var->value = newvalue + 1;
				var->func();
				return;
			}
		}
1934 1935
#define MINVAL 0
#define MAXVAL 1
Alam Ed Arias committed
1936 1937
		else if (var->PossibleValue[MINVAL].strvalue && !strcmp(var->PossibleValue[MINVAL].strvalue, "MIN"))
		{
1938 1939 1940 1941
#ifdef PARANOIA
			if (!var->PossibleValue[MAXVAL].strvalue)
				I_Error("Bounded cvar \"%s\" without maximum!\n", var->name);
#endif
Alam Ed Arias committed
1942

1943 1944 1945 1946
			if (newvalue < var->PossibleValue[MINVAL].value || newvalue > var->PossibleValue[MAXVAL].value)
			{
				INT32 currentindice = -1, newindice;
				for (max = MAXVAL+1; var->PossibleValue[max].strvalue; max++)
1947 1948 1949 1950
				{
					if (var->PossibleValue[max].value == newvalue)
					{
						increment = 0;
1951
						currentindice = max;
1952 1953 1954 1955
					}
					else if (var->PossibleValue[max].value == var->value)
						currentindice = max;
				}
Alam Ed Arias committed
1956

1957
				if (increment)
1958
				{
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
					increment = (increment > 0) ? 1 : -1;
					if (currentindice == -1 && max != MAXVAL+1)
						newindice = ((increment > 0) ? MAXVAL : max) + increment;
					else
						newindice = currentindice + increment;

					if (newindice >= max || newindice <= MAXVAL)
					{
						if (var == &cv_pointlimit && (gametype == GT_MATCH) && increment > 0)
							CV_SetValue(var, 50);
						else
						{
							newvalue = var->PossibleValue[((increment > 0) ? MINVAL : MAXVAL)].value;
							CV_SetValue(var, newvalue);
						}
					}
					else
						CV_Set(var, var->PossibleValue[newindice].strvalue);
1977 1978
				}
				else
1979
					CV_Set(var, var->PossibleValue[currentindice].strvalue);
1980 1981 1982
			}
			else
				CV_SetValue(var, newvalue);
Alam Ed Arias committed
1983
		}
1984 1985
#undef MINVAL
#undef MAXVAL
Alam Ed Arias committed
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
		else
		{
			INT32 currentindice = -1, newindice;

			// this code do not support more than same value for differant PossibleValue
			for (max = 0; var->PossibleValue[max].strvalue; max++)
				if (var->PossibleValue[max].value == var->value)
					currentindice = max;

			if (var == &cv_chooseskin)
			{
				// Special case for the chooseskin variable, used only directly from the menu
toaster committed
1998 1999
				newvalue = var->value - 1;
				do
Alam Ed Arias committed
2000
				{
toaster committed
2001
					if (increment > 0) // Going up!
Alam Ed Arias committed
2002 2003 2004 2005
					{
						newvalue++;
						if (newvalue == MAXSKINS)
							newvalue = 0;
toaster committed
2006 2007
					}
					else if (increment < 0) // Going down!
Alam Ed Arias committed
2008 2009 2010 2011
					{
						newvalue--;
						if (newvalue == -1)
							newvalue = MAXSKINS-1;
toaster committed
2012 2013 2014 2015 2016 2017 2018
					}
				} while (var->PossibleValue[newvalue].strvalue == NULL);

				var->value = newvalue + 1;
				var->string = var->PossibleValue[newvalue].strvalue;
				var->func();
				return;
Alam Ed Arias committed
2019 2020 2021 2022 2023 2024 2025
			}
#ifdef PARANOIA
			if (currentindice == -1)
				I_Error("CV_AddValue: current value %d not found in possible value\n",
					var->value);
#endif

2026
			newindice = (currentindice + increment + max) % max;
Alam Ed Arias committed
2027 2028 2029 2030 2031 2032 2033 2034 2035
			CV_Set(var, var->PossibleValue[newindice].strvalue);
		}
	}
	else
		CV_SetValue(var, newvalue);

	var->changed = 1; // user has changed it now
}

2036 2037 2038 2039 2040 2041
void CV_InitFilterVar(void)
{
	joyaxis_default = joyaxis2_default = true;
	joyaxis_count = joyaxis2_count = 0;
}

2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
void CV_ToggleExecVersion(boolean enable)
{
	execversion_enabled = enable;
}

static void CV_EnforceExecVersion(void)
{
	if (!execversion_enabled)
		CV_StealthSetValue(&cv_execversion, EXECVERSION);
}

2053 2054 2055
static boolean CV_FilterJoyAxisVars(consvar_t *v, const char *valstr)
{
	// If ALL axis settings are previous defaults, set them to the new defaults
2056
	// EXECVERSION < 26 (2.1.21)
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187

	if (joyaxis_default)
	{
		if (!stricmp(v->name, "joyaxis_turn"))
		{
			if (joyaxis_count > 6) return false;
			// we're currently setting the new defaults, don't interfere
			else if (joyaxis_count == 6) return true;

			if (!stricmp(valstr, "X-Axis")) joyaxis_count++;
			else joyaxis_default = false;
		}
		if (!stricmp(v->name, "joyaxis_move"))
		{
			if (joyaxis_count > 6) return false;
			else if (joyaxis_count == 6) return true;

			if (!stricmp(valstr, "Y-Axis")) joyaxis_count++;
			else joyaxis_default = false;
		}
		if (!stricmp(v->name, "joyaxis_side"))
		{
			if (joyaxis_count > 6) return false;
			else if (joyaxis_count == 6) return true;

			if (!stricmp(valstr, "Z-Axis")) joyaxis_count++;
			else joyaxis_default = false;
		}
		if (!stricmp(v->name, "joyaxis_look"))
		{
			if (joyaxis_count > 6) return false;
			else if (joyaxis_count == 6) return true;

			if (!stricmp(valstr, "None")) joyaxis_count++;
			else joyaxis_default = false;
		}
		if (!stricmp(v->name, "joyaxis_fire")
			|| !stricmp(v->name, "joyaxis_firenormal"))
		{
			if (joyaxis_count > 6) return false;
			else if (joyaxis_count == 6) return true;

			if (!stricmp(valstr, "None")) joyaxis_count++;
			else joyaxis_default = false;
		}
		// reset all axis settings to defaults
		if (joyaxis_count == 6)
		{
			COM_BufInsertText(va("%s \"%s\"\n", cv_turnaxis.name, cv_turnaxis.defaultvalue));
			COM_BufInsertText(va("%s \"%s\"\n", cv_moveaxis.name, cv_moveaxis.defaultvalue));
			COM_BufInsertText(va("%s \"%s\"\n", cv_sideaxis.name, cv_sideaxis.defaultvalue));
			COM_BufInsertText(va("%s \"%s\"\n", cv_lookaxis.name, cv_lookaxis.defaultvalue));
			COM_BufInsertText(va("%s \"%s\"\n", cv_fireaxis.name, cv_fireaxis.defaultvalue));
			COM_BufInsertText(va("%s \"%s\"\n", cv_firenaxis.name, cv_firenaxis.defaultvalue));
			joyaxis_count++;
			return false;
		}
	}

	if (joyaxis2_default)
	{
		if (!stricmp(v->name, "joyaxis2_turn"))
		{
			if (joyaxis2_count > 6) return false;
			// we're currently setting the new defaults, don't interfere
			else if (joyaxis2_count == 6) return true;

			if (!stricmp(valstr, "X-Axis")) joyaxis2_count++;
			else joyaxis2_default = false;
		}
		if (!stricmp(v->name, "joyaxis2_move"))
		{
			if (joyaxis2_count > 6) return false;
			else if (joyaxis2_count == 6) return true;

			if (!stricmp(valstr, "Y-Axis")) joyaxis2_count++;
			else joyaxis2_default = false;
		}
		if (!stricmp(v->name, "joyaxis2_side"))
		{
			if (joyaxis2_count > 6) return false;
			else if (joyaxis2_count == 6) return true;

			if (!stricmp(valstr, "Z-Axis")) joyaxis2_count++;
			else joyaxis2_default = false;
		}
		if (!stricmp(v->name, "joyaxis2_look"))
		{
			if (joyaxis2_count > 6) return false;
			else if (joyaxis2_count == 6) return true;

			if (!stricmp(valstr, "None")) joyaxis2_count++;
			else joyaxis2_default = false;
		}
		if (!stricmp(v->name, "joyaxis2_fire")
			|| !stricmp(v->name, "joyaxis2_firenormal"))
		{
			if (joyaxis2_count > 6) return false;
			else if (joyaxis2_count == 6) return true;

			if (!stricmp(valstr, "None")) joyaxis2_count++;
			else joyaxis2_default = false;
		}

		// reset all axis settings to defaults
		if (joyaxis2_count == 6)
		{
			COM_BufInsertText(va("%s \"%s\"\n", cv_turnaxis2.name, cv_turnaxis2.defaultvalue));
			COM_BufInsertText(va("%s \"%s\"\n", cv_moveaxis2.name, cv_moveaxis2.defaultvalue));
			COM_BufInsertText(va("%s \"%s\"\n", cv_sideaxis2.name, cv_sideaxis2.defaultvalue));
			COM_BufInsertText(va("%s \"%s\"\n", cv_lookaxis2.name, cv_lookaxis2.defaultvalue));
			COM_BufInsertText(va("%s \"%s\"\n", cv_fireaxis2.name, cv_fireaxis2.defaultvalue));
			COM_BufInsertText(va("%s \"%s\"\n", cv_firenaxis2.name, cv_firenaxis2.defaultvalue));
			joyaxis2_count++;
			return false;
		}
	}

	// we haven't reached our counts yet, or we're not default
	return true;
}

static boolean CV_FilterVarByVersion(consvar_t *v, const char *valstr)
{
	// True means allow the CV change, False means block it

	// We only care about CV_SAVE because this filters the user's config files
	// We do this same check in CV_Command
	if (!(v->flags & CV_SAVE))
		return true;

2188
	if (GETMAJOREXECVERSION(cv_execversion.value) < 26) // 26 = 2.1.21
2189 2190 2191 2192
	{
		// MOUSE SETTINGS
		// alwaysfreelook split between first and third person (chasefreelook)
		// mousemove was on by default, which invalidates the current approach
2193 2194
		if (!stricmp(v->name, "alwaysmlook")
			|| !stricmp(v->name, "alwaysmlook2")
2195 2196
			|| !stricmp(v->name, "mousemove")
			|| !stricmp(v->name, "mousemove2"))
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
			return false;

		// mousesens was changed from 35 to 20 due to oversensitivity
		if ((!stricmp(v->name, "mousesens")
			|| !stricmp(v->name, "mousesens2")
			|| !stricmp(v->name, "mouseysens")
			|| !stricmp(v->name, "mouseysens2"))
			&& atoi(valstr) == 35)
			return false;

		// JOYSTICK DEFAULTS
		// use_joystick was changed from 0 to 1 to automatically use a joystick if available
#if defined(HAVE_SDL) || defined(_WINDOWS)
		if ((!stricmp(v->name, "use_joystick")
			|| !stricmp(v->name, "use_joystick2"))
			&& atoi(valstr) == 0)
			return false;
#endif

		// axis defaults were changed to be friendly to 360 controllers
		// if ALL axis settings are defaults, then change them to new values
		if (!CV_FilterJoyAxisVars(v, valstr))
			return false;
	}
	return true;
}

Alam Ed Arias committed
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
/** Displays or changes a variable from the console.
  * Since the user is presumed to have been directly responsible
  * for this change, the variable is marked as changed this game.
  *
  * \return False if passed command was not recognized as a console
  *         variable, otherwise true.
  * \sa CV_ClearChangedFlags
  */
static boolean CV_Command(void)
{
	consvar_t *v;

	// check variables
	v = CV_FindVar(COM_Argv(0));
	if (!v)
		return false;

2241 2242 2243
	if (( com_flags & COM_SAFE ) && ( v->flags & CV_NOLUA ))
		return false;

Alam Ed Arias committed
2244 2245 2246 2247 2248 2249 2250
	// perform a variable print or set
	if (COM_Argc() == 1)
	{
		CONS_Printf(M_GetText("\"%s\" is \"%s\" default is \"%s\"\n"), v->name, v->string, v->defaultvalue);
		return true;
	}