Merge pull request #52 from ByDexterTR/main

v1.2.3.b7
This commit is contained in:
Juzlus 2026-08-17 19:08:12 +02:00 • committed by GitHub
commit c8a8757d58
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
29 changed files with 634 additions and 251 deletions

View file

@ -225,7 +225,7 @@ public class WasdMenuPlayer
if (option == CurrentChoice)
builder.AppendLine(string.Format(itemHoverText, finalOptionText));
else
builder.AppendLine(string.Format(itemText, $"<font {(string.IsNullOrEmpty(color) ? "" : $"color='{color}'")}'>{finalOptionText}</font>"));
builder.AppendLine(string.Format(itemText, string.IsNullOrEmpty(color) ? finalOptionText : $"<font color='{color}'>{finalOptionText}</font>"));
option = option.Next;
shown++;

View file

@ -91,7 +91,7 @@ namespace src.command
return;
string[] commands = _.ArgString.Trim().Split(" ", StringSplitOptions.RemoveEmptyEntries);
Debug.WriteToDebug($"Player {player.PlayerName} used the skill: {playerInfo.Skill}");
Debug.WriteToDebug($"Player {player.PlayerName} used the skill: {playerInfo.Skill}", DebugCategory.Skill);
if (commands == null || commands.Length == 0)
Instance.SkillAction(playerInfo.Skill.ToString(), "UseSkill", [player]);

View file

@ -20,7 +20,7 @@ namespace src
public static jRandomSkills Instance { get; private set; }
#pragma warning restore CS8618
public IEnumerable<jSkill_PlayerInfo> SkillPlayer => PlayerManager.GetAllPlayers();
public Random Random { get; } = new Random();
public Random Random => Random.Shared;
public CCSGameRules? GameRules { get; set; }
private ConcurrentBag<string> ManifestResources { get; set; } = ["models/sprays/spray_plane.vmdl"];
public IWasdMenuManager? MenuManager;
@ -31,7 +31,7 @@ namespace src
public override string ModuleName => "[CS2] [ jRandomSkills ]";
public override string ModuleAuthor => "D3X (Original), Juzlus (Modifier), ByDexterTR (Contributor)";
public override string ModuleDescription => "Plugin adds random skills every round for CS2 by D3X. Modified by Juzlus.";
public override string ModuleVersion => "1.2.3.b6";
public override string ModuleVersion => "1.2.3.b7";
public override void Load(bool hotReload)
{
@ -87,9 +87,9 @@ namespace src
SkillAction(skill.ToString()!, "LoadSkill");
Debug.WriteToDebug($"jRandomSkills v{Instance.ModuleVersion} ({SkillData.Skills.Count - 1}/{SkillsInfo.LoadedConfig.Count - 1} Skills) loaded!");
Debug.WriteToDebug($"GameModes: {(Config.GameModes)Config.LoadedConfig.GameMode}, Lang: {Config.LoadedConfig.LanguageSystem.DefaultLangCode}");
Debug.WriteToDebug($"GameModes: {(Config.GameModes)Config.LoadedConfig.GameMode}, Lang: {Config.LoadedConfig.LanguageSystem.DefaultLangCode}, Debug: {DebugCategories.Describe(Config.DebugFlags)}");
foreach (var skill in SkillData.Skills)
Debug.WriteToDebug($"Loaded: {skill.Skill}");
Debug.WriteToDebug($"Loaded: {skill.Skill}", DebugCategory.Skill);
}
private static bool TryClaimCurseTarget(object[]? param)

View file

