Developer Console Control

From Valve Developer Community
Revision as of 04:53, 10 April 2019 by Ethan101au (talk | contribs) (Changed bitwise OR to logical OR)
Jump to: navigation, search
Deutsch Русский

This document explains how to write code that prints to the console, as well as how to execute and create console commands and variables. See Developer Console for an overview of console features.

Printing to the console

Printing text to the console is done the same way in all modules, since the Tier0 debug layer provides these routines. The three most common functions are Msg(), DevMsg() and Warning() which all support VarArgs, like sprintf():

DevMsg (char const* pMsg, ... ) - only in developer mode
Msg(char const* pMsg, ... )	 - always, white
Warning(char const *pMsg, ... ) - always, red
Note.png Note: Only 989 characters can be output to the console at once!

For backward compatibility with HL1 source code you can still use Con_Printf() and Con_DPrintf().

Including variables:


DevMsg("Include this variable: %.2f", floatVariable)


DevMsg("Include this variable: %i", integerVariable)


DevMsg("Include this variable: %s", stringVariable)

Multiple Variable:

DevMsg("Include this %i followed by %s and the %.2f", integerVariable, stringVariable, floatVariable)

Include \n to create carriage return, ready to output on line below when Msg/DevMsg next called.

Note.png Note:  There exist versions of these functions which have an additional parameter called level. If level is higher than the developer cvar setting, the message will not be printed in the console. This allows you to print extended debug info only when developer mode is at a certain setting. See Developer for more info on which levels print what kind of information.

Setting cvars

[the_cvar]->SetValue( [value] );

If you do not have access to a cvar, do this first:

ConVar *[the_cvar] = cvar->FindVar( "[the_cvar]" );

This works even for closed-source cvars.

Executing commands

The engine provides interface to server and client code to execute commands (strings) from code as if the user would have entered them. The server has to use the interface IVEngineServer::ServerCommand():

engine->ServerCommand("changelevel de_dust\n");

Client code has to use the interface IVEngineClient and can choose here between two functions, depending if the command should be executed on the client first or be sent directly to the server:

engine->ServerCmd( "say hello\n" ); // send command to server


engine->ClientCmd( "say hello\n" ); // execute command on client

If you wish to execute a console command on a client from the server use:

engine->ClientCommand( edict(), "command", ... );

Where edict() is your ent's edict, "command" would be replaced by your concommand, followed by any formatted vars (same as printf). This would be useful for showing a team selection menu.

Note.png Note: You can't pass dynamic arguments to these functions. All parameters are decided when the code compiles.

Adding new commands & variables

The developer console is a subsystem provided by the Source engine and is accessible for all other modules via a public interface ICvar ( see \public\icvar.h). This interface allows registering new commands and finding/iterating existing commands. This interface is available via the global CVAR in-game server/client code (cv in engine code). Console commands are implemented in ConCommand and console_variables in ConVar, which both derive from the base class ConCommandBase (see \public\convar.h).

Adding a new command or variable is fairly simple and the same code in both server and client (even engine) modules. The constructor of these classes automatically registers the command at the console system. This short example code adds a new command my_function and a new variable my_variable initialized to 42:

#include <convar.h>
ConVar my_variable( "my_variable", "42", FCVAR_ARCHIVE, "My favorite number" );	

void MyFunction_f( void )
    Msg("This is my function\n");

ConCommand my_function( "my_function", MyFunction_f, "Shows a message.", FCVAR_CHEAT );

It is common use that the object name and the command name are the same and variables used only in a single source file are declared as static.

Using the ConVar class

ConVars store variables that can be altered through the console and (optionally) saved in config.cfg. Let's take a look at the most used constructor:

ConVar( char const *pName,
	char const *pDefaultValue,
	int flags,
	char const *pHelpString )

The first argument pName is the variable name (no spaces), followed by pDefaultValue, which is always given as a string even for ConVars with numerical values. Flags specify special characteristics of the variable — all flag definitions start with a FCVAR_ prefix. More information about these flags can be found below. It's always good to provide a pHelpString, so users get an idea what this variable is about. ConVars are not bound to a certain type, their value can be an integer or a float or string and you may use it however you like. As long as you have the ConVar object itself or as a pointer, you can access and modify its values directly. All these examples are valid and have the same result:

