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.4")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.4.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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.4")] 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.4"; public const string PluginVersion = "1.0.4"; internal static ManualLogSource Log = null; internal static FearNoSpearConfig Cfg = null; private static readonly ConfigSync Sync = new ConfigSync("sighsorry.FearNoSpear") { DisplayName = "FearNoSpear", CurrentVersion = "1.0.4", MinimumRequiredVersion = "1.0.4" }; private static ConfigEntry _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(_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.4 loaded"); } private void OnDestroy() { IsShuttingDown = true; SaveWithRespectToConfigSet(); _watcher?.Dispose(); Harmony? harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private void OnApplicationQuit() { IsShuttingDown = true; } internal ConfigEntry BindConfig(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 val = ((BaseUnityPlugin)this).Config.Bind(group, name, value, new ConfigDescription(description + text, (AcceptableValueBase)null, Array.Empty())); Sync.AddConfigEntry(val).SynchronizedConfig = synchronizedSetting; return val; } internal ConfigEntry BindConfig(string group, string name, T value, string description, AcceptableValueBase acceptableValues, bool synchronizedSetting = true) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown string text = (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"); ConfigEntry val = ((BaseUnityPlugin)this).Config.Bind(group, name, value, new ConfigDescription(description + text, acceptableValues, Array.Empty())); Sync.AddConfigEntry(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 Enabled; internal static readonly bool NameFallback = true; internal static readonly bool TrackAllRespawnItemProjectilesForDebug = false; internal static readonly bool ExtendInitialTtl = true; internal static readonly bool RescueBeforeTtlExpiry = true; internal static readonly bool RescueOnUnexpectedDestroy = true; internal static readonly bool UseItemDropFallback = true; internal static readonly bool OnlyOwnerMayRescue = true; internal static readonly bool UseZdoClaimFlag = true; internal const float MinimumInitialTtlSeconds = 60f; internal const int MaxPinsPerCommand = 5; internal static readonly bool Verbose = false; internal readonly ConfigEntry TtlRescueWindowSeconds; internal readonly ConfigEntry AllowLastKnownOwnerIfZNetViewInvalid; internal readonly ConfigEntry LastKnownOwnerGraceSeconds; internal readonly ConfigEntry ChatCommand; internal readonly ConfigEntry 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 the latest known tracked spear location on the minimap. 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 int GetMaxPinsPerCommand() { return 5; } } 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 MethodInfo? M_zNetViewGetZdo; internal static MethodInfo? M_zdoGetBool; internal static MethodInfo? M_zdoSetBool; 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); M_zNetViewGetZdo = AccessTools.Method(typeof(ZNetView), "GetZDO", (Type[])null, (Type[])null); M_zdoGetBool = AccessTools.Method(typeof(ZDO), "GetBool", new Type[2] { typeof(string), typeof(bool) }, (Type[])null); M_zdoSetBool = AccessTools.Method(typeof(ZDO), "Set", new Type[2] { typeof(string), typeof(bool) }, (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_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(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(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(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(ReflectionCache.F_spawnItem, projectile, null) != null; } internal static bool IsTrackedSpearProjectile(Projectile projectile) { if (!IsRecoverableProjectile(projectile)) { return false; } if (FearNoSpearConfig.TrackAllRespawnItemProjectilesForDebug) { return true; } ItemData item = ReflectionCache.Get(ReflectionCache.F_spawnItem, projectile, null); ItemData item2 = ReflectionCache.Get(ReflectionCache.F_weapon, projectile, null); if (IsSpearItem(item) || IsSpearItem(item2)) { return true; } if (!FearNoSpearConfig.NameFallback) { return false; } return ContainsSpearToken(((Object)projectile).name ?? string.Empty); } internal static bool IsSpearItem(ItemData? item) { if (item?.m_shared == null) { return false; } string a = ((object)(SkillType)(ref item.m_shared.m_skillType)).ToString(); if (string.Equals(a, "Spears", StringComparison.OrdinalIgnoreCase) || string.Equals(a, "Spear", StringComparison.OrdinalIgnoreCase)) { return true; } if (!FearNoSpearConfig.NameFallback) { return false; } return ContainsSpearToken(item.m_shared.m_name); } private static bool ContainsSpearToken(string? value) { if (value == null || value.Length == 0) { return false; } if (value.IndexOf("spear", StringComparison.OrdinalIgnoreCase) < 0) { return value.IndexOf("$item_spear", StringComparison.OrdinalIgnoreCase) >= 0; } return true; } internal static string DescribeProjectile(Projectile projectile) { ItemData obj = ReflectionCache.Get(ReflectionCache.F_spawnItem, projectile, null); ItemData val = ReflectionCache.Get(ReflectionCache.F_weapon, projectile, null); string text = obj?.m_shared?.m_name ?? ""; string text2 = val?.m_shared?.m_name ?? ""; object obj2; if (obj == null) { obj2 = null; } else { SharedData shared = obj.m_shared; obj2 = ((shared != null) ? ((object)(SkillType)(ref shared.m_skillType)).ToString() : null); } if (obj2 == null) { if (val == null) { obj2 = null; } else { SharedData shared2 = val.m_shared; obj2 = ((shared2 != null) ? ((object)(SkillType)(ref shared2.m_skillType)).ToString() : null); } if (obj2 == null) { obj2 = ""; } } string text3 = (string)obj2; 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, "Projectile.Setup"); } } } [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.GetOrArmIfTracked(__instance, "Projectile.FixedUpdate"); 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 sealed class PickedSpearState { internal string RecordKey = string.Empty; internal string ItemKey = string.Empty; internal Vector3 Position; } private static void Prefix(Humanoid __instance, GameObject go, out PickedSpearState? __state) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) __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(); if (!((Object)(object)component == (Object)null) && component.m_itemData != null && SpearProjectileDetector.IsSpearItem(component.m_itemData)) { string itemKey = SpearItemIdentity.BuildLocatorKey(component.m_itemData); __state = new PickedSpearState { ItemKey = itemKey, RecordKey = SpearItemIdentity.BuildDropRecordKey(component, itemKey), Position = go.transform.position }; } } } private static void Postfix(bool __result, PickedSpearState? __state) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (__result && __state != null) { SpearLocator.MarkSpearPickedUp(__state.RecordKey, __state.ItemKey, __state.Position); } } } [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() { 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()?.MarkNormalHit("Projectile.OnHit"); } } } [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 || !FearNoSpearConfig.RescueOnUnexpectedDestroy || (Object)(object)__0 == (Object)null) { return; } SpearSafetyTracker spearSafetyTracker = __0.GetComponent(); if ((Object)(object)spearSafetyTracker == (Object)null) { Projectile component = __0.GetComponent(); if ((Object)(object)component != (Object)null) { spearSafetyTracker = SpearSafetyTracker.GetOrArmIfTracked(component, "ZNetScene.Destroy"); } } spearSafetyTracker?.TryRescue("ZNetScene.Destroy before hit"); } } internal static class DeathPinCleaner { private sealed class PendingDeath { internal long PlayerId; internal Vector3 Position; internal float StartedAt; internal bool TombstoneCreated; } private const float RecentDeathSeconds = 8f; private const float DeathPinRemoveRadius = 32f; private static readonly Dictionary TombstoneDeathPositions = new Dictionary(); private static readonly HashSet CleanedTombstones = new HashSet(); 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 CompleteLocalDeath(Player player) { //IL_0039: 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)) { PendingDeath pendingDeath = _pendingDeath; _pendingDeath = null; if (pendingDeath != null && !pendingDeath.TombstoneCreated) { 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_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: 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 value = GetTombstonePinPosition(tombstone); PendingDeath pendingDeath = _pendingDeath; if (pendingDeath != null && pendingDeath.PlayerId == owner && Time.time - pendingDeath.StartedAt <= 8f) { pendingDeath.TombstoneCreated = true; value = pendingDeath.Position; } TombstoneDeathPositions[instanceID] = value; } } 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)) { RemoveNearestDeathPin(TombstoneDeathPositions.TryGetValue(instanceID, out var value) ? value : GetTombstonePinPosition(tombstone)); } } } 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(); 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 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); } private static void Postfix(Player __instance) { DeathPinCleaner.CompleteLocalDeath(__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(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(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 BuildLocatorKey(ItemData item) { string value = (((Object)(object)item.m_dropPrefab != (Object)null) ? ((Object)item.m_dropPrefab).name : string.Empty); string value2 = item.m_shared?.m_name ?? string.Empty; List list = new List { Escape(value), Escape(value2), item.m_quality.ToString(), item.m_variant.ToString(), item.m_worldLevel.ToString(), item.m_crafterID.ToString(), Escape(item.m_crafterName) }; if (item.m_customData != null) { foreach (KeyValuePair item2 in item.m_customData.OrderBy((KeyValuePair pair) => pair.Key)) { list.Add(Escape(item2.Key) + "=" + Escape(item2.Value)); } } return string.Join("|", list); } internal static string BuildLocatorKey(string prefabName, ItemData prefabItem, ZDO zdo) { string value = prefabItem.m_shared?.m_name ?? string.Empty; int @int = zdo.GetInt(ZDOVars.s_quality, prefabItem.m_quality); int int2 = zdo.GetInt(ZDOVars.s_variant, prefabItem.m_variant); int int3 = zdo.GetInt(ZDOVars.s_worldLevel, prefabItem.m_worldLevel); long @long = zdo.GetLong(ZDOVars.s_crafterID, prefabItem.m_crafterID); string @string = zdo.GetString(ZDOVars.s_crafterName, prefabItem.m_crafterName); List list = new List { Escape(prefabName), Escape(value), @int.ToString(), int2.ToString(), int3.ToString(), @long.ToString(), Escape(@string) }; int int4 = zdo.GetInt(ZDOVars.s_dataCount, 0); Dictionary dictionary = new Dictionary(); for (int i = 0; i < int4; i++) { string string2 = zdo.GetString($"data_{i}", ""); if (!string.IsNullOrEmpty(string2)) { dictionary[string2] = zdo.GetString($"data__{i}", ""); } } foreach (KeyValuePair item in dictionary.OrderBy((KeyValuePair pair) => pair.Key)) { list.Add(Escape(item.Key) + "=" + Escape(item.Value)); } return string.Join("|", list); } internal static string BuildDropRecordKey(ItemDrop drop, string itemKey) { string text = TryGetZdoKey(((Component)drop).GetComponent()); if (text != null && text.Length > 0) { return BuildDropRecordKey(text); } return $"{itemKey}#drop-local:{((Object)drop).GetInstanceID()}"; } internal static string BuildWorldDropRecordKey(ZDOID zdoId) { return BuildDropRecordKey(((object)(ZDOID)(ref zdoId)).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)(ZDOID)(ref zDO.m_uid)).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 string Escape(string? value) { return (value ?? string.Empty).Replace("\\", "\\\\").Replace("|", "\\p").Replace("=", "\\e"); } private static bool DictionariesEqual(Dictionary? expected, Dictionary? 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 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 { internal const string LoadedDropSource = "loaded ItemDrop"; internal const string WorldZdoDropSource = "world ZDO spear drop"; private const int MaxRecords = 12; private const float ServerRequestTimeoutSeconds = 2f; private static readonly SpearRecordStore Records = new SpearRecordStore(12); private static float _serverRequestFallbackAt = float.NegativeInfinity; internal static void Clear() { Records.Clear(); 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; } RefreshLoadedSpearDrops(); if (SpearNetwork.RequestServerSpearLocation(localPlayer)) { _serverRequestFallbackAt = Time.time + 2f; ShowMessage("Requesting spear location from server..."); } else { PinLocalKnownSpears("No spear drop location found.", "Pinned local spear location"); } } internal static void PinServerSpears(List records) { ClearPendingServerRequest(); if ((Object)(object)Player.m_localPlayer == (Object)null) { FearNoSpearPlugin.Log.LogInfo((object)"Received a spear location from the server, but no local player exists."); return; } MergeServerRecords(records); PinLocalKnownSpears("No spear drop location found on server or client.", "Pinned spear location"); } internal static void MarkSpearPickedUp(string recordKey, string itemKey, Vector3 pickupPosition) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) if (!string.IsNullOrEmpty(recordKey)) { int num = SpearPinManager.RemoveForPickedSpear(recordKey, pickupPosition); int num2 = RemoveRecordsForPickedSpear(recordKey); if (FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogInfo((object)$"Cleared picked spear locator state: recordKey={recordKey}; itemKey={itemKey}; removedPins={num}; removedRecords={num2}; pos={pickupPosition}"); } } } internal static void PinLocalAfterEmptyServer() { ClearPendingServerRequest(); PinLocalKnownSpears("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(); PinLocalKnownSpears("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 PinLocalKnownSpears(string missingMessage, string pinnedPrefix) { return PinRecords(Records.SelectBest(FearNoSpearPlugin.Cfg.GetMaxPinsPerCommand()), missingMessage, pinnedPrefix); } private static bool PinRecords(List 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 void RefreshLoadedSpearDrops() { //IL_0082: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } long playerID = localPlayer.GetPlayerID(); if (playerID == 0L) { return; } ItemDrop[] array = Object.FindObjectsByType((FindObjectsSortMode)0); foreach (ItemDrop val in array) { if (!((Object)(object)val == (Object)null) && val.m_itemData != null && SpearProjectileDetector.IsSpearItem(val.m_itemData)) { string itemKey = SpearItemIdentity.BuildLocatorKey(val.m_itemData); string recordKey = SpearItemIdentity.BuildDropRecordKey(val, itemKey); long num = SpearThrowerMetadata.ReadFromDrop(val); if (num != 0L && num == playerID) { Record(recordKey, itemKey, ((Component)val).transform.position, "loaded ItemDrop"); } } } } private static SpearLocationRecord Record(string recordKey, string itemKey, Vector3 position, string source, float lastUpdated = -1f) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Records.Record(recordKey, itemKey, position, source, lastUpdated); } private static void MergeServerRecords(List records) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) foreach (SpearLocationRecord record in records) { if (!string.IsNullOrEmpty(record.Key)) { string itemKey = (string.IsNullOrEmpty(record.ItemKey) ? record.Key : record.ItemKey); Record(record.Key, itemKey, record.Position, record.Source, record.LastUpdated); } } } private static int RemoveRecordsForPickedSpear(string recordKey) { return Records.RemovePicked(recordKey); } 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 static class SpearLocatorProtocol { private const int ProtocolVersion = 3; internal static void WriteHeader(ZPackage package) { package.Write(3); } internal static bool TryReadHeader(ZPackage package, string rpcName) { int num = package.ReadInt(); if (num == 3) { return true; } FearNoSpearPlugin.Log.LogWarning((object)$"Ignoring incompatible {rpcName} payload: protocol={num}; expected={3}. Make sure server and client use the same FearNoSpear build."); return false; } internal static void WriteRecord(ZPackage package, SpearLocationRecord record) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) package.Write(record.Key); package.Write(record.ItemKey); package.Write(record.Position); package.Write(record.Source); package.Write(Mathf.Max(0f, Time.time - record.LastUpdated)); } internal static SpearLocationRecord ReadRecord(ZPackage package) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) string key = package.ReadString(); string itemKey = package.ReadString(); Vector3 position = package.ReadVector3(); string source = package.ReadString(); float num = package.ReadSingle(); return new SpearLocationRecord { Key = key, ItemKey = itemKey, Position = position, Source = source, LastUpdated = Time.time - Mathf.Max(0f, num) }; } } internal static class SpearNetwork { private const string RequestRpcName = "FearNoSpear_SpearLocationRequest"; private const string ResponseRpcName = "FearNoSpear_SpearLocationResponse"; internal static void ClearSession() { SpearOwnership.ClearPeerMappings(); SpearServerRegistry.Clear(); } internal static void RegisterRpcs() { ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null) { TryRegister(instance, "FearNoSpear_SpearLocationRequest", RPC_RequestSpearLocation); TryRegister(instance, "FearNoSpear_SpearLocationResponse", RPC_SpearLocationResponse); } } internal static bool RequestServerSpearLocation(Player localPlayer) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown //IL_004c: 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; } long playerID = localPlayer.GetPlayerID(); if (playerID == 0L) { return false; } ZPackage val = new ZPackage(); SpearLocatorProtocol.WriteHeader(val); val.Write(playerID); val.Write(FearNoSpearPlugin.Cfg.GetMaxPinsPerCommand()); val.Write(((Component)localPlayer).transform.position); ZRoutedRpc.instance.InvokeRoutedRPC(serverPeerId, "FearNoSpear_SpearLocationRequest", new object[1] { val }); return true; } private static void TryRegister(ZRoutedRpc rpc, string name, Action handler) { try { rpc.Register(name, handler); } catch (ArgumentException) { } } 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 && !ZNet.instance.IsServer()) { return false; } return true; } private static void RPC_RequestSpearLocation(long senderPeerId, ZPackage package) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_00f8: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } long num = 0L; int maxPinsPerCommand = FearNoSpearPlugin.Cfg.GetMaxPinsPerCommand(); Vector3 zero = Vector3.zero; try { if (!SpearLocatorProtocol.TryReadHeader(package, "FearNoSpear_SpearLocationRequest")) { SendSpearLocationResponse(senderPeerId, new List()); return; } num = package.ReadLong(); maxPinsPerCommand = package.ReadInt(); zero = 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()); return; } if (!SpearOwnership.TryResolveRequestedPeerPlayerId(senderPeerId, num, out var playerId)) { if (FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)$"Ignoring spear location request from unmapped peer={senderPeerId}; requestedPlayerId={num}"); } SendSpearLocationResponse(senderPeerId, new List()); } else { int maxRecords = Mathf.Clamp(Mathf.Min(maxPinsPerCommand, FearNoSpearPlugin.Cfg.GetMaxPinsPerCommand()), 1, 20); List records = SpearServerRegistry.SelectBest(playerId, maxRecords, zero); SendSpearLocationResponse(senderPeerId, records); } } private static void RPC_SpearLocationResponse(long senderPeerId, ZPackage package) { try { if (!SpearLocatorProtocol.TryReadHeader(package, "FearNoSpear_SpearLocationResponse")) { SpearLocator.PinLocalAfterEmptyServer(); return; } int num = package.ReadInt(); if (num <= 0) { SpearLocator.PinLocalAfterEmptyServer(); return; } List list = new List(); for (int i = 0; i < num; i++) { list.Add(SpearLocatorProtocol.ReadRecord(package)); } SpearLocator.PinServerSpears(list); } 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 records) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown if (ZRoutedRpc.instance == null) { return; } ZPackage val = new ZPackage(); SpearLocatorProtocol.WriteHeader(val); val.Write(records.Count); foreach (SpearLocationRecord record in records) { SpearLocatorProtocol.WriteRecord(val, record); } ZRoutedRpc.instance.InvokeRoutedRPC(targetPeerId, "FearNoSpear_SpearLocationResponse", new object[1] { val }); } } internal static class SpearOwnership { private static readonly Dictionary PeerPlayerIds = new Dictionary(); internal static void ClearPeerMappings() { PeerPlayerIds.Clear(); } internal static bool TryResolveRequestedPeerPlayerId(long senderPeerId, long requestedPlayerId, out long playerId) { if (!TryResolveAuthoritativePlayerId(senderPeerId, requestedPlayerId, out playerId)) { return TryResolveMappedPlayerId(senderPeerId, out playerId); } return true; } private static bool TryResolveMappedPlayerId(long senderPeerId, out long playerId) { if (PeerPlayerIds.TryGetValue(senderPeerId, out var value) && value != 0L) { playerId = value; return true; } playerId = 0L; return false; } private static bool TryResolveAuthoritativePlayerId(long senderPeerId, long reportedPlayerId, out long playerId) { playerId = 0L; if (senderPeerId == 0L) { return false; } if (TryResolvePeerCharacterPlayerId(senderPeerId, reportedPlayerId, out playerId)) { 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) { continue; } long playerID = allPlayer.GetPlayerID(); if (playerID != 0L) { if (reportedPlayerId != 0L && reportedPlayerId != playerID && FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)$"Ignoring mismatched client player id: peer={senderPeerId}; reported={reportedPlayerId}; resolved={playerID}"); } playerId = playerID; PeerPlayerIds[senderPeerId] = playerId; return true; } } return false; } private static bool TryResolvePeerCharacterPlayerId(long senderPeerId, long reportedPlayerId, out long playerId) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) playerId = 0L; ZNetPeer val = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetPeer(senderPeerId) : null); if (val == null || ((ZDOID)(ref val.m_characterID)).IsNone()) { return false; } ZDO val2 = ((ZDOMan.instance != null) ? ZDOMan.instance.GetZDO(val.m_characterID) : null); if (val2 == null || !val2.IsValid()) { return false; } long @long = val2.GetLong(ZDOVars.s_playerID, 0L); if (@long == 0L) { return false; } if (reportedPlayerId != 0L && reportedPlayerId != @long && FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)$"Ignoring mismatched client player id from peer character: peer={senderPeerId}; reported={reportedPlayerId}; resolved={@long}"); } playerId = @long; PeerPlayerIds[senderPeerId] = playerId; return true; } } 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 ActivePins = new List(); internal static void Clear() { ActivePins.Clear(); } internal static int PinRecords(List records, Action showMessage) { //IL_003b: 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 pinName = ((count == 1) ? "Spear!" : $"Spear {i + 1}"); if (TryPinPosition(spearLocationRecord.Position, pinName, spearLocationRecord.Source, showMessage)) { num++; RememberPin(spearLocationRecord, pinName); } } return num; } internal static int RemoveForPickedSpear(string recordKey, Vector3 pickupPosition) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) string recordKey2 = recordKey; Minimap instance = Minimap.instance; if ((Object)(object)instance == (Object)null) { ActivePins.RemoveAll((SpearPinRecord pin) => MatchesPickedSpear(pin, recordKey2)); return 0; } List list = (from pin in ActivePins where MatchesPickedSpear(pin, recordKey2) orderby Vector3.SqrMagnitude(pin.Position - pickupPosition) select pin).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, recordKey2)); 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 void RememberPin(SpearLocationRecord record, string pinName) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) SpearLocationRecord record2 = record; string pinName2 = pinName; ActivePins.RemoveAll((SpearPinRecord pin) => string.Equals(pin.Key, record2.Key, StringComparison.Ordinal) && string.Equals(pin.Name, pinName2, StringComparison.Ordinal)); ActivePins.Add(new SpearPinRecord { Key = record2.Key, Name = pinName2, Position = record2.Position }); } private static bool TryPinPosition(Vector3 position, string pinName, string source, Action showMessage) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { FearNoSpearPlugin.Log.LogInfo((object)"Could not pin spear location because no local player exists."); return false; } 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); if (FearNoSpearConfig.Verbose) { float num = Vector3.Distance(((Component)localPlayer).transform.position, position); FearNoSpearPlugin.Log.LogInfo((object)$"Pinned known spear from !myspear: source={source}; pos={position}; distance={num:0.0}m"); } return true; } private static PinData? FindMatchingMinimapPin(Minimap minimap, SpearPinRecord trackedPin) { SpearPinRecord trackedPin2 = trackedPin; if (!(ReflectionCache.F_minimapPins?.GetValue(minimap) is List 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, trackedPin2.Name, StringComparison.Ordinal) where Vector3.Distance(pin.m_pos, trackedPin2.Position) <= 24f orderby Vector3.SqrMagnitude(pin.m_pos - trackedPin2.Position) select pin).FirstOrDefault(); } } internal sealed class SpearLocationRecord { internal string Key = string.Empty; internal string ItemKey = string.Empty; internal Vector3 Position; internal float LastUpdated; internal string Source = string.Empty; } internal sealed class SpearRecordStore { private readonly int _maxRecords; private readonly List _records = new List(); internal SpearRecordStore(int maxRecords) { _maxRecords = maxRecords; } internal void Clear() { _records.Clear(); } internal List SelectBest(int maxRecords) { if (_records.Count == 0) { return new List(); } return _records.OrderByDescending((SpearLocationRecord record) => record.LastUpdated).Take(Mathf.Clamp(maxRecords, 1, _maxRecords)).ToList(); } internal SpearLocationRecord Record(string key, string itemKey, Vector3 position, string source, float lastUpdated = -1f) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0089: 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_0059: Unknown result type (might be due to invalid IL or missing references) string key2 = key; float num = ((lastUpdated >= 0f) ? lastUpdated : Time.time); SpearLocationRecord spearLocationRecord = _records.FirstOrDefault((SpearLocationRecord record) => record.Key == key2); if (spearLocationRecord != null) { if (num >= spearLocationRecord.LastUpdated) { spearLocationRecord.Key = key2; spearLocationRecord.ItemKey = itemKey; spearLocationRecord.Position = position; spearLocationRecord.LastUpdated = num; spearLocationRecord.Source = source; } return spearLocationRecord; } SpearLocationRecord spearLocationRecord2 = new SpearLocationRecord { Key = key2, ItemKey = itemKey, Position = position, LastUpdated = num, Source = source }; _records.Add(spearLocationRecord2); Trim(); return spearLocationRecord2; } internal int RemovePicked(string recordKey) { string recordKey2 = recordKey; if (string.IsNullOrEmpty(recordKey2)) { return 0; } SpearLocationRecord spearLocationRecord = _records.FirstOrDefault((SpearLocationRecord record) => record.Key == recordKey2); if (spearLocationRecord == null) { return 0; } _records.Remove(spearLocationRecord); return 1; } private void Trim() { while (_records.Count > _maxRecords) { SpearLocationRecord item = _records.OrderBy((SpearLocationRecord record) => record.LastUpdated).First(); _records.Remove(item); } } } internal static class SpearServerRegistry { private const int MaxRecordsPerPlayer = 20; private static List? _spearItemDropPrefabNames; internal static void Clear() { _spearItemDropPrefabNames = null; } internal static List SelectBest(long playerId, int maxRecords, Vector3 referencePosition) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (playerId == 0L) { return new List(); } int limit = Mathf.Clamp(maxRecords, 1, 20); return SelectWorldZdoSpearDrops(playerId, limit, referencePosition); } private static List SelectWorldZdoSpearDrops(long playerId, int limit, 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_0100: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011f: 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(); } if (ZDOMan.instance == null || (Object)(object)ZNetScene.instance == (Object)null) { return new List(); } List list = new List(); foreach (string spearItemDropPrefabName in GetSpearItemDropPrefabNames()) { GameObject prefab = ZNetScene.instance.GetPrefab(spearItemDropPrefabName); ItemDrop val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent() : null); if ((Object)(object)val == (Object)null || val.m_itemData == null) { continue; } List list2 = new List(); 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) { string itemKey = SpearItemIdentity.BuildLocatorKey(spearItemDropPrefabName, val.m_itemData, item); list.Add(new SpearLocationRecord { Key = SpearItemIdentity.BuildWorldDropRecordKey(item.m_uid), ItemKey = itemKey, Position = item.GetPosition(), LastUpdated = Time.time, Source = "world ZDO spear drop" }); } } } return list.OrderBy((SpearLocationRecord record) => Vector3.SqrMagnitude(record.Position - referencePosition)).Take(limit).ToList(); } private static List GetSpearItemDropPrefabNames() { if (_spearItemDropPrefabNames != null) { return _spearItemDropPrefabNames; } _spearItemDropPrefabNames = new List(); 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() : 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 object? Zdo; internal readonly bool Claimed; internal NetworkRescueClaim(object zdo) { Zdo = zdo; Claimed = true; } } private sealed class PendingDropTag { internal ItemData SpawnItem; internal Vector3 Position; internal long ThrowerPlayerId; internal string Reason = string.Empty; internal float ExpiresAt; } private const string ZdoRescueClaimKey = "FearNoSpear.Rescued"; private const float NearbyDuplicateCheckRadius = 4f; private const float PendingDropTagSeconds = 2f; private static readonly List PendingDropTags = new List(); private Projectile? _projectile; private bool _armed; 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 ArmOrRefresh(Projectile projectile) { SpearSafetyTracker spearSafetyTracker = ((Component)projectile).GetComponent(); if ((Object)(object)spearSafetyTracker == (Object)null) { spearSafetyTracker = ((Component)projectile).gameObject.AddComponent(); } spearSafetyTracker.Arm(projectile); return spearSafetyTracker; } internal static SpearSafetyTracker? GetOrArmIfTracked(Projectile projectile, string source) { if (!SpearProjectileDetector.IsTrackedSpearProjectile(projectile)) { return null; } SpearSafetyTracker component = ((Component)projectile).GetComponent(); if ((Object)(object)component != (Object)null) { return component; } component = ((Component)projectile).gameObject.AddComponent(); component.Arm(projectile); if (FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)("Lazy-armed thrown spear tracker from " + source + ": " + SpearProjectileDetector.DescribeProjectile(projectile))); } return component; } internal static void ClearPendingDropTags() { PendingDropTags.Clear(); } internal static void UpdatePendingDropTags() { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) if (PendingDropTags.Count == 0) { return; } 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); if (!((Object)(object)val == (Object)null)) { if (SpearThrowerMetadata.TryWriteToDrop(val, pendingDropTag.ThrowerPlayerId) && FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)$"Tagged delayed spear drop with thrower metadata after {pendingDropTag.Reason}: playerId={pendingDropTag.ThrowerPlayerId}; drop={((Object)val).name}; pos={((Component)val).transform.position}"); } PendingDropTags.RemoveAt(num); } } } } internal void Arm(Projectile projectile) { _projectile = projectile; _armed = true; _normalHit = ReflectionCache.Get(ReflectionCache.F_didHit, projectile, fallback: false); _rescueAttempted = false; _throwerPlayerId = 0L; RefreshState(); EnsureThrowerMetadata(); ExtendInitialTtlIfNeeded(); if (FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogInfo((object)$"Tracked thrown spear: {SpearProjectileDetector.DescribeProjectile(projectile)} ttl={_lastTtl:0.00} owner={_lastKnownOwner}"); } } internal void MarkNormalHit(string source) { if ((Object)(object)_projectile != (Object)null) { RefreshState(); TryCopyThrowerMetadataToNearbyDrop("normal hit"); } _normalHit = true; if (FearNoSpearConfig.Verbose && (Object)(object)_projectile != (Object)null) { FearNoSpearPlugin.Log.LogInfo((object)("Spear projectile normal hit observed (" + source + "): " + ((Object)_projectile).name)); } } internal bool TryRescue(string reason) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_0197: 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 (!_armed || (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(ReflectionCache.F_spawnItem, _projectile, null); if (val == null) { return false; } if (!TryClaimNetworkRescue(out var claim)) { return false; } _rescueAttempted = true; bool flag = false; try { if (TryUseExistingNearbyDrop(val, _lastPosition, EnsureThrowerMetadata(), "pre-rescue", out var _)) { flag = true; _normalHit = true; ReflectionCache.Set(ReflectionCache.F_didHit, _projectile, value: true); return true; } Vector3 normal = ((((Vector3)(ref _lastVelocity)).sqrMagnitude > 0.001f) ? (-((Vector3)(ref _lastVelocity)).normalized) : Vector3.up); if (!TrySpawnOriginalItem(_projectile, val, normal, reason, out var dropPosition2)) { 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); TryCopyThrowerMetadataToNearbyDrop(val, dropPosition2, "rescue"); RemoveNearbyDuplicateDrops(val, dropPosition2); FearNoSpearPlugin.Log.LogInfo((object)$"Rescued thrown spear before projectile loss: reason={reason}; pos={dropPosition2}; 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 (!FearNoSpearConfig.RescueBeforeTtlExpiry) { return false; } if (!_armed || (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 && FearNoSpearConfig.RescueOnUnexpectedDestroy) { 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(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 || !FearNoSpearConfig.ExtendInitialTtl) { return; } float num = Mathf.Max(0f, 60f); if (num <= 0f) { return; } float num2 = ReflectionCache.Get(ReflectionCache.F_ttl, _projectile, 0f); if (num2 > 0f && num2 < num) { ReflectionCache.Set(ReflectionCache.F_ttl, _projectile, num); _lastTtl = num; if (FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogInfo((object)$"Extended thrown spear TTL {num2:0.00}s -> {num:0.00}s: {SpearProjectileDetector.DescribeProjectile(_projectile)}"); } } } private bool MayThisClientRescue() { if ((Object)(object)_projectile == (Object)null) { return false; } if (!FearNoSpearConfig.OnlyOwnerMayRescue) { return true; } ZNetView nView = ReflectionCache.GetNView(_projectile); if ((Object)(object)nView != (Object)null && nView.IsValid()) { bool num = nView.IsOwner(); if (!num && FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)("Skipped spear rescue because this client is not current owner: " + ((Object)_projectile).name)); } return num; } float num2 = Mathf.Max(0f, FearNoSpearPlugin.Cfg.LastKnownOwnerGraceSeconds.Value); float num3 = Time.time - _lastOwnerStateTime; bool flag = FearNoSpearPlugin.Cfg.AllowLastKnownOwnerIfZNetViewInvalid.Value && _lastKnownOwner && num3 <= num2; if (!flag && FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)$"Skipped spear rescue because ZNetView invalid and this client is not a recent last-known owner: {((Object)_projectile).name}; lastOwner={_lastKnownOwner}; age={num3:0.00}s; maxAge={num2:0.00}s"); } return flag; } 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(string reason) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_projectile == (Object)null)) { ItemData val = ReflectionCache.Get(ReflectionCache.F_spawnItem, _projectile, null); if (val != null) { TryCopyThrowerMetadataToNearbyDrop(val, _lastPosition, reason); } } } private void TryCopyThrowerMetadataToNearbyDrop(ItemData spawnItem, Vector3 position, string reason) { //IL_000c: 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) //IL_0064: 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, reason); } else if (SpearThrowerMetadata.TryWriteToDrop(val, num) && FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)$"Tagged spear drop with thrower metadata after {reason}: playerId={num}; drop={((Object)val).name}; pos={((Component)val).transform.position}"); } } } private static void QueuePendingDropTag(ItemData spawnItem, Vector3 position, long throwerPlayerId, string reason) { //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, Reason = reason, ExpiresAt = Time.time + 2f }); } } private bool TryClaimNetworkRescue(out NetworkRescueClaim claim) { claim = default(NetworkRescueClaim); if ((Object)(object)_projectile == (Object)null) { return false; } if (!FearNoSpearConfig.UseZdoClaimFlag) { return true; } ZNetView nView = ReflectionCache.GetNView(_projectile); if ((Object)(object)nView == (Object)null || !nView.IsValid()) { return true; } if (ReflectionCache.M_zNetViewGetZdo == null || ReflectionCache.M_zdoGetBool == null || ReflectionCache.M_zdoSetBool == null) { return true; } try { object obj = ReflectionCache.M_zNetViewGetZdo.Invoke(nView, Array.Empty()); if (obj == null) { return true; } if ((bool)ReflectionCache.M_zdoGetBool.Invoke(obj, new object[2] { "FearNoSpear.Rescued", false })) { if (FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)("Skipped spear rescue because ZDO claim flag is already set: " + ((Object)_projectile).name)); } return false; } ReflectionCache.M_zdoSetBool.Invoke(obj, new object[2] { "FearNoSpear.Rescued", true }); claim = new NetworkRescueClaim(obj); return true; } catch (Exception ex) { if (FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)("Could not use ZDO rescue claim flag; continuing without it. ex=" + ex.GetType().Name + ": " + ex.Message)); } return true; } } private void ReleaseNetworkRescueClaim(NetworkRescueClaim claim, string reason) { if (!claim.Claimed || claim.Zdo == null || ReflectionCache.M_zdoSetBool == null) { return; } try { ReflectionCache.M_zdoSetBool.Invoke(claim.Zdo, new object[2] { "FearNoSpear.Rescued", false }); if (FearNoSpearConfig.Verbose && (Object)(object)_projectile != (Object)null) { FearNoSpearPlugin.Log.LogDebug((object)("Released spear rescue ZDO claim after failed rescue: reason=" + reason + "; " + ((Object)_projectile).name)); } } catch (Exception ex) { if (FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)("Could not release failed spear rescue ZDO claim: reason=" + reason + "; ex=" + ex.GetType().Name + ": " + ex.Message)); } } } private static bool TryUseExistingNearbyDrop(ItemData spawnItem, Vector3 position, long throwerPlayerId, string phase, out Vector3 dropPosition) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: 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_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) ItemDrop val = FindBestMatchingNearbyDrop(spawnItem, position); if ((Object)(object)val == (Object)null) { dropPosition = position; return false; } dropPosition = ((Component)val).transform.position; if (throwerPlayerId != 0L) { SpearThrowerMetadata.TryWriteToDrop(val, throwerPlayerId); } if (FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogInfo((object)$"Skipped spear rescue because an equivalent item drop already exists nearby during {phase}: drop={((Object)val).name}; pos={((Component)val).transform.position}; radius={4f:0.0}m"); } return true; } private static void RemoveNearbyDuplicateDrops(ItemData? spawnItem, 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) //IL_0013: 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 (spawnItem == null) { return; } List list = FindMatchingNearbyDrops(spawnItem, position); if (list.Count <= 1) { return; } list.Sort((ItemDrop a, ItemDrop b) => Vector3.SqrMagnitude(((Component)a).transform.position - position).CompareTo(Vector3.SqrMagnitude(((Component)b).transform.position - position))); for (int i = 1; i < list.Count; i++) { ItemDrop val = list[i]; if (DestroyDuplicateDrop(val) && FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogInfo((object)$"Removed duplicate rescued spear drop near rescue point: drop={((Object)val).name}; pos={((Component)val).transform.position}; kept={((Object)list[0]).name}; radius={4f:0.0}m"); } } } private static ItemDrop? FindBestMatchingNearbyDrop(ItemData spawnItem, 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) //IL_000f: Unknown result type (might be due to invalid IL or missing references) List list = FindMatchingNearbyDrops(spawnItem, position); if (list.Count == 0) { return null; } list.Sort((ItemDrop a, ItemDrop b) => Vector3.SqrMagnitude(((Component)a).transform.position - position).CompareTo(Vector3.SqrMagnitude(((Component)b).transform.position - position))); return list[0]; } private static List FindMatchingNearbyDrops(ItemData spawnItem, Vector3 position) { //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_003c: Unknown result type (might be due to invalid IL or missing references) List list = new List(); float num = 16f; ItemDrop[] array = Object.FindObjectsByType((FindObjectsSortMode)0); foreach (ItemDrop val in array) { if (!((Object)(object)val == (Object)null) && val.m_itemData != null && !(Vector3.SqrMagnitude(((Component)val).transform.position - position) > num) && SpearItemIdentity.IsEquivalent(spawnItem, val.m_itemData)) { list.Add(val); } } return list; } private static bool DestroyDuplicateDrop(ItemDrop duplicate) { try { ZNetView component = ((Component)duplicate).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid()) { if (!component.IsOwner()) { component.ClaimOwnership(); } component.Destroy(); return true; } Object.Destroy((Object)(object)((Component)duplicate).gameObject); return true; } catch (Exception ex) { FearNoSpearPlugin.Log.LogWarning((object)("Failed to remove duplicate rescued spear drop: drop=" + ((Object)duplicate).name + "; ex=" + ex.GetType().Name + ": " + ex.Message)); return false; } } private bool TrySpawnOriginalItem(Projectile projectile, ItemData spawnItem, Vector3 normal, string reason, out Vector3 dropPosition) { //IL_0003: 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_002a: 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_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) dropPosition = _lastPosition; bool flag = ReflectionCache.Get(ReflectionCache.F_groundHitOnly, projectile, fallback: false); string failure = (flag ? "ground-hit-only projectile without a ground hit object" : null); if (!flag && TrySpawnOriginalItemThroughValheimPath(projectile, normal, out failure)) { if (TryFindSpawnedDrop(spawnItem, _lastPosition, out dropPosition)) { return true; } failure = "SpawnOnHit completed but no equivalent ItemDrop appeared nearby"; } if (!FearNoSpearConfig.UseItemDropFallback) { return false; } if (flag && FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)("Using ItemDrop fallback because SpawnOnHit requires a ground hit object. reason=" + reason + "; " + SpearProjectileDetector.DescribeProjectile(projectile))); } else if (failure != null && FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)("Using ItemDrop fallback after SpawnOnHit failed: " + failure + ". reason=" + reason + "; " + SpearProjectileDetector.DescribeProjectile(projectile))); } if (!TryDropStoredItem(projectile, spawnItem, _lastPosition)) { return false; } if (TryFindSpawnedDrop(spawnItem, _lastPosition, out dropPosition)) { return true; } if (FearNoSpearConfig.Verbose) { FearNoSpearPlugin.Log.LogDebug((object)("ItemDrop fallback returned without a matching spear drop near the rescue point. reason=" + reason + "; " + SpearProjectileDetector.DescribeProjectile(projectile))); } return false; } private static bool TrySpawnOriginalItemThroughValheimPath(Projectile projectile, Vector3 normal, out string? failure) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) MethodInfo m_spawnOnHit = ReflectionCache.M_spawnOnHit; if (m_spawnOnHit == null) { failure = "method missing"; return false; } try { object[] parameters = BuildSpawnOnHitArguments(m_spawnOnHit, normal); m_spawnOnHit.Invoke(projectile, parameters); failure = null; return true; } catch (TargetInvocationException ex) { failure = ((ex.InnerException == null) ? ex.Message : (ex.InnerException.GetType().Name + ": " + ex.InnerException.Message)); return false; } catch (Exception ex2) { failure = ex2.GetType().Name + ": " + ex2.Message; return false; } } private static bool TryDropStoredItem(Projectile projectile, ItemData spawnItem, Vector3 position) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) MethodInfo m_itemDropDropItem = ReflectionCache.M_itemDropDropItem; if (m_itemDropDropItem == null) { return false; } try { m_itemDropDropItem.Invoke(null, new object[4] { spawnItem, 1, position, ((Component)projectile).transform.rotation }); 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 bool TryFindSpawnedDrop(ItemData spawnItem, Vector3 position, out Vector3 dropPosition) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0012: 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) ItemDrop val = FindBestMatchingNearbyDrop(spawnItem, position); if ((Object)(object)val == (Object)null) { dropPosition = position; return false; } dropPosition = ((Component)val).transform.position; return true; } 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(), playerId); } internal static long ReadFromDrop(ItemDrop drop) { if ((Object)(object)drop == (Object)null) { return 0L; } return ReadFromView(((Component)drop).GetComponent()); } 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 && (Object)(object)owner != (Object)null && (Object)(object)owner == (Object)(object)Player.m_localPlayer) { val = Player.m_localPlayer; } 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 : OwnConfigEntryBase { public readonly ConfigEntry SourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public SyncedConfigEntry(ConfigEntry sourceConfig) { SourceConfig = sourceConfig; base..ctor(); } 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 : 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(configSync2.Name + " ConfigSync", (Action)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 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 CurrentList = new List(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List 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 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(configSync.Name + " ConfigSync", (Action)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary configValues = new Dictionary(); public readonly Dictionary customValues = new Dictionary(); } [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 Package = new List(); 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? __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(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZRpc rpc2 = rpc; ZNet __instance2 = __instance; Dictionary __state2 = __state; ZNetPeer peer; if (__instance2.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance2).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc2.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state2[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 entries = new List(); 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(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc2.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List { 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 configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); 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> configValueCache = new Dictionary>(); private readonly List> cacheExpirations = new List>(); 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.GetValueOrDefault(); } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0053: return (byte)result != 0; IL_0052: result = 0; goto IL_0053; } 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? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry(ConfigEntry configEntry) { ConfigEntry configEntry2 = configEntry; OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry2); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry2.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { CustomSyncedValueBase customValue2 = customValue; if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue2); allCustomValues = new HashSet(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue2.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue2); } }; } 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 kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2u) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(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 & 4u) != 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 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 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 dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int i = 0; i < num; i++) { 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) { OwnConfigEntryBase config2 = config; ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(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 distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZNetPeer peer2 = peer; 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 (peer2.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) { peer2.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg }); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer2.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout"); peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer2); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { ZPackage package2 = package; if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package2.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package2 = compressedPackage; } List> writers = (from peer in peers where peer.IsReady() select peer into p select distributeConfigToPeers(p, package2)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } public static SyncedConfigEntry? ConfigData(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable? configs = null, IEnumerable? customValues = null, IEnumerable? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List source = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; private string? displayName; private string? currentVersion; private string? minimumRequiredVersion; public bool ModRequired = true; private string? ReceivedCurrentVersion; private string? ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); private ConfigSync? ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."); } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error(ZRpc? rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { ZRpc rpc2 = rpc; return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action? original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register("ServerSync VersionCheck", (Action)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy, string>((KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } }