Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of FearNoSpear v1.0.6
FearNoSpear.dll
Decompiled a month ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("FearNoSpear")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("sighsorry")] [assembly: AssemblyProduct("FearNoSpear")] [assembly: AssemblyCopyright("Copyright 2026 sighsorry")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: AssemblyFileVersion("1.0.6")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.6.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FearNoSpear { [BepInPlugin("sighsorry.FearNoSpear", "FearNoSpear", "1.0.6")] public sealed class FearNoSpearPlugin : BaseUnityPlugin { public enum Toggle { On = 1, Off = 0 } public const string Author = "sighsorry"; public const string ModName = "FearNoSpear"; public const string PluginGuid = "sighsorry.FearNoSpear"; public const string PluginName = "FearNoSpear"; public const string ModVersion = "1.0.6"; public const string PluginVersion = "1.0.6"; internal static ManualLogSource Log = null; internal static FearNoSpearConfig Cfg = null; private static readonly ConfigSync Sync = new ConfigSync("sighsorry.FearNoSpear") { DisplayName = "FearNoSpear", CurrentVersion = "1.0.6", MinimumRequiredVersion = "1.0.6" }; private static ConfigEntry<Toggle> _serverConfigLocked = null; private Harmony? _harmony; private FileSystemWatcher? _watcher; private readonly object _reloadLock = new object(); private DateTime _lastConfigReloadTime; private const long ReloadDelayTicks = 10000000L; internal static bool IsShuttingDown { get; private set; } private static string ConfigFileName => "sighsorry.FearNoSpear.cfg"; private static string ConfigFileFullPath => Path.Combine(Paths.ConfigPath, ConfigFileName); private void Awake() { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; _serverConfigLocked = BindConfig("General", "Lock Configuration", Toggle.On, "Locks the synchronized gameplay settings to the server's config when the mod is installed on a server. Keep this on for multiplayer servers so every client uses the same spear rescue timing and ownership safety rules."); Sync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); Cfg = new FearNoSpearConfig(this); ReflectionCache.Initialize(((BaseUnityPlugin)this).Logger); _harmony = new Harmony("sighsorry.FearNoSpear"); _harmony.PatchAll(); SetupWatcher(); ((BaseUnityPlugin)this).Config.Save(); ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; ((BaseUnityPlugin)this).Logger.LogInfo((object)"FearNoSpear 1.0.6 loaded"); } private void OnDestroy() { IsShuttingDown = true; SaveWithRespectToConfigSet(); _watcher?.Dispose(); Harmony? harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private void OnApplicationQuit() { IsShuttingDown = true; } internal ConfigEntry<T> BindConfig<T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown string text = (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"); ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, new ConfigDescription(description + text, (AcceptableValueBase)null, Array.Empty<object>())); Sync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting; return val; } private void SetupWatcher() { _watcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName) { IncludeSubdirectories = true, SynchronizingObject = ThreadingHelper.SynchronizingObject, EnableRaisingEvents = true }; _watcher.Changed += ReadConfigValues; _watcher.Created += ReadConfigValues; _watcher.Renamed += ReadConfigValues; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { DateTime now = DateTime.Now; if (now.Ticks - _lastConfigReloadTime.Ticks < 10000000) { return; } lock (_reloadLock) { if (!File.Exists(ConfigFileFullPath)) { Log.LogWarning((object)"Config file does not exist. Skipping reload."); return; } try { Log.LogDebug((object)"Reloading configuration..."); SaveWithRespectToConfigSet(reload: true); Log.LogInfo((object)"Configuration reload complete."); } catch (Exception ex) { Log.LogError((object)("Error reloading configuration: " + ex.Message)); } } _lastConfigReloadTime = now; } private void SaveWithRespectToConfigSet(bool reload = false) { bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; if (reload) { ((BaseUnityPlugin)this).Config.Reload(); } ((BaseUnityPlugin)this).Config.Save(); ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } } internal sealed class FearNoSpearConfig { internal readonly ConfigEntry<bool> Enabled; internal const float MinimumInitialTtlSeconds = 60f; internal const int MaxPinsPerCommand = 5; internal readonly ConfigEntry<float> TtlRescueWindowSeconds; internal readonly ConfigEntry<bool> AllowLastKnownOwnerIfZNetViewInvalid; internal readonly ConfigEntry<float> LastKnownOwnerGraceSeconds; internal readonly ConfigEntry<string> ChatCommand; internal readonly ConfigEntry<bool> CleanDeathPins; internal FearNoSpearConfig(FearNoSpearPlugin plugin) { Enabled = plugin.BindConfig("General", "Enabled", value: true, "Master switch for all FearNoSpear behavior. When disabled, the mod does not track thrown spear projectiles, extend their TTL, or rescue stored spear item data."); ChatCommand = plugin.BindConfig("General", "ChatCommand", "!myspear", "Chat command used to pin known thrown spear locations on the minimap, nearest first. The comparison is case-insensitive and the command is consumed locally instead of being sent to public chat. Server operators can change this value, such as !spear or !lostspear, and lock it through ServerSync. Leave it empty to disable the chat command."); CleanDeathPins = plugin.BindConfig("General", "CleanDeathPins", value: true, "Removes the vanilla death map pin when the local player's tombstone is recovered, and suppresses the death pin when a death creates no tombstone. This setting is synchronized so server operators can keep the same behavior for all clients."); TtlRescueWindowSeconds = plugin.BindConfig("Rescue", "TTLRescueWindowSeconds", 1f, "How close to projectile TTL expiry the mod should rescue a still-airborne tracked spear. A value of 1.0 means the stored spear item is respawned during the final second of projectile lifetime if no normal hit occurred. Increase this if projectiles are still being cleaned up before rescue; decrease it if rescued spears feel like they stop flying too early."); AllowLastKnownOwnerIfZNetViewInvalid = plugin.BindConfig("Rescue", "AllowLastKnownOwnerIfZNetViewInvalid", value: true, "Allows a rescue attempt when the projectile ZNetView has already become invalid, but only if this client was the most recent known owner. This helps recover spears lost during unload, ownership disruption, or network cleanup. Disable it if multiplayer testing shows duplicate rescued spears."); LastKnownOwnerGraceSeconds = plugin.BindConfig("Rescue", "LastKnownOwnerGraceSeconds", 2f, "Maximum age, in seconds, for the last-known owner state used by the invalid-ZNetView fallback. Lower values reduce duplicate-spawn risk but may miss late cleanup cases; higher values are more forgiving but less conservative in multiplayer."); } } internal static class ReflectionCache { internal static FieldInfo? F_ttl; internal static FieldInfo? F_vel; internal static FieldInfo? F_nview; internal static FieldInfo? F_didHit; internal static FieldInfo? F_weapon; internal static FieldInfo? F_spawnItem; internal static FieldInfo? F_respawnItemOnHit; internal static FieldInfo? F_groundHitOnly; internal static FieldInfo? F_terminalInput; internal static MethodInfo? M_spawnOnHit; internal static MethodInfo? M_itemDropDropItem; internal static FieldInfo? F_minimapPins; internal static void Initialize(ManualLogSource log) { F_ttl = AccessTools.Field(typeof(Projectile), "m_ttl"); F_vel = AccessTools.Field(typeof(Projectile), "m_vel"); F_nview = AccessTools.Field(typeof(Projectile), "m_nview"); F_didHit = AccessTools.Field(typeof(Projectile), "m_didHit"); F_weapon = AccessTools.Field(typeof(Projectile), "m_weapon"); F_spawnItem = AccessTools.Field(typeof(Projectile), "m_spawnItem"); F_respawnItemOnHit = AccessTools.Field(typeof(Projectile), "m_respawnItemOnHit"); F_groundHitOnly = AccessTools.Field(typeof(Projectile), "m_groundHitOnly"); F_terminalInput = AccessTools.Field(typeof(Terminal), "m_input"); M_spawnOnHit = AccessTools.Method(typeof(Projectile), "SpawnOnHit", new Type[3] { typeof(GameObject), typeof(Collider), typeof(Vector3) }, (Type[])null) ?? AccessTools.GetDeclaredMethods(typeof(Projectile)).FirstOrDefault((MethodInfo m) => m.Name == "SpawnOnHit" && m.GetParameters().Any((ParameterInfo p) => p.ParameterType == typeof(Vector3))) ?? AccessTools.Method(typeof(Projectile), "SpawnOnHit", (Type[])null, (Type[])null); M_itemDropDropItem = AccessTools.Method(typeof(ItemDrop), "DropItem", new Type[4] { typeof(ItemData), typeof(int), typeof(Vector3), typeof(Quaternion) }, (Type[])null); F_minimapPins = AccessTools.Field(typeof(Minimap), "m_pins"); WarnMissing(log, "F_ttl", F_ttl); WarnMissing(log, "F_vel", F_vel); WarnMissing(log, "F_nview", F_nview); WarnMissing(log, "F_didHit", F_didHit); WarnMissing(log, "F_weapon", F_weapon); WarnMissing(log, "F_spawnItem", F_spawnItem); WarnMissing(log, "F_respawnItemOnHit", F_respawnItemOnHit); WarnMissing(log, "F_groundHitOnly", F_groundHitOnly); WarnMissing(log, "F_terminalInput", F_terminalInput); WarnMissing(log, "M_spawnOnHit", M_spawnOnHit); WarnMissing(log, "M_itemDropDropItem", M_itemDropDropItem); WarnMissing(log, "F_minimapPins", F_minimapPins); } private static void WarnMissing(ManualLogSource log, string label, MemberInfo? member) { if (member == null) { log.LogWarning((object)("Reflection member not found: " + label)); } } internal static T Get<T>(FieldInfo? field, object target, T fallback) { if (field == null || target == null) { return fallback; } try { return (T)((field.GetValue(target) is T val) ? ((object)val) : ((object)fallback)); } catch { return fallback; } } internal static void Set<T>(FieldInfo? field, object target, T value) { if (field == null || target == null) { return; } try { field.SetValue(target, value); } catch { } } internal static ZNetView? GetNView(Projectile projectile) { return Get<ZNetView>(F_nview, projectile, null); } } internal static class SpearProjectileDetector { internal static bool IsRecoverableProjectile(Projectile projectile) { if ((Object)(object)projectile == (Object)null) { return false; } if (!ReflectionCache.Get(ReflectionCache.F_respawnItemOnHit, projectile, fallback: false)) { return false; } return ReflectionCache.Get<ItemData>(ReflectionCache.F_spawnItem, projectile, null) != null; } internal static bool IsTrackedSpearProjectile(Projectile projectile) { if (!IsRecoverableProjectile(projectile)) { return false; } ItemData item = ReflectionCache.Get<ItemData>(ReflectionCache.F_spawnItem, projectile, null); ItemData item2 = ReflectionCache.Get<ItemData>(ReflectionCache.F_weapon, projectile, null); if (IsSpearItem(item) || IsSpearItem(item2)) { return true; } return ContainsSpearToken(((Object)projectile).name ?? string.Empty); } internal static bool IsSpearItem(ItemData? item) { if (item?.m_shared == null) { return false; } string a = ((object)Unsafe.As<SkillType, SkillType>(ref item.m_shared.m_skillType)/*cast due to .constrained prefix*/).ToString(); if (string.Equals(a, "Spears", StringComparison.OrdinalIgnoreCase) || string.Equals(a, "Spear", StringComparison.OrdinalIgnoreCase)) { return true; } return ContainsSpearToken(item.m_shared.m_name); } private static bool ContainsSpearToken(string? value) { if (value == null || value.Length == 0) { return false; } return value.IndexOf("spear", StringComparison.OrdinalIgnoreCase) >= 0; } internal static string DescribeProjectile(Projectile projectile) { ItemData obj = ReflectionCache.Get<ItemData>(ReflectionCache.F_spawnItem, projectile, null); ItemData val = ReflectionCache.Get<ItemData>(ReflectionCache.F_weapon, projectile, null); string text = obj?.m_shared?.m_name ?? "<null>"; string text2 = val?.m_shared?.m_name ?? "<null>"; string text3 = ((object)Unsafe.As<SkillType, SkillType>(ref obj?.m_shared?.m_skillType)/*cast due to .constrained prefix*/).ToString() ?? ((object)Unsafe.As<SkillType, SkillType>(ref val?.m_shared?.m_skillType)/*cast due to .constrained prefix*/).ToString() ?? "<unknown>"; return "projectile=" + ((Object)projectile).name + ", spawnItem=" + text + ", weapon=" + text2 + ", skill=" + text3; } } [HarmonyPatch(typeof(Projectile), "Setup")] internal static class ProjectileSetupPatch { private static void Postfix(Projectile __instance) { if (FearNoSpearPlugin.Cfg.Enabled.Value) { SpearSafetyTracker.GetOrArmIfTracked(__instance); } } } [HarmonyPatch(typeof(Projectile), "FixedUpdate")] internal static class ProjectileFixedUpdatePatch { private static bool Prefix(Projectile __instance) { if (!FearNoSpearPlugin.Cfg.Enabled.Value) { return true; } SpearSafetyTracker spearSafetyTracker = ((Component)__instance).GetComponent<SpearSafetyTracker>() ?? SpearSafetyTracker.GetOrArmIfTracked(__instance); if ((Object)(object)spearSafetyTracker == (Object)null) { return true; } return !spearSafetyTracker.TryTtlRescueAndDestroyIfNeeded(); } } [HarmonyPatch(typeof(Chat), "SendInput")] internal static class ChatSendInputPatch { private static bool Prefix(Chat __instance) { return !SpearChatCommand.TryConsume(__instance); } } [HarmonyPatch(typeof(Humanoid), "Pickup", new Type[] { typeof(GameObject), typeof(bool), typeof(bool) })] internal static class HumanoidPickupPatch { private static void Prefix(Humanoid __instance, GameObject go, out string? __state) { __state = null; if (FearNoSpearPlugin.Cfg.Enabled.Value && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && !((Object)(object)go == (Object)null)) { ItemDrop component = go.GetComponent<ItemDrop>(); if (!((Object)(object)component == (Object)null) && component.m_itemData != null && SpearProjectileDetector.IsSpearItem(component.m_itemData)) { __state = SpearItemIdentity.BuildDropRecordKey(component); } } } private static void Postfix(bool __result, string? __state) { if (__result && __state != null && __state.Length != 0) { SpearLocator.MarkSpearPickedUp(__state); } } } [HarmonyPatch(typeof(Game), "Start")] internal static class GameStartPatch { private static void Postfix() { SpearLocator.Clear(); SpearSafetyTracker.ClearPendingDropTags(); DeathPinCleaner.Clear(); SpearNetwork.ClearSession(); SpearNetwork.RegisterRpcs(); } } [HarmonyPatch(typeof(Game), "Update")] internal static class GameUpdatePatch { private static void Postfix() { DeathPinCleaner.UpdatePendingDeath(); if (FearNoSpearPlugin.Cfg.Enabled.Value) { SpearSafetyTracker.UpdatePendingDropTags(); SpearLocator.UpdatePendingServerRequest(); } } } [HarmonyPatch(typeof(ZNet), "Start")] internal static class ZNetStartPatch { private static void Postfix() { SpearNetwork.RegisterRpcs(); } } [HarmonyPatch] internal static class ProjectileOnHitPatch { private static bool Prepare() { return AccessTools.Method(typeof(Projectile), "OnHit", (Type[])null, (Type[])null) != null; } private static MethodBase? TargetMethod() { return AccessTools.Method(typeof(Projectile), "OnHit", (Type[])null, (Type[])null); } private static void Postfix(Projectile __instance) { if (ReflectionCache.Get(ReflectionCache.F_didHit, __instance, fallback: false)) { ((Component)__instance).GetComponent<SpearSafetyTracker>()?.MarkNormalHit(); } } } [HarmonyPatch] internal static class ZNetSceneDestroyPatch { private static bool Prepare() { return AccessTools.Method(typeof(ZNetScene), "Destroy", new Type[1] { typeof(GameObject) }, (Type[])null) != null; } private static MethodBase? TargetMethod() { return AccessTools.Method(typeof(ZNetScene), "Destroy", new Type[1] { typeof(GameObject) }, (Type[])null); } private static void Prefix(GameObject __0) { if (!FearNoSpearPlugin.Cfg.Enabled.Value || (Object)(object)__0 == (Object)null) { return; } SpearSafetyTracker spearSafetyTracker = __0.GetComponent<SpearSafetyTracker>(); if ((Object)(object)spearSafetyTracker == (Object)null) { Projectile component = __0.GetComponent<Projectile>(); if ((Object)(object)component != (Object)null) { spearSafetyTracker = SpearSafetyTracker.GetOrArmIfTracked(component); } } spearSafetyTracker?.TryRescue("ZNetScene.Destroy before hit"); } } internal static class DeathPinCleaner { private sealed class PendingDeath { internal long PlayerId; internal Vector3 Position; internal float StartedAt; } private const float RecentDeathSeconds = 8f; private const float DeathPinRemoveRadius = 32f; private static readonly Dictionary<int, Vector3> TombstoneDeathPositions = new Dictionary<int, Vector3>(); private static readonly HashSet<int> CleanedTombstones = new HashSet<int>(); private static PendingDeath? _pendingDeath; internal static void Clear() { TombstoneDeathPositions.Clear(); CleanedTombstones.Clear(); _pendingDeath = null; } internal static void BeginLocalDeath(Player player) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) if (IsEnabled() && !((Object)(object)player == (Object)null) && !((Object)(object)player != (Object)(object)Player.m_localPlayer)) { long localPlayerId = GetLocalPlayerId(); if (localPlayerId != 0L) { _pendingDeath = new PendingDeath { PlayerId = localPlayerId, Position = ((Component)player).transform.position, StartedAt = Time.time }; } } } internal static void UpdatePendingDeath() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) PendingDeath pendingDeath = _pendingDeath; if (pendingDeath != null) { if (!IsEnabled()) { _pendingDeath = null; } else if (!(Time.time - pendingDeath.StartedAt < 8f)) { _pendingDeath = null; RemoveNearestDeathPin(pendingDeath.Position); } } } internal static void RegisterTombstone(TombStone tombstone) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) if (!IsEnabled() || (Object)(object)tombstone == (Object)null) { return; } long owner = tombstone.GetOwner(); if (owner != 0L && owner == GetLocalPlayerId()) { int instanceID = ((Object)tombstone).GetInstanceID(); Vector3 val = GetTombstonePinPosition(tombstone); PendingDeath pendingDeath = _pendingDeath; if (pendingDeath != null && pendingDeath.PlayerId == owner && Time.time - pendingDeath.StartedAt <= 8f && Vector3.SqrMagnitude(val - pendingDeath.Position) <= 1024f) { val = pendingDeath.Position; _pendingDeath = null; } TombstoneDeathPositions[instanceID] = val; } } internal static void CleanForRecoveredTombstone(TombStone tombstone) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (IsEnabled() && IsLocalTombstone(tombstone)) { int instanceID = ((Object)tombstone).GetInstanceID(); if (CleanedTombstones.Add(instanceID)) { Vector3 value; Vector3 position = (TombstoneDeathPositions.TryGetValue(instanceID, out value) ? value : GetTombstonePinPosition(tombstone)); TombstoneDeathPositions.Remove(instanceID); RemoveNearestDeathPin(position); } } } internal static void CleanIfTombstoneIsEmpty(TombStone tombstone) { if (IsEnabled() && IsLocalTombstone(tombstone) && IsTombstoneEmpty(tombstone)) { CleanForRecoveredTombstone(tombstone); } } private static bool IsEnabled() { if (FearNoSpearPlugin.Cfg.Enabled.Value) { return FearNoSpearPlugin.Cfg.CleanDeathPins.Value; } return false; } private static bool IsLocalTombstone(TombStone tombstone) { if ((Object)(object)tombstone == (Object)null) { return false; } long owner = tombstone.GetOwner(); long localPlayerId = GetLocalPlayerId(); if (owner != 0L) { return owner == localPlayerId; } return false; } private static long GetLocalPlayerId() { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { return localPlayer.GetPlayerID(); } Game instance = Game.instance; PlayerProfile val = (((Object)(object)instance != (Object)null) ? instance.GetPlayerProfile() : null); if (val == null) { return 0L; } return val.GetPlayerID(); } private static bool IsTombstoneEmpty(TombStone tombstone) { Container container = tombstone.m_container; Inventory val = (((Object)(object)container != (Object)null) ? container.GetInventory() : null); if (val != null) { return val.NrOfItems() <= 0; } return false; } private static Vector3 GetTombstonePinPosition(TombStone tombstone) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) ZNetView component = ((Component)tombstone).GetComponent<ZNetView>(); if ((Object)(object)component != (Object)null && component.IsValid()) { ZDO zDO = component.GetZDO(); if (zDO != null && zDO.IsValid()) { return zDO.GetVec3(ZDOVars.s_spawnPoint, ((Component)tombstone).transform.position); } } return ((Component)tombstone).transform.position; } private static bool RemoveNearestDeathPin(Vector3 position) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) Minimap instance = Minimap.instance; if ((Object)(object)instance == (Object)null) { return false; } if (!(ReflectionCache.F_minimapPins?.GetValue(instance) is List<PinData> source)) { return false; } PinData val = (from pin in source where pin != null && pin.m_save && (int)pin.m_type == 4 where Vector3.Distance(pin.m_pos, position) <= 32f orderby Vector3.SqrMagnitude(pin.m_pos - position) select pin).FirstOrDefault(); if (val == null) { return false; } instance.RemovePin(val); return true; } } [HarmonyPatch(typeof(Player), "OnDeath")] internal static class PlayerOnDeathDeathPinPatch { private static void Prefix(Player __instance) { DeathPinCleaner.BeginLocalDeath(__instance); } } [HarmonyPatch(typeof(TombStone), "Setup", new Type[] { typeof(string), typeof(long) })] internal static class TombStoneSetupDeathPinPatch { private static void Postfix(TombStone __instance) { DeathPinCleaner.RegisterTombstone(__instance); } } [HarmonyPatch(typeof(TombStone), "OnTakeAllSuccess")] internal static class TombStoneTakeAllDeathPinPatch { private static void Postfix(TombStone __instance) { DeathPinCleaner.CleanForRecoveredTombstone(__instance); } } [HarmonyPatch(typeof(TombStone), "UpdateDespawn")] internal static class TombStoneUpdateDespawnDeathPinPatch { private static void Prefix(TombStone __instance) { DeathPinCleaner.CleanIfTombstoneIsEmpty(__instance); } } internal static class SpearChatCommand { internal static bool TryConsume(Chat chat) { string text = FearNoSpearPlugin.Cfg.ChatCommand.Value.Trim(); if (string.IsNullOrEmpty(text)) { return false; } if (!string.Equals(GetInputText(chat).Trim(), text, StringComparison.OrdinalIgnoreCase)) { return false; } ClearInput(chat); SpearLocator.PinKnownSpear(); return true; } private static string GetInputText(Chat chat) { object obj = ReflectionCache.Get<object>(ReflectionCache.F_terminalInput, chat, null); if (obj == null) { return string.Empty; } return (obj.GetType().GetProperty("text", BindingFlags.Instance | BindingFlags.Public)?.GetValue(obj, null) as string) ?? string.Empty; } private static void ClearInput(Chat chat) { object obj = ReflectionCache.Get<object>(ReflectionCache.F_terminalInput, chat, null); if (obj != null) { obj.GetType().GetProperty("text", BindingFlags.Instance | BindingFlags.Public)?.SetValue(obj, string.Empty, null); Component val = (Component)((obj is Component) ? obj : null); if (val != null) { val.gameObject.SetActive(false); } chat.Hide(); } } } internal static class SpearItemIdentity { internal static string BuildDropRecordKey(ItemDrop drop) { string text = TryGetZdoKey(((Component)drop).GetComponent<ZNetView>()); if (text != null && text.Length > 0) { return BuildDropRecordKey(text); } return $"drop-local:{((Object)drop).GetInstanceID()}"; } internal unsafe static string BuildWorldDropRecordKey(ZDOID zdoId) { return BuildDropRecordKey(((object)(*(ZDOID*)(&zdoId))/*cast due to .constrained prefix*/).ToString()); } internal static string? TryGetZdoKey(ZNetView? nview) { if ((Object)(object)nview == (Object)null || !nview.IsValid()) { return null; } ZDO zDO = nview.GetZDO(); if (zDO == null || !zDO.IsValid()) { return null; } return ((object)Unsafe.As<ZDOID, ZDOID>(ref zDO.m_uid)/*cast due to .constrained prefix*/).ToString(); } private static string BuildDropRecordKey(string zdoKey) { return "drop:" + zdoKey; } internal static bool IsEquivalent(ItemData expected, ItemData actual) { if ((Object)(object)expected.m_dropPrefab != (Object)(object)actual.m_dropPrefab) { return false; } if (expected.m_shared?.m_name != actual.m_shared?.m_name) { return false; } if (expected.m_quality != actual.m_quality) { return false; } if (expected.m_variant != actual.m_variant) { return false; } if (expected.m_worldLevel != actual.m_worldLevel) { return false; } if (expected.m_crafterID != actual.m_crafterID) { return false; } if (!string.Equals(expected.m_crafterName, actual.m_crafterName, StringComparison.Ordinal)) { return false; } float num = Mathf.Max(0f, expected.m_durability); float num2 = Mathf.Max(0f, actual.m_durability); if (Mathf.Abs(num - num2) > 0.01f) { return false; } return DictionariesEqual(expected.m_customData, actual.m_customData); } private static bool DictionariesEqual(Dictionary<string, string>? expected, Dictionary<string, string>? actual) { int num = expected?.Count ?? 0; int num2 = actual?.Count ?? 0; if (num != num2) { return false; } if (num == 0) { return true; } if (expected == null || actual == null) { return false; } foreach (KeyValuePair<string, string> item in expected) { if (!actual.TryGetValue(item.Key, out string value)) { return false; } if (!string.Equals(item.Value, value, StringComparison.Ordinal)) { return false; } } return true; } } internal static class SpearLocator { private const float ServerRequestTimeoutSeconds = 2f; private static readonly List<SpearLocationRecord> PendingLoadedRecords = new List<SpearLocationRecord>(); private static float _serverRequestFallbackAt = float.NegativeInfinity; internal static void Clear() { PendingLoadedRecords.Clear(); ClearPendingServerRequest(); SpearPinManager.Clear(); } internal static void PinKnownSpear() { if (!FearNoSpearPlugin.Cfg.Enabled.Value) { ShowMessage("FearNoSpear is disabled."); return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { FearNoSpearPlugin.Log.LogInfo((object)"Could not run !myspear because no local player exists."); return; } PendingLoadedRecords.Clear(); PendingLoadedRecords.AddRange(FindLoadedSpearDrops(localPlayer)); if (SpearNetwork.RequestServerSpearLocation(localPlayer)) { _serverRequestFallbackAt = Time.time + 2f; ShowMessage("Requesting spear location from server..."); } else { PinPendingLoadedSpears("No spear drop location found.", "Pinned local spear location"); } } internal static void PinServerSpears(List<SpearLocationRecord> serverRecords) { ClearPendingServerRequest(); if ((Object)(object)Player.m_localPlayer == (Object)null) { PendingLoadedRecords.Clear(); FearNoSpearPlugin.Log.LogInfo((object)"Received a spear location from the server, but no local player exists."); } else { List<SpearLocationRecord> records = MergeServerWithLoadedRecords(serverRecords); PendingLoadedRecords.Clear(); PinRecords(records, "No spear drop location found on server or client.", "Pinned spear location"); } } internal static void MarkSpearPickedUp(string recordKey) { if (!string.IsNullOrEmpty(recordKey)) { SpearPinManager.RemoveForPickedSpear(recordKey); } } internal static void PinLocalAfterEmptyServer() { ClearPendingServerRequest(); PinPendingLoadedSpears("No spear drop location found on server or client.", "Server had no spear record; pinned local loaded spear location"); } internal static void UpdatePendingServerRequest() { if (!(_serverRequestFallbackAt <= 0f) && !(Time.time < _serverRequestFallbackAt)) { ClearPendingServerRequest(); PinPendingLoadedSpears("No response from server and no local spear drop location found.", "Server did not respond; pinned local loaded spear location"); } } private static void ClearPendingServerRequest() { _serverRequestFallbackAt = float.NegativeInfinity; } private static bool PinPendingLoadedSpears(string missingMessage, string pinnedPrefix) { List<SpearLocationRecord> records = PendingLoadedRecords.ToList(); PendingLoadedRecords.Clear(); return PinRecords(records, missingMessage, pinnedPrefix); } private static bool PinRecords(List<SpearLocationRecord> records, string missingMessage, string pinnedPrefix) { int num = SpearPinManager.PinRecords(records, ShowMessage); if (records.Count == 0) { ShowMessage(missingMessage); return false; } string message; switch (num) { case 0: return false; default: message = $"{pinnedPrefix}s ({num})."; break; case 1: message = pinnedPrefix + "."; break; } ShowMessage(message); return true; } private static List<SpearLocationRecord> FindLoadedSpearDrops(Player localPlayer) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) long playerID = localPlayer.GetPlayerID(); if (playerID == 0L) { return new List<SpearLocationRecord>(); } Vector3 playerPosition = ((Component)localPlayer).transform.position; List<SpearLocationRecord> list = new List<SpearLocationRecord>(); ItemDrop[] array = Object.FindObjectsByType<ItemDrop>((FindObjectsSortMode)0); foreach (ItemDrop val in array) { if (!((Object)(object)val == (Object)null) && val.m_itemData != null && SpearProjectileDetector.IsSpearItem(val.m_itemData) && SpearThrowerMetadata.ReadFromDrop(val) == playerID) { list.Add(new SpearLocationRecord { Key = SpearItemIdentity.BuildDropRecordKey(val), Position = ((Component)val).transform.position }); } } return list.OrderBy((SpearLocationRecord record) => Vector3.SqrMagnitude(record.Position - playerPosition)).Take(5).ToList(); } private static List<SpearLocationRecord> MergeServerWithLoadedRecords(List<SpearLocationRecord> serverRecords) { Dictionary<string, SpearLocationRecord> dictionary = new Dictionary<string, SpearLocationRecord>(); foreach (SpearLocationRecord pendingLoadedRecord in PendingLoadedRecords) { if (!string.IsNullOrEmpty(pendingLoadedRecord.Key)) { dictionary[pendingLoadedRecord.Key] = pendingLoadedRecord; } } HashSet<string> hashSet = new HashSet<string>(); List<SpearLocationRecord> list = new List<SpearLocationRecord>(); foreach (SpearLocationRecord serverRecord in serverRecords) { if (!string.IsNullOrEmpty(serverRecord.Key) && hashSet.Add(serverRecord.Key)) { if (dictionary.TryGetValue(serverRecord.Key, out var value)) { list.Add(value); dictionary.Remove(serverRecord.Key); } else { list.Add(serverRecord); } } } foreach (SpearLocationRecord pendingLoadedRecord2 in PendingLoadedRecords) { if (dictionary.Remove(pendingLoadedRecord2.Key) && hashSet.Add(pendingLoadedRecord2.Key)) { list.Add(pendingLoadedRecord2); } } return list.Take(5).ToList(); } private static void ShowMessage(string message) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { ((Character)localPlayer).Message((MessageType)1, message, 0, (Sprite)null); } else { FearNoSpearPlugin.Log.LogInfo((object)message); } } } internal sealed class SpearLocationRecord { internal string Key = string.Empty; internal Vector3 Position; } internal static class SpearNetwork { private const int ProtocolVersion = 5; private const string RequestRpcName = "FearNoSpear_SpearLocationRequest"; private const string ResponseRpcName = "FearNoSpear_SpearLocationResponse"; private static ZRoutedRpc? _registeredRpc; internal static void ClearSession() { SpearServerRegistry.Clear(); } internal static void RegisterRpcs() { ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null && _registeredRpc != instance) { instance.Register<ZPackage>("FearNoSpear_SpearLocationRequest", (Action<long, ZPackage>)RPC_RequestSpearLocation); instance.Register<ZPackage>("FearNoSpear_SpearLocationResponse", (Action<long, ZPackage>)RPC_SpearLocationResponse); _registeredRpc = instance; } } internal static bool RequestServerSpearLocation(Player localPlayer) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0029: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)localPlayer == (Object)null) { return false; } if (!TryGetServerPeerId(out var serverPeerId)) { return false; } ZPackage val = new ZPackage(); WriteHeader(val); val.Write(((Component)localPlayer).transform.position); ZRoutedRpc.instance.InvokeRoutedRPC(serverPeerId, "FearNoSpear_SpearLocationRequest", new object[1] { val }); return true; } private static bool TryGetServerPeerId(out long serverPeerId) { serverPeerId = 0L; if ((Object)(object)ZNet.instance == (Object)null || ZRoutedRpc.instance == null) { return false; } serverPeerId = ZRoutedRpc.instance.GetServerPeerID(); if (serverPeerId == 0L) { return ZNet.instance.IsServer(); } return true; } private static void RPC_RequestSpearLocation(long senderPeerId, ZPackage package) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } Vector3 referencePosition; try { if (!TryReadHeader(package, "FearNoSpear_SpearLocationRequest")) { SendSpearLocationResponse(senderPeerId, new List<SpearLocationRecord>()); return; } referencePosition = package.ReadVector3(); } catch (Exception ex) { FearNoSpearPlugin.Log.LogWarning((object)("Failed to read spear location request RPC: " + ex.GetType().Name + ": " + ex.Message)); SendSpearLocationResponse(senderPeerId, new List<SpearLocationRecord>()); return; } if (!TryResolvePeerPlayerId(senderPeerId, out var playerId)) { SendSpearLocationResponse(senderPeerId, new List<SpearLocationRecord>()); return; } List<SpearLocationRecord> records = SpearServerRegistry.SelectBest(playerId, referencePosition); SendSpearLocationResponse(senderPeerId, records); } private static void RPC_SpearLocationResponse(long senderPeerId, ZPackage package) { if (!TryGetServerPeerId(out var serverPeerId) || senderPeerId != serverPeerId) { FearNoSpearPlugin.Log.LogWarning((object)$"Ignored spear location response from non-server peer {senderPeerId}."); return; } try { if (!TryReadHeader(package, "FearNoSpear_SpearLocationResponse")) { SpearLocator.PinLocalAfterEmptyServer(); return; } int num = package.ReadInt(); switch (num) { default: FearNoSpearPlugin.Log.LogWarning((object)$"Ignored spear location response with invalid record count {num}."); SpearLocator.PinLocalAfterEmptyServer(); break; case 0: SpearLocator.PinLocalAfterEmptyServer(); break; case 1: case 2: case 3: case 4: case 5: { List<SpearLocationRecord> list = new List<SpearLocationRecord>(num); for (int i = 0; i < num; i++) { list.Add(ReadRecord(package)); } SpearLocator.PinServerSpears(list); break; } } } catch (Exception ex) { FearNoSpearPlugin.Log.LogWarning((object)("Failed to read spear location response RPC: " + ex.GetType().Name + ": " + ex.Message)); } } private static void SendSpearLocationResponse(long targetPeerId, List<SpearLocationRecord> records) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown if (ZRoutedRpc.instance != null) { int num = Mathf.Min(records.Count, 5); ZPackage val = new ZPackage(); WriteHeader(val); val.Write(num); for (int i = 0; i < num; i++) { WriteRecord(val, records[i]); } ZRoutedRpc.instance.InvokeRoutedRPC(targetPeerId, "FearNoSpear_SpearLocationResponse", new object[1] { val }); } } private static bool TryResolvePeerPlayerId(long senderPeerId, out long playerId) { //IL_008f: Unknown result type (might be due to invalid IL or missing references) playerId = 0L; if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && ZRoutedRpc.instance != null && senderPeerId == ZRoutedRpc.instance.GetServerPeerID()) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { playerId = localPlayer.GetPlayerID(); if (playerId != 0L) { return true; } } } if (senderPeerId == 0L) { return false; } ZNetPeer val = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetPeer(senderPeerId) : null); if (val != null && !((ZDOID)(ref val.m_characterID)).IsNone()) { ZDO val2 = ((ZDOMan.instance != null) ? ZDOMan.instance.GetZDO(val.m_characterID) : null); if (val2 != null && val2.IsValid()) { playerId = val2.GetLong(ZDOVars.s_playerID, 0L); if (playerId != 0L) { return true; } } } foreach (Player allPlayer in Player.GetAllPlayers()) { if ((Object)(object)allPlayer == (Object)null) { continue; } ZNetView nview = ((Character)allPlayer).m_nview; if ((Object)(object)nview == (Object)null || !nview.IsValid()) { continue; } ZDO zDO = nview.GetZDO(); if (zDO != null && zDO.IsValid() && zDO.GetOwner() == senderPeerId) { playerId = allPlayer.GetPlayerID(); if (playerId != 0L) { return true; } } } playerId = 0L; return false; } private static void WriteHeader(ZPackage package) { package.Write(5); } private static bool TryReadHeader(ZPackage package, string rpcName) { int num = package.ReadInt(); if (num == 5) { return true; } FearNoSpearPlugin.Log.LogWarning((object)$"Ignoring incompatible {rpcName} payload: protocol={num}; expected={5}. Make sure server and client use the same FearNoSpear build."); return false; } private static void WriteRecord(ZPackage package, SpearLocationRecord record) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) package.Write(record.Key); package.Write(record.Position); } private static SpearLocationRecord ReadRecord(ZPackage package) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) return new SpearLocationRecord { Key = package.ReadString(), Position = package.ReadVector3() }; } } internal static class SpearPinManager { private sealed class SpearPinRecord { internal string Key = string.Empty; internal string Name = string.Empty; internal Vector3 Position; } private const string PinName = "Spear!"; private const float PinPickupRemoveRadius = 24f; private static readonly List<SpearPinRecord> ActivePins = new List<SpearPinRecord>(); internal static void Clear() { ActivePins.Clear(); } internal static int PinRecords(List<SpearLocationRecord> records, Action<string> showMessage) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) RemoveActivePinsFromMap(); int num = 0; int count = records.Count; for (int i = 0; i < count; i++) { SpearLocationRecord spearLocationRecord = records[i]; string text = ((count == 1) ? "Spear!" : $"Spear {i + 1}"); if (TryPinPosition(spearLocationRecord.Position, text, showMessage)) { num++; ActivePins.Add(new SpearPinRecord { Key = spearLocationRecord.Key, Name = text, Position = spearLocationRecord.Position }); } } return num; } internal static int RemoveForPickedSpear(string recordKey) { Minimap instance = Minimap.instance; if ((Object)(object)instance == (Object)null) { ActivePins.RemoveAll((SpearPinRecord pin) => MatchesPickedSpear(pin, recordKey)); return 0; } List<SpearPinRecord> list = ActivePins.Where((SpearPinRecord pin) => MatchesPickedSpear(pin, recordKey)).ToList(); if (list.Count == 0) { return 0; } int num = 0; foreach (SpearPinRecord item in list) { PinData val = FindMatchingMinimapPin(instance, item); if (val != null) { instance.RemovePin(val); num++; } } ActivePins.RemoveAll((SpearPinRecord pin) => MatchesPickedSpear(pin, recordKey)); return num; } private static bool MatchesPickedSpear(SpearPinRecord pin, string recordKey) { if (!string.IsNullOrEmpty(recordKey)) { return string.Equals(pin.Key, recordKey, StringComparison.Ordinal); } return false; } private static int RemoveActivePinsFromMap() { Minimap instance = Minimap.instance; if ((Object)(object)instance == (Object)null) { ActivePins.Clear(); return 0; } int num = 0; foreach (SpearPinRecord activePin in ActivePins) { PinData val = FindMatchingMinimapPin(instance, activePin); if (val != null) { instance.RemovePin(val); num++; } } ActivePins.Clear(); return num; } private static bool TryPinPosition(Vector3 position, string pinName, Action<string> showMessage) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) Minimap instance = Minimap.instance; if ((Object)(object)instance == (Object)null) { showMessage("No minimap is available yet."); return false; } instance.DiscoverLocation(position, (PinType)3, pinName, true); return true; } private static PinData? FindMatchingMinimapPin(Minimap minimap, SpearPinRecord trackedPin) { if (!(ReflectionCache.F_minimapPins?.GetValue(minimap) is List<PinData> source)) { return null; } return (from pin in source where pin != null && pin.m_save && (int)pin.m_type == 3 where string.Equals(pin.m_name, trackedPin.Name, StringComparison.Ordinal) where Vector3.Distance(pin.m_pos, trackedPin.Position) <= 24f orderby Vector3.SqrMagnitude(pin.m_pos - trackedPin.Position) select pin).FirstOrDefault(); } } internal static class SpearServerRegistry { private static List<string>? _spearItemDropPrefabNames; internal static void Clear() { _spearItemDropPrefabNames = null; } internal static List<SpearLocationRecord> SelectBest(long playerId, Vector3 referencePosition) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (playerId == 0L) { return new List<SpearLocationRecord>(); } return SelectWorldZdoSpearDrops(playerId, referencePosition); } private static List<SpearLocationRecord> SelectWorldZdoSpearDrops(long playerId, Vector3 referencePosition) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return new List<SpearLocationRecord>(); } if (ZDOMan.instance == null || (Object)(object)ZNetScene.instance == (Object)null) { return new List<SpearLocationRecord>(); } List<SpearLocationRecord> list = new List<SpearLocationRecord>(); foreach (string spearItemDropPrefabName in GetSpearItemDropPrefabNames()) { List<ZDO> list2 = new List<ZDO>(); int num = 0; while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative(spearItemDropPrefabName, list2, ref num)) { } foreach (ZDO item in list2) { if (item != null && item.IsValid() && SpearThrowerMetadata.ReadFromZdo(item) == playerId) { list.Add(new SpearLocationRecord { Key = SpearItemIdentity.BuildWorldDropRecordKey(item.m_uid), Position = item.GetPosition() }); } } } return list.OrderBy((SpearLocationRecord record) => Vector3.SqrMagnitude(record.Position - referencePosition)).Take(5).ToList(); } private static List<string> GetSpearItemDropPrefabNames() { if (_spearItemDropPrefabNames != null) { return _spearItemDropPrefabNames; } _spearItemDropPrefabNames = new List<string>(); if ((Object)(object)ZNetScene.instance == (Object)null) { return _spearItemDropPrefabNames; } foreach (string prefabName in ZNetScene.instance.GetPrefabNames()) { GameObject prefab = ZNetScene.instance.GetPrefab(prefabName); ItemDrop val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<ItemDrop>() : null); if (!((Object)(object)val == (Object)null) && val.m_itemData != null && SpearProjectileDetector.IsSpearItem(val.m_itemData)) { _spearItemDropPrefabNames.Add(prefabName); } } return _spearItemDropPrefabNames; } } internal sealed class SpearSafetyTracker : MonoBehaviour { private readonly struct NetworkRescueClaim { internal readonly ZDO? Zdo; internal NetworkRescueClaim(ZDO zdo) { Zdo = zdo; } } private sealed class PendingDropTag { internal ItemData SpawnItem; internal Vector3 Position; internal long ThrowerPlayerId; internal float ExpiresAt; } private const string ZdoRescueClaimKey = "FearNoSpear.Rescued"; private const float NearbyDropMatchRadius = 4f; private const float PendingDropTagSeconds = 2f; private const float PendingDropTagRetrySeconds = 0.1f; private static readonly List<PendingDropTag> PendingDropTags = new List<PendingDropTag>(); private static float _nextPendingDropTagScanAt; private Projectile? _projectile; private bool _normalHit; private bool _rescueAttempted; private bool _lastKnownOwner; private float _lastOwnerStateTime = float.NegativeInfinity; private float _lastTtl; private Vector3 _lastPosition; private Vector3 _lastVelocity; private long _throwerPlayerId; internal static SpearSafetyTracker? GetOrArmIfTracked(Projectile projectile) { if (!SpearProjectileDetector.IsTrackedSpearProjectile(projectile)) { return null; } SpearSafetyTracker component = ((Component)projectile).GetComponent<SpearSafetyTracker>(); if ((Object)(object)component != (Object)null) { return component; } component = ((Component)projectile).gameObject.AddComponent<SpearSafetyTracker>(); component.Arm(projectile); return component; } internal static void ClearPendingDropTags() { PendingDropTags.Clear(); _nextPendingDropTagScanAt = 0f; } internal static void UpdatePendingDropTags() { //IL_006d: Unknown result type (might be due to invalid IL or missing references) if (PendingDropTags.Count == 0 || Time.time < _nextPendingDropTagScanAt) { return; } _nextPendingDropTagScanAt = Time.time + 0.1f; ItemDrop[] loadedDrops = Object.FindObjectsByType<ItemDrop>((FindObjectsSortMode)0); for (int num = PendingDropTags.Count - 1; num >= 0; num--) { PendingDropTag pendingDropTag = PendingDropTags[num]; if (Time.time > pendingDropTag.ExpiresAt) { PendingDropTags.RemoveAt(num); } else { ItemDrop val = FindBestMatchingNearbyDrop(pendingDropTag.SpawnItem, pendingDropTag.Position, loadedDrops); if (!((Object)(object)val == (Object)null)) { SpearThrowerMetadata.TryWriteToDrop(val, pendingDropTag.ThrowerPlayerId); PendingDropTags.RemoveAt(num); } } } } internal void Arm(Projectile projectile) { _projectile = projectile; _normalHit = ReflectionCache.Get(ReflectionCache.F_didHit, projectile, fallback: false); _rescueAttempted = false; _throwerPlayerId = 0L; RefreshState(); EnsureThrowerMetadata(); ExtendInitialTtlIfNeeded(); } internal void MarkNormalHit() { if ((Object)(object)_projectile != (Object)null) { RefreshState(); TryCopyThrowerMetadataToNearbyDrop(); } _normalHit = true; } internal bool TryRescue(string reason) { //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) if (FearNoSpearPlugin.IsShuttingDown) { return false; } if (!FearNoSpearPlugin.Cfg.Enabled.Value) { return false; } if ((Object)(object)_projectile == (Object)null || _rescueAttempted) { return false; } if (_normalHit || ReflectionCache.Get(ReflectionCache.F_didHit, _projectile, fallback: false)) { return false; } if (!SpearProjectileDetector.IsTrackedSpearProjectile(_projectile)) { return false; } if (!MayThisClientRescue()) { return false; } ItemData val = ReflectionCache.Get<ItemData>(ReflectionCache.F_spawnItem, _projectile, null); if (val == null) { return false; } if (!TryClaimNetworkRescue(out var claim)) { return false; } _rescueAttempted = true; bool flag = false; try { Vector3 normal = ((((Vector3)(ref _lastVelocity)).sqrMagnitude > 0.001f) ? (-((Vector3)(ref _lastVelocity)).normalized) : Vector3.up); if (!TrySpawnOriginalItem(_projectile, val, normal, out ItemDrop drop)) { ReleaseNetworkRescueClaim(claim, "spawn failed"); FearNoSpearPlugin.Log.LogWarning((object)("Could not rescue spear; Valheim SpawnOnHit and ItemDrop fallback were unavailable or failed. reason=" + reason + "; " + SpearProjectileDetector.DescribeProjectile(_projectile))); return false; } flag = true; _normalHit = true; ReflectionCache.Set(ReflectionCache.F_didHit, _projectile, value: true); long num = EnsureThrowerMetadata(); if (num != 0L) { SpearThrowerMetadata.TryWriteToDrop(drop, num); } Vector3 position = ((Component)drop).transform.position; FearNoSpearPlugin.Log.LogInfo((object)$"Rescued thrown spear before projectile loss: reason={reason}; pos={position}; ttl={_lastTtl:0.00}; {SpearProjectileDetector.DescribeProjectile(_projectile)}"); return true; } catch (Exception arg) { if (!flag) { ReleaseNetworkRescueClaim(claim, "exception before spawn completed"); } FearNoSpearPlugin.Log.LogWarning((object)$"Exception while rescuing thrown spear: reason={reason}; ex={arg}"); return false; } } internal bool TryTtlRescueAndDestroyIfNeeded() { if (!FearNoSpearPlugin.Cfg.Enabled.Value) { return false; } if ((Object)(object)_projectile == (Object)null) { return false; } RefreshState(); float lastTtl = _lastTtl; float num = Mathf.Max(Time.fixedDeltaTime * 1.5f, FearNoSpearPlugin.Cfg.TtlRescueWindowSeconds.Value); if (lastTtl <= 0f || lastTtl > num) { return false; } if (!TryRescue("TTL expiry")) { return false; } if ((Object)(object)ZNetScene.instance != (Object)null) { ZNetScene.instance.Destroy(((Component)_projectile).gameObject); } else { Object.Destroy((Object)(object)((Component)_projectile).gameObject); } return true; } private void OnDestroy() { if (!FearNoSpearPlugin.IsShuttingDown) { TryRescue("OnDestroy fallback"); } } private void RefreshState() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_projectile == (Object)null)) { _lastPosition = ((Component)_projectile).transform.position; _lastVelocity = ReflectionCache.Get<Vector3>(ReflectionCache.F_vel, _projectile, Vector3.zero); _lastTtl = ReflectionCache.Get(ReflectionCache.F_ttl, _projectile, 0f); ZNetView nView = ReflectionCache.GetNView(_projectile); if ((Object)(object)nView != (Object)null && nView.IsValid()) { _lastKnownOwner = nView.IsOwner(); _lastOwnerStateTime = Time.time; } EnsureThrowerMetadata(); } } private void ExtendInitialTtlIfNeeded() { if (!((Object)(object)_projectile == (Object)null)) { float num = ReflectionCache.Get(ReflectionCache.F_ttl, _projectile, 0f); if (num > 0f && num < 60f) { ReflectionCache.Set(ReflectionCache.F_ttl, _projectile, 60f); _lastTtl = 60f; } } } private bool MayThisClientRescue() { if ((Object)(object)_projectile == (Object)null) { return false; } ZNetView nView = ReflectionCache.GetNView(_projectile); if ((Object)(object)nView != (Object)null && nView.IsValid()) { return nView.IsOwner(); } float num = Mathf.Max(0f, FearNoSpearPlugin.Cfg.LastKnownOwnerGraceSeconds.Value); float num2 = Time.time - _lastOwnerStateTime; if (FearNoSpearPlugin.Cfg.AllowLastKnownOwnerIfZNetViewInvalid.Value && _lastKnownOwner) { return num2 <= num; } return false; } private long EnsureThrowerMetadata() { if (_throwerPlayerId != 0L) { return _throwerPlayerId; } if ((Object)(object)_projectile == (Object)null) { return 0L; } _throwerPlayerId = SpearThrowerMetadata.ReadFromProjectile(_projectile); if (_throwerPlayerId != 0L) { return _throwerPlayerId; } if (SpearThrowerMetadata.TryWriteToProjectile(_projectile, out var playerId)) { _throwerPlayerId = playerId; } else if (SpearThrowerMetadata.TryResolveThrowerPlayerId(_projectile, out playerId)) { _throwerPlayerId = playerId; } return _throwerPlayerId; } private void TryCopyThrowerMetadataToNearbyDrop() { //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_projectile == (Object)null)) { ItemData val = ReflectionCache.Get<ItemData>(ReflectionCache.F_spawnItem, _projectile, null); if (val != null) { TryCopyThrowerMetadataToNearbyDrop(val, _lastPosition); } } } private void TryCopyThrowerMetadataToNearbyDrop(ItemData spawnItem, Vector3 position) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) long num = EnsureThrowerMetadata(); if (num != 0L) { ItemDrop val = FindBestMatchingNearbyDrop(spawnItem, position); if ((Object)(object)val == (Object)null) { QueuePendingDropTag(spawnItem, position, num); } else { SpearThrowerMetadata.TryWriteToDrop(val, num); } } } private static void QueuePendingDropTag(ItemData spawnItem, Vector3 position, long throwerPlayerId) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (throwerPlayerId != 0L) { PendingDropTags.Add(new PendingDropTag { SpawnItem = spawnItem, Position = position, ThrowerPlayerId = throwerPlayerId, ExpiresAt = Time.time + 2f }); } } private bool TryClaimNetworkRescue(out NetworkRescueClaim claim) { claim = default(NetworkRescueClaim); if ((Object)(object)_projectile == (Object)null) { return false; } ZNetView nView = ReflectionCache.GetNView(_projectile); if ((Object)(object)nView == (Object)null || !nView.IsValid()) { return true; } try { ZDO zDO = nView.GetZDO(); if (zDO == null || !zDO.IsValid()) { return true; } if (zDO.GetBool("FearNoSpear.Rescued", false)) { return false; } zDO.Set("FearNoSpear.Rescued", true); claim = new NetworkRescueClaim(zDO); return true; } catch { return true; } } private void ReleaseNetworkRescueClaim(NetworkRescueClaim claim, string reason) { if (claim.Zdo == null) { return; } try { claim.Zdo.Set("FearNoSpear.Rescued", false); } catch { FearNoSpearPlugin.Log.LogWarning((object)("Could not release failed spear rescue claim: reason=" + reason)); } } private static ItemDrop? FindBestMatchingNearbyDrop(ItemData spawnItem, Vector3 position, ItemDrop[]? loadedDrops = null) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) ItemDrop result = null; float num = float.PositiveInfinity; float num2 = 16f; ItemDrop[] array = loadedDrops ?? Object.FindObjectsByType<ItemDrop>((FindObjectsSortMode)0); foreach (ItemDrop val in array) { if (!((Object)(object)val == (Object)null) && val.m_itemData != null) { float num3 = Vector3.SqrMagnitude(((Component)val).transform.position - position); if (!(num3 > num2) && !(num3 >= num) && SpearItemIdentity.IsEquivalent(spawnItem, val.m_itemData)) { result = val; num = num3; } } } return result; } private bool TrySpawnOriginalItem(Projectile projectile, ItemData spawnItem, Vector3 normal, out ItemDrop drop) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) drop = null; if (!ReflectionCache.Get(ReflectionCache.F_groundHitOnly, projectile, fallback: false) && TrySpawnOriginalItemThroughValheimPath(projectile, normal)) { ItemDrop val = FindBestMatchingNearbyDrop(spawnItem, _lastPosition); if ((Object)(object)val != (Object)null) { drop = val; return true; } } return TryDropStoredItem(projectile, spawnItem, _lastPosition, out drop); } private static bool TrySpawnOriginalItemThroughValheimPath(Projectile projectile, Vector3 normal) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) MethodInfo m_spawnOnHit = ReflectionCache.M_spawnOnHit; if (m_spawnOnHit == null) { return false; } try { object[] parameters = BuildSpawnOnHitArguments(m_spawnOnHit, normal); m_spawnOnHit.Invoke(projectile, parameters); return true; } catch { return false; } } private static bool TryDropStoredItem(Projectile projectile, ItemData spawnItem, Vector3 position, out ItemDrop drop) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) drop = null; MethodInfo m_itemDropDropItem = ReflectionCache.M_itemDropDropItem; if (m_itemDropDropItem == null) { return false; } try { object? obj = m_itemDropDropItem.Invoke(null, new object[4] { spawnItem, 1, position, ((Component)projectile).transform.rotation }); ItemDrop val = (ItemDrop)((obj is ItemDrop) ? obj : null); if ((Object)(object)val == (Object)null) { return false; } drop = val; return true; } catch (TargetInvocationException ex) { FearNoSpearPlugin.Log.LogWarning((object)("ItemDrop fallback failed while rescuing spear: " + (ex.InnerException?.GetType().Name ?? ex.GetType().Name) + ": " + (ex.InnerException?.Message ?? ex.Message))); return false; } catch (Exception ex2) { FearNoSpearPlugin.Log.LogWarning((object)("ItemDrop fallback failed while rescuing spear: " + ex2.GetType().Name + ": " + ex2.Message)); return false; } } private static object?[] BuildSpawnOnHitArguments(MethodInfo method, Vector3 normal) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) ParameterInfo[] parameters = method.GetParameters(); object[] array = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { Type parameterType = parameters[i].ParameterType; if (parameterType == typeof(Vector3)) { array[i] = normal; } else if (!parameterType.IsValueType) { array[i] = null; } else if (parameterType == typeof(bool)) { array[i] = false; } else if (parameterType == typeof(int)) { array[i] = 0; } else if (parameterType == typeof(float)) { array[i] = 0f; } else { array[i] = Activator.CreateInstance(parameterType); } } return array; } } internal static class SpearThrowerMetadata { internal const string ThrowerPlayerIdKey = "FearNoSpear.ThrowerPlayerID"; internal static bool TryWriteToProjectile(Projectile projectile, out long playerId) { playerId = 0L; if ((Object)(object)projectile == (Object)null) { return false; } if (!TryResolveThrowerPlayerId(projectile, out playerId)) { return false; } return TryWriteToView(ReflectionCache.GetNView(projectile), playerId); } internal static bool TryWriteToDrop(ItemDrop drop, long playerId) { if ((Object)(object)drop == (Object)null || playerId == 0L) { return false; } return TryWriteToView(((Component)drop).GetComponent<ZNetView>(), playerId); } internal static long ReadFromDrop(ItemDrop drop) { if ((Object)(object)drop == (Object)null) { return 0L; } return ReadFromView(((Component)drop).GetComponent<ZNetView>()); } internal static long ReadFromProjectile(Projectile projectile) { if ((Object)(object)projectile == (Object)null) { return 0L; } return ReadFromView(ReflectionCache.GetNView(projectile)); } internal static long ReadFromZdo(ZDO? zdo) { if (zdo == null || !zdo.IsValid()) { return 0L; } return zdo.GetLong("FearNoSpear.ThrowerPlayerID", 0L); } internal static bool TryResolveThrowerPlayerId(Projectile projectile, out long playerId) { playerId = 0L; if ((Object)(object)projectile == (Object)null) { return false; } Character owner = projectile.m_owner; Player val = (Player)(object)((owner is Player) ? owner : null); if ((Object)(object)val == (Object)null) { return false; } playerId = val.GetPlayerID(); return playerId != 0; } private static long ReadFromView(ZNetView? nview) { if ((Object)(object)nview == (Object)null || !nview.IsValid()) { return 0L; } return ReadFromZdo(nview.GetZDO()); } private static bool TryWriteToView(ZNetView? nview, long playerId) { if ((Object)(object)nview == (Object)null || !nview.IsValid() || playerId == 0L) { return false; } if (!CanWrite(nview)) { return false; } ZDO zDO = nview.GetZDO(); if (zDO == null || !zDO.IsValid()) { return false; } if (zDO.GetLong("FearNoSpear.ThrowerPlayerID", 0L) == playerId) { return true; } zDO.Set("FearNoSpear.ThrowerPlayerID", playerId); return true; } private static bool CanWrite(ZNetView nview) { if (!((Object)(object)ZNet.instance != (Object)null) || !ZNet.instance.IsServer()) { return nview.IsOwner(); } return true; } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry<T> SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } internal abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] internal class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List<ZNetPeer> peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable<bool> waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid