Game Functions

Reaching game functions by gamedata name with ISource2ModFunctions — the names the core ships, the startup check, SOURCE2MOD_CALL_FUNCTION, SOURCE2MOD_ORIGINAL, and HookChain on schema helpers.

Game functions are reached by their gamedata name, through ISource2ModFunctions. Find returns the function; Call<Sig> calls it through the hooks and CallOriginal<Sig> past them. In SourcePawn the same entry is Source2ModFunction.Find.

#include "source2mod/ISource2ModFunctions.h"

if (ISource2ModFunction* pSwitchTeam = g_pSource2ModFunctions->Find("CCSPlayerController::SwitchTeam"))
    pSwitchTeam->Call<void(CCSPlayerController*, int)>(pController, 3);

g_pSource2ModFunctions is filled by SOURCE2MOD_SAVEVARS() in Load() (SOURCE2MOD_GLOBALVARS() declares it in your other files). How an entry describes its types, and what Call checks, is on Calling game functions. Module inspection, pattern scanning and pointer arithmetic are on ISource2ModModule and ISource2ModMemory. Reference: ISource2ModFunctions.

Ways to reach a game function

you want to…use
do something the SDK already wraps (give an item, switch team, end the round)the schema helper — pItemServices->GiveNamedItem("weapon_ak47")
call a function the helpers do not wrap, or with arguments they do not exposeg_pSource2ModFunctions->Find(name) and Call<Sig>(...), or SOURCE2MOD_CALL_FUNCTION
call it past every plugin's hooksCallOriginal<Sig>(...), SOURCE2MOD_CALL_FUNCTION with HookChain::Bypass, or the helper with HookChain::Bypass
use an entry with no "function" object, or override its typesFromGameConfig<F>(name) with the function's C++ type
get the raw addressGAMECONFIG_RESOLVE(name)
hook itthe typed hook point if there is one, else HookPoint::Function(fn) with the same ISource2ModFunction — see Function hooks
reach a function the core's gamedata does not haveyour own gamedata entry — see Gamedata

The sample plugin shows the first and the raw way side by side:

plugin.cpp
// A gamedata entry with a "function" object. Find() reads the types from it
// and Call checks yours against them.
if (ISource2ModFunction* pSwitchTeam = g_pSource2ModFunctions->Find("CCSPlayerController::SwitchTeam"))
{
    pSwitchTeam->Call<void(CCSPlayerController*, int)>(pCaller, nNewTeam);
    return;
}

// Any gamedata entry, with the type spelled out by you.
using SwitchTeam_t = void (FASTCALL*)(CCSPlayerController*, unsigned char);

if (auto pfnSwitchTeam = GAMECONFIG_RESOLVE("CCSPlayerController::SwitchTeam").RCast<SwitchTeam_t>())
    pfnSwitchTeam(pCaller, nNewTeam);

// pCaller->SwitchTeam(nNewTeam) does exactly the above.

SOURCE2MOD_CALL_FUNCTION

The macro does the Find once per call site and picks the call by a HookChain. It is how the SDK's schema helpers make their calls. When the entry is missing or does not match the signature nothing is called and the result is value-initialised.

SOURCE2MOD_CALL_FUNCTION(void(CCSPlayerController*, int), "CCSPlayerController::SwitchTeam", HookChain::Run, pController, 3);

FromGameConfig

Find returns null for an entry without a "function" object. FromGameConfig takes the types from you instead, and also gives you a different view of an entry that has one. In C++ you give the function's C++ type and the types are read off it; in a script SetTypes takes the prototype in the gamedata type names. A function from it is the plugin's: freed with Destroy() or when the plugin unloads.

// A free function: void UTIL_Remove(CEntityInstance*).
ISource2ModFunction* pUtilRemove = g_pSource2ModFunctions->FromGameConfig<void(CEntityInstance*)>("UTIL::Remove");

A member function is a pointer-to-member type, this first: FromGameConfig<void (CCSPlayerController::*)(int)>("CCSPlayerController::SwitchTeam") ("void (entity this, int32 team)" in a script).

Calling past the hooks

Once any plugin inline-hooks a function, its first bytes are a jump into the detour, so calling it runs the whole Pre/Post chain.

That is right when you stand in for the game — a plugin dealing damage as if a weapon fired wants the other plugins' rules to apply. It is wrong when you are asking for the function itself — an admin command, a forced round end — where another plugin's rules have no business vetoing what the server was told to do. For that, use CallOriginal or HookChain::Bypass:

SOURCE2MOD_CALL_FUNCTION(int64_t(CBaseEntity*, CTakeDamageInfo*, CTakeDamageResult*), "CBaseEntity::TakeDamageOld",
                         HookChain::Bypass, pPawn, &info, &result);

For a function pointer of your own there is SOURCE2MOD_ORIGINAL (ISource2ModKHook.h):

SOURCE2MOD_ORIGINAL(pfnSwitchTeam)(pCaller, nNewTeam);

SOURCE2MOD_ORIGINAL(fn) casts KHook::FindOriginal(fn) back to fn's type. It is signature-blind, so it works whatever prototype you hold and however the plugin that hooked the function declared its hook. Unhooked functions come back unchanged, so it is always safe to apply.

Apply it at the call; do not cache the result in a global. The address is only the original from the moment a hook exists, and hooks are installed long after the address is resolved.

HookChain on schema helpers

The schema helpers make the same choice through their last argument, a HookChain (ISource2ModTypes.h):

valuethe call goes
HookChain::Runthrough the Pre/Post chain, as if the game made the call
HookChain::Bypassstraight to the original, past every hook — inline detours and vtable hooks alike

The default of each helper is what it always did, so existing calls keep their behaviour. CCSGameRules::TerminateRound and CCSPlayerController::TakeDamage default to Bypass (the server was told to end the round or deal the damage); every other helper defaults to Run.

pItemServices->GiveNamedItem("weapon_ak47");                        // hooks run
pController->TakeDamage(pAttacker, 50, DMG_BULLET, HookChain::Run); // opt in to the hooks
pGameRules->TerminateRound(5.0f, nReason);                          // bypasses by default

Helpers that take a HookChain:

classhelpers
CBaseEntityAcceptInput, AddEntityIOEvent, DispatchSpawn, Teleport, Remove, DispatchParticleEffect
CBaseModelEntitySetModel
CBasePlayerControllerSetPawn
CBasePlayerPawnCommitSuicide, SnapViewAngles
CCSPlayerPawnPostThink
CCSPlayerControllerTakeDamage (Bypass), Respawn, SwitchTeam, ChangeTeam
CCSGameRulesTerminateRound (Bypass), GoToIntermission
CPlayer_ItemServicesGiveNamedItem, DropActivePlayerWeapon, RemoveWeapons
CPlayer_WeaponServicesDropWeapon, BumpWeapon, SelectItem, Destroy
CAttributeListSetOrAddAttribute, SetOrAddAttributeValueByName
grenade projectilesCHEGrenadeProjectile, CFlashbangProjectile, CSmokeGrenadeProjectile, CDecoyProjectile, CMolotovProjectile — EmitGrenade

