This article's documentation is for anything that uses the Source engine. Click here for more information.

Authoring a Model Entity

From Valve Developer Community
Jump to: navigation, search
English (en)Русский (ru)中文 (zh)中文(台灣)‎ (zh-tw)Translate (Translate)

This tutorial assumes you have completed and understood Authoring a Logical Entity.

In this tutorial we'll create an entity that can move, collide with other objects, and that has a visual component (in this case, a model). We will make the entity randomly move around the world.

Create sdk_modelentity.cpp in your personal Server folder and we'll begin.

Include and Declare

You should understand this code now:

#include "cbase.h"

class CMyModelEntity : public CBaseAnimating
{
public:
	DECLARE_CLASS( CMyModelEntity, CBaseAnimating );
	DECLARE_DATADESC();

	CMyModelEntity()
	{
		m_bActive = false;
	}

	void Spawn( void );
	void Precache( void );

	void MoveThink( void );

	// Input function
	void InputToggle( inputdata_t &inputData );

private:

	bool	m_bActive;
	float	m_flNextChangeTime;
};

Notice how we are now inheriting from CBaseAnimating, and how we have some new functions. The private variables are a boolean (true/false) and a floating point (decimalised number).

Note.pngNote:Our entity won't begin moving until prompted by InputToggle(). Changing this behaviour so that it starts active (which isn't just as simple as changing m_bActive in the code above!) would be a good project once you finish the tutorial proper.

Entity name and Datadesc

LINK_ENTITY_TO_CLASS( my_model_entity, CMyModelEntity );

// Start of our data description for the class
BEGIN_DATADESC( CMyModelEntity )
	
	// Save/restore our active state
	DEFINE_FIELD( m_bActive, FIELD_BOOLEAN ),
	DEFINE_FIELD( m_flNextChangeTime, FIELD_TIME ),

	// Links our input name from Hammer to our input member function
	DEFINE_INPUTFUNC( FIELD_VOID, "Toggle", InputToggle ),

	// Declare our think function
	DEFINE_THINKFUNC( MoveThink ),

END_DATADESC()

The biggest change here from our logical entity is DEFINE_THINKFUNC. Think functions are special cases in Source, and we need to identify them.

Defining the model

// Name of our entity's model
#define	ENTITY_MODEL	"models/gibs/airboat_broken_engine.mdl"

This hard-codes the model that our entity will present to the world. This is a static piece of information, not a variable: it cannot change once the code has been compiled. The path to the .mdl file is relative to the game directory (e.g. hl2/).

Note.pngNote:We are only creating this define to make finding and changing its value later on easier. It has no effect on how our code works.

Precache()

Now we come to our first function. Precache() should be called when an entity spawns, and ensures that loading of whatever is listed in it occurs before the player spawns (i.e. sees the world and gains control). See Precaching Assets for more information.

Precaching gets a special name because there are other types of "asynchronous" loading that can occur after player spawn.

//-----------------------------------------------------------------------------
// Purpose: Precache assets used by the entity
//-----------------------------------------------------------------------------
void CMyModelEntity::Precache( void )
{
	PrecacheModel( ENTITY_MODEL );

	BaseClass::Precache();
}

