Decompiled source of YggdrasilNetwork v1.0.0

YggdrasilNetwork.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.UI;
using YggdrasilNetwork.I18n;
using YggdrasilNetwork.Items;
using YggdrasilNetwork.Models;
using YggdrasilNetwork.Network;
using YggdrasilNetwork.Pieces;
using YggdrasilNetwork.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("YggdrasilNetwork")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+41527b33963c78282fde63e507328a4882467cc5")]
[assembly: AssemblyProduct("Yggdrasil Network")]
[assembly: AssemblyTitle("YggdrasilNetwork")]
[assembly: AssemblyVersion("1.0.0.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 YggdrasilNetwork
{
	internal static class Visuals
	{
		public static readonly Color RuneBlue = new Color(0.3f, 0.7f, 1f);

		public static readonly Color RunePurple = new Color(0.72f, 0.4f, 1f);

		private static readonly MethodInfo LoadImage = Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")?.GetMethod("LoadImage", new Type[2]
		{
			typeof(Texture2D),
			typeof(byte[])
		});

		private static string AssetsDir => Path.Combine(Path.GetDirectoryName(typeof(YggdrasilPlugin).Assembly.Location) ?? "", "Assets");

		public static Sprite Icon(string name)
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = EmbeddedTexture("icon_" + name + ".png");
			if (!Object.op_Implicit((Object)(object)val))
			{
				string text = Path.Combine(AssetsDir, "icon_" + name + ".png");
				if (File.Exists(text))
				{
					val = AssetUtils.LoadTexture(text, false);
				}
			}
			if (!Object.op_Implicit((Object)(object)val))
			{
				YggdrasilPlugin.Log.LogWarning((object)("Falta el ícono icon_" + name + ".png"));
				return null;
			}
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
		}

		private static Texture2D EmbeddedTexture(string file)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			using Stream stream = typeof(YggdrasilPlugin).Assembly.GetManifestResourceStream("YggdrasilNetwork.Assets." + file);
			if (stream == null)
			{
				return null;
			}
			byte[] array = new byte[stream.Length];
			int num;
			for (int i = 0; i < array.Length; i += num)
			{
				num = stream.Read(array, i, array.Length - i);
				if (num <= 0)
				{
					break;
				}
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false)
			{
				name = file
			};
			return (LoadImage != null && (bool)LoadImage.Invoke(null, new object[2] { val, array })) ? val : null;
		}

		public static void Tint(GameObject go, Color tint, Color emission)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if (((object)val).GetType().Name == "ParticleSystemRenderer")
				{
					continue;
				}
				Material[] sharedMaterials = val.sharedMaterials;
				Material[] array = (Material[])(object)new Material[sharedMaterials.Length];
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					if (Object.op_Implicit((Object)(object)sharedMaterials[j]))
					{
						Material val2 = new Material(sharedMaterials[j]);
						if (val2.HasProperty("_Color"))
						{
							val2.SetColor("_Color", val2.GetColor("_Color") * tint);
						}
						if (emission != Color.black && val2.HasProperty("_EmissionColor"))
						{
							val2.EnableKeyword("_EMISSION");
							val2.SetColor("_EmissionColor", emission);
						}
						array[j] = val2;
					}
				}
				val.sharedMaterials = array;
			}
		}

		public static void AddLight(GameObject go, Color color, float range, float intensity, float height)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("RuneVaultLight");
			val.transform.SetParent(go.transform, false);
			val.transform.localPosition = new Vector3(0f, height, 0f);
			Light obj = val.AddComponent<Light>();
			obj.type = (LightType)2;
			obj.color = color;
			obj.range = range;
			obj.intensity = intensity;
			obj.shadows = (LightShadows)0;
		}
	}
	[BepInPlugin("jeanne.valheim.yggdrasilnetwork", "Yggdrasil Network", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class YggdrasilPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "jeanne.valheim.yggdrasilnetwork";

		public const string PluginName = "Yggdrasil Network";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<float> CoreRadius;

		internal static ConfigEntry<float> RadiusLevel1;

		internal static ConfigEntry<float> RadiusLevel2;

		internal static ConfigEntry<string> CostLevel1;

		internal static ConfigEntry<string> CostLevel2;

		internal static ConfigEntry<float> PillarRadius;

		internal static ConfigEntry<bool> DebugLog;

		internal static ConfigEntry<ChestFilter> ChestFilterMode;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Expected O, but got Unknown
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ConfigurationManagerAttributes val = new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			};
			CoreRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Red", "Radio del núcleo", 8f, new ConfigDescription("Metros alrededor del núcleo en que se enlazan cofres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 16f), new object[1] { val }));
			RadiusLevel1 = ((BaseUnityPlugin)this).Config.Bind<float>("Progresión", "Radio nivel 1", 14f, new ConfigDescription("Radio del núcleo tras la mejora del Pantano. Nunca menor que el radio base.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 32f), new object[1] { val }));
			RadiusLevel2 = ((BaseUnityPlugin)this).Config.Bind<float>("Progresión", "Radio nivel 2", 20f, new ConfigDescription("Radio del núcleo tras la mejora de la Montaña. Nunca menor que el nivel 1.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(8f, 64f), new object[1] { val }));
			CostLevel1 = ((BaseUnityPlugin)this).Config.Bind<string>("Progresión", "Costo nivel 1", "Iron:20,TrophyBonemass:1", new ConfigDescription("Materiales para mejorar el núcleo a nivel 1 (prefab:cantidad, separados por coma).", (AcceptableValueBase)null, new object[1] { val }));
			CostLevel2 = ((BaseUnityPlugin)this).Config.Bind<string>("Progresión", "Costo nivel 2", "Silver:20,TrophyDragonQueen:1", new ConfigDescription("Materiales para mejorar el núcleo a nivel 2 (prefab:cantidad, separados por coma).", (AcceptableValueBase)null, new object[1] { val }));
			PillarRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Progresión", "Radio del pilar rúnico", 10f, new ConfigDescription("Metros que cubre cada pilar rúnico conectado a la red.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 32f), new object[1] { val }));
			DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("Depuración", "Registro detallado", false, "Escribe en el log el detalle de los cofres vinculados (para encontrar errores).");
			ChestFilterMode = ((BaseUnityPlugin)this).Config.Bind<ChestFilter>("Red", "Cofres que se enlazan", ChestFilter.ConPermiso, "ConPermiso: todos los cofres que puedes abrir (útil en bases compartidas). SoloPropios: solo los cofres que construiste tú.");
			Texts.Register();
			PieceRegistration.Init();
			AccessRune.Init();
			TerminalWindow.Create(((Component)this).gameObject);
			((Component)this).gameObject.AddComponent<LinkedChestTracker>();
			_harmony = new Harmony("jeanne.valheim.yggdrasilnetwork");
			_harmony.PatchAll(typeof(YggdrasilPlugin).Assembly);
			Log.LogInfo((object)"Yggdrasil Network 1.0.0 cargado.");
		}

		private void Start()
		{
			Compat.Detect();
			if (Compat.QuickStackStore)
			{
				QuickStackCompat.TryPatch(_harmony, (MonoBehaviour)(object)this);
			}
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class Compat
	{
		public const string MultiUserChestGuid = "com.maxsch.valheim.MultiUserChest";

		public const string StashLinkGuid = "rhyzt.valheim.stashlink";

		public const string QuickStackStoreGuid = "goldenrevolver.quick_stack_store";

		public const string PathOfValheimanGuid = "treextr.pathofvalheiman";

		public static bool MultiUserChest { get; private set; }

		public static bool StashLink { get; private set; }

		public static bool QuickStackStore { get; private set; }

		public static bool PathOfValheiman { get; private set; }

		public static bool OtherCraftFromChests
		{
			get
			{
				if (!StashLink)
				{
					return PathOfValheiman;
				}
				return true;
			}
		}

		public static void Detect()
		{
			MultiUserChest = Chainloader.PluginInfos.ContainsKey("com.maxsch.valheim.MultiUserChest");
			StashLink = Chainloader.PluginInfos.ContainsKey("rhyzt.valheim.stashlink");
			QuickStackStore = Chainloader.PluginInfos.ContainsKey("goldenrevolver.quick_stack_store");
			PathOfValheiman = Chainloader.PluginInfos.ContainsKey("treextr.pathofvalheiman");
			ManualLogSource log = YggdrasilPlugin.Log;
			log.LogInfo((object)$"Compat: MultiUserChest={MultiUserChest}, StashLink={StashLink}, QuickStackStore={QuickStackStore}, PathOfValheiman={PathOfValheiman}");
			if (OtherCraftFromChests)
			{
				log.LogInfo((object)"Hay otro mod de crafteo desde cofres: el crafteo desde la red queda desactivado para evitar doble descuento.");
			}
		}
	}
}
namespace YggdrasilNetwork.UI
{
	internal class TerminalWindow : MonoBehaviour
	{
		internal enum Category
		{
			Todo,
			Materiales,
			Comida,
			Armas,
			Armaduras,
			Herramientas,
			Otros
		}

		private enum SortMode
		{
			Cantidad,
			Nombre,
			Tipo
		}

		private const float MaxDistance = 6f;

		private const float RefreshSeconds = 0.5f;

		private const float OpenGraceSeconds = 0.4f;

		private const float Pad = 12f;

		private const float CellSize = 56f;

		private const float ExtraHeight = 150f;

		private static TerminalWindow _instance;

		private static readonly FieldRef<InventoryGui, ItemData> DragItem = AccessTools.FieldRefAccess<InventoryGui, ItemData>("m_dragItem");

		private static readonly FieldRef<InventoryGui, Inventory> DragInventory = AccessTools.FieldRefAccess<InventoryGui, Inventory>("m_dragInventory");

		private static readonly FieldRef<InventoryGui, int> DragAmount = AccessTools.FieldRefAccess<InventoryGui, int>("m_dragAmount");

		private AccessTerminal _terminal;

		private StorageCore _core;

		private bool _remote;

		private bool _open;

		private float _openedAt;

		private float _nextRefresh;

		private StorageNetwork _network;

		private List<NetworkItem> _items = new List<NetworkItem>();

		private Category _category;

		private SortMode _sort;

		private int _blockUntilFrame;

		private bool _inputBlocked;

		private GameObject _panel;

		private Text _chestsText;

		private InputField _search;

		private Text _footer;

		private RectTransform _gridContent;

		private readonly List<Text> _categoryLabels = new List<Text>();

		private readonly List<Text> _sortLabels = new List<Text>();

		private readonly List<ItemCell> _cells = new List<ItemCell>();

		private GameObject _dialog;

		private Text _dialogTitle;