When to pick which

  • Standing in for the game (a custom weapon dealing damage, a round reward handing out an item): Run. Other plugins' damage rules, item restrictions and so on should apply.
  • Doing what the server was told (admin command, forced round end, a gamemode's own rule): Bypass.
  • Inside a hook on the same function: Bypass, always — Run would re-enter your own handler. See Recursion.

For your own calls through a vtable index, CALL_VIRTUAL_CHAIN(retType, index, eChain, this, args...) (utils/virtual.h) does the same for virtual functions; ResolveHookChain(fn, eChain) does it for a function pointer.

The core's gamedata names

These are entries of the core's gamedata.json. The core scans the required ones at start and refuses to start on a miss, so a game update that breaks one shows right away. The others resolve on first use: Find, FromGameConfig and GAMECONFIG_RESOLVE return null when the signature stopped matching, so check before you call or hook them (a hook on a null function returns 0).

The first use of a name the core did not scan is a pattern scan: keep the pointer instead of looking it up every frame.

Required: entities and players

Every one has a "function" object for Find, except where the table says otherwise.

gamedata namefunction
UTIL::CreateEntityByNameCreateEntityByName — no "function", use FromGameConfig
CBaseEntity::DispatchSpawnCBaseEntity::DispatchSpawn
CBaseEntity::TakeDamageOldCBaseEntity::TakeDamageOld
CTakeDamageInfo::ConstructorCTakeDamageInfo constructor
CBaseModelEntity::SetModelCBaseModelEntity::SetModel
CBasePlayerController::SetPawnCBasePlayerController::SetPawn
CBasePlayerPawn::SnapViewAnglesCBasePlayerPawn::SnapViewAngles
CCSPlayerController::SwitchTeamCCSPlayerController::SwitchTeam
CCSPlayer_WeaponServices::DestroyCPlayer_WeaponServices::Destroy
CCSPlayer_ItemServices::GiveNamedItemCCSPlayer_ItemServices::GiveNamedItem (the full implementation)
CCSPlayerPawn::PostThinkCCSPlayerPawn::PostThink
CCSPlayerPawnBase::CanMoveCCSPlayerPawnBase::CanMove
UTIL::RemoveUTIL_Remove
CAttributeList::SetOrAddAttributeValueByNameCAttributeList::SetOrAddAttributeValueByName
GetWeaponCSDataFromKeyGetWeaponCSDataFromKey
DispatchParticleEffectDispatchParticleEffect
CHEGrenadeProjectile::EmitGrenadeCHEGrenadeProjectile::EmitGrenade
CFlashbangProjectile::EmitGrenadeCFlashbangProjectile::EmitGrenade
CSmokeGrenadeProjectile::EmitGrenadeCSmokeGrenadeProjectile::EmitGrenade
CDecoyProjectile::EmitGrenadeCDecoyProjectile::EmitGrenade
CMolotovProjectile::EmitGrenadeCMolotovProjectile::EmitGrenade

Required: game rules, entity I/O and networking

gamedata namefunction
CCSGameRules::TerminateRoundCCSGameRules::TerminateRound — argument order differs per platform
CEntityInstance::AcceptInputCEntityInstance::AcceptInput
CEntityIOOutput::FireOutputInternalCEntityIOOutput::FireOutputInternal — no "function", use FromGameConfig
CEntitySystem::AddEntityIOEventCEntitySystem::AddEntityIOEvent
CGameEntitySystem::FindEntityByClassNameCGameEntitySystem::FindEntityByClassName — no "function", use FromGameConfig
CGameEntitySystem::FindEntityByNameCGameEntitySystem::FindEntityByName — no "function", use FromGameConfig
LegacyGameEventListenerLegacyGameEventListener

Others: may be null

None of these has a "function" object, so Find returns null for them: use FromGameConfig or GAMECONFIG_RESOLVE.

gamedata namefunction
CEntityIdentity::AcceptInputCEntityIdentity::AcceptInput
CCSPlayer_ItemServices::CanAcquireCCSPlayer_ItemServices::CanAcquire
CCSPlayerController::ProcessUserCmdCCSPlayerController::ProcessUserCmd
CBasePlayerController::OnSimulateUserCommandsCBasePlayerController::OnSimulateUserCommands
CSource2Server::GetNavMeshDataCSource2Server::GetNavMeshData
CLoggingSystem::LogDirectCLoggingSystem::LogDirect (tier0)
Cmd_ExecuteCommandCmd_ExecuteCommand (engine2)

Movement:

gamedata name
CCSPlayer_MovementServices::AirAccelerate
CCSPlayer_MovementServices::AirMove
CCSPlayer_MovementServices::CanUnduck
CCSPlayer_MovementServices::CategorizePosition
CCSPlayer_MovementServices::CheckFalling
CCSPlayer_MovementServices::CheckParameters
CCSPlayer_MovementServices::CheckVelocity
CCSPlayer_MovementServices::CheckWater
CCSPlayer_MovementServices::Duck
CCSPlayer_MovementServices::Friction
CCSPlayer_MovementServices::FullWalkMove
CCSPlayer_MovementServices::GroundAccelerateargument order differs per platform
CCSPlayer_MovementServices::LadderMove
CCSPlayer_MovementServices::MoveInit
CCSPlayer_MovementServices::PlayerMove
CCSPlayer_MovementServices::ProcessMovement
CCSPlayer_MovementServices::SetupMove
CCSPlayer_MovementServices::TryPlayerMove
CCSPlayer_MovementServices::WalkMove
CCSPlayer_MovementServices::WaterMove

Jumping (members of the jump components, not of the movement services):

gamedata name
CCSPlayerLegacyJump::OnJump
CCSPlayerModernJump::OnJump
CCSPlayerLegacyJump::CheckJumpButton
CCSPlayerModernJump::CheckJumpButton

Most of these are typed hook points as well (HookPoint::CanAcquire, HookPoint::AirAccelerate, HookPoint::CheckJumpButtonLegacy, …): hook those rather than the function. When the signature broke, IsAvailable is false and Hook() returns 0.

if (g_pSource2ModHooks->IsAvailable(HookPointId::CheckJumpButtonLegacy))
    g_pSource2ModHooks->Hook(HookPoint::CheckJumpButtonLegacy, HookTarget::All(), OnCheckJumpButtonLegacy);

On this page