For this entity we precache the model we will be using, then call the underlying precache function of our base class (which in CBaseAnimating's case serves to load the particle effect for fire, since any entity with a model can be ignited). Other precache commands include PrecacheParticleSystem and PrecacheScriptSound.

Spawn()

Valve's Spawn() function is called whenever a new instance of the entity is created, much like its constructor. In fact it is entirely legal to use Spawn() on its own, but for manageability it is recommended that you employ a constructor too to keep variable initialization separate from other code.

//-----------------------------------------------------------------------------
// Purpose: Sets up the entity's initial state
//-----------------------------------------------------------------------------
void CMyModelEntity::Spawn( void )
{
	Precache();

	SetModel( ENTITY_MODEL );
	SetSolid( SOLID_BBOX );
	UTIL_SetSize( this, -Vector(20,20,20), Vector(20,20,20) );
}

We call Precache() first, followed by several CBaseAnimating functions. SetModel() should be obvious if you think back to our earlier define, but SetSolid() needs some explanation. It defines the type of shape that our entity will use to test for collisions with other objects in the world. Using the model itself would be far, far too expensive, so Source offers us a set of compromises:

SOLID_NONE
Not solid.
SOLID_BBOX
Uses an axis-aligned bounding box.
SOLID_BSP
Uses the BSP tree to determine solidity (used for brushes).
SOLID_CUSTOM
Entity defines its own functions for testing collisions.
SOLID_VPHYSICS
Uses a model's embedded collision model to test accurate physics collisions.

These are engine-level choices that mod authors cannot change or add to. We are using SOLID_BBOX, which generates a "bounding box" that is sized by the engine to completely enclose our model. The more expensive SOLID_VPHYSICS, which physically simulates collisions based on the model's embedded collision model, doesn't support the low-level movement functions we'll be using for this entity and should be avoided.

We call UTIL_SetSize() to make our bounding box a cube. This is done because, as bizarre as this might at first sound, bounding boxes cannot rotate. You will need vphysics collisions if you want rotation, and as noted above we aren't using them.

Warning.pngWarning:Spawn() is called immediately after the creation of the entity. If this has occurred at the beginning of a map there is no guarantee that other entities have been spawned yet. Therefore, any code which requires the entity to search or otherwise link itself to other entities is unreliable. Use the Activate() function instead, which is always called after all spawning has completed.

MoveThink()

A think function allows an entity to make decisions without being prompted by an external source. If you think back to our logical entity, it only ever did anything when it received an input; this is clearly no good for something that is meant to move around of its own accord. A think function, if present, is usually the core of the entity's programming.

Here we create a think function that will be called up to 20 times a second. This may sound like a lot, but modern processors are very fast and this entity is very simple. You'll be able to have an awful lot of CMyModelEntitys in a map without running into any CPU issues!

//-----------------------------------------------------------------------------
// Purpose: Think function to randomly move the entity
//-----------------------------------------------------------------------------
void CMyModelEntity::MoveThink( void )
{
	// See if we should change direction again
	if ( m_flNextChangeTime < gpGlobals->curtime )
	{
		// Randomly take a new direction and speed
		Vector vecNewVelocity = RandomVector( -64.0f, 64.0f );
		SetAbsVelocity( vecNewVelocity );

		// Randomly change it again within one to three seconds
		m_flNextChangeTime = gpGlobals->curtime + random->RandomFloat( 1.0f, 3.0f );
	}

	// Snap our facing to where we're heading
	Vector velFacing = GetAbsVelocity();
	QAngle angFacing;
	VectorAngles( velFacing, angFacing );
 	SetAbsAngles( angFacing );

	// Think at 20Hz
	SetNextThink( gpGlobals->curtime + 0.05f );
}

While a lot of code is packed into this function, its outcome is fairly simple. Once a random time interval has elapsed, the entity will choose a new, random direction and speed to travel at. It will also update its angles so that the model visibly faces towards the new direction. This occurs in three dimensions.

Some help:

  • gpGlobals->curtime returns the time at which the code is being executed as a floating point value.
  • Vector variables are used for movement, since they contain information about both facing and speed. SetAbsVelocity() 'Sets' the 'Absolute' 'Velocity' with one.
  • QAngle is simply an angle - a vector minus data about velocity. It's used to set facing.
  • VectorAngles() converts a vector (velFacing) to an angle (angFacing). Remember that C++ is very strict about data types: you need utility functions ,like VectorAngles(), to convert between any two.

Having done all this we call SetNextThink(). This tells the entity when next to run its think function. Here it is set to think again in 0.05 seconds (1/20th), but that number can vary between entities. It’s important to note that failure to use SetNextThink() will cause the entity to stop thinking.

You will have noticed that we are defining new variables here. Like the variables in the class declaration, which are internal to the class, these are internal to this particular function. They are created every time the function is called and destroyed when its execution completes.

Tip.pngTip:We don't really need the vecNewVelocity. See if you can work out how to pass a value to SetAbsVelocity() without creating any new variables. Remember why we put void in front of all of our functions?

InputToggle()

Now we come to our last function. This is an input that will toggle movement on and off.

//-----------------------------------------------------------------------------
// Purpose: Toggle the movement of the entity
//-----------------------------------------------------------------------------
void CMyModelEntity::InputToggle( inputdata_t &inputData )
{
	// Toggle our active state
	if ( !m_bActive )
	{
		// Start thinking
		SetThink( &CMyModelEntity::MoveThink );

		SetNextThink( gpGlobals->curtime + 0.05f );
		
		// Start moving
		SetMoveType( MOVETYPE_FLY );

		// Force MoveThink() to choose a new speed and direction immediately
		m_flNextChangeTime = gpGlobals->curtime;

		// Update m_bActive to reflect our new state
		m_bActive = true;
	}
	else
	{
		// Stop thinking
		SetThink( NULL );
		
		// Stop moving
		SetAbsVelocity( vec3_origin );
 		SetMoveType( MOVETYPE_NONE );
		
		m_bActive = false;
	}
}

This is all very straightforward. We use an if statement to check whether or not m_bActive is true. The exclamation mark means "not": "if m_bActive is not true, do this". Later on, we use the else command to specify what we want to do in any other case - which with a boolean value can only be if m_bActive is true.

When activating the entity we start its think loop by telling Source what think function to use (the default is Think(), but we don't have that here) - note the addition of an & and the omission of any parentheses in the argument. We then tell Source that the entity will move by flying, although this would actually be better-described as "floating" since there is no true simulation of flight in Source (perhaps you could make one?). And, of course, we set m_bActive to true. It isn't going to change itself!

Under the else command we stop the entity from moving. The active think function is set to NULL to stop all thinking, AbsVelocity() is set to the entity's origin, a vector with no movement, the movement type is set to MOVETYPE_NONE to prevent any kind of movement that might be imposed externally, and lastly m_bActive is made false.

FGD entry

The FGD entry for this entity displays the model in Hammer and allows you to name it and send the input "Toggle".

@PointClass base(Targetname) studio("models/gibs/airboat_broken_engine.mdl")= my_model_entity :  "Tutorial model entity."
[
	input Toggle(void) : "Toggle movement."
]

The working entity

my_model_entity in-game.

Place the entity in your map with Hammer. Remember that you need to call the 'toggle' input before it will start moving; you can create another entity (perhaps logic_auto) or use the console command ent_fire my_model_entity toggle to do this.

You'll notice a few things:

The entity doesn't collide with physics objects
The SetAbs* functions interfere with physics calculations. If you want to physically simulate collisions, you'll need to use a different method of movement.
It will dodge around me every time I get in its way
It isn't clear why this happens. Perhaps CBaseAnimating thinks every time its path is blocked?
If I spawn it from the console, it will be stuck halfway inside the wall
You can add this code to your sdk_modelentity.cpp
CON_COMMAND(create_sdk_modelentity, "Creates an instance of the sdk model entity in front of the player.")
{
	Vector vecForward;
	CBasePlayer *pPlayer = UTIL_GetCommandClient();
	if(!pPlayer)
	{
		Warning("Could not determine calling player!\n");
		return;
	}

	AngleVectors( pPlayer->EyeAngles(), &vecForward );
	CBaseEntity *pEnt = CreateEntityByName( "my_model_entity" );
	if ( pEnt )
	{
		Vector vecOrigin = pPlayer->GetAbsOrigin() + vecForward * 256 + Vector(0,0,64);
		QAngle vecAngles(0, pPlayer->GetAbsAngles().y - 90, 0);
		pEnt->SetAbsOrigin(vecOrigin);
		pEnt->SetAbsAngles(vecAngles);
		DispatchSpawn(pEnt);
	}
}
Then type create_sdk_modelentity in the console to spawn the entity.
Alternatively, simply place the entity in Hammer.

Animating this entity

In order to add animation we need a model with animations, in this tutorial we will use the scanner. Change ENTITY_MODEL to "models/combine_scanner.mdl". Then add this to Spawn() function.

// Select the scanner's idle sequence
SetSequence( LookupSequence("idle") );
// Set the animation speed to 100%
SetPlaybackRate( 1.0f );
// Tell the client to animate this model
UseClientSideAnimation();

With any luck you should notice the scanner's "ears" and "face" moving.

See also