		private InputField _dialogAmount;

		private Text _dialogTakeLabel;

		private NetworkItem _pending;

		internal const float RemoteRange = 2500f;

		private bool _remotePending;

		private bool _remoteUnlimited;

		private int _lastDropFrame = -100;

		internal static bool IsOpen
		{
			get
			{
				if (Object.op_Implicit((Object)(object)_instance))
				{
					return _instance._open;
				}
				return false;
			}
		}

		private float CurrentRemoteRange
		{
			get
			{
				if (!_remoteUnlimited)
				{
					return 2500f;
				}
				return float.PositiveInfinity;
			}
		}

		private int PendingMax
		{
			get
			{
				if (_pending != null)
				{
					return Mathf.Max(1, (_items.FirstOrDefault((NetworkItem i) => i.Matches(_pending.Sample)) ?? _pending).Amount);
				}
				return 1;
			}
		}

		private int PendingValue
		{
			get
			{
				if (!int.TryParse(_dialogAmount.text, out var result))
				{
					return 1;
				}
				return Mathf.Clamp(result, 1, PendingMax);
			}
		}

		internal static void Create(GameObject host)
		{
			if (!Object.op_Implicit((Object)(object)_instance))
			{
				_instance = host.AddComponent<TerminalWindow>();
			}
		}

		internal static void Open(AccessTerminal terminal, StorageCore core)
		{
			if (Object.op_Implicit((Object)(object)_instance) && Object.op_Implicit((Object)(object)InventoryGui.instance))
			{
				TerminalWindow instance = _instance;
				instance._terminal = terminal;
				instance._core = core;
				instance._remote = false;
				instance.ShowPanel();
			}
		}

		internal static void OpenRemote(bool unlimited = false)
		{
			if (Object.op_Implicit((Object)(object)_instance) && Object.op_Implicit((Object)(object)InventoryGui.instance) && !IsOpen)
			{
				_instance._remotePending = true;
				_instance._remoteUnlimited = unlimited;
				LinkedChests.Query(force: true);
			}
		}

		private void TryFinishRemoteOpen()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if (!_remotePending)
			{
				return;
			}
			_remotePending = false;
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				return;
			}
			if (!LinkedChests.HasCore)
			{
				((Character)localPlayer).Message((MessageType)2, Texts.T("rv_no_core_world"), 0, (Sprite)null, false);
				return;
			}
			float num = LinkedChests.DistanceToNetwork(((Component)localPlayer).transform.position);
			if (num > CurrentRemoteRange)
			{
				((Character)localPlayer).Message((MessageType)2, Texts.T("rv_remote_too_far", num.ToString("0"), 2500f.ToString("0")), 0, (Sprite)null, false);
				return;
			}
			_terminal = null;
			_core = StorageCore.All.FirstOrDefault((StorageCore c) => Object.op_Implicit((Object)(object)c));
			_remote = true;
			ShowPanel();
		}

		private void ShowPanel()
		{
			_open = true;
			_openedAt = Time.time;
			_nextRefresh = 0f;
			InventoryGui.instance.Show((Container)null, 1);
			if (!Object.op_Implicit((Object)(object)_panel) || !Object.op_Implicit((Object)(object)_dialog))
			{
				try
				{
					Build();
				}
				catch (Exception ex)
				{
					YggdrasilPlugin.Log.LogError((object)("No se pudo construir el panel de la terminal: " + ex));
					if (Object.op_Implicit((Object)(object)_panel))
					{
						Object.Destroy((Object)(object)_panel);
					}
					_panel = null;
					_open = false;
					return;
				}
			}
			_search.text = "";
			_category = Category.Todo;
			HideDialog();
			UpdateTabLabels();
			_panel.SetActive(true);
		}

		private void Close()
		{
			if (_open)
			{
				_open = false;
				_pending = null;
				_network = null;
				_items.Clear();
				if (Object.op_Implicit((Object)(object)_panel))
				{
					_panel.SetActive(false);
				}
				SetInputBlocked(block: false);
				if (InventoryGui.IsVisible() && Object.op_Implicit((Object)(object)InventoryGui.instance))
				{
					InventoryGui.instance.Hide();
				}
			}
		}

		internal static void StoreDraggedFromCursor()
		{
			if (IsOpen && Time.frameCount - _instance._lastDropFrame >= 30)
			{
				_instance.TryStoreDragged();
			}
		}

		internal static void NotifyChanged()
		{
			if (Object.op_Implicit((Object)(object)_instance))
			{
				_instance._nextRefresh = 0f;
				_instance.TryFinishRemoteOpen();
			}
		}

		internal static bool IsProtected(ItemData item)
		{
			if (!IsOpen || !_instance._remote || item == null || !Object.op_Implicit((Object)(object)item.m_dropPrefab))
			{
				return false;
			}
			string name = ((Object)item.m_dropPrefab).name;
			if (!(name == "RuneVault_AccessRune"))
			{
				return name == "RuneVault_VoidRune";
			}
			return true;
		}

		internal static void StoreFromInventory(ItemData item, int amount = -1)
		{
			if (IsOpen)
			{
				_instance.Store(item, (amount <= 0) ? item.m_stack : amount);
			}
		}

		private void Update()
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			if (!_open)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			bool flag = Time.time - _openedAt > 0.4f && !InventoryGui.IsVisible();
			bool flag2 = !Object.op_Implicit((Object)(object)localPlayer) || (_remote ? (LinkedChests.DistanceToNetwork(((Component)localPlayer).transform.position) > CurrentRemoteRange) : (!Object.op_Implicit((Object)(object)_terminal) || !Object.op_Implicit((Object)(object)_core) || Vector3.Distance(((Component)localPlayer).transform.position, ((Component)_terminal).transform.position) > 6f));
			if (!Object.op_Implicit((Object)(object)localPlayer) || ((Character)localPlayer).IsDead() || !Object.op_Implicit((Object)(object)_panel) || !Object.op_Implicit((Object)(object)_dialog) || flag || flag2)
			{
				Close();
				return;
			}
			if (_dialog.activeSelf)
			{
				if (Input.GetKeyDown((KeyCode)27))
				{
					HideDialog();
				}
				else if (Input.GetKeyDown((KeyCode)13) || Input.GetKeyDown((KeyCode)271))
				{
					ConfirmDialog();
				}
			}
			if (_search.isFocused || _dialog.activeSelf || (Object.op_Implicit((Object)(object)_dialogAmount) && _dialogAmount.isFocused))
			{
				_blockUntilFrame = Time.frameCount + 2;
			}
			SetInputBlocked(Time.frameCount <= _blockUntilFrame);
			if (Input.GetMouseButtonDown(0) && PointerOverPanel() && TryStoreDragged())
			{
				_lastDropFrame = Time.frameCount;
				if (YggdrasilPlugin.DebugLog.Value)
				{
					YggdrasilPlugin.Log.LogInfo((object)"[Debug] Objeto arrastrado soltado sobre el panel.");
				}
			}
			if (Time.time >= _nextRefresh)
			{
				Refresh(localPlayer);
			}
		}

		private bool PointerOverPanel()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = ((!Object.op_Implicit((Object)(object)_panel)) ? ((RectTransform)null) : ((RectTransform)_panel.transform));
			if (!Object.op_Implicit((Object)(object)val))
			{
				return false;
			}
			Canvas componentInParent = ((Component)val).GetComponentInParent<Canvas>();
			Camera val2 = ((Object.op_Implicit((Object)(object)componentInParent) && (int)componentInParent.renderMode != 0) ? componentInParent.worldCamera : null);
			return RectTransformUtility.RectangleContainsScreenPoint(val, Vector2.op_Implicit(Input.mousePosition), val2);
		}

		private void Refresh(Player player)
		{
			_nextRefresh = Time.time + 0.5f;
			_network = StorageNetwork.For(_core, player.GetPlayerID());
			_items = _network.AggregateItems();
			_chestsText.text = Texts.T("rv_chests", _network.ChestCount);
			RedrawGrid();
		}

		private void SetInputBlocked(bool block)
		{
			if (block != _inputBlocked)
			{
				_inputBlocked = block;
				GUIManager.BlockInput(block);
			}
		}

		private void Build()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: 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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: 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_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Expected O, but got Unknown
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f4: Expected O, but got Unknown
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_031f: Expected O, but got Unknown
			//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: Expected O, but got Unknown
			//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ee: Expected O, but got Unknown
			//IL_08f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0913: Unknown result type (might be due to invalid IL or missing references)
			//IL_092d: Unknown result type (might be due to invalid IL or missing references)
			//IL_093d: Unknown result type (might be due to invalid IL or missing references)
			//IL_094d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0993: Unknown result type (might be due to invalid IL or missing references)
			//IL_09a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_09b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_09c3: Expected O, but got Unknown
			//IL_0a2a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0474: Unknown result type (might be due to invalid IL or missing references)
			//IL_0480: Expected O, but got Unknown
			//IL_0489: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b1: Expected O, but got Unknown
			//IL_04eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Expected O, but got Unknown
			//IL_04fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0528: Expected O, but got Unknown
			//IL_055a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0561: Expected O, but got Unknown
			//IL_0568: Unknown result type (might be due to invalid IL or missing references)
			//IL_056f: Expected O, but got Unknown
			//IL_05b9: 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_05f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f9: Expected O, but got Unknown
			//IL_0605: Unknown result type (might be due to invalid IL or missing references)
			//IL_0611: Unknown result type (might be due to invalid IL or missing references)
			//IL_061d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0633: Unknown result type (might be due to invalid IL or missing references)
			//IL_0655: Unknown result type (might be due to invalid IL or missing references)
			//IL_065c: Expected O, but got Unknown
			//IL_0664: Unknown result type (might be due to invalid IL or missing references)
			//IL_066e: Expected O, but got Unknown
			//IL_06ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b5: Expected O, but got Unknown
			//IL_06bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c3: Expected O, but got Unknown
			//IL_06d9: 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_0705: Unknown result type (might be due to invalid IL or missing references)
			//IL_071b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0727: Unknown result type (might be due to invalid IL or missing references)
			//IL_0749: Unknown result type (might be due to invalid IL or missing references)
			//IL_0753: Unknown result type (might be due to invalid IL or missing references)
			//IL_075a: Expected O, but got Unknown
			//IL_0766: Unknown result type (might be due to invalid IL or missing references)
			//IL_0772: 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_0785: Unknown result type (might be due to invalid IL or missing references)
			//IL_0786: Unknown result type (might be due to invalid IL or missing references)
			//IL_078d: Unknown result type (might be due to invalid IL or missing references)
			//IL_07b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_07c0: Expected O, but got Unknown
			//IL_07c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ce: Expected O, but got Unknown
			//IL_07da: Unknown result type (might be due to invalid IL or missing references)
			//IL_07e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f9: 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_0801: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)_panel))
			{
				Object.Destroy((Object)(object)_panel);
			}
			_cells.Clear();
			InventoryGui instance = InventoryGui.instance;
			RectTransform container = instance.m_container;
			_panel = new GameObject("RuneVaultPanel", new Type[1] { typeof(RectTransform) });
			RectTransform val = (RectTransform)_panel.transform;
			((Transform)val).SetParent(((Transform)container).parent, false);
			val.anchorMin = container.anchorMin;
			val.anchorMax = container.anchorMax;
			val.pivot = new Vector2(container.pivot.x, 1f);
			Vector2 anchoredPosition = container.anchoredPosition;
			Rect rect = container.rect;
			val.anchoredPosition = anchoredPosition + new Vector2(0f, ((Rect)(ref rect)).height * (1f - container.pivot.y));
			rect = container.rect;
			val.SetSizeWithCurrentAnchors((Axis)0, ((Rect)(ref rect)).width);
			rect = container.rect;
			val.SetSizeWithCurrentAnchors((Axis)1, ((Rect)(ref rect)).height + 150f);
			((Transform)val).SetSiblingIndex(((Transform)container).GetSiblingIndex() + 1);
			if (Object.op_Implicit((Object)(object)instance.m_splitDialog) && (Object)(object)((Component)instance.m_splitDialog).transform.parent == (Object)(object)((Transform)val).parent)
			{
				((Component)instance.m_splitDialog).transform.SetAsLastSibling();
			}
			rect = val.rect;
			float width = ((Rect)(ref rect)).width;
			rect = val.rect;
			float height = ((Rect)(ref rect)).height;
			GameObject obj = GUIManager.Instance.CreateWoodpanel((Transform)(object)val, Vector2.zero, Vector2.one, Vector2.zero, 0f, 0f, false);
			Stretch((RectTransform)obj.transform);
			obj.AddComponent<PanelDropTarget>();
			Place(((Graphic)MakeText(Texts.T("rv_title"), (Transform)(object)val, 18, GUIManager.Instance.ValheimOrange, (TextAnchor)3)).rectTransform, 12f, 8f, width * 0.65f, 26f);
			_chestsText = MakeText("", (Transform)(object)val, 15, Color.white, (TextAnchor)5);
			Place(((Graphic)_chestsText).rectTransform, width * 0.65f, 8f, width * 0.35f - 12f, 26f);
			GameObject val2 = GUIManager.Instance.CreateInputField((Transform)(object)val, Vector2.zero, Vector2.zero, Vector2.zero, (ContentType)0, Texts.T("rv_search"), 16, 100f, 30f);
			_search = val2.GetComponentInChildren<InputField>(true);
			_search.characterLimit = 32;
			((UnityEvent<string>)(object)_search.onValueChanged).AddListener((UnityAction<string>)delegate
			{
				RedrawGrid();
			});
			Place((RectTransform)val2.transform, 12f, 38f, width - 24f - 40f, 30f);
			Place((RectTransform)MakeButton("X", (Transform)(object)val, (UnityAction)delegate
			{
				_search.text = "";
				RedrawGrid();
			}).transform, width - 12f - 34f, 38f, 34f, 30f);
			string[] array = new string[7] { "rv_cat_all", "rv_cat_materials", "rv_cat_food", "rv_cat_weapons", "rv_cat_armor", "rv_cat_tools", "rv_cat_other" };
			float num = (width - 24f) / (float)array.Length;
			_categoryLabels.Clear();
			for (int num2 = 0; num2 < array.Length; num2++)
			{
				int index = num2;
				GameObject val3 = MakeButton(Texts.T(array[num2]), (Transform)(object)val, (UnityAction)delegate
				{
					_category = (Category)index;
					UpdateTabLabels();
					RedrawGrid();
				}, 12);
				Place((RectTransform)val3.transform, 12f + (float)num2 * num, 74f, num - 2f, 28f);
				_categoryLabels.Add(val3.GetComponentInChildren<Text>());
			}
			string[] array2 = new string[3] { "rv_sort_amount", "rv_sort_name", "rv_sort_type" };
			_sortLabels.Clear();
			for (int num3 = 0; num3 < array2.Length; num3++)
			{
				int index2 = num3;
				GameObject val4 = MakeButton(Texts.T(array2[num3]), (Transform)(object)val, (UnityAction)delegate
				{
					_sort = (SortMode)index2;
					UpdateTabLabels();
					RedrawGrid();
				}, 12);
				Place((RectTransform)val4.transform, 12f + (float)num3 * 82f, 106f, 80f, 26f);
				_sortLabels.Add(val4.GetComponentInChildren<Text>());
			}
			Place((RectTransform)MakeButton(Texts.T("rv_store_existing"), (Transform)(object)val, new UnityAction(StoreExisting), 12).transform, 264f, 106f, width - 24f - 246f - 6f, 26f);
			GameObject val5 = new GameObject("Scroll", new Type[3]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(ScrollRect)
			});
			RectTransform val6 = (RectTransform)val5.transform;
			((Transform)val6).SetParent((Transform)(object)val, false);
			Place(val6, 12f, 138f, width - 24f, height - 138f - 40f);
			((Graphic)val5.GetComponent<Image>()).color = new Color(0f, 0f, 0f, 0.25f);
			RectTransform val7 = (RectTransform)new GameObject("Viewport", new Type[2]
			{
				typeof(RectTransform),
				typeof(RectMask2D)
			}).transform;
			((Transform)val7).SetParent((Transform)(object)val6, false);
			val7.anchorMin = Vector2.zero;
			val7.anchorMax = Vector2.one;
			val7.offsetMin = Vector2.zero;
			val7.offsetMax = new Vector2(-14f, 0f);
			GameObject val8 = new GameObject("Content", new Type[1] { typeof(RectTransform) });
			_gridContent = (RectTransform)val8.transform;
			((Transform)_gridContent).SetParent((Transform)(object)val7, false);
			GameObject val9 = new GameObject("Scrollbar", new Type[3]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(Scrollbar)
			});
			RectTransform val10 = (RectTransform)val9.transform;
			((Transform)val10).SetParent((Transform)(object)val6, false);
			val10.anchorMin = new Vector2(1f, 0f);
			val10.anchorMax = new Vector2(1f, 1f);
			val10.pivot = new Vector2(1f, 0.5f);
			val10.sizeDelta = new Vector2(10f, 0f);
			val10.anchoredPosition = Vector2.zero;
			RectTransform val11 = (RectTransform)new GameObject("Sliding Area", new Type[1] { typeof(RectTransform) }).transform;
			((Transform)val11).SetParent((Transform)(object)val10, false);
			val11.anchorMin = Vector2.zero;
			val11.anchorMax = Vector2.one;
			Vector2 offsetMin = (val11.offsetMax = Vector2.zero);
			val11.offsetMin = offsetMin;
			GameObject val12 = new GameObject("Handle", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			RectTransform val13 = (RectTransform)val12.transform;
			((Transform)val13).SetParent((Transform)(object)val11, false);
			val13.anchorMin = Vector2.zero;
			val13.anchorMax = Vector2.one;
			offsetMin = (val13.offsetMax = Vector2.zero);
			val13.offsetMin = offsetMin;
			Scrollbar component = val9.GetComponent<Scrollbar>();
			component.handleRect = val13;
			((Selectable)component).targetGraphic = (Graphic)(object)val12.GetComponent<Image>();
			component.direction = (Direction)2;
			try
			{
				GUIManager.Instance.ApplyScrollbarStyle(component);
			}
			catch
			{
			}
			ScrollRect component2 = val5.GetComponent<ScrollRect>();
			component2.viewport = val7;
			component2.content = _gridContent;
			component2.horizontal = false;
			component2.vertical = true;
			component2.movementType = (MovementType)2;
			component2.scrollSensitivity = 120f;
			component2.verticalScrollbar = component;
			component2.verticalScrollbarVisibility = (ScrollbarVisibility)0;
			LayoutGroup[] components = ((Component)_gridContent).GetComponents<LayoutGroup>();
			foreach (LayoutGroup val14 in components)
			{
				if (!(val14 is GridLayoutGroup))
				{
					Object.DestroyImmediate((Object)(object)val14);
				}
			}
			GridLayoutGroup val15 = ((Component)_gridContent).GetComponent<GridLayoutGroup>();
			if (!Object.op_Implicit((Object)(object)val15))
			{
				val15 = ((Component)_gridContent).gameObject.AddComponent<GridLayoutGroup>();
			}
			_gridContent.anchorMin = new Vector2(0f, 1f);
			_gridContent.anchorMax = new Vector2(1f, 1f);
			_gridContent.pivot = new Vector2(0f, 1f);
			_gridContent.anchoredPosition = Vector2.zero;
			_gridContent.sizeDelta = Vector2.zero;
			float num5 = width - 24f - 14f;
			int constraintCount = Mathf.Max(1, Mathf.FloorToInt((num5 - 8f + 4f) / 60f));
			val15.cellSize = new Vector2(56f, 56f);
			val15.spacing = new Vector2(4f, 4f);
			((LayoutGroup)val15).padding = new RectOffset(4, 4, 4, 4);
			val15.startCorner = (Corner)0;
			val15.startAxis = (Axis)0;
			((LayoutGroup)val15).childAlignment = (TextAnchor)0;
			val15.constraint = (Constraint)1;
			val15.constraintCount = constraintCount;
			ContentSizeFitter val16 = ((Component)_gridContent).GetComponent<ContentSizeFitter>();
			if (!Object.op_Implicit((Object)(object)val16))
			{
				val16 = ((Component)_gridContent).gameObject.AddComponent<ContentSizeFitter>();
			}
			val16.verticalFit = (FitMode)2;
			_footer = MakeText("", (Transform)(object)val, 13, GUIManager.Instance.ValheimBeige, (TextAnchor)3);
			Place(((Graphic)_footer).rectTransform, 12f, height - 38f, width - 24f, 32f);
			ShowHelp();
			BuildDialog(val, width, height);
			UpdateTabLabels();
			_panel.SetActive(false);
		}

		private void BuildDialog(RectTransform parent, float width, float height)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_006e: 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_00a3: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Expected O, but got Unknown
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Expected O, but got Unknown
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Expected O, but got Unknown
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Expected O, but got Unknown
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Expected O, but got Unknown
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Expected O, but got Unknown
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0333: Expected O, but got Unknown
			//IL_034a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0356: Expected O, but got Unknown
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_038f: Expected O, but got Unknown
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Expected O, but got Unknown
			//IL_02a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Expected O, but got Unknown
			_dialog = new GameObject("AmountDialog", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			RectTransform val = (RectTransform)_dialog.transform;
			((Transform)val).SetParent((Transform)(object)parent, false);
			Stretch(val);
			((Graphic)_dialog.GetComponent<Image>()).color = new Color(0f, 0f, 0f, 0.45f);
			float num = 320f;
			float num2 = 160f;
			RectTransform val2 = (RectTransform)GUIManager.Instance.CreateWoodpanel((Transform)(object)val, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, num, num2, false).transform;
			_dialogTitle = MakeText("", (Transform)(object)val2, 15, GUIManager.Instance.ValheimOrange, (TextAnchor)4);
			Place(((Graphic)_dialogTitle).rectTransform, 10f, 10f, num - 20f, 24f);
			Place((RectTransform)MakeButton("-", (Transform)(object)val2, (UnityAction)delegate
			{
				AddPending(-1);
			}).transform, 60f, 40f, 34f, 30f);
			GameObject val3 = GUIManager.Instance.CreateInputField((Transform)(object)val2, Vector2.zero, Vector2.zero, Vector2.zero, (ContentType)2, "", 16, 100f, 30f);
			_dialogAmount = val3.GetComponentInChildren<InputField>(true);
			_dialogAmount.characterLimit = 6;
			((UnityEvent<string>)(object)_dialogAmount.onValueChanged).AddListener((UnityAction<string>)delegate
			{
				UpdateTakeLabel();
			});
			Place((RectTransform)val3.transform, 100f, 40f, 120f, 30f);
			Place((RectTransform)MakeButton("+", (Transform)(object)val2, (UnityAction)delegate
			{
				AddPending(1);
			}).transform, 226f, 40f, 34f, 30f);
			string[] array = new string[5] { "1", "10", "rv_half", "rv_stack", "rv_all" };
			float num3 = (num - 20f) / (float)array.Length;
			for (int num4 = 0; num4 < array.Length; num4++)
			{
				int index = num4;
				Place((RectTransform)MakeButton(array[num4].StartsWith("rv_") ? Texts.T(array[num4]) : array[num4], (Transform)(object)val2, (UnityAction)delegate
				{
					QuickPending(index);
				}, 12).transform, 10f + (float)num4 * num3, 78f, num3 - 4f, 26f);
			}
			GameObject val4 = MakeButton("", (Transform)(object)val2, new UnityAction(ConfirmDialog));
			_dialogTakeLabel = val4.GetComponentInChildren<Text>();
			Place((RectTransform)val4.transform, 10f, 114f, (num - 30f) / 2f, 32f);
			Place((RectTransform)MakeButton(Texts.T("rv_cancel"), (Transform)(object)val2, new UnityAction(HideDialog)).transform, 20f + (num - 30f) / 2f, 114f, (num - 30f) / 2f, 32f);
			_dialog.SetActive(false);
		}

		private void RedrawGrid()
		{
			if (!Object.op_Implicit((Object)(object)_panel) || !_open)
			{
				return;
			}
			List<NetworkItem> list = Filtered();
			while (_cells.Count < list.Count)
			{
				_cells.Add(ItemCell.Create((Transform)(object)_gridContent, this));
			}
			for (int i = 0; i < _cells.Count; i++)
			{
				if (i < list.Count)
				{
					_cells[i].Show(list[i]);
				}
				else
				{
					((Component)_cells[i]).gameObject.SetActive(false);
				}
			}
			if (list.Count == 0)
			{
				_footer.text = ((_items.Count == 0) ? Texts.T("rv_empty") : Texts.T("rv_no_match"));
			}
			else if (!ItemCell.Hovered)
			{
				ShowHelp();
			}
		}

		private List<NetworkItem> Filtered()
		{
			IEnumerable<NetworkItem> source = _items;
			if (_category != Category.Todo)
			{
				source = source.Where((NetworkItem i) => CategoryOf(i.Sample) == _category);
			}
			string s = (Object.op_Implicit((Object)(object)_search) ? _search.text.Trim().ToLowerInvariant() : "");
			if (s.Length > 0)
			{
				source = source.Where((NetworkItem i) => Localize(i.Name).ToLowerInvariant().Contains(s));
			}
			return (_sort switch
			{
				SortMode.Nombre => source.OrderBy((NetworkItem i) => Localize(i.Name)), 
				SortMode.Tipo => from i in source
					orderby CategoryOf(i.Sample), Localize(i.Name)
					select i, 
				_ => source.OrderByDescending((NetworkItem i) => i.Amount), 
			}).ToList();
		}

		private void UpdateTabLabels()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < _categoryLabels.Count; i++)
			{
				((Graphic)_categoryLabels[i]).color = ((i == (int)_category) ? GUIManager.Instance.ValheimOrange : Color.white);
			}
			for (int j = 0; j < _sortLabels.Count; j++)
			{
				((Graphic)_sortLabels[j]).color = ((j == (int)_sort) ? GUIManager.Instance.ValheimOrange : Color.white);
			}
		}

		internal void ShowHelp()
		{
			_footer.text = Texts.T("rv_help_take") + "\n" + Texts.T("rv_help_store");
		}

		internal void ShowTooltip(NetworkItem item)
		{
			string arg = Localize(item.Name);
			_footer.text = ((item.Quality > 1) ? string.Format("{0} ({1}) × {2}", arg, Texts.T("rv_level", item.Quality), item.Amount) : $"{arg} × {item.Amount}");
		}

		internal void OnCellClick(NetworkItem item, InputButton button)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Invalid comparison between Unknown and I4
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Invalid comparison between Unknown and I4
			//IL_0082: 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)
			if (Time.frameCount - _lastDropFrame >= 30 && !TryStoreDragged() && !_dialog.activeSelf)
			{
				bool flag = Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305);
				int num = Mathf.Max(1, item.Sample.m_shared.m_maxStackSize);
				if ((int)button == 1)
				{
					Take(item, 1);
				}
				else if ((int)button == 0 && flag)
				{
					Take(item, Mathf.Min(num, item.Amount));
				}
				else if ((int)button == 0 && item.Amount <= 1)
				{
					Take(item, 1);
				}
				else if ((int)button == 0)
				{
					ShowDialog(item);
				}
			}
		}

		internal bool TryStoreDragged()
		{
			InventoryGui instance = InventoryGui.instance;
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)localPlayer))
			{
				return false;
			}
			ItemData val = DragItem.Invoke(instance);
			if (val == null)
			{
				return false;
			}
			if (DragInventory.Invoke(instance) == ((Humanoid)localPlayer).GetInventory())
			{
				Store(val, DragAmount.Invoke(instance));
			}
			AccessTools.Method(typeof(InventoryGui), "SetupDragItem", (Type[])null, (Type[])null).Invoke(instance, new object[3] { null, null, 1 });
			return true;
		}

		private void ShowDialog(NetworkItem item)
		{
			_pending = item;
			int num = Mathf.Max(1, item.Sample.m_shared.m_maxStackSize);
			_dialogTitle.text = Texts.T("rv_take_title", Localize(item.Name), item.Amount);
			SetPending(Mathf.Min(num, item.Amount));
			_dialog.SetActive(true);
			_dialog.transform.SetAsLastSibling();
		}

		private void HideDialog()
		{
			_pending = null;
			if (Object.op_Implicit((Object)(object)_dialog))
			{
				_dialog.SetActive(false);
			}
		}

		private void SetPending(int n)
		{
			_dialogAmount.text = Mathf.Clamp(n, 1, PendingMax).ToString();
			UpdateTakeLabel();
		}

		private void AddPending(int delta)
		{
			SetPending(PendingValue + delta);
		}

		private void QuickPending(int index)
		{
			if (_pending != null)
			{
				int pending = Mathf.Max(1, _pending.Sample.m_shared.m_maxStackSize);
				switch (index)
				{
				case 0:
					SetPending(1);
					break;
				case 1:
					SetPending(10);
					break;
				case 2:
					SetPending(PendingMax / 2);
					break;
				case 3:
					SetPending(pending);
					break;
				default:
					SetPending(PendingMax);
					break;
				}
			}
		}

		private void UpdateTakeLabel()
		{
			if (Object.op_Implicit((Object)(object)_dialogTakeLabel))
			{
				_dialogTakeLabel.text = Texts.T("rv_take_n", PendingValue);
			}
		}

		private void ConfirmDialog()
		{
			if (_pending != null)
			{
				NetworkItem pending = _pending;
				int pendingValue = PendingValue;
				HideDialog();
				Take(pending, pendingValue);
			}
		}

		private void Take(NetworkItem item, int wanted)
		{
			Player localPlayer = Player.m_localPlayer;
			if (Object.op_Implicit((Object)(object)localPlayer) && _network != null && wanted > 0 && _network.RequestTake(localPlayer, item, wanted) == 0)
			{
				((Character)localPlayer).Message((MessageType)2, Texts.T("rv_take_failed"), 0, (Sprite)null, false);
			}
		}

		private void Store(ItemData item, int amount)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer) || _network == null)
			{
				return;
			}
			if (((Humanoid)localPlayer).IsItemEquiped(item))
			{
				((Character)localPlayer).Message((MessageType)2, Texts.T("rv_store_equipped"), 0, (Sprite)null, false);
				return;
			}
			if (IsProtected(item))
			{
				((Character)localPlayer).Message((MessageType)2, Texts.T("rv_store_rune_in_use"), 0, (Sprite)null, false);
				return;
			}
			int num = _network.RequestStore(localPlayer, item, Mathf.Min(amount, item.m_stack));
			if (YggdrasilPlugin.DebugLog.Value)
			{
				YggdrasilPlugin.Log.LogInfo((object)$"[Debug] Guardar {item.m_shared.m_name} x{amount} (a distancia: {_remote}) → {num} enviados.");
			}
			if (num == 0)
			{
				((Character)localPlayer).Message((MessageType)2, Texts.T("rv_store_failed", Localize(item.m_shared.m_name)), 0, (Sprite)null, false);
			}
		}

		private void StoreExisting()
		{
			Player localPlayer = Player.m_localPlayer;
			if (Object.op_Implicit((Object)(object)localPlayer) && _network != null && _network.RequestStoreExisting(localPlayer) == 0)
			{
				((Character)localPlayer).Message((MessageType)2, Texts.T("rv_stored_none"), 0, (Sprite)null, false);
			}
		}

		internal static Category CategoryOf(ItemData item)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected I4, but got Unknown
			if (item.m_shared.m_name.ToLowerInvariant().Contains("bait"))
			{
				return Category.Herramientas;
			}
			ItemType itemType = item.m_shared.m_itemType;
			switch (itemType - 1)
			{
			case 0:
			case 12:
				return Category.Materiales;
			case 1:
			case 20:
				return Category.Comida;
			case 2:
			case 3:
			case 4:
			case 8:
			case 13:
			case 19:
			case 21:
			case 22:
				return Category.Armas;
			case 5:
			case 6:
			case 10:
			case 11:
			case 16:
			case 17:
			case 23:
				return Category.Armaduras;
			case 14:
			case 18:
				return Category.Herramientas;
			default:
				return Category.Otros;
			}
		}

		internal static string Localize(string token)
		{
			return Localization.instance.Localize(token);
		}

		private static void Place(RectTransform rt, float x, float y, float w, float h)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(0f, 1f);
			rt.anchorMax = val;
			rt.anchorMin = val;
			rt.pivot = new Vector2(0f, 1f);
			rt.anchoredPosition = new Vector2(x, 0f - y);
			rt.sizeDelta = new Vector2(w, h);
		}

		private static void Stretch(RectTransform rt)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			rt.anchorMin = Vector2.zero;
			rt.anchorMax = Vector2.one;
			Vector2 offsetMin = (rt.offsetMax = Vector2.zero);
			rt.offsetMin = offsetMin;
		}

		private static Text MakeText(string text, Transform parent, int size, Color color, TextAnchor align)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			Text componentInChildren = GUIManager.Instance.CreateText(text, parent, Vector2.zero, Vector2.zero, Vector2.zero, GUIManager.Instance.AveriaSerifBold, size, color, true, Color.black, 100f, 20f, false).GetComponentInChildren<Text>(true);
			componentInChildren.alignment = align;
			((Graphic)componentInChildren).raycastTarget = false;
			componentInChildren.horizontalOverflow = (HorizontalWrapMode)0;
			componentInChildren.verticalOverflow = (VerticalWrapMode)0;
			return componentInChildren;
		}

		private static GameObject MakeButton(string text, Transform parent, UnityAction onClick, int fontSize = 14)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GUIManager.Instance.CreateButton(text, parent, Vector2.zero, Vector2.zero, Vector2.zero, 100f, 30f);
			((UnityEvent)obj.GetComponentInChildren<Button>(true).onClick).AddListener(onClick);
			Text componentInChildren = obj.GetComponentInChildren<Text>();
			if (Object.op_Implicit((Object)(object)componentInChildren))
			{
				componentInChildren.fontSize = fontSize;
				componentInChildren.resizeTextForBestFit = true;
				componentInChildren.resizeTextMinSize = 9;
				componentInChildren.resizeTextMaxSize = fontSize;
			}
			return obj;
		}
	}
	internal class ItemCell : MonoBehaviour, IPointerClickHandler, IEventSystemHandler, IPointerEnterHandler, IPointerExitHandler
	{
		internal static bool Hovered;

		private TerminalWindow _owner;

		private NetworkItem _item;

		private Image _icon;

		private Text _amount;

		private Text _quality;

		internal static ItemCell Create(Transform parent, TerminalWindow owner)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_00ad: 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)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: 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)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Cell", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.transform.SetParent(parent, false);
			((Graphic)val.GetComponent<Image>()).color = new Color(0f, 0f, 0f, 0.5f);
			ItemCell itemCell = val.AddComponent<ItemCell>();
			itemCell._owner = owner;
			GameObject val2 = new GameObject("Icon", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val2.transform.SetParent(val.transform, false);
			RectTransform val3 = (RectTransform)val2.transform;
			val3.anchorMin = Vector2.zero;
			val3.anchorMax = Vector2.one;
			val3.offsetMin = new Vector2(6f, 6f);
			val3.offsetMax = new Vector2(-6f, -6f);
			itemCell._icon = val2.GetComponent<Image>();
			((Graphic)itemCell._icon).raycastTarget = false;
			itemCell._icon.preserveAspect = true;
			itemCell._amount = MakeLabel(val.transform, (TextAnchor)8, Color.white);
			itemCell._quality = MakeLabel(val.transform, (TextAnchor)0, GUIManager.Instance.ValheimOrange);
			return itemCell;
		}

		private static Text MakeLabel(Transform parent, TextAnchor align, Color color)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GUIManager.Instance.CreateText("", parent, Vector2.zero, Vector2.one, Vector2.zero, GUIManager.Instance.AveriaSerifBold, 13, color, true, Color.black, 0f, 0f, false);
			RectTransform val = (RectTransform)obj.transform;
			val.anchorMin = Vector2.zero;
			val.anchorMax = Vector2.one;
			val.offsetMin = new Vector2(3f, 1f);
			val.offsetMax = new Vector2(-3f, -1f);
			Text componentInChildren = obj.GetComponentInChildren<Text>(true);
			componentInChildren.alignment = align;
			((Graphic)componentInChildren).raycastTarget = false;
			return componentInChildren;
		}

		internal void Show(NetworkItem item)
		{
			_item = item;
			((Component)this).gameObject.SetActive(true);
			Sprite val = null;
			try
			{
				val = item.Sample.GetIcon();
			}
			catch
			{
			}
			_icon.sprite = val;
			((Behaviour)_icon).enabled = Object.op_Implicit((Object)(object)val);
			_amount.text = ((item.Amount >= 10000) ? (item.Amount / 1000 + "k") : item.Amount.ToString());
			Text quality = _quality;
			object text;
			if (item.Quality <= 1)
			{
				text = "";
			}
			else
			{
				int quality2 = item.Quality;
				text = "★" + quality2;
			}
			quality.text = (string)text;
		}

		public void OnPointerClick(PointerEventData eventData)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if (_item != null)
			{
				_owner.OnCellClick(_item, eventData.button);
			}
		}

		public void OnPointerEnter(PointerEventData eventData)
		{
			Hovered = true;
			if (_item != null)
			{
				_owner.ShowTooltip(_item);
			}
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			Hovered = false;
			_owner.ShowHelp();
		}
	}
	internal class PanelDropTarget : MonoBehaviour, IPointerClickHandler, IEventSystemHandler
	{
		public void OnPointerClick(PointerEventData eventData)
		{
			TerminalWindow.StoreDraggedFromCursor();
		}
	}
}
namespace YggdrasilNetwork.Pieces
{
	public class AbyssalChest : MonoBehaviour
	{
	}
	public class AccessTerminal : MonoBehaviour, Hoverable, Interactable
	{
		internal static readonly List<AccessTerminal> All = new List<AccessTerminal>();

