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 HearthShare v1.0.2
HearthShare.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Security.Cryptography; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using Jotunn.Utils; using TMPro; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("HearthShare")] [assembly: AssemblyDescription("Personal persistent treasure for cooperative Valheim exploration")] [assembly: AssemblyFileVersion("1.0.2.0")] [assembly: AssemblyInformationalVersion("1.0.2")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.2.0")] namespace HearthShare; [BepInPlugin("twiggy.hearthshare", "HearthShare", "1.0.2")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(Container), "Awake")] private static class AwakePatch { private static void Postfix(Container __instance) { Attach(__instance); } } [HarmonyPatch(typeof(Container), "Interact")] private static class InteractPatch { [HarmonyPriority(800)] private static bool Prefix(Container __instance, Humanoid character, bool hold, ref bool __result) { if (!Managed(__instance)) { return true; } if (!hold && (Object)(object)character == (Object)(object)Player.m_localPlayer) { Instance.Open(__instance); } __result = true; return false; } } [HarmonyPatch(typeof(Container), "GetHoverText")] private static class HoverPatch { private static bool Prefix(Container __instance, ref string __result) { if (!Managed(__instance)) { return true; } __result = Hover(__instance); return false; } } [HarmonyPatch(typeof(Container), "GetInventory")] private static class InventoryPatch { private static bool Prefix(Container __instance, ref Inventory __result) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (!Managed(__instance)) { return true; } __result = (Inventory)((pinQuery != PinQuery.None) ? PinStatus(__instance) : (((Object)(object)previewChest == (Object)(object)__instance) ? ((object)PreviewShare(__instance)) : ((object)new Inventory("HearthShare protected", (Sprite)null, 1, 1)))); return false; } } [HarmonyPatch] private static class NativeTransferPatch { private static IEnumerable<MethodBase> TargetMethods() { string[] names = new string[9] { "RPC_RequestOpen", "RPC_OpenResponse", "RPC_RequestStack", "RPC_StackResponse", "RPC_RequestTakeAll", "RPC_TakeAllResponse", "DropAllItems", "TakeAll", "StackAll" }; return from m in typeof(Container).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where names.Contains(m.Name) select m; } [HarmonyPriority(800)] private static bool Prefix(Container __instance) { return !Managed(__instance); } } [HarmonyPatch(typeof(Container), "CanBeRemoved")] private static class RemoveContainerPatch { private static void Postfix(Container __instance, ref bool __result) { if (Managed(__instance)) { __result = false; } } } [HarmonyPatch] private static class DamagePatch { private static IEnumerable<MethodBase> TargetMethods() { string[] names = new string[6] { "Damage", "RPC_Damage", "ApplyDamage", "Remove", "RPC_Remove", "Destroy" }; return from m in typeof(WearNTear).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where names.Contains(m.Name) select m; } [HarmonyPriority(800)] private static bool Prefix(WearNTear __instance) { return !Protected((Component)(object)__instance); } } [HarmonyPatch(typeof(WearNTear), "CanBeRemoved")] private static class RemoveWearPatch { private static void Postfix(WearNTear __instance, ref bool __result) { if (Protected((Component)(object)__instance)) { __result = false; } } } [HarmonyPatch(typeof(Player), "TakeInput")] private static class InputPatch { private static void Postfix(ref bool __result) { if (Object.op_Implicit((Object)(object)Instance) && Instance.windowOpen) { __result = false; } } } [HarmonyPatch(typeof(InventoryGui), "UpdateContainer")] private static class PersonalContainerUiPatch { [HarmonyPriority(800)] private static bool Prefix() { if (!Object.op_Implicit((Object)(object)Instance) || !Instance.windowOpen || !Object.op_Implicit((Object)(object)Instance.chestGui)) { return true; } Instance.session.Guard(Instance.RefreshChestUi, Instance.Fault); return false; } } [HarmonyPatch(typeof(InventoryGui), "Hide")] private static class CloseChestUiPatch { private static void Postfix() { if (Object.op_Implicit((Object)(object)Instance) && Instance.windowOpen) { Instance.Close(); } } } [HarmonyPatch(typeof(InventoryGui), "OnTakeAll")] private static class PersonalTakeAllPatch { [HarmonyPriority(800)] private static bool Prefix() { if (!Object.op_Implicit((Object)(object)Instance) || !Instance.windowOpen) { return true; } Instance.session.Guard(Instance.QueueTakeAll, Instance.Fault); return false; } } [HarmonyPatch(typeof(InventoryGui), "OnStackAll")] private static class NoPersonalDepositPatch { [HarmonyPriority(800)] private static bool Prefix() { if (Object.op_Implicit((Object)(object)Instance)) { return !Instance.windowOpen; } return true; } } [HarmonyPatch(typeof(InventoryGui), "OnSelectedItem")] private static class ShiftDepositPatch { [HarmonyPriority(800)] private static bool Prefix(InventoryGui __instance, InventoryGrid grid, ItemData item, Vector2i pos, Modifier mod) { //IL_0054: 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) //IL_0061: Invalid comparison between Unknown and I4 if (!Object.op_Implicit((Object)(object)Instance) || !Instance.windowOpen || (Object)(object)Instance.chestGui != (Object)(object)__instance || !Object.op_Implicit((Object)(object)grid) || !Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return true; } if (Instance.PlaceCarried(__instance, grid, pos)) { return false; } if ((int)mod != 2 || grid.GetInventory() != ((Humanoid)Player.m_localPlayer).GetInventory() || dragItem.GetValue(__instance) != null) { return true; } if (item != null) { Instance.session.Guard(delegate { Instance.Deposit(item, item.m_stack); }, Instance.Fault); } return false; } } [HarmonyPatch(typeof(InventoryGui), "OnDropOutside")] private static class ThrowCarriedPatch { [HarmonyPriority(800)] private static bool Prefix(InventoryGui __instance) { if (Object.op_Implicit((Object)(object)Instance) && Instance.windowOpen) { return !Instance.ThrowCarried(__instance); } return true; } } [HarmonyPatch(typeof(InventoryGui), "OnReleasedItem")] private static class PlaceOnReleasePatch { [HarmonyPriority(800)] private static bool Prefix(InventoryGui __instance, InventoryGrid grid, Vector2i pos) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)Instance) || !Instance.windowOpen || !Object.op_Implicit((Object)(object)grid)) { return true; } return !Instance.PlaceCarried(__instance, grid, pos); } } private enum PinQuery { None, LootedSweep, DungeonCheck } internal const string VanillaRules = "vanilla-v2"; private const int MaxStacks = 64; private const int MaxPreviewChars = 300000; public const string Id = "twiggy.hearthshare"; public const string Version = "1.0.2"; internal static Plugin Instance; private static readonly MethodInfo serverPeer = AccessTools.Method(typeof(ZRoutedRpc), "GetServerPeerID", Type.EmptyTypes, (Type[])null); private readonly WindowSession session = new WindowSession(delegate { }); private ConfigEntry<string> integration; private ConfigEntry<bool> glow; private ConfigEntry<string> marker; private ConfigEntry<float> outlineBrightness; private Harmony harmony; private ZRoutedRpc rpc; private long world; private Player journalPlayer; private ClientLoot loot; private string journalKey = ""; private bool frozen; private string active = ""; private string status = ""; private float queryAt; private const int MaxSent = 8; private const float Resend = 3f; private readonly Dictionary<string, float> sentAt = new Dictionary<string, float>(); private readonly Dictionary<string, Receipt> held = new Dictionary<string, Receipt>(); private readonly Dictionary<string, Vector2i> placeAt = new Dictionary<string, Vector2i>(); private readonly HashSet<string> planned = new HashSet<string>(); private readonly HashSet<string> dropAt = new HashSet<string>(); private List<string> confirmQueue = new List<string>(); private int syncFrom; private bool synced; private float syncAt; private readonly Dictionary<string, LootLedger> ledgers = new Dictionary<string, LootLedger>(); private readonly Dictionary<string, Response> views = new Dictionary<string, Response>(); private readonly Dictionary<long, TokenBucket> rates = new Dictionary<long, TokenBucket>(); private readonly Dictionary<long, TokenBucket> peekRates = new Dictionary<long, TokenBucket>(); private static readonly Dictionary<string, string> hints = new Dictionary<string, string>(); internal const float OpenRange = 8f; internal const float PeekRange = 16f; private readonly HashSet<string> unaddressed = new HashSet<string>(); private const string Help = "Click a stack to pick it up, Shift+click to take it, or Take all. Shift+click your items to store them."; private static MethodInfo abIsBackpack; private static bool abLooked; private InventoryGui chestGui; private Inventory displayInventory; private readonly Dictionary<ItemData, LootStack> displayItems = new Dictionary<ItemData, LootStack>(); private readonly Queue<LootStack> takeQueue = new Queue<LootStack>(); private string displayKey = ""; private int activeWidth; private int activeHeight; private string oldTitle; private string oldWeight; private TMP_Text chestStatus; private bool stackWasActive; private bool takeWasInteractable; private Action<InventoryGrid, ItemData, Vector2i, Modifier> oldSelected; private Action<InventoryGrid, ItemData, Vector2i> oldRight; private Action<InventoryGrid, ItemData, Vector2i> oldReleased; private Action<InventoryGrid, Vector2i> oldEnter; private Func<ItemData, bool> oldCanDrop; private static readonly MethodInfo closeContainer = AccessTools.Method(typeof(InventoryGui), "CloseContainer", Type.EmptyTypes, (Type[])null); private static readonly FieldInfo dragItem = AccessTools.Field(typeof(InventoryGui), "m_dragItem"); private static readonly FieldInfo dragInventory = AccessTools.Field(typeof(InventoryGui), "m_dragInventory"); private static readonly FieldInfo dragAmount = AccessTools.Field(typeof(InventoryGui), "m_dragAmount"); private static readonly MethodInfo setupDrag = AccessTools.Method(typeof(InventoryGui), "SetupDragItem", new Type[3] { typeof(ItemData), typeof(Inventory), typeof(int) }, (Type[])null); private LootStack carrying; private GameObject carryGo; private static Container previewChest; private static Inventory previewInventory; private static string previewKey = ""; private static bool previewSupported; private static FieldInfo previewRect; private static FieldInfo extraSlotsFix; private static MethodInfo extraSlotsHeight; private static readonly MethodInfo receivedChanged = AccessTools.Method(typeof(Inventory), "Changed", new Type[2] { typeof(bool), typeof(bool) }, (Type[])null); private static readonly MethodInfo findEmptySlot = AccessTools.Method(typeof(Inventory), "FindEmptySlot", new Type[1] { typeof(bool) }, (Type[])null); private static readonly MethodInfo topFirst = AccessTools.Method(typeof(Inventory), "TopFirst", new Type[1] { typeof(ItemData) }, (Type[])null); private const int BagWidth = 8; private const int BagHeight = 4; private static PinQuery pinQuery; private static HashSet<string> Supported = ChestCatalog.Build("", "", null); private ConfigEntry<string> additionalChests; private ConfigEntry<string> excludedChests; private bool windowOpen => session.IsOpen; internal bool Glow => glow.Value; internal string Marker => marker.Value; internal float OutlineBrightness => MarkerRules.Brightness(outlineBrightness.Value); private static bool FreeCellApiReady { get { if (findEmptySlot != null) { return topFirst != null; } return false; } } private List<LootStack> Roll(Container template, Vector3 position) { //IL_02f9: 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_0094: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)template == (Object)null) { throw new InvalidOperationException("Chest has no container template."); } State state = Random.state; try { byte[] array = new byte[4]; using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create()) { randomNumberGenerator.GetBytes(array); } Random.InitState(BitConverter.ToInt32(array, 0)); bool num = integration.Value != "Disabled" && EpicLootAdapter.Present; string name = ((Object)((Component)template).gameObject).name; List<ItemData> list = ((template.m_defaultItems != null) ? template.m_defaultItems.GetDropListItems() : new List<ItemData>()); if (num) { list.AddRange(EpicLootAdapter.Roll(name, position)); } List<LootStack> list2 = new List<LootStack>(); int num2 = 2; foreach (ItemData item in list) { string text = ((item != null && Object.op_Implicit((Object)(object)item.m_dropPrefab)) ? ((Object)item.m_dropPrefab).name : "(unknown item)"); if (item == null || !Object.op_Implicit((Object)(object)item.m_dropPrefab)) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("HearthShare: left one stack out of a new roll in " + name + ": " + text + " has no item prefab.")); continue; } int maxStackSize = item.m_shared.m_maxStackSize; int num3 = PickRules.Count(item.m_stack, maxStackSize); if (num3 < 1 || num3 > 1000000 || maxStackSize < 1) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("HearthShare: left one stack out of a new roll in " + name + ": " + text + " has an unsupported quantity (" + num3 + ").")); continue; } while (num3 > 0) { ItemData val = item.Clone(); val.m_stack = Math.Min(num3, maxStackSize); num3 -= val.m_stack; if (list2.Count >= 64) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("HearthShare: a new roll in " + name + " exceeded " + 64 + " stacks; the extra " + text + " was left out.")); break; } LootStack lootStack; try { lootStack = Encode(val); } catch (InvalidDataException ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("HearthShare: left one stack out of a new roll in " + name + ": " + ex.Message)); continue; } int num4 = Codec.Json(lootStack).Length + 1; if (num2 + num4 > 300000) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("HearthShare: a new roll in " + name + " exceeded the preview size limit; " + text + " was left out.")); } else { num2 += num4; list2.Add(lootStack); } } } return list2; } finally { Random.state = state; } } private static string Pack(ItemData item) { //IL_0008: 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) //IL_001c: 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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown Inventory val = new Inventory("HS_Transfer", (Sprite)null, 8, 4); item.m_equipped = false; item.m_gridPos = new Vector2i(0, 0); val.AddItem(item); ZPackage val2 = new ZPackage(); val.Save(val2); return Convert.ToBase64String(val2.GetArray()); } private static ItemData Unpack(string payload) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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_001e: Expected O, but got Unknown Inventory val = new Inventory("HS_Transfer", (Sprite)null, 8, 4); val.Load(new ZPackage(Convert.FromBase64String(payload))); List<ItemData> allItems = val.GetAllItems(); if (allItems.Count != 1) { throw new InvalidDataException("Item dependencies missing or payload invalid. Restore required mods before receiving."); } return allItems[0]; } private static string Difference(ItemData a, ItemData b) { if ((Object.op_Implicit((Object)(object)a.m_dropPrefab) ? ((Object)a.m_dropPrefab).name : "") != (Object.op_Implicit((Object)(object)b.m_dropPrefab) ? ((Object)b.m_dropPrefab).name : "")) { return "prefab"; } if (a.m_stack != b.m_stack) { return "stack " + a.m_stack + " vs " + b.m_stack; } if (a.m_quality != b.m_quality) { return "quality " + a.m_quality + " vs " + b.m_quality; } if (a.m_variant != b.m_variant) { return "variant " + a.m_variant + " vs " + b.m_variant; } if (a.m_worldLevel != b.m_worldLevel) { return "world level " + a.m_worldLevel + " vs " + b.m_worldLevel; } if (a.m_crafterID != b.m_crafterID || a.m_crafterName != b.m_crafterName) { return "crafter"; } if (a.m_customData.Count != b.m_customData.Count) { return "custom data entries " + a.m_customData.Count + " vs " + b.m_customData.Count; } foreach (KeyValuePair<string, string> customDatum in a.m_customData) { if (!b.m_customData.TryGetValue(customDatum.Key, out var value) || value != customDatum.Value) { return "custom data '" + customDatum.Key + "'"; } } return null; } private static LootStack Encode(ItemData item) { string text = (Object.op_Implicit((Object)(object)item.m_dropPrefab) ? ((Object)item.m_dropPrefab).name : "(unknown item)"); ItemData val = item.Clone(); if (val.m_variant > 0 && val.m_variant >= val.m_shared.m_variants) { val.m_variant = 0; } string payload = Pack(val); ItemData once = Unpack(payload); List<string> list = val.m_customData.Keys.Where((string k) => !once.m_customData.ContainsKey(k)).ToList(); if (list.Count > 0) { throw new InvalidDataException(text + " lost custom data (" + string.Join(", ", list) + ") when stored."); } foreach (KeyValuePair<string, string> customDatum in val.m_customData) { if (once.m_customData.TryGetValue(customDatum.Key, out var value) && value != customDatum.Value) { Plugin instance = Instance; if (instance != null) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)("HearthShare: " + text + " custom data '" + customDatum.Key + "' changed on first store (" + (customDatum.Value?.Length ?? 0) + " -> " + (value?.Length ?? 0) + " chars); the stored item holds the reloaded value.")); } } } string payload2 = Pack(once); ItemData val2 = Unpack(payload2); string text2 = Difference(once, val2); if (text2 != null) { throw new InvalidDataException(text + " is not stable when stored: " + text2 + " changes on every reload."); } if (!Object.op_Implicit((Object)(object)val2.m_dropPrefab) || val2.m_stack < 1 || val2.m_stack > val2.m_shared.m_maxStackSize) { throw new InvalidDataException(text + " did not survive storage intact."); } LootStack lootStack = new LootStack { Prefab = ((Object)val2.m_dropPrefab).name, Name = val2.m_shared.m_name, Count = val2.m_stack, Quality = val2.m_quality, Payload = payload2 }; try { LootLedger.ValidateStack(lootStack); return lootStack; } catch (InvalidDataException ex) { throw new InvalidDataException(text + " cannot be stored: " + ex.Message); } } private static ItemData Decode(LootStack stack) { LootLedger.ValidateStack(stack); ItemData val = Unpack(stack.Payload); if (!Object.op_Implicit((Object)(object)val.m_dropPrefab) || ((Object)val.m_dropPrefab).name != stack.Prefab || val.m_stack != stack.Count || val.m_quality != stack.Quality || val.m_stack > val.m_shared.m_maxStackSize) { throw new InvalidDataException("Item changed during decoding."); } return val; } private static long ServerPeer(ZRoutedRpc r) { return (long)serverPeer.Invoke(r, null); } private void Awake() { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Expected O, but got Unknown //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Expected O, but got Unknown Instance = this; integration = ((BaseUnityPlugin)this).Config.Bind<string>("Integration", "EpicLootIntegration", "Auto", new ConfigDescription("Auto uses EpicLoot when it is loaded and its API matches what HearthShare checks at startup (see the log); Enabled requires it. Disabled is ordinary loot only. World boss gating; personal boss tracking is not yet implemented.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Auto", "Enabled", "Disabled" }), Array.Empty<object>())); glow = ((BaseUnityPlugin)this).Config.Bind<bool>("Appearance", "ShowPersonalRuneRing", true, "Show your personal chest marker: pulsing gold unopened, green opened with loot remaining, vanilla when empty. Hover text always available."); marker = ((BaseUnityPlugin)this).Config.Bind<string>("Appearance", "MarkerStyle", "Tint", new ConfigDescription("Tint colors the chest lid itself. Outline draws a rectangle fitted to the lid. Both shows both. Local to you only.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Tint", "Outline", "Both" }), Array.Empty<object>())); outlineBrightness = ((BaseUnityPlugin)this).Config.Bind<float>("Appearance", "OutlineBrightness", 1f, new ConfigDescription("Brightness of the outline marker, from 0.1 (faint) to 1.0 (full). The outline ignores the game's lighting, so lower it if it stands out in dark places. Local to you only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1f), Array.Empty<object>())); BindChestCoverage(); if (serverPeer == null || receivedChanged == null || !FreeCellApiReady) { ((BaseUnityPlugin)this).Logger.LogError((object)"HearthShare disabled: a required game method (GetServerPeerID, Inventory.Changed, FindEmptySlot or TopFirst) was not found in this Valheim version."); Instance = null; return; } harmony = new Harmony("twiggy.hearthshare"); harmony.PatchAll(); PatchPreviewCompatibility(); PatchMapPinCompatibility(); EpicLootAdapter.Initialize(harmony); ((BaseUnityPlugin)this).Logger.LogInfo((object)"HearthShare 1.0.2 loaded. EpicLoot boss gating follows the world's boss kills; personal boss tracking is not implemented."); } private void OnDisable() { Close(); ClearPreview(); } private void OnDestroy() { Close(); ClearPreview(); Harmony obj = harmony; if (obj != null) { obj.UnpatchSelf(); } Instance = null; } private void Fault(Exception e) { Close(); frozen = true; ((Behaviour)this).enabled = false; ((BaseUnityPlugin)this).Logger.LogError((object)("HearthShare stopped after an error; input released. Any delivery your character has not saved is re-delivered on your next connect. " + e)); } internal static string ChestId(Container c) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) ZNetView val = (Object.op_Implicit((Object)(object)c) ? ((Component)c).GetComponent<ZNetView>() : null); if (!Object.op_Implicit((Object)(object)val) || !val.IsValid()) { return ""; } ZDO zDO = val.GetZDO(); string text = KeyOf(zDO); if (text != "") { hints[text] = Key(zDO.m_uid); } return text; } private static string KeyOf(ZDO z) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) GameObject val = ((z != null && Object.op_Implicit((Object)(object)ZNetScene.instance)) ? ZNetScene.instance.GetPrefab(z.GetPrefab()) : null); if (!Object.op_Implicit((Object)(object)val)) { return ""; } Vector3 position = z.GetPosition(); return ChestKey.Make(((Object)val).name, position.x, position.y, position.z); } private static string Hint(string key) { if (!hints.TryGetValue(key, out var value)) { return null; } return value; } private static string Key(ZDOID id) { return ((ZDOID)(ref id)).UserID + ":" + ((ZDOID)(ref id)).ID; } private static bool ParseId(string text, out ZDOID id) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0048: 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) id = default(ZDOID); if (string.IsNullOrEmpty(text) || text.Length > 80) { return false; } string[] array = text.Split(':'); if (array.Length != 2 || !long.TryParse(array[0], out var result) || !uint.TryParse(array[1], out var result2)) { return false; } id = new ZDOID(result, result2); return true; } internal static bool Managed(Container c) { if (!Object.op_Implicit((Object)(object)Instance) || !Object.op_Implicit((Object)(object)c)) { return false; } ZNetView component = ((Component)c).GetComponent<ZNetView>(); if (!Object.op_Implicit((Object)(object)component) || !component.IsValid()) { return false; } ZDO zDO = component.GetZDO(); if (zDO.GetLong("creator", 0L) != 0L) { return false; } GameObject val = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab(zDO.GetPrefab()) : null); if (Object.op_Implicit((Object)(object)val)) { return Supported.Contains(((Object)val).name); } return false; } private static bool Protected(Component c) { if (Object.op_Implicit((Object)(object)c)) { return Managed(c.GetComponent<Container>()); } return false; } private void Update() { if ((Object)(object)Instance == (Object)(object)this) { session.Guard(UpdateSession, Fault); } } private void UpdateSession() { if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZRoutedRpc.instance == null || ZNet.instance.GetWorld() == null) { Reset(); return; } if (rpc != ZRoutedRpc.instance) { Reset(); rpc = ZRoutedRpc.instance; world = ZNet.instance.GetWorldUID(); rpc.Register<string>("HS_Open", (Action<long, string>)OnOpen); rpc.Register<string>("HS_Peek", (Action<long, string>)OnPeek); rpc.Register<string>("HS_Take", (Action<long, string>)OnTake); rpc.Register<string>("HS_Sync", (Action<long, string>)OnSync); rpc.Register<string>("HS_Put", (Action<long, string>)OnPut); rpc.Register<string>("HS_Reply", (Action<long, string>)delegate(long s, string t) { session.Guard(delegate { OnReply(s, t); }, Fault); }); rpc.Register<string>("HS_SyncReply", (Action<long, string>)delegate(long s, string t) { session.Guard(delegate { OnSyncReply(s, t); }, Fault); }); Container[] array = Object.FindObjectsByType<Container>((FindObjectsSortMode)0); for (int num = 0; num < array.Length; num++) { Attach(array[num]); } ReportChestCoverage(); ((BaseUnityPlugin)this).Logger.LogInfo((object)("HearthShare world " + world + " ready. Server=" + ZNet.instance.IsServer() + ". EpicLoot mode=" + integration.Value + ", EpicLoot " + EpicLootAdapter.Describe())); } Player localPlayer = Player.m_localPlayer; if (!Object.op_Implicit((Object)(object)localPlayer)) { return; } if ((Object)(object)journalPlayer != (Object)(object)localPlayer) { Close(); views.Clear(); ClearPreview(); journalPlayer = localPlayer; if (loot != null) { PersistJournal(); } else { ClearTransfers(); frozen = false; journalKey = "twiggy.hearthshare.journal." + world; try { loot = new ClientLoot(localPlayer.m_customData.TryGetValue(journalKey, out var value) ? Codec.Read<ClientJournal>(value) : new ClientJournal()); } catch (Exception ex) { loot = null; frozen = true; ((BaseUnityPlugin)this).Logger.LogError((object)ex); Tell("Character journal unreadable. Loot transfers blocked."); } } } if (windowOpen && (((Character)localPlayer).IsDead() || !NearLocal(active, 8f))) { Close(); } PumpTakeAll(); PumpTransfers(localPlayer); } private void ClearTransfers() { loot = null; sentAt.Clear(); held.Clear(); placeAt.Clear(); planned.Clear(); dropAt.Clear(); confirmQueue = new List<string>(); syncFrom = 0; synced = false; syncAt = 0f; } private void Reset() { if (rpc != null) { Close(); rpc = null; unaddressed.Clear(); world = 0L; ClearTransfers(); journalPlayer = null; frozen = false; ledgers.Clear(); views.Clear(); hints.Clear(); ClearPreview(); rates.Clear(); peekRates.Clear(); active = ""; } } private void PumpTransfers(Player p) { if (loot == null || frozen || ((Character)p).IsDead()) { return; } float now = Time.unscaledTime; if (!synced && now >= syncAt) { syncAt = now + 3f; rpc.InvokeRoutedRPC(ServerPeer(rpc), "HS_Sync", new object[1] { Codec.Json(new SyncRequest { From = syncFrom, Confirm = confirmQueue }) }); } ((Humanoid)p).GetInventory(); foreach (Receipt item in held.Values.ToList()) { Deliver(item); } if (frozen) { return; } int num = sentAt.Count((KeyValuePair<string, float> x) => now - x.Value < 3f && !held.ContainsKey(x.Key)); foreach (TakeRequest item2 in loot.Requests()) { if (!held.ContainsKey(item2.Id) && (!sentAt.TryGetValue(item2.Id, out var value) || !(now - value < 3f))) { if (num >= 8 || (!planned.Contains(item2.Id) && !dropAt.Contains(item2.Id) && num + held.Count > 0 && !Room(num + held.Count, item2.Chest, item2.Entry))) { break; } item2.At = Hint(item2.Chest); sentAt[item2.Id] = now; num++; rpc.InvokeRoutedRPC(ServerPeer(rpc), "HS_Take", new object[1] { Codec.Json(item2) }); } } foreach (PutRequest item3 in loot.Puts()) { if (!sentAt.TryGetValue(item3.Id, out var value2) || !(now - value2 < 3f)) { if (num >= 8) { break; } sentAt[item3.Id] = now; num++; rpc.InvokeRoutedRPC(ServerPeer(rpc), "HS_Put", new object[1] { Codec.Json(item3) }); } } } private void PersistJournal() { Player.m_localPlayer.m_customData[journalKey] = Codec.Json(loot.Journal); } internal void Open(Container c) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) if (session.Faulted) { Player localPlayer = Player.m_localPlayer; if (localPlayer != null) { ((Character)localPlayer).Message((MessageType)2, "HearthShare is paused after an error. Restart the game.", 0, (Sprite)null, false); } } else { if (windowOpen || rpc == null || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || ((Character)Player.m_localPlayer).IsDead() || !PrivateArea.CheckAccess(((Component)c).transform.position, 0f, true, false)) { return; } if (loot != null && !frozen) { try { session.TryOpen(delegate { active = ChestId(c); activeWidth = c.m_width; activeHeight = c.m_height; status = "Reading your treasure..."; BeginChestUi(); rpc.InvokeRoutedRPC(ServerPeer(rpc), "HS_Open", new object[1] { active + "#" + Hint(active) }); }); return; } catch (Exception ex) { Close(); ((BaseUnityPlugin)this).Logger.LogError((object)ex); Tell("Could not open personal treasure. See the log."); return; } } Tell("Character journal unavailable; loot is protected."); } } private void Close() { session.Close(); EndChestUi(); } private void Tell(string s) { status = s; Player localPlayer = Player.m_localPlayer; if (localPlayer != null) { ((Character)localPlayer).Message((MessageType)2, s, 0, (Sprite)null, false); } } private bool NearLocal(string key, float radius) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (!ChestKey.TryParse(key, out var _, out var x, out var y, out var z) || !Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return false; } return Vector3.Distance(new Vector3(x, y, z), ((Component)Player.m_localPlayer).transform.position) <= radius; } private string Actor(long sender) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) if (sender == ZNet.GetUID() && Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return Player.m_localPlayer.GetPlayerID().ToString(); } ZNetPeer peer = ZNet.instance.GetPeer(sender); if (peer == null) { return null; } if (peer.m_playerID != 0L) { return peer.m_playerID.ToString(); } if (((ZDOID)(ref peer.m_characterID)).IsNone() || ZDOMan.instance == null) { return null; } ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID); if (zDO == null || zDO.GetOwner() != sender) { return null; } long num = zDO.GetLong(ZDOVars.s_playerID, 0L); if (num == 0L) { return null; } return num.ToString(); } private bool Rate(long sender, bool peek = false) { if (!Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer()) { return false; } Dictionary<long, TokenBucket> dictionary = (peek ? peekRates : rates); if (!dictionary.TryGetValue(sender, out var value)) { value = (dictionary[sender] = (peek ? new TokenBucket(4f, 10f) : new TokenBucket(24f, 12f))); } return value.Take(Time.unscaledTime); } private Vector3? Where(long sender) { //IL_001e: 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_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) if (sender == ZNet.GetUID() && Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return ((Component)Player.m_localPlayer).transform.position; } ZNetPeer peer = ZNet.instance.GetPeer(sender); if (peer == null) { return null; } ZDO val = ((!((ZDOID)(ref peer.m_characterID)).IsNone() && ZDOMan.instance != null) ? ZDOMan.instance.GetZDO(peer.m_characterID) : null); return (val != null && val.GetOwner() == sender) ? val.GetPosition() : peer.m_refPos; } private Container Authorize(long sender, string key, string hint, out Vector3 at, float range = 8f) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: 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_0061: 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_00c8: 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) at = Vector3.zero; if (!ChestKey.TryParse(key, out var _, out var _, out var _, out var _) || !ParseId(hint, out var id)) { throw new InvalidDataException("Invalid chest."); } ZDO zDO = ZDOMan.instance.GetZDO(id); Vector3? val = Where(sender); if (zDO == null || KeyOf(zDO) != key || !val.HasValue || Vector3.Distance(val.Value, zDO.GetPosition()) > range || zDO.GetLong("creator", 0L) != 0L) { throw new InvalidOperationException("Approach a natural treasure chest."); } GameObject prefab2 = ZNetScene.instance.GetPrefab(zDO.GetPrefab()); if (!Object.op_Implicit((Object)(object)prefab2) || !Supported.Contains(((Object)prefab2).name)) { throw new InvalidOperationException("This chest is not a personal treasure chest."); } at = zDO.GetPosition(); return prefab2.GetComponent<Container>(); } private LootLedger Ledger(string actor) { if (ledgers.TryGetValue(actor, out var value)) { return value; } LedgerFile ledgerFile = new LedgerFile(Path.Combine(Paths.ConfigPath, "HearthShare", world.ToString(), Codec.Hash(actor) + ".loot"), world.ToString(), actor); value = new LootLedger(ledgerFile.Load(), ledgerFile.Save); ledgers.Add(actor, value); return value; } private string IntegrationBlock() { return EpicLootAdapter.Block(integration.Value.Trim()); } private void Send(long sender, Response response) { response.World = world.ToString(); response.Actor = Actor(sender) ?? ""; rpc.InvokeRoutedRPC(sender, "HS_Reply", new object[1] { Codec.Json(response) }); } private Response Snapshot(LootLedger ledger, string chest, bool show = false) { ChestRecord chestRecord = ledger.Peek(chest); int hidden = 0; List<LootStack> items = ((chestRecord == null) ? new List<LootStack>() : LootLedger.Fit(chestRecord.Items.Select((LootStack x) => new LootStack { Id = x.Id, Prefab = x.Prefab, Name = x.Name, Count = x.Count, Quality = x.Quality, Payload = x.Payload }).ToList(), 300000, out hidden)); return new Response { Chest = chest, Show = show, Revision = ledger.Revision, Opened = (chestRecord != null), Items = items, Hidden = hidden }; } private void OnPeek(long sender, string token) { HandleRead(sender, token, open: false); } private void OnOpen(long sender, string token) { HandleRead(sender, token, open: true); } private void HandleRead(long sender, string text, bool open) { if (!Rate(sender, !open) || string.IsNullOrEmpty(text) || text.Length > 400) { return; } int num = text.LastIndexOf('#'); string text2 = ((num < 0) ? text : text.Substring(0, num)); string hint = ((num < 0) ? "" : text.Substring(num + 1)); try { string text3 = Actor(sender); if (text3 == null) { throw new InvalidOperationException("Your character isn't ready on the host yet. Try again in a moment."); } Vector3 at; Container template = Authorize(sender, text2, hint, out at, open ? 8f : 20f); LootLedger lootLedger = Ledger(text3); if (open) { string text4 = IntegrationBlock(); if (text4 != "") { throw new InvalidOperationException(text4); } lootLedger.Open(text2, ((Object)((Component)template).gameObject).name, () => Roll(template, at), (integration.Value != "Disabled" && EpicLootAdapter.Present) ? "epicloot-patched0152-world-v1" : "vanilla-v2"); } Send(sender, Snapshot(lootLedger, text2, open)); } catch (Exception ex) { if (open) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Chest request: " + ex.Message)); } Send(sender, new Response { Chest = text2, Error = ex.Message, Show = open }); } } private void OnTake(long sender, string text) { if (!Rate(sender) || string.IsNullOrEmpty(text) || text.Length > 2048) { return; } TakeRequest takeRequest = null; try { takeRequest = Codec.Read<TakeRequest>(text); string text2 = Actor(sender); if (text2 == null) { throw new InvalidOperationException("Your character isn't ready on the host yet. Try again in a moment."); } LootLedger lootLedger = Ledger(text2); if (lootLedger.Existing(takeRequest.Id) == null) { Authorize(sender, takeRequest.Chest, takeRequest.At, out var _); string text3 = IntegrationBlock(); if (text3 != "") { throw new InvalidOperationException(text3); } } Receipt receipt = lootLedger.Take(takeRequest); Response response = Snapshot(lootLedger, takeRequest.Chest); response.Receipt = receipt; Send(sender, response); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Transfer request: " + ex.Message)); Send(sender, new Response { Chest = (takeRequest?.Chest ?? ""), Error = ex.Message, Failed = takeRequest?.Id }); } } private void OnSync(long sender, string text) { if (!Rate(sender) || string.IsNullOrEmpty(text) || text.Length > 32768) { return; } SyncPage syncPage; try { SyncRequest r = Codec.Read<SyncRequest>(text); string text2 = Actor(sender); if (text2 == null) { throw new InvalidOperationException("Your character isn't ready on the host yet. Try again in a moment."); } syncPage = Ledger(text2).Sync(r); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Sync request: " + ex.Message)); syncPage = new SyncPage { Error = ex.Message }; } syncPage.World = world.ToString(); syncPage.Actor = Actor(sender) ?? ""; rpc.InvokeRoutedRPC(sender, "HS_SyncReply", new object[1] { Codec.Json(syncPage) }); } private void OnSyncReply(long sender, string text) { if (rpc == null || sender != ServerPeer(rpc) || string.IsNullOrEmpty(text) || text.Length > 262144 || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || loot == null || synced) { return; } SyncPage syncPage; try { syncPage = Codec.Read<SyncPage>(text); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("HearthShare sync reply unreadable: " + ex.Message)); return; } if (syncPage.Protocol != 2 || syncPage.World != world.ToString()) { return; } if (syncPage.Actor == "" && syncPage.Error != "") { Unaddressed(syncPage.Error); } else { if (syncPage.Actor != Player.m_localPlayer.GetPlayerID().ToString()) { return; } if (syncPage.Error != "") { ((BaseUnityPlugin)this).Logger.LogWarning((object)("HearthShare sync refused: " + syncPage.Error)); } else { if (syncPage.From != syncFrom) { return; } if (loot.Confirmed(syncPage.Confirmed)) { PersistJournal(); } confirmQueue = loot.Plan(syncPage); syncFrom = syncPage.Next; if (syncPage.More || confirmQueue.Count > 0) { syncAt = 0f; return; } synced = true; if (loot.InFlight > 0) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("HearthShare: re-delivering " + loot.InFlight + " stack(s) your character had not saved yet.")); } } } } private void Take(LootStack item, Vector2i? cell = null, bool isPlanned = false, bool drop = false) { //IL_008b: Unknown result type (might be due to invalid IL or missing references) if (frozen || loot == null || loot.Requested(active, item.Id)) { return; } if (!isPlanned && !drop && !Room(loot.InFlight, active, item.Id)) { status = "No room for that stack. Free a slot first."; return; } TakeRequest takeRequest = loot.Begin(active, item.Id); if (cell.HasValue) { placeAt[takeRequest.Id] = cell.Value; } if (isPlanned) { planned.Add(takeRequest.Id); } if (drop) { dropAt.Add(takeRequest.Id); } status = "Taking your treasure..."; } private void Unaddressed(string error) { if (unaddressed.Add(error)) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("HearthShare: the host could not identify this character and refused: " + error + " (host and every player need the same HearthShare version).")); } } private void OnReply(long sender, string text) { if (rpc == null || sender != ServerPeer(rpc) || string.IsNullOrEmpty(text) || text.Length > 524288 || !Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return; } try { Response response = Codec.Read<Response>(text); if (response.Protocol != 1 || response.World != world.ToString()) { return; } if (response.Actor == "" && response.Error != "") { if (response.Chest == active) { status = "The host refused: " + response.Error; } Unaddressed(response.Error); } else { if (response.Actor != Player.m_localPlayer.GetPlayerID().ToString()) { return; } if (response.Error != "") { if (loot != null && loot.Abandon(response.Failed)) { sentAt.Remove(response.Failed); placeAt.Remove(response.Failed); planned.Remove(response.Failed); dropAt.Remove(response.Failed); } if (response.Chest == active) { status = response.Error; } return; } if (!views.TryGetValue(response.Chest, out var value) || value.Revision <= response.Revision) { views[response.Chest] = response; } if (response.Show && active == response.Chest) { status = ((response.Items.Count == 0) ? "Your share is empty. Shift+click or drag items here to store them." : ((response.Hidden > 0) ? (response.Hidden + ((response.Hidden == 1) ? " more stack appears" : " more stacks appear") + " as you take these.") : "Click a stack to pick it up, Shift+click to take it, or Take all. Shift+click your items to store them.")); } if (response.Deposit != null && loot != null && !frozen && !((Character)Player.m_localPlayer).IsDead()) { SettleDeposit(response.Deposit); } if (!frozen && loot != null && !((Character)Player.m_localPlayer).IsDead() && loot.Expecting(response.Receipt)) { Deliver(response.Receipt); } } } catch (Exception ex) { Close(); frozen = true; Tell("Delivery paused: " + ex.Message); ((BaseUnityPlugin)this).Logger.LogError((object)ex); } } private void Deliver(Receipt receipt) { //IL_0148: Unknown result type (might be due to invalid IL or missing references) Inventory inv = ((Humanoid)Player.m_localPlayer).GetInventory(); ItemData decoded = null; if (receipt.Item != null && !loot.Journal.Applied.Contains(receipt.Id)) { try { decoded = Decode(receipt.Item); } catch (Exception ex) { frozen = true; Close(); Tell("Delivery paused: " + ex.Message + " Your stack stays reserved."); ((BaseUnityPlugin)this).Logger.LogError((object)ex); return; } if (!dropAt.Contains(receipt.Id) && !CanReceive(inv, decoded)) { held[receipt.Id] = receipt; status = "Inventory full. Your stack is reserved and arrives when there is room."; return; } } held.Remove(receipt.Id); sentAt.Remove(receipt.Id); planned.Remove(receipt.Id); bool drop = dropAt.Remove(receipt.Id); Vector2i? cell = null; if (placeAt.TryGetValue(receipt.Id, out var value)) { cell = value; } placeAt.Remove(receipt.Id); try { loot.Accept(receipt, delegate { if (drop) { DropAtFeet(decoded); } else { InsertReceived(inv, decoded, cell); } }, PersistJournal); if (!drop) { NotifyReceived(inv); } } catch (Exception ex2) { frozen = true; Close(); Tell("Delivery paused: " + ex2.Message + " Your stack stays reserved."); ((BaseUnityPlugin)this).Logger.LogError((object)ex2); return; } status = ((receipt.Item == null) ? "That stack is already gone." : (drop ? "Stack dropped." : "Stack received.")); } private static void DropAtFeet(ItemData item) { //IL_0013: 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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_0063: Unknown result type (might be due to invalid IL or missing references) Transform transform = ((Component)Player.m_localPlayer).transform; ItemDrop obj = ItemDrop.DropItem(item, item.m_stack, transform.position + transform.forward + transform.up, transform.rotation); obj.OnPlayerDrop(); Rigidbody component = ((Component)obj).GetComponent<Rigidbody>(); if (Object.op_Implicit((Object)(object)component)) { component.linearVelocity = (transform.forward + Vector3.up) * 5f; } } internal bool Deposit(ItemData item, int amount, bool swap = false) { Player localPlayer = Player.m_localPlayer; if (!windowOpen || frozen || loot == null || !Object.op_Implicit((Object)(object)localPlayer) || ((Character)localPlayer).IsDead() || item == null) { return false; } Inventory inventory = ((Humanoid)localPlayer).GetInventory(); if (!inventory.ContainsItem(item)) { return false; } if (!views.TryGetValue(active, out var value) || !value.Opened) { status = "Wait for your treasure to load."; return false; } if (item.m_shared.m_questItem) { status = "That item can't be stored."; return false; } if (HoldsInventory(item)) { status = "Backpacks and other items that hold items can't be stored here."; return false; } if (!swap && value.Items.Count + value.Hidden + loot.Putting(active) >= 32) { status = "This chest is full."; return false; } amount = Math.Max(1, Math.Min(amount, item.m_stack)); ((Humanoid)localPlayer).RemoveEquipAction(item); ((Humanoid)localPlayer).UnequipItem(item, false); ItemData val = item.Clone(); val.m_stack = amount; LootStack item2; try { item2 = Encode(val); } catch (InvalidDataException ex) { status = "That item can't be stored: " + ex.Message; return false; } int stack = item.m_stack; bool flag = amount == stack; bool flag2 = false; PutRequest putRequest = loot.BeginPut(active, item2); PersistJournal(); try { if (flag) { inventory.RemoveItem(item); } else { inventory.RemoveItem(item, amount); } } finally { flag2 = (flag ? (!inventory.ContainsItem(item)) : (item.m_stack == stack - amount)); if (!flag2) { loot.CancelPut(putRequest.Id); PersistJournal(); } } status = "Storing..."; return flag2; } internal void Swap(ItemData bagItem, LootStack chestStack) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) if (!frozen && loot != null && !loot.Requested(active, chestStack.Id)) { Vector2i gridPos = bagItem.m_gridPos; if (gridPos.x >= 8 || gridPos.y >= 4) { status = "Swap with an item in your main bag."; } else if (Deposit(bagItem, bagItem.m_stack, swap: true)) { Take(chestStack, gridPos, isPlanned: true); status = "Swapping..."; } } } private void SettleDeposit(Deposit d) { Inventory inv = ((Humanoid)Player.m_localPlayer).GetInventory(); bool inBag = false; bool num = loot.Settle(d, delegate(LootStack stack) { ItemData item = Decode(stack); if (CanReceive(inv, item)) { InsertReceived(inv, item); inBag = true; } else { DropAtFeet(item); } }, PersistJournal); if (inBag) { NotifyReceived(inv); } if (num) { sentAt.Remove(d.Id); if (d.Chest == active) { status = (d.Accepted ? "Stored." : (d.Reason + " Your item was returned.")); } } } private static bool HoldsInventory(ItemData item) { if (!abLooked) { abLooked = true; Type type = AccessTools.TypeByName("AdventureBackpacks.API.ABAPI"); abIsBackpack = ((type == null) ? null : AccessTools.Method(type, "IsBackpack", new Type[1] { typeof(ItemData) }, (Type[])null)); } try { if (abIsBackpack != null && (bool)abIsBackpack.Invoke(null, new object[1] { item })) { return true; } } catch (Exception) { return true; } return ItemRules.InventoryKey(item.m_customData.Keys); } private static string VerifyDeposit(LootStack stack) { try { ItemData val = Decode(stack); return val.m_shared.m_questItem ? "That item can't be stored." : (HoldsInventory(val) ? "Backpacks and other items that hold items can't be stored here." : null); } catch (Exception) { return "That item can't be stored here."; } } private void OnPut(long sender, string text) { if (!Rate(sender) || string.IsNullOrEmpty(text) || text.Length > 140000) { return; } PutRequest putRequest = null; try { putRequest = Codec.Read<PutRequest>(text); string text2 = Actor(sender); if (text2 == null) { throw new InvalidOperationException("Your character isn't ready on the host yet. Try again in a moment."); } LootLedger lootLedger = Ledger(text2); Deposit deposit = lootLedger.Put(putRequest, VerifyDeposit); Response response = Snapshot(lootLedger, putRequest.Chest); response.Deposit = deposit; Send(sender, response); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Deposit request: " + ex.Message)); Send(sender, new Response { Chest = (putRequest?.Chest ?? ""), Error = ex.Message }); } } private bool Room(int outstanding, string chest, string entry) { Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory(); if (inventory.GetEmptySlots() > outstanding) { return true; } if (outstanding > 0 || !views.TryGetValue(chest, out var value)) { return false; } LootStack lootStack = value.Items.FirstOrDefault((LootStack x) => x.Id == entry); GameObject val = ((lootStack != null && Object.op_Implicit((Object)(object)ObjectDB.instance)) ? ObjectDB.instance.GetItemPrefab(lootStack.Prefab) : null); if (Object.op_Implicit((Object)(object)(Object.op_Implicit((Object)(object)val) ? val.GetComponent<ItemDrop>() : null))) { return CanReceive(inventory, Decode(lootStack)); } return false; } internal Response View(Container c) { views.TryGetValue(ChestId(c), out var value); return value; } internal bool Query(Container c) { if (rpc == null || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || (Object)(object)journalPlayer != (Object)(object)Player.m_localPlayer || windowOpen || Time.unscaledTime < queryAt) { return false; } queryAt = Time.unscaledTime + 0.25f; string text = ChestId(c); rpc.InvokeRoutedRPC(ServerPeer(rpc), "HS_Peek", new object[1] { text + "#" + Hint(text) }); return true; } internal static void Diagnostic(string s) { if (Object.op_Implicit((Object)(object)Instance)) { ((BaseUnityPlugin)Instance).Logger.LogInfo((object)s); } } internal static void Attach(Container c) { if (Managed(c) && !Object.op_Implicit((Object)(object)((Component)c).GetComponent<ChestVisual>())) { ((Component)c).gameObject.AddComponent<ChestVisual>(); } } internal static string Hover(Container c) { Response response = Instance.View(c); return "HearthShare treasure\n[<color=yellow>E</color>] Open your share\n" + ((response == null) ? "Checking your treasure..." : ((!response.Opened) ? "Unopened treasure" : ((response.Items.Count > 0) ? "Treasure remaining" : "Emptied"))); } private void BeginChestUi() { //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) InventoryGui instance = InventoryGui.instance; if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)instance.ContainerGrid) || closeContainer == null || dragItem == null || dragInventory == null || dragAmount == null || setupDrag == null) { throw new InvalidOperationException("Native chest UI unavailable."); } closeContainer.Invoke(instance, null); instance.Show((Container)null, 1); chestGui = instance; oldTitle = instance.m_containerName.text; oldWeight = instance.m_containerWeight.text; InventoryGrid containerGrid = instance.ContainerGrid; oldSelected = containerGrid.m_onSelected; oldRight = containerGrid.m_onRightClick; oldReleased = containerGrid.m_onReleased; oldEnter = containerGrid.m_onEnter; oldCanDrop = containerGrid.CanDropDragOntoItem; containerGrid.m_onSelected = delegate(InventoryGrid g, ItemData item, Vector2i pos, Modifier mod) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 if (!DepositDragged(item)) { if ((int)mod == 2) { ChooseDisplayItem(item); } else { PickUp(item); } } }; containerGrid.m_onRightClick = delegate { StopCarry(); }; containerGrid.m_onReleased = delegate(InventoryGrid g, ItemData item, Vector2i pos) { DepositDragged(item); }; containerGrid.m_onEnter = delegate { }; containerGrid.CanDropDragOntoItem = (ItemData item) => false; stackWasActive = ((Component)instance.m_stackAllButton).gameObject.activeSelf; takeWasInteractable = ((Selectable)instance.m_takeAllButton).interactable; ((Component)instance.m_stackAllButton).gameObject.SetActive(false); chestStatus = Object.Instantiate<TMP_Text>(instance.m_containerName, (Transform)(object)instance.m_container); ((Object)chestStatus).name = "HearthShare.Status"; chestStatus.font = instance.m_containerWeight.font; chestStatus.fontSize = 17f; ((Graphic)chestStatus).raycastTarget = false; chestStatus.alignment = (TextAlignmentOptions)514; chestStatus.textWrappingMode = (TextWrappingModes)1; RectTransform rectTransform = chestStatus.rectTransform; rectTransform.anchorMin = new Vector2(0f, 0f); rectTransform.anchorMax = new Vector2(1f, 0f); rectTransform.pivot = new Vector2(0.5f, 1f); rectTransform.anchoredPosition = new Vector2(0f, -4f); rectTransform.sizeDelta = new Vector2(-20f, 58f); displayKey = ""; RefreshChestUi(); containerGrid.ResetView(); } private void EndChestUi() { //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Expected O, but got Unknown StopCarry(); takeQueue.Clear(); displayItems.Clear(); displayInventory = null; displayKey = ""; if (Object.op_Implicit((Object)(object)chestStatus)) { ((Component)chestStatus).gameObject.SetActive(false); Object.Destroy((Object)(object)((Component)chestStatus).gameObject); } chestStatus = null; if (Object.op_Implicit((Object)(object)chestGui)) { InventoryGui obj = chestGui; chestGui = null; InventoryGrid containerGrid = obj.ContainerGrid; if (Object.op_Implicit((Object)(object)containerGrid)) { containerGrid.m_onSelected = oldSelected; containerGrid.m_onRightClick = oldRight; containerGrid.m_onReleased = oldReleased; containerGrid.m_onEnter = oldEnter; containerGrid.CanDropDragOntoItem = oldCanDrop; containerGrid.UpdateInventory(new Inventory("", (Sprite)null, 8, 4), (Player)null, (ItemData)null); } ((Component)obj.m_stackAllButton).gameObject.SetActive(stackWasActive); ((Selectable)obj.m_takeAllButton).interactable = takeWasInteractable; obj.m_containerName.text = oldTitle; obj.m_containerWeight.text = oldWeight; ((Component)obj.m_container).gameObject.SetActive(false); } } private void RefreshChestUi() { //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Expected O, but got Unknown //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)chestGui) || !windowOpen) { return; } views.TryGetValue(active, out var value); string text = active + ":" + (value?.Revision ?? (-1)); if (displayInventory == null || text != displayKey) { displayKey = text; displayItems.Clear(); List<LootStack> list = ((value != null && value.Opened) ? value.Items : new List<LootStack>()); ChestGrid.Size(activeWidth, activeHeight, list.Count, out var width, out var height); displayInventory = new Inventory("Personal treasure", (Sprite)null, width, height); for (int i = 0; i < list.Count; i++) { LootStack lootStack = list[i]; GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(lootStack.Prefab); if (!Object.op_Implicit((Object)(object)(Object.op_Implicit((Object)(object)itemPrefab) ? itemPrefab.GetComponent<ItemDrop>() : null))) { throw new InvalidOperationException("Missing item prefab: " + lootStack.Prefab); } ItemData val = Decode(lootStack); val.m_gridPos = new Vector2i(i % width, i / width); displayInventory.GetAllItems().Add(val); displayItems.Add(val, lootStack); } } ((Component)chestGui.m_container).gameObject.SetActive(true); chestGui.m_containerName.text = "Personal treasure"; chestGui.m_containerWeight.text = ""; chestGui.ContainerGrid.UpdateInventory(displayInventory, (Player)null, (ItemData)null); ((Selectable)chestGui.m_takeAllButton).interactable = !frozen && loot != null && takeQueue.Count == 0 && displayItems.Count > 0; UpdateCarry(); if (Object.op_Implicit((Object)(object)chestStatus)) { chestStatus.text = ((loot != null && (loot.InFlight > 0 || takeQueue.Count > 0)) ? "Receiving your items…" : status); } } private void PickUp(ItemData item) { if (windowOpen && !frozen && loot != null && takeQueue.Count <= 0) { if (item == null || !displayItems.TryGetValue(item, out var value) || (carrying != null && carrying.Id == value.Id)) { StopCarry(); } else if (!loot.Requested(active, value.Id)) { StopCarry(); carrying = value; carryGo = Object.Instantiate<GameObject>(chestGui.m_dragItemPrefab, ((Component)chestGui).transform); ((Component)carryGo.transform.Find("icon")).GetComponent<Image>().sprite = item.GetIcon(); ((Component)carryGo.transform.Find("name")).GetComponent<TMP_Text>().text = item.m_shared.m_name; ((Component)carryGo.transform.Find("amount")).GetComponent<TMP_Text>().text = ((item.m_stack > 1) ? item.m_stack.ToString() : ""); status = "Click a slot in your inventory to place it, or outside to drop it. Right-click to cancel."; UpdateCarry(); } } } private void UpdateCarry() { //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) if (carrying != null) { Response value; bool flag = views.TryGetValue(active, out value) && value.Items.Any((LootStack x) => x.Id == carrying.Id); if (!Object.op_Implicit((Object)(object)chestGui) || !Object.op_Implicit((Object)(object)carryGo) || !flag || loot == null || frozen || loot.Requested(active, carrying.Id) || dragItem.GetValue(chestGui) != null) { StopCarry(); } else if (ZInput.GetMouseButton(1) || ZInput.GetButton("JoyButtonB")) { StopCarry(); status = "Click a stack to pick it up, Shift+click to take it, or Take all. Shift+click your items to store them."; } else { carryGo.transform.position = (Vector3)(ZInput.IsMouseActive() ? ZInput.pointerPosition : new Vector3(-99999f, 0f, 0f)); } } } private void StopCarry() { carrying = null; if (Object.op_Implicit((Object)(object)carryGo)) { Object.Destroy((Object)(object)carryGo); } carryGo = null; } private bool PlaceCarried(InventoryGui gui, InventoryGrid grid, Vector2i pos) { //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) if (carrying == null || (Object)(object)chestGui != (Object)(object)gui) { return false; } if ((Object)(object)grid != (Object)(object)gui.m_playerGrid) { status = "Place it in your main inventory grid."; return true; } LootStack record = carrying; StopCarry(); session.Guard(delegate { //IL_0074: 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) ItemData itemAt = grid.GetInventory().GetItemAt(pos.x, pos.y); if (itemAt != null && !PreferredCell(grid.GetInventory(), Decode(record), pos, out var _)) { Swap(itemAt, record); } else { Take(record, pos); } }, Fault); return true; } private bool ThrowCarried(InventoryGui gui) { if (carrying == null || (Object)(object)chestGui != (Object)(object)gui) { return false; } LootStack record = carrying; StopCarry(); session.Guard(delegate { Take(record, null, isPlanned: false, drop: true); }, Fault); return true; } private bool DepositDragged(ItemData target) { if (!Object.op_Implicit((Object)(object)chestGui) || !Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return false; } ItemData item = default(ItemData); ref ItemData reference = ref item; object? value = dragItem.GetValue(chestGui); reference = (ItemData)((value is ItemData) ? value : null); if (item == null) { return false; } object? value2 = dragInventory.GetValue(chestGui); object? obj = ((value2 is Inventory) ? value2 : null); int amount = (int)dragAmount.GetValue(chestGui); LootStack record = null; if (target != null) { displayItems.TryGetValue(target, out record); } if (obj != ((Humanoid)Player.m_localPlayer).GetInventory()) { status = "Only items from your inventory can be stored."; } else if (record != null && amount >= item.m_stack && takeQueue.Count == 0 && !Mergeable(item, Decode(record))) { session.Guard(delegate { Swap(item, record); }, Fault); } else { session.Guard(delegate { Deposit(item, amount); }, Fault); } setupDrag.Invoke(chestGui, new object[3] { null, null, 1 }); return true; } private void ChooseDisplayItem(ItemData item) { if (!windowOpen || frozen || loot == null || takeQueue.Count > 0) { return; } StopCarry(); session.Guard(delegate { if (item != null && displayItems.TryGetValue(item, out var value)) { Take(value); } }, Fault); } private void QueueTakeAll() { if (!windowOpen || frozen || loot == null || takeQueue.Count > 0) { return; } StopCarry(); if (!views.TryGetValue(active, out var value)) { return; } foreach (LootStack item in value.Items) { if (!loot.Requested(active, item.Id)) { takeQueue.Enqueue(item); } } } private void PumpTakeAll() { if (!windowOpen || frozen) { takeQueue.Clear(); } else { if (loot == null || takeQueue.Count == 0 || loot.InFlight > held.Count) { return; } Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory(); List<ItemData> list = (from r in held.Values where r.Item != null select Decode(r.Item)).ToList(); List<LootStack> list2 = takeQueue.ToList(); takeQueue.Clear(); List<ItemData> items = list.Concat(list2.Select(Decode)).ToList(); bool[] array = PlanBatch(inventory, items, list.Count); int num = 0; for (int num2 = 0; num2 < list2.Count; num2++) { if (array[num2]) { Take(list2[num2], null, isPlanned: true); } else { num++; } } if (num > 0) { status = "Inventory full. " + num + ((num == 1) ? " stack stays" : " stacks stay") + " here."; } } } private static void ClearPreview() { previewInventory = null; previewKey = ""; previewChest = null; } private void PatchPreviewCompatibility() { //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Expected O, but got Unknown //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Expected O, but got Unknown //IL_0159: Expected O, but got Unknown //IL_0159: Expected O, but got Unknown Type type = AccessTools.TypeByName("ContentsPreview.HoverPatch"); Type type2 = AccessTools.TypeByName("ContentsPreview.PreviewPanel"); MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "CanPreview", new Type[1] { typeof(Container) }, (Type[])null)); MethodInfo methodInfo2 = ((type2 == null) ? null : AccessTools.Method(type2, "Show", new Type[1] { typeof(Container) }, (Type[])null)); if (!(methodInfo == null)) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Plugin), "PreviewAllowed", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); previewRect = ((type2 == null) ? null : AccessTools.Field(type2, "_clonedPanelRect")); extraSlotsHeight = AccessTools.Method(AccessTools.TypeByName("ExtraSlots.API"), "GetInventoryHeightPlayer", Type.EmptyTypes, (Type[])null); Type type3 = AccessTools.TypeByName("ExtraSlots.ExtraSlots"); extraSlotsFix = ((type3 == null) ? null : AccessTools.Field(type3, "fixContainerPosition")); if (methodInfo2 != null) { harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(Plugin), "BeginPreview", (Type[])null), new HarmonyMethod(typeof(Plugin), "AlignPreview", (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "EndPreview", (Type[])null), (HarmonyMethod)null); previewSupported = true; ((BaseUnityPlugin)this).Logger.LogInfo((object)"HearthShare: ContentsPreview shows your own share on opened personal chests."); } else { ((BaseUnityPlugin)this).Logger.LogInfo((object)"HearthShare: ContentsPreview hidden on personal chests (its preview panel was not found)."); } } } private static bool PreviewAllowed(Container container, ref bool __result) { if (!Managed(container)) { return true; } Response response = Instance.View(container); __result = previewSupported && response != null && response.Opened && !InventoryGui.IsVisible(); return false; } private static void BeginPreview(Container container) { previewChest = container; } private static void AlignPreview(object __instance) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) try { object? obj = previewRect?.GetValue(__instance); RectTransform val = (RectTransform)((obj is RectTransform) ? obj : null); RectTransform val2 = (Object.op_Implicit((Object)(object)InventoryGui.instance) ? InventoryGui.instance.m_container : null); if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val2)) { return; } Vector2 pivot = val2.pivot; if (extraSlotsHeight != null) { ConfigEntry<bool> obj2 = extraSlotsFix?.GetValue(null) as ConfigEntry<bool>; if (obj2 != null && obj2.Value) { ((Vector2)(ref pivot))..ctor(0f, 1f + (float)((int)extraSlotsHeight.Invoke(null, null) - 4) * 0.2f); } } if (val.pivot != pivot) { val.pivot = pivot; } } catch (Exception) { } } private static Exception EndPreview(Exception __exception) { previewChest = null; return __exception; } private static Inventory PreviewShare(Container chest) { //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Expected O, but got Unknown //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) Response response = (Object.op_Implicit((Object)(object)Instance) ? Instance.View(chest) : null); if (response == null || !response.Opened || !Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return new Inventory("HearthShare protected", (Sprite)null, 1, 1); } string text = ChestKey.ViewCache(Instance.world.ToString(), Player.m_localPlayer.GetPlayerID().ToString(), ChestId(chest), response.Revision); if (previewInventory != null && text == previewKey) { return previewInventory; } ChestGrid.Size(chest.m_width, chest.m_height, response.Items.Count, out var width, out var height); Inventory val = new Inventory("Personal treasure", (Sprite)null, width, height); try { for (int i = 0; i < response.Items.Count; i++) { ItemData val2 = Decode(response.Items[i]); val2.m_gridPos = new Vector2i(i % width, i / width); val.GetAllItems().Add(val2); } } catch (Exception ex) { ((BaseUnityPlugin)Instance).Logger.LogWarning((object)("HearthShare: preview of your share unavailable: " + ex.Message)); val = new Inventory("HearthShare protected", (Sprite)null, 1, 1); } previewKey = text; previewInventory = val; return val; } private static Vector2i FreeCell(Inventory inv, ItemData item) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) bool flag = (bool)topFirst.Invoke(inv, new object[1] { item }); return (Vector2i)findEmptySlot.Invoke(inv, new object[1] { flag }); } private static bool SameData(Dictionary<string, string> a, Dictionary<string, string> b) { if (a.Count != b.Count) { return false; } foreach (KeyValuePair<string, string> item in a) { if (!b.TryGetValue(item.Key, out var value) || value != item.Value) { return false; } } return true; } private static bool Mergeable(ItemData a, ItemData b) { if (SameData(a.m_customData, b.m_customData) && (Object)(object)a.m_dropPrefab == (Object)(object)b.m_dropPrefab && a.m_quality == b.m_quality && a.m_worldLevel == b.m_worldLevel && a.m_variant == b.m_variant && a.m_crafterID == b.m_crafterID && a.m_crafterName == b.m_crafterName && a.m_durability == b.m_durability && a.m_shared.m_maxStackSize == b.m_shared.m_maxStackSize) { return a.m_cheated == b.m_cheated; } return false; } private static List<KeyValuePair<ItemData, int>> PlanReceipt(Inventory inv, ItemData item, out int remaining) { remaining = item.m_stack; List<KeyValuePair<ItemData, int>> list = new List<KeyValuePair<ItemData, int>>(); foreach (ItemData allItem in inv.GetAllItems()) { if (remaining == 0) { break; } if (Mergeable(allItem, item)) { int num = Math.Min(remaining, Math.Max(0, allItem.m_shared.m_maxStackSize - allItem.m_stack)); if (num > 0) { list.Add(new KeyValuePair<ItemData, int>(allItem, num)); remaining -= num; } } } return list; } private static bool[] PlanBatch(Inventory inv, IList<ItemData> items, int reserved) { List<ItemData> list = new List<ItemData>(); List<int> list2 = new List<int>(); foreach (ItemData allItem in inv.GetAllItems()) { list.Add(allItem); list2.Add(Math.Max(0, allItem.m_shared.m_maxStackSize - allItem.m_stack)); } int num = inv.GetEmptySlots(); bool[] array = new bool[Math.Max(0, items.Count - reserved)]; for (int i = 0; i < items.Count; i++) { ItemData val = items[i]; int num2 = val.m_stack; int[] array2 = new int[list.Count]; for (int j = 0; j < list.Count; j++) { if (num2 <= 0) { break; } if (Mergeable(list[j], val)) { array2[j] = Math.Min(num2, list2[j]); num2 -= array2[j]; } } bool flag = num2 == 0 || num > 0; if (flag) { for (int k = 0; k < array2.Length; k++) { list2[k] -= array2[k]; } if (num2 > 0) { num--; list.Add(val); list2.Add(Math.Max(0, val.m_shared.m_maxStackSize - num2)); } } if (i >= reserved) { array[i - reserved] = flag; } } return array; } private static bool CanReceive(Inventory inv, ItemData item) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) PlanReceipt(inv, item, out var remaining); if (remaining != 0) { return FreeCell(inv, item).x >= 0; } return true; } private static bool PreferredCell(Inventory inv, ItemData item, Vector2i? want, out ItemData target) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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_0028: 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) //IL_0053: 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) target = null; if (!want.HasValue) { return false; } Vector2i value = want.Value; if (value.x < 0 || value.y < 0 || value.x >= Math.Min(8, inv.GetWidth()) || value.y >= Math.Min(4, inv.GetHeight())) { return false; } ItemData itemAt = inv.GetItemAt(value.x, value.y); if (itemAt == null) { return true; } if (Mergeable(itemAt, item) && itemAt.m_shared.m_maxStackSize - itemAt.m_stack >= item.m_stack) { target = itemAt; return true; } return false; } private static void InsertReceived(Inventory inv, ItemData item, Vector2i? want = null) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_004c: 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_002b: 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_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) if (PreferredCell(inv, item, want, out var target)) { if (target != null) { ItemData obj = target; obj.m_stack += item.m_stack; } else { item.m_gridPos = want.Value; inv.GetAllItems().Add(item); } return; } int remaining; List<KeyValuePair<ItemData, int>> list = PlanReceipt(inv, item, out remaining); Vector2i val = (Vector2i)((remaining > 0) ? FreeCell(inv, item) : new Vector2i(-1, -1)); if (remaining > 0 && val.x < 0) { throw new InvalidOperationException("Inventory space became unavailable."); } if (remaining > 0) { item.m_gridPos = val; item.m_stack = remaining; inv.GetAllItems().Add(item); } foreach (KeyValuePair<ItemData, int> item2 in list) { ItemData key = item2.Key; key.m_stack += item2.Value; } } private static void NotifyReceived(Inventory inv) { try { receivedChanged.Invoke(inv, new object[2] { false, false }); } catch (Exception ex) { if (Object.op_Implicit((Object)(object)Instance)) { ((BaseUnityPlugin)Instance).Logger.LogWarning((object)("Inventory refresh failed after committed delivery: " + ex.GetBaseException().Message)); } } } private void PatchMapPinCompatibility() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown Type type = AccessTools.TypeByName("CarturMapPins.PinPlacer"); if (!(type == null)) { MethodInfo methodInfo = AccessTools.Method(type, "SweepLootedChests", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(type, "LootLeftInInterior", (Type[])null, (Type[])null); HarmonyMethod val = new HarmonyMethod(typeof(Plugin), "EndPinQuery", (Type[])null); if (methodInfo != null) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Plugin), "BeginLootedSweep", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null); } if (methodInfo2 != null) { harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(Plugin), "BeginDungeonCheck", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null); } ((BaseUnityPlugin)this).Logger.LogInfo((object)("HearthShare: Cartur's Map Pins chest and dungeon status now follow your own personal share" + ((methodInfo == null || methodInfo2 == null) ? " (partially: a Cartur method was not found)." : "."))); } } private static void BeginLootedSweep() { pinQuery = PinQuery.LootedSweep; } private static void BeginDungeonCheck() { pinQuery = PinQuery.DungeonCheck; } private static Exception EndPinQuery(Exception __exception) { pinQuery = PinQuery.None; return __exception; } private static Inventory PinStatus(Container chest) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown Response response = (Object.op_Implicit((Object)(object)Instance) ? Instance.View(chest) : null); if (response == null && pinQuery == PinQuery.LootedSweep) { return null; } Inventory val = new Inventory("HearthShare map status", (Sprite)null, 1, 1); if (response == null || !response.Opened || response.Items.Count > 0) { val.GetAllItems().Add(new ItemData()); } return val; } private void BindChestCoverage() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown additionalChests = ((BaseUnityPlugin)this).Config.Bind<string>("Chests", "AdditionalChests", "", new ConfigDescription("Comma-separated chest prefab names to make personal as well (for example chests added by other mods). Quest chests (*_hildir, TreasureMapChest_*) are always left shared. Server controls this.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); excludedChests = ((BaseUnityPlugin)this).Config.Bind<string>("Chests", "ExcludedChests", "", new ConfigDescription("Comma-separated chest prefab names to leave as ordinary shared chests. Server controls this.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); additionalChests.SettingChanged += delegate { RebuildChests(); }; excludedChests.SettingChanged += delegate { RebuildChests(); }; RebuildChests(); } private void RebuildChests() { List<string> list = new List<string>(); Supported = ChestCatalog.Build(additionalChests.Value, excludedChests.Value, list); if (list.Count > 0) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("HearthShare: quest chests stay shared and were not added: " + string.Join(", ", list))); } if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { Container[] array = Object.FindObjectsByType<Container>((FindObjectsSortMode)0); for (int i = 0; i < array.Length; i++) { Attach(array[i]); } } } private void ReportChestCoverage() { ZNetScene scene = ZNetScene.instance; if (!Object.op_Implicit((Object)(object)scene)) { return; } List<string> list = Supported.ToList(); List<string> list2 = list.Where((string n) => Object.op_Implicit((Object)(object)scene.GetPrefab(n))).ToList(); List<string> list3 = (from x in list.Except(list2) orderby x select x).ToList(); if (list3.Count > 0) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("HearthShare: listed chest types not in this game (ignored): " + string.Join(", ", list3))); } HashSet<string> buildable = new HashSet<string>(); if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { foreach (GameObject item in ObjectDB.instance.m_items) { ItemDrop val = (Object.op_Implicit((Object)(object)item) ? item.GetComponent<ItemDrop>() : null); PieceTable val2 = (Object.op_Implicit((Object)(object)val) ? val.m_itemData.m_shared.m_buildPieces : null); if (!Object.op_Implicit((Object)(object)val2)) { continue; } foreach (GameObject piece in val2.m_pieces) { if (Object.op_Implicit((Object)(object)piece)) { buildable.Add(((Object)piece).name); } } } } List<string> list4 = (from p in scene.m_prefabs where Object.op_Implicit((Object)(object)p) && Object.op_Implicit((Object)(object)p.GetComponent<Container>()) && !Supported.Contains(((Object)p).name) && !buildable.Contains(((Object)p).name) select ((Object)p).name + (ChestCatalog.IsQuest(((Object)p).name) ? " (quest)" : "") into x orderby x select x).ToList(); ((BaseUnityPlugin)this).Logger.LogInfo((object)("HearthShare: " + list2.Count + " personal chest types active.")); if (list4.Count > 0) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("HearthShare: other non-buildable containers left shared (add natural ones to AdditionalChests): " + string.Join(", ", list4))); } } } [DataContract] public sealed class LootStack { [DataMember] public string Id = ""; [DataMember] public string Prefab = ""; [DataMember] public string Name = ""; [DataMember] public string Payload = ""; [DataMember] public int Count; [DataMember] public int Quality = 1; } [DataContract] public sealed class ChestRecord { [DataMember] public string Id = ""; [DataMember] public string Prefab = ""; [DataMember] public string Rules = "vanilla-only-v1"; [DataMember] public List<LootStack> Items = new List<LootStack>(); } [DataContract] public sealed class TakeRequest { [DataMember] public string Id = ""; [DataMember] public string Chest = ""; [DataMember] public string Entry = ""; [DataMember(EmitDefaultValue = false)] public string At; } public static class ItemRules { public static bool InventoryKey(IEnumerable<string> customDataKeys) { return customDataKeys?.Any((string k) => k != null && (k.IndexOf("inventory", StringComparison.OrdinalIgnoreCase) >= 0 || k.IndexOf("backpack", StringComparison.OrdinalIgnoreCase) >= 0)) ?? false; } } public static class ChestGrid { public const int MaxWidth = 8; public const int FallbackWidth = 8; public const int FallbackHeight = 4; public static void Size(int chestWidth, int chestHeight, int count, out int width, out int height) { bool flag = chestWidth >= 1 && chestHeight >= 1; width = (flag ? Math.Min(8, chestWidth) : 8); int val = (flag ? chestHeight : 4); height = Math.Max(val, (Math.Max(0, count) + width - 1) / width); } } public static class MarkerRules { public const float MinBrightness = 0.1f; public static float Brightness(float value) { if (!float.IsNaN(value)) { return Math.Max(0.1f, Math.Min(1f, value)); } return 1f; } } public static class PickRules { public static int Count(int rolled, int maxStack) { if (maxStack != 1 || rolled <= 1) { return rolled; } return 1; } } public static class ChestKey { public static string ViewCache(string world, string actor, string chest, long revision) { return world + "|" + actor + "|" + chest + "|" + revision; } public static string Make(string prefab, float x, float y, float z) { if (string.IsNullOrEmpty(prefab) || prefab.Contains("@")) { return ""; } return prefab + "@" + F(x) + "," + F(y) + "," + F(z); } private static string F(float v) { string text = Math.Round(v, 2, MidpointRounding.AwayFromZero).ToString("0.00", CultureInfo.InvariantCulture); if (!(text == "-0.00")) { return text; } return "0.00"; } public static bool TryParse(string key, out string prefab, out float x, out float y, out float z) { prefab = ""; x = (y = (z = 0f)); if (string.IsNullOrEmpty(key) || key.Length > 256) { return false; } int num = key.IndexOf('@'); if (num < 1 || num != key.LastIndexOf('@')) { return false; } string[] array = key.Substring(num + 1).Split(','); if (array.Length != 3) { return false; } CultureInfo invariantCulture = CultureInfo.InvariantCulture; NumberStyles style = NumberStyles.Float; if (!float.TryParse(array[0], style, invariantCulture, out x) || !float.TryParse(array[1], style, invariantCulture, out y) || !float.TryParse(array[2], style, invariantCulture, out z)) { return false; } prefab = key.Substring(0, num); return Make(prefab, x, y, z) == key; } } [DataContract] public sealed class Receipt { [DataMember] public string Id = ""; [DataMember] public string Chest = ""; [DataMember] public string Entry = ""; [DataMember] public LootStack Item; [DataMember(EmitDefaultValue = false)] public bool Confirmed; } [DataContract] public sealed class PutRequest { [DataMember] public string Id = ""; [DataMember] public string Chest = ""; [DataMember] public LootStack Item; } [DataContract] public sealed class Deposit { [DataMember] public string Id = ""; [DataMember] public string Chest = ""; [DataMember] public bool Accepted; [DataMember] public string Reason = ""; } [DataContract] public sealed class DeliveryRef { [DataMember] public string Id = ""; [DataMember] public string Chest = ""; [DataMember] public string Entry = ""; } [DataContract] public sealed class SyncRequest { [DataMember] public int From; [DataMember] public List<string> Confirm = new List<string>(); } [DataContract] public sealed class SyncPage { [DataMember] public int Protocol = 2; [DataMember] public string World = ""; [DataMember] public string Actor = ""; [DataMember] public string Error = ""; [DataMember] public int From; [DataMember] public int Next; [DataMember] public bool More; [DataMember] public List<DeliveryRef> Refs = new List<DeliveryRef>(); [DataMember] public List<string> Confirmed = new List<string>(); } [DataContract] public sealed class PlayerLedgerState { [DataMember] public int Schema = 2; [DataMember] public string World = ""; [DataMember] public string Actor = ""; [DataMember] public long Revision; [DataMember] public List<ChestRecord> Chests = new List<ChestRecord>(); [DataMember] public List<Receipt> Receipts = new List<Receipt>(); [DataMember(EmitDefaultValue = false)] public List<Deposit> Deposits = new List<Deposit>(); } [DataContract] public sealed class Response { [DataMember] public int Protocol = 1; [DataMember] public string World = ""; [DataMember] public string Actor = ""; [DataMember] public string Chest = ""; [DataMember] public string Error = ""; [DataMember] public long Revision; [DataMember] public bool Opened; [DataMember] public bool Show; [DataMember] public List<LootStack> Items = new List<LootStack>(); [DataMember] public Receipt Receipt; [DataMember(EmitDefaultValue = false)] public string Failed; [DataMember(EmitDefaultValue = false)] public Deposit Deposit; [DataMember(EmitDefaultValue = false)] public int Hidden; } [DataContract] public sealed class ClientJournal { [DataMember] public TakeRequest Pending; [DataMember] public List<string> Applied = new List<string>(); [DataMember(EmitDefaultValue = false)] public List<PutRequest> Outbox = new List<PutRequest>(); } public sealed class ClientLoot { private readonly HashSet<string> loaded = new HashSet<string>(); private readonly Dictionary<string, TakeRequest> inFlight = new Dictionary<string, TakeRequest>(); public ClientJournal Journal { get; private set; } public int InFlight => inFlight.Count; public ClientLoot(ClientJournal journal) { if (journal == null || journal.Applied == null) { throw new InvalidDataException("Invalid client delivery journal."); } if (journal.Outbox == null) { journal.Outbox = new List<PutRequest>(); } Journal = journal; foreach (string item in journal.Applied) { loaded.Add(item); } if (journal.Pending != null && !journal.Applied.Contains(journal.Pending.Id)) { inFlight[journal.Pending.Id] = Codec.Copy(journal.Pending); } else { journal.Pending = null; } } public List<TakeRequest> Requests() { return inFlight.Values.Select(Codec.Copy).ToList(); } public bool Requested(string chest, string entry) { return inFlight.Values.Any((TakeRequest x) => x.Chest == chest && x.Entry == entry); } public TakeRequest Begin(string chest, string entry) { TakeRequest takeRequest = new TakeRequest { Id = Guid.NewGuid().ToString("N"), Chest = chest, Entry = entry }; inFlight.Add(takeRequest.Id, takeRequest); return Codec.Copy(takeRequest); } public bool Expecting(Receipt r) { if (r != null && inFlight.TryGetValue(r.Id, out var value) && value.Chest == r.Chest) { return value.Entry == r.Entry; } return false; } public bool Accept(Receipt r, Action<LootStack> insert, Action persist) { if (!Expecting(r)) { return false; } bool result = false; if (r.Item != null && !Journal.Applied.Contains(r.Id)) { insert(Codec.Copy(r.Item)); Journal.Applied.Add(r.Id); result = true; } inFlight.Remove(r.Id); if (Journal.Pending != null && Journal.Pending.Id == r.Id) { Journal.Pending = null; } persist(); return result; } public bool Abandon(string id) { if (string.IsNullOrEmpty(id) || !inFlight.Remove(id)) { return false; } if (Journal.Pending != null && Journal.Pending.Id == id) { Journal.Pending = null; } return true; } public List<string> Plan(SyncPage page) { List<string> list = new List<string>(); foreach (DeliveryRef @ref in page.Refs) { if (loaded.Contains(@ref.Id)) { list.Add(@ref.Id); } else if (!Journal.Applied.Contains(@ref.Id) && !inFlight.ContainsKey(@ref.Id)) { inFlight[@ref.Id] = new TakeRequest { Id = @ref.Id, Chest = @ref.Chest, Entry = @ref.Entry }; } } return list; } public bool Confirmed(IEnumerable<string> ids) { bool flag = false; foreach (string id in ids) { flag |= Journal.Applied.Remove(id); loaded.Remove(id); } return flag; } public PutRequest BeginPut(string chest, LootStack item) { if (string.IsNullOrEmpty(chest) || item == null) { throw new InvalidDataException("Invalid deposit."); } PutRequest putRequest = new PutRequest { Id = Guid.NewGuid().ToString("N"), Chest = chest, Item = Codec.Copy(item) }; Journal.Outbox.Add(putRequest); return Codec.Copy(putRequest); } public List<PutRequest> Puts() { return Journal.Outbox.Select(Codec.Copy).ToList(); } public bool CancelPut(string id) { PutRequest putRequest = Journal.Outbox.FirstOrDefault((PutRequest x) => x.Id == id); if (putRequest != null) { return Journal.Outbox.Remove(putRequest); } return false; } public int Putting(string chest) { return Journal.Outbox.Count((PutRequest x) => x.Chest == chest); } public bool Settle(Deposit d, Action<LootStack> refund, Action persist) { if (d == null) { return false; } PutRequest putRequest = Journal.Outbox.FirstOrDefault((PutRequest x) => x.Id == d.Id); if (putRequest == null || putRequest.Chest != d.Chest) { return false; } if (!d.Accepted) { refund(Codec.Copy(putRequest.Item)); } Journal.Outbox.Remove(putRequest); persist(); return true; } } public sealed class TokenBucket { private readonly float capacity; private readonly float perSecond; private float tokens; private float last; private bool started; public TokenBucket(float capacity, float perSecond) { this.capacity = capacity; this.perSecond = perSecond; tokens = capacity; } public bool Take(float now) { if (started) { tokens = Math.Min(capacity, tokens + Math.Max(0f, now - last) * perSecond); } started = true; last = now; if (tokens < 1f) { return false; } tokens -= 1f; return true; } } public static class ChestCatalog { public static readonly string[] Natural = new string[26] { "TreasureChest_meadows", "TreasureChest_meadows_01", "TreasureChest_meadows_02", "TreasureChest_meadows_buried", "TreasureChest_meadows_combat", "TreasureChest_memorial_buried", "TreasureChest_blackforest", "TreasureChest_forestcrypt", "TreasureChest_fCrypt", "TreasureChest_trollcave", "TreasureChest_swamp", "TreasureChest_sunkencrypt", "TreasureChest_mountains", "TreasureChest_mountaincave", "TreasureChest_heath", "TreasureChest_plains_stone", "TreasureChest_dvergrtown", "TreasureChest_dvergrtower", "TreasureChest_dvergr_loose_stone", "TreasureChest_ashland_stone", "TreasureChest_charredfortress", "TreasureChest_deepnorth_village", "TreasureChest_morkhalla", "Morkhalla_ChestAncient", "shipwreck_karve_chest", "shipwreck_vikingship_chest" }; public static bool IsQuest(string name) { if (!name.EndsWith("_hildir", StringComparison.OrdinalIgnoreCase)) { return name.StartsWith("TreasureMapChest_", StringComparison.OrdinalIgnoreCase); } return true; } public static IEnumerable<string> Split(string list) { return from x in (list ?? "").Split(new char[3] { ',', ';', '\n' }, StringSplitOptions.RemoveEmptyEntries) select x.Trim() into x where x.Length > 0 select x; } public static HashSet<string> Build(string additional, string excluded, List<string> refused) { HashSet<string> hashSet = new HashSet<string>(Natural, StringComparer.OrdinalIgnoreCase); foreach (string item in Split(additional)) { if (IsQuest(item)) { refused?.Add(item); } else { hashSet.Add(item); } } foreach (string item2 in Split(excluded)) { hashSet.Remove(item2); } return hashSet; } } public static class Codec { public static string Json<T>(T value) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) using MemoryStream memoryStream = new MemoryStream(); ((XmlObjectSerializer)new DataContractJsonSerializer(typeof(T))).WriteObject((Stream)memoryStream, (object)value); return Encoding.UTF8.GetString(memoryStream.ToArray()); } public static T Read<T>(string text) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) using MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(text)); return (T)((XmlObjectSerializer)new DataContractJsonSerializer(typeof(T))).ReadObject((Stream)memoryStream); } public static T Copy<T>(T value) { return Read<T>(Json(value)); } public static string Hash(string text) { using SHA256