Decompiled source of FreshDedicatedStorage v2.4.3

BepInEx/plugins/JuStIIFrEsH-FreshDedicatedStorage/FreshStorage.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("FreshStorage")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("2.4.3.0")]
[assembly: AssemblyInformationalVersion("2.4.3+b4ff4061bbebfbb02df761ee9b7ca4202fef71bb")]
[assembly: AssemblyProduct("FreshStorage")]
[assembly: AssemblyTitle("FreshStorage")]
[assembly: AssemblyVersion("2.4.3.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace JuStIIFrEsH.Valheim.FreshDedicatedStorage
{
	internal static class BuildheimBridge
	{
		private sealed class ObservedBox
		{
			internal BulkBox Box;

			internal string Name;

			internal int Count = -1;
		}

		private sealed class BuildSpend
		{
			internal Player Player;

			internal Dictionary<string, int> Missing;
		}

		private const string Guid = "augusdogus.Buildheim";

		private const float DefaultBuildRange = 20f;

		private static readonly Dictionary<object, Dictionary<string, ObservedBox>> Observed = new Dictionary<object, Dictionary<string, ObservedBox>>();

		private static Harmony harmony;

		private static FieldInfo checklistField;

		private static FieldInfo assistanceInstance;

		private static MethodInfo observeMethod;

		private static MethodInfo assistanceActive;

		private static PropertyInfo targetPlayer;

		private static PropertyInfo targetPiece;

		private static bool warned;

		private static int placementScope;

		private static int targetScope;

		private static Container[] nearbyContainers = Array.Empty<Container>();

		private static float nextContainerScan;

		private static ZNetScene containerScene;

		internal static void Install()
		{
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Expected O, but got Unknown
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Expected O, but got Unknown
			//IL_035a: Unknown result type (might be due to invalid IL or missing references)
			//IL_035f: Unknown result type (might be due to invalid IL or missing references)
			//IL_037c: Expected O, but got Unknown
			if (!Chainloader.PluginInfos.TryGetValue("augusdogus.Buildheim", out var value))
			{
				return;
			}
			try
			{
				Assembly assembly = ((object)value.Instance).GetType().Assembly;
				Type type = assembly.GetType("PlanBuild.Client.ChestObservation", throwOnError: true);
				Type type2 = assembly.GetType("PlanBuild.Client.MaterialChecklist", throwOnError: true);
				Type type3 = assembly.GetType("PlanBuild.Client.HammerTarget", throwOnError: true);
				Type type4 = assembly.GetType("PlanBuild.Client.HammerAssistance", throwOnError: true);
				checklistField = AccessTools.Field(type, "checklist");
				observeMethod = AccessTools.Method(type2, "Observe", new Type[2]
				{
					typeof(string),
					typeof(IEnumerable<KeyValuePair<string, int>>)
				}, (Type[])null);
				assistanceInstance = AccessTools.Field(type4, "instance");
				assistanceActive = AccessTools.Method(type4, "Active", new Type[1] { typeof(Player) }, (Type[])null);
				targetPlayer = AccessTools.Property(type3, "Player");
				targetPiece = AccessTools.Property(type3, "Piece");
				MethodInfo methodInfo = AccessTools.Method(type, "Update", (Type[])null, (Type[])null);
				MethodInfo methodInfo2 = AccessTools.Method(type, "Dispose", (Type[])null, (Type[])null);
				MethodInfo methodInfo3 = AccessTools.Method(type3, "HasInventoryResources", (Type[])null, (Type[])null);
				MethodInfo methodInfo4 = AccessTools.Method(type3, "MissingMaterialsError", (Type[])null, (Type[])null);
				MethodInfo methodInfo5 = AccessTools.PropertyGetter(type3, "RequirementsMet");
				MethodInfo methodInfo6 = AccessTools.Method(typeof(Player), "UpdatePlacement", (Type[])null, (Type[])null);
				MethodInfo methodInfo7 = AccessTools.Method(typeof(Player), "HaveRequirements", new Type[2]
				{
					typeof(Piece),
					typeof(RequirementMode)
				}, (Type[])null);
				MethodInfo methodInfo8 = AccessTools.Method(typeof(Player), "ConsumeResources", (Type[])null, (Type[])null);
				if (checklistField == null || observeMethod == null || assistanceInstance == null || assistanceActive == null || targetPlayer == null || targetPiece == null || methodInfo == null || methodInfo2 == null || methodInfo3 == null || methodInfo4 == null || methodInfo5 == null || methodInfo6 == null || methodInfo7 == null || methodInfo8 == null)
				{
					throw new MissingMethodException("Buildheim 1.2.x compatibility surface changed.");
				}
				harmony = new Harmony("justiifresh.valheim.freshdedicatedstorage.buildheim");
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, Patch("AfterObservation"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, Patch("AfterDispose"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, Patch("HasBuildMaterials"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, Patch("MissingBuildMaterials"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo5, Patch("BeginTarget"), (HarmonyMethod)null, (HarmonyMethod)null, Patch("EndTarget"), (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo6, new HarmonyMethod(typeof(BuildheimBridge), "BeginPlacement", (Type[])null)
				{
					priority = 800
				}, (HarmonyMethod)null, (HarmonyMethod)null, Patch("EndPlacement"), (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo7, (HarmonyMethod)null, Patch("HaveBuildRequirements"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo8, new HarmonyMethod(typeof(BuildheimBridge), "BeginSpend", (Type[])null)
				{
					priority = 800
				}, Patch("EndSpend"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Logger.LogInfo((object)"Optional Buildheim storage checklist and autobuild bridge enabled.");
			}
			catch (Exception ex)
			{
				Uninstall();
				Logger.LogWarning((object)("Buildheim integration disabled; dedicated storage remains unchanged: " + ex));
			}
		}

		internal static void Uninstall()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			harmony = null;
			Observed.Clear();
			placementScope = (targetScope = 0);
			nearbyContainers = Array.Empty<Container>();
			nextContainerScan = 0f;
			containerScene = null;
		}

		private static HarmonyMethod Patch(string name)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return new HarmonyMethod(typeof(BuildheimBridge), name, (Type[])null);
		}

		private static bool Active(Player player)
		{
			if (!ZNet.IsSinglePlayer || !Object.op_Implicit((Object)(object)player) || (Object)(object)player != (Object)(object)Player.m_localPlayer)
			{
				return false;
			}
			try
			{
				object value = assistanceInstance.GetValue(null);
				return value != null && (bool)assistanceActive.Invoke(value, new object[1] { player });
			}
			catch (Exception error)
			{
				Warn(error);
				return false;
			}
		}

		private static void Warn(Exception error)
		{
			if (!warned)
			{
				warned = true;
				Logger.LogWarning((object)("Buildheim integration unavailable for this session: " + error));
			}
		}

		private static void AfterObservation(object __instance)
		{
			if (!ZNet.IsSinglePlayer || !Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return;
			}
			try
			{
				if (!Observed.TryGetValue(__instance, out var value))
				{
					Observed.Add(__instance, value = new Dictionary<string, ObservedBox>());
				}
				foreach (BulkBox item in Boxes(Player.m_localPlayer))
				{
					ZNetView component = ((Component)item).GetComponent<ZNetView>();
					if (Object.op_Implicit((Object)(object)item) && Object.op_Implicit((Object)(object)component) && component.IsValid() && item.TryGetStoredMaterial(out var _, out var count) && count > 0)
					{
						string key = ((object)Unsafe.As<ZDOID, ZDOID>(ref component.GetZDO().m_uid)/*cast due to .constrained prefix*/).ToString();
						if (!value.ContainsKey(key))
						{
							value.Add(key, new ObservedBox
							{
								Box = item
							});
						}
					}
				}
				object value2 = checklistField.GetValue(__instance);
				foreach (KeyValuePair<string, ObservedBox> item2 in value)
				{
					ObservedBox value3 = item2.Value;
					if (Object.op_Implicit((Object)(object)value3.Box) && value3.Box.TryGetStoredMaterial(out var name2, out var count2) && (value3.Count != count2 || !(value3.Name == name2)))
					{
						IEnumerable<KeyValuePair<string, int>> enumerable = ((count2 <= 0 || string.IsNullOrEmpty(name2)) ? ((IEnumerable<KeyValuePair<string, int>>)Array.Empty<KeyValuePair<string, int>>()) : ((IEnumerable<KeyValuePair<string, int>>)new KeyValuePair<string, int>[1]
						{
							new KeyValuePair<string, int>(name2, count2)
						}));
						observeMethod.Invoke(value2, new object[2] { item2.Key, enumerable });
						value3.Name = name2;
						value3.Count = count2;
					}
				}
			}
			catch (Exception error)
			{
				Warn(error);
			}
		}

		private static void AfterDispose(object __instance)
		{
			Observed.Remove(__instance);
		}

		private static void BeginTarget(object __instance, out bool __state)
		{
			__state = false;
			try
			{
				object? value = targetPlayer.GetValue(__instance);
				Player val = (Player)((value is Player) ? value : null);
				if (ZNet.IsSinglePlayer && !((Object)(object)val != (Object)(object)Player.m_localPlayer))
				{
					targetScope++;
					__state = true;
				}
			}
			catch (Exception error)
			{
				Warn(error);
			}
		}

		private static Exception EndTarget(Exception __exception, bool __state)
		{
			if (__state)
			{
				targetScope--;
			}
			return __exception;
		}

		private static void BeginPlacement(Player __instance, out bool __state)
		{
			__state = Active(__instance);
			if (__state)
			{
				placementScope++;
			}
		}

		private static Exception EndPlacement(Exception __exception, bool __state)
		{
			if (__state)
			{
				placementScope--;
			}
			return __exception;
		}

		private static IEnumerable<BulkBox> Boxes(Player player)
		{
			float range = 20f;
			bool leaveOne = false;
			StoreAndCraftBridge.TryGetCraftSettings(player, out range, out leaveOne, 20f);
			float rangeSquared = range * range;
			return BulkBox.Active.Where(delegate(BulkBox box)
			{
				//IL_0016: 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_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				if (Object.op_Implicit((Object)(object)box) && ((Behaviour)box).isActiveAndEnabled)
				{
					Vector3 val = ((Component)box).transform.position - ((Component)player).transform.position;
					if (((Vector3)(ref val)).sqrMagnitude <= rangeSquared)
					{
						return PrivateArea.CheckAccess(((Component)box).transform.position, 0f, false, false);
					}
				}
				return false;
			}).OrderBy(delegate(BulkBox box)
			{
				//IL_0006: 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_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val = ((Component)box).transform.position - ((Component)player).transform.position;
				return ((Vector3)(ref val)).sqrMagnitude;
			});
		}

		private static IEnumerable<Container> Containers(Player player)
		{
			if ((Object)(object)containerScene != (Object)(object)ZNetScene.instance || Time.time >= nextContainerScan)
			{
				containerScene = ZNetScene.instance;
				nearbyContainers = Resources.FindObjectsOfTypeAll<Container>();
				nextContainerScan = Time.time + 0.5f;
			}
			float range = 20f;
			StoreAndCraftBridge.TryGetCraftSettings(player, out range, out var _, 20f);
			float rangeSquared = range * range;
			return nearbyContainers.Where(delegate(Container container)
			{
				//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_0092: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00de: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e4: Invalid comparison between Unknown and I4
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
				if (Object.op_Implicit((Object)(object)container) && ((Behaviour)container).isActiveAndEnabled)
				{
					Scene scene = ((Component)container).gameObject.scene;
					if (((Scene)(ref scene)).IsValid() && ((Component)container).gameObject.activeInHierarchy && !Object.op_Implicit((Object)(object)((Component)container).GetComponentInParent<BulkBox>()) && !container.IsInUse() && (!Object.op_Implicit((Object)(object)container.m_wagon) || !container.m_wagon.InUse()) && container.IsOwner() && container.GetInventory() != null)
					{
						Vector3 val = ((Component)container).transform.position - ((Component)player).transform.position;
						if (((Vector3)(ref val)).sqrMagnitude <= rangeSquared && (!container.m_checkGuardStone || PrivateArea.CheckAccess(((Component)container).transform.position, 0f, false, false)))
						{
							if ((int)container.m_privacy != 2)
							{
								if ((int)container.m_privacy == 0)
								{
									Piece component = ((Component)container).GetComponent<Piece>();
									return ((component != null) ? new long?(component.GetCreator()) : ((long?)null)) == player.GetPlayerID();
								}
								return false;
							}
							return true;
						}
					}
				}
				return false;
			}).OrderBy(delegate(Container container)
			{
				//IL_0006: 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_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val = ((Component)container).transform.position - ((Component)player).transform.position;
				return ((Vector3)(ref val)).sqrMagnitude;
			});
		}

		private static int BoxCount(Player player, string name, int quality)
		{
			bool leaveOne = false;
			StoreAndCraftBridge.TryGetCraftSettings(player, out var _, out leaveOne, 20f);
			long num = 0L;
			foreach (BulkBox item in Boxes(player))
			{
				num += item.CraftAvailable(name, quality, leaveOne);
				if (num >= int.MaxValue)
				{
					return int.MaxValue;
				}
			}
			return (int)num;
		}

		private static int StoredCount(Player player, string name, int quality)
		{
			if (StoreAndCraftBridge.TryCountNearby(player, name, quality, out var count))
			{
				return count;
			}
			long num = BoxCount(player, name, quality);
			foreach (Container item in Containers(player))
			{
				num += item.GetInventory().CountItems(name, quality, true);
				if (num >= int.MaxValue)
				{
					return int.MaxValue;
				}
			}
			return (int)num;
		}

		private static int Available(Player player, string name, int quality = -1)
		{
			long num = (from item in ((Humanoid)player).GetInventory().GetAllItems()
				where item.m_shared.m_name == name && (quality < 0 || item.m_quality == quality) && item.m_worldLevel >= Game.m_worldLevel
				select item).Sum((Func<ItemData, long>)((ItemData item) => item.m_stack));
			return (int)Math.Min(2147483647L, num + StoredCount(player, name, quality));
		}

		private static Dictionary<string, int> Costs(Requirement[] requirements, int qualityLevel, int multiplier = 1)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			Requirement[] array = requirements ?? Array.Empty<Requirement>();
			checked
			{
				foreach (Requirement val in array)
				{
					if (val != null && Object.op_Implicit((Object)(object)val.m_resItem))
					{
						int num = val.GetAmount(qualityLevel) * Math.Max(1, multiplier);
						if (num > 0)
						{
							string name = val.m_resItem.m_itemData.m_shared.m_name;
							dictionary.TryGetValue(name, out var value);
							dictionary[name] = value + num;
						}
					}
				}
				return dictionary;
			}
		}

		private static void HasBuildMaterials(object __instance, ref bool __result)
		{
			if (__result || !ZNet.IsSinglePlayer)
			{
				return;
			}
			try
			{
				Player player = default(Player);
				ref Player reference = ref player;
				object? value = targetPlayer.GetValue(__instance);
				reference = (Player)((value is Player) ? value : null);
				if (!Object.op_Implicit((Object)(object)player) || (Object)(object)player != (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				object? value2 = targetPiece.GetValue(__instance);
				Piece val = (Piece)((value2 is Piece) ? value2 : null);
				if (Object.op_Implicit((Object)(object)val))
				{
					__result = Costs(val.m_resources, 0).All((KeyValuePair<string, int> cost) => Available(player, cost.Key) >= cost.Value);
				}
			}
			catch (Exception error)
			{
				Warn(error);
			}
		}

		private static void MissingBuildMaterials(object __instance, ref string __result)
		{
			if (__result == null || !ZNet.IsSinglePlayer)
			{
				return;
			}
			try
			{
				Player player = default(Player);
				ref Player reference = ref player;
				object? value = targetPlayer.GetValue(__instance);
				reference = (Player)((value is Player) ? value : null);
				if (!Object.op_Implicit((Object)(object)player) || (Object)(object)player != (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				object? value2 = targetPiece.GetValue(__instance);
				Piece val = (Piece)((value2 is Piece) ? value2 : null);
				if (Object.op_Implicit((Object)(object)val))
				{
					var array = (from cost in Costs(val.m_resources, 0)
						select new
						{
							Key = cost.Key,
							Amount = cost.Value - Available(player, cost.Key)
						} into cost
						where cost.Amount > 0
						select cost).ToArray();
					__result = ((array.Length == 0) ? null : (Localization.instance.Localize(val.m_name) + ": missing " + string.Join(", ", array.Select(cost => cost.Amount + " " + Localization.instance.Localize(cost.Key))) + " nearby."));
				}
			}
			catch (Exception error)
			{
				Warn(error);
			}
		}

		private static void HaveBuildRequirements(Player __instance, Piece piece, RequirementMode mode, ref bool __result)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			if (__result || !ZNet.IsSinglePlayer || (placementScope <= 0 && targetScope <= 0) || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || !Object.op_Implicit((Object)(object)piece) || (int)mode != 0)
			{
				return;
			}
			try
			{
				if ((!Object.op_Implicit((Object)(object)piece.m_craftingStation) || Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(piece.m_craftingStation.m_name, ((Component)__instance).transform.position)) || ZoneSystem.instance.GetGlobalKey((GlobalKeys)27)) && (piece.m_dlc.Length <= 0 || DLCMan.instance.IsDLCInstalled(piece.m_dlc)))
				{
					__result = Costs(piece.m_resources, 0).All((KeyValuePair<string, int> cost) => Available(__instance, cost.Key) >= cost.Value);
				}
			}
			catch (Exception error)
			{
				Warn(error);
			}
		}

		private static void BeginSpend(Player __instance, Requirement[] requirements, int qualityLevel, int itemQuality, int multiplier, out BuildSpend __state)
		{
			__state = null;
			if (placementScope <= 0 || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			BuildSpend buildSpend = (__state = new BuildSpend
			{
				Player = __instance
			});
			if (__instance.PlacementCostDisabled || StoreAndCraftBridge.TryGetCraftSettings(__instance, out var _, out var _, 20f))
			{
				return;
			}
			try
			{
				Dictionary<string, int> source = Costs(requirements, qualityLevel, multiplier);
				buildSpend.Missing = source.ToDictionary((KeyValuePair<string, int> entry) => entry.Key, (KeyValuePair<string, int> entry) => Math.Max(0, entry.Value - ((Humanoid)__instance).GetInventory().CountItems(entry.Key, itemQuality, true)));
			}
			catch (Exception error)
			{
				Warn(error);
			}
		}

		private static void EndSpend(BuildSpend __state)
		{
			if (__state?.Missing == null)
			{
				return;
			}
			try
			{
				foreach (KeyValuePair<string, int> item in __state.Missing)
				{
					int num = item.Value;
					foreach (BulkBox item2 in Boxes(__state.Player))
					{
						if (num > 0)
						{
							num -= item2.ConsumeForCraft(item.Key, -1, leaveOne: false, num);
							continue;
						}
						break;
					}
					foreach (Container item3 in Containers(__state.Player))
					{
						if (num > 0)
						{
							Inventory inventory = item3.GetInventory();
							int num2 = Math.Min(num, inventory.CountItems(item.Key, -1, true));
							if (num2 > 0)
							{
								inventory.RemoveItem(item.Key, num2, -1, true);
								num -= num2;
							}
							continue;
						}
						break;
					}
					if (num > 0)
					{
						Warn(new InvalidOperationException("Buildheim placement could not debit all " + item.Key));
					}
				}
			}
			catch (Exception error)
			{
				Warn(error);
			}
		}
	}
	public sealed class BulkBox : MonoBehaviour, Hoverable, Interactable
	{
		private sealed class WithdrawalOption
		{
			internal string Key;

			internal string Label;

			internal BigInteger Amount;
		}

		private sealed class WithdrawalTarget
		{
			internal Vector2i Position;

			internal int Amount;

			internal int PreviousStack;
		}

		private const string StateKey = "freshdedicatedstorage_bulkbox_state_v1";

		private static readonly string LegacyStateKey = 'm' + "ike_bulkbox_state_v1";

		private static readonly Dictionary<string, string> CurrentTemplates = new Dictionary<string, string>();

		internal static readonly HashSet<BulkBox> Active = new HashSet<BulkBox>();

		private ZNetView view;

		private string cachedRaw;

		private BulkState cachedState;

		private ItemData cachedItem;

		private bool busy;

		private Container assignment;

		private bool assignmentFailed;

		private SpriteRenderer[] itemIcons;

		private TextMeshPro quantityText;

		private static TMP_FontAsset quantityFont;

		private static float nextFontLookup;

		private string iconTemplate;

		private string quantityDisplay;

		private string selectedWithdrawal = "stack";

		private int altWithdrawalFrame = -1;

		private Container Assignment
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)assignment))
				{
					return assignment = ((Component)this).GetComponentInChildren<Container>();
				}
				return assignment;
			}
		}

		private ZNetView View
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)view))
				{
					return view = ((Component)this).GetComponent<ZNetView>();
				}
				return view;
			}
		}

		public bool ProtectContents
		{
			get
			{
				try
				{
					int result;
					if (!(Read().Count > 0L))
					{
						if (Object.op_Implicit((Object)(object)Assignment))
						{
							Inventory inventory = Assignment.GetInventory();
							result = ((inventory != null && inventory.NrOfItems() > 0) ? 1 : 0);
						}
						else
						{
							result = 0;
						}
					}
					else
					{
						result = 1;
					}
					return (byte)result != 0;
				}
				catch
				{
					return true;
				}
			}
		}

		internal static bool IsWithdrawalWheelActive()
		{
			if (!ZNet.IsSinglePlayer || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || !ZInput.GetButton("AltPlace"))
			{
				return false;
			}
			GameObject hoverObject = ((Humanoid)Player.m_localPlayer).GetHoverObject();
			BulkBox bulkBox = (Object.op_Implicit((Object)(object)hoverObject) ? hoverObject.GetComponentInParent<BulkBox>() : null);
			if (Object.op_Implicit((Object)(object)bulkBox) && Object.op_Implicit((Object)(object)bulkBox.View) && bulkBox.View.IsValid())
			{
				return bulkBox.Read().Count > 0L;
			}
			return false;
		}

		internal static float FilterCameraZoomScrollWheel()
		{
			if (!IsWithdrawalWheelActive())
			{
				return ZInput.GetMouseScrollWheel();
			}
			return 0f;
		}

		internal static bool TryCtrlUseHovered()
		{
			if (!IsUseModifierHeld() || !Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return false;
			}
			GameObject hoverObject = ((Humanoid)Player.m_localPlayer).GetHoverObject();
			BulkBox bulkBox = (Object.op_Implicit((Object)(object)hoverObject) ? hoverObject.GetComponentInParent<BulkBox>() : null);
			if (Object.op_Implicit((Object)(object)bulkBox))
			{
				return bulkBox.UseOneForAltUse((Humanoid)(object)Player.m_localPlayer);
			}
			return false;
		}

		private static bool IsUseModifierHeld()
		{
			if (!ZInput.GetKey((KeyCode)306, true))
			{
				return ZInput.GetKey((KeyCode)305, true);
			}
			return true;
		}

		internal static bool TryGetHoveredLinkContainer(out Container container)
		{
			container = null;
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return false;
			}
			GameObject hoverObject = ((Humanoid)Player.m_localPlayer).GetHoverObject();
			BulkBox bulkBox = (Object.op_Implicit((Object)(object)hoverObject) ? hoverObject.GetComponentInParent<BulkBox>() : null);
			if (!Object.op_Implicit((Object)(object)bulkBox) || !Object.op_Implicit((Object)(object)bulkBox.Assignment))
			{
				return false;
			}
			container = bulkBox.Assignment;
			return true;
		}

		private void OnEnable()
		{
			Active.Add(this);
		}

		private void OnDisable()
		{
			Active.Remove(this);
		}

		internal string SortingTemplate()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			if (busy || !Object.op_Implicit((Object)(object)View) || !View.IsValid() || !PrivateArea.CheckAccess(((Component)this).transform.position, 0f, false, false))
			{
				return null;
			}
			if (Object.op_Implicit((Object)(object)Assignment))
			{
				if (!Assignment.IsInUse())
				{
					Inventory inventory = Assignment.GetInventory();
					if (inventory == null || inventory.NrOfItems() <= 0)
					{
						goto IL_0075;
					}
				}
				return null;
			}
			goto IL_0075;
			IL_0075:
			return CurrentTemplate(Read().Template);
		}

		internal bool TryGetWithdrawalStock(out string template, out ItemData item, out BigInteger count)
		{
			template = null;
			item = null;
			count = BigInteger.Zero;
			if (!ZNet.IsSinglePlayer || string.IsNullOrEmpty(SortingTemplate()))
			{
				return false;
			}
			BulkState bulkState = Read();
			if (bulkState.Count <= 0L)
			{
				return false;
			}
			template = bulkState.Template;
			item = Item(bulkState);
			count = bulkState.Count;
			return true;
		}

		internal BigInteger WithdrawForReliquary(Player user, string expectedTemplate, BigInteger requested)
		{
			BigInteger withdrawn = BigInteger.Zero;
			if (requested <= 0L || string.IsNullOrEmpty(expectedTemplate))
			{
				return withdrawn;
			}
			Run((Humanoid)(object)user, delegate
			{
				BulkState bulkState = Read();
				if (!(bulkState.Template != expectedTemplate) && !(bulkState.Count <= 0L))
				{
					withdrawn = Withdraw((Humanoid)(object)user, bulkState, requested, announce: false);
				}
			});
			return withdrawn;
		}

		internal bool DepositGroundItem(ItemDrop drop)
		{
			if (!ZNet.IsSinglePlayer || !Object.op_Implicit((Object)(object)drop) || !drop.CanPickup(true) || busy)
			{
				return false;
			}
			ZNetView component = ((Component)drop).GetComponent<ZNetView>();
			if (!Object.op_Implicit((Object)(object)component) || !component.IsValid() || !component.IsOwner())
			{
				return false;
			}
			ItemData itemData = drop.m_itemData;
			if (itemData == null || itemData.m_stack <= 0 || SortingTemplate() != EncodeItem(itemData))
			{
				return false;
			}
			View.ClaimOwnership();
			if (!View.IsOwner())
			{
				return false;
			}
			int stack = itemData.m_stack;
			BulkState bulkState = Read();
			BulkState bulkState2 = bulkState.Deposit(bulkState.Template, stack);
			MethodInfo methodInfo = AccessTools.Method(typeof(ItemDrop), "Save", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				throw new MissingMethodException("ItemDrop.Save");
			}
			busy = true;
			try
			{
				itemData.m_stack = 0;
				methodInfo.Invoke(drop, null);
				View.GetZDO().Set("freshdedicatedstorage_bulkbox_state_v1", bulkState2.Encode());
			}
			catch
			{
				View.GetZDO().Set("freshdedicatedstorage_bulkbox_state_v1", bulkState.Encode());
				itemData.m_stack = stack;
				methodInfo.Invoke(drop, null);
				throw;
			}
			finally
			{
				busy = false;
			}
			component.Destroy();
			return true;
		}

		internal bool DepositAssigned(Humanoid user, ItemData item)
		{
			if ((Object)(object)user != (Object)(object)Player.m_localPlayer || !ZNet.IsSinglePlayer || item.m_equipped)
			{
				return false;
			}
			return DepositFromInventory(user.GetInventory(), item);
		}

		internal bool DepositFromInventory(Inventory inventory, ItemData item)
		{
			if (!ZNet.IsSinglePlayer || inventory == null || item == null || item.m_equipped)
			{
				return false;
			}
			string text = SortingTemplate();
			if (string.IsNullOrEmpty(text) || text != EncodeItem(item))
			{
				return false;
			}
			View.ClaimOwnership();
			if (!View.IsOwner())
			{
				return false;
			}
			busy = true;
			try
			{
				Deposit(inventory, item);
				return true;
			}
			finally
			{
				busy = false;
			}
		}

		internal static bool DepositToSavedBox(ZDO box, Inventory inventory, ItemData item, Action persistSource)
		{
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			if (!ZNet.IsSinglePlayer || box == null || inventory == null || item == null || item.m_equipped || !inventory.ContainsItem(item) || item.m_stack <= 0)
			{
				return false;
			}
			string text = box.GetString("freshdedicatedstorage_bulkbox_state_v1", "");
			if (string.IsNullOrEmpty(text))
			{
				text = box.GetString(LegacyStateKey, "");
			}
			BulkState bulkState = BulkState.Decode(text);
			string text2 = EncodeItem(item);
			if (string.IsNullOrEmpty(bulkState.Template) || CurrentTemplate(bulkState.Template) != text2)
			{
				return false;
			}
			BulkState bulkState2 = bulkState.Deposit(bulkState.Template, item.m_stack);
			string text3 = box.GetString("freshdedicatedstorage_bulkbox_state_v1", "");
			ZPackage val = new ZPackage();
			inventory.Save(val);
			try
			{
				if (!inventory.RemoveItem(item))
				{
					throw new InvalidOperationException("Could not remove the delivery stack.");
				}
				persistSource?.Invoke();
				box.Set("freshdedicatedstorage_bulkbox_state_v1", bulkState2.Encode());
				return true;
			}
			catch
			{
				box.Set("freshdedicatedstorage_bulkbox_state_v1", text3);
				inventory.Load(new ZPackage(val.GetArray()));
				persistSource?.Invoke();
				throw;
			}
		}

		internal static bool SavedBoxMatches(ZDO box, string template)
		{
			if (box == null || string.IsNullOrEmpty(template))
			{
				return false;
			}
			string text = box.GetString("freshdedicatedstorage_bulkbox_state_v1", "");
			if (string.IsNullOrEmpty(text))
			{
				text = box.GetString(LegacyStateKey, "");
			}
			return CurrentTemplate(BulkState.Decode(text).Template) == template;
		}

		internal string StoreAndCraftLabel()
		{
			if (!Object.op_Implicit((Object)(object)View) || !View.IsValid())
			{
				return "";
			}
			return View.GetZDO().GetString("kac_label", "");
		}

		private int StoreAndCraftLinkId()
		{
			return StoreAndCraftBridge.ParseLinkId(StoreAndCraftLabel());
		}

		private BulkState Read()
		{
			string text = ((Object.op_Implicit((Object)(object)View) && View.IsValid()) ? View.GetZDO().GetString("freshdedicatedstorage_bulkbox_state_v1", "") : "");
			if (string.IsNullOrEmpty(text) && Object.op_Implicit((Object)(object)View) && View.IsValid())
			{
				text = View.GetZDO().GetString(LegacyStateKey, "");
			}
			if (cachedState == null || text != cachedRaw)
			{
				cachedState = BulkState.Decode(text);
				cachedRaw = text;
				cachedItem = null;
			}
			return cachedState;
		}

		public string GetHoverName()
		{
			return "Dedicated Storage Box";
		}

		public float GetHoverOffset()
		{
			return 0.25f;
		}

		public string GetHoverText()
		{
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				BulkState bulkState = Read();
				string text = (string.IsNullOrEmpty(bulkState.Template) ? "Unassigned" : Item(bulkState).m_shared.m_name);
				int num = (StoreAndCraftBridge.IsLinkUiAvailable ? StoreAndCraftLinkId() : 0);
				string text2 = ((num > 0) ? (StoreAndCraftBridge.ColorizeLink(num, "Link: " + num) + "\n") : "") + "Dedicated Storage Box\n" + text + ": <color=yellow>" + bulkState.Count.ToString("N0", CultureInfo.InvariantCulture) + "</color>";
				if (!ZNet.IsSinglePlayer)
				{
					return text2 + "\nSingle-player storage only";
				}
				if (!PrivateArea.CheckAccess(((Component)this).transform.position, 0f, false, false))
				{
					return text2 + "\n$piece_noaccess";
				}
				text2 += (string.IsNullOrEmpty(bulkState.Template) ? "\n[<color=yellow>$KEY_Use</color>] Choose item type" : "\n[<color=yellow>$KEY_Use</color>] Deposit all matching items");
				if (StoreAndCraftBridge.IsLinkUiAvailable)
				{
					text2 = text2 + "\n[<color=yellow>" + (ControllerStorageInput.Active ? ControllerStorageInput.StoreAndCraftKey : "Alt + $KEY_Use") + "</color>] Auto-pull settings";
				}
				if (bulkState.Count > 0L)
				{
					WithdrawalOption withdrawalOption = SelectedWithdrawal(bulkState);
					text2 = text2 + "\n[<color=yellow>" + (ControllerStorageInput.Active ? ControllerStorageInput.SecondaryActionKey : "Ctrl + $KEY_Use") + "</color>] Use 1";
					text2 = text2 + "\n[<color=yellow>" + (ControllerStorageInput.Active ? ControllerStorageInput.AmountActionKey : "$KEY_AltPlace + Mouse wheel") + "</color>] Amount: <color=yellow>" + withdrawalOption.Label + "</color>";
					text2 = text2 + "\n[<color=yellow>" + ControllerStorageInput.AlternateUseKey + " + $KEY_Use</color>] Withdraw " + withdrawalOption.Label;
				}
				else
				{
					text2 = text2 + "\n[<color=yellow>" + ControllerStorageInput.AlternateUseKey + " + $KEY_Use</color>] Clear item assignment";
				}
				return Localization.instance.Localize(text2);
			}
			catch
			{
				return "Dedicated Storage Box\nStored data unavailable; contents preserved. Check the log.";
			}
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			if (hold)
			{
				return false;
			}
			if ((Object)(object)user == (Object)(object)Player.m_localPlayer && IsUseModifierHeld())
			{
				return UseOneForAltUse(user);
			}
			if ((Object)(object)user == (Object)(object)Player.m_localPlayer && StoreAndCraftBridge.WantsRename())
			{
				return true;
			}
			if (altWithdrawalFrame == Time.frameCount)
			{
				return true;
			}
			return Run(user, delegate
			{
				BulkState bulkState = Read();
				if (Object.op_Implicit((Object)(object)Assignment))
				{
					Inventory inventory = Assignment.GetInventory();
					if (inventory != null && inventory.NrOfItems() > 0)
					{
						OpenAssignment();
						return;
					}
				}
				if (alt)
				{
					if (bulkState.Count == 0L)
					{
						View.GetZDO().Set("freshdedicatedstorage_bulkbox_state_v1", BulkState.Empty.Encode());
						Say(user, "Item assignment cleared.");
					}
					else
					{
						Withdraw(user, bulkState, SelectedWithdrawal(bulkState).Amount);
					}
				}
				else if (string.IsNullOrEmpty(bulkState.Template))
				{
					OpenAssignment();
				}
				else
				{
					BigInteger zero = BigInteger.Zero;
					ItemData[] array = user.GetInventory().GetAllItems().ToArray();
					foreach (ItemData val in array)
					{
						if (!val.m_equipped && val.m_stack > 0 && EncodeItem(val) == CurrentTemplate(Read().Template))
						{
							int stack = val.m_stack;
							Deposit(user.GetInventory(), val);
							zero += (BigInteger)stack;
						}
					}
					Say(user, (zero > 0L) ? $"Deposited {zero:N0}." : "No matching items in your inventory.");
				}
			});
		}

		private bool UseOneForAltUse(Humanoid user)
		{
			if (altWithdrawalFrame == Time.frameCount)
			{
				return true;
			}
			altWithdrawalFrame = Time.frameCount;
			return Run(user, delegate
			{
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Expected O, but got Unknown
				BulkState bulkState = Read();
				if (bulkState.Count <= 0L)
				{
					Say(user, "No stored items to use.");
				}
				else
				{
					ItemData val = Item(bulkState).Clone();
					val.m_stack = 1;
					if (!user.CanConsumeItem(val, true))
					{
						Say(user, "This stored item cannot be used right now.");
					}
					else
					{
						Inventory val2 = new Inventory("Dedicated storage use", (Sprite)null, 1, 1);
						val2.GetAllItems().Add(val);
						user.UseItem(val2, val, true);
						if (!val2.ContainsItem(val))
						{
							View.GetZDO().Set("freshdedicatedstorage_bulkbox_state_v1", bulkState.Withdraw(BigInteger.One).Encode());
						}
					}
				}
			});
		}

		internal bool UseOneWithController(Player user)
		{
			if ((Object)(object)user == (Object)(object)Player.m_localPlayer)
			{
				return UseOneForAltUse((Humanoid)(object)user);
			}
			return false;
		}

		public bool UseItem(Humanoid user, ItemData item)
		{
			return false;
		}

		private void OpenAssignment()
		{
			if (!Object.op_Implicit((Object)(object)Assignment) || Assignment.GetInventory() == null || !Object.op_Implicit((Object)(object)InventoryGui.instance))
			{
				throw new InvalidOperationException("Assignment inventory is not ready; try again.");
			}
			assignmentFailed = false;
			Assignment.SetInUse(true);
			InventoryGui.instance.Show(Assignment, 1);
		}

		private void Awake()
		{
			itemIcons = (SpriteRenderer[])(object)new SpriteRenderer[1] { CreateItemIcon("Assigned item icon front", -1f) };
		}

		private void LateUpdate()
		{
			EnsureQuantityText();
			RefreshFrontDisplay();
			UpdateWithdrawalSelection();
			if (busy || assignmentFailed || !ZNet.IsSinglePlayer || !Object.op_Implicit((Object)(object)View) || !View.IsValid() || !View.IsOwner() || !Object.op_Implicit((Object)(object)Assignment) || Assignment.GetInventory() == null)
			{
				return;
			}
			Inventory inventory = Assignment.GetInventory();
			List<ItemData> allItems = inventory.GetAllItems();
			if (allItems.Count == 0)
			{
				return;
			}
			busy = true;
			try
			{
				if (allItems.Count != 1)
				{
					throw new InvalidOperationException("Assignment slot has unexpected contents; retrieve them first.");
				}
				ItemData item = allItems[0];
				if (!Object.op_Implicit((Object)(object)item.m_dropPrefab) || !Object.op_Implicit((Object)(object)ObjectDB.instance.GetItemPrefab(((Object)item.m_dropPrefab).name)))
				{
					throw new InvalidOperationException("This item cannot be stored safely; take it back from the slot.");
				}
				BulkState next = Read().AssignFromSlot(EncodeItem(item), item.m_stack);
				ChangeInventory(inventory, next, delegate
				{
					if (!inventory.RemoveItem(item))
					{
						throw new InvalidOperationException("Assignment transfer failed.");
					}
				});
				if (Object.op_Implicit((Object)(object)Player.m_localPlayer))
				{
					Say((Humanoid)(object)Player.m_localPlayer, Localization.instance.Localize("Assigned " + item.m_shared.m_name + $"; stored {item.m_stack:N0}."));
				}
			}
			catch (Exception arg)
			{
				assignmentFailed = true;
				Logger.LogError((object)$"Bulk box assignment failed; inspect the saved assignment slot: {arg}");
				if (Object.op_Implicit((Object)(object)Player.m_localPlayer))
				{
					Say((Humanoid)(object)Player.m_localPlayer, "Could not assign that item. Press E to retrieve it from the slot.");
				}
			}
			finally
			{
				busy = false;
			}
		}

		private void UpdateWithdrawalSelection()
		{
			if (!ZNet.IsSinglePlayer || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || !ZInput.GetButton("AltPlace"))
			{
				return;
			}
			GameObject hoverObject = ((Humanoid)Player.m_localPlayer).GetHoverObject();
			if (Object.op_Implicit((Object)(object)hoverObject) && !((Object)(object)hoverObject.GetComponentInParent<BulkBox>() != (Object)(object)this))
			{
				float mouseScrollWheel = ZInput.GetMouseScrollWheel();
				if (!(Mathf.Abs(mouseScrollWheel) < 0.01f))
				{
					CycleWithdrawalSelection((mouseScrollWheel > 0f) ? 1 : (-1));
				}
			}
		}

		internal void CycleWithdrawalWithController(int direction)
		{
			if (ZNet.IsSinglePlayer && Object.op_Implicit((Object)(object)View) && View.IsValid())
			{
				CycleWithdrawalSelection(direction);
			}
		}

		private void CycleWithdrawalSelection(int direction)
		{
			List<WithdrawalOption> list = WithdrawalOptions(Read());
			if (list.Count != 0)
			{
				int num = list.FindIndex((WithdrawalOption option) => option.Key == selectedWithdrawal);
				if (num < 0)
				{
					num = DefaultWithdrawalIndex(list);
				}
				num = (num + direction + list.Count) % list.Count;
				selectedWithdrawal = list[num].Key;
			}
		}

		private WithdrawalOption SelectedWithdrawal(BulkState state)
		{
			List<WithdrawalOption> list = WithdrawalOptions(state);
			if (list.Count == 0)
			{
				throw new InvalidOperationException("This box has no items to withdraw.");
			}
			WithdrawalOption withdrawalOption = list.FirstOrDefault((WithdrawalOption option) => option.Key == selectedWithdrawal);
			if (withdrawalOption != null)
			{
				return withdrawalOption;
			}
			withdrawalOption = list[DefaultWithdrawalIndex(list)];
			selectedWithdrawal = withdrawalOption.Key;
			return withdrawalOption;
		}

		private List<WithdrawalOption> WithdrawalOptions(BulkState state)
		{
			List<WithdrawalOption> list = new List<WithdrawalOption>();
			if (state.Count <= 0L)
			{
				return list;
			}
			int num = Math.Max(1, Math.Min(65535, Item(state).m_shared.m_maxStackSize));
			int[] array = new int[6] { 1, 5, 10, 20, 50, 100 };
			for (int i = 0; i < array.Length; i++)
			{
				int num2 = array[i];
				if (num2 < num && state.Count > num2)
				{
					list.Add(new WithdrawalOption
					{
						Key = num2.ToString(CultureInfo.InvariantCulture),
						Label = num2.ToString(CultureInfo.InvariantCulture),
						Amount = num2
					});
				}
			}
			if (state.Count > num)
			{
				list.Add(new WithdrawalOption
				{
					Key = "stack",
					Label = "stack",
					Amount = num
				});
			}
			list.Add(new WithdrawalOption
			{
				Key = "all",
				Label = "all",
				Amount = state.Count
			});
			return list;
		}

		private static int DefaultWithdrawalIndex(List<WithdrawalOption> options)
		{
			int num = options.FindIndex((WithdrawalOption option) => option.Key == "stack");
			if (num < 0)
			{
				return options.Count - 1;
			}
			return num;
		}

		private void RefreshFrontDisplay()
		{
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			if (itemIcons == null || itemIcons.Length == 0 || !Object.op_Implicit((Object)(object)View) || !View.IsValid() || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return;
			}
			BulkState bulkState;
			try
			{
				bulkState = Read();
			}
			catch
			{
				SetItemIconVisible(visible: false);
				if (Object.op_Implicit((Object)(object)quantityText))
				{
					((Behaviour)quantityText).enabled = false;
				}
				return;
			}
			bool flag = !string.IsNullOrEmpty(bulkState.Template);
			string text = (flag ? FormatDisplayedCount(bulkState.Count) : "");
			if (Object.op_Implicit((Object)(object)quantityText) && text != quantityDisplay)
			{
				quantityDisplay = text;
				((TMP_Text)quantityText).text = text;
				((Behaviour)quantityText).enabled = flag;
			}
			if (bulkState.Template == iconTemplate)
			{
				return;
			}
			iconTemplate = bulkState.Template;
			if (!flag)
			{
				SetItemIconVisible(visible: false);
				return;
			}
			try
			{
				Sprite icon = Item(bulkState).GetIcon();
				if (!Object.op_Implicit((Object)(object)icon))
				{
					SetItemIconVisible(visible: false);
					return;
				}
				Bounds bounds = icon.bounds;
				float x = ((Bounds)(ref bounds)).size.x;
				bounds = icon.bounds;
				float num = Mathf.Max(x, ((Bounds)(ref bounds)).size.y);
				Vector3 localScale = ((num > 0f) ? (Vector3.one * (0.1375f / num)) : Vector3.one);
				SpriteRenderer[] array = itemIcons;
				foreach (SpriteRenderer obj2 in array)
				{
					obj2.sprite = icon;
					((Component)obj2).transform.localScale = localScale;
					((Renderer)obj2).enabled = true;
				}
			}
			catch
			{
				SetItemIconVisible(visible: false);
			}
		}

		private static string FormatDisplayedCount(BigInteger count)
		{
			if (count < 1000L)
			{
				return count.ToString("N0", CultureInfo.InvariantCulture);
			}
			string[] array = new string[5] { "K", "M", "B", "T", "Q" };
			BigInteger bigInteger = 1000;
			int i;
			for (i = 0; i < array.Length - 1; i++)
			{
				if (!(count >= bigInteger * 1000))
				{
					break;
				}
				bigInteger *= (BigInteger)1000;
			}
			BigInteger bigInteger2 = (count * 10 + bigInteger / 2) / bigInteger;
			if (bigInteger2 >= 10000L && i < array.Length - 1)
			{
				bigInteger2 = 10;
				i++;
			}
			return (bigInteger2 / 10).ToString(CultureInfo.InvariantCulture) + "." + (bigInteger2 % 10).ToString(CultureInfo.InvariantCulture) + array[i];
		}

		private SpriteRenderer CreateItemIcon(string name, float side)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name)
			{
				layer = ((Component)this).gameObject.layer
			};
			val.transform.SetParent(((Component)this).transform, false);
			val.transform.localPosition = new Vector3(-0.1f, ModelAsset.BoxVisualSize.y * 0.355f, side * (ModelAsset.BoxVisualSize.z * 0.5f + 0.01f));
			val.transform.localRotation = ((side < 0f) ? Quaternion.Euler(0f, 180f, 0f) : Quaternion.identity);
			SpriteRenderer obj = val.AddComponent<SpriteRenderer>();
			((Renderer)obj).sortingOrder = 10;
			((Renderer)obj).enabled = false;
			return obj;
		}

		private void EnsureQuantityText()
		{
			if (Object.op_Implicit((Object)(object)quantityText))
			{
				return;
			}
			if (!Object.op_Implicit((Object)(object)quantityFont) && Time.unscaledTime >= nextFontLookup)
			{
				nextFontLookup = Time.unscaledTime + 1f;
				quantityFont = (from label in Resources.FindObjectsOfTypeAll<TMP_Text>()
					select (!Object.op_Implicit((Object)(object)label)) ? null : label.font).FirstOrDefault((Func<TMP_FontAsset, bool>)((TMP_FontAsset font) => Object.op_Implicit((Object)(object)font) && Object.op_Implicit((Object)(object)font.atlasTexture)));
				if (!Object.op_Implicit((Object)(object)quantityFont))
				{
					quantityFont = ((IEnumerable<TMP_FontAsset>)Resources.FindObjectsOfTypeAll<TMP_FontAsset>()).FirstOrDefault((Func<TMP_FontAsset, bool>)((TMP_FontAsset font) => Object.op_Implicit((Object)(object)font) && Object.op_Implicit((Object)(object)font.atlasTexture)));
				}
			}
			if (Object.op_Implicit((Object)(object)quantityFont))
			{
				quantityText = CreateQuantityText(quantityFont);
			}
		}

		private TextMeshPro CreateQuantityText(TMP_FontAsset font)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Stored quantity front", new Type[1] { typeof(RectTransform) })
			{
				layer = ((Component)this).gameObject.layer
			};
			val.SetActive(false);
			val.transform.SetParent(((Component)this).transform, false);
			val.transform.localPosition = new Vector3(0.1f, ModelAsset.BoxVisualSize.y * 0.355f, 0f - (ModelAsset.BoxVisualSize.z * 0.5f + 0.012f));
			val.transform.localRotation = Quaternion.identity;
			val.transform.localScale = Vector3.one * 0.0525f;
			TextMeshPro obj = val.AddComponent<TextMeshPro>();
			((TMP_Text)obj).font = font;
			((TMP_Text)obj).alignment = (TextAlignmentOptions)514;
			((TMP_Text)obj).fontStyle = (FontStyles)1;
			((TMP_Text)obj).enableAutoSizing = true;
			((TMP_Text)obj).fontSizeMin = 1.25f;
			((TMP_Text)obj).fontSizeMax = 2.7f;
			val.GetComponent<RectTransform>().sizeDelta = new Vector2(4f, 1.8f);
			((Graphic)obj).color = new Color(0.92f, 0.86f, 0.72f, 1f);
			MeshRenderer component = val.GetComponent<MeshRenderer>();
			if (Object.op_Implicit((Object)(object)component))
			{
				((Renderer)component).sortingOrder = 11;
			}
			((Behaviour)obj).enabled = false;
			val.SetActive(true);
			return obj;
		}

		private void SetItemIconVisible(bool visible)
		{
			if (itemIcons == null)
			{
				return;
			}
			SpriteRenderer[] array = itemIcons;
			foreach (SpriteRenderer val in array)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					((Renderer)val).enabled = visible;
				}
			}
		}

		private bool Run(Humanoid user, Action operation)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if (busy || (Object)(object)user != (Object)(object)Player.m_localPlayer)
			{
				return true;
			}
			if (!ZNet.IsSinglePlayer)
			{
				Say(user, "Bulk boxes currently support single-player worlds only.");
				return true;
			}
			if (!Object.op_Implicit((Object)(object)View) || !View.IsValid())
			{
				return true;
			}
			if (!PrivateArea.CheckAccess(((Component)this).transform.position, 0f, true, false))
			{
				return true;
			}
			View.ClaimOwnership();
			if (!View.IsOwner())
			{
				Say(user, "Box not ready; try again.");
				return true;
			}
			busy = true;
			try
			{
				operation();
			}
			catch (InvalidOperationException ex)
			{
				Say(user, ex.Message);
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Bulk box operation failed; stored state retained: {arg}");
				Say(user, "Storage operation failed. Check the log before using this box again.");
			}
			finally
			{
				busy = false;
			}
			return true;
		}

		internal int CraftAvailable(string name, int quality, bool leaveOne)
		{
			if (!ZNet.IsSinglePlayer || string.IsNullOrEmpty(SortingTemplate()))
			{
				return 0;
			}
			BulkState bulkState = Read();
			ItemData val = Item(bulkState);
			if (val.m_shared.m_name != name || (quality >= 0 && val.m_quality != quality) || val.m_worldLevel < Game.m_worldLevel)
			{
				return 0;
			}
			return (int)BigInteger.Min(int.MaxValue, BigInteger.Max(0, bulkState.Count - (leaveOne ? 1 : 0)));
		}

		internal bool TryGetStoredMaterial(out string name, out int count)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			name = null;
			count = 0;
			if (!ZNet.IsSinglePlayer || busy || !Object.op_Implicit((Object)(object)View) || !View.IsValid() || !PrivateArea.CheckAccess(((Component)this).transform.position, 0f, false, false))
			{
				return false;
			}
			BulkState bulkState = Read();
			if (bulkState.Count <= 0L)
			{
				return true;
			}
			ItemData val = Item(bulkState);
			name = val.m_shared.m_name;
			count = (int)BigInteger.Min(int.MaxValue, bulkState.Count);
			return true;
		}

		internal int ConsumeForCraft(string name, int quality, bool leaveOne, int requested)
		{
			int num = Math.Min(requested, CraftAvailable(name, quality, leaveOne));
			if (num <= 0)
			{
				return 0;
			}
			View.ClaimOwnership();
			if (!View.IsOwner())
			{
				return 0;
			}
			View.GetZDO().Set("freshdedicatedstorage_bulkbox_state_v1", Read().Withdraw(num).Encode());
			return num;
		}

		private void Deposit(Inventory inventory, ItemData item)
		{
			if (!inventory.ContainsItem(item) || item.m_stack <= 0)
			{
				throw new InvalidOperationException("That item is no longer in your inventory.");
			}
			if (!Object.op_Implicit((Object)(object)item.m_dropPrefab) || !Object.op_Implicit((Object)(object)ObjectDB.instance.GetItemPrefab(((Object)item.m_dropPrefab).name)))
			{
				throw new InvalidOperationException("This item has no registered prefab and cannot be stored safely.");
			}
			BulkState bulkState = Read();
			if (CurrentTemplate(bulkState.Template) != EncodeItem(item))
			{
				throw new InvalidOperationException("This box is assigned to a different item or variant.");
			}
			BulkState next = bulkState.Deposit(bulkState.Template, item.m_stack);
			ChangeInventory(inventory, next, delegate
			{
				if (!inventory.RemoveItem(item))
				{
					throw new InvalidOperationException("Could not remove the deposited stack.");
				}
			});
		}

		private BigInteger Withdraw(Humanoid user, BulkState state, BigInteger requested, bool announce = true)
		{
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			Inventory inventory = user.GetInventory();
			ItemData template = Item(state);
			int num = Math.Max(1, Math.Min(65535, template.m_shared.m_maxStackSize));
			int num2 = VisibleWithdrawalHeight(inventory);
			BigInteger bigInteger = BigInteger.Min(state.Count, requested);
			List<WithdrawalTarget> targets = new List<WithdrawalTarget>();
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (bigInteger > 0L && allItem.m_gridPos.x >= 0 && allItem.m_gridPos.x < inventory.GetWidth() && allItem.m_gridPos.y >= 0 && allItem.m_gridPos.y < num2 && allItem.m_stack < num && EncodeItem(allItem) == CurrentTemplate(state.Template))
				{
					int num3 = (int)BigInteger.Min(bigInteger, num - allItem.m_stack);
					targets.Add(new WithdrawalTarget
					{
						Position = allItem.m_gridPos,
						Amount = num3,
						PreviousStack = allItem.m_stack
					});
					bigInteger -= (BigInteger)num3;
				}
			}
			int num4 = 0;
			while (bigInteger > 0L && num4 < num2)
			{
				int num5 = 0;
				while (bigInteger > 0L && num5 < inventory.GetWidth())
				{
					if (inventory.GetItemAt(num5, num4) == null)
					{
						int num6 = (int)BigInteger.Min(bigInteger, num);
						targets.Add(new WithdrawalTarget
						{
							Position = new Vector2i(num5, num4),
							Amount = num6
						});
						bigInteger -= (BigInteger)num6;
					}
					num5++;
				}
				num4++;
			}
			BigInteger bigInteger2 = BigInteger.Min(state.Count, requested) - bigInteger;
			if (bigInteger2 <= 0L)
			{
				if (announce)
				{
					Say(user, "Inventory full. 0 items withdrawn.");
				}
				return BigInteger.Zero;
			}
			ChangeInventory(inventory, state.Withdraw(bigInteger2), delegate
			{
				//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
				foreach (WithdrawalTarget item in targets)
				{
					ItemData itemAt = inventory.GetItemAt(item.Position.x, item.Position.y);
					if (item.PreviousStack > 0)
					{
						if (itemAt == null || itemAt.m_stack != item.PreviousStack || EncodeItem(itemAt) != CurrentTemplate(state.Template))
						{
							throw new InvalidOperationException("Inventory changed during withdrawal; nothing withdrawn.");
						}
						itemAt.m_stack += item.Amount;
					}
					else
					{
						if (itemAt != null)
						{
							throw new InvalidOperationException("Inventory changed during withdrawal; nothing withdrawn.");
						}
						ItemData val = template.Clone();
						val.m_stack = item.Amount;
						val.m_gridPos = item.Position;
						inventory.GetAllItems().Add(val);
					}
				}
				AccessTools.Method(typeof(Inventory), "Changed", new Type[2]
				{
					typeof(bool),
					typeof(bool)
				}, (Type[])null)?.Invoke(inventory, new object[2] { false, false });
				foreach (WithdrawalTarget item2 in targets)
				{
					ItemData itemAt2 = inventory.GetItemAt(item2.Position.x, item2.Position.y);
					if (itemAt2 == null || itemAt2.m_stack != item2.PreviousStack + item2.Amount || EncodeItem(itemAt2) != CurrentTemplate(state.Template))
					{
						throw new InvalidOperationException("Withdrawal did not land in a visible inventory slot; nothing withdrawn.");
					}
				}
			});
			if (announce)
			{
				Say(user, (bigInteger > 0L) ? $"Withdrew {bigInteger2:N0}; inventory is full." : $"Withdrew {bigInteger2:N0}.");
			}
			return bigInteger2;
		}

		private static int VisibleWithdrawalHeight(Inventory inventory)
		{
			int num = inventory.GetHeight();
			try
			{
				if ((AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "EquipmentAndQuickSlots")?.GetType("EquipmentAndQuickSlots.Slots")?.GetProperty("VisibleRows"))?.GetValue(null) is int num2 && num2 > 0)
				{
					num = Math.Min(num, num2);
				}
			}
			catch (Exception arg)
			{
				Logger.LogWarning((object)$"Could not read visible inventory rows; withdrawal will verify every placement: {arg}");
			}
			return num;
		}

		private void ChangeInventory(Inventory inventory, BulkState next, Action transfer)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			string text = next.Encode();
			string text2 = View.GetZDO().GetString("freshdedicatedstorage_bulkbox_state_v1", "");
			ZPackage val = new ZPackage();
			inventory.Save(val);
			try
			{
				transfer();
				View.GetZDO().Set("freshdedicatedstorage_bulkbox_state_v1", text);
			}
			catch
			{
				View.GetZDO().Set("freshdedicatedstorage_bulkbox_state_v1", text2);
				inventory.Load(new ZPackage(val.GetArray()));
				throw;
			}
		}

		internal static string EncodeItem(ItemData item)
		{
			//IL_0011: 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_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: 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)
			//IL_00be: Expected O, but got Unknown
			ItemData val = item.Clone();
			val.m_stack = 1;
			val.m_gridPos = new Vector2i(0, 0);
			val.m_equipped = false;
			val.m_pickedUp = true;
			val.m_customData = new Dictionary<string, string>();
			foreach (KeyValuePair<string, string> item2 in item.m_customData.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> pair) => pair.Key, StringComparer.Ordinal))
			{
				val.m_customData.Add(item2.Key, item2.Value);
			}
			Inventory val2 = new Inventory("Bulk template", (Sprite)null, 1, 1);
			val2.GetAllItems().Add(val);
			ZPackage val3 = new ZPackage();
			val2.Save(val3);
			return Convert.ToBase64String(val3.GetArray());
		}

		private static string CurrentTemplate(string template)
		{
			if (string.IsNullOrEmpty(template))
			{
				return template;
			}
			if (!CurrentTemplates.TryGetValue(template, out var value))
			{
				value = EncodeItem(DecodeTemplateItem(template));
				CurrentTemplates[template] = value;
			}
			return value;
		}

		private static ItemData DecodeTemplateItem(string template)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Invalid comparison between Unknown and I4
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage(Convert.FromBase64String(template));
			Item val2 = (Item)val.ReadInt();
			if ((int)val2 < 108 || val.ReadUShort() != 1)
			{
				throw new FormatException("Invalid item template version/count.");
			}
			(int, ItemData) tuple = ItemData.Load(val, val2);
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(tuple.Item1);
			if (!Object.op_Implicit((Object)(object)itemPrefab))
			{
				throw new InvalidOperationException("Stored item's mod is missing. Restore it before withdrawing.");
			}
			ItemData item = tuple.Item2;
			item.m_shared = itemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared;
			item.m_dropPrefab = itemPrefab;
			return item;
		}

		private ItemData Item(BulkState state)
		{
			if (cachedItem != null)
			{
				return cachedItem;
			}
			cachedItem = DecodeTemplateItem(state.Template);
			return cachedItem;
		}

		private static void Say(Humanoid user, string text)
		{
			((Character)user).Message((MessageType)2, text, 0, (Sprite)null, false);
		}
	}
	[HarmonyPatch(typeof(Piece), "CanBeRemoved")]
	internal static class BulkRemovalProtection
	{
		private static void Postfix(Piece __instance, ref bool __result)
		{
			BulkBox component = ((Component)__instance).GetComponent<BulkBox>();
			if (Object.op_Implicit((Object)(object)component) && component.ProtectContents)
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(WearNTear), "ApplyDamage")]
	internal static class BulkDamageProtection
	{
		private static bool Prefix(WearNTear __instance, ref bool __result)
		{
			BulkBox component = ((Component)__instance).GetComponent<BulkBox>();
			if (!Object.op_Implicit((Object)(object)component) || !component.ProtectContents)
			{
				return true;
			}
			__result = false;
			return false;
		}
	}
	[HarmonyPatch(typeof(WearNTear), "Destroy")]
	internal static class BulkDestroyProtection
	{
		private static bool Prefix(WearNTear __instance)
		{
			BulkBox component = ((Component)__instance).GetComponent<BulkBox>();
			if (Object.op_Implicit((Object)(object)component))
			{
				return !component.ProtectContents;
			}
			return true;
		}
	}
	internal sealed class BulkState
	{
		public BigInteger Count { get; }

		public string Template { get; }

		public static BulkState Empty => new BulkState(BigInteger.Zero, "");

		public BulkState(BigInteger count, string template)
		{
			if (count < 0L)
			{
				throw new ArgumentOutOfRangeException("count");
			}
			if (count > 0L && string.IsNullOrEmpty(template))
			{
				throw new ArgumentException("Missing item template.");
			}
			Count = count;
			Template = template ?? "";
		}

		public string Encode()
		{
			return "1|" + Count.ToString(CultureInfo.InvariantCulture) + "|" + Template;
		}

		public static BulkState Decode(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return Empty;
			}
			string[] array = text.Split('|');
			if (array.Length != 3 || array[0] != "1" || !BigInteger.TryParse(array[1], NumberStyles.None, CultureInfo.InvariantCulture, out var result))
			{
				throw new FormatException("Invalid bulk box data; preserved without modification.");
			}
			if (array[2].Length > 0)
			{
				Convert.FromBase64String(array[2]);
			}
			return new BulkState(result, array[2]);
		}

		public BulkState Deposit(string template, int amount)
		{
			if (amount <= 0)
			{
				throw new ArgumentOutOfRangeException("amount");
			}
			if (!string.IsNullOrEmpty(Template) && Template != template)
			{
				throw new InvalidOperationException("This box is assigned to a different item or variant.");
			}
			return new BulkState(Count + amount, template);
		}

		public BulkState Withdraw(BigInteger amount)
		{
			if (amount <= 0L || amount > Count)
			{
				throw new ArgumentOutOfRangeException("amount");
			}
			return new BulkState(Count - amount, Template);
		}

		public BulkState AssignFromSlot(string template, int amount)
		{
			return (Count.IsZero ? Empty : this).Deposit(template, amount);
		}
	}
	internal static class ControllerStorageInput
	{
		[HarmonyPatch(typeof(InventoryGui), "Update")]
		private static class InventoryGuiUpdatePatch
		{
			private static void Prefix()
			{
				TryOpenStoreAndCraft(Player.m_localPlayer);
			}
		}

		[HarmonyPatch(typeof(Player), "UpdateHover")]
		private static class PlayerHoverPatch
		{
			private static void Postfix(Player __instance)
			{
				if (!CanHandle(__instance))
				{
					return;
				}
				GameObject hoverObject = ((Humanoid)__instance).GetHoverObject();
				if (!Object.op_Implicit((Object)(object)hoverObject))
				{
					return;
				}
				BulkBox componentInParent = hoverObject.GetComponentInParent<BulkBox>();
				SortingStation componentInParent2 = hoverObject.GetComponentInParent<SortingStation>();
				MuninWaystation componentInParent3 = hoverObject.GetComponentInParent<MuninWaystation>();
				if (!Object.op_Implicit((Object)(object)componentInParent) && !Object.op_Implicit((Object)(object)componentInParent2) && !Object.op_Implicit((Object)(object)componentInParent3))
				{
					return;
				}
				try
				{
					ZInput.ResetButtonStatus("JoySit");
					if (ZInput.GetButton("JoyButtonX") || ZInput.GetButtonDown("JoyButtonX") || ZInput.GetButtonUp("JoyButtonX"))
					{
						if (AlternateUseHeld && ZInput.GetButtonDown("JoyButtonX"))
						{
							if (Object.op_Implicit((Object)(object)componentInParent))
							{
								componentInParent.UseOneWithController(__instance);
							}
							else if (Object.op_Implicit((Object)(object)componentInParent2))
							{
								componentInParent2.ToggleAutoPickup((Humanoid)(object)__instance);
							}
						}
						ZInput.ResetButtonStatus("JoyButtonX");
						ZInput.ResetButtonStatus("JoyHide");
						ZInput.ResetButtonStatus("JoyAttack");
						ZInput.ResetButtonStatus("JoyAutoPickup");
						ZInput.ResetButtonStatus("JoyRadial");
					}
					if (Object.op_Implicit((Object)(object)componentInParent) && AlternateUseHeld)
					{
						TryOpenStoreAndCraft(__instance);
						if (ZInput.GetButtonDown("JoyDPadLeft") || ZInput.GetButtonDown("JoyDPadRight"))
						{
							int direction = (ZInput.GetButtonDown("JoyDPadRight") ? 1 : (-1));
							ZInput.ResetButtonStatus("JoyDPadLeft");
							ZInput.ResetButtonStatus("JoyDPadRight");
							ZInput.ResetButtonStatus("JoyHotbarLeft");
							ZInput.ResetButtonStatus("JoyHotbarRight");
							componentInParent.CycleWithdrawalWithController(direction);
						}
					}
				}
				catch (Exception arg)
				{
					Logger.LogError((object)$"Controller storage action failed: {arg}");
				}
			}
		}

		internal static bool Active => ZInput.IsGamepadActive();

		internal static string AlternateUseKey
		{
			get
			{
				if (!Active || !ZInput.IsNonClassicFunctionality())
				{
					return "$KEY_AltPlace";
				}
				return "$KEY_AltKeys";
			}
		}

		internal static string SecondaryActionKey => AlternateUseKey + " + " + Bound("JoyButtonX");

		internal static string AmountActionKey => AlternateUseKey + " + " + Bound("JoyDPadLeft") + "/" + Bound("JoyDPadRight");

		internal static string StoreAndCraftKey => AlternateUseKey + " + " + Bound("JoyButtonY");

		private static bool AlternateUseHeld
		{
			get
			{
				if (!ZInput.IsNonClassicFunctionality())
				{
					return ZInput.GetButton("JoyAltPlace");
				}
				return ZInput.GetButton("JoyAltKeys");
			}
		}

		private static string Bound(string action)
		{
			ZInput instance = ZInput.instance;
			string text = ((instance != null) ? instance.GetBoundKeyString(action, false) : null);
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
			return action;
		}

		private static bool CanHandle(Player player)
		{
			if (Object.op_Implicit((Object)(object)player) && (Object)(object)player == (Object)(object)Player.m_localPlayer && Active && !InventoryGui.IsVisible() && !TextInput.IsVisible() && !Console.IsVisible() && (!Object.op_Implicit((Object)(object)Chat.instance) || !Chat.instance.HasFocus()) && !Minimap.IsOpen() && !Hud.InRadial() && !Hud.IsPieceSelectionVisible() && !PlayerController.HasInputDelay)
			{
				return !((Character)player).InPlaceMode();
			}
			return false;
		}

		private static bool TryOpenStoreAndCraft(Player player)
		{
			if (!CanHandle(player) || !AlternateUseHeld || !StoreAndCraftBridge.IsLinkUiAvailable || !ZInput.GetButtonDown("JoyButtonY"))
			{
				return false;
			}
			GameObject hoverObject = ((Humanoid)player).GetHoverObject();
			if (!Object.op_Implicit((Object)(object)hoverObject) || !Object.op_Implicit((Object)(object)hoverObject.GetComponentInParent<BulkBox>()) || !BulkBox.TryGetHoveredLinkContainer(out var container))
			{
				return false;
			}
			ZInput.ResetButtonStatus("JoyButtonY");
			ZInput.ResetButtonStatus("Inventory");
			try
			{
				StoreAndCraftBridge.TryOpenSettings(container);
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"StoreAndCraft controller settings failed: {arg}");
			}
			return true;
		}
	}
	internal sealed class CraftBudget
	{
		internal readonly Dictionary<string, int> Remaining = new Dictionary<string, int>();

		internal void Need(string name, int required, int carried)
		{
			Remaining.TryGetValue(name, out var value);
			Remaining[name] = checked(value + Math.Max(0, required - carried));
		}

		internal void Consumed(string name, int amount)
		{
			if (Remaining.TryGetValue(name, out var value))
			{
				Remaining[name] = Math.Max(0, value - Math.Max(0, amount));
			}
		}
	}
	[HarmonyPatch(typeof(ZDOMan), "DestroyZDO", new Type[] { typeof(ZDO) })]
	internal static class MissingPrefabProtection
	{
		private static bool Prefix(ZDO zdo)
		{
			int prefab = zdo.GetPrefab();
			if (prefab == StringExtensionMethods.GetStableHashCode("M" + "ike_BulkStorageBox"))
			{
				if (Object.op_Implicit((Object)(object)ZNetScene.instance))
				{
					return Object.op_Implicit((Object)(object)ZNetScene.instance.GetPrefab(prefab));
				}
				return false;
			}
			return true;
		}
	}
	internal static class ModelAsset
	{
		internal sealed class MeshPart
		{
			internal string Material;

			internal Mesh Mesh;
		}

		internal static readonly Vector3 BoxSize = new Vector3(0.55f, 0.4f, 0.55f);

		internal static readonly Vector3 BoxVisualSize = new Vector3(0.545f, 0.395f, 0.545f);

		internal static readonly Vector3 ColumnSize = new Vector3(0.75f, 1.2f, 0.75f);

		internal static readonly Vector3 WaystationChestSize = new Vector3(1.26f, 0.97f, 0.78f);

		private static readonly Dictionary<string, Color[]> Colors = new Dictionary<string, Color[]>
		{
			["dedicated_storage_box_wood"] = (Color[])(object)new Color[1]
			{
				new Color(0.3f, 0.15f, 0.07f)
			},
			["dedicated_storage_box_iron"] = (Color[])(object)new Color[1]
			{
				new Color(0.12f, 0.14f, 0.15f)
			},
			["dedicated_storage_box_rune"] = (Color[])(object)new Color[1]
			{
				new Color(0f, 0.72f, 0.88f)
			},
			["dedicated_storage_box_panel"] = (Color[])(object)new Color[1]
			{
				new Color(0.055f, 0.045f, 0.035f)
			},
			["munins_waystation_wood"] = (Color[])(object)new Color[1]
			{
				new Color(0.43f, 0.24f, 0.12f)
			},
			["munins_waystation_wood_dark"] = (Color[])(object)new Color[1]
			{
				new Color(0.29f, 0.15f, 0.08f)
			},
			["munins_waystation_iron"] = (Color[])(object)new Color[1]
			{
				new Color(0.12f, 0.14f, 0.15f)
			},
			["munins_waystation_rune"] = (Color[])(object)new Color[1]
			{
				new Color(0f, 0.72f, 0.88f)
			}
		};

		private static readonly Dictionary<string, Texture2D> Textures = new Dictionary<string, Texture2D>();

		internal static Texture2D Texture(string resource)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			if (Textures.TryGetValue(resource, out var value))
			{
				return value;
			}
			value = new Texture2D(2, 2, (TextureFormat)4, false, false)
			{
				name = resource,
				filterMode = (FilterMode)1,
				wrapMode = (TextureWrapMode)0
			};
			if (!ImageConversion.LoadImage(value, Read(resource), true))
			{
				throw new InvalidDataException("Unable to load runtime texture " + resource + ".");
			}
			((Texture)value).filterMode = (FilterMode)1;
			((Texture)value).wrapMode = (TextureWrapMode)0;
			Textures.Add(resource, value);
			return value;
		}

		internal static Material Material(string model, Material source)
		{
			return CreateMaterial(model, source, preserveSurfaceDefaults: false);
		}

		internal static Material WaystationMaterial(string model, Material source)
		{
			return CreateMaterial(model, source, preserveSurfaceDefaults: true);
		}

		internal static Material DedicatedStorageMaterial(string part, Material source)
		{
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			string model = part switch
			{
				"Wood" => "dedicated_storage_box_wood", 
				"Iron" => "dedicated_storage_box_iron", 
				"RuneGlow" => "dedicated_storage_box_rune", 
				"DisplayPanel" => "dedicated_storage_box_panel", 
				_ => throw new InvalidDataException("Unknown Dedicated Storage material group: " + part), 
			};
			Texture2D surface = ((part == "Wood") ? Texture("DedicatedStorageChest.textures.DSC_Wood_128.png") : ((part == "Iron") ? Texture("DedicatedStorageChest.textures.DSC_Iron_128.png") : null));
			Material val = CreateMaterial(model, source, preserveSurfaceDefaults: false, surface);
			switch (part)
			{
			case "Iron":
				if (val.HasProperty("_Metallic"))
				{
					val.SetFloat("_Metallic", 0.68f);
				}
				if (val.HasProperty("_Glossiness"))
				{
					val.SetFloat("_Glossiness", 0.3f);
				}
				break;
			case "RuneGlow":
				if (val.HasProperty("_Metallic"))
				{
					val.SetFloat("_Metallic", 0.08f);
				}
				if (val.HasProperty("_Glossiness"))
				{
					val.SetFloat("_Glossiness", 0.38f);
				}
				if (val.HasProperty("_EmissionColor"))
				{
					val.SetColor("_EmissionColor", new Color(0f, 0.35f, 0.6f, 1f));
					val.EnableKeyword("_EMISSION");
				}
				break;
			case "DisplayPanel":
				if (val.HasProperty("_Glossiness"))
				{
					val.SetFloat("_Glossiness", 0.06f);
				}
				break;
			}
			return val;
		}

		private static Material CreateMaterial(string model, Material source, bool preserveSurfaceDefaults, Texture2D surface = null)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_00a5: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)source) || !Object.op_Implicit((Object)(object)source.shader))
			{
				throw new InvalidOperationException("Base chest shader is unavailable.");
			}
			if (!Object.op_Implicit((Object)(object)surface))
			{
				Color[] array = Colors[model];
				surface = new Texture2D(array.Length, 1, (TextureFormat)4, false, false)
				{
					filterMode = (FilterMode)0,
					wrapMode = (TextureWrapMode)1
				};
				for (int i = 0; i < array.Length; i++)
				{
					surface.SetPixel(i, 0, ((Color)(ref array[i])).gamma);
				}
				surface.Apply();
			}
			Material val = (preserveSurfaceDefaults ? new Material(source)
			{
				name = model + "_material"
			} : new Material(source.shader)
			{
				name = model + "_material",
				shaderKeywords = Array.Empty<string>()
			});
			val.mainTexture = (Texture)(object)surface;
			if (val.HasProperty("_Color"))
			{
				val.SetColor("_Color", Color.white);
			}
			if (val.HasProperty("_EmissionColor"))
			{
				val.SetColor("_EmissionColor", Color.black);
			}
			if (val.HasProperty("_Glossiness"))
			{
				val.SetFloat("_Glossiness", 0.12f);
			}
			if (val.HasProperty("_Metallic"))
			{
				val.SetFloat("_Metallic", 0f);
			}
			return val;
		}

		internal static Mesh Mesh(string model, Vector3 size)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_031d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0324: Unknown result type (might be due to invalid IL or missing references)
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0333: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0342: Unknown result type (might be due to invalid IL or missing references)
			//IL_034a: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0353: Unknown result type (might be due to invalid IL or missing references)
			//IL_036d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_0383: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_039b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ab: Expected O, but got Unknown
			List<Vector3> list = new List<Vector3>();
			List<Vector2> list2 = new List<Vector2>();
			List<Vector3> list3 = new List<Vector3>();
			List<Vector3> list4 = new List<Vector3>();
			List<Vector2> list5 = new List<Vector2>();
			List<Vector3> list6 = new List<Vector3>();
			List<int> list7 = new List<int>();
			string[] array = Encoding.UTF8.GetString(Read(model + ".obj")).Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Trim().Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
				if (array2.Length == 0)
				{
					continue;
				}
				if (array2[0] == "v")
				{
					list.Add(new Vector3(0f - F(array2[1]), F(array2[2]), F(array2[3])));
				}
				else if (array2[0] == "vt")
				{
					list2.Add(new Vector2(F(array2[1]), F(array2[2])));
				}
				else if (array2[0] == "vn")
				{
					list3.Add(new Vector3(0f - F(array2[1]), F(array2[2]), F(array2[3])));
				}
				else if (array2[0] == "f")
				{
					int count = list4.Count;
					for (int j = 1; j < array2.Length; j++)
					{
						string[] array3 = array2[j].Split('/');
						list4.Add(list[int.Parse(array3[0], CultureInfo.InvariantCulture) - 1]);
						list5.Add(list2[int.Parse(array3[1], CultureInfo.InvariantCulture) - 1]);
						list6.Add(list3[int.Parse(array3[2], CultureInfo.InvariantCulture) - 1]);
					}
					for (int k = 1; k < array2.Length - 2; k++)
					{
						list7.Add(count);
						list7.Add(count + k + 1);
						list7.Add(count + k);
					}
				}
			}
			if (list4.Count == 0 || list7.Count == 0 || list4.Count > 65535)
			{
				throw new InvalidDataException(model + " has invalid runtime geometry.");
			}
			Bounds val = default(Bounds);
			((Bounds)(ref val))..ctor(list4[0], Vector3.zero);
			foreach (Vector3 item in list4)
			{
				((Bounds)(ref val)).Encapsulate(item);
			}
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(size.x / ((Bounds)(ref val)).size.x, size.y / ((Bounds)(ref val)).size.y, size.z / ((Bounds)(ref val)).size.z);
			Vector3 val3 = default(Vector3);
			((Vector3)(ref val3))..ctor(((Bounds)(ref val)).center.x, ((Bounds)(ref val)).min.y, ((Bounds)(ref val)).center.z);
			for (int l = 0; l < list4.Count; l++)
			{
				list4[l] = Vector3.Scale(list4[l] - val3, val2);
				Vector3 val4 = list6[l];
				int index = l;
				Vector3 val5 = new Vector3(val4.x / val2.x, val4.y / val2.y, val4.z / val2.z);
				list6[index] = ((Vector3)(ref val5)).normalized;
			}
			Mesh val6 = new Mesh
			{
				name = model + "_mesh"
			};
			val6.SetVertices(list4);
			val6.SetUVs(0, list5);
			val6.SetNormals(list6);
			val6.SetTriangles(list7, 0);
			val6.RecalculateBounds();
			return val6;
		}

		internal static List<MeshPart> MeshParts(string model, Vector3 size)
		{
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Unknown result type (might be due to invalid IL or missing references)
			//IL_0337: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0362: Unknown result type (might be due to invalid IL or missing references)
			//IL_0364: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_0377: Unknown result type (might be due to invalid IL or missing references)
			//IL_0479: Unknown result type (might be due to invalid IL or missing references)
			//IL_047e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0495: Unknown result type (might be due to invalid IL or missing references)
			//IL_049a: Unknown result type (might be due to invalid IL or missing references)
			//IL_049e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0405: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06be: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0705: Unknown result type (might be due to invalid IL or missing references)
			//IL_070f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0717: Unknown result type (might be due to invalid IL or missing references)
			//IL_071c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0720: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_050b: Unknown result type (might be due to invalid IL or missing references)
			//IL_075b: Unknown result type (might be due to invalid IL or missing references)
			//IL_076b: Unknown result type (might be due to invalid IL or missing references)
			//IL_077b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0780: Unknown result type (might be due to invalid IL or missing references)
			//IL_0527: Unknown result type (might be due to invalid IL or missing references)
			//IL_0533: Unknown result type (might be due to invalid IL or missing references)
			//IL_0541: Unknown result type (might be due to invalid IL or missing references)
			//IL_0552: Unknown result type (might be due to invalid IL or missing references)
			//IL_055e: Unknown result type (might be due to invalid IL or missing references)
			//IL_056c: Unknown result type (might be due to invalid IL or missing references)
			//IL_057b: Unknown result type (might be due to invalid IL or missing references)
			//IL_05bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_07fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0811: Expected O, but got Unknown
			//IL_061d: Unknown result type (might be due to invalid IL or missing references)
			//IL_063a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0649: Unknown result type (might be due to invalid IL or missing references)
			//IL_067b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0698: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a7: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			List<Vector2> list2 = new List<Vector2>();
			List<Vector3> list3 = new List<Vector3>();
			Dictionary<string, List<string[]>> dictionary = new Dictionary<string, List<string[]>>();
			string text = "Wood";
			string text2 = "WaystationChest";
			string[] array = Encoding.UTF8.GetString(Read(model + ".obj")).Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Trim().Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
				if (array2.Length == 0)
				{
					continue;
				}
				if (array2[0] == "v")
				{
					list.Add(new Vector3(0f - F(array2[1]), F(array2[2]), F(array2[3])));
				}
				else if (array2[0] == "vt")
				{
					list2.Add(new Vector2(F(array2[1]), F(array2[2])));
				}
				else if (array2[0] == "vn")
				{
					list3.Add(new Vector3(0f - F(array2[1]), F(array2[2]), F(array2[3])));
				}
				else if (array2[0] == "o")
				{
					text2 = ((array2.Length > 1) ? array2[1] : text2);
				}
				else if (array2[0] == "usemtl")
				{
					text = array2[1];
				}
				else if (array2[0] == "f")
				{
					string key = text2 + "|" + text;
					if (!dictionary.ContainsKey(key))
					{
						dictionary.Add(key, new List<string[]>());
					}
					dictionary[key].Add(array2.Skip(1).ToArray());
				}
			}
			if (list.Count == 0 || dictionary.Count == 0)
			{
				throw new InvalidDataException(model + " has invalid runtime geometry.");
			}
			Bounds val = default(Bounds);
			((Bounds)(ref val))..ctor(list[0], Vector3.zero);
			foreach (Vector3 item in list)
			{
				((Bounds)(ref val)).Encapsulate(item);
			}
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(size.x / ((Bounds)(ref val)).size.x, size.y / ((Bounds)(ref val)).size.y, size.z / ((Bounds)(ref val)).size.z);
			Vector3 val3 = default(Vector3);
			((Vector3)(ref val3))..ctor(((Bounds)(ref val)).center.x, ((Bounds)(ref val)).min.y, ((Bounds)(ref val)).center.z);
			List<MeshPart> list4 = new List<MeshPart>();
			Bounds bounds = default(Bounds);
			foreach (KeyValuePair<string, List<string[]>> item2 in dictionary)
			{
				List<Vector3> list5 = new List<Vector3>();
				List<Vector2> list6 = new List<Vector2>();
				List<Vector3> list7 = new List<Vector3>();
				List<int> list8 = new List<int>();
				Vector3 val6;
				foreach (string[] item3 in item2.Value)
				{
					int count = list5.Count;
					Vector3 val4 = list[int.Parse(item3[0].Split('/')[0], CultureInfo.InvariantCulture) - 1];
					Vector3 val5 = list[int.Parse(item3[1].Split('/')[0], CultureInfo.InvariantCulture) - 1];
					val6 = Vector3.Cross(list[int.Parse(item3[2].Split('/')[0], CultureInfo.InvariantCulture) - 1] - val4, val5 - val4);
					Vector3 normalized = ((Vector3)(ref val6)).normalized;
					for (int j = 0; j < item3.Length; j++)
					{
						string[] array3 = item3[j].Split('/');
						int index = int.Parse(array3[0], CultureInfo.InvariantCulture) - 1;
						list5.Add(list[index]);
						list6.Add((array3.Length > 1 && !string.IsNullOrEmpty(array3[1])) ? list2[int.Parse(array3[1], CultureInfo.InvariantCulture) - 1] : Vector2.zero);
						list7.Add((array3.Length > 2) ? list3[int.Parse(array3[2], CultureInfo.InvariantCulture) - 1] : normalized);
					}
					for (int k = 1; k < item3.Length - 1; k++)
					{
						list8.Add(count);
						list8.Add(count + k + 1);
						list8.Add(count + k);
					}
				}
				((Bounds)(ref bounds))..ctor(list5[0], Vector3.zero);
				foreach (Vector3 item4 in list5)
				{
					((Bounds)(ref bounds)).Encapsulate(item4);
				}
				for (int l = 0; l < list5.Count; l++)
				{
					if (list2.Count == 0)
					{
						list6[l] = ProjectedUv(list5[l], list7[l], bounds);
						if (item2.Key.StartsWith("MWC_Lid|", StringComparison.Ordinal) && Mathf.Abs(list7[l].x) < 0.8f)
						{
							list6[l] = new Vector2(Mathf.InverseLerp(((Bounds)(ref bounds)).min.x, ((Bounds)(ref bounds)).max.x, list5[l].x), Mathf.InverseLerp(((Bounds)(ref bounds)).min.z, ((Bounds)(ref bounds)).max.z, list5[l].z));
						}
						if (!model.StartsWith("DedicatedStorageChest.", StringComparison.Ordinal))
						{
							if (item2.Key.EndsWith("|Wood", StringComparison.Ordinal))
							{
								list6[l] = new Vector2(Mathf.Lerp(1f / 32f, 57f / 128f, list6[l].x), Mathf.Lerp(69f / 128f, 61f / 64f, list6[l].y));
							}
							else if (item2.Key.EndsWith("|Iron", StringComparison.Ordinal))
							{
								list6[l] = new Vector2(Mathf.Lerp(0.5625f, 113f / 128f, list6[l].x), Mathf.Lerp(81f / 128f, 121f / 128f, list6[l].y));
							}
							else if (item2.Key.EndsWith("|RuneGlow", StringComparison.Ordinal))
							{
								list6[l] = new Vector2(Mathf.Lerp(3f / 128f, 17f / 128f, list6[l].x), Mathf.Lerp(47f / 64f, 31f / 32f, list6[l].y));
							}
						}
					}
					list5[l] = Vector3.Scale(list5[l] - val3, val2);
					int index2 = l;
					val6 = new Vector3(list7[l].x / val2.x, list7[l].y / val2.y, list7[l].z / val2.z);
					list7[index2] = ((Vector3)(ref val6)).normalized;
				}
				int count2 = list5.Count;
				int count3 = list8.Count;
				for (int m = 0; m < count2; m++)
				{
					list5.Add(list5[m]);
					list6.Add(list6[m]);
					list7.Add(-list7[m]);
				}
				for (int n = 0; n < count3; n += 3)
				{
					list8.Add(list8[n] + count2);
					list8.Add(list8[n + 2] + count2);
					list8.Add(list8[n + 1] + count2);
				}
				string[] array4 = item2.Key.Split('|');
				Mesh val7 = new Mesh
				{
					name = model + "_" + array4[0]
				};
				val7.SetVertices(list5);
				val7.SetUVs(0, list6);
				val7.SetNormals(list7);
				val7.SetTriangles(list8, 0);
				val7.RecalculateBounds();
				list4.Add(new MeshPart
				{
					Material = array4[1],
					Mesh = val7
				});
			}
			return list4;
		}

		private static Vector2 ProjectedUv(Vector3 position, Vector3 normal, Bounds bounds)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: 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)
			//IL_0084: 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)
			//IL_009a: 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)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.InverseLerp(((Bounds)(ref bounds)).min.x, ((Bounds)(ref bounds)).max.x, position.x);
			float num2 = Mathf.InverseLerp(((Bounds)(ref bounds)).min.y, ((Bounds)(ref bounds)).max.y, position.y);
			float num3 = Mathf.InverseLerp(((Bounds)(ref bounds)).min.z, ((Bounds)(ref bounds)).max.z, position.z)