@ -15,20 +15,23 @@ 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;
if (Config.DebugEnabled(DebugCategory.Round))
{
Instance.RegisterEventHandler<EventPlayerConnectFull>((@event, info) =>
{
var player = PlayerManager.GetPlayerEvent(@event.Userid);
if (player == null || !player.IsValid) return HookResult.Continue;
WriteToDebug($"{(player.IsBot ? "Bot" : "Player")} {player.PlayerName} joined the game.");
WriteToDebug($"{(player.IsBot ? "Bot" : "Player")} {player.PlayerName} joined the game.", DebugCategory.Round);
return HookResult.Continue;
});
@ -36,7 +39,7 @@ namespace src.player
{
var player = PlayerManager.GetPlayerEvent(@event.Userid);
if (player == null || !player.IsValid) return HookResult.Continue;
WriteToDebug($"{(player.IsBot ? "Bot" : "Player")} {player.PlayerName} disconnected.");
WriteToDebug($"{(player.IsBot ? "Bot" : "Player")} {player.PlayerName} disconnected.", DebugCategory.Round);
return HookResult.Continue;
});
@ -45,13 +48,13 @@ namespace src.player
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()}");
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()}");
WriteToDebug($"Freeze time ended.{WarmupTag()}", DebugCategory.Round);
return HookResult.Continue;
});
@ -60,7 +63,7 @@ namespace src.player
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()}");
WriteToDebug($"Round #{tTeam?.Score + ctTeam?.Score} (CT {ctTeam?.Score} : {tTeam?.Score} TT) ended.{WarmupTag()}", DebugCategory.Round);
return HookResult.Continue;
});
@ -71,37 +74,46 @@ namespace src.player
if (victim != null)
{
if (attacker != null)
WriteToDebug($"{(victim.IsBot ? "Bot" : "Player")} {victim.PlayerName} died from {(attacker.IsBot ? "bot" : "player")} {attacker.PlayerName}.");
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.");
WriteToDebug($"{(victim.IsBot ? "Bot" : "Player")} {victim.PlayerName} died.", DebugCategory.Round);
}
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventBombPlanted>((@event, info) =>
{
WriteToDebug($"Bomb planted.");
WriteToDebug($"Bomb planted.", DebugCategory.Round);
return HookResult.Continue;
});
Instance.RegisterEventHandler<EventBombDefused>((@event, info) =>
{
WriteToDebug($"Bomb defused.");
WriteToDebug($"Bomb defused.", DebugCategory.Round);
return HookResult.Continue;
});
}
Instance.RegisterListener<OnMapStart>((mapName) =>
{
WriteToDebug($"Map changed: {mapName}.");
});
if (Config.DebugEnabled(DebugCategory.Damage))
{
VirtualFunctions.CBaseEntity_TakeDamageOldFunc.Hook(OnTakeDamage, HookMode.Pre);
damageHooked = true;
}
}
public static void Unload()
{
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,13 +28,35 @@ namespace src.player.skills
private static void KillAllDecoys()
{
foreach (var decoyIndex in decoys.Keys.ToArray())
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);
}
decoys.Clear();
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)
@ -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 decoyRadius = SkillsInfo.GetValue<float>(skillName, "triggerRadius");
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"));
pawns.Add(pawn);
}
if (pawns.Count == 0) return;
foreach (Vector decoyPos in decoyPositions)
foreach (var pawn in pawns)
{
var origin = pawn.AbsOrigin;
if (origin == null) continue;
double distance = SkillUtils.GetDistance(decoyPos, origin);
if (distance > decoyRadius) continue;
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,52 +37,60 @@ 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 decoyRadius = SkillsInfo.GetValue<float>(skillName, "triggerRadius");
var pawn = eventPlayer.PlayerPawn.Value;
if (pawn == null || !pawn.IsValid || pawn.AbsOrigin == null) continue;
double distance = SkillUtils.GetDistance(decoyPos, pawn.AbsOrigin);
if (distance <= decoyRadius && distance > 10)
pawns.Add(pawn);
}
if (pawns.Count == 0) return;
foreach (Vector decoyPos in decoyPositions)
foreach (var pawn in pawns)
{
Vector direction = new(decoyPos.X - pawn.AbsOrigin.X, decoyPos.Y - pawn.AbsOrigin.Y, 0);
var origin = pawn.AbsOrigin;
if (origin == null) continue;
double distance = SkillUtils.GetDistance(decoyPos, origin);
if (distance > decoyRadius || distance <= 10) continue;
Vector direction = new(decoyPos.X - origin.X, decoyPos.Y - origin.Y, 0);
float length = direction.Length();
if (length <= 0) continue;
Vector normalized = direction / length;
float ratio = 1 - (float)(distance / decoyRadius);
float strenght = SkillsInfo.GetValue<float>(skillName, "strenght") * ratio;
float strenght = baseStrenght * (1 - (float)(distance / decoyRadius));
pawn.AbsVelocity.X += normalized.X * strenght;
pawn.AbsVelocity.Y += normalized.Y * strenght;
}
}
}
public static void GrenadeThrown(EventGrenadeThrown @event)
{
@ -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)

View file

@ -10,9 +10,14 @@ namespace src.utils
private static readonly string configPath = Path.Combine(configsFolder, "config.json");
private static readonly object fileLock = new();
private static DebugCategory debugFlags;
private static SettingsModel config = LoadConfig();
public static SettingsModel LoadedConfig => config;
public static DebugCategory DebugFlags => debugFlags;
public static bool DebugEnabled(DebugCategory category) => (debugFlags & category) != 0;
public static SettingsModel LoadConfig()
{
lock (fileLock)
@ -23,6 +28,7 @@ namespace src.utils
{
Instance.Logger.LogInformation("Config file does not exist. Create a new config file...");
SaveConfig(newConfig);
debugFlags = DebugCategories.Parse(newConfig.DebugMode);
return config = newConfig;
}
@ -34,7 +40,7 @@ namespace src.utils
json = sr.ReadToEnd();
newConfig = JsonConvert.DeserializeObject<SettingsModel>(json) ?? new SettingsModel();
if (IsSectionMissing(json, nameof(SettingsModel.Weapons)))
if (HasMissingKeys(json) || IsLegacyDebugMode(json))
SaveConfig(newConfig);
}
catch
@ -44,15 +50,36 @@ namespace src.utils
if (newConfig.DisplayAlwaysDescription)
newConfig.SkillDescriptionDuration = 9999;
debugFlags = DebugCategories.Parse(newConfig.DebugMode);
return config = newConfig;
}
}
private static bool IsSectionMissing(string json, string section)
private static bool HasMissingKeys(string json)
{
try
{
return Newtonsoft.Json.Linq.JObject.Parse(json)[section] == null;
var current = Newtonsoft.Json.Linq.JObject.Parse(json);
var expected = Newtonsoft.Json.Linq.JObject.FromObject(new SettingsModel());
foreach (var property in expected.Properties())
if (current[property.Name] == null) return true;
return false;
}
catch
{
return false;
}
}
private static bool IsLegacyDebugMode(string json)
{
try
{
var token = Newtonsoft.Json.Linq.JObject.Parse(json)[nameof(SettingsModel.DebugMode)];
return token != null && token.Type == Newtonsoft.Json.Linq.JTokenType.Boolean;
}
catch
{
@ -93,7 +120,8 @@ namespace src.utils
public bool EnableBotSkills { get; set; }
public bool EnableBotKickDebug { get; set; }
public bool EnableFullForceUpdate { get; set; }
public bool DebugMode { get; set; }
[JsonConverter(typeof(DebugModeConverter))]
public int DebugMode { get; set; }
public bool PerfMode { get; set; }
public string? AlternativeSkillButton { get; set; }
public float SkillTimeBeforeStart { get; set; }
@ -126,7 +154,7 @@ namespace src.utils
EnableBotSkills = true;
EnableBotKickDebug = false;
EnableFullForceUpdate = false;
DebugMode = false;
DebugMode = 0;
PerfMode = false;
AlternativeSkillButton = null;
SkillTimeBeforeStart = 7;

View file

@ -0,0 +1,74 @@
using Newtonsoft.Json;
namespace src.utils
{
[Flags]
public enum DebugCategory
{
None = 0,
Skill = 1 << 0,
Round = 1 << 1,
Entity = 1 << 2,
Damage = 1 << 3,
Core = 1 << 4,
}
public static class DebugCategories
{
public const int LegacyEnabledValue = 1234;
public static DebugCategory Parse(int value)
{
if (value <= 0) return DebugCategory.None;
DebugCategory flags = DebugCategory.None;
for (int rest = value; rest > 0; rest /= 10)
{
flags |= (rest % 10) switch
{
1 => DebugCategory.Skill,
2 => DebugCategory.Round,
3 => DebugCategory.Entity,
4 => DebugCategory.Damage,
_ => DebugCategory.None,
};
}
if (flags != DebugCategory.None) flags |= DebugCategory.Core;
return flags;
}
public static string Describe(DebugCategory flags)
{
if (flags == DebugCategory.None) return "Off";
List<string> parts = [];
if (flags.HasFlag(DebugCategory.Skill)) parts.Add("Skill");
if (flags.HasFlag(DebugCategory.Round)) parts.Add("Round");
if (flags.HasFlag(DebugCategory.Entity)) parts.Add("Entity");
if (flags.HasFlag(DebugCategory.Damage)) parts.Add("Damage");
return parts.Count == 0 ? "Off" : string.Join(" + ", parts);
}
}
public sealed class DebugModeConverter : JsonConverter<int>
{
public override int ReadJson(JsonReader reader, Type objectType, int existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return reader.TokenType switch
{
JsonToken.Boolean => (bool)reader.Value! ? DebugCategories.LegacyEnabledValue : 0,
JsonToken.Integer => Convert.ToInt32(reader.Value),
JsonToken.Float => Convert.ToInt32(reader.Value),
JsonToken.String => int.TryParse((string?)reader.Value, out int parsed) ? parsed : 0,
_ => 0,
};
}
public override void WriteJson(JsonWriter writer, int value, JsonSerializer serializer)
{
writer.WriteValue(value);
}
}
}

View file

@ -0,0 +1,91 @@
using CounterStrikeSharp.API.Modules.Utils;
using src.player;
namespace src.utils
{
public static class DecoyTracker
{
private sealed class Entry
{
public required Skills Skill { get; init; }
public required uint EntityId { get; init; }
public required Vector Position { get; init; }
public required uint Owner { get; init; }
}
private static readonly object gate = new();
private static readonly List<Entry> entries = [];
private static readonly Dictionary<Skills, Vector[]> positionCache = [];
public static void Add(Skills skill, uint entityId, Vector position, uint owner)
{
lock (gate)
{
entries.RemoveAll(e => e.Skill == skill && e.EntityId == entityId);
entries.Add(new Entry { Skill = skill, EntityId = entityId, Position = position, Owner = owner });
positionCache.Remove(skill);
}
}
public static void Remove(Skills skill, uint entityId)
{
lock (gate)
{
if (entries.RemoveAll(e => e.Skill == skill && e.EntityId == entityId) == 0) return;
positionCache.Remove(skill);
}
DecoyRing.Hide(skill, entityId);
}
public static void RemoveOwner(Skills skill, uint owner)
{
List<uint> removed = [];
lock (gate)
{
foreach (var entry in entries)
if (entry.Skill == skill && entry.Owner == owner)
removed.Add(entry.EntityId);
if (removed.Count == 0) return;
entries.RemoveAll(e => e.Skill == skill && e.Owner == owner);
positionCache.Remove(skill);
}
foreach (var entityId in removed)
DecoyRing.Hide(skill, entityId);
}
public static void Clear(Skills skill)
{
lock (gate)
{
entries.RemoveAll(e => e.Skill == skill);
positionCache.Remove(skill);
}
DecoyRing.ClearAll(skill);
}
public static Vector[] Positions(Skills skill)
{
lock (gate)
{
if (positionCache.TryGetValue(skill, out var cached)) return cached;
List<Vector> list = [];
foreach (var entry in entries)
if (entry.Skill == skill)
list.Add(entry.Position);
var result = list.ToArray();
positionCache[skill] = result;
return result;
}
}
public static bool IsEmpty(Skills skill) => Positions(skill).Length == 0;
}
}

View file

@ -2,6 +2,7 @@ using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Entities.Constants;
using CounterStrikeSharp.API.Modules.Utils;
using src.player;
using System.Collections.Concurrent;
using System.Drawing;
using static src.jRandomSkills;
@ -48,6 +49,20 @@ namespace src.utils
EntityType = entityType,
CreatedAt = DateTime.UtcNow
};
if (Config.DebugEnabled(DebugCategory.Entity))
Debug.WriteToDebug($"[Entity] + {entityType} #{entityIndex} owner={DescribeOwner(playerIndex)} tracked={trackedEntities.Count}", DebugCategory.Entity);
}
private static string DescribeOwner(uint playerIndex)
{
return playerIndex == SystemOwnerIndex ? "system" : playerIndex.ToString();
}
private static void LogEntityError(string message)
{
Server.PrintToConsole($"[EntityManager] {message}");
Debug.WriteToDebug($"[Entity] ! {message}", DebugCategory.Entity);
}
public static void RegisterExisting(CBaseEntity? entity, uint playerIndex, string entityType)
@ -95,7 +110,7 @@ namespace src.utils
}
catch (Exception ex)
{
Server.PrintToConsole($"[EntityManager] CreateTrackedParticleSystem: {ex.Message}");
LogEntityError($"CreateTrackedParticleSystem: {ex.Message}");
return null;
}
}
@ -113,7 +128,7 @@ namespace src.utils
}
catch (Exception ex)
{
Server.PrintToConsole($"[EntityManager] CreateTrackedDynamicProp: {ex.Message}");
LogEntityError($"CreateTrackedDynamicProp: {ex.Message}");
return null;
}
}
@ -137,7 +152,7 @@ namespace src.utils
}
catch (Exception ex)
{
Server.PrintToConsole($"[EntityManager] CreateTrackedChicken: {ex.Message}");
LogEntityError($"CreateTrackedChicken: {ex.Message}");
return null;
}
}
@ -155,7 +170,7 @@ namespace src.utils
}
catch (Exception ex)
{
Server.PrintToConsole($"[EntityManager] CreateTrackedPhysicsProp: {ex.Message}");
LogEntityError($"CreateTrackedPhysicsProp: {ex.Message}");
return null;
}
}
@ -195,7 +210,7 @@ namespace src.utils
}
catch (Exception ex)
{
Server.PrintToConsole($"[EntityManager] CreateTrackedTrigger: {ex.Message}");
LogEntityError($"CreateTrackedTrigger: {ex.Message}");
return null;
}
}
@ -222,7 +237,7 @@ namespace src.utils
}
catch (Exception ex)
{
Server.PrintToConsole($"[EntityManager] CreateTrackedBeam: {ex.Message}");
LogEntityError($"CreateTrackedBeam: {ex.Message}");
return null;
}
}
@ -248,7 +263,10 @@ namespace src.utils
public static bool DestroyEntity(uint entityIndex, float delay = 0.1f)
{
trackedEntities.TryRemove(entityIndex, out _);
bool wasTracked = trackedEntities.TryRemove(entityIndex, out var removed);
if (wasTracked && Config.DebugEnabled(DebugCategory.Entity))
Debug.WriteToDebug($"[Entity] - {removed.EntityType} #{entityIndex} owner={DescribeOwner(removed.PlayerIndex)} tracked={trackedEntities.Count}", DebugCategory.Entity);
if (SuppressKills)
return false;
@ -267,7 +285,7 @@ namespace src.utils
}
catch (Exception ex)
{
Server.PrintToConsole($"[EntityManager] DestroyEntity {entityIndex}: {ex.Message}");
LogEntityError($"DestroyEntity {entityIndex}: {ex.Message}");
}
return false;
@ -291,7 +309,7 @@ namespace src.utils
}
catch (Exception ex)
{
Server.PrintToConsole($"[EntityManager] DestroyBeam {entityIndex}: {ex.Message}");
LogEntityError($"DestroyBeam {entityIndex}: {ex.Message}");
}
bool killed = DestroyEntity(entityIndex);