		private void Start()
		{
			ZNetView component = ((Component)this).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component) && component.IsValid())
			{
				All.Add(this);
			}
		}

		private void OnDestroy()
		{
			All.Remove(this);
		}

		public string GetHoverName()
		{
			return Texts.T("rv_terminal_name");
		}

		public float GetHoverOffset()
		{
			return 0f;
		}

		public string GetHoverText()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)StorageCore.FindFor(((Component)this).transform.position)))
			{
				return GetHoverName() + "\n<color=red>" + Texts.T("rv_no_core") + "</color>";
			}
			return Localization.instance.Localize(GetHoverName() + "\n[<color=yellow><b>$KEY_Use</b></color>] " + Texts.T("rv_open"));
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (!hold)
			{
				Player val = (Player)(object)((user is Player) ? user : null);
				if (val != null)
				{
					if (TerminalWindow.IsOpen)
					{
						return true;
					}
					StorageCore storageCore = StorageCore.FindFor(((Component)this).transform.position);
					if (!Object.op_Implicit((Object)(object)storageCore))
					{
						((Character)val).Message((MessageType)2, Texts.T("rv_no_core"), 0, (Sprite)null, false);
						return false;
					}
					TerminalWindow.Open(this, storageCore);
					return true;
				}
			}
			return false;
		}

		public bool UseItem(Humanoid user, ItemData item)
		{
			return false;
		}
	}
	public class LinkedChest : MonoBehaviour
	{
	}
	internal static class PieceRegistration
	{
		public const string CorePrefab = "piece_runevault_core";

		public const string TerminalPrefab = "piece_runevault_terminal";

		public const string PillarPrefab = "piece_runevault_pillar";

		public const string LinkedChestPrefab = "piece_runevault_linkedchest";

		public const string AbyssalChestPrefab = "piece_runevault_abyssalchest";

		public const int AbyssalWidth = 8;

		public const int AbyssalHeight = 8;

		public const string HammerCategory = "Yggdrasil";

		public static void Init()
		{
			PrefabManager.OnVanillaPrefabsAvailable += AddPieces;
		}

		private static void AddPieces()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: 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_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Expected O, but got Unknown
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Expected O, but got Unknown
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Expected O, but got Unknown
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Expected O, but got Unknown
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_029e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: 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_030c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0313: Expected O, but got Unknown
			//IL_0373: Unknown result type (might be due to invalid IL or missing references)
			//IL_0379: Expected O, but got Unknown
			//IL_0383: Unknown result type (might be due to invalid IL or missing references)
			//IL_0389: Expected O, but got Unknown
			//IL_0390: Unknown result type (might be due to invalid IL or missing references)
			//IL_0397: Expected O, but got Unknown
			//IL_03bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Unknown result type (might be due to invalid IL or missing references)
			//IL_0454: Unknown result type (might be due to invalid IL or missing references)
			//IL_045b: Expected O, but got Unknown
			//IL_04bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c1: Expected O, but got Unknown
			//IL_04cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d2: Expected O, but got Unknown
			//IL_04dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e2: Expected O, but got Unknown
			//IL_04e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f0: Expected O, but got Unknown
			//IL_0513: Unknown result type (might be due to invalid IL or missing references)
			//IL_0518: Unknown result type (might be due to invalid IL or missing references)
			//IL_0522: Unknown result type (might be due to invalid IL or missing references)
			//IL_0542: Unknown result type (might be due to invalid IL or missing references)
			//IL_055f: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b9: Expected O, but got Unknown
			//IL_0619: Unknown result type (might be due to invalid IL or missing references)
			//IL_061f: Expected O, but got Unknown
			//IL_0629: Unknown result type (might be due to invalid IL or missing references)
			//IL_062f: Expected O, but got Unknown
			//IL_0636: Unknown result type (might be due to invalid IL or missing references)
			//IL_063d: Expected O, but got Unknown
			//IL_0660: Unknown result type (might be due to invalid IL or missing references)
			//IL_0665: Unknown result type (might be due to invalid IL or missing references)
			//IL_066f: Unknown result type (might be due to invalid IL or missing references)
			//IL_068f: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ac: Unknown result type (might be due to invalid IL or missing references)
			PrefabManager.OnVanillaPrefabsAvailable -= AddPieces;
			PieceConfig val = new PieceConfig();
			val.Name = "$rv_core_name";
			val.Icon = Visuals.Icon("core");
			val.Description = "$rv_core_desc";
			val.PieceTable = PieceTables.Hammer;
			val.Category = "Yggdrasil";
			val.CraftingStation = CraftingStations.Workbench;
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
			{
				new RequirementConfig("Wood", 10, 0, true),
				new RequirementConfig("SurtlingCore", 1, 0, true)
			};
			CustomPiece val2 = new CustomPiece("piece_runevault_core", "stone_pillar", val);
			val2.PiecePrefab.AddComponent<StorageCore>();
			val2.PiecePrefab.AddComponent<RangeMarker>();
			if (CoreModel.Apply(val2.PiecePrefab))
			{
				ModelKit.AddLight(val2.PiecePrefab, ModelKit.GlowBlue, 5f, 1f, CoreModel.CrystalPos);
			}
			else
			{
				Visuals.Tint(val2.PiecePrefab, new Color(0.8f, 0.9f, 1.15f), Visuals.RuneBlue * 0.35f);
				Visuals.AddLight(val2.PiecePrefab, Visuals.RuneBlue, 5f, 1.6f, 2.2f);
			}
			WearNTear component = val2.PiecePrefab.GetComponent<WearNTear>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.m_materialType = (MaterialType)0;
			}
			PieceManager.Instance.AddPiece(val2);
			string text = (Object.op_Implicit((Object)(object)PrefabManager.Instance.GetPrefab("piece_table")) ? "piece_table" : "stone_pillar");
			val = new PieceConfig();
			val.Name = "$rv_terminal_name";
			val.Icon = Visuals.Icon("terminal");
			val.Description = "$rv_terminal_desc";
			val.PieceTable = PieceTables.Hammer;
			val.Category = "Yggdrasil";
			val.CraftingStation = CraftingStations.Workbench;
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
			{
				new RequirementConfig("Wood", 10, 0, true),
				new RequirementConfig("SurtlingCore", 1, 0, true)
			};
			CustomPiece val3 = new CustomPiece("piece_runevault_terminal", text, val);
			val3.PiecePrefab.AddComponent<AccessTerminal>();
			if (TerminalModel.Apply(val3.PiecePrefab))
			{
				ModelKit.AddLight(val3.PiecePrefab, ModelKit.GlowBlue, 3f, 0.8f, new Vector3(0f, 1.75f, 0f));
			}
			else
			{
				Visuals.Tint(val3.PiecePrefab, new Color(0.85f, 0.92f, 1.1f), Visuals.RuneBlue * 0.2f);
				Visuals.AddLight(val3.PiecePrefab, Visuals.RuneBlue, 3f, 1f, 1.4f);
			}
			WearNTear component2 = val3.PiecePrefab.GetComponent<WearNTear>();
			if (Object.op_Implicit((Object)(object)component2))
			{
				component2.m_materialType = (MaterialType)0;
			}
			PieceManager.Instance.AddPiece(val3);
			string text2 = (Object.op_Implicit((Object)(object)PrefabManager.Instance.GetPrefab("wood_pole2")) ? "wood_pole2" : "stone_pillar");
			val = new PieceConfig();
			val.Name = "$rv_pillar_name";
			val.Icon = Visuals.Icon("pillar");
			val.Description = "$rv_pillar_desc";
			val.PieceTable = PieceTables.Hammer;
			val.Category = "Yggdrasil";
			val.CraftingStation = CraftingStations.Workbench;
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
			{
				new RequirementConfig("BlackMetal", 20, 0, true),
				new RequirementConfig("TrophyGoblinShaman", 1, 0, true)
			};
			CustomPiece val4 = new CustomPiece("piece_runevault_pillar", text2, val);
			if (!PillarModel.Apply(val4.PiecePrefab))
			{
				Visuals.Tint(val4.PiecePrefab, new Color(0.55f, 0.48f, 0.7f), Visuals.RunePurple * 0.4f);
			}
			WearNTear component3 = val4.PiecePrefab.GetComponent<WearNTear>();
			if (Object.op_Implicit((Object)(object)component3))
			{
				component3.m_health = Mathf.Max(component3.m_health, 1000f);
			}
			val4.PiecePrefab.AddComponent<RunePillar>();
			val4.PiecePrefab.AddComponent<RangeMarker>();
			Visuals.AddLight(val4.PiecePrefab, PillarModel.RuneColor, 4f, 0.8f, 1.8f);
			PieceManager.Instance.AddPiece(val4);
			val = new PieceConfig();
			val.Name = "$rv_linked_name";
			val.Icon = Visuals.Icon("linked");
			val.Description = "$rv_linked_desc";
			val.PieceTable = PieceTables.Hammer;
			val.Category = "Yggdrasil";
			val.CraftingStation = CraftingStations.Workbench;
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
			{
				new RequirementConfig("Iron", 30, 0, true),
				new RequirementConfig("FineWood", 20, 0, true),
				new RequirementConfig("TrophyDraugr", 1, 0, true)
			};
			CustomPiece val5 = new CustomPiece("piece_runevault_linkedchest", "piece_chest_blackmetal", val);
			val5.PiecePrefab.AddComponent<LinkedChest>();
			Visuals.Tint(val5.PiecePrefab, new Color(0.55f, 0.72f, 1.15f), Visuals.RuneBlue * 0.15f);
			ModelKit.RecolorAccents(val5.PiecePrefab, new Color(0.6f, 2.2f, 4.5f));
			ChestModels.Linked(val5.PiecePrefab);
			Visuals.AddLight(val5.PiecePrefab, Visuals.RuneBlue, 2.5f, 0.8f, 1f);
			Container component4 = val5.PiecePrefab.GetComponent<Container>();
			if (Object.op_Implicit((Object)(object)component4))
			{
				component4.m_name = "$rv_linked_name";
			}
			PieceManager.Instance.AddPiece(val5);
			val = new PieceConfig();
			val.Name = "$rv_abyssal_name";
			val.Icon = Visuals.Icon("abyssal");
			val.Description = "$rv_abyssal_desc";
			val.PieceTable = PieceTables.Hammer;
			val.Category = "Yggdrasil";
			val.CraftingStation = CraftingStations.Workbench;
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
			{
				new RequirementConfig("Frostwood", 30, 0, true),
				new RequirementConfig("TrophyJotunWitch", 1, 0, true)
			};
			CustomPiece val6 = new CustomPiece("piece_runevault_abyssalchest", "piece_chest_blackmetal", val);
			val6.PiecePrefab.AddComponent<AbyssalChest>();
			Visuals.Tint(val6.PiecePrefab, new Color(0.42f, 0.34f, 0.55f), Visuals.RunePurple * 0.2f);
			ModelKit.RecolorAccents(val6.PiecePrefab, new Color(0.9f, 0.2f, 1.8f));
			ChestModels.Abyssal(val6.PiecePrefab);
			Visuals.AddLight(val6.PiecePrefab, Visuals.RunePurple, 3.5f, 1.2f, 1.2f);
			Container component5 = val6.PiecePrefab.GetComponent<Container>();
			if (Object.op_Implicit((Object)(object)component5))
			{
				component5.m_name = "$rv_abyssal_name";
				component5.m_width = 8;
				component5.m_height = 8;
			}
			PieceManager.Instance.AddPiece(val6);
			YggdrasilPlugin.Log.LogInfo((object)("Piezas registradas: piece_runevault_core, piece_runevault_terminal (base " + text + ")"));
		}
	}
	public class RangeMarker : MonoBehaviour
	{
		private const float ShowDistance = 80f;

		private ZNetView _nview;

		private StorageCore _core;

		private GameObject _marker;

		private CircleProjector _projector;

		private int _tintedSegments = -1;

		private static readonly Color CoreColor = new Color(0.3f, 0.65f, 1f, 1f);

		private static readonly Color PillarColor = new Color(0.72f, 0.38f, 1f, 1f);

		private void Start()
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			_nview = ((Component)this).GetComponent<ZNetView>();
			_core = ((Component)this).GetComponent<StorageCore>();
			GameObject val = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab("piece_workbench") : null);
			CraftingStation val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<CraftingStation>() : null);
			if (Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val2.m_areaMarker))
			{
				_marker = Object.Instantiate<GameObject>(val2.m_areaMarker, ((Component)this).transform);
				_marker.transform.localPosition = Vector3.zero;
				_marker.transform.localRotation = Quaternion.identity;
				_projector = _marker.GetComponentInChildren<CircleProjector>(true);
				if (Object.op_Implicit((Object)(object)_projector))
				{
					_projector.m_radius = CurrentRadius();
					_projector.m_nrOfSegments = Mathf.Clamp(Mathf.CeilToInt(_projector.m_radius * 4f), 20, 200);
				}
				_marker.SetActive(false);
			}
		}

		private float CurrentRadius()
		{
			if (Object.op_Implicit((Object)(object)_core))
			{
				return _core.Radius;
			}
			return YggdrasilPlugin.PillarRadius.Value;
		}

		private void Update()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)_marker))
			{
				bool num = !Object.op_Implicit((Object)(object)_nview) || !_nview.IsValid();
				Player localPlayer = Player.m_localPlayer;
				bool flag = num || (Object.op_Implicit((Object)(object)localPlayer) && ((Character)localPlayer).InPlaceMode() && Vector3.Distance(((Component)localPlayer).transform.position, ((Component)this).transform.position) < 80f);
				if (_marker.activeSelf != flag)
				{
					_marker.SetActive(flag);
				}
				if (flag && Object.op_Implicit((Object)(object)_projector))
				{
					_projector.m_radius = CurrentRadius();
				}
				if (flag)
				{
					Tint();
				}
			}
		}

		private void Tint()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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)
			Renderer[] componentsInChildren = _marker.GetComponentsInChildren<Renderer>(true);
			if (componentsInChildren.Length == _tintedSegments)
			{
				return;
			}
			_tintedSegments = componentsInChildren.Length;
			Color val = (Object.op_Implicit((Object)(object)_core) ? CoreColor : PillarColor);
			Renderer[] array = componentsInChildren;
			for (int i = 0; i < array.Length; i++)
			{
				Material material = array[i].material;
				if (material.HasProperty("_Color"))
				{
					material.SetColor("_Color", val);
				}
				if (material.HasProperty("_TintColor"))
				{
					material.SetColor("_TintColor", val);
				}
				if (material.HasProperty("_EmissionColor"))
				{
					material.SetColor("_EmissionColor", val);
				}
			}
		}
	}
	public class RunePillar : MonoBehaviour, Hoverable
	{
		internal static readonly List<RunePillar> All = new List<RunePillar>();

		private void Start()
		{
			ZNetView component = ((Component)this).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component) && component.IsValid())
			{
				All.Add(this);
			}
		}

		private void OnDestroy()
		{
			All.Remove(this);
		}

		public string GetHoverName()
		{
			return Texts.T("rv_pillar_name");
		}

		public float GetHoverOffset()
		{
			return 0f;
		}

		public string GetHoverText()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			bool flag = Object.op_Implicit((Object)(object)StorageCore.FindFor(((Component)this).transform.position));
			string text = YggdrasilPlugin.PillarRadius.Value.ToString("0");
			return GetHoverName() + "\n" + (flag ? ("<color=#9cf09c>" + Texts.T("rv_pillar_connected", text) + "</color>") : ("<color=red>" + Texts.T("rv_pillar_disconnected") + "</color>"));
		}
	}
	public class StorageCore : MonoBehaviour, Hoverable, Interactable
	{
		private sealed class CostEntry
		{
			public ItemData item;

			public int amount;
		}

		internal const string WorldKey = "runevault_core";

		private const string LevelKey = "rv_level";

		private static readonly string[] LevelWorldKeys = new string[3] { "", "runevault_core_lvl1", "runevault_core_lvl2" };

		internal const int MaxLevel = 2;

		internal static readonly List<StorageCore> All = new List<StorageCore>();

		private ZNetView _nview;

		internal static int WorldLevel
		{
			get
			{
				ZoneSystem instance = ZoneSystem.instance;
				if (!Object.op_Implicit((Object)(object)instance))
				{
					return 0;
				}
				for (int num = 2; num >= 1; num--)
				{
					if (instance.GetGlobalKey(LevelWorldKeys[num]))
					{
						return num;
					}
				}
				return 0;
			}
		}

		internal int Level => WorldLevel;

		internal float Radius => RadiusFor(Level);

		private void Start()
		{
			_nview = ((Component)this).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)_nview) && _nview.IsValid())
			{
				All.Add(this);
				if (Object.op_Implicit((Object)(object)ZoneSystem.instance) && !ZoneSystem.instance.GetGlobalKey("runevault_core"))
				{
					ZoneSystem.instance.SetGlobalKey("runevault_core");
				}
				int num = Mathf.Clamp(_nview.GetZDO().GetInt("rv_level", 0), 0, 2);
				for (int i = 1; i <= num; i++)
				{
					SetWorldLevel(i);
				}
			}
		}

		private void OnDestroy()
		{
			All.Remove(this);
		}

		private static void SetWorldLevel(int level)
		{
			if (Object.op_Implicit((Object)(object)ZoneSystem.instance) && level >= 1 && level <= 2 && !ZoneSystem.instance.GetGlobalKey(LevelWorldKeys[level]))
			{
				ZoneSystem.instance.SetGlobalKey(LevelWorldKeys[level]);
			}
		}

		internal static float RadiusFor(int level)
		{
			float num = YggdrasilPlugin.CoreRadius.Value;
			if (level >= 1)
			{
				num = Mathf.Max(num, YggdrasilPlugin.RadiusLevel1.Value);
			}
			if (level >= 2)
			{
				num = Mathf.Max(num, YggdrasilPlugin.RadiusLevel2.Value);
			}
			return num;
		}

		internal List<NetworkSphere> NetworkSpheres()
		{
			//IL_000c: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
			List<NetworkSphere> list = new List<NetworkSphere>
			{
				new NetworkSphere(((Component)this).transform.position, Radius)
			};
			List<RunePillar> list2 = RunePillar.All.Where((RunePillar p) => Object.op_Implicit((Object)(object)p)).ToList();
			bool flag = true;
			while (flag)
			{
				flag = false;
				foreach (RunePillar item in list2.ToList())
				{
					Vector3 pos = ((Component)item).transform.position;
					if (list.Any((NetworkSphere sp) => sp.Contains(pos)))
					{
						list.Add(new NetworkSphere(pos, YggdrasilPlugin.PillarRadius.Value));
						list2.Remove(item);
						flag = true;
					}
				}
			}
			return list;
		}

		internal bool Covers(Vector3 position)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return NetworkSpheres().Any((NetworkSphere sp) => sp.Contains(position));
		}

		private static string CostFor(int level)
		{
			return level switch
			{
				2 => YggdrasilPlugin.CostLevel2.Value, 
				1 => YggdrasilPlugin.CostLevel1.Value, 
				_ => "", 
			};
		}

		private static List<CostEntry> ParseCost(string cost)
		{
			List<CostEntry> list = new List<CostEntry>();
			if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || string.IsNullOrWhiteSpace(cost))
			{
				return list;
			}
			string[] array = cost.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split(new char[1] { ':' });
				if (array2.Length == 2 && int.TryParse(array2[1].Trim(), out var result) && result > 0)
				{
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(array2[0].Trim());
					ItemDrop val = (Object.op_Implicit((Object)(object)itemPrefab) ? itemPrefab.GetComponent<ItemDrop>() : null);
					if (Object.op_Implicit((Object)(object)val))
					{
						list.Add(new CostEntry
						{
							item = val.m_itemData,
							amount = result
						});
					}
				}
			}
			return list;
		}

		private static string Describe(List<CostEntry> cost)
		{
			return string.Join(", ", cost.Select((CostEntry c) => $"{c.amount} {c.item.m_shared.m_name}"));
		}

		internal static StorageCore FindFor(Vector3 position)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return (from c in All
				where Object.op_Implicit((Object)(object)c) && c.Covers(position)
				orderby Vector3.Distance(((Component)c).transform.position, position)
				select c).FirstOrDefault();
		}

		public string GetHoverName()
		{
			return Texts.T("rv_core_name");
		}

		public float GetHoverOffset()
		{
			return 0f;
		}

		public string GetHoverText()
		{
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				return GetHoverName();
			}
			StorageNetwork storageNetwork = StorageNetwork.For(this, localPlayer.GetPlayerID());
			int num = NetworkSpheres().Count - 1;
			string text = GetHoverName() + " — " + Texts.T("rv_core_level", Level) + "\n" + Texts.T("rv_core_linked", storageNetwork.ChestCount, Radius.ToString("0")) + ((num > 0) ? (" · " + Texts.T("rv_core_pillars", num)) : "") + "\n[<color=yellow><b>$KEY_Use</b></color>] " + Texts.T("rv_core_use");
			if (Level < 2)
			{
				List<CostEntry> cost = ParseCost(CostFor(Level + 1));
				text = text + "\n[<color=yellow><b>$KEY_AltPlace + $KEY_Use</b></color>] " + Texts.T("rv_upgrade", Level + 1, RadiusFor(Level + 1).ToString("0"), Describe(cost));
			}
			else
			{
				text = text + "\n" + Texts.T("rv_upgrade_max");
			}
			return Localization.instance.Localize(text);
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			if (!hold)
			{
				Player val = (Player)(object)((user is Player) ? user : null);
				if (val != null)
				{
					if (alt)
					{
						return TryUpgrade(val);
					}
					StorageNetwork storageNetwork = StorageNetwork.For(this, val.GetPlayerID());
					List<NetworkItem> list = storageNetwork.AggregateItems();
					int num = list.Sum((NetworkItem i) => i.Amount);
					((Character)val).Message((MessageType)2, Texts.T("rv_core_summary", storageNetwork.ChestCount, list.Count, num) + "\n" + Texts.T("rv_core_hint"), 0, (Sprite)null, false);
					return true;
				}
			}
			return false;
		}

		private bool TryUpgrade(Player player)
		{
			if (Level >= 2)
			{
				((Character)player).Message((MessageType)2, Texts.T("rv_upgrade_max"), 0, (Sprite)null, false);
				return false;
			}
			int num = Level + 1;
			List<CostEntry> list = ParseCost(CostFor(num));
			Inventory inv = ((Humanoid)player).GetInventory();
			List<CostEntry> list2 = (from c in list
				select new CostEntry
				{
					item = c.item,
					amount = c.amount - inv.CountItems(c.item.m_shared.m_name, -1, true)
				} into c
				where c.amount > 0
				select c).ToList();
			if (list2.Count > 0)
			{
				((Character)player).Message((MessageType)2, Localization.instance.Localize(Texts.T("rv_upgrade_missing", Describe(list2))), 0, (Sprite)null, false);
				return false;
			}
			foreach (CostEntry item in list)
			{
				inv.RemoveItem(item.item.m_shared.m_name, item.amount, -1, true);
			}
			SetWorldLevel(num);
			((Character)player).Message((MessageType)2, Texts.T("rv_upgraded", num, RadiusFor(num).ToString("0")), 0, (Sprite)null, false);
			return true;
		}

		public bool UseItem(Humanoid user, ItemData item)
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(Player), "TryPlacePiece")]
	internal static class OneCorePerWorldPatch
	{
		private static bool Prefix(Player __instance, Piece __0, ref bool __result)
		{
			if (!Object.op_Implicit((Object)(object)__0) || !Object.op_Implicit((Object)(object)((Component)__0).GetComponent<StorageCore>()))
			{
				return true;
			}
			if (!Object.op_Implicit((Object)(object)ZoneSystem.instance) || !ZoneSystem.instance.GetGlobalKey("runevault_core"))
			{
				return true;
			}
			((Character)__instance).Message((MessageType)2, Texts.T("rv_core_exists"), 0, (Sprite)null, false);
			__result = false;
			return false;
		}
	}
	[HarmonyPatch(typeof(WearNTear), "Destroy")]
	internal static class CoreDestroyedPatch
	{
		private static void Prefix(WearNTear __instance)
		{
			if (Object.op_Implicit((Object)(object)((Component)__instance).GetComponent<StorageCore>()) && Object.op_Implicit((Object)(object)ZoneSystem.instance))
			{
				ZoneSystem.instance.RemoveGlobalKey("runevault_core");
			}
		}
	}
}
namespace YggdrasilNetwork.Network
{
	internal static class ChestRpc
	{
		private const string TakeRpc = "RuneVault_Take";

