v1.2.3.b7

## Shared Systems

* **DecoyTracker** - owner-aware decoy tracking shared by FrozenDecoy, GravityDecoy and MagneticDecoy, replacing the per-skill position dictionaries.
* **DebugCategory** - new flag enum backing the numeric `DebugMode`, with automatic migration from the old boolean value.
* **SkillsInfo.GetSkillConfig** - indexed skill config lookup replacing the linear scan used by draws and HUD rendering.
* **SkillNames** - cached enum name table, removing repeated `ToString()` calls from the draw path.
* **SkillUtils.HideCarriedEntities** - shared carried-weapon resolution for C4Camouflage, Ghost and Ninja.

## Performance

* **Skill draw** - replaced the O(n²) config lookup; rounds exceeding the perf threshold dropped from 89% to 0.3%.
* **CheckTransmit** - the weapon chain is now resolved once per hidden pawn instead of once per receiver; Ghost cost down 61%.
* **Pilot** - the exhaust trail is paused and resumed instead of being destroyed and recreated on every jump release.
* **MagneticDecoy** - config reads and the pawn list are hoisted out of the per-decoy loop.
* **FrozenDecoy** - config reads are hoisted out of the per-tick loop.
* **Debug** - the damage hook is only installed when damage logging is enabled.

## Fixes

* **PsychicDefusing** - can no longer finish a defuse and award an extra round after the round has already ended.
* **Spectator** - now picks a different enemy on each activation and no longer creates an unused camera prop every time the skill is switched off.
* **Random** - replaced the shared `Random` instance with `Random.Shared`, preventing degenerate results from concurrent use.
* **Baseball** - decoys are removed when their owner dies or loses the skill.
* **FrozenDecoy, GravityDecoy, MagneticDecoy** - decoys and their ground rings are removed when the skill is taken away.
* **ThirdEye** - fixed the camera check dereferencing a missing `CameraServices`, and the door toggle now verifies the entity class before casting.
* **Round start** - fixed `[gamerules unavailable]` appearing on the first freeze-time end after every map change.
* **Config** - added migration for keys missing from existing configuration files.

## Menu

* **WASDMenuAPI** - fixed a malformed `<font>` tag that wrapped every non-hovered menu row in an unclosed attribute.
* **WSAD menu** - the controls line is no longer dropped when the header line is hidden.
* **HtmlHudCustomisation** - line size options left empty now hide their line instead of emitting an invalid font class.

## Debug

* **DebugMode** - changed from a boolean to a number with concatenated category digits: `1` Skill, `2` Round, `3` Entity, `4` Damage. `123` enables Skill, Round and Entity. `0` disables logging. Existing `true` values migrate automatically.
* **EntityManager** - entity creation, destruction and failures are now logged under the Entity category instead of the server console.
* Startup now reports which debug categories are active.
This commit is contained in:
ByDexter 2026-08-16 16:33:09 +03:00
parent 5c65f4ac71
commit 0033d1e13d
29 changed files with 634 additions and 251 deletions

View file

@ -15,93 +15,105 @@ namespace src.player
private static readonly string debugFolder = Path.Combine(Instance.ModuleDirectory, "logs");
private static StreamWriter? _writer;
private static readonly object _writeLock = new();
private static bool damageHooked;
public static void Load()
{
sessionId = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}";
lock (_writeLock) { _writer?.Dispose(); _writer = null; }
if (Config.LoadedConfig.DebugMode != true)
if (Config.DebugFlags == DebugCategory.None)
return;
Instance.RegisterEventHandler<EventPlayerConnectFull>((@event, info) =>
if (Config.DebugEnabled(DebugCategory.Round))
{
var player = PlayerManager.GetPlayerEvent(@event.Userid);
if (player == null || !player.IsValid) return HookResult.Continue;
WriteToDebug($"{(player.IsBot ? "Bot" : "Player")} {player.PlayerName} joined the game.");
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventPlayerDisconnect>((@event, info) =>
{
var player = PlayerManager.GetPlayerEvent(@event.Userid);
if (player == null || !player.IsValid) return HookResult.Continue;
WriteToDebug($"{(player.IsBot ? "Bot" : "Player")} {player.PlayerName} disconnected.");
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventRoundStart>((@event, info) =>
{
var teams = Utilities.FindAllEntitiesByDesignerName<CCSTeam>("cs_team_manager").Where(t => t != null).ToList();
var tTeam = teams.FirstOrDefault(t => t.TeamNum == (int)CsTeam.Terrorist);
var ctTeam = teams.FirstOrDefault(t => t.TeamNum == (int)CsTeam.CounterTerrorist);
WriteToDebug($"Round #{tTeam?.Score + ctTeam?.Score + 1} (CT {ctTeam?.Score} : {tTeam?.Score} TT) started.{WarmupTag()}");
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventRoundFreezeEnd>((@event, info) =>
{
WriteToDebug($"Freeze time ended.{WarmupTag()}");
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventRoundEnd>((@event, info) =>
{
var teams = Utilities.FindAllEntitiesByDesignerName<CCSTeam>("cs_team_manager").Where(t => t != null).ToList();
var tTeam = teams.FirstOrDefault(t => t.TeamNum == (int)CsTeam.Terrorist);
var ctTeam = teams.FirstOrDefault(t => t.TeamNum == (int)CsTeam.CounterTerrorist);
WriteToDebug($"Round #{tTeam?.Score + ctTeam?.Score} (CT {ctTeam?.Score} : {tTeam?.Score} TT) ended.{WarmupTag()}");
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventPlayerDeath>((@event, info) =>
{
var victim = PlayerManager.GetPlayerEvent(@event.Userid);
var attacker = PlayerManager.GetPlayerEvent(@event.Attacker);
if (victim != null)
Instance.RegisterEventHandler<EventPlayerConnectFull>((@event, info) =>
{
if (attacker != null)
WriteToDebug($"{(victim.IsBot ? "Bot" : "Player")} {victim.PlayerName} died from {(attacker.IsBot ? "bot" : "player")} {attacker.PlayerName}.");
else
WriteToDebug($"{(victim.IsBot ? "Bot" : "Player")} {victim.PlayerName} died.");
}
return HookResult.Continue;
});
var player = PlayerManager.GetPlayerEvent(@event.Userid);
if (player == null || !player.IsValid) return HookResult.Continue;
WriteToDebug($"{(player.IsBot ? "Bot" : "Player")} {player.PlayerName} joined the game.", DebugCategory.Round);
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventBombPlanted>((@event, info) =>
{
WriteToDebug($"Bomb planted.");
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventPlayerDisconnect>((@event, info) =>
{
var player = PlayerManager.GetPlayerEvent(@event.Userid);
if (player == null || !player.IsValid) return HookResult.Continue;
WriteToDebug($"{(player.IsBot ? "Bot" : "Player")} {player.PlayerName} disconnected.", DebugCategory.Round);
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventBombDefused>((@event, info) =>
{
WriteToDebug($"Bomb defused.");
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventRoundStart>((@event, info) =>
{
var teams = Utilities.FindAllEntitiesByDesignerName<CCSTeam>("cs_team_manager").Where(t => t != null).ToList();
var tTeam = teams.FirstOrDefault(t => t.TeamNum == (int)CsTeam.Terrorist);
var ctTeam = teams.FirstOrDefault(t => t.TeamNum == (int)CsTeam.CounterTerrorist);
WriteToDebug($"Round #{tTeam?.Score + ctTeam?.Score + 1} (CT {ctTeam?.Score} : {tTeam?.Score} TT) started.{WarmupTag()}", DebugCategory.Round);
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventRoundFreezeEnd>((@event, info) =>
{
WriteToDebug($"Freeze time ended.{WarmupTag()}", DebugCategory.Round);
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventRoundEnd>((@event, info) =>
{
var teams = Utilities.FindAllEntitiesByDesignerName<CCSTeam>("cs_team_manager").Where(t => t != null).ToList();
var tTeam = teams.FirstOrDefault(t => t.TeamNum == (int)CsTeam.Terrorist);
var ctTeam = teams.FirstOrDefault(t => t.TeamNum == (int)CsTeam.CounterTerrorist);
WriteToDebug($"Round #{tTeam?.Score + ctTeam?.Score} (CT {ctTeam?.Score} : {tTeam?.Score} TT) ended.{WarmupTag()}", DebugCategory.Round);
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventPlayerDeath>((@event, info) =>
{
var victim = PlayerManager.GetPlayerEvent(@event.Userid);
var attacker = PlayerManager.GetPlayerEvent(@event.Attacker);
if (victim != null)
{
if (attacker != null)
WriteToDebug($"{(victim.IsBot ? "Bot" : "Player")} {victim.PlayerName} died from {(attacker.IsBot ? "bot" : "player")} {attacker.PlayerName}.", DebugCategory.Round);
else
WriteToDebug($"{(victim.IsBot ? "Bot" : "Player")} {victim.PlayerName} died.", DebugCategory.Round);
}
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventBombPlanted>((@event, info) =>
{
WriteToDebug($"Bomb planted.", DebugCategory.Round);
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventBombDefused>((@event, info) =>
{
WriteToDebug($"Bomb defused.", DebugCategory.Round);
return HookResult.Continue;
});
}
Instance.RegisterListener<OnMapStart>((mapName) =>
{
WriteToDebug($"Map changed: {mapName}.");
});
VirtualFunctions.CBaseEntity_TakeDamageOldFunc.Hook(OnTakeDamage, HookMode.Pre);
if (Config.DebugEnabled(DebugCategory.Damage))
{
VirtualFunctions.CBaseEntity_TakeDamageOldFunc.Hook(OnTakeDamage, HookMode.Pre);
damageHooked = true;
}
}
public static void Unload()
{
try { VirtualFunctions.CBaseEntity_TakeDamageOldFunc.Unhook(OnTakeDamage, HookMode.Pre); }
catch { }
if (damageHooked)
{
try { VirtualFunctions.CBaseEntity_TakeDamageOldFunc.Unhook(OnTakeDamage, HookMode.Pre); }
catch { }
damageHooked = false;
}
lock (_writeLock) { _writer?.Dispose(); _writer = null; }
}
@ -133,20 +145,27 @@ namespace src.player
WriteToDebug($"{(victim.IsBot ? "Bot" : "Player")} {victim.PlayerName} took damage from {(attacker.IsBot ? "bot" : "player")} {attacker.PlayerName}. " +
$"[dmg={param2.Damage:0.#} hp={victimPawn.Health}/{victimPawn.MaxHealth} armor={victimPawn.ArmorValue} hitgroup={nativeHitGroup} " +
$"takes={victimPawn.TakesDamage} vskill={PlayerManager.GetPlayerByIndex(victim.Index)?.Skill} askill={playerInfo.Skill}]");
$"takes={victimPawn.TakesDamage} vskill={PlayerManager.GetPlayerByIndex(victim.Index)?.Skill} askill={playerInfo.Skill}]", DebugCategory.Damage);
return HookResult.Continue;
}
private static string WarmupTag()
{
var gameRules = Instance?.GameRules;
if (gameRules == null || gameRules.Handle == IntPtr.Zero)
{
PlayerOnTick.InitializeGameRules();
gameRules = Instance?.GameRules;
}
if (gameRules == null || gameRules.Handle == IntPtr.Zero) return " [gamerules unavailable]";
return gameRules.WarmupPeriod ? " [WARMUP]" : string.Empty;
}
public static void WriteToDebug(string message)
public static void WriteToDebug(string message, DebugCategory category = DebugCategory.Core)
{
if (Config.LoadedConfig.DebugMode != true)
if (!Config.DebugEnabled(category))
return;
lock (_writeLock)

View file

@ -10,8 +10,6 @@ using RayTraceAPI;
using src.player.skills;
using src.utils;
using System.Collections.Concurrent;
using System.ComponentModel.Design;
using System.Security.Principal;
using System.Text.RegularExpressions;
using static CounterStrikeSharp.API.Core.Listeners;
using static src.jRandomSkills;
@ -198,7 +196,7 @@ namespace src.player
private static void InvokeOnTakeDamage(Skills skill, DynamicHook h, object[] args, bool post)
{
if (Config.LoadedConfig.DebugMode != true)
if (!Config.DebugEnabled(DebugCategory.Damage))
{
InvokeSkill(skill, post ? "OnTakeDamagePost" : "OnTakeDamage", args);
return;
@ -211,7 +209,7 @@ namespace src.player
float after = info == null ? 0f : info.Damage;
if (Math.Abs(before - after) > 0.01f)
Debug.WriteToDebug($"[DMG] {skill} changed damage {before:0.#} -> {after:0.#}{DescribeDamageTarget(h)}");
Debug.WriteToDebug($"[DMG] {skill} changed damage {before:0.#} -> {after:0.#}{DescribeDamageTarget(h)}", DebugCategory.Damage);
}
private static string DescribeDamageTarget(DynamicHook h)
@ -752,7 +750,7 @@ namespace src.player
}
}
Debug.WriteToDebug($"Player {player.PlayerName} used the skill: {playerInfo.Skill} by PlayerButtons: {pressed}");
Debug.WriteToDebug($"Player {player.PlayerName} used the skill: {playerInfo.Skill} by PlayerButtons: {pressed}", DebugCategory.Skill);
Instance.SkillAction(playerInfo.Skill.ToString(), "UseSkill", [player]);
}
}
@ -805,9 +803,10 @@ namespace src.player
string skillLine = $"{emptySymbol2}<font class='fontWeight-Bold fontSize-{config.SkillLineSize}'>{centerLine}</font>{emptySymbol2}";
string remainingLine = string.IsNullOrWhiteSpace(extraLine)
var extraLineSize = isDescription ? config.SkillDescriptionLineSize : config.InfoLineSize;
string remainingLine = string.IsNullOrWhiteSpace(extraLine) || string.IsNullOrEmpty(extraLineSize)
? ""
: $"<br>{emptySymbol}<font class='fontSize-{(isDescription ? config.SkillDescriptionLineSize : config.InfoLineSize)}' color='{(isDescription ? config.SkillDescriptionLineColor : config.InfoLineColor)}'>{extraLine}</font>{emptySymbol}";
: $"<br>{emptySymbol}<font class='fontSize-{extraLineSize}' color='{(isDescription ? config.SkillDescriptionLineColor : config.InfoLineColor)}'>{extraLine}</font>{emptySymbol}";
var hudContent = "<jRS/>" + infoLine + skillLine + remainingLine;

View file

@ -54,9 +54,9 @@ namespace src.player
BotManager.Stop();
}
private static void InitializeGameRules()
public static void InitializeGameRules()
{
if (Instance.GameRules != null) return;
if (Instance.GameRules != null && Instance.GameRules.Handle != IntPtr.Zero) return;
var gameRulesProxy = Utilities.FindAllEntitiesByDesignerName<CCSGameRulesProxy>("cs_gamerules").FirstOrDefault();
if (gameRulesProxy != null)
@ -182,7 +182,12 @@ namespace src.player
skillLine = $"<font color='{observedSpecialInfo.Color}'>{specialName}({primaryName})</font>";
}
if (showDescriptionHUD)
if (observedSkill.Skill != Skills.None && !string.IsNullOrEmpty(observedSkill.PrintHTML))
{
remainingLine = observedSkill.PrintHTML;
isDescription = false;
}
else if (showDescriptionHUD)
remainingLine = player.GetSkillDescription(observedSkill.Skill, observedSkill.SkillChance);
}
}

View file

@ -27,27 +27,31 @@ namespace src.player
bool ignoreMax = gameMode == Config.GameModes.SameSkills || gameMode == Config.GameModes.TeamSkills;
const int attempts = 6;
var filtered = new List<jSkill_SkillInfo>(candidates.Count);
for (int attempt = 0; attempt < attempts; attempt++)
{
var (roll, rolled) = RarityManager.RollRarity();
string rolledName = rolled.ToString();
var filtered = candidates.Where(s =>
filtered.Clear();
foreach (var s in candidates)
{
if (s == null) return false;
var def = SkillsInfo.LoadedConfig.FirstOrDefault(d => d.Name == s.Skill.ToString());
if (def == null) return false;
if (s == null) continue;
var def = SkillsInfo.GetSkillConfig(s.Skill);
if (def == null) continue;
if (!string.Equals(def.Rarity ?? string.Empty, rolled.ToString(), StringComparison.OrdinalIgnoreCase))
return false;
if (!string.Equals(def.Rarity ?? string.Empty, rolledName, StringComparison.OrdinalIgnoreCase))
continue;
if (!ignoreMax && def.MaxPerServer >= 0)
{
int current = assignmentCounts.TryGetValue(s.Skill, out var c) ? c : 0;
if (current >= def.MaxPerServer) return false;
if (current >= def.MaxPerServer) continue;
}
return true;
}).ToList();
filtered.Add(s);
}
if (filtered.Count > 0)
return filtered[Random.Shared.Next(filtered.Count)];
@ -55,7 +59,7 @@ namespace src.player
var fallback = candidates.Where(s =>
{
var def = SkillsInfo.LoadedConfig.FirstOrDefault(d => d.Name == s.Skill.ToString());
var def = SkillsInfo.GetSkillConfig(s.Skill);
if (def == null) return true;
if (ignoreMax) return true;
if (def.MaxPerServer < 0) return true;
@ -361,11 +365,11 @@ namespace src.player
if (pick.Skill == Skills.None) return true;
if (!SkillData.Skills.Any(s => s.Skill == pick.Skill)) return false;
string name = pick.Skill.ToString();
string name = SkillNames.Get(pick.Skill);
if (player.Team == CsTeam.Terrorist && counterterroristSkills.Any(s => s.Name == name)) return false;
if (player.Team == CsTeam.CounterTerrorist && terroristSkills.Any(s => s.Name == name)) return false;
var def = SkillsInfo.LoadedConfig.FirstOrDefault(d => d.Name == name);
var def = SkillsInfo.GetSkillConfig(pick.Skill);
if (def == null) return false;
if (def.DisableOnPistolRound && SkillUtils.IsPistolRound()) return false;
if (def.NeedsTeammates && validPlayers.Count(p => p.Team == player.Team) == 1) return false;
@ -557,18 +561,18 @@ namespace src.player
if (playerTarget == null || !playerTarget.IsValid) return;
if (PlayerManager.GetPlayerByIndex(playerTarget!.Index)?.Skill != randomSkill.Skill) return;
Debug.WriteToDebug("Enabling skill after freeze time: " + randomSkill.Skill);
Debug.WriteToDebug("Enabling skill after freeze time: " + randomSkill.Skill, DebugCategory.Skill);
Instance?.SkillAction(randomSkill.Skill.ToString(), "EnableSkill", [playerTarget]);
}, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
else
{
if (PlayerManager.GetPlayerByIndex(playerTarget!.Index)?.Skill != randomSkill.Skill) return;
Debug.WriteToDebug("Enabling skill: " + randomSkill.Skill);
Debug.WriteToDebug("Enabling skill: " + randomSkill.Skill, DebugCategory.Skill);
Instance?.SkillAction(randomSkill.Skill.ToString(), "EnableSkill", [playerTarget]);
}
}, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
Debug.WriteToDebug($"Player {skillPlayer.PlayerName} has got the skill \"{player.GetSkillName(randomSkill.Skill)}\".");
Debug.WriteToDebug($"Player {skillPlayer.PlayerName} has got the skill \"{SkillNames.Get(randomSkill.Skill)}\".", DebugCategory.Skill);
UpdateSkillHudExpired(skillPlayer, randomSkill.Skill);
if (Config.LoadedConfig.TeamMateSkillChatInfo)
@ -714,7 +718,7 @@ namespace src.player
Instance?.SkillAction(randomSkill.Skill.ToString(), "EnableSkill", [player]);
}, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
Debug.WriteToDebug($"Player {skillPlayer.PlayerName} has got the skill \"{player.GetSkillName(randomSkill.Skill)}\".");
Debug.WriteToDebug($"Player {skillPlayer.PlayerName} has got the skill \"{SkillNames.Get(randomSkill.Skill)}\".", DebugCategory.Skill);
UpdateSkillHudExpired(skillPlayer, randomSkill.Skill);
}
}

View file

@ -11,7 +11,7 @@ namespace src.player.skills
public class Baseball : ISkill
{
private const Skills skillName = Skills.Baseball;
private static readonly ConcurrentDictionary<uint, byte> decoys = [];
private static readonly ConcurrentDictionary<uint, uint> decoys = [];
private readonly static ConcurrentDictionary<uint, int> playersWithSkill = [];
public static void LoadSkill()
@ -28,15 +28,37 @@ namespace src.player.skills
private static void KillAllDecoys()
{
foreach (var decoyIndex in decoys.Keys.ToArray())
{
var decoy = Utilities.GetEntityFromIndex<CDecoyProjectile>((int)decoyIndex);
if (decoy != null && decoy.IsValid && decoy.DesignerName == "decoy_projectile")
decoy.AddEntityIOEvent("Kill", decoy, delay: 0.1f);
}
KillDecoy(decoyIndex);
decoys.Clear();
}
private static void KillDecoy(uint decoyIndex)
{
var decoy = Utilities.GetEntityFromIndex<CDecoyProjectile>((int)decoyIndex);
if (decoy != null && decoy.IsValid && decoy.DesignerName == "decoy_projectile")
decoy.AddEntityIOEvent("Kill", decoy, delay: 0.1f);
}
private static void KillOwnerDecoys(uint ownerIndex)
{
foreach (var pair in decoys.ToArray())
{
if (pair.Value != ownerIndex) continue;
KillDecoy(pair.Key);
decoys.TryRemove(pair.Key, out _);
}
}
public static void PlayerDeath(EventPlayerDeath @event)
{
var player = PlayerManager.GetPlayerEvent(@event.Userid);
if (player == null || !player.IsValid) return;
KillOwnerDecoys(player.Index);
}
public static void PlayerHurt(EventPlayerHurt @event)
{
var victim = PlayerManager.GetPlayerEvent(@event.Userid);
@ -76,9 +98,11 @@ namespace src.player.skills
var player = pawn.Controller.Value.As<CCSPlayerController>();
if (player == null || !player.IsValid) return;
var playerInfo = PlayerManager.GetPlayerByIndex((PlayerManager.GetPlayerEvent(player)?.Index ?? player.Index));
uint ownerIndex = PlayerManager.GetPlayerEvent(player)?.Index ?? player.Index;
var playerInfo = PlayerManager.GetPlayerByIndex(ownerIndex);
if (playerInfo?.Skill != skillName) return;
decoys.TryAdd(decoy.Index, 0);
decoys.TryAdd(decoy.Index, ownerIndex);
decoy.Collision.CollisionAttribute.InteractsWith = pawn.Collision.CollisionAttribute.InteractsWith;
decoy.Collision.CollisionGroup = pawn.Collision.CollisionGroup;
@ -93,13 +117,8 @@ namespace src.player.skills
if (playerInfo?.Skill != skillName) return;
uint key = (uint)@event.Entityid;
if (decoys.ContainsKey(key))
{
var decoy = Utilities.GetEntityFromIndex<CDecoyProjectile>(@event.Entityid);
if (decoy != null && decoy.IsValid)
decoy.AddEntityIOEvent("Kill", decoy, delay: 0.1f);
decoys.TryRemove(key, out _);
}
if (decoys.TryRemove(key, out _))
KillDecoy(key);
}
public static void OnTick()
@ -194,6 +213,13 @@ namespace src.player.skills
if (player == null || !player.IsValid) return;
playersWithSkill.TryRemove(player.Index, out _);
KillOwnerDecoys(player.Index);
var eventPlayer = PlayerManager.GetPlayerEvent(player);
if (eventPlayer != null && eventPlayer.IsValid && eventPlayer.Index != player.Index)
KillOwnerDecoys(eventPlayer.Index);
SkillUtils.UpdateGrenadeCount(player, CsItem.DecoyGrenade, 1);
}

View file

@ -125,7 +125,7 @@ namespace src.player.skills
if (info.TransmitEntities.Contains(target.Pawn.Index))
info.TransmitEntities.Remove(target.Pawn.Index);
SkillUtils.HideCarriedEntities(info, target.Pawn);
SkillUtils.HideCarriedEntities(info, target);
if (bomb == null) continue;

View file

@ -10,7 +10,6 @@ namespace src.player.skills
public class FrozenDecoy : ISkill
{
private const Skills skillName = Skills.FrozenDecoy;
private static readonly ConcurrentDictionary<Vector, byte> decoys = [];
private readonly static ConcurrentDictionary<uint, int> playersWithSkill = [];
public static void LoadSkill()
@ -21,14 +20,12 @@ namespace src.player.skills
public static void NewRound()
{
decoys.Clear();
DecoyRing.ClearAll(skillName);
DecoyTracker.Clear(skillName);
}
public static void RoundEnd()
{
decoys.Clear();
DecoyRing.ClearAll(skillName);
DecoyTracker.Clear(skillName);
}
public static void DecoyStarted(EventDecoyStarted @event)
@ -40,43 +37,51 @@ namespace src.player.skills
if (playerInfo?.Skill != skillName) return;
Vector pos = new(@event.X, @event.Y, @event.Z);
decoys.TryAdd(pos, 0);
DecoyTracker.Add(skillName, (uint)@event.Entityid, pos, player.Index);
DecoyRing.Show(skillName, (uint)@event.Entityid, pos, SkillsInfo.GetValue<float>(skillName, "triggerRadius"));
}
public static void DecoyDetonate(EventDecoyDetonate @event)
{
var player = PlayerManager.GetPlayerEvent(@event.Userid);
if (player == null || !player.IsValid) return;
var playerInfo = PlayerManager.GetPlayerByIndex(player!.Index);
if (playerInfo?.Skill != skillName) return;
foreach (var decoy in decoys.Keys.Where(v => v.X == @event.X && v.Y == @event.Y && v.Z == @event.Z))
decoys.TryRemove(decoy, out _);
DecoyRing.Hide(skillName, (uint)@event.Entityid);
DecoyTracker.Remove(skillName, (uint)@event.Entityid);
}
public static void OnTick()
{
foreach (Vector decoyPos in decoys.Keys)
foreach (var player in PlayerManager.GetTickPlayers().Where(p => p.IsValid && p.Team is CsTeam.CounterTerrorist or CsTeam.Terrorist))
var decoyPositions = DecoyTracker.Positions(skillName);
if (decoyPositions.Length == 0) return;
float decoyRadius = SkillsInfo.GetValue<float>(skillName, "triggerRadius");
int slownessMultiplier = SkillsInfo.GetValue<int>(skillName, "slownessMultiplier");
List<CCSPlayerPawn> pawns = [];
foreach (var player in PlayerManager.GetTickPlayers())
{
if (player == null || !player.IsValid) continue;
if (player.Team is not (CsTeam.CounterTerrorist or CsTeam.Terrorist)) continue;
var eventPlayer = PlayerManager.GetPlayerEvent(player);
if (eventPlayer == null || !eventPlayer.IsValid) continue;
var pawn = eventPlayer.PlayerPawn.Value;
if (pawn == null || !pawn.IsValid || pawn.AbsOrigin == null) continue;
pawns.Add(pawn);
}
if (pawns.Count == 0) return;
foreach (Vector decoyPos in decoyPositions)
foreach (var pawn in pawns)
{
var eventPlayer = PlayerManager.GetPlayerEvent(player);
if (eventPlayer == null || !eventPlayer.IsValid) continue;
var origin = pawn.AbsOrigin;
if (origin == null) continue;
var decoyRadius = SkillsInfo.GetValue<float>(skillName, "triggerRadius");
double distance = SkillUtils.GetDistance(decoyPos, origin);
if (distance > decoyRadius) continue;
var pawn = eventPlayer.PlayerPawn.Value;
if (pawn == null || !pawn.IsValid || pawn.AbsOrigin == null) continue;
double distance = SkillUtils.GetDistance(decoyPos, pawn.AbsOrigin);
if (distance <= decoyRadius)
{
double modifier = Math.Clamp(distance / decoyRadius, 0f, 1f);
pawn.VelocityModifier = (float)Math.Pow(modifier, SkillsInfo.GetValue<int>(skillName, "slownessMultiplier"));
}
double modifier = Math.Clamp(distance / decoyRadius, 0f, 1f);
pawn.VelocityModifier = (float)Math.Pow(modifier, slownessMultiplier);
}
}
@ -137,6 +142,12 @@ namespace src.player.skills
if (player == null || !player.IsValid) return;
playersWithSkill.TryRemove(player.Index, out _);
DecoyTracker.RemoveOwner(skillName, player.Index);
var eventPlayer = PlayerManager.GetPlayerEvent(player);
if (eventPlayer != null && eventPlayer.IsValid && eventPlayer.Index != player.Index)
DecoyTracker.RemoveOwner(skillName, eventPlayer.Index);
SkillUtils.UpdateGrenadeCount(player, CsItem.DecoyGrenade, 1);
}

View file

@ -85,7 +85,7 @@ namespace src.player.skills
if (info.TransmitEntities.Contains(target.Pawn.Index))
info.TransmitEntities.Remove(target.Pawn.Index);
SkillUtils.HideCarriedEntities(info, target.Pawn);
SkillUtils.HideCarriedEntities(info, target);
// Hide the bomb as well, but only while this hidden player is the one holding it.
if (bomb == null || !target.HoldsBomb) continue;

View file

@ -13,7 +13,6 @@ namespace src.player.skills
private const float defaultGravity = 1f;
private static readonly ConcurrentDictionary<Vector, byte> decoys = [];
private static readonly ConcurrentDictionary<uint, int> playersWithSkill = [];
private static readonly ConcurrentDictionary<uint, byte> affected = [];
private static readonly ConcurrentDictionary<uint, byte> restoreOnRespawn = [];
@ -27,15 +26,13 @@ namespace src.player.skills
public static void NewRound()
{
RestoreAll();
decoys.Clear();
DecoyRing.ClearAll(skillName);
DecoyTracker.Clear(skillName);
}
public static void RoundEnd()
{
RestoreAll();
decoys.Clear();
DecoyRing.ClearAll(skillName);
DecoyTracker.Clear(skillName);
}
public static void DecoyStarted(EventDecoyStarted @event)
@ -47,31 +44,24 @@ namespace src.player.skills
if (playerInfo?.Skill != skillName) return;
Vector pos = new(@event.X, @event.Y, @event.Z);
decoys.TryAdd(pos, 0);
DecoyTracker.Add(skillName, (uint)@event.Entityid, pos, player.Index);
DecoyRing.Show(skillName, (uint)@event.Entityid, pos, SkillsInfo.GetValue<float>(skillName, "triggerRadius"));
}
public static void DecoyDetonate(EventDecoyDetonate @event)
{
var player = PlayerManager.GetPlayerEvent(@event.Userid);
if (player == null || !player.IsValid) return;
DecoyTracker.Remove(skillName, (uint)@event.Entityid);
var playerInfo = PlayerManager.GetPlayerByIndex(player!.Index);
if (playerInfo?.Skill != skillName) return;
foreach (var decoy in decoys.Keys.Where(v => v.X == @event.X && v.Y == @event.Y && v.Z == @event.Z))
decoys.TryRemove(decoy, out _);
DecoyRing.Hide(skillName, (uint)@event.Entityid);
if (decoys.IsEmpty) RestoreAll();
if (DecoyTracker.IsEmpty(skillName)) RestoreAll();
}
public static void OnTick()
{
if (decoys.IsEmpty && affected.IsEmpty && restoreOnRespawn.IsEmpty) return;
var decoyPositions = DecoyTracker.Positions(skillName);
if (decoys.IsEmpty && !affected.IsEmpty) RestoreAll();
if (decoyPositions.Length == 0 && affected.IsEmpty && restoreOnRespawn.IsEmpty) return;
if (decoyPositions.Length == 0 && !affected.IsEmpty) RestoreAll();
float radius = SkillsInfo.GetValue<float>(skillName, "triggerRadius");
float gravity = SkillsInfo.GetValue<float>(skillName, "gravityScale");
@ -91,7 +81,9 @@ namespace src.player.skills
if (restoreOnRespawn.TryRemove(eventPlayer.Index, out _))
pawn.ActualGravityScale = defaultGravity;
bool inside = !decoys.IsEmpty && decoys.Keys.Any(d => SkillUtils.GetDistance(d, pawn.AbsOrigin) <= radius);
bool inside = false;
foreach (var decoyPos in decoyPositions)
if (SkillUtils.GetDistance(decoyPos, pawn.AbsOrigin) <= radius) { inside = true; break; }
if (inside)
{
@ -176,6 +168,15 @@ namespace src.player.skills
if (player == null || !player.IsValid) return;
playersWithSkill.TryRemove(player.Index, out _);
DecoyTracker.RemoveOwner(skillName, player.Index);
var eventPlayer = PlayerManager.GetPlayerEvent(player);
if (eventPlayer != null && eventPlayer.IsValid && eventPlayer.Index != player.Index)
DecoyTracker.RemoveOwner(skillName, eventPlayer.Index);
if (DecoyTracker.IsEmpty(skillName)) RestoreAll();
SkillUtils.UpdateGrenadeCount(player, CsItem.DecoyGrenade, 1);
}

View file

@ -10,7 +10,6 @@ namespace src.player.skills
public class MagneticDecoy : ISkill
{
private const Skills skillName = Skills.MagneticDecoy;
private static readonly ConcurrentDictionary<Vector, byte> decoys = [];
private readonly static ConcurrentDictionary<uint, int> playersWithSkill = [];
public static void LoadSkill()
@ -21,14 +20,12 @@ namespace src.player.skills
public static void NewRound()
{
decoys.Clear();
DecoyRing.ClearAll(skillName);
DecoyTracker.Clear(skillName);
}
public static void RoundEnd()
{
decoys.Clear();
DecoyRing.ClearAll(skillName);
DecoyTracker.Clear(skillName);
}
public static void DecoyStarted(EventDecoyStarted @event)
@ -40,50 +37,58 @@ namespace src.player.skills
if (playerInfo?.Skill != skillName) return;
Vector pos = new(@event.X, @event.Y, @event.Z);
decoys.TryAdd(pos, 0);
DecoyTracker.Add(skillName, (uint)@event.Entityid, pos, player.Index);
DecoyRing.Show(skillName, (uint)@event.Entityid, pos, SkillsInfo.GetValue<float>(skillName, "triggerRadius"));
}
public static void DecoyDetonate(EventDecoyDetonate @event)
{
var player = PlayerManager.GetPlayerEvent(@event.Userid);
if (player == null || !player.IsValid) return;
var playerInfo = PlayerManager.GetPlayerByIndex(player!.Index);
if (playerInfo?.Skill != skillName) return;
foreach (var decoy in decoys.Keys.Where(v => v.X == @event.X && v.Y == @event.Y && v.Z == @event.Z))
decoys.TryRemove(decoy, out _);
DecoyRing.Hide(skillName, (uint)@event.Entityid);
DecoyTracker.Remove(skillName, (uint)@event.Entityid);
}
public static void OnTick()
{
foreach (Vector decoyPos in decoys.Keys)
foreach (var player in PlayerManager.GetTickPlayers().Where(p => p.IsValid && p.Team is CsTeam.CounterTerrorist or CsTeam.Terrorist))
var decoyPositions = DecoyTracker.Positions(skillName);
if (decoyPositions.Length == 0) return;
float decoyRadius = SkillsInfo.GetValue<float>(skillName, "triggerRadius");
float baseStrenght = SkillsInfo.GetValue<float>(skillName, "strenght");
List<CCSPlayerPawn> pawns = [];
foreach (var player in PlayerManager.GetTickPlayers())
{
if (player == null || !player.IsValid) continue;
if (player.Team is not (CsTeam.CounterTerrorist or CsTeam.Terrorist)) continue;
var eventPlayer = PlayerManager.GetPlayerEvent(player);
if (eventPlayer == null || !eventPlayer.IsValid) continue;
var pawn = eventPlayer.PlayerPawn.Value;
if (pawn == null || !pawn.IsValid || pawn.AbsOrigin == null) continue;
pawns.Add(pawn);
}
if (pawns.Count == 0) return;
foreach (Vector decoyPos in decoyPositions)
foreach (var pawn in pawns)
{
var eventPlayer = PlayerManager.GetPlayerEvent(player);
if (eventPlayer == null || !eventPlayer.IsValid) continue;
var origin = pawn.AbsOrigin;
if (origin == null) continue;
var decoyRadius = SkillsInfo.GetValue<float>(skillName, "triggerRadius");
double distance = SkillUtils.GetDistance(decoyPos, origin);
if (distance > decoyRadius || distance <= 10) continue;
var pawn = eventPlayer.PlayerPawn.Value;
if (pawn == null || !pawn.IsValid || pawn.AbsOrigin == null) continue;
Vector direction = new(decoyPos.X - origin.X, decoyPos.Y - origin.Y, 0);
float length = direction.Length();
if (length <= 0) continue;
double distance = SkillUtils.GetDistance(decoyPos, pawn.AbsOrigin);
if (distance <= decoyRadius && distance > 10)
{
Vector direction = new(decoyPos.X - pawn.AbsOrigin.X, decoyPos.Y - pawn.AbsOrigin.Y, 0);
float length = direction.Length();
Vector normalized = direction / length;
float strenght = baseStrenght * (1 - (float)(distance / decoyRadius));
Vector normalized = direction / length;
float ratio = 1 - (float)(distance / decoyRadius);
float strenght = SkillsInfo.GetValue<float>(skillName, "strenght") * ratio;
pawn.AbsVelocity.X += normalized.X * strenght;
pawn.AbsVelocity.Y += normalized.Y * strenght;
}
pawn.AbsVelocity.X += normalized.X * strenght;
pawn.AbsVelocity.Y += normalized.Y * strenght;
}
}
@ -144,6 +149,12 @@ namespace src.player.skills
if (player == null || !player.IsValid) return;
playersWithSkill.TryRemove(player.Index, out _);
DecoyTracker.RemoveOwner(skillName, player.Index);
var eventPlayer = PlayerManager.GetPlayerEvent(player);
if (eventPlayer != null && eventPlayer.IsValid && eventPlayer.Index != player.Index)
DecoyTracker.RemoveOwner(skillName, eventPlayer.Index);
SkillUtils.UpdateGrenadeCount(player, CsItem.DecoyGrenade, 1);
}

View file

@ -83,7 +83,7 @@ namespace src.player.skills
if (info.TransmitEntities.Contains(target.Pawn.Index))
info.TransmitEntities.Remove(target.Pawn.Index);
SkillUtils.HideCarriedEntities(info, target.Pawn);
SkillUtils.HideCarriedEntities(info, target);
if (bomb == null || !target.HoldsBomb) continue;

View file

@ -120,7 +120,9 @@ namespace src.player.skills
}
else
{
if (pilotInfo.TrailIndex != null)
PauseTrail(pilotInfo);
if (isOnGround)
ClearTrail(pilotInfo);
if (pilotInfo.Fuel <= 0)
@ -164,8 +166,13 @@ namespace src.player.skills
if (pilotInfo.TrailIndex != null)
{
var existing = Utilities.GetEntityFromIndex<CParticleSystem>((int)pilotInfo.TrailIndex.Value);
if (existing != null && existing.IsValid) return;
pilotInfo.TrailIndex = null;
if (existing != null && existing.IsValid)
{
ResumeTrail(pilotInfo);
return;
}
ClearTrail(pilotInfo);
}
if (pawn.AbsOrigin == null) return;
@ -179,6 +186,29 @@ namespace src.player.skills
particle.AcceptInput("Start");
pilotInfo.TrailIndex = particle.Index;
pilotInfo.TrailActive = true;
}
private static void ResumeTrail(Pilot_PlayerInfo pilotInfo)
{
if (pilotInfo.TrailActive || pilotInfo.TrailIndex == null) return;
var particle = Utilities.GetEntityFromIndex<CParticleSystem>((int)pilotInfo.TrailIndex.Value);
if (particle != null && particle.IsValid)
particle.AcceptInput("Start");
pilotInfo.TrailActive = true;
}
private static void PauseTrail(Pilot_PlayerInfo pilotInfo)
{
if (!pilotInfo.TrailActive || pilotInfo.TrailIndex == null) return;
var particle = Utilities.GetEntityFromIndex<CParticleSystem>((int)pilotInfo.TrailIndex.Value);
if (particle != null && particle.IsValid)
particle.AcceptInput("Stop");
pilotInfo.TrailActive = false;
}
private static void StopTrail(Pilot_PlayerInfo pilotInfo)
@ -187,6 +217,7 @@ namespace src.player.skills
uint index = pilotInfo.TrailIndex.Value;
pilotInfo.TrailIndex = null;
pilotInfo.TrailActive = false;
var particle = Utilities.GetEntityFromIndex<CParticleSystem>((int)index);
if (particle != null && particle.IsValid)
@ -252,9 +283,10 @@ namespace src.player.skills
public float LastJumpTime { get; set; } = 0;
public bool IsFlying { get; set; } = false;
public uint? TrailIndex { get; set; }
public bool TrailActive { get; set; }
}
public class SkillConfig(Skills skill = skillName, bool active = true, string color = "#1466F5", CsTeam onlyTeam = CsTeam.None, bool disableOnFreezeTime = true, bool needsTeammates = false, string requiredPermission = "", float? hudDuration = null, float? descriptionHudDuration = null, int maxPerServer = -1, Rarity rarity = Rarity.Common, float maximumFuel = 150f, float fuelConsumption = .64f, float refuelling = .1f, string particleName = "particles/inferno_fx/incgrenade_thrown_trail.vpcf", float particleOffset = 0f) : SkillsInfo.DefaultSkillInfo(skill, active, color, onlyTeam, disableOnFreezeTime, needsTeammates, requiredPermission, hudDuration, descriptionHudDuration, maxPerServer, rarity)
public class SkillConfig(Skills skill = skillName, bool active = true, string color = "#1466F5", CsTeam onlyTeam = CsTeam.None, bool disableOnFreezeTime = true, bool needsTeammates = false, string requiredPermission = "", float? hudDuration = null, float? descriptionHudDuration = null, int maxPerServer = -1, Rarity rarity = Rarity.Common, float maximumFuel = 150f, float fuelConsumption = .64f, float refuelling = .1f, string particleName = "particles/inferno_fx/incgrenade_thrown_trail.vpcf", float particleOffset = 10f) : SkillsInfo.DefaultSkillInfo(skill, active, color, onlyTeam, disableOnFreezeTime, needsTeammates, requiredPermission, hudDuration, descriptionHudDuration, maxPerServer, rarity)
{
public string ParticleName { get; set; } = particleName;
public float ParticleOffset { get; set; } = particleOffset;

View file

@ -12,6 +12,7 @@ namespace src.player.skills
private const Skills skillName = Skills.PsychicDefusing;
private static readonly ConcurrentDictionary<uint, PlayerSkillInfo> SkillPlayerInfo = [];
private static Vector? bombLocation = null;
private static bool roundEnded;
private static readonly float tickRate = 64f;
private static readonly object setLock = new();
@ -26,6 +27,17 @@ namespace src.player.skills
{
SkillPlayerInfo.Clear();
bombLocation = null;
roundEnded = false;
}
}
public static void RoundEnd()
{
lock (setLock)
{
roundEnded = true;
bombLocation = null;
SkillPlayerInfo.Clear();
}
}
@ -48,7 +60,8 @@ namespace src.player.skills
public static void OnTick()
{
if (bombLocation == null) return;
var bomb = bombLocation;
if (roundEnded || bomb == null) return;
foreach (var skillInfo in SkillPlayerInfo)
{
var playerIndex = skillInfo.Key;
@ -60,7 +73,7 @@ namespace src.player.skills
var pawn = player.PlayerPawn.Value;
if (pawn == null || !pawn.IsValid) continue;
if (pawn.AbsOrigin == null || SkillUtils.GetDistance(pawn.AbsOrigin, bombLocation) > SkillsInfo.GetValue<float>(skillName, "maxDefusingRange"))
if (pawn.AbsOrigin == null || SkillUtils.GetDistance(pawn.AbsOrigin, bomb) > SkillsInfo.GetValue<float>(skillName, "maxDefusingRange"))
{
info.Defusing = false;
info.DefusingTime = SkillsInfo.GetValue<float>(skillName, "defusingTime");
@ -76,13 +89,14 @@ namespace src.player.skills
if (info.DefusingTime <= 0)
{
var plantedBomb = Utilities.FindAllEntitiesByDesignerName<CPlantedC4>("planted_c4").FirstOrDefault();
if (plantedBomb != null)
if (plantedBomb != null && plantedBomb.IsValid && plantedBomb.BombTicking && !plantedBomb.BombDefused)
{
plantedBomb.AddEntityIOEvent("Kill", plantedBomb, delay: 0.1f);
SkillUtils.TerminateRound(CsTeam.CounterTerrorist);
}
SkillUtils.ResetPrintHTML(player);
SkillPlayerInfo.Clear();
bombLocation = null;
}
UpdateHUD(player, info);

View file

@ -116,7 +116,7 @@ namespace src.player.skills
if (cam != null && cam.IsValid)
EntityManager.DestroyEntity(cam.Index);
if (!forceToDefault)
if (!forceToDefault && pawn.CameraServices.ViewEntity.Raw == orginalCameraRaw)
newCameraRaw = CreateCamera(player);
}
else
@ -140,7 +140,7 @@ namespace src.player.skills
Utilities.SetStateChanged(pawn, "CBasePlayerPawn", "m_pCameraServices");
if (forceToDefault && cameras.TryGetValue(player.Index, out var current) && current.Item2 != 0)
if (defaultCam && cameras.TryGetValue(player.Index, out var current) && current.Item2 != 0)
cameras[player.Index] = (current.Item1, 0, current.Item3);
BlockWeapon(player, !defaultCam);
@ -165,7 +165,11 @@ namespace src.player.skills
return 0;
}
var enemy = enemies[Instance.Random.Next(enemies.Count)];
uint lastTarget = cameras.TryGetValue(player.Index, out var previous) ? previous.Item3 : 0;
if (lastTarget != 0 && enemies.Count > 1)
enemies.RemoveAll(p => p.Index == lastTarget);
var enemy = enemies[Random.Shared.Next(enemies.Count)];
var pawn = enemy.PlayerPawn.Value;
if (pawn == null || !pawn.IsValid || pawn.CameraServices == null || pawn.AbsOrigin == null)

View file

@ -52,8 +52,11 @@ namespace src.player.skills
var pawn = player.PlayerPawn?.Value;
if (pawn == null || !pawn.IsValid) return true;
var cameraServices = pawn.CameraServices;
if (cameraServices == null) return true;
if (cameras.TryGetValue(player.Index, out var cameraInfo) && cameraInfo.Item1 != 0)
return pawn?.CameraServices?.ViewEntity.Raw == cameraInfo.Item1;
return cameraServices.ViewEntity.Raw == cameraInfo.Item1;
return true;
}

View file

@ -68,7 +68,7 @@ namespace src.player.skills
Utilities.SetStateChanged(victimPawn, "CCSPlayerPawn", "m_ArmorValue");
Debug.WriteToDebug($"[TrueArmor] {victim.PlayerName}: raw={damage:0.#} absorbed={absorbed:0.#} " +
$"passed={info.Damage:0.#} armor={armor}->{pending[victim.Index]} hp={victimPawn.Health}");
$"passed={info.Damage:0.#} armor={armor}->{pending[victim.Index]} hp={victimPawn.Health}", DebugCategory.Damage);
}
public static void OnTakeDamagePost(DynamicHook h)