View file

@ -671,7 +671,7 @@ namespace src.utils
return true;
}
public readonly record struct HiddenPawn(uint Index, CsTeam Team, CCSPlayerPawn Pawn, bool HoldsBomb);
public readonly record struct HiddenPawn(uint Index, CsTeam Team, CCSPlayerPawn Pawn, bool HoldsBomb, uint[] CarriedIndexes);
public static List<HiddenPawn> ResolveHiddenPawns(ICollection<uint> playerIndexes, uint? bombOwnerIndex)
{
@ -685,33 +685,41 @@ namespace src.utils
var pawn = controller.PlayerPawn.Value;
if (pawn == null || !pawn.IsValid) continue;
hidden.Add(new HiddenPawn(controller.Index, controller.Team, pawn, bombOwnerIndex == controller.Index));
hidden.Add(new HiddenPawn(controller.Index, controller.Team, pawn, bombOwnerIndex == controller.Index, ResolveCarriedIndexes(pawn)));
}
return hidden;
}
public static void HideCarriedEntities(CCheckTransmitInfo info, CCSPlayerPawn? pawn)
private static uint[] ResolveCarriedIndexes(CCSPlayerPawn pawn)
{
if (pawn == null || !pawn.IsValid) return;
var weaponServices = pawn.WeaponServices;
if (weaponServices == null) return;
if (weaponServices == null) return [];
List<uint> indexes = [];
var activeWeapon = weaponServices.ActiveWeapon?.Value;
if (activeWeapon != null && activeWeapon.IsValid && info.TransmitEntities.Contains(activeWeapon.Index))
info.TransmitEntities.Remove(activeWeapon.Index);
if (weaponServices.MyWeapons == null) return;
if (activeWeapon != null && activeWeapon.IsValid)
indexes.Add(activeWeapon.Index);
if (weaponServices.MyWeapons != null)
foreach (var handle in weaponServices.MyWeapons)
{
var weapon = handle?.Value;
if (weapon == null || !weapon.IsValid) continue;
if (indexes.Contains(weapon.Index)) continue;
if (info.TransmitEntities.Contains(weapon.Index))
info.TransmitEntities.Remove(weapon.Index);
indexes.Add(weapon.Index);
}
return [.. indexes];
}
public static void HideCarriedEntities(CCheckTransmitInfo info, in HiddenPawn target)
{
foreach (var index in target.CarriedIndexes)
if (info.TransmitEntities.Contains(index))
info.TransmitEntities.Remove(index);
}
public static void ResetPrintHTML(CCSPlayerController? player)
@ -1050,16 +1058,16 @@ namespace src.utils
: $"<font class='fontWeight-Bold fontSize-{config.SkillLineSize}' color='{skillData.Color}'>\u202A{player.GetSkillName(skillData.Skill)}\u202C</font><br>";
var skill_select_info = player.GetTranslation($"{playerInfo.Skill.ToString().ToLowerInvariant()}_select_info");
string remainingLine = string.IsNullOrWhiteSpace(skill_select_info)
string remainingLine = string.IsNullOrWhiteSpace(skill_select_info) || string.IsNullOrEmpty(config.WSADMenuSelectInfoLineSize)
? ""
: $"<font class='fontSize-{config.WSADMenuSelectInfoLineSize}' color='{config.WSADMenuSelectInfoLineColor}'>{skill_select_info}</font><br>";
var hudContent = infoLine + skillLine + remainingLine;
string controllsLine =
string controllsLine = string.IsNullOrEmpty(config.WSADMenuControllsLineSize) ? "" :
$"{emptySymbol}<font class='fontSize-{config.WSADMenuControllsLineSize}' color='{config.WSADMenuControllsLineColor1}'>{player.GetTranslationWithoutIlliterate($"menu_controlls_scroll")}</font>"
+ $"<font class='fontSize-{config.WSADMenuControllsLineSize}' color='{config.WSADMenuControllsLineColor2}'>{player.GetTranslationWithoutIlliterate($"menu_controlls_padding")}</font>"
+ $"<font class='fontSize-{config.WSADMenuControllsLineSize}' color='{config.WSADMenuControllsLineColor3}'>{player.GetTranslationWithoutIlliterate($"menu_controlls_select")}</font>{emptySymbol}";
+ $"<font class='fontSize-{config.WSADMenuControllsLineSize}' color='{config.WSADMenuControllsLineColor3}'>{player.GetTranslationWithoutIlliterate($"menu_controlls_select")}</font>{emptySymbol}<br>";
string itemText = $"<font class='fontSize-{config.WSADMenuItemLineSize}' color='{config.WSADMenuItemLineColor}'>{{0}}</font><br>";
string itemHoverText = $"<font class='fontSize-{config.WSADMenuItemLineSize}'><font color='purple'>[ </font><font color='{config.WSADMenuItemHoverLineColor}'>{{0}}</font><font color='purple'> ]</font></font><br>";
@ -1103,7 +1111,8 @@ namespace src.utils
{
if (pawn == null || !pawn.IsValid) return;
if (entity == null || !entity.IsValid) return;
if (!entity.DesignerName.Contains("door")) return;
if (!entity.DesignerName.StartsWith("prop_door_rotating", StringComparison.Ordinal)) return;
var door = new CPropDoorRotating(entity.Handle);
if (door == null || !door.IsValid) return;

View file

@ -85,6 +85,14 @@ namespace src.utils
}
}
public static DefaultSkillInfo? GetSkillConfig(Skills skill)
{
if (config == null) return null;
EnsureIndex();
return _byName.TryGetValue(SkillNames.Get(skill), out var skillConfig) ? skillConfig : null;
}
public static T GetValue<T>(object skill, string key)
{
if (config == null) return default!;
@ -171,4 +179,30 @@ namespace src.utils
}
}
public static class SkillNames
{
private static readonly string[] names = BuildNames();
private static string[] BuildNames()
{
var values = Enum.GetValues<Skills>();
int max = 0;
foreach (var value in values)
if ((int)value > max) max = (int)value;
var table = new string[max + 1];
foreach (var value in values)
table[(int)value] = value.ToString();
return table;
}
public static string Get(Skills skill)
{
int index = (int)skill;
if (index < 0 || index >= names.Length) return skill.ToString();
return names[index] ?? skill.ToString();
}
}
}

View file

@ -8,7 +8,7 @@
"EnableBotSkills": true,
"EnableBotKickDebug": false,
"EnableFullForceUpdate": false,
"DebugMode": false,
"DebugMode": 0,
"PerfMode": false,
"AlternativeSkillButton": null,
"SkillTimeBeforeStart": 7.0,

View file

@ -818,7 +818,7 @@
},
{
"ParticleName": "particles/inferno_fx/incgrenade_thrown_trail.vpcf",
"ParticleOffset": 0.0,
"ParticleOffset": 10.0,
"MaximumFuel": 150.0,
"FuelConsumption": 0.64,
"Refuelling": 0.1,