Skip to content

Instantly share code, notes, and snippets.

@sigsegv-mvm
Last active March 30, 2024 04:38
Show Gist options
  • Save sigsegv-mvm/9e20ec65af666c45d5eb9657730bf718 to your computer and use it in GitHub Desktop.
Save sigsegv-mvm/9e20ec65af666c45d5eb9657730bf718 to your computer and use it in GitHub Desktop.
A fancy-pants RAII helper class to reduce chances of lag compensation screwups
// example RAII class to help ensure that FinishLagCompensation is called upon leaving scope
class CLagCompensatedSection
{
public:
// start lag compensation upon construction
CLagCompensatedSection(CBasePlayer *player, CUserCmd *cmd) :
m_pPlayer(player)
{
lagcompensation->StartLagCompensation(player, cmd);
}
// guaranteed to finish lag compensation upon destruction (when going out of scope)
~CLagCompensatedSection()
{
lagcompensation->FinishLagCompensation(m_pPlayer);
}
private:
CBasePlayer m_pPlayer;
};
// only do lag compensation in server simulation code, not client prediction code
#ifndef CLIENT_DLL
#define LAG_COMPENSATED_SECTION(player, cmd) CLagCompensatedSection lagcomp(player, cmd)
#else
#define LAG_COMPENSATED_SECTION(player, cmd)
#endif
////////////////////////////////////////////////////////////////////////////////
// example usage by a hypothetical CTFGizmoGadget weapon ///////////////////////
////////////////////////////////////////////////////////////////////////////////
void CTFGizmoGadget::FireWomboWidget()
{
CTFPlayer *pOwner = ToTFPlayer(GetOwnerEntity);
if (!pOwner) return;
LAG_COMPENSATED_SECTION(pOwner, pOwner->GetCurrentCommand());
// at this point, lagcompensation->StartLagCompensation() has been called
DoHitTraceStuff();
if (MaybeWeShouldntActuallyFireAWidget())
{
// by leaving scope, lagcompensation->FinishLagCompensation() will automatically be called
// (we don't even have to remember to do anything, it just happens because we exit scope)
return;
}
ApplyDamageToPlayersWeHit();
// by leaving scope, lagcompensation->FinishLagCompensation() will automatically be called
// (we don't even have to remember to do anything, it just happens because we exit scope)
}
////////////////////////////////////////////////////////////////////////////////
// another example of potential usage //////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void CTFGizmoGadget::UseNeatoAttack()
{
CTFPlayer *pOwner = ToTFPlayer(GetOwnerEntity);
if (!pOwner) return;
DoStuffThatShouldNotBeLagCompensated();
{
LAG_COMPENSATED_SECTION(pOwner, pOwner->GetCurrentCommand());
// at this point, lagcompensation->StartLagCompensation() has been called
DoLagCompensatedStuff();
}
// right here, since the CLagCompensatedSection object goes out of scope,
// lagcompensation->FinishLagCompensation() is automatically called
DoOtherStuffThatShouldNotBeLagCompensated();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment