Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of TamePickup v1.0.0
plugins/TamePickup.dll
Decompiled 3 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: IgnoresAccessChecksTo("assembly_valheim")] [assembly: AssemblyCompany("TamePickup")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+319924712ee4746501db6f0ef83d4ecd89b33627")] [assembly: AssemblyProduct("TamePickup")] [assembly: AssemblyTitle("TamePickup")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Oddhatter.TamePickup { public sealed class CarriedData { public const string KeyPrefix = "oddhatter.tamepickup."; public const int CurrentVersion = 1; private const string KeyVersion = "oddhatter.tamepickup.v"; private const string KeyWorld = "oddhatter.tamepickup.world"; private const string KeyZdoUser = "oddhatter.tamepickup.zdoUser"; private const string KeyZdoId = "oddhatter.tamepickup.zdoId"; private const string KeyPrefab = "oddhatter.tamepickup.prefab"; private const string KeySnapshot = "oddhatter.tamepickup.snapshot"; private const string KeyToken = "oddhatter.tamepickup.token"; public const string KeyLabel = "oddhatter.tamepickup.label"; public int Version; public long WorldUid; public long ZdoUser; public uint ZdoId; public string Prefab; public string Snapshot; public string Label; public long Token; public static bool IsCarried(IDictionary<string, string> customData) { return customData?.ContainsKey("oddhatter.tamepickup.v") ?? false; } public void WriteTo(IDictionary<string, string> customData) { CultureInfo invariantCulture = CultureInfo.InvariantCulture; customData["oddhatter.tamepickup.v"] = Version.ToString(invariantCulture); customData["oddhatter.tamepickup.world"] = WorldUid.ToString(invariantCulture); customData["oddhatter.tamepickup.zdoUser"] = ZdoUser.ToString(invariantCulture); customData["oddhatter.tamepickup.zdoId"] = ZdoId.ToString(invariantCulture); customData["oddhatter.tamepickup.prefab"] = Prefab; customData["oddhatter.tamepickup.snapshot"] = Snapshot; customData["oddhatter.tamepickup.label"] = Label; customData["oddhatter.tamepickup.token"] = Token.ToString(invariantCulture); } public static CarriedData ReadFrom(IDictionary<string, string> customData) { if (!IsCarried(customData)) { return null; } CultureInfo invariantCulture = CultureInfo.InvariantCulture; CarriedData carriedData = new CarriedData(); if (!customData.TryGetValue("oddhatter.tamepickup.v", out var value) || !int.TryParse(value, NumberStyles.Integer, invariantCulture, out carriedData.Version)) { return null; } if (!customData.TryGetValue("oddhatter.tamepickup.world", out value) || !long.TryParse(value, NumberStyles.Integer, invariantCulture, out carriedData.WorldUid)) { return null; } if (!customData.TryGetValue("oddhatter.tamepickup.zdoUser", out value) || !long.TryParse(value, NumberStyles.Integer, invariantCulture, out carriedData.ZdoUser)) { return null; } if (!customData.TryGetValue("oddhatter.tamepickup.zdoId", out value) || !uint.TryParse(value, NumberStyles.Integer, invariantCulture, out carriedData.ZdoId)) { return null; } if (!customData.TryGetValue("oddhatter.tamepickup.prefab", out carriedData.Prefab) || carriedData.Prefab == null) { return null; } if (!customData.TryGetValue("oddhatter.tamepickup.snapshot", out carriedData.Snapshot) || carriedData.Snapshot == null) { return null; } if (!customData.TryGetValue("oddhatter.tamepickup.label", out carriedData.Label) || carriedData.Label == null) { return null; } if (!customData.TryGetValue("oddhatter.tamepickup.token", out value) || !long.TryParse(value, NumberStyles.Integer, invariantCulture, out carriedData.Token)) { carriedData.Token = 0L; } return carriedData; } public static long NewToken() { long num; do { num = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0); } while (num == 0L); return num; } public static bool TokenMatches(long itemToken, int itemPrefabHash, long zdoToken, int zdoPrefabHash) { if (itemToken != 0L && itemToken == zdoToken) { return itemPrefabHash == zdoPrefabHash; } return false; } public bool IsSameCreature(long worldUid, long zdoToken) { if (Token != 0L && Token == zdoToken) { return WorldUid == worldUid; } return false; } public static string MakeLabel(string creatureName, int stars, string customName) { string text = creatureName; if (stars > 0) { text = text + " " + new string('★', stars); } if (!string.IsNullOrWhiteSpace(customName)) { text = text + " — " + customName; } return text; } public static string ReleaseRefusal(bool enabled, CarriedData data, long currentWorldUid, string fallbackLabel) { string text = ((data != null) ? data.Label : fallbackLabel); if (!enabled) { return "Turn TamePickup on to release " + text; } if (data == null) { return text + " can't be released: its data is damaged"; } if (data.WorldUid != currentWorldUid) { return text + " belongs to another world"; } return null; } public static bool TryDecodeSnapshot(string snapshot, out byte[] bytes, out int prefabHash) { bytes = null; prefabHash = 0; if (string.IsNullOrEmpty(snapshot)) { return false; } byte[] array; try { array = Convert.FromBase64String(snapshot); } catch (FormatException) { return false; } if (array.Length < 6) { return false; } prefabHash = array[2] | (array[3] << 8) | (array[4] << 16) | (array[5] << 24); bytes = array; return true; } public static (float x, float z) ParkOffset(double angle01, double dist01) { double num = angle01 * 2.0 * Math.PI; double num2 = 2.0 + 2.0 * dist01; return (x: (float)(Math.Cos(num) * num2), z: (float)(Math.Sin(num) * num2)); } } internal static class CarriedItem { [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })] private static class AddItemPatch { private static void Prefix(ItemData item) { SafeApply(item); } } [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData), typeof(Vector2i) })] private static class AddItemAtPatch { private static void Prefix(ItemData item) { SafeApply(item); } } [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData), typeof(int), typeof(int), typeof(int), typeof(bool) })] private static class AddItemAmountAtPatch { private static void Prefix(ItemData item) { SafeApply(item); } } [HarmonyPatch(typeof(Inventory), "Load", new Type[] { typeof(ZPackage) })] private static class LoadPatch { private static void Postfix(Inventory __instance) { foreach (ItemData item in __instance.m_inventory) { SafeApply(item); } } } [HarmonyPatch(typeof(ItemDrop), "Load")] private static class GroundLoadPatch { private static void Postfix(ItemDrop __instance) { SafeApply(__instance.m_itemData); } } [HarmonyPatch(typeof(ItemDrop), "LoadFromExternalZDO")] private static class GroundLoadExternalPatch { private static void Postfix(ItemDrop __instance) { SafeApply(__instance.m_itemData); } } [HarmonyPatch(typeof(Inventory), "RemoveUnequipped")] private static class RemoveUnequippedPatch { private static bool Prefix(Inventory __instance) { __instance.m_inventory.RemoveAll((ItemData x) => !x.m_shared.m_questItem && !x.m_equipped && !IsCarried(x)); __instance.Changed(false, false); return false; } } [HarmonyPatch(typeof(ItemStand), "CanAttach")] private static class ItemStandCanAttachPatch { private static bool Prefix(ItemData item, ref bool __result) { if (!IsCarried(item)) { return true; } __result = false; return false; } } [HarmonyPatch(typeof(ArmorStand), "CanAttach", new Type[] { typeof(ArmorStandSlot), typeof(ItemData) })] private static class ArmorStandCanAttachPatch { private static bool Prefix(ItemData item, ref bool __result) { try { if (!IsCarried(item)) { return true; } } catch (Exception arg) { if (!_armorStandFailureLogged) { _armorStandFailureLogged = true; TamePickupPlugin.Log.LogError((object)$"Checking an item for an armor stand failed (logged once); it isn't attached: {arg}"); } } __result = false; return false; } } [HarmonyPatch(typeof(Player), "AddKnownItem")] private static class AddKnownItemPatch { private static bool Prefix(ItemData item) { try { return !IsCarried(item); } catch (Exception arg) { if (!_knownItemFailureLogged) { _knownItemFailureLogged = true; TamePickupPlugin.Log.LogError((object)$"Checking an item before marking it known failed (logged once): {arg}"); } return true; } } } [HarmonyPatch(typeof(Catapult), "CanItemBeLoaded")] private static class CatapultCanItemBeLoadedPatch { private static bool Prefix(ItemData item, ref bool __result) { if (!IsCarried(item)) { return true; } __result = false; return false; } } [HarmonyPatch(typeof(Incinerator), "RPC_RequestIncinerate")] private static class IncineratorRequestPatch { private static bool Prefix(Incinerator __instance, long uid) { if (!__instance.m_nview.IsOwner() || !HoldsCarried(__instance)) { return true; } __instance.m_nview.InvokeRPC(uid, "RPC_IncinerateRespons", new object[1] { 100 }); return false; } } [HarmonyPatch] private static class IncinerateCoroutinePatch { private static MethodBase TargetMethod() { return AccessTools.EnumeratorMoveNext((MethodBase)AccessTools.Method(typeof(Incinerator), "Incinerate", (Type[])null, (Type[])null)); } private static bool Prefix(object __instance, ref bool __result) { Traverse val = Traverse.Create(__instance); if (val.Field<int>("<>1__state").Value != 1) { return true; } Incinerator value = val.Field<Incinerator>("<>4__this").Value; if ((Object)(object)value == (Object)null || !value.m_nview.IsValid() || !HoldsCarried(value)) { return true; } value.m_nview.InvokeRPC(ZNetView.Everybody, "RPC_AnimateLeverReturn", Array.Empty<object>()); value.isInUse = false; value.m_nview.InvokeRPC(val.Field<long>("uid").Value, "RPC_IncinerateRespons", new object[1] { 100 }); val.Field<int>("<>1__state").Value = -1; __result = false; return false; } } [HarmonyPatch(typeof(Incinerator), "RPC_IncinerateRespons")] private static class IncineratorResponsePatch { private static bool Prefix(int r) { if (r != 100) { return true; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { ((Character)localPlayer).Message((MessageType)1, "Carried creatures can't be obliterated. Take them out first.", 0, (Sprite)null, false); } return false; } } public const string FallbackItemPrefab = "TrophyDeer"; public const string Description = "A carried creature. Drop it to release it here."; private const string FallbackName = "Carried creature"; private static readonly object Marker = new object(); private static readonly ConditionalWeakTable<SharedData, object> Copies = new ConditionalWeakTable<SharedData, object>(); private static readonly MethodInfo MemberwiseCloneMethod = typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic); private static bool _armorStandFailureLogged; private static bool _knownItemFailureLogged; private const int IncineratorRefusedCarried = 100; private const string IncineratorRefusal = "Carried creatures can't be obliterated. Take them out first."; public static bool IsCarried(ItemData item) { if (item?.m_customData != null) { return CarriedData.IsCarried(item.m_customData); } return false; } public static void Apply(ItemData item) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown if (IsCarried(item) && item.m_shared != null && !Copies.TryGetValue(item.m_shared, out var _)) { SharedData val = (SharedData)MemberwiseCloneMethod.Invoke(item.m_shared, null); val.m_name = LabelOf(item); val.m_maxStackSize = 1; val.m_description = "A carried creature. Drop it to release it here."; val.m_teleportable = true; val.m_questItem = false; val.m_value = 0; Copies.Add(val, Marker); item.m_shared = val; } } public static ItemData Create(GameObject itemPrefab, CarriedData data) { if ((Object)(object)itemPrefab == (Object)null) { throw new ArgumentException("No item prefab.", "itemPrefab"); } if (data == null) { throw new ArgumentException("No carried data.", "data"); } if (data.Prefab == null || data.Snapshot == null || data.Label == null) { throw new ArgumentException("Carried data needs Prefab, Snapshot and Label.", "data"); } ItemDrop component = itemPrefab.GetComponent<ItemDrop>(); if ((Object)(object)component == (Object)null) { throw new ArgumentException(((Object)itemPrefab).name + " is not an item.", "itemPrefab"); } if ((Object)(object)ObjectDB.instance == (Object)null || (Object)(object)ObjectDB.instance.GetItemPrefab(((Object)itemPrefab).name) != (Object)(object)itemPrefab) { throw new ArgumentException(((Object)itemPrefab).name + " is not an ObjectDB item prefab.", "itemPrefab"); } ItemData val = component.m_itemData.Clone(); val.m_stack = 1; val.m_dropPrefab = itemPrefab; val.m_worldLevel = (byte)Game.m_worldLevel; data.WriteTo(val.m_customData); Apply(val); return val; } public static GameObject ItemPrefabFor(Character creature) { ObjectDB instance = ObjectDB.instance; if ((Object)(object)instance == (Object)null) { return null; } CharacterDrop val = (((Object)(object)creature != (Object)null) ? ((Component)creature).GetComponent<CharacterDrop>() : null); if ((Object)(object)val != (Object)null && val.m_drops != null) { foreach (Drop drop in val.m_drops) { if (drop != null && !((Object)(object)drop.m_prefab == (Object)null)) { GameObject itemPrefab = instance.GetItemPrefab(((Object)drop.m_prefab).name); if (IsItemOfType(itemPrefab, (ItemType)13)) { return itemPrefab; } } } } GameObject itemPrefab2 = instance.GetItemPrefab("TrophyDeer"); if (!((Object)(object)itemPrefab2 != (Object)null) || !((Object)(object)itemPrefab2.GetComponent<ItemDrop>() != (Object)null)) { return null; } return itemPrefab2; } private static bool IsItemOfType(GameObject prefab, ItemType type) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)prefab == (Object)null) { return false; } ItemDrop component = prefab.GetComponent<ItemDrop>(); if ((Object)(object)component != (Object)null && component.m_itemData?.m_shared != null) { return component.m_itemData.m_shared.m_itemType == type; } return false; } private static string LabelOf(ItemData item) { string value = CarriedData.ReadFrom(item.m_customData)?.Label; if (string.IsNullOrWhiteSpace(value)) { item.m_customData.TryGetValue("oddhatter.tamepickup.label", out value); } if (!string.IsNullOrWhiteSpace(value)) { return value; } return "Carried creature"; } private static void SafeApply(ItemData item) { try { Apply(item); } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Failed to set up carried item: {arg}"); } } private static bool HoldsCarried(Incinerator incinerator) { return (((Object)(object)incinerator.m_container != (Object)null) ? incinerator.m_container.GetInventory() : null)?.m_inventory.Exists(IsCarried) ?? false; } } internal static class CharacterSave { internal static void Save(string after) { try { Game instance = Game.instance; if (!((Object)(object)instance == (Object)null) && !((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer()) { float saveTimer = instance.m_saveTimer; Stopwatch stopwatch = Stopwatch.StartNew(); try { instance.SavePlayerProfile(false, false); } finally { instance.m_saveTimer = saveTimer; } TamePickupPlugin.Log.LogInfo((object)$"Saved the character after {after} ({stopwatch.Elapsed.TotalMilliseconds:F0} ms)."); } } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Failed to save the character after {after}: {arg}"); } } } internal static class Parking { [HarmonyPatch(typeof(ZNetScene), "CreateObjects", new Type[] { typeof(List<ZDO>), typeof(List<ZDO>) })] private static class HideParkedPatch { private static bool _failureLogged; private static void Prefix(List<ZDO> currentNearObjects, List<ZDO> currentDistantObjects) { try { Placement.CheckPendingDeletesForRollback(); if (TamePickupPlugin.Enabled.Value) { Placement.ResolvePendingDeletes(currentNearObjects, currentDistantObjects); currentNearObjects.RemoveAll(IsParkedPredicate); currentDistantObjects.RemoveAll(IsParkedPredicate); } } catch (Exception arg) { if (!_failureLogged) { _failureLogged = true; TamePickupPlugin.Log.LogError((object)$"Hiding parked creatures failed (logged once): {arg}"); } } } } [HarmonyPatch(typeof(ZNetScene), "CreateObjects", new Type[] { typeof(List<ZDO>), typeof(List<ZDO>) })] private static class RecoverWhileDisabledPatch { private static bool _failureLogged; private static void Postfix(ZNetScene __instance, List<ZDO> currentNearObjects, List<ZDO> currentDistantObjects) { if (TamePickupPlugin.Enabled.Value) { return; } try { Unpark(__instance, currentNearObjects); Unpark(__instance, currentDistantObjects); } catch (Exception arg) { if (!_failureLogged) { _failureLogged = true; TamePickupPlugin.Log.LogError((object)$"Un-parking recovered creatures failed (logged once): {arg}"); } } } private static void Unpark(ZNetScene scene, List<ZDO> zdos) { //IL_0087: Unknown result type (might be due to invalid IL or missing references) foreach (ZDO zdo in zdos) { try { if (zdo.Created && zdo.IsOwner() && IsParked(zdo) && !((Object)(object)scene.FindInstance(zdo) == (Object)null)) { zdo.Set(ParkedHash, false); zdo.Set("oddhatter.tamepickup.parkedBy", 0L); GameObject prefab = scene.GetPrefab(zdo.GetPrefab()); TamePickupPlugin.Log.LogInfo((object)string.Format("Recovered parked {0} {1} at the spawn while disabled; it stays released.", ((Object)(object)prefab != (Object)null) ? ((Object)prefab).name : "creature", zdo.m_uid)); } } catch (Exception arg) { if (!_failureLogged) { _failureLogged = true; TamePickupPlugin.Log.LogError((object)$"Un-parking a recovered creature failed (logged once): {arg}"); } } } } } [HarmonyPatch(typeof(ZNetScene), "IsAreaReady", new Type[] { typeof(Vector3) })] private static class AreaReadyPatch { private static bool _failureLogged; private static bool Prefix(ZNetScene __instance, Vector3 point, ref bool __result) { //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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) try { if (!TamePickupPlugin.Enabled.Value) { return true; } Vector2s zone = ZoneSystem.GetZone(point); if (!ZoneSystem.instance.IsZoneLoaded(zone)) { __result = false; return false; } AreaObjects.Clear(); ZDOMan.instance.FindSectorObjects(zone, new SimulationDistance(1, 0, false), AreaObjects, (List<ZDO>)null); __result = true; foreach (ZDO areaObject in AreaObjects) { if (__instance.IsPrefabZDOValid(areaObject) && !Object.op_Implicit((Object)(object)__instance.FindInstance(areaObject)) && !IsParked(areaObject)) { __result = false; break; } } AreaObjects.Clear(); return false; } catch (Exception arg) { if (!_failureLogged) { _failureLogged = true; TamePickupPlugin.Log.LogError((object)$"Area check failed (logged once); using the game's own check: {arg}"); } AreaObjects.Clear(); return true; } } } public const string ParkedKey = "oddhatter.tamepickup.parked"; public static readonly int ParkedHash = StringExtensionMethods.GetStableHashCode("oddhatter.tamepickup.parked"); public const string ParkedByKey = "oddhatter.tamepickup.parkedBy"; public const string TokenKey = "oddhatter.tamepickup.token"; public static readonly int TokenHash = StringExtensionMethods.GetStableHashCode("oddhatter.tamepickup.token"); public const string ReplacesKey = "oddhatter.tamepickup.replaces"; public static readonly int ReplacesHash = StringExtensionMethods.GetStableHashCode("oddhatter.tamepickup.replaces"); private static readonly Predicate<ZDO> IsParkedPredicate = IsParked; private static readonly List<ZDO> AreaObjects = new List<ZDO>(); public static bool IsParked(ZDO zdo) { if (zdo != null) { return zdo.GetBool(ParkedHash, false); } return false; } public static Vector3 SpawnAreaPoint(Vector3 offsetXZ) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: 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) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: 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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Vector3.zero; try { PlayerProfile val2 = (((Object)(object)Game.instance != (Object)null) ? Game.instance.GetPlayerProfile() : null); Vector3 val3 = default(Vector3); if (val2 != null && val2.HaveCustomSpawnPoint()) { val = val2.GetCustomSpawnPoint(); } else if ((Object)(object)Game.instance != (Object)null && (Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetLocationIcon(Game.instance.m_StartLocation, ref val3)) { val = val3; } else { TamePickupPlugin.Log.LogWarning((object)"Spawn location not found; parking at the world origin."); } } catch (Exception ex) { TamePickupPlugin.Log.LogWarning((object)("Failed to resolve the spawn location, parking at the world origin: " + ex.Message)); val = Vector3.zero; } Vector3 val4 = default(Vector3); ((Vector3)(ref val4))..ctor(val.x + offsetXZ.x, val.y, val.z + offsetXZ.z); try { if ((Object)(object)ZoneSystem.instance != (Object)null) { float num = default(float); val4.y = (ZoneSystem.instance.GetSolidHeight(val4, ref num, 1000) ? num : ZoneSystem.instance.GetGroundHeight(val4)); } } catch (Exception ex2) { TamePickupPlugin.Log.LogWarning((object)("Failed to get ground height for the parking spot: " + ex2.Message)); } return val4; } public static void Park(ZDO zdo, Vector3 parkPos, long playerId, long token) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) zdo.Set(TokenHash, token); zdo.Set(ParkedHash, true); zdo.Set("oddhatter.tamepickup.parkedBy", playerId); zdo.Set(ZDOVars.s_follow, ""); zdo.Set(ZDOVars.s_patrol, true); zdo.Set(ZDOVars.s_patrolPoint, parkPos); zdo.SetPosition(parkPos); } } public static class PendingDeletes { public struct Entry : IEquatable<Entry> { public readonly long Token; public readonly int PrefabHash; public readonly long WorldUid; public readonly double DropTime; public readonly bool HasWorldAndTime; public Entry(long token, int prefabHash, long worldUid, double dropTime) { Token = token; PrefabHash = prefabHash; WorldUid = worldUid; DropTime = dropTime; HasWorldAndTime = true; } public Entry(long token, int prefabHash) { Token = token; PrefabHash = prefabHash; WorldUid = 0L; DropTime = 0.0; HasWorldAndTime = false; } public bool Matches(long token, int prefabHash) { if (token != 0L && Token == token) { return PrefabHash == prefabHash; } return false; } public bool Equals(Entry other) { if (Token == other.Token && PrefabHash == other.PrefabHash && HasWorldAndTime == other.HasWorldAndTime && WorldUid == other.WorldUid) { double dropTime = DropTime; return dropTime.Equals(other.DropTime); } return false; } public override bool Equals(object obj) { if (obj is Entry other) { return Equals(other); } return false; } public override int GetHashCode() { long token = Token; return token.GetHashCode() ^ PrefabHash; } public override string ToString() { CultureInfo invariantCulture = CultureInfo.InvariantCulture; long token = Token; string text = token.ToString(invariantCulture); int prefabHash = PrefabHash; string text2 = text + ":" + prefabHash.ToString(invariantCulture); if (!HasWorldAndTime) { return text2; } string[] obj = new string[5] { text2, ":", null, null, null }; token = WorldUid; obj[2] = token.ToString(invariantCulture); obj[3] = ":"; obj[4] = FormatTime(DropTime); return string.Concat(obj); } private static string FormatTime(double time) { CultureInfo invariantCulture = CultureInfo.InvariantCulture; string text = time.ToString("R", invariantCulture); if (!double.TryParse(text, NumberStyles.Float, invariantCulture, out var result) || !result.Equals(time)) { return time.ToString("G17", invariantCulture); } return text; } } public enum SessionCheck { Keep, Discard, OtherWorld } public sealed class Sightings { private readonly struct SightKey : IEquatable<SightKey> { private readonly long _token; private readonly int _prefabHash; public SightKey(long token, int prefabHash) { _token = token; _prefabHash = prefabHash; } public bool Equals(SightKey other) { if (_token == other._token) { return _prefabHash == other._prefabHash; } return false; } public override bool Equals(object obj) { if (obj is SightKey other) { return Equals(other); } return false; } public override int GetHashCode() { long token = _token; return token.GetHashCode() * 31 + _prefabHash; } } private long _session; private bool _started; private readonly HashSet<SightKey> _seen = new HashSet<SightKey>(); public bool ForSession(long session) { if (_started && session == _session) { return false; } _started = true; _session = session; _seen.Clear(); return true; } public void Add(long replacedToken, int prefabHash) { if (replacedToken != 0L) { _seen.Add(new SightKey(replacedToken, prefabHash)); } } public bool Seen(long replacedToken, int prefabHash) { if (replacedToken != 0L) { return _seen.Contains(new SightKey(replacedToken, prefabHash)); } return false; } } public const string Key = "oddhatter.tamepickup.pendingDelete"; public static SessionCheck CheckAtSessionStart(Entry entry, long worldUid, double now) { if (!entry.HasWorldAndTime) { return SessionCheck.Discard; } if (entry.WorldUid != worldUid) { return SessionCheck.OtherWorld; } if (!(entry.DropTime > now)) { return SessionCheck.Keep; } return SessionCheck.Discard; } public static List<Entry> Decode(string raw) { List<Entry> list = new List<Entry>(); if (string.IsNullOrEmpty(raw)) { return list; } CultureInfo invariantCulture = CultureInfo.InvariantCulture; string[] array = raw.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string[] array2 = array[i].Split(new char[1] { ':' }); if ((array2.Length == 2 || array2.Length == 4 || array2.Length == 5) && long.TryParse(array2[0], NumberStyles.Integer, invariantCulture, out var result) && result != 0L && int.TryParse(array2[1], NumberStyles.Integer, invariantCulture, out var result2)) { long result3; double result4; if (array2.Length == 2) { list.Add(new Entry(result, result2)); } else if (long.TryParse(array2[2], NumberStyles.Integer, invariantCulture, out result3) && double.TryParse(array2[3], NumberStyles.Float, invariantCulture, out result4) && !double.IsNaN(result4) && !double.IsInfinity(result4) && result4 >= 0.0) { list.Add(new Entry(result, result2, result3, result4)); } } } return list; } public static string Encode(List<Entry> entries) { StringBuilder stringBuilder = new StringBuilder(); foreach (Entry entry in entries) { if (stringBuilder.Length > 0) { stringBuilder.Append(','); } stringBuilder.Append(entry.ToString()); } return stringBuilder.ToString(); } public static List<Entry> Read(IDictionary<string, string> customData) { customData.TryGetValue("oddhatter.tamepickup.pendingDelete", out var value); return Decode(value); } public static void Add(IDictionary<string, string> customData, long token, int prefabHash, long worldUid, double dropTime) { if (token != 0L) { List<Entry> list = Read(customData); if (!Contains(list, token, prefabHash)) { list.Add(new Entry(token, prefabHash, worldUid, dropTime)); } customData["oddhatter.tamepickup.pendingDelete"] = Encode(list); } } public static bool Remove(IDictionary<string, string> customData, long token, int prefabHash) { List<Entry> list = Read(customData); if (list.RemoveAll((Entry e) => e.Matches(token, prefabHash)) == 0) { return false; } Write(customData, list); return true; } public static List<Entry> DiscardRolledBack(IDictionary<string, string> customData, long worldUid, double now) { List<Entry> list = new List<Entry>(); List<Entry> list2 = new List<Entry>(); foreach (Entry item in Read(customData)) { ((CheckAtSessionStart(item, worldUid, now) == SessionCheck.Discard) ? list : list2).Add(item); } if (list.Count > 0) { Write(customData, list2); } return list; } public static List<Entry> ForWorld(List<Entry> entries, long worldUid) { return entries.FindAll((Entry e) => e.HasWorldAndTime && e.WorldUid == worldUid); } public static bool Contains(List<Entry> entries, long token, int prefabHash) { Entry found; return TryFind(entries, token, prefabHash, out found); } public static bool HasPrefab(List<Entry> entries, int prefabHash) { foreach (Entry entry in entries) { if (entry.PrefabHash == prefabHash) { return true; } } return false; } public static bool TryFind(List<Entry> entries, long token, int prefabHash, out Entry found) { foreach (Entry entry in entries) { if (entry.Matches(token, prefabHash)) { found = entry; return true; } } found = default(Entry); return false; } public static bool ServerHasReplacement(bool isServer, long creatorSession, long mySession, Func<bool> sentToServer) { if (!isServer && creatorSession == mySession) { return sentToServer(); } return true; } private static void Write(IDictionary<string, string> customData, List<Entry> entries) { if (entries.Count == 0) { customData.Remove("oddhatter.tamepickup.pendingDelete"); } else { customData["oddhatter.tamepickup.pendingDelete"] = Encode(entries); } } } internal static class Pickup { public const string DefaultPickupButton = "JoyRStick"; private const string AltButton = "JoyAltKeys"; internal static void UpdateInput() { //IL_002c: Unknown result type (might be due to invalid IL or missing references) try { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || !((Character)localPlayer).TakeInput() || Hud.InRadial() || Hud.IsPieceSelectionVisible() || (!ZInput.GetKeyDown(TamePickupPlugin.PickupKey.Value, false) && !GamepadComboDown())) { return; } if (!TamePickupPlugin.Enabled.Value) { ((Character)localPlayer).Message((MessageType)1, "TamePickup is disabled", 0, (Sprite)null, false); return; } Character hoverCreature = localPlayer.GetHoverCreature(); string text = CheckTarget(localPlayer, hoverCreature); if (text != null) { ((Character)localPlayer).Message((MessageType)1, text, 0, (Sprite)null, false); } else { PickUp(localPlayer, hoverCreature); } } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Pickup input failed: {arg}"); } } internal static bool GamepadComboDown() { string value = TamePickupPlugin.PickupButton.Value; if (string.IsNullOrWhiteSpace(value)) { return false; } if (ZInput.IsGamepadActive() && ZInput.GetButton("JoyAltKeys")) { return ZInput.GetButtonDown(value.Trim()); } return false; } internal static string CheckTarget(Player player, Character target) { //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null || (Object)(object)target == (Object)null || target.IsPlayer()) { return "Look at a tamed creature to pick it up"; } string text = NameOf(target); if (!target.IsTamed()) { return text + " isn't tame"; } if (target.IsDead()) { return text + " is dead"; } Sadle componentInChildren = ((Component)target).GetComponentInChildren<Sadle>(); Tameable component = ((Component)target).GetComponent<Tameable>(); if (((Object)(object)componentInChildren != (Object)null && componentInChildren.HaveValidUser()) || ((Object)(object)component != (Object)null && component.HaveRider())) { return "Someone is riding " + text; } ZNetView component2 = ((Component)target).GetComponent<ZNetView>(); if ((Object)(object)component2 == (Object)null || !component2.IsValid() || !component2.GetZDO().Persistent) { return text + " can't be picked up"; } if (Vector3.Distance(((Component)player).transform.position, ((Component)target).transform.position) > TamePickupPlugin.MaxDistance.Value) { return text + " is too far away"; } string text2 = CarriedLabelFor(((Humanoid)player).GetInventory(), component2.GetZDO().GetLong(Parking.TokenHash, 0L)); if (text2 != null) { return "You're already carrying " + text2; } if (!((Humanoid)player).GetInventory().HaveEmptySlot()) { return "No room in your inventory"; } return null; } private static string CarriedLabelFor(Inventory inventory, long zdoToken) { try { if (zdoToken == 0L || inventory == null || (Object)(object)ZNet.instance == (Object)null) { return null; } long worldUID = ZNet.instance.GetWorldUID(); foreach (ItemData allItem in inventory.GetAllItems()) { if (CarriedItem.IsCarried(allItem)) { CarriedData carriedData = CarriedData.ReadFrom(allItem.m_customData); if (carriedData != null && carriedData.IsSameCreature(worldUID, zdoToken)) { return carriedData.Label; } } } } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Checking the inventory for an item of the same creature failed: {arg}"); } return null; } private static void PickUp(Player player, Character creature) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) string text = NameOf(creature); ZNetView component = ((Component)creature).GetComponent<ZNetView>(); GameObject val = CarriedItem.ItemPrefabFor(creature); if ((Object)(object)val == (Object)null) { TamePickupPlugin.Log.LogWarning((object)("No item prefab for " + Utils.GetPrefabName(((Component)creature).gameObject) + " (fallback TrophyDeer missing).")); ((Character)player).Message((MessageType)1, text + " can't be picked up", 0, (Sprite)null, false); return; } component.ClaimOwnership(); ZDO zDO = component.GetZDO(); ZPackage val2 = new ZPackage(); zDO.Serialize(val2); CarriedData carriedData = new CarriedData { Version = 1, WorldUid = ZNet.instance.GetWorldUID(), ZdoUser = ((ZDOID)(ref zDO.m_uid)).UserID, ZdoId = ((ZDOID)(ref zDO.m_uid)).ID, Token = CarriedData.NewToken(), Prefab = Utils.GetPrefabName(((Component)creature).gameObject), Snapshot = Convert.ToBase64String(val2.GetArray()), Label = CarriedData.MakeLabel(text, creature.GetLevel() - 1, zDO.GetString(ZDOVars.s_tamedName, "")) }; Inventory inventory = ((Humanoid)player).GetInventory(); ItemData val3 = CarriedItem.Create(val, carriedData); long num = zDO.GetLong(Parking.TokenHash, 0L); zDO.Set(Parking.TokenHash, carriedData.Token); try { inventory.AddItem(val3); } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Adding the carried item for {carriedData.Label} threw: {arg}"); } if (!inventory.m_inventory.Contains(val3)) { zDO.Set(Parking.TokenHash, num); ((Character)player).Message((MessageType)1, "No room in your inventory", 0, (Sprite)null, false); return; } try { (float x, float z) tuple = CarriedData.ParkOffset(Random.value, Random.value); float item = tuple.x; float item2 = tuple.z; Vector3 parkPos = Parking.SpawnAreaPoint(new Vector3(item, 0f, item2)); long playerID = Game.instance.GetPlayerProfile().GetPlayerID(); ZNetScene.instance.m_instances.Remove(zDO); component.ResetZDO(); Object.Destroy((Object)(object)((Component)creature).gameObject); Parking.Park(zDO, parkPos, playerID, carriedData.Token); ZDOMan.instance.ForceSendZDO(zDO.m_uid); } catch (Exception arg2) { TamePickupPlugin.Log.LogError((object)$"Picked up {carriedData.Label} but failed to park it; the item stays in the inventory: {arg2}"); ((Character)player).Message((MessageType)1, "Couldn't pick up " + text + " properly; drop its item to release it", 0, (Sprite)null, false); return; } ((Character)player).Message((MessageType)2, carriedData.Label + " picked up", 0, (Sprite)null, false); TamePickupPlugin.Log.LogInfo((object)$"Picked up {carriedData.Prefab} {zDO.m_uid} (token {carriedData.Token}) as \"{carriedData.Label}\"."); } private static string NameOf(Character creature) { return Localization.instance.Localize(creature.m_name); } } internal static class Placement { [HarmonyPatch(typeof(Humanoid), "DropItem", new Type[] { typeof(Inventory), typeof(ItemData), typeof(int) })] private static class RefuseDropPatch { private static bool Prefix(Humanoid __instance, ItemData item, ref bool __result) { try { if (!CarriedItem.IsCarried(item) || (Object)(object)__instance != (Object)(object)Player.m_localPlayer) { return true; } string text = CarriedData.ReleaseRefusal(TamePickupPlugin.Enabled.Value, CarriedData.ReadFrom(item.m_customData), ZNet.instance.GetWorldUID(), item.m_shared.m_name); if (text == null) { return true; } ((Character)__instance).Message((MessageType)1, text, 0, (Sprite)null, false); } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Checking a carried item drop failed; the item stays in the inventory: {arg}"); } __result = false; return false; } } [HarmonyPatch(typeof(ItemDrop), "DropItem", new Type[] { typeof(ItemData), typeof(int), typeof(Vector3), typeof(Quaternion) })] private static class DropItemPatch { private static void Postfix(ItemDrop __result) { Enqueue(__result); } } [HarmonyPatch(typeof(ItemDrop), "Awake")] private static class AwakePatch { private static void Postfix(ItemDrop __instance) { Enqueue(__instance); } } [HarmonyPatch(typeof(ItemDrop), "TimedDestruction")] private static class KeepOnGroundPatch { private static bool Prefix(ItemDrop __instance) { try { return !CarriedItem.IsCarried(__instance.m_itemData); } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Checking a ground item before despawn failed; it stays: {arg}"); return false; } } } [HarmonyPatch(typeof(ItemDrop), "LoadFromExternalZDO")] private static class LoadFromExternalZDOPatch { private static void Postfix(ItemDrop __instance) { Enqueue(__instance); } } private static readonly List<ItemDrop> Queue = new List<ItemDrop>(); private static string _pendingRaw; private static List<PendingDeletes.Entry> _pendingEntries = new List<PendingDeletes.Entry>(); private static bool _pendingFailureLogged; private static long? _rollbackCheckedSession; private static bool _rollbackFailureLogged; private static readonly PendingDeletes.Sightings _sightings = new PendingDeletes.Sightings(); private static readonly HashSet<long> _waitLogged = new HashSet<long>(); private static bool _sentListFailureLogged; private static void Enqueue(ItemDrop drop) { try { if (!((Object)(object)drop == (Object)null) && !((Object)(object)drop.m_nview == (Object)null) && drop.m_nview.IsValid() && CarriedItem.IsCarried(drop.m_itemData) && !Queue.Contains(drop)) { Queue.Add(drop); } } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Failed to queue a carried ground item: {arg}"); } } internal static void ProcessQueue() { try { if (Queue.Count == 0 || !TamePickupPlugin.Enabled.Value || (Object)(object)ZNet.instance == (Object)null || (Object)(object)ZNetScene.instance == (Object)null || ZDOMan.instance == null || (Object)(object)Game.instance == (Object)null) { return; } long worldUID = ZNet.instance.GetWorldUID(); for (int num = Queue.Count - 1; num >= 0; num--) { ItemDrop val = Queue[num]; if ((Object)(object)val == (Object)null || (Object)(object)val.m_nview == (Object)null || !val.m_nview.IsValid()) { Queue.RemoveAt(num); } else if (val.m_nview.IsOwner()) { Queue.RemoveAt(num); try { ReleaseGroundItem(val, worldUID); } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Releasing a carried ground item failed; the item stays on the ground: {arg}"); } } } } catch (Exception arg2) { TamePickupPlugin.Log.LogError((object)$"Processing carried ground items failed: {arg2}"); } } private static void ReleaseGroundItem(ItemDrop drop, long worldUid) { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) bool flag = ((ZDOID)(ref drop.m_nview.GetZDO().m_uid)).UserID == ZDOMan.GetSessionID(); CarriedData carriedData = CarriedData.ReadFrom(drop.m_itemData.m_customData); if (carriedData == null) { TamePickupPlugin.Log.LogWarning((object)("Carried item \"" + drop.m_itemData.m_shared.m_name + "\" on the ground has unreadable data; it stays there.")); return; } if (carriedData.WorldUid != worldUid) { TamePickupPlugin.Log.LogWarning((object)$"{carriedData.Label} on the ground belongs to another world ({carriedData.WorldUid}); it stays there."); return; } Transform transform = ((Component)drop).transform; if (Release(carriedData, transform.position, Quaternion.Euler(0f, transform.eulerAngles.y, 0f))) { try { ZNetScene.instance.Destroy(((Component)drop).gameObject); } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Released {carriedData.Label} but failed to remove its ground item (dropping it again would make a second one): {arg}"); } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && flag) { ((Character)localPlayer).Message((MessageType)2, carriedData.Label + " released", 0, (Sprite)null, false); } TamePickupPlugin.Log.LogInfo((object)$"Released {carriedData.Prefab} \"{carriedData.Label}\" (token {carriedData.Token})."); } } internal static bool Release(CarriedData data, Vector3 pos, Quaternion rot) { //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown //IL_00d7: 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) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) if (!CarriedData.TryDecodeSnapshot(data.Snapshot, out var bytes, out var prefabHash)) { TamePickupPlugin.Log.LogError((object)("Can't release " + data.Label + ": its snapshot can't be decoded.")); return false; } if ((Object)(object)ZNetScene.instance.GetPrefab(prefabHash) == (Object)null) { TamePickupPlugin.Log.LogError((object)$"Can't release {data.Label}: its prefab {data.Prefab} ({prefabHash}) is unknown."); return false; } ZDO val = ZDOMan.instance.CreateNewZDO(pos, prefabHash); try { val.Deserialize(new ZPackage(bytes)); } catch (Exception arg) { ZDOMan.instance.DestroyZDO(val); TamePickupPlugin.Log.LogError((object)$"Can't release {data.Label}: its snapshot is damaged: {arg}"); return false; } try { val.Set("oddhatter.tamepickup.token", 0L); val.Set(Parking.ReplacesHash, data.Token); val.SetPosition(pos); val.SetRotation(rot); val.Set(Parking.ParkedHash, false); val.Set("oddhatter.tamepickup.parkedBy", 0L); val.Set(ZDOVars.s_follow, ""); val.Set(ZDOVars.s_patrol, true); val.Set(ZDOVars.s_patrolPoint, pos); ZDOMan.instance.ForceSendZDO(val.m_uid); } catch (Exception arg2) { TamePickupPlugin.Log.LogError((object)$"Released {data.Label} ({val.m_uid}) but failed to finish setting it up: {arg2}"); } DeleteOriginal(data, prefabHash, val.m_uid); return true; } private static void DeleteOriginal(CarriedData data, int prefabHash, ZDOID newUid) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) try { if (data.Token == 0L) { TamePickupPlugin.Log.LogWarning((object)(data.Label + " has no carry token (picked up by an older version); its original isn't deleted.")); return; } if (!ZNet.instance.IsServer()) { AddPendingDelete(data, prefabHash); return; } ZDO zDO = ZDOMan.instance.GetZDO(new ZDOID(data.ZdoUser, data.ZdoId)); if (IsOriginal(zDO, data.Token, prefabHash, newUid)) { DestroyHeld(zDO); TamePickupPlugin.Log.LogInfo((object)$"Deleted the original of {data.Label} ({zDO.m_uid}), found by its stored ID."); return; } Stopwatch stopwatch = Stopwatch.StartNew(); int num = 0; zDO = null; foreach (ZDO value in ZDOMan.instance.m_objectsByID.Values) { num++; if (value.GetPrefab() == prefabHash && IsOriginal(value, data.Token, prefabHash, newUid)) { zDO = value; break; } } stopwatch.Stop(); if (zDO != null) { DestroyHeld(zDO); TamePickupPlugin.Log.LogInfo((object)$"Deleted the original of {data.Label} ({zDO.m_uid}), found by the scan ({num} ZDOs, {stopwatch.Elapsed.TotalMilliseconds:F1} ms)."); } else { TamePickupPlugin.Log.LogWarning((object)$"The original of {data.Label} (token {data.Token}) was not found among the {num} ZDOs this game holds; nothing is deleted."); } } catch (Exception arg) { TamePickupPlugin.Log.LogError((object)$"Released {data.Label}, but deleting the original (token {data.Token}) failed; it may still be parked at the spawn: {arg}"); } } private static void AddPendingDelete(CarriedData data, int prefabHash) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { TamePickupPlugin.Log.LogError((object)$"There's no local player to remember the original of {data.Label} (token {data.Token}); it isn't deleted."); return; } long worldUID = ZNet.instance.GetWorldUID(); double timeSeconds = ZNet.instance.GetTimeSeconds(); PendingDeletes.Add(localPlayer.m_customData, data.Token, prefabHash, worldUID, timeSeconds); TamePickupPlugin.Log.LogInfo((object)$"Pending delete {data.Token}:{prefabHash} for the original of {data.Label} (world {worldUID}, time {timeSeconds:F1}): deleted once its replacement has reached the server and it's near."); } private static bool IsOriginal(ZDO zdo, long token, int prefabHash, ZDOID newUid) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (zdo != null && zdo.m_uid != newUid) { return CarriedData.TokenMatches(token, prefabHash, zdo.GetLong(Parking.TokenHash, 0L), zdo.GetPrefab()); } return false; } private static void DestroyHeld(ZDO zdo) { zdo.SetOwner(ZDOMan.GetSessionID()); ZDOMan.instance.DestroyZDO(zdo); } internal static void ResolvePendingDeletes(List<ZDO> currentNearObjects, List<ZDO> currentDistantObjects) { try { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } long sessionID = ZDOMan.GetSessionID(); if (_rollbackCheckedSession == sessionID && localPlayer.m_customData.TryGetValue("oddhatter.tamepickup.pendingDelete", out var value) && !string.IsNullOrEmpty(value)) { if ((object)value != _pendingRaw) { _pendingEntries = PendingDeletes.ForWorld(PendingDeletes.Decode(value), ZNet.instance.GetWorldUID()); _pendingRaw = value; } if (_sightings.ForSession(sessionID)) { _waitLogged.Clear(); } if (_pendingEntries.Count != 0) { bool isServer = ZNet.instance.IsServer(); RecordReplacements(currentNearObjects, isServer, sessionID); RecordReplacements(currentDistantObjects, isServer, sessionID); ResolveIn(localPlayer, currentNearObjects); ResolveIn(localPlayer, currentDistantObjects); } } } catch (Exception arg) { if (!_pendingFailureLogged) { _pendingFailureLogged = true; TamePickupPlugin.Log.LogError((object)$"Resolving pending deletes failed (logged once): {arg}"); } } } internal static void CheckPendingDeletesForRollback() { try { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)ZNet.instance == (Object)null || ZDOMan.instance == null) { return; } long sessionID = ZDOMan.GetSessionID(); if (_rollbackCheckedSession != sessionID) { double timeSeconds = ZNet.instance.GetTimeSeconds(); if (!(timeSeconds <= 0.0)) { DiscardEntriesRolledBackPast(localPlayer, timeSeconds); _rollbackCheckedSession = sessionID; _pendingRaw = null; } } } catch (Exception arg) { if (!_rollbackFailureLogged) { _rollbackFailureLogged = true; TamePickupPlugin.Log.LogError((object)$"Checking pending deletes for a rollback failed (logged once); none resolve until it succeeds: {arg}"); } } } private static void DiscardEntriesRolledBackPast(Player player, double now) { long worldUID = ZNet.instance.GetWorldUID(); List<PendingDeletes.Entry> list = PendingDeletes.DiscardRolledBack(player.m_customData, worldUID, now); foreach (PendingDeletes.Entry item in list) { TamePickupPlugin.Log.LogWarning((object)(item.HasWorldAndTime ? $"Rollback: discarded pending delete {item.Token}:{item.PrefabHash}, dropped at world time {item.DropTime:F1} but the world is at {now:F1}; nothing is deleted, the original stays parked." : $"Discarded pending delete {item.Token}:{item.PrefabHash} from an earlier version (no world or time to check); nothing is deleted.")); } if (list.Count > 0) { CharacterSave.Save("discarding pending deletes"); } } private static void RecordReplacements(List<ZDO> zdos, bool isServer, long session) { //IL_0064: 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) foreach (ZDO zdo in zdos) { if (_pendingEntries.Count == 0) { break; } int prefab = zdo.GetPrefab(); if (PendingDeletes.HasPrefab(_pendingEntries, prefab)) { long num = zdo.GetLong(Parking.ReplacesHash, 0L); if (PendingDeletes.Contains(_pendingEntries, num, prefab) && !_sightings.Seen(num, prefab) && ServerHasReplacement(zdo.m_uid, isServer, session)) { _sightings.Add(num, prefab); TamePickupPlugin.Log.LogInfo((object)$"Saw {zdo.m_uid}, the replacement for pending delete {num}:{prefab}, and the server has it; its original may now be deleted."); } } } } private static bool ServerHasReplacement(ZDOID uid, bool isServer, long session) { //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) return PendingDeletes.ServerHasReplacement(isServer, ((ZDOID)(ref uid)).UserID, session, () => SentToServerOrFalse(uid)); } private static bool SentToServerOrFalse(ZDOID uid) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) try { return SentToServer(uid); } catch (Exception arg) { if (!_sentListFailureLogged) { _sentListFailureLogged = true; TamePickupPlugin.Log.LogError((object)$"Reading the server's sent list failed (logged once); replacements made in this session can't be proven, so their originals stay parked: {arg}"); } return false; } } [MethodImpl(MethodImplOptions.NoInlining)] private static bool SentToServer(ZDOID uid) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); return ((serverPeer != null) ? ZDOMan.instance.FindPeer(serverPeer) : null)?.m_zdos.ContainsKey(uid) ?? false; } private static void ResolveIn(Player player, List<ZDO> zdos) { //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) foreach (ZDO zdo in zdos) { if (_pendingEntries.Count == 0) { break; } int prefab = zdo.GetPrefab(); if (!PendingDeletes.HasPrefab(_pendingEntries, prefab)) { continue; } long num = zdo.GetLong(Parking.TokenHash, 0L); if (!PendingDeletes.Contains(_pendingEntries, num, prefab)) { continue; } if (!_sightings.Seen(num, prefab)) { if (_waitLogged.Add(num)) { TamePickupPlugin.Log.LogInfo((object)$"{zdo.m_uid} is the original for pending delete {num}:{prefab}; it stays parked until its replacement has been seen this session and is known to be on the server."); } } else { DestroyHeld(zdo); PendingDeletes.Remove(player.m_customData, num, prefab); player.m_customData.TryGetValue("oddhatter.tamepickup.pendingDelete", out _pendingRaw); _pendingEntries = PendingDeletes.ForWorld(PendingDeletes.Decode(_pendingRaw), ZNet.instance.GetWorldUID()); TamePickupPlugin.Log.LogInfo((object)$"Deleted {zdo.m_uid}, the original of a released creature (pending delete {num}:{prefab})."); } } } } [BepInPlugin("com.oddhatter.tamepickup", "TamePickup", "1.0.0")] [BepInProcess("valheim.exe")] public sealed class TamePickupPlugin : BaseUnityPlugin { public const string Guid = "com.oddhatter.tamepickup"; public const string Name = "TamePickup"; public const string Version = "1.0.0"; internal static ManualLogSource Log; internal static TamePickupPlugin Instance; internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<KeyCode> PickupKey; internal static ConfigEntry<string> PickupButton; internal static ConfigEntry<float> MaxDistance; private const float ConfigReloadDelay = 0.5f; private Harmony _harmony; private bool _inert; private FileSystemWatcher _configWatcher; private volatile bool _configFileChanged; private float _configReloadAt = -1f; private bool _configLockedLogged; private void Awake() { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Instance = this; Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master switch. When false, pickup and drop are refused with a message, parked creatures appear at their spawn and stay released even after re-enabling, and carried items stay in your pack."); PickupKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "PickupKey", (KeyCode)112, "Look at a creature you tamed and press this key to pick it up into your inventory."); PickupButton = ((BaseUnityPlugin)this).Config.Bind<string>("General", "PickupButton", "JoyRStick", "Gamepad pickup: hold the alt-modifier button (ZInput JoyAltKeys) and press this button. The value is a ZInput button name. Default JoyRStick = hold LT and click the right stick in the default controller layout, a combo the game doesn't use there. In the alternative layouts LB/LT + right stick also toggles crouch and alternative placement; use JoyLTrigger (Alternative 1) or JoyLBumper (Alternative 2) instead. Empty disables gamepad pickup."); MaxDistance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "MaxDistance", 5f, new ConfigDescription("How far away the creature can be, in meters.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 20f), Array.Empty<object>())); _harmony = new Harmony("com.oddhatter.tamepickup"); if (!PatchAllOrNothing()) { return; } foreach (MethodBase patchedMethod in _harmony.GetPatchedMethods()) { Log.LogInfo((object)("Patched " + patchedMethod.DeclaringType?.Name + "." + patchedMethod.Name)); } WatchConfigFile(); Log.LogInfo((object)"TamePickup 1.0.0 loaded."); } private bool PatchAllOrNothing() { try { _harmony.PatchAll(typeof(TamePickupPlugin).Assembly); return true; } catch (Exception arg) { Log.LogError((object)("Patching failed, so TamePickup is turned off (no pickup, no drop, nothing hidden). " + $"Carried creatures appear at their spawn as after an uninstall. Likely a game update changed a patched method: {arg}")); } _inert = true; try { _harmony.UnpatchSelf(); } catch (Exception arg2) { Log.LogError((object)$"Removing the patches that did apply failed too; some may still run: {arg2}"); } Log.LogError((object)"TamePickup 1.0.0 is inactive."); return false; } private void Update() { if (!_inert) { Pickup.UpdateInput(); Placement.ProcessQueue(); if (_configFileChanged) { _configFileChanged = false; _configReloadAt = Time.realtimeSinceStartup + 0.5f; } if (_configReloadAt >= 0f && Time.realtimeSinceStartup >= _configReloadAt) { _configReloadAt = -1f; ReloadConfigFromDisk(); } } } private void OnDestroy() { _configWatcher?.Dispose(); Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private void WatchConfigFile() { string configFilePath = ((BaseUnityPlugin)this).Config.ConfigFilePath; _configWatcher = new FileSystemWatcher(Path.GetDirectoryName(configFilePath), Path.GetFileName(configFilePath)) { NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite), IncludeSubdirectories = false }; _configWatcher.Changed += OnConfigFileEvent; _configWatcher.Created += OnConfigFileEvent; _configWatcher.Renamed += OnConfigFileEvent; _configWatcher.EnableRaisingEvents = true; } private void OnConfigFileEvent(object sender, FileSystemEventArgs e) { _configFileChanged = true; } private void ReloadConfigFromDisk() { if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath)) { return; } bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; try { ((BaseUnityPlugin)this).Config.Reload(); _configLockedLogged = false; Log.LogInfo((object)"Configuration reloaded from disk."); } catch (IOException ex) { if (!_configLockedLogged) { _configLockedLogged = true; Log.LogWarning((object)("Config file busy, will retry: " + ex.Message)); } _configReloadAt = Time.realtimeSinceStartup + 0.5f; } catch (Exception ex2) { Log.LogError((object)("Failed to reload configuration: " + ex2.Message)); } finally { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { internal IgnoresAccessChecksToAttribute(string assemblyName) { } } }