		private const string TakeResultRpc = "RuneVault_TakeResult";

		private const string StoreRpc = "RuneVault_Store";

		private const string StoreResultRpc = "RuneVault_StoreResult";

		internal const string TakeForRpc = "RuneVault_TakeFor";

		internal const string StoreForRpc = "RuneVault_StoreFor";

		internal static void Register(Container container)
		{
			ZNetView val = ContainerRegistry.NView.Invoke(container);
			if (Object.op_Implicit((Object)(object)val))
			{
				val.Register<ZPackage>("RuneVault_Take", (Action<long, ZPackage>)delegate(long sender, ZPackage pkg)
				{
					OnTake(container, sender, pkg);
				});
				val.Register<ZPackage>("RuneVault_TakeResult", (Action<long, ZPackage>)delegate(long sender, ZPackage pkg)
				{
					OnTakeResult(pkg);
				});
				val.Register<ZPackage>("RuneVault_Store", (Action<long, ZPackage>)delegate(long sender, ZPackage pkg)
				{
					OnStore(container, sender, pkg);
				});
				val.Register<ZPackage>("RuneVault_StoreResult", (Action<long, ZPackage>)delegate(long sender, ZPackage pkg)
				{
					OnStoreResult(pkg);
				});
				val.Register<ZPackage>("RuneVault_TakeFor", (Action<long, ZPackage>)delegate(long sender, ZPackage pkg)
				{
					OnTakeFor(container, pkg);
				});
				val.Register<ZPackage>("RuneVault_StoreFor", (Action<long, ZPackage>)delegate(long sender, ZPackage pkg)
				{
					OnStoreFor(container, pkg);
				});
			}
		}

		internal static void RequestTake(Container chest, NetworkItem entry, int amount)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(entry.Name);
			val.Write(entry.Quality);
			val.Write(entry.Variant);
			val.Write(amount);
			ContainerRegistry.NView.Invoke(chest).InvokeRPC("RuneVault_Take", new object[1] { val });
		}

		internal static void RequestStore(Container chest, Player player, ItemData item, int amount)
		{
			ItemData val = item.Clone();
			val.m_stack = amount;
			if (((Humanoid)player).GetInventory().RemoveItem(item, amount))
			{
				ContainerRegistry.NView.Invoke(chest).InvokeRPC("RuneVault_Store", new object[1] { Pack((IEnumerable<ItemData>)(object)new ItemData[1] { val }) });
			}
		}

		private static void OnTake(Container chest, long sender, ZPackage pkg)
		{
			ZNetView val = ContainerRegistry.NView.Invoke(chest);
			if (Object.op_Implicit((Object)(object)val) && val.IsOwner())
			{
				List<ItemData> items = TakeFrom(chest, pkg);
				val.InvokeRPC(sender, "RuneVault_TakeResult", new object[1] { Pack(items) });
			}
		}

		private static void OnTakeFor(Container chest, ZPackage pkg)
		{
			long num = pkg.ReadLong();
			ZNetView val = ContainerRegistry.NView.Invoke(chest);
			List<ItemData> items = ((Object.op_Implicit((Object)(object)val) && val.IsOwner()) ? TakeFrom(chest, pkg) : new List<ItemData>());
			ZRoutedRpc.instance.InvokeRoutedRPC(num, "RuneVault_RemoteTakeResult", new object[1] { Pack(items) });
		}

		private static List<ItemData> TakeFrom(Container chest, ZPackage pkg)
		{
			string text = pkg.ReadString();
			int num = pkg.ReadInt();
			int num2 = pkg.ReadInt();
			int num3 = pkg.ReadInt();
			Inventory inventory = chest.GetInventory();
			List<ItemData> list = new List<ItemData>();
			int num4 = num3;
			foreach (ItemData item in inventory.GetAllItems().ToList())
			{
				if (num4 <= 0)
				{
					break;
				}
				if (!(item.m_shared.m_name != text) && item.m_quality == num && item.m_variant == num2)
				{
					int num5 = Mathf.Min(item.m_stack, num4);
					ItemData val = item.Clone();
					val.m_stack = num5;
					if (inventory.RemoveItem(item, num5))
					{
						list.Add(val);
						num4 -= num5;
					}
				}
			}
			return list;
		}

		private static void OnStore(Container chest, long sender, ZPackage pkg)
		{
			ContainerRegistry.NView.Invoke(chest).InvokeRPC(sender, "RuneVault_StoreResult", new object[1] { StoreInto(chest, Unpack(pkg)) });
		}

		private static void OnStoreFor(Container chest, ZPackage pkg)
		{
			long num = pkg.ReadLong();
			List<ItemData> incoming = Unpack(pkg.ReadPackage());
			ZRoutedRpc.instance.InvokeRoutedRPC(num, "RuneVault_RemoteStoreResult", new object[1] { StoreInto(chest, incoming) });
		}

		private static ZPackage StoreInto(Container chest, List<ItemData> incoming)
		{
			ZNetView val = ContainerRegistry.NView.Invoke(chest);
			List<ItemData> list = new List<ItemData>();
			if (!Object.op_Implicit((Object)(object)val) || !val.IsOwner())
			{
				list.AddRange(incoming);
			}
			else
			{
				Inventory inventory = chest.GetInventory();
				foreach (ItemData item in incoming)
				{
					int num = MaxFit(inventory, item, item.m_stack);
					if (num > 0)
					{
						ItemData val2 = item.Clone();
						val2.m_stack = num;
						if (!inventory.AddItem(val2))
						{
							num = 0;
						}
					}
					if (num < item.m_stack)
					{
						ItemData val3 = item.Clone();
						val3.m_stack = item.m_stack - num;
						list.Add(val3);
					}
				}
			}
			ZPackage obj = Pack(list);
			obj.Write(incoming.Sum((ItemData i) => i.m_stack) - list.Sum((ItemData i) => i.m_stack));
			obj.Write((incoming.Count > 0) ? incoming[0].m_shared.m_name : "");
			return obj;
		}

		internal static void OnTakeResult(ZPackage pkg)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				return;
			}
			List<ItemData> list = Unpack(pkg);
			if (list.Count == 0)
			{
				((Character)localPlayer).Message((MessageType)1, Texts.T("rv_take_failed"), 0, (Sprite)null, false);
				return;
			}
			foreach (ItemData item in list)
			{
				GiveOrDrop(localPlayer, item);
			}
			((Character)localPlayer).Message((MessageType)1, Texts.T("rv_took", list.Sum((ItemData i) => i.m_stack), Localize(list[0].m_shared.m_name)), 0, (Sprite)null, false);
			LinkedChests.Query(force: true);
			TerminalWindow.NotifyChanged();
		}

		internal static void OnStoreResult(ZPackage pkg)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				return;
			}
			List<ItemData> list = Unpack(pkg);
			int num = pkg.ReadInt();
			string text = Localize(pkg.ReadString());
			foreach (ItemData item in list)
			{
				GiveOrDrop(localPlayer, item);
			}
			((Character)localPlayer).Message((MessageType)1, (num > 0) ? Texts.T("rv_stored", num, text) : Texts.T("rv_store_failed", text), 0, (Sprite)null, false);
			LinkedChests.Query(force: true);
			TerminalWindow.NotifyChanged();
		}

		private static void GiveOrDrop(Player player, ItemData item)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (!inventory.CanAddItem(item, item.m_stack) || !inventory.AddItem(item))
			{
				Transform transform = ((Component)player).transform;
				ItemDrop.DropItem(item, item.m_stack, transform.position + transform.forward * 0.5f + Vector3.up, Quaternion.identity);
			}
		}

		internal static int MaxFit(Inventory inv, ItemData item, int max)
		{
			if (max <= 0)
			{
				return 0;
			}
			if (inv.CanAddItem(item, max))
			{
				return max;
			}
			int num = 0;
			int num2 = max - 1;
			while (num < num2)
			{
				int num3 = (num + num2 + 1) / 2;
				if (inv.CanAddItem(item, num3))
				{
					num = num3;
				}
				else
				{
					num2 = num3 - 1;
				}
			}
			return num;
		}

		internal static ZPackage Pack(IEnumerable<ItemData> items)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			List<ItemData> list = items.ToList();
			Inventory val = new Inventory("Yggdrasil", (Sprite)null, 8, Mathf.Max(1, list.Count));
			int num = 0;
			foreach (ItemData item in list)
			{
				item.m_gridPos = new Vector2i(0, num++);
				val.GetAllItems().Add(item);
			}
			ZPackage val2 = new ZPackage();
			val.Save(val2);
			return val2;
		}

		internal static List<ItemData> Unpack(ZPackage pkg)
		{
			//IL_0009: 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)
			Inventory val = new Inventory("Yggdrasil", (Sprite)null, 8, 64);
			val.Load(pkg);
			return val.GetAllItems().ToList();
		}

		private static string Localize(string token)
		{
			return Localization.instance.Localize(token);
		}
	}
	[HarmonyPatch(typeof(Container), "Awake")]
	internal static class ContainerRpcRegisterPatch
	{
		private static void Postfix(Container __instance)
		{
			ChestRpc.Register(__instance);
		}
	}
	internal static class ContainerRegistry
	{
		private static readonly HashSet<Container> Containers = new HashSet<Container>();

		internal static readonly FieldRef<Container, ZNetView> NView = AccessTools.FieldRefAccess<Container, ZNetView>("m_nview");

		internal static void Register(Container container)
		{
			if (Object.op_Implicit((Object)(object)container))
			{
				Containers.Add(container);
			}
		}

		internal static List<Container> FindInSpheres(List<NetworkSphere> spheres)
		{
			//IL_0059: 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)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			Containers.RemoveWhere((Container c) => !Object.op_Implicit((Object)(object)c));
			Vector3 origin = ((spheres.Count > 0) ? spheres[0].Center : Vector3.zero);
			return (from c in Containers.Where(IsStorageChest)
				where Object.op_Implicit((Object)(object)((Component)c).GetComponent<LinkedChest>()) || Object.op_Implicit((Object)(object)((Component)c).GetComponent<AbyssalChest>()) || spheres.Any((NetworkSphere sp) => sp.Contains(((Component)c).transform.position))
				select c).OrderBy(delegate(Container c)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//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)
				Vector3 val = ((Component)c).transform.position - origin;
				return ((Vector3)(ref val)).sqrMagnitude;
			}).ToList();
		}

		internal static List<Container> Loaded()
		{
			Containers.RemoveWhere((Container c) => !Object.op_Implicit((Object)(object)c));
			return Containers.Where(IsStorageChest).ToList();
		}

		private static bool IsStorageChest(Container c)
		{
			ZNetView val = NView.Invoke(c);
			if (!Object.op_Implicit((Object)(object)val) || !val.IsValid())
			{
				return false;
			}
			Piece component = ((Component)c).GetComponent<Piece>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return false;
			}
			if (component.GetCreator() == 0L)
			{
				return false;
			}
			if (((Object)c).name.StartsWith("PT_RuneVault"))
			{
				return false;
			}
			if (Object.op_Implicit((Object)(object)((Component)c).GetComponentInParent<Ship>()))