diff --git a/LagCompensation/gamedata/LagCompensation.games.txt b/LagCompensation/gamedata/LagCompensation.games.txt index 6ba768a..33e8ae5 100644 --- a/LagCompensation/gamedata/LagCompensation.games.txt +++ b/LagCompensation/gamedata/LagCompensation.games.txt @@ -8,36 +8,42 @@ { "library" "server" "linux" "@_Z11UTIL_RemoveP18IServerNetworkable" + "linux64" "@_Z11UTIL_RemoveP18IServerNetworkable" } "CCSGameRules::RestartRound" { "library" "server" "linux" "@_ZN12CCSGameRules12RestartRoundEv" + "linux64" "@_ZN12CCSGameRules12RestartRoundEv" } "CLogicMeasureMovement::SetTarget" { "library" "server" "linux" "@_ZN21CLogicMeasureMovement9SetTargetEPKc" + "linux64" "@_ZN21CLogicMeasureMovement9SetTargetEPKc" } "CEntityTouchManager::FrameUpdatePostEntityThink" { "library" "server" "linux" "@_ZN19CEntityTouchManager26FrameUpdatePostEntityThinkEv" + "linux64" "@_ZN19CEntityTouchManager26FrameUpdatePostEntityThinkEv" } "CalcAbsolutePosition" { "library" "server" "linux" "@_ZN11CBaseEntity20CalcAbsolutePositionEv" + "linux64" "@_ZN11CBaseEntity20CalcAbsolutePositionEv" } "MarkPartitionHandleDirty" { "library" "server" "linux" "@_ZN18CCollisionProperty24MarkPartitionHandleDirtyEv" + "linux64" "@_ZN18CCollisionProperty24MarkPartitionHandleDirtyEv" } } @@ -108,14 +114,25 @@ "CServerNetworkableProperty::m_pOuter" { "linux" "8" + "linux64" "16" "windows" "8" } "CGameRules::EndGameFrame" { "linux" "49" + "linux64" "49" "windows" "48" } + + // variant_t is passed by value to CBaseEntity::AcceptInput. + // x64: string_t in the union is a pointer, so it is 8-byte aligned (eVal at 16, fieldType at 20). + "sizeof(variant_t)" + { + "linux" "20" + "linux64" "24" + "windows" "20" + } } } diff --git a/LagCompensation/scripting/LagCompensation.sp b/LagCompensation/scripting/LagCompensation.sp index 056050a..ac5f741 100644 --- a/LagCompensation/scripting/LagCompensation.sp +++ b/LagCompensation/scripting/LagCompensation.sp @@ -4,8 +4,8 @@ #include #include #include - -#define PLUGIN_VERSION "1.0.4" +#include +#include #define SetBit(%1,%2) ((%1)[(%2) >> 5] |= (1 << ((%2) & 31))) #define ClearBit(%1,%2) ((%1)[(%2) >> 5] &= ~(1 << ((%2) & 31))) @@ -17,15 +17,18 @@ public Plugin myinfo = { name = "LagCompensation", - author = "BotoX", + author = "BotoX, Vauff, .Rushaway, maxime1907", description = "", - version = PLUGIN_VERSION, + version = "1.2.0", url = "" }; bool g_bLateLoad = false; bool g_bHasPhysHooks = true; bool g_bHasOnEntitySpawned = false; +bool g_bCheckPing = false; +bool g_bMapDisabled = false; +int g_iCompenseEntityClass; // Don't change this. #define MAX_EDICTS 2048 @@ -103,6 +106,7 @@ enum struct EntityLagData int iNotMoving; bool bRestore; bool bLateKill; + char sClassname[64]; } LagRecord g_aaLagRecords[MAX_ENTITIES][MAX_RECORDS]; @@ -110,6 +114,12 @@ EntityLagData g_aEntityLagData[MAX_ENTITIES]; int g_iNumEntities = 0; bool g_bCleaningUp = true; +// When more than sm_lagcomp_max_entities entities are lag compensation at the same time we switch off lag compensation +//enabled again on next round or through command +bool g_bLagCompSuspended = false; // nothing new gets compensated +bool g_bReleasePending = false; // the tracked entities still have to be released +int g_iMaxEntities = MAX_ENTITIES; + // Cache int g_iGameTick; float g_fTickInterval; @@ -131,6 +141,8 @@ Handle g_hActivate; Handle g_hAcceptInput; Handle g_hEndGameFrame; +#define PREFIX "{green}[LagCompensation]{default}" + int g_iNetworkableOuter; int g_iParent; int g_iSpawnFlags; @@ -148,6 +160,7 @@ int g_iVecMins; int g_iVecMaxs; int g_iSimulationTime; int g_iCoordinateFrame; +int g_iMinPing; int g_aLagCompensated[MAX_EDICTS] = {-1, ...}; int g_aBlockTriggerTouchPlayers[MAX_EDICTS / 32]; @@ -155,19 +168,25 @@ int g_aaFilterClientSolidTouch[((MAXPLAYERS + 1) * MAX_EDICTS) / 32]; int g_aBlockTriggerMoved[MAX_EDICTS / 32]; int g_aBlacklisted[MAX_EDICTS / 32]; -//Handle g_hCookie_DisableLagComp; -//bool g_bDisableLagComp[MAXPLAYERS + 1]; -//int g_iDisableLagComp[MAXPLAYERS + 1]; - -ConVar g_bLagCompTriggers; -ConVar g_bLagCompPhysboxes; +Handle g_hCookie_LagCompSettings; +bool g_bDisableLagComp[MAXPLAYERS + 1]; +bool g_bPlayerLaserCompensated[MAXPLAYERS + 1]; +bool g_bLagCompMessages[MAXPLAYERS + 1]; +bool g_bSettingsTouched[MAXPLAYERS + 1]; +int g_iDisableLagComp[MAXPLAYERS + 1]; +ConVar g_cvCompenseEntityClass; +ConVar g_cvCheckUserPing; +ConVar g_cvMinimumPing; +ConVar g_cvMaxEntities; public void OnPluginStart() { - CreateConVar("sm_lagcomp_version", PLUGIN_VERSION, "LagCompensation Version", FCVAR_SPONLY|FCVAR_NOTIFY|FCVAR_DONTRECORD).SetString(PLUGIN_VERSION); + LoadTranslations("common.phrases"); - g_bLagCompTriggers = CreateConVar("sm_lagcomp_triggers", "1", "Lag compensate triggers", FCVAR_NONE, true, 0.0, true, 1.0); - g_bLagCompPhysboxes = CreateConVar("sm_lagcomp_physboxes", "1", "Lag compensate physboxes", FCVAR_NONE, true, 0.0, true, 1.0); + g_cvCompenseEntityClass = CreateConVar("sm_lagcomp_entityclass", "0", "Only lagcompensate: [0 = All | 1 = func_physbox only]", _, true, 0.0, true, 1.0); + g_cvCheckUserPing = CreateConVar("sm_lagcomp_checkuserping", "0", "Check user's ping before lagcompensating them [0 = Disabled | 1 = Enabled]", _, true, 0.0, true, 1.0); + g_cvMinimumPing = CreateConVar("sm_lagcomp_ping", "180", "Minimum ping threshold to apply lagcomp on a client", _, true, 0.0); + g_cvMaxEntities = CreateConVar("sm_lagcomp_max_entities", "30", "Maximum entities lag compensated at the same time. Going over it disables lag compensation for everyone until the next round. [1-256]", _, true, 1.0, true, float(MAX_ENTITIES)); AutoExecConfig(true); @@ -287,6 +306,11 @@ public void OnPluginStart() delete hGameData; SetFailState("Failed to DHook CGameRules::EndGameFrame."); } + + // variant_t is 20 bytes on x86 and 24 on x64. + int iVariantSize = GameConfGetOffset(hGameData, "sizeof(variant_t)"); + if(iVariantSize == -1) + iVariantSize = 20; delete hGameData; @@ -327,23 +351,32 @@ public void OnPluginStart() DHookAddParam(g_hAcceptInput, HookParamType_CharPtr); DHookAddParam(g_hAcceptInput, HookParamType_CBaseEntity); DHookAddParam(g_hAcceptInput, HookParamType_CBaseEntity); - DHookAddParam(g_hAcceptInput, HookParamType_Object, 20, DHookPass_ByVal|DHookPass_ODTOR|DHookPass_OCTOR|DHookPass_OASSIGNOP); // variant_t is a union of 12 (float[3]) plus two int type params 12 + 8 = 20 + DHookAddParam(g_hAcceptInput, HookParamType_Object, iVariantSize, DHookPass_ByVal|DHookPass_ODTOR|DHookPass_OCTOR|DHookPass_OASSIGNOP); // variant_t is a union of 12 (float[3]) plus two int type params 12 + 8 = 20 (x64: union padded to 16, so 24) DHookAddParam(g_hAcceptInput, HookParamType_Int); delete hGameData; // Capability provider from https://github.com/alliedmodders/sourcemod/pull/1078 - g_bHasOnEntitySpawned = true; + g_bHasOnEntitySpawned = GetFeatureStatus(FeatureType_Capability, "SDKHook_OnEntitySpawned") == FeatureStatus_Available; - //g_hCookie_DisableLagComp = RegClientCookie("disable_lagcomp", "", CookieAccess_Private); - //RegConsoleCmd("sm_lagcomp", OnToggleLagCompSettings); - //RegConsoleCmd("sm_0ping", OnToggleLagCompSettings); - //SetCookieMenuItem(MenuHandler_CookieMenu, 0, "LagCompensation"); + HookConVarChange(g_cvCompenseEntityClass, OnConVarChanged); + HookConVarChange(g_cvCheckUserPing, OnConVarChanged); + HookConVarChange(g_cvMinimumPing, OnConVarChanged); + HookConVarChange(g_cvMaxEntities, OnConVarChanged); - //CreateTimer(0.1, DisableLagCompTimer, _, TIMER_REPEAT); - RegAdminCmd("sm_unlag", Command_AddLagCompensation, ADMFLAG_RCON, "sm_unlag "); - RegAdminCmd("sm_lagged", Command_CheckLagCompensated, ADMFLAG_GENERIC, "sm_lagged"); + g_hCookie_LagCompSettings = RegClientCookie("lagcomp_settings", "LagCompensation Settings", CookieAccess_Private); + RegConsoleCmd("sm_lagcomp", OnLagCompSettings); + RegConsoleCmd("sm_0ping", OnToggleLagCompSettings); + RegConsoleCmd("sm_0pinglasers", OnToggleLagCompLasersSettings); + RegConsoleCmd("sm_checklag", CheckLagComp); + SetCookieMenuItem(MenuHandler_CookieMenu, 0, "LagCompensation"); + + CreateTimer(0.1, DisableLagCompTimer, _, TIMER_REPEAT); + + RegAdminCmd("sm_unlag", Command_AddLagCompensation, ADMFLAG_ROOT, "sm_unlag [late]"); + RegAdminCmd("sm_lagged", Command_CheckLagCompensated, ADMFLAG_ROOT, "sm_lagged"); + RegAdminCmd("sm_lagcomp_enable", Command_EnableLagCompensation, ADMFLAG_GENERIC, "Re-enables lag compensation after it was disabled for going over sm_lagcomp_max_entities"); FilterClientSolidTouch(g_aaFilterClientSolidTouch, true); BlockTriggerMoved(g_aBlockTriggerMoved, true); @@ -351,13 +384,14 @@ public void OnPluginStart() public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + RegPluginLibrary("LagCompensation"); g_bLateLoad = late; return APLRes_Success; } public void OnLibraryRemoved(const char[] name) { - if(StrEqual(name, "PhysHooks")) + if(strcmp(name, "PhysHooks", false) == 0) g_bHasPhysHooks = false; } @@ -385,8 +419,32 @@ public void OnPluginEnd() } } +public void OnConfigsExecuted() +{ + g_iCompenseEntityClass = GetConVarInt(g_cvCompenseEntityClass); + g_bCheckPing = GetConVarBool(g_cvCheckUserPing); + g_iMinPing = GetConVarInt(g_cvMinimumPing); + g_iMaxEntities = GetConVarInt(g_cvMaxEntities); +} + +void OnConVarChanged(ConVar convar, const char[] oldValue, const char[] newValue) +{ + if (convar == g_cvCompenseEntityClass) + g_iCompenseEntityClass = GetConVarInt(convar); + else if (convar == g_cvCheckUserPing) + g_bCheckPing = GetConVarBool(convar); + else if (convar == g_cvMinimumPing) + g_iMinPing = GetConVarInt(convar); + else if (convar == g_cvMaxEntities) + g_iMaxEntities = GetConVarInt(convar); +} + public void OnMapStart() { + char map[128]; + GetCurrentMap(map, sizeof(map)); + g_bMapDisabled = GetMapLagCompensationDisabled(map); + bool bLate = g_bLateLoad; DHookGamerules(g_hEndGameFrame, true); @@ -435,7 +493,7 @@ public void OnMapStart() OnEntityCreated(entity, sClassname); OnEntitySpawned(entity, sClassname); - if(StrEqual(sClassname, "phys_thruster", false)) + if(strcmp(sClassname, "phys_thruster", false) == 0) { Hook_CPhysForce_Activate(entity); } @@ -452,52 +510,66 @@ public void OnMapEnd() g_bCleaningUp = true; } -//public void OnClientConnected(int client) -//{ -// g_bDisableLagComp[client] = false; -// g_iDisableLagComp[client] = 0; -//} -// -//public void OnClientCookiesCached(int client) -//{ -// char sBuffer[16]; -// GetClientCookie(client, g_hCookie_DisableLagComp, sBuffer, sizeof(sBuffer)); -// if(sBuffer[0]) -// g_bDisableLagComp[client] = true; -// else -// g_bDisableLagComp[client] = false; -//} +public void OnClientConnected(int client) +{ + // Must match the defaults in ParseClientCookie() for clients whose cookies never cache. + g_bDisableLagComp[client] = false; + g_bPlayerLaserCompensated[client] = true; + g_bLagCompMessages[client] = false; + g_bSettingsTouched[client] = false; + g_iDisableLagComp[client] = 0; + g_aLerpTicks[client] = 0; +} + +public void OnClientCookiesCached(int client) +{ + // A toggle made before the cookies arrived wins, so flush it instead of + // overwriting the client's choice with the stored value. + if(g_bSettingsTouched[client]) + { + SaveLagCompSettings(client); + return; + } + + // Load all settings from single cookie + ParseClientCookie(client, g_bDisableLagComp[client], g_bPlayerLaserCompensated[client], g_bLagCompMessages[client]); +} public void OnClientSettingsChanged(int client) { - if(!IsClientInGame(client)) + if(!IsClientInGame(client) || IsFakeClient(client)) return; float fLerpTime = GetEntPropFloat(client, Prop_Data, "m_fLerpTime"); g_aLerpTicks[client] = RoundToNearest(fLerpTime / g_fTickInterval); } -//public void OnClientDisconnect(int client) -//{ -// g_bDisableLagComp[client] = false; -// g_iDisableLagComp[client] = 0; -//} +public void OnClientDisconnect(int client) +{ + g_bDisableLagComp[client] = false; + g_bPlayerLaserCompensated[client] = true; + g_bLagCompMessages[client] = false; + g_bSettingsTouched[client] = false; + g_iDisableLagComp[client] = 0; +} public void OnEntityCreated(int entity, const char[] classname) { if(g_bCleaningUp) return; - if(StrEqual(classname, "phys_thruster", false)) + if (strcmp(classname, "phys_thruster", false) == 0) { DHookEntity(g_hActivate, true, entity); } - else if(StrEqual(classname, "game_ui", false)) + else if (strcmp(classname, "game_ui", false) == 0) { DHookEntity(g_hAcceptInput, true, entity); } - if(!g_bHasOnEntitySpawned) + if (!g_bHasOnEntitySpawned && (!strncmp(classname, "func_physbox", 12, false) || + (g_iCompenseEntityClass == 0 && (strcmp(classname, "trigger_hurt", false) == 0 || + strcmp(classname, "trigger_push", false) == 0 || strcmp(classname, "trigger_teleport", false) == 0)))) { SDKHook(entity, SDKHook_SpawnPost, OnSDKHookEntitySpawnPost); } @@ -527,7 +599,7 @@ public MRESReturn Hook_AcceptInput(int entity, Handle hReturn, Handle hParams) char sCommand[128]; DHookGetParamString(hParams, 1, sCommand, sizeof(sCommand)); - if(!StrEqual(sCommand, "Activate", false)) + if (strcmp(sCommand, "Activate", false) != 0) return MRES_Ignored; if(DHookIsNullParam(hParams, 3)) @@ -590,12 +662,16 @@ void BlacklistChildren(int parent) bool CheckEntityForLagComp(int entity, const char[] classname, bool bRecursive=false, bool bGoodParents=false) { - if(entity < 0 || entity > MAX_EDICTS) + if(entity < 0 || entity >= MAX_EDICTS) return false; if(!IsValidEntity(entity)) return false; + // Disabled for the rest of the round. + if(g_bLagCompSuspended) + return false; + if(g_aLagCompensated[entity] != -1) return false; @@ -603,24 +679,19 @@ bool CheckEntityForLagComp(int entity, const char[] classname, bool bRecursive=f if(SpawnFlags & SF_LAGCOMP_DISABLE) return false; - bool bTrigger = StrEqual(classname, "trigger_hurt", false) || - StrEqual(classname, "trigger_push", false) || - StrEqual(classname, "trigger_teleport", false); + bool bTrigger = false; - if(bTrigger && !g_bLagCompTriggers.BoolValue) - return false; + if (g_iCompenseEntityClass == 0) + bTrigger = strcmp(classname, "trigger_hurt", false) == 0 || strcmp(classname, "trigger_push", false) == 0 || strcmp(classname, "trigger_teleport", false) == 0; bool bPhysbox = !strncmp(classname, "func_physbox", 12, false); - if(bPhysbox && !g_bLagCompPhysboxes.BoolValue) - return false; - bool bBlacklisted = CheckBit(g_aBlacklisted, entity); if(!bTrigger && !bPhysbox || bBlacklisted) return false; - // Don't lag compensate anything that could be parented to a player + // Dont lag compensate anything that could be parented to a player // The player simulation would usually move the entity, // but we would overwrite that position change by restoring the entity to its previous state. int iParent = INVALID_ENT_REFERENCE; @@ -640,7 +711,7 @@ bool CheckEntityForLagComp(int entity, const char[] classname, bool bRecursive=f return false; } - if(CheckBit(g_aBlacklisted, entity)) + if(CheckBit(g_aBlacklisted, iParent)) { return false; } @@ -654,10 +725,10 @@ bool CheckEntityForLagComp(int entity, const char[] classname, bool bRecursive=f if(strncmp(sParentClassname, "func_", 5)) continue; - if(StrEqual(sParentClassname[5], "movelinear") || - StrEqual(sParentClassname[5], "door") || - StrEqual(sParentClassname[5], "rotating") || - StrEqual(sParentClassname[5], "tracktrain")) + if(strcmp(sParentClassname[5], "movelinear", true) == 0 || + strcmp(sParentClassname[5], "door", true) == 0 || + strcmp(sParentClassname[5], "rotating", true) == 0 || + strcmp(sParentClassname[5], "tracktrain", true) == 0) { bGoodParents = true; break; @@ -667,6 +738,14 @@ bool CheckEntityForLagComp(int entity, const char[] classname, bool bRecursive=f if(!bGoodParents) return false; + // One more than allowed: switch lag compensation off until the next round. + //switch lag comp off every round if the map is not allowed to use it + if(g_iNumEntities >= g_iMaxEntities || g_bMapDisabled) + { + SuspendLagCompensation(); + return false; + } + if(AddEntityForLagCompensation(entity, bTrigger)) { if(bTrigger) @@ -708,7 +787,7 @@ public void OnEntityDestroyed(int entity) if(g_bCleaningUp) return; - if(entity < 0 || entity > MAX_EDICTS) + if(entity < 0 || entity >= MAX_EDICTS) return; ClearBit(g_aBlacklisted, entity); @@ -730,7 +809,7 @@ public MRESReturn Detour_OnUTIL_Remove(Handle hParams) return MRES_Ignored; int entity = DHookGetParamObjectPtrVar(hParams, 1, g_iNetworkableOuter, ObjectValueType_CBaseEntityPtr); - if(entity < 0 || entity > MAX_EDICTS) + if(entity < 0 || entity >= MAX_EDICTS) return MRES_Ignored; int iIndex = g_aLagCompensated[entity]; @@ -757,9 +836,32 @@ public MRESReturn Detour_OnRestartRound() { g_bCleaningUp = true; + ReleaseAllEntities(); + + for(int i = 0; i < sizeof(g_aBlacklisted); i++) + g_aBlacklisted[i] = 0; + + // New round, lag compensation is back on. + g_bLagCompSuspended = false; + + g_bCleaningUp = false; + return MRES_Ignored; +} + +// Stops compensating everything that is currently tracked. +void ReleaseAllEntities() +{ + g_bReleasePending = false; + for(int i = 0; i < g_iNumEntities; i++) { int iEntity = g_aEntityLagData[i].iEntity; + bool bValid = IsValidEntity(iEntity); + + // Should never be rewound at this point, but never leave an entity in the past. + if(g_aEntityLagData[i].bRestore && bValid) + RestoreEntityFromRecord(iEntity, g_aaLagRecords[i][g_aEntityLagData[i].iRecordIndex]); + g_aEntityLagData[i].bRestore = false; g_aLagCompensated[iEntity] = -1; ClearBit(g_aBlockTriggerTouchPlayers, iEntity); @@ -770,22 +872,39 @@ public MRESReturn Detour_OnRestartRound() ClearBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); } - if(g_aEntityLagData[i].iDeleted) + if(g_aEntityLagData[i].iDeleted && bValid) { - if(IsValidEntity(iEntity)) - RemoveEdict(iEntity); + ClearBit(g_aBlacklisted, iEntity); + RemoveEdict(iEntity); } g_aEntityLagData[i].iEntity = INVALID_ENT_REFERENCE; } - for(int i = 0; i < sizeof(g_aBlacklisted); i++) - g_aBlacklisted[i] = 0; - g_iNumEntities = 0; +} - g_bCleaningUp = false; - return MRES_Ignored; +void ReleaseAllEntitiesNow() +{ + bool bWasCleaningUp = g_bCleaningUp; + g_bCleaningUp = true; + ReleaseAllEntities(); + g_bCleaningUp = bWasCleaningUp; +} + +void SuspendLagCompensation() +{ + if(g_bLagCompSuspended) + return; + + g_bLagCompSuspended = true; + g_bReleasePending = true; + + for(int client = 1; client <= MaxClients; client++) + { + if(IsClientInGame(client) && !IsFakeClient(client) && !g_bDisableLagComp[client]) + CPrintToChat(client, "%s LagCompensation has been {red}disabled{default} until the next round, too many entities needed to be compensated.", PREFIX); + } } // https://developer.valvesoftware.com/wiki/Logic_measure_movement @@ -829,7 +948,7 @@ public MRESReturn Detour_OnFrameUpdatePostEntityThink() { for(int i = 0; i < g_iNumEntities; i++) { - // Don't make the entity check untouch in FrameUpdatePostEntityThink. + // Dont make the entity check untouch in FrameUpdatePostEntityThink. // If the player didn't get simulated in the current frame then // they didn't have a chance to touch this entity. // Hence the touchlink could be broken and we only let the player check untouch. @@ -837,6 +956,7 @@ public MRESReturn Detour_OnFrameUpdatePostEntityThink() EFlags &= ~EFL_CHECK_UNTOUCH; SetEntData(g_aEntityLagData[i].iEntity, g_iEFlags, EFlags); } + return MRES_Ignored; } @@ -848,7 +968,10 @@ public void OnRunThinkFunctions(bool simulating) public Action OnPlayerRunCmd(int client, int &buttons, int &impulse, float vel[3], float angles[3], int &weapon, int &subtype, int &cmdnum, int &tickcount, int &seed, int mouse[2]) { - if(!IsPlayerAlive(client) || IsFakeClient(client)) + if(!IsClientInGame(client) || !IsPlayerAlive(client) || IsFakeClient(client)) + return Plugin_Continue; + + if(g_bLagCompSuspended) return Plugin_Continue; int iTargetTick = tickcount - g_aLerpTicks[client]; @@ -858,11 +981,11 @@ public Action OnPlayerRunCmd(int client, int &buttons, int &impulse, float vel[3 // hence no new entity record was inserted on the current tick int iDelta = g_iGameTick - iTargetTick - 1; - // The player is stupid and doesn't want lag compensation. + // The player is stupid and doesnt want lag compensation. // To get the original behavior back lets assume they actually have 0 latency. // To avoid abusing toggling lagcomp we increase/decrease this var by 1 every 100ms. // This is so we only skip single ticks at a time. Fully ON = 0, Fully OFF = MAX_RECORDS - //iDelta -= g_iDisableLagComp[client]; + iDelta -= g_iDisableLagComp[client]; if(iDelta < 0) iDelta = 0; @@ -875,7 +998,7 @@ public Action OnPlayerRunCmd(int client, int &buttons, int &impulse, float vel[3 { int iEntity = g_aEntityLagData[i].iEntity; - // Entity too new, the client couldn't even see it yet. + // Entity too new, the client couldnt even see it yet. if(g_aEntityLagData[i].iSpawned > iPlayerSimTick) { SetBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); @@ -899,6 +1022,13 @@ public Action OnPlayerRunCmd(int client, int &buttons, int &impulse, float vel[3 continue; int iRecord = iDelta; + + if(!g_bPlayerLaserCompensated[client] && + (strcmp(g_aEntityLagData[i].sClassname, "trigger_hurt", false) == 0 || + strcmp(g_aEntityLagData[i].sClassname, "trigger_push", false) == 0 || + strcmp(g_aEntityLagData[i].sClassname, "trigger_teleport", false) == 0)) + iRecord = 0; + if(iRecord >= g_aEntityLagData[i].iNumRecords) iRecord = g_aEntityLagData[i].iNumRecords - 1; @@ -929,6 +1059,13 @@ public void OnPostPlayerThinkFunctions() public MRESReturn Hook_EndGameFrame() { + // Lag compensation got disabled this frame, let go of everything. + if(g_bReleasePending) + { + ReleaseAllEntitiesNow(); + return MRES_Ignored; + } + for(int i = 0; i < g_iNumEntities; i++) { if(g_aEntityLagData[i].iDeleted) @@ -1083,23 +1220,28 @@ bool AddEntityForLagCompensation(int iEntity, bool bLateKill) if(g_bCleaningUp) return false; - if(g_iNumEntities == MAX_ENTITIES) - { - char sClassname[64]; - GetEntityClassname(iEntity, sClassname, sizeof(sClassname)); - - char sTargetname[64]; - GetEntPropString(iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); - - int iHammerID = GetEntProp(iEntity, Prop_Data, "m_iHammerID"); - - PrintToBoth("[%d] OUT OF LAGCOMP SLOTS entity %d (%s)\"%s\"(#%d)", GetGameTickCount(), iEntity, sClassname, sTargetname, iHammerID); + // sm_unlag takes an arbitrary index from the console, so validate before indexing anything. + if(iEntity < 0 || iEntity >= MAX_EDICTS || !IsValidEntity(iEntity)) return false; - } if(g_aLagCompensated[iEntity] != -1) return false; + char sClassname[64]; + GetEntityClassname(iEntity, sClassname, sizeof(sClassname)); + + char sTargetname[64]; + GetEntPropString(iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); + + int iHammerID = GetEntProp(iEntity, Prop_Data, "m_iHammerID"); + + if(g_iNumEntities >= MAX_ENTITIES) + { + PrintToBoth("[%d] OUT OF LAGCOMP SLOTS entity %d (%s)\"%s\"(#%d)", GetGameTickCount(), iEntity, sClassname, sTargetname, iHammerID); + LogError("OUT OF LAGCOMP SLOTS entity %d (%s)\"%s\"(#%d)", iEntity, sClassname, sTargetname, iHammerID); + return false; + } + int i = g_iNumEntities; g_iNumEntities++; @@ -1114,6 +1256,7 @@ bool AddEntityForLagCompensation(int iEntity, bool bLateKill) g_aEntityLagData[i].iNotMoving = MAX_RECORDS; g_aEntityLagData[i].bRestore = false; g_aEntityLagData[i].bLateKill = bLateKill; + g_aEntityLagData[i].sClassname = sClassname; if(bLateKill) { @@ -1121,18 +1264,7 @@ bool AddEntityForLagCompensation(int iEntity, bool bLateKill) } RecordDataIntoRecord(iEntity, g_aaLagRecords[i][0]); - - { - char sClassname[64]; - GetEntityClassname(iEntity, sClassname, sizeof(sClassname)); - - char sTargetname[64]; - GetEntPropString(iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); - - int iHammerID = GetEntProp(iEntity, Prop_Data, "m_iHammerID"); - - PrintToBoth("[%d] added entity %d (%s)\"%s\"(#%d) under index %d", GetGameTickCount(), iEntity, sClassname, sTargetname, iHammerID, i); - } + PrintToBoth("[%d] added entity %d (%s)\"%s\"(#%d) under index %d", GetGameTickCount(), iEntity, sClassname, sTargetname, iHammerID, i); return true; } @@ -1207,6 +1339,7 @@ void EntityLagData_Copy(EntityLagData obj, const EntityLagData other) obj.iNotMoving = other.iNotMoving; obj.bRestore = other.bRestore; obj.bLateKill = other.bLateKill; + obj.sClassname = other.sClassname; } void LagRecord_Copy(LagRecord obj, const LagRecord other) @@ -1234,6 +1367,59 @@ bool CompareVectors(const float vec1[3], const float vec2[3]) return vec1[0] == vec2[0] && vec1[1] == vec2[1] && vec1[2] == vec2[2]; } +void SaveLagCompSettings(int client) +{ + // Remember that this client chose something, so OnClientCookiesCached + // flushes it rather than loading over the top of it. + g_bSettingsTouched[client] = true; + + // Cookie reads/writes are meaningless until the cookies arrive; we get called back then. + if(!AreClientCookiesCached(client)) + return; + + // Read current cookie values + bool currentDisableLagComp, currentPlayerLaserCompensated, currentLagCompMessages; + ParseClientCookie(client, currentDisableLagComp, currentPlayerLaserCompensated, currentLagCompMessages); + + // Check if values have changed + bool disableChanged = g_bDisableLagComp[client] != currentDisableLagComp; + bool laserChanged = g_bPlayerLaserCompensated[client] != currentPlayerLaserCompensated; + bool messagesChanged = g_bLagCompMessages[client] != currentLagCompMessages; + + // If no values have changed, no need to save + if (!disableChanged && !laserChanged && !messagesChanged) { + return; + } + + // Otherwise, save the chain format + char sBuffer[8]; + Format(sBuffer, sizeof(sBuffer), "%d%d%d", + g_bDisableLagComp[client] ? 1 : 0, + g_bPlayerLaserCompensated[client] ? 1 : 0, + g_bLagCompMessages[client] ? 1 : 0); + SetClientCookie(client, g_hCookie_LagCompSettings, sBuffer); +} + +void ParseClientCookie(int client, bool &disableLagComp, bool &playerLaserCompensated, bool &lagCompMessages) +{ + char buffer[16]; + GetClientCookie(client, g_hCookie_LagCompSettings, buffer, sizeof(buffer)); + + // Parse chain format: disable|laser|messages + if (strlen(buffer) >= 3) + { + disableLagComp = (buffer[0] == '1'); + playerLaserCompensated = (buffer[1] == '1'); + lagCompMessages = (buffer[2] == '1'); + } + else + { + // Default values + disableLagComp = false; + playerLaserCompensated = true; + lagCompMessages = false; + } +} public Action Command_AddLagCompensation(int client, int argc) { @@ -1255,11 +1441,43 @@ public Action Command_AddLagCompensation(int client, int argc) late = view_as(StringToInt(sArgs)); } + if(g_bLagCompSuspended) + { + ReplyToCommand(client, "[SM] LagCompensation is disabled until the next round, use sm_lagcomp_enable first."); + return Plugin_Handled; + } + AddEntityForLagCompensation(entity, late); return Plugin_Handled; } +public Action Command_EnableLagCompensation(int client, int argc) +{ + if(!g_bLagCompSuspended) + { + ReplyToCommand(client, "[SM] LagCompensation is already enabled."); + return Plugin_Handled; + } + + // Let go of whatever was tracked before it got disabled, so only + // entities that spawn from now on are compensated. + if(g_bReleasePending) + ReleaseAllEntitiesNow(); + + g_bLagCompSuspended = false; + + ReplyToCommand(client, "[SM] LagCompensation has been re-enabled."); + + for(int i = 1; i <= MaxClients; i++) + { + if(IsClientInGame(i) && !IsFakeClient(i) && !g_bDisableLagComp[i]) + CPrintToChat(i, "%s LagCompensation has been {green}re-enabled{default} by an admin.", PREFIX); + } + + return Plugin_Handled; +} + public Action Command_CheckLagCompensated(int client, int argc) { if(argc == 0) @@ -1277,6 +1495,9 @@ public Action Command_CheckLagCompensated(int client, int argc) PrintToConsole(client, "%2d. #%d %s \"%s\" (#%d)", i, g_aEntityLagData[i].iEntity, sClassname, sTargetname, iHammerID); } + PrintToConsole(client, "Active: %d / %d%s", g_iNumEntities, g_iMaxEntities, + g_bLagCompSuspended ? " | DISABLED until next round (over the limit)" : ""); + return Plugin_Handled; } @@ -1336,101 +1557,207 @@ stock void PrintToBoth(const char[] format, any ...) for(int client = 1; client <= MaxClients; client++) { - if(IsClientInGame(client)) + if (IsClientInGame(client) && g_bLagCompMessages[client] && CheckCommandAccess(client, "sm_lagged", ADMFLAG_ROOT)) { PrintToConsole(client, "%s", buffer); } } } -//public Action DisableLagCompTimer(Handle timer) -//{ -// for(int client = 1; client <= MaxClients; client++) -// { -// if(g_bDisableLagComp[client] && g_iDisableLagComp[client] < MAX_RECORDS) -// { -// g_iDisableLagComp[client]++; -// } -// else if(!g_bDisableLagComp[client] && g_iDisableLagComp[client] > 0) -// { -// g_iDisableLagComp[client]--; -// } -// } -// -// return Plugin_Continue; -//} -// -//public Action OnLagCompSettings(int client, int args) -//{ -// ShowSettingsMenu(client); -// return Plugin_Handled; -//} +public Action DisableLagCompTimer(Handle timer) +{ + for(int client = 1; client <= MaxClients; client++) + { + if(!IsClientInGame(client) || !IsPlayerAlive(client) || IsFakeClient(client)) + continue; -//public Action OnToggleLagCompSettings(int client, int args) -//{ -// ToggleLagCompSettings(client); -// return Plugin_Handled; -//} -// -//public void ToggleLagCompSettings(int client) -//{ -// if(!client) -// return; -// -// g_bDisableLagComp[client] = !g_bDisableLagComp[client]; -// SetClientCookie(client, g_hCookie_DisableLagComp, g_bDisableLagComp[client] ? "1" : ""); -// -// PrintToChat(client, "\x04[LagCompensation]\x01 LagCompensation has been %s.", g_bDisableLagComp[client] ? "disabled" : "enabled"); -//} -// -//public void ShowSettingsMenu(int client) -//{ -// Menu menu = new Menu(MenuHandler_MainMenu); -// menu.SetTitle("LagCompensation Settings", client); -// menu.ExitBackButton = true; -// -// char sBuffer[128]; -// Format(sBuffer, sizeof(sBuffer), "LagCompensation: %s", g_bDisableLagComp[client] ? "Disabled" : "Enabled"); -// menu.AddItem("0", sBuffer); -// -// menu.Display(client, MENU_TIME_FOREVER); -//} -// -//public void MenuHandler_CookieMenu(int client, CookieMenuAction action, any info, char[] buffer, int maxlen) -//{ -// switch(action) -// { -// case(CookieMenuAction_DisplayOption): -// { -// Format(buffer, maxlen, "LagCompensation", client); -// } -// case(CookieMenuAction_SelectOption): -// { -// ShowSettingsMenu(client); -// } -// } -//} -// -//public int MenuHandler_MainMenu(Menu menu, MenuAction action, int client, int selection) -//{ -// switch(action) -// { -// case(MenuAction_Select): -// { -// switch(selection) -// { -// case(0): ToggleLagCompSettings(client); -// } -// -// ShowSettingsMenu(client); -// } -// case(MenuAction_Cancel): -// { -// ShowCookieMenu(client); -// } -// case(MenuAction_End): -// { -// delete menu; -// } -// } -//} + // https://github.com/ValveSoftware/source-sdk-2013/blob/master/sp/src/game/server/util.cpp#L747 + // Lag compensation only kicks in above the ping threshold, so ramp it off below it. + if (g_bCheckPing) + { + int iAvgPing = RoundFloat(GetClientAvgLatency(client, NetFlow_Outgoing) * 1000); + + if (iAvgPing <= g_iMinPing) + { + if(g_iDisableLagComp[client] < MAX_RECORDS) + g_iDisableLagComp[client]++; + + continue; + } + } + + if(g_bDisableLagComp[client] && g_iDisableLagComp[client] < MAX_RECORDS) + { + g_iDisableLagComp[client]++; + } + else if(!g_bDisableLagComp[client] && g_iDisableLagComp[client] > 0) + { + g_iDisableLagComp[client]--; + } + } + + return Plugin_Continue; +} + +public Action OnLagCompSettings(int client, int args) +{ + ShowSettingsMenu(client); + return Plugin_Handled; +} + +public Action OnToggleLagCompSettings(int client, int args) +{ + ToggleLagCompSettings(client); + return Plugin_Handled; +} + +public Action OnToggleLagCompLasersSettings(int client, int args) +{ + ToggleLagCompLasers(client); + return Plugin_Handled; +} + +public void ToggleLagCompSettings(int client) +{ + if(!client || !IsClientInGame(client) || IsFakeClient(client)) + return; + + g_bDisableLagComp[client] = !g_bDisableLagComp[client]; + SaveLagCompSettings(client); + + CPrintToChat(client, "%s LagCompensation has been %s.", PREFIX, g_bDisableLagComp[client] ? "disabled" : "enabled"); + + if(!g_bDisableLagComp[client] && g_bLagCompSuspended) + CPrintToChat(client, "%s It is currently {red}disabled{default} for everyone until the next round (too many entities).", PREFIX); +} + +public void ToggleLagCompLasers(int client) +{ + if(!client || !IsClientInGame(client) || IsFakeClient(client)) + return; + + g_bPlayerLaserCompensated[client] = !g_bPlayerLaserCompensated[client]; + SaveLagCompSettings(client); + + CPrintToChat(client, "%s LagCompensation for Lasers has been %s.", PREFIX, g_bPlayerLaserCompensated[client] ? "enabled" : "disabled"); + if (g_bCheckPing && g_bPlayerLaserCompensated[client]) + CPrintToChat(client, "%s It will take effect if your real ping is higher than %dms.", PREFIX, g_iMinPing); +} + +public void ToggleLagCompMessages(int client) +{ + if(!client || !IsClientInGame(client) || IsFakeClient(client)) + return; + + g_bLagCompMessages[client] = !g_bLagCompMessages[client]; + SaveLagCompSettings(client); + + CPrintToChat(client, "%s LagCompensation messages have been %s.", PREFIX, g_bLagCompMessages[client] ? "enabled" : "disabled"); +} + +public Action CheckLagComp(int client, int args) +{ + if (args > 1 || (args == 0 && !client)) + { + CReplyToCommand(client, "%s Usage: sm_checklag ", PREFIX); + return Plugin_Handled; + } + + int target = -1; + char sEnable[64]; + FormatEx(sEnable, sizeof(sEnable), "enabled (%s)", g_iCompenseEntityClass == 0 ? "Triggers and func_physbox" : "func_physbox only"); + + if (args == 0) + target = client; + else + { + char arg1[65]; + GetCmdArg(1, arg1, sizeof(arg1)); + target = FindTarget(client, arg1, true, false); + } + + if (target == -1) + { + CReplyToCommand(client, "%s Invalid target.", PREFIX); + return Plugin_Handled; + } + + CReplyToCommand(client, "%s LagCompensation is %s for {olive}%N", PREFIX, g_bDisableLagComp[target] ? "disabled" : sEnable, target); + CReplyToCommand(client, "%s Laser compensation: %s", PREFIX, g_bPlayerLaserCompensated[target] ? "enabled" : "disabled"); + + if(g_bLagCompSuspended) + CReplyToCommand(client, "%s Server status: {red}disabled{default} for everyone until the next round (more than %d entities needed to be compensated).", PREFIX, g_iMaxEntities); + else + CReplyToCommand(client, "%s Server status: {green}active{default}.", PREFIX); + + // g_iDisableLagComp also ramps from the ping threshold, so report it when they haven't opted out. + if(!g_bDisableLagComp[target] && g_iDisableLagComp[target] > 0) + CReplyToCommand(client, "%s Currently reduced: %d of %d ticks skipped%s.", PREFIX, + g_iDisableLagComp[target], MAX_RECORDS, + g_bCheckPing ? " (ping at or below the threshold ramps this up)" : ""); + + return Plugin_Handled; +} + +public void ShowSettingsMenu(int client) +{ + Menu menu = new Menu(MenuHandler_MainMenu); + if(g_bLagCompSuspended) + menu.SetTitle("LagCompensation Settings\nCurrently disabled until the next round (too many entities)"); + else + menu.SetTitle("LagCompensation Settings"); + menu.ExitBackButton = true; + + char buffer[128], buffer_lasers[128], msg_buffer[128]; + Format(buffer, sizeof(buffer), "LagCompensation: %s", g_bDisableLagComp[client] ? "Disabled" : "Enabled"); + Format(buffer_lasers, sizeof(buffer_lasers), "LagCompensation for Lasers: %s", g_bPlayerLaserCompensated[client] ? "Enabled" : "Disabled"); + Format(msg_buffer, sizeof(msg_buffer), "LagCompensation Messages: %s", g_bLagCompMessages[client] ? "Enabled" : "Disabled"); + + menu.AddItem("0", buffer); + menu.AddItem("1", buffer_lasers); + menu.AddItem("2", msg_buffer, CheckCommandAccess(client, "sm_lagged", ADMFLAG_ROOT) ? ITEMDRAW_DEFAULT : ITEMDRAW_DISABLED); + + menu.Display(client, MENU_TIME_FOREVER); +} + +public void MenuHandler_CookieMenu(int client, CookieMenuAction action, any info, char[] buffer, int maxlen) +{ + switch(action) + { + case(CookieMenuAction_DisplayOption): + { + strcopy(buffer, maxlen, "LagCompensation"); + } + case(CookieMenuAction_SelectOption): + { + ShowSettingsMenu(client); + } + } +} + +public int MenuHandler_MainMenu(Menu menu, MenuAction action, int client, int selection) +{ + switch(action) + { + case(MenuAction_Select): + { + switch(selection) + { + case(0): ToggleLagCompSettings(client); + case(1): ToggleLagCompLasers(client); + case(2): ToggleLagCompMessages(client); + } + + ShowSettingsMenu(client); + } + case(MenuAction_Cancel): + { + ShowCookieMenu(client); + } + case(MenuAction_End): + { + delete menu; + } + } + return 0; +} diff --git a/LagCompensation/scripting/LagCompensation_nide_edit-old.sp b/LagCompensation/scripting/LagCompensation_nide_edit-old.sp deleted file mode 100644 index 43973b5..0000000 --- a/LagCompensation/scripting/LagCompensation_nide_edit-old.sp +++ /dev/null @@ -1,1592 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#define SetBit(%1,%2) ((%1)[(%2) >> 5] |= (1 << ((%2) & 31))) -#define ClearBit(%1,%2) ((%1)[(%2) >> 5] &= ~(1 << ((%2) & 31))) -#define CheckBit(%1,%2) !!((%1)[(%2) >> 5] & (1 << ((%2) & 31))) - -#pragma semicolon 1 -#pragma newdecls required - -public Plugin myinfo = -{ - name = "LagCompensation", - author = "BotoX, Vauff, .Rushaway, maxime1907", - description = "", - version = "1.1.0", - url = "" -}; - -bool g_bLateLoad = false; -bool g_bHasPhysHooks = true; -bool g_bHasOnEntitySpawned = false; -bool g_bCheckPing = false; -int g_iCompenseEntityClass; - -// Don't change this. -#define MAX_EDICTS 2048 -#define FSOLID_FORCE_WORLD_ALIGNED 0x0040 -#define FSOLID_ROOT_PARENT_ALIGNED 0x0100 -#define EFL_DIRTY_ABSTRANSFORM (1<<11) -#define EFL_DIRTY_SURROUNDING_COLLISION_BOUNDS (1<<14) -#define EFL_CHECK_UNTOUCH (1<<24) -#define COORDINATE_FRAME_SIZE 14 - -enum -{ - USE_OBB_COLLISION_BOUNDS = 0, - USE_BEST_COLLISION_BOUNDS, - USE_HITBOXES, - USE_SPECIFIED_BOUNDS, - USE_GAME_CODE, - USE_ROTATION_EXPANDED_BOUNDS, - USE_COLLISION_BOUNDS_NEVER_VPHYSICS, -} - -enum -{ - SOLID_NONE = 0, // no solid model - SOLID_BSP = 1, // a BSP tree - SOLID_BBOX = 2, // an AABB - SOLID_OBB = 3, // an OBB (not implemented yet) - SOLID_OBB_YAW = 4, // an OBB, constrained so that it can only yaw - SOLID_CUSTOM = 5, // Always call into the entity for tests - SOLID_VPHYSICS = 6, // solid vphysics object, get vcollide from the model and collide with that - SOLID_LAST, -}; - -enum -{ - SF_TRIGGER_ALLOW_CLIENTS = 0x01, // Players can fire this trigger - SF_TRIGGER_ALLOW_NPCS = 0x02, // NPCS can fire this trigger - SF_TRIGGER_ALLOW_PUSHABLES = 0x04, // Pushables can fire this trigger - SF_TRIGGER_ALLOW_PHYSICS = 0x08, // Physics objects can fire this trigger - SF_TRIGGER_ONLY_PLAYER_ALLY_NPCS = 0x10, // *if* NPCs can fire this trigger, this flag means only player allies do so - SF_TRIGGER_ONLY_CLIENTS_IN_VEHICLES = 0x20, // *if* Players can fire this trigger, this flag means only players inside vehicles can - SF_TRIGGER_ALLOW_ALL = 0x40, // Everything can fire this trigger EXCEPT DEBRIS! - SF_TRIGGER_ONLY_CLIENTS_OUT_OF_VEHICLES = 0x200, // *if* Players can fire this trigger, this flag means only players outside vehicles can - SF_TRIG_PUSH_ONCE = 0x80, // trigger_push removes itself after firing once - SF_TRIG_PUSH_AFFECT_PLAYER_ON_LADDER = 0x100, // if pushed object is player on a ladder, then this disengages them from the ladder (HL2only) - SF_TRIG_TOUCH_DEBRIS = 0x400, // Will touch physics debris objects - SF_TRIGGER_ONLY_NPCS_IN_VEHICLES = 0x800, // *if* NPCs can fire this trigger, only NPCs in vehicles do so (respects player ally flag too) -}; - -#define SF_LAGCOMP_DISABLE (1 << 30) - -#define MAX_RECORDS 32 -#define MAX_ENTITIES 256 - -enum struct LagRecord -{ - float vecOrigin[3]; - float vecAbsOrigin[3]; - float angRotation[3]; - float angAbsRotation[3]; - float vecMins[3]; - float vecMaxs[3]; - float flSimulationTime; - float rgflCoordinateFrame[COORDINATE_FRAME_SIZE]; -} - -enum struct EntityLagData -{ - int iEntity; - int iRecordIndex; - int iNumRecords; - int iRecordsValid; - int iSpawned; - int iDeleted; - int iNotMoving; - bool bRestore; - bool bLateKill; - char sClassname[64]; -} - -LagRecord g_aaLagRecords[MAX_ENTITIES][MAX_RECORDS]; -EntityLagData g_aEntityLagData[MAX_ENTITIES]; -int g_iNumEntities = 0; -bool g_bCleaningUp = true; - -// Cache -int g_iGameTick; -float g_fTickInterval; -int g_aLerpTicks[MAXPLAYERS + 1]; - -// SDKCall -Handle g_hCalcAbsolutePosition; -Handle g_hMarkPartitionHandleDirty; - -// DHooks Detour -Handle g_hUTIL_Remove; -Handle g_hRestartRound; -Handle g_hSetTarget; -Handle g_hSetTargetPost; -Handle g_hFrameUpdatePostEntityThink; - -// DHooks Virtual -Handle g_hActivate; -Handle g_hAcceptInput; -Handle g_hEndGameFrame; - -#define PREFIX "{green}[LagCompensation]{default}" - -int g_iNetworkableOuter; -int g_iParent; -int g_iSpawnFlags; -int g_iCollision; -int g_iSolidFlags; -int g_iSolidType; -int g_iSurroundType; -int g_iEFlags; - -int g_iVecOrigin; -int g_iVecAbsOrigin; -int g_iAngRotation; -int g_iAngAbsRotation; -int g_iVecMins; -int g_iVecMaxs; -int g_iSimulationTime; -int g_iCoordinateFrame; -int g_iMinPing; - -int g_aLagCompensated[MAX_EDICTS] = {-1, ...}; -int g_aBlockTriggerTouchPlayers[MAX_EDICTS / 32]; -int g_aaFilterClientSolidTouch[((MAXPLAYERS + 1) * MAX_EDICTS) / 32]; -int g_aBlockTriggerMoved[MAX_EDICTS / 32]; -int g_aBlacklisted[MAX_EDICTS / 32]; - -Handle g_hCookie_LagCompSettings; -bool g_bDisableLagComp[MAXPLAYERS + 1]; -bool g_bPlayerLaserCompensated[MAXPLAYERS + 1]; -bool g_bLagCompMessages[MAXPLAYERS + 1]; -int g_iDisableLagComp[MAXPLAYERS + 1]; -ConVar g_cvCompenseEntityClass; -ConVar g_cvCheckUserPing; -ConVar g_cvMinimumPing; - -public void OnPluginStart() -{ - LoadTranslations("common.phrases"); - - g_cvCompenseEntityClass = CreateConVar("sm_lagcomp_entityclass", "0", "Only lagcompensate: [0 = All | 1 = func_physbox only]", _, true, 0.0, true, 1.0); - g_cvCheckUserPing = CreateConVar("sm_lagcomp_checkuserping", "0", "Check user's ping before lagcompensating them [0 = Disabled | 1 = Enabled]", _, true, 0.0, true, 1.0); - g_cvMinimumPing = CreateConVar("sm_lagcomp_ping", "180", "Minimum ping threshold to apply lagcomp on a client", _, true, 0.0); - - AutoExecConfig(true); - - Handle hGameData = LoadGameConfigFile("LagCompensation.games"); - if(!hGameData) - SetFailState("Failed to load LagCompensation gamedata."); - - // CBaseEntity::CalcAbsolutePosition - StartPrepSDKCall(SDKCall_Entity); - if(!PrepSDKCall_SetFromConf(hGameData, SDKConf_Signature, "CalcAbsolutePosition")) - { - delete hGameData; - SetFailState("PrepSDKCall_SetFromConf(hGameData, SDKConf_Signature, \"CalcAbsolutePosition\") failed!"); - } - g_hCalcAbsolutePosition = EndPrepSDKCall(); - - // CCollisionProperty::MarkPartitionHandleDirty - StartPrepSDKCall(SDKCall_Raw); - if(!PrepSDKCall_SetFromConf(hGameData, SDKConf_Signature, "MarkPartitionHandleDirty")) - { - delete hGameData; - SetFailState("PrepSDKCall_SetFromConf(hGameData, SDKConf_Signature, \"MarkPartitionHandleDirty\") failed!"); - } - g_hMarkPartitionHandleDirty = EndPrepSDKCall(); - - - // ::UTIL_Remove - g_hUTIL_Remove = DHookCreateFromConf(hGameData, "UTIL_Remove"); - if(!g_hUTIL_Remove) - { - delete hGameData; - SetFailState("Failed to setup detour for UTIL_Remove"); - } - - if(!DHookEnableDetour(g_hUTIL_Remove, false, Detour_OnUTIL_Remove)) - { - delete hGameData; - SetFailState("Failed to detour UTIL_Remove."); - } - - // CCSGameRules::RestartRound - g_hRestartRound = DHookCreateFromConf(hGameData, "CCSGameRules__RestartRound"); - if(!g_hRestartRound) - { - delete hGameData; - SetFailState("Failed to setup detour for CCSGameRules__RestartRound"); - } - - if(!DHookEnableDetour(g_hRestartRound, false, Detour_OnRestartRound)) - { - delete hGameData; - SetFailState("Failed to detour CCSGameRules__RestartRound."); - } - - // CLogicMeasureMovement::SetTarget - g_hSetTarget = DHookCreateFromConf(hGameData, "CLogicMeasureMovement__SetTarget"); - if(!g_hSetTarget) - { - delete hGameData; - SetFailState("Failed to setup detour for CLogicMeasureMovement__SetTarget"); - } - - if(!DHookEnableDetour(g_hSetTarget, false, Detour_OnSetTargetPre)) - { - delete hGameData; - SetFailState("Failed to detour CLogicMeasureMovement__SetTarget."); - } - - // CLogicMeasureMovement::SetTarget (fix post hook crashing due to this pointer being overwritten) - g_hSetTargetPost = DHookCreateFromConf(hGameData, "CLogicMeasureMovement__SetTarget_post"); - if(!g_hSetTargetPost) - { - delete hGameData; - SetFailState("Failed to setup detour for CLogicMeasureMovement__SetTarget_post"); - } - - if(!DHookEnableDetour(g_hSetTargetPost, true, Detour_OnSetTargetPost)) - { - delete hGameData; - SetFailState("Failed to detour CLogicMeasureMovement__SetTarget_post."); - } - - // CEntityTouchManager::FrameUpdatePostEntityThink - g_hFrameUpdatePostEntityThink = DHookCreateFromConf(hGameData, "CEntityTouchManager__FrameUpdatePostEntityThink"); - if(!g_hFrameUpdatePostEntityThink) - { - delete hGameData; - SetFailState("Failed to setup detour for CEntityTouchManager__FrameUpdatePostEntityThink"); - } - - if(!DHookEnableDetour(g_hFrameUpdatePostEntityThink, false, Detour_OnFrameUpdatePostEntityThink)) - { - delete hGameData; - SetFailState("Failed to detour CEntityTouchManager__FrameUpdatePostEntityThink."); - } - - - g_iNetworkableOuter = GameConfGetOffset(hGameData, "CServerNetworkableProperty::m_pOuter"); - if(g_iNetworkableOuter == -1) - { - delete hGameData; - SetFailState("GameConfGetOffset(hGameData, \"CServerNetworkableProperty::m_pOuter\") failed!"); - } - - - int offset = GameConfGetOffset(hGameData, "CGameRules::EndGameFrame"); - if(offset == -1) - { - delete hGameData; - SetFailState("Failed to find CGameRules::EndGameFrame offset."); - } - - // CGameRules::EndGameFrame - g_hEndGameFrame = DHookCreate(offset, HookType_GameRules, ReturnType_Void, ThisPointer_Ignore, Hook_EndGameFrame); - if(g_hEndGameFrame == INVALID_HANDLE) - { - delete hGameData; - SetFailState("Failed to DHook CGameRules::EndGameFrame."); - } - delete hGameData; - - - hGameData = LoadGameConfigFile("sdktools.games"); - if(!hGameData) - SetFailState("Failed to load sdktools gamedata."); - - offset = GameConfGetOffset(hGameData, "Activate"); - if(offset == -1) - { - delete hGameData; - SetFailState("Failed to find Activate offset"); - } - - // CPhysForce::Activate - g_hActivate = DHookCreate(offset, HookType_Entity, ReturnType_Void, ThisPointer_CBaseEntity, Hook_CPhysForce_Activate); - if(g_hActivate == INVALID_HANDLE) - { - delete hGameData; - SetFailState("Failed to DHookCreate Activate"); - } - - offset = GameConfGetOffset(hGameData, "AcceptInput"); - if(offset == -1) - { - delete hGameData; - SetFailState("Failed to find AcceptInput offset."); - } - - // CBaseEntity::AcceptInput( const char *szInputName, CBaseEntity *pActivator, CBaseEntity *pCaller, variant_t Value, int outputID ) - g_hAcceptInput = DHookCreate(offset, HookType_Entity, ReturnType_Bool, ThisPointer_CBaseEntity, Hook_AcceptInput); - if(g_hAcceptInput == INVALID_HANDLE) - { - delete hGameData; - SetFailState("Failed to DHook AcceptInput."); - } - - DHookAddParam(g_hAcceptInput, HookParamType_CharPtr); - DHookAddParam(g_hAcceptInput, HookParamType_CBaseEntity); - DHookAddParam(g_hAcceptInput, HookParamType_CBaseEntity); - DHookAddParam(g_hAcceptInput, HookParamType_Object, 20, DHookPass_ByVal|DHookPass_ODTOR|DHookPass_OCTOR|DHookPass_OASSIGNOP); // variant_t is a union of 12 (float[3]) plus two int type params 12 + 8 = 20 - DHookAddParam(g_hAcceptInput, HookParamType_Int); - - delete hGameData; - - // Capability provider from https://github.com/alliedmodders/sourcemod/pull/1078 - g_bHasOnEntitySpawned = GetFeatureStatus(FeatureType_Capability, "SDKHook_OnEntitySpawned") == FeatureStatus_Available; - - HookConVarChange(g_cvCompenseEntityClass, OnConVarChanged); - HookConVarChange(g_cvCheckUserPing, OnConVarChanged); - HookConVarChange(g_cvMinimumPing, OnConVarChanged); - - - g_hCookie_LagCompSettings = RegClientCookie("lagcomp_settings", "LagCompensation Settings", CookieAccess_Private); - RegConsoleCmd("sm_lagcomp", OnToggleLagCompSettings); - RegConsoleCmd("sm_0ping", OnToggleLagCompSettings); - RegConsoleCmd("sm_0pinglasers", OnToggleLagCompLasersSettings); - RegConsoleCmd("sm_checklag", CheckLagComp); - SetCookieMenuItem(MenuHandler_CookieMenu, 0, "LagCompensation"); - - CreateTimer(0.1, DisableLagCompTimer, _, TIMER_REPEAT); - - RegAdminCmd("sm_unlag", Command_AddLagCompensation, ADMFLAG_ROOT, "sm_unlag "); - RegAdminCmd("sm_lagged", Command_CheckLagCompensated, ADMFLAG_ROOT, "sm_lagged"); - - FilterClientSolidTouch(g_aaFilterClientSolidTouch, true); - BlockTriggerMoved(g_aBlockTriggerMoved, true); -} - -public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) -{ - RegPluginLibrary("LagCompensation"); - g_bLateLoad = late; - return APLRes_Success; -} - -public void OnLibraryRemoved(const char[] name) -{ - if(strcmp(name, "PhysHooks", false) == 0) - g_bHasPhysHooks = false; -} - -public void OnPluginEnd() -{ - g_bCleaningUp = true; - if(g_bHasPhysHooks) - { - FilterClientSolidTouch(g_aaFilterClientSolidTouch, false); - BlockTriggerMoved(g_aBlockTriggerMoved, false); - BlockTriggerTouchPlayers(g_aBlockTriggerTouchPlayers, false); - } - - DHookDisableDetour(g_hUTIL_Remove, false, Detour_OnUTIL_Remove); - - for(int i = 0; i < g_iNumEntities; i++) - { - if(!IsValidEntity(g_aEntityLagData[i].iEntity)) - continue; - - if(g_aEntityLagData[i].iDeleted) - { - RemoveEdict(g_aEntityLagData[i].iEntity); - } - } - - delete g_hCookie_LagCompSettings; -} - -public void OnConfigsExecuted() -{ - g_iCompenseEntityClass = GetConVarInt(g_cvCompenseEntityClass); - g_bCheckPing = GetConVarBool(g_cvCheckUserPing); - g_iMinPing = GetConVarInt(g_cvMinimumPing); -} - -void OnConVarChanged(ConVar convar, const char[] oldValue, const char[] newValue) -{ - if (convar == g_cvCompenseEntityClass) - g_iCompenseEntityClass = GetConVarInt(convar); - else if (convar == g_cvCheckUserPing) - g_bCheckPing = GetConVarBool(convar); - else if (convar == g_cvMinimumPing) - g_iMinPing = GetConVarInt(convar); -} - -public void OnMapStart() -{ - bool bLate = g_bLateLoad; - - DHookGamerules(g_hEndGameFrame, true); - - g_bCleaningUp = false; - - g_fTickInterval = GetTickInterval(); - - g_iParent = FindDataMapInfo(0, "m_pParent"); - g_iSpawnFlags = FindDataMapInfo(0, "m_spawnflags"); - g_iCollision = FindDataMapInfo(0, "m_Collision"); - g_iSolidFlags = FindDataMapInfo(0, "m_usSolidFlags"); - g_iSolidType = FindDataMapInfo(0, "m_nSolidType"); - g_iSurroundType = FindDataMapInfo(0, "m_nSurroundType"); - g_iEFlags = FindDataMapInfo(0, "m_iEFlags"); - - g_iVecOrigin = FindDataMapInfo(0, "m_vecOrigin"); - g_iVecAbsOrigin = FindDataMapInfo(0, "m_vecAbsOrigin"); - g_iAngRotation = FindDataMapInfo(0, "m_angRotation"); - g_iAngAbsRotation = FindDataMapInfo(0, "m_angAbsRotation"); - g_iVecMins = FindDataMapInfo(0, "m_vecMins"); - g_iVecMaxs = FindDataMapInfo(0, "m_vecMaxs"); - g_iSimulationTime = FindDataMapInfo(0, "m_flSimulationTime"); - g_iCoordinateFrame = FindDataMapInfo(0, "m_rgflCoordinateFrame"); - - /* Late Load */ - if(bLate) - { - for (int client = 1; client <= MaxClients; client++) - { - if(IsClientInGame(client)) - { - OnClientConnected(client); - if(AreClientCookiesCached(client)) - OnClientCookiesCached(client); - OnClientSettingsChanged(client); - } - } - - int entity = INVALID_ENT_REFERENCE; - while((entity = FindEntityByClassname(entity, "*")) != INVALID_ENT_REFERENCE) - { - char sClassname[64]; - if(GetEntityClassname(entity, sClassname, sizeof(sClassname))) - { - OnEntityCreated(entity, sClassname); - OnEntitySpawned(entity, sClassname); - - if(strcmp(sClassname, "phys_thruster", false) == 0) - { - Hook_CPhysForce_Activate(entity); - } - } - } - } - - g_bLateLoad = false; -} - -public void OnMapEnd() -{ - Detour_OnRestartRound(); - g_bCleaningUp = true; -} - -public void OnClientConnected(int client) -{ - g_bDisableLagComp[client] = false; - g_bPlayerLaserCompensated[client] = false; - g_iDisableLagComp[client] = 0; - g_aLerpTicks[client] = 0; -} - -public void OnClientCookiesCached(int client) -{ - // Load all settings from single cookie - ParseClientCookie(client, g_bDisableLagComp[client], g_bPlayerLaserCompensated[client], g_bLagCompMessages[client]); -} - -public void OnClientSettingsChanged(int client) -{ - if(!IsClientInGame(client) || IsFakeClient(client)) - return; - - float fLerpTime = GetEntPropFloat(client, Prop_Data, "m_fLerpTime"); - g_aLerpTicks[client] = RoundToNearest(fLerpTime / g_fTickInterval); -} - -public void OnClientDisconnect(int client) -{ - g_bDisableLagComp[client] = false; - g_bPlayerLaserCompensated[client] = false; - g_iDisableLagComp[client] = 0; -} - -public void OnEntityCreated(int entity, const char[] classname) -{ - if(g_bCleaningUp) - return; - - if (strcmp(classname, "phys_thruster", false) == 0) - { - DHookEntity(g_hActivate, true, entity); - } - else if (strcmp(classname, "game_ui", false) == 0) - { - DHookEntity(g_hAcceptInput, true, entity); - } - - if (!g_bHasOnEntitySpawned && (!strncmp(classname, "func_physbox", 12, false) || (g_iCompenseEntityClass == 0 && strcmp(classname, "trigger_hurt", false) == 0 || - strcmp(classname, "trigger_push", false) == 0 || strcmp(classname, "trigger_teleport", false) == 0))) - { - SDKHook(entity, SDKHook_SpawnPost, OnSDKHookEntitySpawnPost); - } -} - -public void OnSDKHookEntitySpawnPost(int entity) -{ - char classname[64]; - GetEntityClassname(entity, classname, sizeof(classname)); - - OnEntitySpawned(entity, classname); -} - -public void OnEntitySpawned(int entity, const char[] classname) -{ - if(g_bCleaningUp) - return; - - CheckEntityForLagComp(entity, classname); -} - -public MRESReturn Hook_AcceptInput(int entity, Handle hReturn, Handle hParams) -{ - if(!IsValidEntity(entity)) - return MRES_Ignored; - - char sCommand[128]; - DHookGetParamString(hParams, 1, sCommand, sizeof(sCommand)); - - if (strcmp(sCommand, "Activate", false) != 0) - return MRES_Ignored; - - if(DHookIsNullParam(hParams, 3)) - return MRES_Ignored; - - int iCaller = DHookGetParam(hParams, 3); - if(iCaller <= 0 || iCaller >= MAX_EDICTS) - return MRES_Ignored; - - // Don't lagcompensate anything that has a game_ui button in their hierarchy. - BlacklistFamily(iCaller); - - return MRES_Ignored; -} - -void BlacklistFamily(int entity) -{ - if(entity > 0 && entity < MAX_EDICTS) - { - SetBit(g_aBlacklisted, entity); - RemoveEntityFromLagCompensation(entity); - } - - // Blacklist children of this entity - BlacklistChildren(entity); - - // And blacklist all parents and their children - for(;;) - { - entity = GetEntDataEnt2(entity, g_iParent); - if(entity == INVALID_ENT_REFERENCE) - break; - - if(entity > 0 && entity < MAX_EDICTS) - { - SetBit(g_aBlacklisted, entity); - RemoveEntityFromLagCompensation(entity); - } - - // And their children - BlacklistChildren(entity); - } -} - -void BlacklistChildren(int parent) -{ - int entity = INVALID_ENT_REFERENCE; - while((entity = FindEntityByClassname(entity, "*")) != INVALID_ENT_REFERENCE) - { - if(GetEntDataEnt2(entity, g_iParent) != parent) - continue; - - if(entity > 0 && entity < MAX_EDICTS) - { - SetBit(g_aBlacklisted, entity); - RemoveEntityFromLagCompensation(entity); - } - } -} - -bool CheckEntityForLagComp(int entity, const char[] classname, bool bRecursive=false, bool bGoodParents=false) -{ - if(entity < 0 || entity > MAX_EDICTS) - return false; - - if(!IsValidEntity(entity)) - return false; - - if(g_aLagCompensated[entity] != -1) - return false; - - int SpawnFlags = GetEntData(entity, g_iSpawnFlags); - if(SpawnFlags & SF_LAGCOMP_DISABLE) - return false; - - bool bTrigger = false; - - if (g_iCompenseEntityClass == 0) - bTrigger = strcmp(classname, "trigger_hurt", false) == 0 || strcmp(classname, "trigger_push", false) == 0 || strcmp(classname, "trigger_teleport", false) == 0; - - bool bPhysbox = !strncmp(classname, "func_physbox", 12, false); - - bool bBlacklisted = CheckBit(g_aBlacklisted, entity); - - if(!bTrigger && !bPhysbox || bBlacklisted) - return false; - - // Don't lag compensate anything that could be parented to a player - // The player simulation would usually move the entity, - // but we would overwrite that position change by restoring the entity to its previous state. - int iParent = INVALID_ENT_REFERENCE; - char sParentClassname[64]; - for(int iTmp = entity;;) - { - iTmp = GetEntDataEnt2(iTmp, g_iParent); - if(iTmp == INVALID_ENT_REFERENCE) - break; - - iParent = iTmp; - GetEntityClassname(iParent, sParentClassname, sizeof(sParentClassname)); - - if((iParent >= 1 && iParent <= MaxClients) || - !strncmp(sParentClassname, "weapon_", 7)) - { - return false; - } - - if(CheckBit(g_aBlacklisted, entity)) - { - return false; - } - - if(g_aLagCompensated[iParent] != -1) - { - bGoodParents = true; - break; - } - - if(strncmp(sParentClassname, "func_", 5)) - continue; - - if(strcmp(sParentClassname[5], "movelinear", true) == 0 || - strcmp(sParentClassname[5], "door", true) == 0 || - strcmp(sParentClassname[5], "rotating", true) == 0 || - strcmp(sParentClassname[5], "tracktrain", true) == 0) - { - bGoodParents = true; - break; - } - } - - if(!bGoodParents) - return false; - - if(AddEntityForLagCompensation(entity, bTrigger)) - { - if(bTrigger) - { - if(!(SpawnFlags & (SF_TRIGGER_ALLOW_PUSHABLES | SF_TRIGGER_ALLOW_PHYSICS | SF_TRIGGER_ALLOW_ALL | SF_TRIG_TOUCH_DEBRIS))) - SetBit(g_aBlockTriggerMoved, entity); - } - - if(bRecursive) - { - CheckEntityChildrenForLagComp(entity); - } - - return true; - } - - return false; -} - -void CheckEntityChildrenForLagComp(int parent) -{ - int entity = INVALID_ENT_REFERENCE; - while((entity = FindEntityByClassname(entity, "*")) != INVALID_ENT_REFERENCE) - { - if(GetEntDataEnt2(entity, g_iParent) != parent) - continue; - - char sClassname[64]; - if(GetEntityClassname(entity, sClassname, sizeof(sClassname))) - { - CheckEntityForLagComp(entity, sClassname, _, true); - CheckEntityChildrenForLagComp(entity); - } - } -} - -public void OnEntityDestroyed(int entity) -{ - if(g_bCleaningUp) - return; - - if(entity < 0 || entity > MAX_EDICTS) - return; - - ClearBit(g_aBlacklisted, entity); - - int iIndex = g_aLagCompensated[entity]; - if(iIndex == -1) - return; - - RemoveRecord(iIndex); -} - - -public MRESReturn Detour_OnUTIL_Remove(Handle hParams) -{ - if(g_bCleaningUp) - return MRES_Ignored; - - if(DHookIsNullParam(hParams, 1)) - return MRES_Ignored; - - int entity = DHookGetParamObjectPtrVar(hParams, 1, g_iNetworkableOuter, ObjectValueType_CBaseEntityPtr); - if(entity < 0 || entity > MAX_EDICTS) - return MRES_Ignored; - - int iIndex = g_aLagCompensated[entity]; - if(iIndex == -1) - return MRES_Ignored; - - // let it die - if(!g_aEntityLagData[iIndex].bLateKill) - return MRES_Ignored; - - // ignore sleeping entities - if(g_aEntityLagData[iIndex].iNotMoving >= MAX_RECORDS) - return MRES_Ignored; - - if(!g_aEntityLagData[iIndex].iDeleted) - { - g_aEntityLagData[iIndex].iDeleted = GetGameTickCount(); - } - - return MRES_Supercede; -} - -public MRESReturn Detour_OnRestartRound() -{ - g_bCleaningUp = true; - - for(int i = 0; i < g_iNumEntities; i++) - { - int iEntity = g_aEntityLagData[i].iEntity; - - g_aLagCompensated[iEntity] = -1; - ClearBit(g_aBlockTriggerTouchPlayers, iEntity); - ClearBit(g_aBlockTriggerMoved, iEntity); - - for(int client = 1; client <= MaxClients; client++) - { - ClearBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); - } - - if(g_aEntityLagData[i].iDeleted) - { - if(IsValidEntity(iEntity)) - RemoveEdict(iEntity); - } - - g_aEntityLagData[i].iEntity = INVALID_ENT_REFERENCE; - } - - for(int i = 0; i < sizeof(g_aBlacklisted); i++) - g_aBlacklisted[i] = 0; - - g_iNumEntities = 0; - - g_bCleaningUp = false; - return MRES_Ignored; -} - -// https://developer.valvesoftware.com/wiki/Logic_measure_movement -int g_OnSetTarget_pThis; -public MRESReturn Detour_OnSetTargetPre(int pThis, Handle hParams) -{ - g_OnSetTarget_pThis = pThis; - return MRES_Ignored; -} -public MRESReturn Detour_OnSetTargetPost(Handle hParams) -{ - int entity = GetEntPropEnt(g_OnSetTarget_pThis, Prop_Data, "m_hTarget"); - if(!IsValidEntity(entity)) - return MRES_Ignored; - - char sClassname[64]; - if(!GetEntityClassname(entity, sClassname, sizeof(sClassname))) - return MRES_Ignored; - - CheckEntityForLagComp(entity, sClassname, true, true); - - return MRES_Ignored; -} - -public MRESReturn Hook_CPhysForce_Activate(int entity) -{ - int attachedObject = GetEntPropEnt(entity, Prop_Data, "m_attachedObject"); - if(!IsValidEntity(attachedObject)) - return MRES_Ignored; - - char sClassname[64]; - if(!GetEntityClassname(attachedObject, sClassname, sizeof(sClassname))) - return MRES_Ignored; - - CheckEntityForLagComp(attachedObject, sClassname, true, true); - - return MRES_Ignored; -} - -public MRESReturn Detour_OnFrameUpdatePostEntityThink() -{ - for(int i = 0; i < g_iNumEntities; i++) - { - // Don't make the entity check untouch in FrameUpdatePostEntityThink. - // If the player didn't get simulated in the current frame then - // they didn't have a chance to touch this entity. - // Hence the touchlink could be broken and we only let the player check untouch. - int EFlags = GetEntData(g_aEntityLagData[i].iEntity, g_iEFlags); - EFlags &= ~EFL_CHECK_UNTOUCH; - SetEntData(g_aEntityLagData[i].iEntity, g_iEFlags, EFlags); - } - return MRES_Ignored; -} - - -public void OnRunThinkFunctions(bool simulating) -{ - g_iGameTick = GetGameTickCount(); - BlockTriggerTouchPlayers(g_aBlockTriggerTouchPlayers, false); -} - -public Action OnPlayerRunCmd(int client, int &buttons, int &impulse, float vel[3], float angles[3], int &weapon, int &subtype, int &cmdnum, int &tickcount, int &seed, int mouse[2]) -{ - if(!IsClientInGame(client) || !IsPlayerAlive(client) || IsFakeClient(client)) - return Plugin_Continue; - - int iTargetTick = tickcount - g_aLerpTicks[client]; - - // -1 because the newest record in the list is one tick old - // this is because we simulate players first - // hence no new entity record was inserted on the current tick - int iDelta = g_iGameTick - iTargetTick - 1; - - // The player is stupid and doesn't want lag compensation. - // To get the original behavior back lets assume they actually have 0 latency. - // To avoid abusing toggling lagcomp we increase/decrease this var by 1 every 100ms. - // This is so we only skip single ticks at a time. Fully ON = 0, Fully OFF = MAX_RECORDS - iDelta -= g_iDisableLagComp[client]; - - if(iDelta < 0) - iDelta = 0; - if(iDelta > MAX_RECORDS) - iDelta = MAX_RECORDS; - - int iPlayerSimTick = g_iGameTick - iDelta; - - for(int i = 0; i < g_iNumEntities; i++) - { - int iEntity = g_aEntityLagData[i].iEntity; - - // Entity too new, the client couldn't even see it yet. - if(g_aEntityLagData[i].iSpawned > iPlayerSimTick) - { - SetBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); - continue; - } - - if(g_aEntityLagData[i].iDeleted) - { - if(g_aEntityLagData[i].iDeleted <= iPlayerSimTick) - { - SetBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); - continue; - } - } - else - { - ClearBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); - } - - if(g_aEntityLagData[i].iNotMoving >= MAX_RECORDS) - continue; - - // Verify if the client have compensated the lasers - if (!g_bPlayerLaserCompensated[client] || g_iCompenseEntityClass == 0 && strcmp(g_aEntityLagData[i].sClassname, "trigger_hurt", false) != 0 || strcmp(g_aEntityLagData[i].sClassname, "trigger_push", false) != 0 || strcmp(g_aEntityLagData[i].sClassname, "trigger_teleport", false) != 0) - continue; - - int iRecord = iDelta; - if(iRecord >= g_aEntityLagData[i].iNumRecords) - iRecord = g_aEntityLagData[i].iNumRecords - 1; - - int iRecordIndex = g_aEntityLagData[i].iRecordIndex - iRecord; - if(iRecordIndex < 0) - iRecordIndex += MAX_RECORDS; - - RestoreEntityFromRecord(iEntity, g_aaLagRecords[i][iRecordIndex]); - g_aEntityLagData[i].bRestore = !g_aEntityLagData[i].iDeleted; - } - - return Plugin_Continue; -} - -public void OnPostPlayerThinkFunctions() -{ - for(int i = 0; i < g_iNumEntities; i++) - { - if(!g_aEntityLagData[i].bRestore) - continue; - - RestoreEntityFromRecord(g_aEntityLagData[i].iEntity, g_aaLagRecords[i][g_aEntityLagData[i].iRecordIndex]); - g_aEntityLagData[i].bRestore = false; - } - - BlockTriggerTouchPlayers(g_aBlockTriggerTouchPlayers, true); -} - -public MRESReturn Hook_EndGameFrame() -{ - for(int i = 0; i < g_iNumEntities; i++) - { - if(g_aEntityLagData[i].iDeleted) - { - if(g_aEntityLagData[i].iDeleted + MAX_RECORDS <= g_iGameTick) - { - // calls OnEntityDestroyed right away - // which calls RemoveRecord - // which moves the next element to our current position - RemoveEdict(g_aEntityLagData[i].iEntity); - i--; continue; - } - - if(g_aEntityLagData[i].iRecordsValid) - { - g_aEntityLagData[i].iRecordIndex++; - - if(g_aEntityLagData[i].iRecordIndex >= MAX_RECORDS) - g_aEntityLagData[i].iRecordIndex = 0; - - g_aEntityLagData[i].iRecordsValid--; - } - - continue; - } - - LagRecord TmpRecord; - RecordDataIntoRecord(g_aEntityLagData[i].iEntity, TmpRecord); - - // sleep detection - { - int iOldRecord = g_aEntityLagData[i].iRecordIndex; - - if(CompareVectors(g_aaLagRecords[i][iOldRecord].vecAbsOrigin, TmpRecord.vecAbsOrigin) && - CompareVectors(g_aaLagRecords[i][iOldRecord].angAbsRotation, TmpRecord.angAbsRotation)) - { - g_aEntityLagData[i].iNotMoving++; - } - else - { - g_aEntityLagData[i].iNotMoving = 0; - } - - if(g_aEntityLagData[i].iNotMoving >= MAX_RECORDS) - continue; - } - - g_aEntityLagData[i].iRecordIndex++; - - if(g_aEntityLagData[i].iRecordIndex >= MAX_RECORDS) - g_aEntityLagData[i].iRecordIndex = 0; - - if(g_aEntityLagData[i].iNumRecords < MAX_RECORDS) - g_aEntityLagData[i].iRecordsValid = ++g_aEntityLagData[i].iNumRecords; - - LagRecord_Copy(g_aaLagRecords[i][g_aEntityLagData[i].iRecordIndex], TmpRecord); - } - - return MRES_Ignored; -} - - -void RecordDataIntoRecord(int iEntity, LagRecord Record) -{ - // Force recalculation of all values - int EFlags = GetEntData(iEntity, g_iEFlags); - EFlags |= EFL_DIRTY_ABSTRANSFORM; - SetEntData(iEntity, g_iEFlags, EFlags); - - SDKCall(g_hCalcAbsolutePosition, iEntity); - - GetEntDataVector(iEntity, g_iVecOrigin, Record.vecOrigin); - GetEntDataVector(iEntity, g_iVecAbsOrigin, Record.vecAbsOrigin); - GetEntDataVector(iEntity, g_iAngRotation, Record.angRotation); - GetEntDataVector(iEntity, g_iAngAbsRotation, Record.angAbsRotation); - GetEntDataVector(iEntity, g_iVecMins, Record.vecMins); - GetEntDataVector(iEntity, g_iVecMaxs, Record.vecMaxs); - GetEntDataArray(iEntity, g_iCoordinateFrame, view_as(Record.rgflCoordinateFrame), COORDINATE_FRAME_SIZE); - Record.flSimulationTime = GetEntDataFloat(iEntity, g_iSimulationTime); -} - -bool DoesRotationInvalidateSurroundingBox(int iEntity) -{ - int SolidFlags = GetEntData(iEntity, g_iSolidFlags); - if(SolidFlags & FSOLID_ROOT_PARENT_ALIGNED) - return true; - - int SurroundType = GetEntData(iEntity, g_iSurroundType); - switch(SurroundType) - { - case USE_COLLISION_BOUNDS_NEVER_VPHYSICS, - USE_OBB_COLLISION_BOUNDS, - USE_BEST_COLLISION_BOUNDS: - { - // IsBoundsDefinedInEntitySpace() - int SolidType = GetEntData(iEntity, g_iSolidType); - return ((SolidFlags & FSOLID_FORCE_WORLD_ALIGNED) == 0) && - (SolidType != SOLID_BBOX) && (SolidType != SOLID_NONE); - } - - case USE_HITBOXES, - USE_GAME_CODE: - { - return true; - } - - case USE_ROTATION_EXPANDED_BOUNDS, - USE_SPECIFIED_BOUNDS: - { - return false; - } - - default: - { - return true; - } - } -} - -void InvalidatePhysicsRecursive(int iEntity) -{ - // CollisionProp()->MarkPartitionHandleDirty(); - Address CollisionProp = GetEntityAddress(iEntity) + view_as
(g_iCollision); - SDKCall(g_hMarkPartitionHandleDirty, CollisionProp); - - if(DoesRotationInvalidateSurroundingBox(iEntity)) - { - // CollisionProp()->MarkSurroundingBoundsDirty(); - int EFlags = GetEntData(iEntity, g_iEFlags); - EFlags |= EFL_DIRTY_SURROUNDING_COLLISION_BOUNDS; - SetEntData(iEntity, g_iEFlags, EFlags); - } -} - -void RestoreEntityFromRecord(int iEntity, LagRecord Record) -{ - SetEntDataVector(iEntity, g_iVecOrigin, Record.vecOrigin); - SetEntDataVector(iEntity, g_iVecAbsOrigin, Record.vecAbsOrigin); - SetEntDataVector(iEntity, g_iAngRotation, Record.angRotation); - SetEntDataVector(iEntity, g_iAngAbsRotation, Record.angAbsRotation); - SetEntDataVector(iEntity, g_iVecMins, Record.vecMins); - SetEntDataVector(iEntity, g_iVecMaxs, Record.vecMaxs); - SetEntDataArray(iEntity, g_iCoordinateFrame, view_as(Record.rgflCoordinateFrame), COORDINATE_FRAME_SIZE); - SetEntDataFloat(iEntity, g_iSimulationTime, Record.flSimulationTime); - - InvalidatePhysicsRecursive(iEntity); -} - - -bool AddEntityForLagCompensation(int iEntity, bool bLateKill) -{ - if(g_bCleaningUp) - return false; - - if(g_aLagCompensated[iEntity] != -1) - return false; - - char sClassname[64]; - GetEntityClassname(iEntity, sClassname, sizeof(sClassname)); - - char sTargetname[64]; - GetEntPropString(iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); - - int iHammerID = GetEntProp(iEntity, Prop_Data, "m_iHammerID"); - - if(g_iNumEntities >= MAX_ENTITIES) - { - PrintToBoth("[%d] OUT OF LAGCOMP SLOTS entity %d (%s)\"%s\"(#%d)", GetGameTickCount(), iEntity, sClassname, sTargetname, iHammerID); - LogError("OUT OF LAGCOMP SLOTS entity %d (%s)\"%s\"(#%d)", iEntity, sClassname, sTargetname, iHammerID); - return false; - } - - int i = g_iNumEntities; - g_iNumEntities++; - - g_aLagCompensated[iEntity] = i; - - g_aEntityLagData[i].iEntity = iEntity; - g_aEntityLagData[i].iRecordIndex = 0; - g_aEntityLagData[i].iNumRecords = 1; - g_aEntityLagData[i].iRecordsValid = 1; - g_aEntityLagData[i].iSpawned = GetGameTickCount(); - g_aEntityLagData[i].iDeleted = 0; - g_aEntityLagData[i].iNotMoving = MAX_RECORDS; - g_aEntityLagData[i].bRestore = false; - g_aEntityLagData[i].bLateKill = bLateKill; - g_aEntityLagData[i].sClassname = sClassname; - - if(bLateKill) - { - SetBit(g_aBlockTriggerTouchPlayers, iEntity); - } - - RecordDataIntoRecord(iEntity, g_aaLagRecords[i][0]); - PrintToBoth("[%d] added entity %d (%s)\"%s\"(#%d) under index %d", GetGameTickCount(), iEntity, sClassname, sTargetname, iHammerID, i); - - return true; -} - -bool RemoveEntityFromLagCompensation(int iEntity) -{ - int index = g_aLagCompensated[iEntity]; - if(index == -1) - return false; - - RemoveRecord(index); - return true; -} - -void RemoveRecord(int index) -{ - if(g_bCleaningUp) - return; - - int iEntity = g_aEntityLagData[index].iEntity; - - if(IsValidEntity(iEntity)) - { - char sClassname[64]; - GetEntityClassname(g_aEntityLagData[index].iEntity, sClassname, sizeof(sClassname)); - - char sTargetname[64]; - GetEntPropString(g_aEntityLagData[index].iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); - - int iHammerID = GetEntProp(g_aEntityLagData[index].iEntity, Prop_Data, "m_iHammerID"); - - PrintToBoth("[%d] RemoveRecord %d / %d (%s)\"%s\"(#%d), num: %d", GetGameTickCount(), index, g_aEntityLagData[index].iEntity, sClassname, sTargetname, iHammerID, g_iNumEntities); - } - - g_aLagCompensated[iEntity] = -1; - ClearBit(g_aBlockTriggerTouchPlayers, iEntity); - ClearBit(g_aBlockTriggerMoved, iEntity); - - for(int client = 1; client <= MaxClients; client++) - { - ClearBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); - } - - g_aEntityLagData[index].iEntity = INVALID_ENT_REFERENCE; - - for(int src = index + 1; src < g_iNumEntities; src++) - { - int dest = src - 1; - - EntityLagData_Copy(g_aEntityLagData[dest], g_aEntityLagData[src]); - g_aEntityLagData[src].iEntity = INVALID_ENT_REFERENCE; - g_aLagCompensated[g_aEntityLagData[dest].iEntity] = dest; - - int iNumRecords = g_aEntityLagData[dest].iNumRecords; - for(int i = 0; i < iNumRecords; i++) - { - LagRecord_Copy(g_aaLagRecords[dest][i], g_aaLagRecords[src][i]); - } - } - - g_iNumEntities--; -} - -void EntityLagData_Copy(EntityLagData obj, const EntityLagData other) -{ - obj.iEntity = other.iEntity; - obj.iRecordIndex = other.iRecordIndex; - obj.iNumRecords = other.iNumRecords; - obj.iRecordsValid = other.iRecordsValid; - obj.iSpawned = other.iSpawned; - obj.iDeleted = other.iDeleted; - obj.iNotMoving = other.iNotMoving; - obj.bRestore = other.bRestore; - obj.bLateKill = other.bLateKill; -} - -void LagRecord_Copy(LagRecord obj, const LagRecord other) -{ - for(int i = 0; i < 3; i++) - { - obj.vecOrigin[i] = other.vecOrigin[i]; - obj.vecAbsOrigin[i] = other.vecAbsOrigin[i]; - obj.angRotation[i] = other.angRotation[i]; - obj.angAbsRotation[i] = other.angAbsRotation[i]; - obj.vecMins[i] = other.vecMins[i]; - obj.vecMaxs[i] = other.vecMaxs[i]; - } - - obj.flSimulationTime = other.flSimulationTime; - - for(int i = 0; i < COORDINATE_FRAME_SIZE; i++) - { - obj.rgflCoordinateFrame[i] = other.rgflCoordinateFrame[i]; - } -} - -bool CompareVectors(const float vec1[3], const float vec2[3]) -{ - return vec1[0] == vec2[0] && vec1[1] == vec2[1] && vec1[2] == vec2[2]; -} - -void SaveLagCompSettings(int client) -{ - // Read current cookie values - bool currentDisableLagComp, currentPlayerLaserCompensated, currentLagCompMessages; - ParseClientCookie(client, currentDisableLagComp, currentPlayerLaserCompensated, currentLagCompMessages); - - // Check if values have changed - bool disableChanged = g_bDisableLagComp[client] != currentDisableLagComp; - bool laserChanged = g_bPlayerLaserCompensated[client] != currentPlayerLaserCompensated; - bool messagesChanged = g_bLagCompMessages[client] != currentLagCompMessages; - - // If no values have changed, no need to save - if (!disableChanged && !laserChanged && !messagesChanged) { - return; - } - - // Otherwise, save the chain format - char sBuffer[8]; - Format(sBuffer, sizeof(sBuffer), "%d%d%d", - g_bDisableLagComp[client] ? 1 : 0, - g_bPlayerLaserCompensated[client] ? 1 : 0, - g_bLagCompMessages[client] ? 1 : 0); - SetClientCookie(client, g_hCookie_LagCompSettings, sBuffer); -} - -void ParseClientCookie(int client, bool &disableLagComp, bool &playerLaserCompensated, bool &lagCompMessages) -{ - char buffer[16]; - GetClientCookie(client, g_hCookie_LagCompSettings, buffer, sizeof(buffer)); - - // Parse chain format: disable|laser|messages - if (strlen(buffer) >= 3) - { - disableLagComp = (buffer[0] == '1'); - playerLaserCompensated = (buffer[1] == '1'); - lagCompMessages = (buffer[2] == '1'); - } - else - { - // Default values - disableLagComp = false; - playerLaserCompensated = true; - lagCompMessages = false; - } -} - -public Action Command_AddLagCompensation(int client, int argc) -{ - if(argc < 1) - { - ReplyToCommand(client, "[SM] Usage: sm_unlag [late]"); - return Plugin_Handled; - } - - char sArgs[32]; - GetCmdArg(1, sArgs, sizeof(sArgs)); - - int entity = StringToInt(sArgs); - - bool late = false; - if(argc >= 2) - { - GetCmdArg(2, sArgs, sizeof(sArgs)); - late = view_as(StringToInt(sArgs)); - } - - AddEntityForLagCompensation(entity, late); - - return Plugin_Handled; -} - -public Action Command_CheckLagCompensated(int client, int argc) -{ - if(argc == 0) - { - for(int i = 0; i < g_iNumEntities; i++) - { - char sClassname[64]; - GetEntityClassname(g_aEntityLagData[i].iEntity, sClassname, sizeof(sClassname)); - - char sTargetname[64]; - GetEntPropString(g_aEntityLagData[i].iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); - - int iHammerID = GetEntProp(g_aEntityLagData[i].iEntity, Prop_Data, "m_iHammerID"); - - PrintToConsole(client, "%2d. #%d %s \"%s\" (#%d)", i, g_aEntityLagData[i].iEntity, sClassname, sTargetname, iHammerID); - } - - return Plugin_Handled; - } - - for(int iEntity = 0; iEntity < MAX_EDICTS; iEntity++) - { - bool bDeleted = false; - for(int j = 1; j <= MaxClients; j++) - { - if(CheckBit(g_aaFilterClientSolidTouch, j * MAX_EDICTS + iEntity)) - { - bDeleted = true; - break; - } - } - - bool bBlockPhysics = CheckBit(g_aBlockTriggerTouchPlayers, iEntity); - bool bBlockTriggerMoved = CheckBit(g_aBlockTriggerMoved, iEntity); - bool bBlacklisted = CheckBit(g_aBlacklisted, iEntity); - - if(bDeleted || bBlockPhysics || bBlockTriggerMoved || bBlacklisted) - { - int index = -1; - for(int j = 0; j < g_iNumEntities; j++) - { - if(g_aEntityLagData[j].iEntity == iEntity) - { - index = j; - break; - } - } - - char sClassname[64] = "INVALID"; - char sTargetname[64] = "INVALID"; - int iHammerID = -1; - - if(IsValidEntity(iEntity)) - { - GetEntityClassname(iEntity, sClassname, sizeof(sClassname)); - GetEntPropString(iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); - iHammerID = GetEntProp(iEntity, Prop_Data, "m_iHammerID"); - } - - PrintToConsole(client, "%2d. #%d %s \"%s\" (#%d) -> Phys: %d / TrigMov: %d / Deleted: %d / Black: %d", - index, iEntity, sClassname, sTargetname, iHammerID, bBlockPhysics, bBlockTriggerMoved, bDeleted, bBlacklisted); - } - } - - return Plugin_Handled; -} - - -stock void PrintToBoth(const char[] format, any ...) -{ - char buffer[254]; - VFormat(buffer, sizeof(buffer), format, 2); - LogMessage(buffer); - - for(int client = 1; client <= MaxClients; client++) - { - if (IsClientInGame(client) && g_bLagCompMessages[client] && CheckCommandAccess(client, "sm_lagged", ADMFLAG_ROOT)) - { - PrintToConsole(client, buffer); - } - } -} - -public Action DisableLagCompTimer(Handle timer) -{ - for(int client = 1; client <= MaxClients; client++) - { - if(!IsClientInGame(client) || !IsPlayerAlive(client) || IsFakeClient(client)) - continue; - - // https://github.com/ValveSoftware/source-sdk-2013/blob/master/sp/src/game/server/util.cpp#L747 - if (g_bCheckPing) - { - int iAvgPing = RoundFloat(GetClientAvgLatency(client, NetFlow_Outgoing) * 1000); - - if (iAvgPing > g_iMinPing) - { - g_iDisableLagComp[client]++; - return Plugin_Continue; - } - } - - if(g_bDisableLagComp[client] && g_iDisableLagComp[client] < MAX_RECORDS) - { - g_iDisableLagComp[client]++; - } - else if(!g_bDisableLagComp[client] && g_iDisableLagComp[client] > 0) - { - g_iDisableLagComp[client]--; - } - } - - return Plugin_Continue; -} - -public Action OnLagCompSettings(int client, int args) -{ - ShowSettingsMenu(client); - return Plugin_Handled; -} - -public Action OnToggleLagCompSettings(int client, int args) -{ - ToggleLagCompSettings(client); - return Plugin_Handled; -} - -public Action OnToggleLagCompLasersSettings(int client, int args) -{ - ToggleLagCompLasers(client); - return Plugin_Handled; -} - -public void ToggleLagCompSettings(int client) -{ - if(!client || !IsClientInGame(client) || IsFakeClient(client)) - return; - - g_bDisableLagComp[client] = !g_bDisableLagComp[client]; - SaveLagCompSettings(client); - - CPrintToChat(client, "%s LagCompensation has been %s.", PREFIX, g_bDisableLagComp[client] ? "disabled" : "enabled"); -} - -public void ToggleLagCompLasers(int client) -{ - if(!client || !IsClientInGame(client) || IsFakeClient(client)) - return; - - g_bPlayerLaserCompensated[client] = !g_bPlayerLaserCompensated[client]; - SaveLagCompSettings(client); - - CPrintToChat(client, "%s LagCompensation for Lasers has been %s.", PREFIX, g_bPlayerLaserCompensated[client] ? "enabled" : "disabled"); - if (g_bCheckPing && g_bPlayerLaserCompensated[client]) - CPrintToChat(client, "%s It will take effect if your real ping is higher than %dms.", PREFIX, g_iMinPing); -} - -public void ToggleLagCompMessages(int client) -{ - if(!client || !IsClientInGame(client) || IsFakeClient(client)) - return; - - g_bLagCompMessages[client] = !g_bLagCompMessages[client]; - SaveLagCompSettings(client); - - CPrintToChat(client, "%s LagCompensation messages have been %s.", PREFIX, g_bLagCompMessages[client] ? "enabled" : "disabled"); -} - -public Action CheckLagComp(int client, int args) -{ - if (args > 1) - { - CPrintToChat(client, "%s Usage sm_checklag ", PREFIX); - return Plugin_Handled; - } - - int target = -1; - char sEnable[64]; - FormatEx(sEnable, sizeof(sEnable), "enabled (%s)", g_iCompenseEntityClass == 0 ? "Triggers and func_physbox" : "func_physbox only"); - - if (args == 0) - target = client; - else - { - char arg1[65]; - GetCmdArg(1, arg1, sizeof(arg1)); - target = FindTarget(client, arg1, true, false); - } - - if (target == -1) - { - CReplyToCommand(client, "%s Invalid target.", PREFIX); - return Plugin_Handled; - } - - CPrintToChat(client, "%s LagCompensation is %s for {olive}%N", PREFIX, g_bDisableLagComp[target] ? "disabled" : sEnable, target); - - return Plugin_Handled; -} - -public void ShowSettingsMenu(int client) -{ - Menu menu = new Menu(MenuHandler_MainMenu); - menu.SetTitle("LagCompensation Settings", client); - menu.ExitBackButton = true; - - char buffer[128], buffer_lasers[128], msg_buffer[128]; - Format(buffer, sizeof(buffer), "LagCompensation: %s", g_bDisableLagComp[client] ? "Disabled" : "Enabled"); - Format(buffer_lasers, sizeof(buffer_lasers), "LagCompensation for Lasers: %s", g_bPlayerLaserCompensated[client] ? "Enabled" : "Disabled"); - Format(msg_buffer, sizeof(msg_buffer), "LagCompensation Messages: %s", g_bLagCompMessages[client] ? "Enabled" : "Disabled"); - - menu.AddItem("0", buffer); - menu.AddItem("1", buffer_lasers); - menu.AddItem("2", msg_buffer, CheckCommandAccess(client, "sm_lagged", ADMFLAG_ROOT) ? ITEMDRAW_DEFAULT : ITEMDRAW_DISABLED); - - menu.Display(client, MENU_TIME_FOREVER); -} - -public void MenuHandler_CookieMenu(int client, CookieMenuAction action, any info, char[] buffer, int maxlen) -{ - switch(action) - { - case(CookieMenuAction_DisplayOption): - { - Format(buffer, maxlen, "LagCompensation", client); - } - case(CookieMenuAction_SelectOption): - { - ShowSettingsMenu(client); - } - } -} - -public int MenuHandler_MainMenu(Menu menu, MenuAction action, int client, int selection) -{ - switch(action) - { - case(MenuAction_Select): - { - switch(selection) - { - case(0): ToggleLagCompSettings(client); - case(1): ToggleLagCompLasers(client); - case(2): ToggleLagCompMessages(client); - } - - ShowSettingsMenu(client); - } - case(MenuAction_Cancel): - { - ShowCookieMenu(client); - } - case(MenuAction_End): - { - delete menu; - } - } - return 0; -} diff --git a/LagCompensation/scripting/LagCompensation_nide_edit.sp b/LagCompensation/scripting/LagCompensation_nide_edit.sp deleted file mode 100644 index 07b373c..0000000 --- a/LagCompensation/scripting/LagCompensation_nide_edit.sp +++ /dev/null @@ -1,1758 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -#define SetBit(%1,%2) ((%1)[(%2) >> 5] |= (1 << ((%2) & 31))) -#define ClearBit(%1,%2) ((%1)[(%2) >> 5] &= ~(1 << ((%2) & 31))) -#define CheckBit(%1,%2) !!((%1)[(%2) >> 5] & (1 << ((%2) & 31))) - -#pragma semicolon 1 -#pragma newdecls required - -public Plugin myinfo = -{ - name = "LagCompensation", - author = "BotoX, Vauff, .Rushaway, maxime1907", - description = "", - version = "1.2.0", - url = "" -}; - -bool g_bLateLoad = false; -bool g_bHasPhysHooks = true; -bool g_bHasOnEntitySpawned = false; -bool g_bCheckPing = false; -bool g_bMapDisabled = false; -int g_iCompenseEntityClass; - -// Don't change this. -#define MAX_EDICTS 2048 -#define FSOLID_FORCE_WORLD_ALIGNED 0x0040 -#define FSOLID_ROOT_PARENT_ALIGNED 0x0100 -#define EFL_DIRTY_ABSTRANSFORM (1<<11) -#define EFL_DIRTY_SURROUNDING_COLLISION_BOUNDS (1<<14) -#define EFL_CHECK_UNTOUCH (1<<24) -#define COORDINATE_FRAME_SIZE 14 - -enum -{ - USE_OBB_COLLISION_BOUNDS = 0, - USE_BEST_COLLISION_BOUNDS, - USE_HITBOXES, - USE_SPECIFIED_BOUNDS, - USE_GAME_CODE, - USE_ROTATION_EXPANDED_BOUNDS, - USE_COLLISION_BOUNDS_NEVER_VPHYSICS, -} - -enum -{ - SOLID_NONE = 0, // no solid model - SOLID_BSP = 1, // a BSP tree - SOLID_BBOX = 2, // an AABB - SOLID_OBB = 3, // an OBB (not implemented yet) - SOLID_OBB_YAW = 4, // an OBB, constrained so that it can only yaw - SOLID_CUSTOM = 5, // Always call into the entity for tests - SOLID_VPHYSICS = 6, // solid vphysics object, get vcollide from the model and collide with that - SOLID_LAST, -}; - -enum -{ - SF_TRIGGER_ALLOW_CLIENTS = 0x01, // Players can fire this trigger - SF_TRIGGER_ALLOW_NPCS = 0x02, // NPCS can fire this trigger - SF_TRIGGER_ALLOW_PUSHABLES = 0x04, // Pushables can fire this trigger - SF_TRIGGER_ALLOW_PHYSICS = 0x08, // Physics objects can fire this trigger - SF_TRIGGER_ONLY_PLAYER_ALLY_NPCS = 0x10, // *if* NPCs can fire this trigger, this flag means only player allies do so - SF_TRIGGER_ONLY_CLIENTS_IN_VEHICLES = 0x20, // *if* Players can fire this trigger, this flag means only players inside vehicles can - SF_TRIGGER_ALLOW_ALL = 0x40, // Everything can fire this trigger EXCEPT DEBRIS! - SF_TRIGGER_ONLY_CLIENTS_OUT_OF_VEHICLES = 0x200, // *if* Players can fire this trigger, this flag means only players outside vehicles can - SF_TRIG_PUSH_ONCE = 0x80, // trigger_push removes itself after firing once - SF_TRIG_PUSH_AFFECT_PLAYER_ON_LADDER = 0x100, // if pushed object is player on a ladder, then this disengages them from the ladder (HL2only) - SF_TRIG_TOUCH_DEBRIS = 0x400, // Will touch physics debris objects - SF_TRIGGER_ONLY_NPCS_IN_VEHICLES = 0x800, // *if* NPCs can fire this trigger, only NPCs in vehicles do so (respects player ally flag too) -}; - -#define SF_LAGCOMP_DISABLE (1 << 30) - -#define MAX_RECORDS 32 -#define MAX_ENTITIES 256 - -enum struct LagRecord -{ - float vecOrigin[3]; - float vecAbsOrigin[3]; - float angRotation[3]; - float angAbsRotation[3]; - float vecMins[3]; - float vecMaxs[3]; - float flSimulationTime; - float rgflCoordinateFrame[COORDINATE_FRAME_SIZE]; -} - -enum struct EntityLagData -{ - int iEntity; - int iRecordIndex; - int iNumRecords; - int iRecordsValid; - int iSpawned; - int iDeleted; - int iNotMoving; - bool bRestore; - bool bLateKill; - char sClassname[64]; -} - -LagRecord g_aaLagRecords[MAX_ENTITIES][MAX_RECORDS]; -EntityLagData g_aEntityLagData[MAX_ENTITIES]; -int g_iNumEntities = 0; -bool g_bCleaningUp = true; - -// When more than sm_lagcomp_max_entities entities are lag compensation at the same time we switch off lag compensation -//enabled again on next round or through command -bool g_bLagCompSuspended = false; // nothing new gets compensated -bool g_bReleasePending = false; // the tracked entities still have to be released -int g_iMaxEntities = MAX_ENTITIES; - -// Cache -int g_iGameTick; -float g_fTickInterval; -int g_aLerpTicks[MAXPLAYERS + 1]; - -// SDKCall -Handle g_hCalcAbsolutePosition; -Handle g_hMarkPartitionHandleDirty; - -// DHooks Detour -Handle g_hUTIL_Remove; -Handle g_hRestartRound; -Handle g_hSetTarget; -Handle g_hSetTargetPost; -Handle g_hFrameUpdatePostEntityThink; - -// DHooks Virtual -Handle g_hActivate; -Handle g_hAcceptInput; -Handle g_hEndGameFrame; - -#define PREFIX "{green}[LagCompensation]{default}" - -int g_iNetworkableOuter; -int g_iParent; -int g_iSpawnFlags; -int g_iCollision; -int g_iSolidFlags; -int g_iSolidType; -int g_iSurroundType; -int g_iEFlags; - -int g_iVecOrigin; -int g_iVecAbsOrigin; -int g_iAngRotation; -int g_iAngAbsRotation; -int g_iVecMins; -int g_iVecMaxs; -int g_iSimulationTime; -int g_iCoordinateFrame; -int g_iMinPing; - -int g_aLagCompensated[MAX_EDICTS] = {-1, ...}; -int g_aBlockTriggerTouchPlayers[MAX_EDICTS / 32]; -int g_aaFilterClientSolidTouch[((MAXPLAYERS + 1) * MAX_EDICTS) / 32]; -int g_aBlockTriggerMoved[MAX_EDICTS / 32]; -int g_aBlacklisted[MAX_EDICTS / 32]; - -Handle g_hCookie_LagCompSettings; -bool g_bDisableLagComp[MAXPLAYERS + 1]; -bool g_bPlayerLaserCompensated[MAXPLAYERS + 1]; -bool g_bLagCompMessages[MAXPLAYERS + 1]; -bool g_bSettingsTouched[MAXPLAYERS + 1]; -int g_iDisableLagComp[MAXPLAYERS + 1]; -ConVar g_cvCompenseEntityClass; -ConVar g_cvCheckUserPing; -ConVar g_cvMinimumPing; -ConVar g_cvMaxEntities; - -public void OnPluginStart() -{ - LoadTranslations("common.phrases"); - - g_cvCompenseEntityClass = CreateConVar("sm_lagcomp_entityclass", "0", "Only lagcompensate: [0 = All | 1 = func_physbox only]", _, true, 0.0, true, 1.0); - g_cvCheckUserPing = CreateConVar("sm_lagcomp_checkuserping", "0", "Check user's ping before lagcompensating them [0 = Disabled | 1 = Enabled]", _, true, 0.0, true, 1.0); - g_cvMinimumPing = CreateConVar("sm_lagcomp_ping", "180", "Minimum ping threshold to apply lagcomp on a client", _, true, 0.0); - g_cvMaxEntities = CreateConVar("sm_lagcomp_max_entities", "30", "Maximum entities lag compensated at the same time. Going over it disables lag compensation for everyone until the next round. [1-256]", _, true, 1.0, true, float(MAX_ENTITIES)); - - AutoExecConfig(true); - - Handle hGameData = LoadGameConfigFile("LagCompensation.games"); - if(!hGameData) - SetFailState("Failed to load LagCompensation gamedata."); - - // CBaseEntity::CalcAbsolutePosition - StartPrepSDKCall(SDKCall_Entity); - if(!PrepSDKCall_SetFromConf(hGameData, SDKConf_Signature, "CalcAbsolutePosition")) - { - delete hGameData; - SetFailState("PrepSDKCall_SetFromConf(hGameData, SDKConf_Signature, \"CalcAbsolutePosition\") failed!"); - } - g_hCalcAbsolutePosition = EndPrepSDKCall(); - - // CCollisionProperty::MarkPartitionHandleDirty - StartPrepSDKCall(SDKCall_Raw); - if(!PrepSDKCall_SetFromConf(hGameData, SDKConf_Signature, "MarkPartitionHandleDirty")) - { - delete hGameData; - SetFailState("PrepSDKCall_SetFromConf(hGameData, SDKConf_Signature, \"MarkPartitionHandleDirty\") failed!"); - } - g_hMarkPartitionHandleDirty = EndPrepSDKCall(); - - - // ::UTIL_Remove - g_hUTIL_Remove = DHookCreateFromConf(hGameData, "UTIL_Remove"); - if(!g_hUTIL_Remove) - { - delete hGameData; - SetFailState("Failed to setup detour for UTIL_Remove"); - } - - if(!DHookEnableDetour(g_hUTIL_Remove, false, Detour_OnUTIL_Remove)) - { - delete hGameData; - SetFailState("Failed to detour UTIL_Remove."); - } - - // CCSGameRules::RestartRound - g_hRestartRound = DHookCreateFromConf(hGameData, "CCSGameRules__RestartRound"); - if(!g_hRestartRound) - { - delete hGameData; - SetFailState("Failed to setup detour for CCSGameRules__RestartRound"); - } - - if(!DHookEnableDetour(g_hRestartRound, false, Detour_OnRestartRound)) - { - delete hGameData; - SetFailState("Failed to detour CCSGameRules__RestartRound."); - } - - // CLogicMeasureMovement::SetTarget - g_hSetTarget = DHookCreateFromConf(hGameData, "CLogicMeasureMovement__SetTarget"); - if(!g_hSetTarget) - { - delete hGameData; - SetFailState("Failed to setup detour for CLogicMeasureMovement__SetTarget"); - } - - if(!DHookEnableDetour(g_hSetTarget, false, Detour_OnSetTargetPre)) - { - delete hGameData; - SetFailState("Failed to detour CLogicMeasureMovement__SetTarget."); - } - - // CLogicMeasureMovement::SetTarget (fix post hook crashing due to this pointer being overwritten) - g_hSetTargetPost = DHookCreateFromConf(hGameData, "CLogicMeasureMovement__SetTarget_post"); - if(!g_hSetTargetPost) - { - delete hGameData; - SetFailState("Failed to setup detour for CLogicMeasureMovement__SetTarget_post"); - } - - if(!DHookEnableDetour(g_hSetTargetPost, true, Detour_OnSetTargetPost)) - { - delete hGameData; - SetFailState("Failed to detour CLogicMeasureMovement__SetTarget_post."); - } - - // CEntityTouchManager::FrameUpdatePostEntityThink - g_hFrameUpdatePostEntityThink = DHookCreateFromConf(hGameData, "CEntityTouchManager__FrameUpdatePostEntityThink"); - if(!g_hFrameUpdatePostEntityThink) - { - delete hGameData; - SetFailState("Failed to setup detour for CEntityTouchManager__FrameUpdatePostEntityThink"); - } - - if(!DHookEnableDetour(g_hFrameUpdatePostEntityThink, false, Detour_OnFrameUpdatePostEntityThink)) - { - delete hGameData; - SetFailState("Failed to detour CEntityTouchManager__FrameUpdatePostEntityThink."); - } - - - g_iNetworkableOuter = GameConfGetOffset(hGameData, "CServerNetworkableProperty::m_pOuter"); - if(g_iNetworkableOuter == -1) - { - delete hGameData; - SetFailState("GameConfGetOffset(hGameData, \"CServerNetworkableProperty::m_pOuter\") failed!"); - } - - - int offset = GameConfGetOffset(hGameData, "CGameRules::EndGameFrame"); - if(offset == -1) - { - delete hGameData; - SetFailState("Failed to find CGameRules::EndGameFrame offset."); - } - - // CGameRules::EndGameFrame - g_hEndGameFrame = DHookCreate(offset, HookType_GameRules, ReturnType_Void, ThisPointer_Ignore, Hook_EndGameFrame); - if(g_hEndGameFrame == INVALID_HANDLE) - { - delete hGameData; - SetFailState("Failed to DHook CGameRules::EndGameFrame."); - } - delete hGameData; - - - hGameData = LoadGameConfigFile("sdktools.games"); - if(!hGameData) - SetFailState("Failed to load sdktools gamedata."); - - offset = GameConfGetOffset(hGameData, "Activate"); - if(offset == -1) - { - delete hGameData; - SetFailState("Failed to find Activate offset"); - } - - // CPhysForce::Activate - g_hActivate = DHookCreate(offset, HookType_Entity, ReturnType_Void, ThisPointer_CBaseEntity, Hook_CPhysForce_Activate); - if(g_hActivate == INVALID_HANDLE) - { - delete hGameData; - SetFailState("Failed to DHookCreate Activate"); - } - - offset = GameConfGetOffset(hGameData, "AcceptInput"); - if(offset == -1) - { - delete hGameData; - SetFailState("Failed to find AcceptInput offset."); - } - - // CBaseEntity::AcceptInput( const char *szInputName, CBaseEntity *pActivator, CBaseEntity *pCaller, variant_t Value, int outputID ) - g_hAcceptInput = DHookCreate(offset, HookType_Entity, ReturnType_Bool, ThisPointer_CBaseEntity, Hook_AcceptInput); - if(g_hAcceptInput == INVALID_HANDLE) - { - delete hGameData; - SetFailState("Failed to DHook AcceptInput."); - } - - DHookAddParam(g_hAcceptInput, HookParamType_CharPtr); - DHookAddParam(g_hAcceptInput, HookParamType_CBaseEntity); - DHookAddParam(g_hAcceptInput, HookParamType_CBaseEntity); - DHookAddParam(g_hAcceptInput, HookParamType_Object, 20, DHookPass_ByVal|DHookPass_ODTOR|DHookPass_OCTOR|DHookPass_OASSIGNOP); // variant_t is a union of 12 (float[3]) plus two int type params 12 + 8 = 20 - DHookAddParam(g_hAcceptInput, HookParamType_Int); - - delete hGameData; - - // Capability provider from https://github.com/alliedmodders/sourcemod/pull/1078 - g_bHasOnEntitySpawned = GetFeatureStatus(FeatureType_Capability, "SDKHook_OnEntitySpawned") == FeatureStatus_Available; - - HookConVarChange(g_cvCompenseEntityClass, OnConVarChanged); - HookConVarChange(g_cvCheckUserPing, OnConVarChanged); - HookConVarChange(g_cvMinimumPing, OnConVarChanged); - HookConVarChange(g_cvMaxEntities, OnConVarChanged); - - - g_hCookie_LagCompSettings = RegClientCookie("lagcomp_settings", "LagCompensation Settings", CookieAccess_Private); - RegConsoleCmd("sm_lagcomp", OnLagCompSettings); - RegConsoleCmd("sm_0ping", OnToggleLagCompSettings); - RegConsoleCmd("sm_0pinglasers", OnToggleLagCompLasersSettings); - RegConsoleCmd("sm_checklag", CheckLagComp); - SetCookieMenuItem(MenuHandler_CookieMenu, 0, "LagCompensation"); - - CreateTimer(0.1, DisableLagCompTimer, _, TIMER_REPEAT); - - RegAdminCmd("sm_unlag", Command_AddLagCompensation, ADMFLAG_ROOT, "sm_unlag [late]"); - RegAdminCmd("sm_lagged", Command_CheckLagCompensated, ADMFLAG_ROOT, "sm_lagged"); - RegAdminCmd("sm_lagcomp_enable", Command_EnableLagCompensation, ADMFLAG_GENERIC, "Re-enables lag compensation after it was disabled for going over sm_lagcomp_max_entities"); - - FilterClientSolidTouch(g_aaFilterClientSolidTouch, true); - BlockTriggerMoved(g_aBlockTriggerMoved, true); -} - -public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) -{ - RegPluginLibrary("LagCompensation"); - g_bLateLoad = late; - return APLRes_Success; -} - -public void OnLibraryRemoved(const char[] name) -{ - if(strcmp(name, "PhysHooks", false) == 0) - g_bHasPhysHooks = false; -} - -public void OnPluginEnd() -{ - g_bCleaningUp = true; - if(g_bHasPhysHooks) - { - FilterClientSolidTouch(g_aaFilterClientSolidTouch, false); - BlockTriggerMoved(g_aBlockTriggerMoved, false); - BlockTriggerTouchPlayers(g_aBlockTriggerTouchPlayers, false); - } - - DHookDisableDetour(g_hUTIL_Remove, false, Detour_OnUTIL_Remove); - - for(int i = 0; i < g_iNumEntities; i++) - { - if(!IsValidEntity(g_aEntityLagData[i].iEntity)) - continue; - - if(g_aEntityLagData[i].iDeleted) - { - RemoveEdict(g_aEntityLagData[i].iEntity); - } - } -} - -public void OnConfigsExecuted() -{ - g_iCompenseEntityClass = GetConVarInt(g_cvCompenseEntityClass); - g_bCheckPing = GetConVarBool(g_cvCheckUserPing); - g_iMinPing = GetConVarInt(g_cvMinimumPing); - g_iMaxEntities = GetConVarInt(g_cvMaxEntities); -} - -void OnConVarChanged(ConVar convar, const char[] oldValue, const char[] newValue) -{ - if (convar == g_cvCompenseEntityClass) - g_iCompenseEntityClass = GetConVarInt(convar); - else if (convar == g_cvCheckUserPing) - g_bCheckPing = GetConVarBool(convar); - else if (convar == g_cvMinimumPing) - g_iMinPing = GetConVarInt(convar); - else if (convar == g_cvMaxEntities) - g_iMaxEntities = GetConVarInt(convar); -} - -public void OnMapStart() -{ - char map[128]; - GetCurrentMap(map, sizeof(map)); - g_bMapDisabled = GetMapLagCompensationDisabled(map); - - bool bLate = g_bLateLoad; - - DHookGamerules(g_hEndGameFrame, true); - - g_bCleaningUp = false; - - g_fTickInterval = GetTickInterval(); - - g_iParent = FindDataMapInfo(0, "m_pParent"); - g_iSpawnFlags = FindDataMapInfo(0, "m_spawnflags"); - g_iCollision = FindDataMapInfo(0, "m_Collision"); - g_iSolidFlags = FindDataMapInfo(0, "m_usSolidFlags"); - g_iSolidType = FindDataMapInfo(0, "m_nSolidType"); - g_iSurroundType = FindDataMapInfo(0, "m_nSurroundType"); - g_iEFlags = FindDataMapInfo(0, "m_iEFlags"); - - g_iVecOrigin = FindDataMapInfo(0, "m_vecOrigin"); - g_iVecAbsOrigin = FindDataMapInfo(0, "m_vecAbsOrigin"); - g_iAngRotation = FindDataMapInfo(0, "m_angRotation"); - g_iAngAbsRotation = FindDataMapInfo(0, "m_angAbsRotation"); - g_iVecMins = FindDataMapInfo(0, "m_vecMins"); - g_iVecMaxs = FindDataMapInfo(0, "m_vecMaxs"); - g_iSimulationTime = FindDataMapInfo(0, "m_flSimulationTime"); - g_iCoordinateFrame = FindDataMapInfo(0, "m_rgflCoordinateFrame"); - - /* Late Load */ - if(bLate) - { - for (int client = 1; client <= MaxClients; client++) - { - if(IsClientInGame(client)) - { - OnClientConnected(client); - if(AreClientCookiesCached(client)) - OnClientCookiesCached(client); - OnClientSettingsChanged(client); - } - } - - int entity = INVALID_ENT_REFERENCE; - while((entity = FindEntityByClassname(entity, "*")) != INVALID_ENT_REFERENCE) - { - char sClassname[64]; - if(GetEntityClassname(entity, sClassname, sizeof(sClassname))) - { - OnEntityCreated(entity, sClassname); - OnEntitySpawned(entity, sClassname); - - if(strcmp(sClassname, "phys_thruster", false) == 0) - { - Hook_CPhysForce_Activate(entity); - } - } - } - } - - g_bLateLoad = false; -} - -public void OnMapEnd() -{ - Detour_OnRestartRound(); - g_bCleaningUp = true; -} - -public void OnClientConnected(int client) -{ - // Must match the defaults in ParseClientCookie() for clients whose cookies never cache. - g_bDisableLagComp[client] = false; - g_bPlayerLaserCompensated[client] = true; - g_bLagCompMessages[client] = false; - g_bSettingsTouched[client] = false; - g_iDisableLagComp[client] = 0; - g_aLerpTicks[client] = 0; -} - -public void OnClientCookiesCached(int client) -{ - // A toggle made before the cookies arrived wins, so flush it instead of - // overwriting the client's choice with the stored value. - if(g_bSettingsTouched[client]) - { - SaveLagCompSettings(client); - return; - } - - // Load all settings from single cookie - ParseClientCookie(client, g_bDisableLagComp[client], g_bPlayerLaserCompensated[client], g_bLagCompMessages[client]); -} - -public void OnClientSettingsChanged(int client) -{ - if(!IsClientInGame(client) || IsFakeClient(client)) - return; - - float fLerpTime = GetEntPropFloat(client, Prop_Data, "m_fLerpTime"); - g_aLerpTicks[client] = RoundToNearest(fLerpTime / g_fTickInterval); -} - -public void OnClientDisconnect(int client) -{ - g_bDisableLagComp[client] = false; - g_bPlayerLaserCompensated[client] = true; - g_bLagCompMessages[client] = false; - g_bSettingsTouched[client] = false; - g_iDisableLagComp[client] = 0; -} - -public void OnEntityCreated(int entity, const char[] classname) -{ - if(g_bCleaningUp) - return; - - if (strcmp(classname, "phys_thruster", false) == 0) - { - DHookEntity(g_hActivate, true, entity); - } - else if (strcmp(classname, "game_ui", false) == 0) - { - DHookEntity(g_hAcceptInput, true, entity); - } - - if (!g_bHasOnEntitySpawned && (!strncmp(classname, "func_physbox", 12, false) || - (g_iCompenseEntityClass == 0 && (strcmp(classname, "trigger_hurt", false) == 0 || - strcmp(classname, "trigger_push", false) == 0 || strcmp(classname, "trigger_teleport", false) == 0)))) - { - SDKHook(entity, SDKHook_SpawnPost, OnSDKHookEntitySpawnPost); - } -} - -public void OnSDKHookEntitySpawnPost(int entity) -{ - char classname[64]; - GetEntityClassname(entity, classname, sizeof(classname)); - - OnEntitySpawned(entity, classname); -} - -public void OnEntitySpawned(int entity, const char[] classname) -{ - if(g_bCleaningUp) - return; - - CheckEntityForLagComp(entity, classname); -} - -public MRESReturn Hook_AcceptInput(int entity, Handle hReturn, Handle hParams) -{ - if(!IsValidEntity(entity)) - return MRES_Ignored; - - char sCommand[128]; - DHookGetParamString(hParams, 1, sCommand, sizeof(sCommand)); - - if (strcmp(sCommand, "Activate", false) != 0) - return MRES_Ignored; - - if(DHookIsNullParam(hParams, 3)) - return MRES_Ignored; - - int iCaller = DHookGetParam(hParams, 3); - if(iCaller <= 0 || iCaller >= MAX_EDICTS) - return MRES_Ignored; - - // Don't lagcompensate anything that has a game_ui button in their hierarchy. - BlacklistFamily(iCaller); - - return MRES_Ignored; -} - -void BlacklistFamily(int entity) -{ - if(entity > 0 && entity < MAX_EDICTS) - { - SetBit(g_aBlacklisted, entity); - RemoveEntityFromLagCompensation(entity); - } - - // Blacklist children of this entity - BlacklistChildren(entity); - - // And blacklist all parents and their children - for(;;) - { - entity = GetEntDataEnt2(entity, g_iParent); - if(entity == INVALID_ENT_REFERENCE) - break; - - if(entity > 0 && entity < MAX_EDICTS) - { - SetBit(g_aBlacklisted, entity); - RemoveEntityFromLagCompensation(entity); - } - - // And their children - BlacklistChildren(entity); - } -} - -void BlacklistChildren(int parent) -{ - int entity = INVALID_ENT_REFERENCE; - while((entity = FindEntityByClassname(entity, "*")) != INVALID_ENT_REFERENCE) - { - if(GetEntDataEnt2(entity, g_iParent) != parent) - continue; - - if(entity > 0 && entity < MAX_EDICTS) - { - SetBit(g_aBlacklisted, entity); - RemoveEntityFromLagCompensation(entity); - } - } -} - -bool CheckEntityForLagComp(int entity, const char[] classname, bool bRecursive=false, bool bGoodParents=false) -{ - if(entity < 0 || entity >= MAX_EDICTS) - return false; - - if(!IsValidEntity(entity)) - return false; - - // Disabled for the rest of the round. - if(g_bLagCompSuspended) - return false; - - if(g_aLagCompensated[entity] != -1) - return false; - - int SpawnFlags = GetEntData(entity, g_iSpawnFlags); - if(SpawnFlags & SF_LAGCOMP_DISABLE) - return false; - - bool bTrigger = false; - - if (g_iCompenseEntityClass == 0) - bTrigger = strcmp(classname, "trigger_hurt", false) == 0 || strcmp(classname, "trigger_push", false) == 0 || strcmp(classname, "trigger_teleport", false) == 0; - - bool bPhysbox = !strncmp(classname, "func_physbox", 12, false); - - bool bBlacklisted = CheckBit(g_aBlacklisted, entity); - - if(!bTrigger && !bPhysbox || bBlacklisted) - return false; - - // Dont lag compensate anything that could be parented to a player - // The player simulation would usually move the entity, - // but we would overwrite that position change by restoring the entity to its previous state. - int iParent = INVALID_ENT_REFERENCE; - char sParentClassname[64]; - for(int iTmp = entity;;) - { - iTmp = GetEntDataEnt2(iTmp, g_iParent); - if(iTmp == INVALID_ENT_REFERENCE) - break; - - iParent = iTmp; - GetEntityClassname(iParent, sParentClassname, sizeof(sParentClassname)); - - if((iParent >= 1 && iParent <= MaxClients) || - !strncmp(sParentClassname, "weapon_", 7)) - { - return false; - } - - if(CheckBit(g_aBlacklisted, iParent)) - { - return false; - } - - if(g_aLagCompensated[iParent] != -1) - { - bGoodParents = true; - break; - } - - if(strncmp(sParentClassname, "func_", 5)) - continue; - - if(strcmp(sParentClassname[5], "movelinear", true) == 0 || - strcmp(sParentClassname[5], "door", true) == 0 || - strcmp(sParentClassname[5], "rotating", true) == 0 || - strcmp(sParentClassname[5], "tracktrain", true) == 0) - { - bGoodParents = true; - break; - } - } - - if(!bGoodParents) - return false; - - // One more than allowed: switch lag compensation off until the next round. - //switch lag comp off every round if the map is not allowed to use it - if(g_iNumEntities >= g_iMaxEntities || g_bMapDisabled) - { - SuspendLagCompensation(); - return false; - } - - if(AddEntityForLagCompensation(entity, bTrigger)) - { - if(bTrigger) - { - if(!(SpawnFlags & (SF_TRIGGER_ALLOW_PUSHABLES | SF_TRIGGER_ALLOW_PHYSICS | SF_TRIGGER_ALLOW_ALL | SF_TRIG_TOUCH_DEBRIS))) - SetBit(g_aBlockTriggerMoved, entity); - } - - if(bRecursive) - { - CheckEntityChildrenForLagComp(entity); - } - - return true; - } - - return false; -} - -void CheckEntityChildrenForLagComp(int parent) -{ - int entity = INVALID_ENT_REFERENCE; - while((entity = FindEntityByClassname(entity, "*")) != INVALID_ENT_REFERENCE) - { - if(GetEntDataEnt2(entity, g_iParent) != parent) - continue; - - char sClassname[64]; - if(GetEntityClassname(entity, sClassname, sizeof(sClassname))) - { - CheckEntityForLagComp(entity, sClassname, _, true); - CheckEntityChildrenForLagComp(entity); - } - } -} - -public void OnEntityDestroyed(int entity) -{ - if(g_bCleaningUp) - return; - - if(entity < 0 || entity >= MAX_EDICTS) - return; - - ClearBit(g_aBlacklisted, entity); - - int iIndex = g_aLagCompensated[entity]; - if(iIndex == -1) - return; - - RemoveRecord(iIndex); -} - - -public MRESReturn Detour_OnUTIL_Remove(Handle hParams) -{ - if(g_bCleaningUp) - return MRES_Ignored; - - if(DHookIsNullParam(hParams, 1)) - return MRES_Ignored; - - int entity = DHookGetParamObjectPtrVar(hParams, 1, g_iNetworkableOuter, ObjectValueType_CBaseEntityPtr); - if(entity < 0 || entity >= MAX_EDICTS) - return MRES_Ignored; - - int iIndex = g_aLagCompensated[entity]; - if(iIndex == -1) - return MRES_Ignored; - - // let it die - if(!g_aEntityLagData[iIndex].bLateKill) - return MRES_Ignored; - - // ignore sleeping entities - if(g_aEntityLagData[iIndex].iNotMoving >= MAX_RECORDS) - return MRES_Ignored; - - if(!g_aEntityLagData[iIndex].iDeleted) - { - g_aEntityLagData[iIndex].iDeleted = GetGameTickCount(); - } - - return MRES_Supercede; -} - -public MRESReturn Detour_OnRestartRound() -{ - g_bCleaningUp = true; - - ReleaseAllEntities(); - - for(int i = 0; i < sizeof(g_aBlacklisted); i++) - g_aBlacklisted[i] = 0; - - // New round, lag compensation is back on. - g_bLagCompSuspended = false; - - g_bCleaningUp = false; - return MRES_Ignored; -} - -// Stops compensating everything that is currently tracked. -void ReleaseAllEntities() -{ - g_bReleasePending = false; - - for(int i = 0; i < g_iNumEntities; i++) - { - int iEntity = g_aEntityLagData[i].iEntity; - bool bValid = IsValidEntity(iEntity); - - // Should never be rewound at this point, but never leave an entity in the past. - if(g_aEntityLagData[i].bRestore && bValid) - RestoreEntityFromRecord(iEntity, g_aaLagRecords[i][g_aEntityLagData[i].iRecordIndex]); - g_aEntityLagData[i].bRestore = false; - - g_aLagCompensated[iEntity] = -1; - ClearBit(g_aBlockTriggerTouchPlayers, iEntity); - ClearBit(g_aBlockTriggerMoved, iEntity); - - for(int client = 1; client <= MaxClients; client++) - { - ClearBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); - } - - if(g_aEntityLagData[i].iDeleted && bValid) - { - ClearBit(g_aBlacklisted, iEntity); - RemoveEdict(iEntity); - } - - g_aEntityLagData[i].iEntity = INVALID_ENT_REFERENCE; - } - - g_iNumEntities = 0; -} - -void ReleaseAllEntitiesNow() -{ - bool bWasCleaningUp = g_bCleaningUp; - g_bCleaningUp = true; - ReleaseAllEntities(); - g_bCleaningUp = bWasCleaningUp; -} - -void SuspendLagCompensation() -{ - if(g_bLagCompSuspended) - return; - - g_bLagCompSuspended = true; - g_bReleasePending = true; - - for(int client = 1; client <= MaxClients; client++) - { - if(IsClientInGame(client) && !IsFakeClient(client) && !g_bDisableLagComp[client]) - CPrintToChat(client, "%s LagCompensation has been {red}disabled{default} until the next round, too many entities needed to be compensated.", PREFIX); - } -} - -// https://developer.valvesoftware.com/wiki/Logic_measure_movement -int g_OnSetTarget_pThis; -public MRESReturn Detour_OnSetTargetPre(int pThis, Handle hParams) -{ - g_OnSetTarget_pThis = pThis; - return MRES_Ignored; -} -public MRESReturn Detour_OnSetTargetPost(Handle hParams) -{ - int entity = GetEntPropEnt(g_OnSetTarget_pThis, Prop_Data, "m_hTarget"); - if(!IsValidEntity(entity)) - return MRES_Ignored; - - char sClassname[64]; - if(!GetEntityClassname(entity, sClassname, sizeof(sClassname))) - return MRES_Ignored; - - CheckEntityForLagComp(entity, sClassname, true, true); - - return MRES_Ignored; -} - -public MRESReturn Hook_CPhysForce_Activate(int entity) -{ - int attachedObject = GetEntPropEnt(entity, Prop_Data, "m_attachedObject"); - if(!IsValidEntity(attachedObject)) - return MRES_Ignored; - - char sClassname[64]; - if(!GetEntityClassname(attachedObject, sClassname, sizeof(sClassname))) - return MRES_Ignored; - - CheckEntityForLagComp(attachedObject, sClassname, true, true); - - return MRES_Ignored; -} - -public MRESReturn Detour_OnFrameUpdatePostEntityThink() -{ - for(int i = 0; i < g_iNumEntities; i++) - { - // Dont make the entity check untouch in FrameUpdatePostEntityThink. - // If the player didn't get simulated in the current frame then - // they didn't have a chance to touch this entity. - // Hence the touchlink could be broken and we only let the player check untouch. - int EFlags = GetEntData(g_aEntityLagData[i].iEntity, g_iEFlags); - EFlags &= ~EFL_CHECK_UNTOUCH; - SetEntData(g_aEntityLagData[i].iEntity, g_iEFlags, EFlags); - } - return MRES_Ignored; -} - - -public void OnRunThinkFunctions(bool simulating) -{ - g_iGameTick = GetGameTickCount(); - BlockTriggerTouchPlayers(g_aBlockTriggerTouchPlayers, false); -} - -public Action OnPlayerRunCmd(int client, int &buttons, int &impulse, float vel[3], float angles[3], int &weapon, int &subtype, int &cmdnum, int &tickcount, int &seed, int mouse[2]) -{ - if(!IsClientInGame(client) || !IsPlayerAlive(client) || IsFakeClient(client)) - return Plugin_Continue; - - if(g_bLagCompSuspended) - return Plugin_Continue; - - int iTargetTick = tickcount - g_aLerpTicks[client]; - - // -1 because the newest record in the list is one tick old - // this is because we simulate players first - // hence no new entity record was inserted on the current tick - int iDelta = g_iGameTick - iTargetTick - 1; - - // The player is stupid and doesnt want lag compensation. - // To get the original behavior back lets assume they actually have 0 latency. - // To avoid abusing toggling lagcomp we increase/decrease this var by 1 every 100ms. - // This is so we only skip single ticks at a time. Fully ON = 0, Fully OFF = MAX_RECORDS - iDelta -= g_iDisableLagComp[client]; - - if(iDelta < 0) - iDelta = 0; - if(iDelta > MAX_RECORDS) - iDelta = MAX_RECORDS; - - int iPlayerSimTick = g_iGameTick - iDelta; - - for(int i = 0; i < g_iNumEntities; i++) - { - int iEntity = g_aEntityLagData[i].iEntity; - - // Entity too new, the client couldnt even see it yet. - if(g_aEntityLagData[i].iSpawned > iPlayerSimTick) - { - SetBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); - continue; - } - - if(g_aEntityLagData[i].iDeleted) - { - if(g_aEntityLagData[i].iDeleted <= iPlayerSimTick) - { - SetBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); - continue; - } - } - else - { - ClearBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); - } - - if(g_aEntityLagData[i].iNotMoving >= MAX_RECORDS) - continue; - - int iRecord = iDelta; - - if(!g_bPlayerLaserCompensated[client] && - (strcmp(g_aEntityLagData[i].sClassname, "trigger_hurt", false) == 0 || - strcmp(g_aEntityLagData[i].sClassname, "trigger_push", false) == 0 || - strcmp(g_aEntityLagData[i].sClassname, "trigger_teleport", false) == 0)) - iRecord = 0; - - if(iRecord >= g_aEntityLagData[i].iNumRecords) - iRecord = g_aEntityLagData[i].iNumRecords - 1; - - int iRecordIndex = g_aEntityLagData[i].iRecordIndex - iRecord; - if(iRecordIndex < 0) - iRecordIndex += MAX_RECORDS; - - RestoreEntityFromRecord(iEntity, g_aaLagRecords[i][iRecordIndex]); - g_aEntityLagData[i].bRestore = !g_aEntityLagData[i].iDeleted; - } - - return Plugin_Continue; -} - -public void OnPostPlayerThinkFunctions() -{ - for(int i = 0; i < g_iNumEntities; i++) - { - if(!g_aEntityLagData[i].bRestore) - continue; - - RestoreEntityFromRecord(g_aEntityLagData[i].iEntity, g_aaLagRecords[i][g_aEntityLagData[i].iRecordIndex]); - g_aEntityLagData[i].bRestore = false; - } - - BlockTriggerTouchPlayers(g_aBlockTriggerTouchPlayers, true); -} - -public MRESReturn Hook_EndGameFrame() -{ - // Lag compensation got disabled this frame, let go of everything. - if(g_bReleasePending) - { - ReleaseAllEntitiesNow(); - return MRES_Ignored; - } - - for(int i = 0; i < g_iNumEntities; i++) - { - if(g_aEntityLagData[i].iDeleted) - { - if(g_aEntityLagData[i].iDeleted + MAX_RECORDS <= g_iGameTick) - { - // calls OnEntityDestroyed right away - // which calls RemoveRecord - // which moves the next element to our current position - RemoveEdict(g_aEntityLagData[i].iEntity); - i--; continue; - } - - if(g_aEntityLagData[i].iRecordsValid) - { - g_aEntityLagData[i].iRecordIndex++; - - if(g_aEntityLagData[i].iRecordIndex >= MAX_RECORDS) - g_aEntityLagData[i].iRecordIndex = 0; - - g_aEntityLagData[i].iRecordsValid--; - } - - continue; - } - - LagRecord TmpRecord; - RecordDataIntoRecord(g_aEntityLagData[i].iEntity, TmpRecord); - - // sleep detection - { - int iOldRecord = g_aEntityLagData[i].iRecordIndex; - - if(CompareVectors(g_aaLagRecords[i][iOldRecord].vecAbsOrigin, TmpRecord.vecAbsOrigin) && - CompareVectors(g_aaLagRecords[i][iOldRecord].angAbsRotation, TmpRecord.angAbsRotation)) - { - g_aEntityLagData[i].iNotMoving++; - } - else - { - g_aEntityLagData[i].iNotMoving = 0; - } - - if(g_aEntityLagData[i].iNotMoving >= MAX_RECORDS) - continue; - } - - g_aEntityLagData[i].iRecordIndex++; - - if(g_aEntityLagData[i].iRecordIndex >= MAX_RECORDS) - g_aEntityLagData[i].iRecordIndex = 0; - - if(g_aEntityLagData[i].iNumRecords < MAX_RECORDS) - g_aEntityLagData[i].iRecordsValid = ++g_aEntityLagData[i].iNumRecords; - - LagRecord_Copy(g_aaLagRecords[i][g_aEntityLagData[i].iRecordIndex], TmpRecord); - } - - return MRES_Ignored; -} - - -void RecordDataIntoRecord(int iEntity, LagRecord Record) -{ - // Force recalculation of all values - int EFlags = GetEntData(iEntity, g_iEFlags); - EFlags |= EFL_DIRTY_ABSTRANSFORM; - SetEntData(iEntity, g_iEFlags, EFlags); - - SDKCall(g_hCalcAbsolutePosition, iEntity); - - GetEntDataVector(iEntity, g_iVecOrigin, Record.vecOrigin); - GetEntDataVector(iEntity, g_iVecAbsOrigin, Record.vecAbsOrigin); - GetEntDataVector(iEntity, g_iAngRotation, Record.angRotation); - GetEntDataVector(iEntity, g_iAngAbsRotation, Record.angAbsRotation); - GetEntDataVector(iEntity, g_iVecMins, Record.vecMins); - GetEntDataVector(iEntity, g_iVecMaxs, Record.vecMaxs); - GetEntDataArray(iEntity, g_iCoordinateFrame, view_as(Record.rgflCoordinateFrame), COORDINATE_FRAME_SIZE); - Record.flSimulationTime = GetEntDataFloat(iEntity, g_iSimulationTime); -} - -bool DoesRotationInvalidateSurroundingBox(int iEntity) -{ - int SolidFlags = GetEntData(iEntity, g_iSolidFlags); - if(SolidFlags & FSOLID_ROOT_PARENT_ALIGNED) - return true; - - int SurroundType = GetEntData(iEntity, g_iSurroundType); - switch(SurroundType) - { - case USE_COLLISION_BOUNDS_NEVER_VPHYSICS, - USE_OBB_COLLISION_BOUNDS, - USE_BEST_COLLISION_BOUNDS: - { - // IsBoundsDefinedInEntitySpace() - int SolidType = GetEntData(iEntity, g_iSolidType); - return ((SolidFlags & FSOLID_FORCE_WORLD_ALIGNED) == 0) && - (SolidType != SOLID_BBOX) && (SolidType != SOLID_NONE); - } - - case USE_HITBOXES, - USE_GAME_CODE: - { - return true; - } - - case USE_ROTATION_EXPANDED_BOUNDS, - USE_SPECIFIED_BOUNDS: - { - return false; - } - - default: - { - return true; - } - } -} - -void InvalidatePhysicsRecursive(int iEntity) -{ - // CollisionProp()->MarkPartitionHandleDirty(); - Address CollisionProp = GetEntityAddress(iEntity) + view_as
(g_iCollision); - SDKCall(g_hMarkPartitionHandleDirty, CollisionProp); - - if(DoesRotationInvalidateSurroundingBox(iEntity)) - { - // CollisionProp()->MarkSurroundingBoundsDirty(); - int EFlags = GetEntData(iEntity, g_iEFlags); - EFlags |= EFL_DIRTY_SURROUNDING_COLLISION_BOUNDS; - SetEntData(iEntity, g_iEFlags, EFlags); - } -} - -void RestoreEntityFromRecord(int iEntity, LagRecord Record) -{ - SetEntDataVector(iEntity, g_iVecOrigin, Record.vecOrigin); - SetEntDataVector(iEntity, g_iVecAbsOrigin, Record.vecAbsOrigin); - SetEntDataVector(iEntity, g_iAngRotation, Record.angRotation); - SetEntDataVector(iEntity, g_iAngAbsRotation, Record.angAbsRotation); - SetEntDataVector(iEntity, g_iVecMins, Record.vecMins); - SetEntDataVector(iEntity, g_iVecMaxs, Record.vecMaxs); - SetEntDataArray(iEntity, g_iCoordinateFrame, view_as(Record.rgflCoordinateFrame), COORDINATE_FRAME_SIZE); - SetEntDataFloat(iEntity, g_iSimulationTime, Record.flSimulationTime); - - InvalidatePhysicsRecursive(iEntity); -} - - -bool AddEntityForLagCompensation(int iEntity, bool bLateKill) -{ - if(g_bCleaningUp) - return false; - - // sm_unlag takes an arbitrary index from the console, so validate before indexing anything. - if(iEntity < 0 || iEntity >= MAX_EDICTS || !IsValidEntity(iEntity)) - return false; - - if(g_aLagCompensated[iEntity] != -1) - return false; - - char sClassname[64]; - GetEntityClassname(iEntity, sClassname, sizeof(sClassname)); - - char sTargetname[64]; - GetEntPropString(iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); - - int iHammerID = GetEntProp(iEntity, Prop_Data, "m_iHammerID"); - - if(g_iNumEntities >= MAX_ENTITIES) - { - PrintToBoth("[%d] OUT OF LAGCOMP SLOTS entity %d (%s)\"%s\"(#%d)", GetGameTickCount(), iEntity, sClassname, sTargetname, iHammerID); - LogError("OUT OF LAGCOMP SLOTS entity %d (%s)\"%s\"(#%d)", iEntity, sClassname, sTargetname, iHammerID); - return false; - } - - int i = g_iNumEntities; - g_iNumEntities++; - - g_aLagCompensated[iEntity] = i; - - g_aEntityLagData[i].iEntity = iEntity; - g_aEntityLagData[i].iRecordIndex = 0; - g_aEntityLagData[i].iNumRecords = 1; - g_aEntityLagData[i].iRecordsValid = 1; - g_aEntityLagData[i].iSpawned = GetGameTickCount(); - g_aEntityLagData[i].iDeleted = 0; - g_aEntityLagData[i].iNotMoving = MAX_RECORDS; - g_aEntityLagData[i].bRestore = false; - g_aEntityLagData[i].bLateKill = bLateKill; - g_aEntityLagData[i].sClassname = sClassname; - - if(bLateKill) - { - SetBit(g_aBlockTriggerTouchPlayers, iEntity); - } - - RecordDataIntoRecord(iEntity, g_aaLagRecords[i][0]); - PrintToBoth("[%d] added entity %d (%s)\"%s\"(#%d) under index %d", GetGameTickCount(), iEntity, sClassname, sTargetname, iHammerID, i); - - return true; -} - -bool RemoveEntityFromLagCompensation(int iEntity) -{ - int index = g_aLagCompensated[iEntity]; - if(index == -1) - return false; - - RemoveRecord(index); - return true; -} - -void RemoveRecord(int index) -{ - if(g_bCleaningUp) - return; - - int iEntity = g_aEntityLagData[index].iEntity; - - if(IsValidEntity(iEntity)) - { - char sClassname[64]; - GetEntityClassname(g_aEntityLagData[index].iEntity, sClassname, sizeof(sClassname)); - - char sTargetname[64]; - GetEntPropString(g_aEntityLagData[index].iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); - - int iHammerID = GetEntProp(g_aEntityLagData[index].iEntity, Prop_Data, "m_iHammerID"); - - PrintToBoth("[%d] RemoveRecord %d / %d (%s)\"%s\"(#%d), num: %d", GetGameTickCount(), index, g_aEntityLagData[index].iEntity, sClassname, sTargetname, iHammerID, g_iNumEntities); - } - - g_aLagCompensated[iEntity] = -1; - ClearBit(g_aBlockTriggerTouchPlayers, iEntity); - ClearBit(g_aBlockTriggerMoved, iEntity); - - for(int client = 1; client <= MaxClients; client++) - { - ClearBit(g_aaFilterClientSolidTouch, client * MAX_EDICTS + iEntity); - } - - g_aEntityLagData[index].iEntity = INVALID_ENT_REFERENCE; - - for(int src = index + 1; src < g_iNumEntities; src++) - { - int dest = src - 1; - - EntityLagData_Copy(g_aEntityLagData[dest], g_aEntityLagData[src]); - g_aEntityLagData[src].iEntity = INVALID_ENT_REFERENCE; - g_aLagCompensated[g_aEntityLagData[dest].iEntity] = dest; - - int iNumRecords = g_aEntityLagData[dest].iNumRecords; - for(int i = 0; i < iNumRecords; i++) - { - LagRecord_Copy(g_aaLagRecords[dest][i], g_aaLagRecords[src][i]); - } - } - - g_iNumEntities--; -} - -void EntityLagData_Copy(EntityLagData obj, const EntityLagData other) -{ - obj.iEntity = other.iEntity; - obj.iRecordIndex = other.iRecordIndex; - obj.iNumRecords = other.iNumRecords; - obj.iRecordsValid = other.iRecordsValid; - obj.iSpawned = other.iSpawned; - obj.iDeleted = other.iDeleted; - obj.iNotMoving = other.iNotMoving; - obj.bRestore = other.bRestore; - obj.bLateKill = other.bLateKill; - obj.sClassname = other.sClassname; -} - -void LagRecord_Copy(LagRecord obj, const LagRecord other) -{ - for(int i = 0; i < 3; i++) - { - obj.vecOrigin[i] = other.vecOrigin[i]; - obj.vecAbsOrigin[i] = other.vecAbsOrigin[i]; - obj.angRotation[i] = other.angRotation[i]; - obj.angAbsRotation[i] = other.angAbsRotation[i]; - obj.vecMins[i] = other.vecMins[i]; - obj.vecMaxs[i] = other.vecMaxs[i]; - } - - obj.flSimulationTime = other.flSimulationTime; - - for(int i = 0; i < COORDINATE_FRAME_SIZE; i++) - { - obj.rgflCoordinateFrame[i] = other.rgflCoordinateFrame[i]; - } -} - -bool CompareVectors(const float vec1[3], const float vec2[3]) -{ - return vec1[0] == vec2[0] && vec1[1] == vec2[1] && vec1[2] == vec2[2]; -} - -void SaveLagCompSettings(int client) -{ - // Remember that this client chose something, so OnClientCookiesCached - // flushes it rather than loading over the top of it. - g_bSettingsTouched[client] = true; - - // Cookie reads/writes are meaningless until the cookies arrive; we get called back then. - if(!AreClientCookiesCached(client)) - return; - - // Read current cookie values - bool currentDisableLagComp, currentPlayerLaserCompensated, currentLagCompMessages; - ParseClientCookie(client, currentDisableLagComp, currentPlayerLaserCompensated, currentLagCompMessages); - - // Check if values have changed - bool disableChanged = g_bDisableLagComp[client] != currentDisableLagComp; - bool laserChanged = g_bPlayerLaserCompensated[client] != currentPlayerLaserCompensated; - bool messagesChanged = g_bLagCompMessages[client] != currentLagCompMessages; - - // If no values have changed, no need to save - if (!disableChanged && !laserChanged && !messagesChanged) { - return; - } - - // Otherwise, save the chain format - char sBuffer[8]; - Format(sBuffer, sizeof(sBuffer), "%d%d%d", - g_bDisableLagComp[client] ? 1 : 0, - g_bPlayerLaserCompensated[client] ? 1 : 0, - g_bLagCompMessages[client] ? 1 : 0); - SetClientCookie(client, g_hCookie_LagCompSettings, sBuffer); -} - -void ParseClientCookie(int client, bool &disableLagComp, bool &playerLaserCompensated, bool &lagCompMessages) -{ - char buffer[16]; - GetClientCookie(client, g_hCookie_LagCompSettings, buffer, sizeof(buffer)); - - // Parse chain format: disable|laser|messages - if (strlen(buffer) >= 3) - { - disableLagComp = (buffer[0] == '1'); - playerLaserCompensated = (buffer[1] == '1'); - lagCompMessages = (buffer[2] == '1'); - } - else - { - // Default values - disableLagComp = false; - playerLaserCompensated = true; - lagCompMessages = false; - } -} - -public Action Command_AddLagCompensation(int client, int argc) -{ - if(argc < 1) - { - ReplyToCommand(client, "[SM] Usage: sm_unlag [late]"); - return Plugin_Handled; - } - - char sArgs[32]; - GetCmdArg(1, sArgs, sizeof(sArgs)); - - int entity = StringToInt(sArgs); - - bool late = false; - if(argc >= 2) - { - GetCmdArg(2, sArgs, sizeof(sArgs)); - late = view_as(StringToInt(sArgs)); - } - - if(g_bLagCompSuspended) - { - ReplyToCommand(client, "[SM] LagCompensation is disabled until the next round, use sm_lagcomp_enable first."); - return Plugin_Handled; - } - - AddEntityForLagCompensation(entity, late); - - return Plugin_Handled; -} - -public Action Command_EnableLagCompensation(int client, int argc) -{ - if(!g_bLagCompSuspended) - { - ReplyToCommand(client, "[SM] LagCompensation is already enabled."); - return Plugin_Handled; - } - - // Let go of whatever was tracked before it got disabled, so only - // entities that spawn from now on are compensated. - if(g_bReleasePending) - ReleaseAllEntitiesNow(); - - g_bLagCompSuspended = false; - - ReplyToCommand(client, "[SM] LagCompensation has been re-enabled."); - - for(int i = 1; i <= MaxClients; i++) - { - if(IsClientInGame(i) && !IsFakeClient(i) && !g_bDisableLagComp[i]) - CPrintToChat(i, "%s LagCompensation has been {green}re-enabled{default} by an admin.", PREFIX); - } - - return Plugin_Handled; -} - -public Action Command_CheckLagCompensated(int client, int argc) -{ - if(argc == 0) - { - for(int i = 0; i < g_iNumEntities; i++) - { - char sClassname[64]; - GetEntityClassname(g_aEntityLagData[i].iEntity, sClassname, sizeof(sClassname)); - - char sTargetname[64]; - GetEntPropString(g_aEntityLagData[i].iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); - - int iHammerID = GetEntProp(g_aEntityLagData[i].iEntity, Prop_Data, "m_iHammerID"); - - PrintToConsole(client, "%2d. #%d %s \"%s\" (#%d)", i, g_aEntityLagData[i].iEntity, sClassname, sTargetname, iHammerID); - } - - PrintToConsole(client, "Active: %d / %d%s", g_iNumEntities, g_iMaxEntities, - g_bLagCompSuspended ? " | DISABLED until next round (over the limit)" : ""); - - return Plugin_Handled; - } - - for(int iEntity = 0; iEntity < MAX_EDICTS; iEntity++) - { - bool bDeleted = false; - for(int j = 1; j <= MaxClients; j++) - { - if(CheckBit(g_aaFilterClientSolidTouch, j * MAX_EDICTS + iEntity)) - { - bDeleted = true; - break; - } - } - - bool bBlockPhysics = CheckBit(g_aBlockTriggerTouchPlayers, iEntity); - bool bBlockTriggerMoved = CheckBit(g_aBlockTriggerMoved, iEntity); - bool bBlacklisted = CheckBit(g_aBlacklisted, iEntity); - - if(bDeleted || bBlockPhysics || bBlockTriggerMoved || bBlacklisted) - { - int index = -1; - for(int j = 0; j < g_iNumEntities; j++) - { - if(g_aEntityLagData[j].iEntity == iEntity) - { - index = j; - break; - } - } - - char sClassname[64] = "INVALID"; - char sTargetname[64] = "INVALID"; - int iHammerID = -1; - - if(IsValidEntity(iEntity)) - { - GetEntityClassname(iEntity, sClassname, sizeof(sClassname)); - GetEntPropString(iEntity, Prop_Data, "m_iName", sTargetname, sizeof(sTargetname)); - iHammerID = GetEntProp(iEntity, Prop_Data, "m_iHammerID"); - } - - PrintToConsole(client, "%2d. #%d %s \"%s\" (#%d) -> Phys: %d / TrigMov: %d / Deleted: %d / Black: %d", - index, iEntity, sClassname, sTargetname, iHammerID, bBlockPhysics, bBlockTriggerMoved, bDeleted, bBlacklisted); - } - } - - return Plugin_Handled; -} - - -stock void PrintToBoth(const char[] format, any ...) -{ - char buffer[254]; - VFormat(buffer, sizeof(buffer), format, 2); - LogMessage(buffer); - - for(int client = 1; client <= MaxClients; client++) - { - if (IsClientInGame(client) && g_bLagCompMessages[client] && CheckCommandAccess(client, "sm_lagged", ADMFLAG_ROOT)) - { - PrintToConsole(client, "%s", buffer); - } - } -} - -public Action DisableLagCompTimer(Handle timer) -{ - for(int client = 1; client <= MaxClients; client++) - { - if(!IsClientInGame(client) || !IsPlayerAlive(client) || IsFakeClient(client)) - continue; - - // https://github.com/ValveSoftware/source-sdk-2013/blob/master/sp/src/game/server/util.cpp#L747 - // Lag compensation only kicks in above the ping threshold, so ramp it off below it. - if (g_bCheckPing) - { - int iAvgPing = RoundFloat(GetClientAvgLatency(client, NetFlow_Outgoing) * 1000); - - if (iAvgPing <= g_iMinPing) - { - if(g_iDisableLagComp[client] < MAX_RECORDS) - g_iDisableLagComp[client]++; - - continue; - } - } - - if(g_bDisableLagComp[client] && g_iDisableLagComp[client] < MAX_RECORDS) - { - g_iDisableLagComp[client]++; - } - else if(!g_bDisableLagComp[client] && g_iDisableLagComp[client] > 0) - { - g_iDisableLagComp[client]--; - } - } - - return Plugin_Continue; -} - -public Action OnLagCompSettings(int client, int args) -{ - ShowSettingsMenu(client); - return Plugin_Handled; -} - -public Action OnToggleLagCompSettings(int client, int args) -{ - ToggleLagCompSettings(client); - return Plugin_Handled; -} - -public Action OnToggleLagCompLasersSettings(int client, int args) -{ - ToggleLagCompLasers(client); - return Plugin_Handled; -} - -public void ToggleLagCompSettings(int client) -{ - if(!client || !IsClientInGame(client) || IsFakeClient(client)) - return; - - g_bDisableLagComp[client] = !g_bDisableLagComp[client]; - SaveLagCompSettings(client); - - CPrintToChat(client, "%s LagCompensation has been %s.", PREFIX, g_bDisableLagComp[client] ? "disabled" : "enabled"); - - if(!g_bDisableLagComp[client] && g_bLagCompSuspended) - CPrintToChat(client, "%s It is currently {red}disabled{default} for everyone until the next round (too many entities).", PREFIX); -} - -public void ToggleLagCompLasers(int client) -{ - if(!client || !IsClientInGame(client) || IsFakeClient(client)) - return; - - g_bPlayerLaserCompensated[client] = !g_bPlayerLaserCompensated[client]; - SaveLagCompSettings(client); - - CPrintToChat(client, "%s LagCompensation for Lasers has been %s.", PREFIX, g_bPlayerLaserCompensated[client] ? "enabled" : "disabled"); - if (g_bCheckPing && g_bPlayerLaserCompensated[client]) - CPrintToChat(client, "%s It will take effect if your real ping is higher than %dms.", PREFIX, g_iMinPing); -} - -public void ToggleLagCompMessages(int client) -{ - if(!client || !IsClientInGame(client) || IsFakeClient(client)) - return; - - g_bLagCompMessages[client] = !g_bLagCompMessages[client]; - SaveLagCompSettings(client); - - CPrintToChat(client, "%s LagCompensation messages have been %s.", PREFIX, g_bLagCompMessages[client] ? "enabled" : "disabled"); -} - -public Action CheckLagComp(int client, int args) -{ - if (args > 1 || (args == 0 && !client)) - { - CReplyToCommand(client, "%s Usage: sm_checklag ", PREFIX); - return Plugin_Handled; - } - - int target = -1; - char sEnable[64]; - FormatEx(sEnable, sizeof(sEnable), "enabled (%s)", g_iCompenseEntityClass == 0 ? "Triggers and func_physbox" : "func_physbox only"); - - if (args == 0) - target = client; - else - { - char arg1[65]; - GetCmdArg(1, arg1, sizeof(arg1)); - target = FindTarget(client, arg1, true, false); - } - - if (target == -1) - { - CReplyToCommand(client, "%s Invalid target.", PREFIX); - return Plugin_Handled; - } - - CReplyToCommand(client, "%s LagCompensation is %s for {olive}%N", PREFIX, g_bDisableLagComp[target] ? "disabled" : sEnable, target); - CReplyToCommand(client, "%s Laser compensation: %s", PREFIX, g_bPlayerLaserCompensated[target] ? "enabled" : "disabled"); - - if(g_bLagCompSuspended) - CReplyToCommand(client, "%s Server status: {red}disabled{default} for everyone until the next round (more than %d entities needed to be compensated).", PREFIX, g_iMaxEntities); - else - CReplyToCommand(client, "%s Server status: {green}active{default}.", PREFIX); - - // g_iDisableLagComp also ramps from the ping threshold, so report it when they haven't opted out. - if(!g_bDisableLagComp[target] && g_iDisableLagComp[target] > 0) - CReplyToCommand(client, "%s Currently reduced: %d of %d ticks skipped%s.", PREFIX, - g_iDisableLagComp[target], MAX_RECORDS, - g_bCheckPing ? " (ping at or below the threshold ramps this up)" : ""); - - return Plugin_Handled; -} - -public void ShowSettingsMenu(int client) -{ - Menu menu = new Menu(MenuHandler_MainMenu); - if(g_bLagCompSuspended) - menu.SetTitle("LagCompensation Settings\nCurrently disabled until the next round (too many entities)"); - else - menu.SetTitle("LagCompensation Settings"); - menu.ExitBackButton = true; - - char buffer[128], buffer_lasers[128], msg_buffer[128]; - Format(buffer, sizeof(buffer), "LagCompensation: %s", g_bDisableLagComp[client] ? "Disabled" : "Enabled"); - Format(buffer_lasers, sizeof(buffer_lasers), "LagCompensation for Lasers: %s", g_bPlayerLaserCompensated[client] ? "Enabled" : "Disabled"); - Format(msg_buffer, sizeof(msg_buffer), "LagCompensation Messages: %s", g_bLagCompMessages[client] ? "Enabled" : "Disabled"); - - menu.AddItem("0", buffer); - menu.AddItem("1", buffer_lasers); - menu.AddItem("2", msg_buffer, CheckCommandAccess(client, "sm_lagged", ADMFLAG_ROOT) ? ITEMDRAW_DEFAULT : ITEMDRAW_DISABLED); - - menu.Display(client, MENU_TIME_FOREVER); -} - -public void MenuHandler_CookieMenu(int client, CookieMenuAction action, any info, char[] buffer, int maxlen) -{ - switch(action) - { - case(CookieMenuAction_DisplayOption): - { - strcopy(buffer, maxlen, "LagCompensation"); - } - case(CookieMenuAction_SelectOption): - { - ShowSettingsMenu(client); - } - } -} - -public int MenuHandler_MainMenu(Menu menu, MenuAction action, int client, int selection) -{ - switch(action) - { - case(MenuAction_Select): - { - switch(selection) - { - case(0): ToggleLagCompSettings(client); - case(1): ToggleLagCompLasers(client); - case(2): ToggleLagCompMessages(client); - } - - ShowSettingsMenu(client); - } - case(MenuAction_Cancel): - { - ShowCookieMenu(client); - } - case(MenuAction_End): - { - delete menu; - } - } - return 0; -}