if ( my_variable.GetInt() == 42 ) DoSomething();
if ( my_variable.GetFloat() == 42.0f ) DoSomething();
if ( strcmp(my_variable.GetString(), "42")==0 ) DoSomething();

To set the value of a ConVar you should use the SetValue() function, which also allows all types of data:

my_variable.SetValue( 42 );
my_variable.SetValue( 42.0f );
my_variable.SetValue( "42" );

At any time you can revert a ConVar back to it's original default value by using the Revert() function.

If a ConVar is created in a different module, the ICvar interface function FindVar() can be used to get a pointer to this object, if the variable name is known. This is an expensive search function and the pointer should be cached if reused often. Here is an example how to check the ConVar sv_cheats defined in the engine module:

ConVar *pCheats  = cvar->FindVar( "sv_cheats" );

	if ( pCheats && pCheats->GetInt() == 1 ) AllowCheating();

A range of valid values can be specified for numerical ConVars using a different constructor. Then a ConVar is automatically checked by the console system whenever changed manually. If the entered number is out of range, it's rounded to the next valid value. Setting valid range from 1 to 100:

ConVar my_variable( "my_variable", "42", 0, "helptext", true, 1, true, 100 );

Sometimes you also want a notification when a user's or another subsystem changes your ConVar value, therefore a callback function can be installed:

static void OnChangeMyVariable ( IConVar *var, const char *pOldValue, float flOldValue )
	DevMsg( "ConVar %s was changed from %s to %s\n", var->GetName(), pOldValue, (( ConVar* )var)->GetString() );

ConVar my_variable( "my_variable", "42", 0, "My favorite number", OnChangeMyVariable );

Using the ConCommand class

The class ConCommand does not store a value, but instead executes a procedure as soon as it is invoked. It is simpler than the ConVar and has just one constructor:

ConCommand( char const *pName,
	FnCommandCallback callback,
	char const *pHelpString = 0,
	int flags = 0,
 	FnCommandCompletionCallback completionFunc = 0 );

As in ConVar, pName specifies the command name (no spaces). callback is the function executed when a user runs this command and both pHelpString and flags have the same function as in ConVar. ConCommands supports auto completion for the first parameter, which is useful especially for commands that process files. For example, if you have a command loadtext <textfile> that expects a .txt file as input, the console scans for all available .txt files and allows the user to choose one from a list. If a valid completionFunc is passed, it will be called whenever the console system needs a list of available arguments.

When the callback function is executed, the parameters entered in the console are not passed as function arguments. The callback function has to query the engine how many arguments where given using the engine interface function args.ArgC(), where 'args' is the name of the CCommand in your function head. Then you can look at single arguments using args.Arg(index), where index 1 is the first argument. The arguments are always returned as strings.

void MySay_f ( const CCommand &args )
	if ( args.ArgC() < 1 || args.Arg(1) == "" )
		Msg("Usage: my_say <text>\n");
	Msg("I say: %s\n", args.Arg(1) );
ConCommand my_say( "my_say", MySay_f , "say something", 0);

Here an example how to build a simple auto complete list. The partial parameter isn't used here; it contains the characters entered so far (including the command name itself) :

static int MySayAutoComplete ( char const *partial, 
	strcpy( commands[0], "hello" );
	strcpy( commands[1], "goodbye" );
	return 2; // number of entries

ConCommand my_say( "my_say", MySay_f, "say something", 0, MySayAutoComplete);

To retrieve the calling player from a concommand, use UTIL_GetCommandClient() on the server or C_BasePlayer::GetLocalPlayer() on the client.

Player Client Commands

All server-side player classes derived from CBasePlayer have a function, ClientCommand, which is called when the player issues a ConCommand. This function can be used to handle concommands.

bool CHL2MP_Player::ClientCommand( const char *pcmd )
	if ( FStrEq( pcmd, "spectate" ) )
		if ( ShouldRunRateLimitedCommand( pcmd ) )
			// instantly join spectators
			HandleCommand_JoinTeam( TEAM_SPECTATOR );	
		return true;
	else if ( FStrEq( pcmd, "jointeam" ) ) 
		if ( engine->Cmd_Argc() < 2 )
			Warning( "Player sent bad jointeam syntax\n" );

		if ( ShouldRunRateLimitedCommand( pcmd ) )
			int iTeam = atoi( engine->Cmd_Argv(1) );
			HandleCommand_JoinTeam( iTeam );
		return true;
	else if ( FStrEq( pcmd, "joingame" ) )
		return true;

	return BaseClass::ClientCommand( pcmd );

As you can see in this example HL2MP code, the function is called with an argument, pcmd, which is then handled based on several if statements. The function ShouldRunRateLimitedCommand is used to prevent spamming and checks to make sure that the command wasn't too recently called.

This function will look slightly different in code derived from the Orangebox engine.

The FCVAR flags

The console command/variable flags can specify quite powerful characteristics and must be handled with care. These flags are usually set in the constructor but may be modified with ConCommandBase::AddFlags() (not used very often). It's not possible to change these flags other than in source code to avoid cheating.

Some flags must be set manually, but those in the list below are set automatically by the console system:


The remaining flags must be set manually:

Most commands and variables are for debugging purposes and not removed in release builds since they are also useful for 3rd party developers and map makers. Unfortunately we cannot allow normal players to use these debugging tools since it gives them an unfair advantage over other players (cheating). A good rule is to add FCVAR_CHEAT to every new console command you add unless it's an explicit and legitimate options setting for players. Experience has shown that even the most harmless looking debugging command can be misused as a cheat somehow.
The game server's setting of sv_cheats decides if cheats are enabled or not. If a client connects to a server where cheats are disabled (should be the default case), all client side console variables labeled as FCVAR_CHEAT are reverted to their default values and can't be changed as long as the client stays connected. Console commands marked as FCVAR_CHEAT can't be executed either.
Marking a command as FCVAR_SERVER_CAN_EXECUTE will make the command only allow the server to use it, whether through the Source Dedicated Server console or by the player that created the local server.
Some console variables should not be changeable while the client is currently in a server (eg. fps_max) due to the possibility of exploitation of the command.
Some console variables contain client information the server needs to know about, like the player's name or their network settings. These variables must be flagged as FCVAR_USERINFO, so they get transmitted to the server and updated every time the user changes them. When the player changes one of these variables the engine notifies the server code via ClientSettingsChanged(). The game server can also query the engine for specific client settings with GetClientConVarValue().
When the game server and clients are using shared code where it's important that both sides run the exact same path using the same data (e.g. predicted movement/weapons, game rules). If this code uses console variables, they must have the same values on both sides. The flag FCVAR_REPLICATED ensures that by broadcasting these values to all clients. While connected, clients can't change these values and are forced to use the server-side values.
Some console variables contain user specific settings we want to restore each time the game is started (like name or network_rate). If a console variable is labeled as FCVAR_ARCHIVE, it is saved in the file config.cfg when the game shuts down and is reloaded when the game is reopened. The command host_writeconfig can also be used to save the settings to config.cfg.
If a console variable is flagged as FCVAR_NOTIFY, the server sends a notification message to all clients whenever the variable is changed. This should be used for variables that change game play rules, which are important for all players (mp_friendlyfire etc).
If a console variable contains private information (passwords etc), we don't want them to be visible to other players. Using FCVAR_PROTECTED flag the information is labeled as confidential.
If executing a command or changing a variable should only be allowed in single player mode, then label it with FCVAR_SPONLY flag.
Some important variables are logged or broadcasted (gamerules etc), so it is important that they contain only printable characters (no control chars etc) to prevent arbitrary code execution and other problems.
The FCVAR_NEVER_AS_STRING flag tells the engine never to print this variable as a string since it contains control sequences.
When starting to record a demo file, some console variables must explicitly be added to the recording to ensure a correct playback.
This is the opposite of FCVAR_DEMO, some console commands shouldn't be recorded in demo files.