Decompiled source of AishoPortals v1.0.0

AishoPortals.dll

Decompiled a year ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using AishoPortals.BlackWhite;
using AishoPortals.Managers;
using AishoPortals.Stations;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Groups;
using Guilds;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.BufferedDeserialization;
using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("AishoPortals")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("AishoPortals")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyCompany("RustyMods")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<b8cc4e87-e74f-4a05-94a6-34af7729a62d>Embedded]
	internal sealed class <b8cc4e87-e74f-4a05-94a6-34af7729a62d>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<b8cc4e87-e74f-4a05-94a6-34af7729a62d>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <58442400-41e8-471d-b095-2aec51fe8fb7>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <58442400-41e8-471d-b095-2aec51fe8fb7>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <58442400-41e8-471d-b095-2aec51fe8fb7>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<b8cc4e87-e74f-4a05-94a6-34af7729a62d>Embedded]
	internal sealed class <1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace AishoPortals
{
	[BepInPlugin("RustyMods.AishoPortals", "AishoPortals", "1.0.0")]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public class AishoPortalsPlugin : BaseUnityPlugin
	{
		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)]
		public enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
			public string Category;

			[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(new byte[] { 2, 1 })]
			[UsedImplicitly]
			public Action<ConfigEntryBase> CustomDrawer;
		}

		internal const string ModName = "AishoPortals";

		internal const string ModVersion = "1.0.0";

		internal const string Author = "RustyMods";

		private const string ModGUID = "RustyMods.AishoPortals";

		private static readonly string ConfigFileName = "RustyMods.AishoPortals.cfg";

		private static readonly string ConfigFileFullPath;

		internal static string ConnectionError;

		private readonly Harmony _harmony = new Harmony("RustyMods.AishoPortals");

		public static readonly ManualLogSource AishoPortalsLogger;

		private static readonly ConfigSync ConfigSync;

		public static readonly AssetBundle _UIAssetBundle;

		public static AishoPortalsPlugin _Plugin;

		public static GameObject _root;

		private static ConfigEntry<Toggle> _serverConfigLocked;

		public static ConfigEntry<Toggle> _TeleportAnything;

		public static ConfigEntry<string> _DeviceFuel;

		public static ConfigEntry<Toggle> _PortalToPlayers;

		public static ConfigEntry<Toggle> _PortalUseFuel;

		public static ConfigEntry<int> _PortalPerFuelAmount;

		public static ConfigEntry<Toggle> _UsePortalKeys;

		private void InitConfigs()
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			_serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked);
			_DeviceFuel = config("Settings", "0 - Portal Fuel", "Coins", "Set the prefab name of the fuel item required to teleport");
			_PortalToPlayers = config("Settings", "2 - Portal To Players", Toggle.Off, "If on, portal shows players as destination options");
			_PortalUseFuel = config("Settings", "3 - Portal Use Fuel", Toggle.Off, "If on, static portals require fuel");
			_PortalPerFuelAmount = config("Settings", "4 - Portal Fuel Distance", 10, new ConfigDescription("Fuel cost per distance", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 101), Array.Empty<object>()));
			_TeleportAnything = config("Teleport Keys", "0 - Teleport Anything", Toggle.Off, "If on, portal station allows to teleport without restrictions");
			_UsePortalKeys = config("Teleport Keys", "1 - Use Keys", Toggle.Off, "If on, portal checks keys to portal player if carrying ores, dragon eggs, etc...");
		}

		private static AssetBundle GetAssetBundle(string fileName)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string name = executingAssembly.GetManifestResourceNames().Single([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (string str) => str.EndsWith(fileName));
			using Stream stream = executingAssembly.GetManifestResourceStream(name);
			return AssetBundle.LoadFromStream(stream);
		}

		public void Awake()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			_Plugin = this;
			_root = new GameObject("root");
			Object.DontDestroyOnLoad((Object)(object)_root);
			_root.SetActive(false);
			InitConfigs();
			Localizer.Load();
			BuildPiece buildPiece = new BuildPiece("portalpondbundle", "PortalAltar");
			buildPiece.Name.English("Portal Altar");
			buildPiece.Description.English("");
			buildPiece.Category.Set(BuildPieceCategory.Misc);
			buildPiece.Crafting.Set(CraftingTable.Workbench);
			buildPiece.RequiredItems.Add("Stone", 10, recover: true);
			buildPiece.RequiredItems.Add("FineWood", 10, recover: true);
			buildPiece.RequiredItems.Add("SurtlingCore", 2, recover: true);
			buildPiece.RequiredItems.Add("GreydwarfEye", 10, recover: true);
			BuildPiece buildPiece2 = new BuildPiece("portalpondbundle", "Aisho_BlackPortal");
			buildPiece2.Name.English("Portal Black");
			buildPiece2.Description.English("");
			buildPiece2.Category.Set(BuildPieceCategory.Misc);
			buildPiece2.Crafting.Set(CraftingTable.None);
			buildPiece2.SpecialProperties = new SpecialProperties
			{
				AdminOnly = true
			};
			AishoPortals.BlackWhite.AishoPortals.PrefabsToSearch.Add(((Object)buildPiece2.Prefab).name);
			((Component)buildPiece2.Prefab.transform.Find("Cube")).gameObject.AddComponent<Connect>();
			BuildPiece buildPiece3 = new BuildPiece("portalpondbundle", "Aisho_WhitePortal");
			buildPiece3.Name.English("Portal White");
			buildPiece3.Description.English("");
			buildPiece3.Category.Set(BuildPieceCategory.Misc);
			buildPiece3.Crafting.Set(CraftingTable.None);
			buildPiece3.SpecialProperties = new SpecialProperties
			{
				AdminOnly = true
			};
			((Component)buildPiece3.Prefab.transform.Find("Cube")).gameObject.AddComponent<Connect>();
			AishoPortals.BlackWhite.AishoPortals.PrefabsToSearch.Add(((Object)buildPiece3.Prefab).name);
			MaterialReplacer.RegisterGameObjectForMatSwap(((Component)buildPiece.Prefab.transform.Find("effects")).gameObject);
			MaterialReplacer.RegisterGameObjectForShaderSwap(((Component)buildPiece.Prefab.transform.Find("model")).gameObject, MaterialReplacer.ShaderType.PieceShader);
			PieceEffectsSetter.PrefabsToSet.Add(buildPiece.Prefab);
			AishoPortals.Stations.Stations.PrefabsToSearch.Add(((Object)buildPiece.Prefab).name);
			buildPiece.Prefab.AddComponent<PortalStation>();
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
			SetupWatcher();
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}

		private void SetupWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			fileSystemWatcher.Changed += ReadConfigValues;
			fileSystemWatcher.Created += ReadConfigValues;
			fileSystemWatcher.Renamed += ReadConfigValues;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			if (!File.Exists(ConfigFileFullPath))
			{
				return;
			}
			try
			{
				AishoPortalsLogger.LogDebug((object)"ReadConfigValues called");
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch
			{
				AishoPortalsLogger.LogError((object)("There was an issue loading your " + ConfigFileName));
				AishoPortalsLogger.LogError((object)"Please check your config entries for spelling and format!");
			}
		}

		public ConfigEntry<T> config<[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags);
			ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val);
			SyncedConfigEntry<T> syncedConfigEntry = ConfigSync.AddConfigEntry<T>(val2);
			syncedConfigEntry.SynchronizedConfig = synchronizedSetting;
			return val2;
		}

		public ConfigEntry<T> config<[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		static AishoPortalsPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			ConnectionError = "";
			AishoPortalsLogger = Logger.CreateLogSource("AishoPortals");
			ConfigSync = new ConfigSync("RustyMods.AishoPortals")
			{
				DisplayName = "AishoPortals",
				CurrentVersion = "1.0.0",
				MinimumRequiredVersion = "1.0.0"
			};
			_UIAssetBundle = GetAssetBundle("portalstationui");
			_Plugin = null;
			_root = null;
			_serverConfigLocked = null;
			_TeleportAnything = null;
			_DeviceFuel = null;
			_PortalToPlayers = null;
			_PortalUseFuel = null;
			_PortalPerFuelAmount = null;
			_UsePortalKeys = null;
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	public static class RegisterAndCheckVersion
	{
		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			AishoPortalsPlugin.AishoPortalsLogger.LogDebug((object)"Registering version RPC handler");
			peer.m_rpc.Register<ZPackage>("AishoPortals_VersionCheck", (Action<ZRpc, ZPackage>)RpcHandlers.RPC_AishoPortals_Version);
			AishoPortalsPlugin.AishoPortalsLogger.LogInfo((object)"Invoking version check");
			ZPackage val = new ZPackage();
			val.Write("1.0.0");
			peer.m_rpc.Invoke("AishoPortals_VersionCheck", new object[1] { val });
		}
	}
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public static class VerifyClient
	{
		private static bool Prefix(ZRpc rpc, ZPackage pkg, ref ZNet __instance)
		{
			if (!__instance.IsServer() || RpcHandlers.ValidatedPeers.Contains(rpc))
			{
				return true;
			}
			AishoPortalsPlugin.AishoPortalsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") never sent version or couldn't due to previous disconnect, disconnecting"));
			rpc.Invoke("Error", new object[1] { 3 });
			return false;
		}

		private static void Postfix(ZNet __instance)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "AishoPortalsRequestAdminSync", new object[1] { (object)new ZPackage() });
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
	public class ShowConnectionError
	{
		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
		private static void Postfix(FejdStartup __instance)
		{
			if (__instance.m_connectionFailedPanel.activeSelf)
			{
				__instance.m_connectionFailedError.fontSizeMax = 25f;
				__instance.m_connectionFailedError.fontSizeMin = 15f;
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + AishoPortalsPlugin.ConnectionError;
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "Disconnect")]
	public static class RemoveDisconnectedPeerFromVerified
	{
		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			if (__instance.IsServer())
			{
				AishoPortalsPlugin.AishoPortalsLogger.LogInfo((object)("Peer (" + peer.m_rpc.m_socket.GetHostName() + ") disconnected, removing from validated list"));
				RpcHandlers.ValidatedPeers.Remove(peer.m_rpc);
			}
		}
	}
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	public static class RpcHandlers
	{
		public static readonly List<ZRpc> ValidatedPeers = new List<ZRpc>();

		public static void RPC_AishoPortals_Version(ZRpc rpc, ZPackage pkg)
		{
			string text = pkg.ReadString();
			AishoPortalsPlugin.AishoPortalsLogger.LogInfo((object)("Version check, local: 1.0.0,  remote: " + text));
			if (text != "1.0.0")
			{
				AishoPortalsPlugin.ConnectionError = "AishoPortals Installed: 1.0.0\n Needed: " + text;
				if (ZNet.instance.IsServer())
				{
					AishoPortalsPlugin.AishoPortalsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting..."));
					rpc.Invoke("Error", new object[1] { 3 });
				}
			}
			else if (!ZNet.instance.IsServer())
			{
				AishoPortalsPlugin.AishoPortalsLogger.LogInfo((object)"Received same version from server!");
			}
			else
			{
				AishoPortalsPlugin.AishoPortalsLogger.LogInfo((object)("Adding peer (" + rpc.m_socket.GetHostName() + ") to validated list"));
				ValidatedPeers.Add(rpc);
			}
		}

		public static string ComputeHashForMod()
		{
			using SHA256 sHA = SHA256.Create();
			byte[] array = sHA.ComputeHash(File.ReadAllBytes(Assembly.GetExecutingAssembly().Location));
			StringBuilder stringBuilder = new StringBuilder();
			byte[] array2 = array;
			foreach (byte b in array2)
			{
				stringBuilder.Append(b.ToString("X2"));
			}
			return stringBuilder.ToString();
		}
	}
}
namespace AishoPortals.Stations
{
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public static class LoadUI
	{
		[Header("Vanilla Assets")]
		private static ButtonSfx m_sfx;

		private static Image m_background;

		[Header("Prefabs")]
		public static GameObject PortalGUI;

		public static GameObject PortalGUI_Item;

		public static GameObject ToggleOn;

		public static GameObject ToggleOff;

		public static GameObject m_public_button;

		public static GameObject m_public_text_go;

		public static RectTransform ItemListRoot;

		[Header("Inputs")]
		public static Text m_title;

		public static Text m_public_text;

		public static void InitGUI(InventoryGui instance)
		{
			if (Object.op_Implicit((Object)(object)instance))
			{
				GetAssets(instance);
				SetVariables(instance);
				SetCloseButton();
				AddBackgroundMaterial();
				SetConfigurable();
				SetToggleButton();
				SetFilterListener();
				AddSFX();
				AddFont();
			}
		}

		private static void AddSFX()
		{
			Button[] componentsInChildren = PortalGUI.GetComponentsInChildren<Button>();
			foreach (Button val in componentsInChildren)
			{
				if (!Object.op_Implicit((Object)(object)((Component)val).GetComponent<ButtonSfx>()))
				{
					((Component)val).gameObject.AddComponent<ButtonSfx>().m_sfxPrefab = m_sfx.m_sfxPrefab;
				}
			}
			Button[] componentsInChildren2 = PortalGUI_Item.GetComponentsInChildren<Button>();
			foreach (Button val2 in componentsInChildren2)
			{
				if (!Object.op_Implicit((Object)(object)((Component)val2).GetComponent<ButtonSfx>()))
				{
					((Component)val2).gameObject.AddComponent<ButtonSfx>().m_sfxPrefab = m_sfx.m_sfxPrefab;
				}
			}
		}

		private static void SetToggleButton()
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			Transform val = Utils.FindChild(PortalGUI.transform, "$part_toggleButton", (IterativeSearchType)0);
			m_public_button = ((Component)val).gameObject;
			Button val2 = default(Button);
			if (((Component)val).TryGetComponent<Button>(ref val2))
			{
				((UnityEvent)val2.onClick).AddListener(new UnityAction(PortalStationGUI.SetToggleValue));
				ToggleOn = ((Component)Utils.FindChild(val, "On", (IterativeSearchType)0)).gameObject;
				ToggleOff = ((Component)Utils.FindChild(val, "Off", (IterativeSearchType)0)).gameObject;
			}
		}

		private static void SetFilterListener()
		{
			InputField val = default(InputField);
			if (((Component)Utils.FindChild(PortalGUI.transform, "$input_filter", (IterativeSearchType)0)).TryGetComponent<InputField>(ref val))
			{
				((UnityEvent<string>)(object)val.onValueChanged).AddListener((UnityAction<string>)PortalStationGUI.OnFilterInput);
			}
		}

		private static void SetConfigurable()
		{
			((Component)Utils.FindChild(PortalGUI.transform, "$text_filter", (IterativeSearchType)0)).GetComponent<Text>().text = Localization.instance.Localize("$text_filter");
			((Component)Utils.FindChild(PortalGUI.transform, "$text_destinations", (IterativeSearchType)0)).GetComponent<Text>().text = Localization.instance.Localize("$text_destination");
			m_title.text = Localization.instance.Localize("text_portal");
			m_public_text.text = Localization.instance.Localize("$text_public");
		}

		private static void AddBackgroundMaterial()
		{
			Image[] componentsInChildren = PortalGUI.GetComponentsInChildren<Image>();
			Image[] array = componentsInChildren;
			foreach (Image val in array)
			{
				((Graphic)val).material = ((Graphic)m_background).material;
			}
		}

		private static void SetCloseButton()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			Transform val = Utils.FindChild(PortalGUI.transform, "$part_CloseButton", (IterativeSearchType)0);
			Button component = ((Component)val).GetComponent<Button>();
			((UnityEvent)component.onClick).AddListener(new UnityAction(PortalStationGUI.HidePortalGUI));
			if (!Object.op_Implicit((Object)(object)((Component)val).GetComponent<ButtonSfx>()))
			{
				ButtonSfx val2 = ((Component)val).gameObject.AddComponent<ButtonSfx>();
				val2.m_sfxPrefab = m_sfx.m_sfxPrefab;
			}
			Text val3 = default(Text);
			if (((Component)val.Find("$text_button_close")).TryGetComponent<Text>(ref val3))
			{
				val3.text = Localization.instance.Localize("$text_close");
			}
		}

		private static void SetVariables(InventoryGui instance)
		{
			PortalGUI = Object.Instantiate<GameObject>(AishoPortalsPlugin._UIAssetBundle.LoadAsset<GameObject>("portalstation_gui"), ((Component)instance).transform, false);
			PortalGUI_Item = Object.Instantiate<GameObject>(AishoPortalsPlugin._UIAssetBundle.LoadAsset<GameObject>("portalstation_gui_stationitem"));
			ItemListRoot = ((Component)Utils.FindChild(PortalGUI.transform, "$part_Content", (IterativeSearchType)0)).GetComponent<RectTransform>();
			Object.DontDestroyOnLoad((Object)(object)PortalGUI);
			PortalGUI.SetActive(false);
			m_public_text_go = ((Component)Utils.FindChild(PortalGUI.transform, "$text_public", (IterativeSearchType)0)).gameObject;
			m_public_text = m_public_text_go.GetComponent<Text>();
			m_title = ((Component)Utils.FindChild(PortalGUI.transform, "$text_title", (IterativeSearchType)0)).GetComponent<Text>();
		}

		private static void GetAssets(InventoryGui instance)
		{
			m_sfx = ((Component)instance.m_trophiesPanel.transform.Find("TrophiesFrame/Closebutton")).GetComponent<ButtonSfx>();
			m_background = ((Component)instance.m_trophiesPanel.transform.Find("TrophiesFrame/border (1)")).GetComponent<Image>();
		}

		private static void AddFont()
		{
			Font font = GetFont("Norsebold");
			AddFonts(PortalGUI.GetComponentsInChildren<Text>(), font);
			AddFonts(PortalGUI_Item.GetComponentsInChildren<Text>(), font);
		}

		private static void AddFonts(Text[] array, [<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)] Font font)
		{
			foreach (Text val in array)
			{
				val.font = font;
			}
		}

		[return: <58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		private static Font GetFont(string name)
		{
			return ((IEnumerable<Font>)Resources.FindObjectsOfTypeAll<Font>()).FirstOrDefault((Func<Font, bool>)([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (Font x) => ((Object)x).name == name));
		}
	}
	public static class Patches
	{
		[HarmonyPatch(typeof(InventoryGui), "Awake")]
		private static class AttachPortalStationGUI
		{
			[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
			private static void Postfix(InventoryGui __instance)
			{
				LoadUI.InitGUI(__instance);
			}
		}

		[HarmonyPatch(typeof(StoreGui), "IsVisible")]
		private static class IsStationVisible2
		{
			private static void Postfix(ref bool __result)
			{
				__result |= PortalStationGUI.IsPortalGUIVisible();
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "Hide")]
		private static class IsStationVisible
		{
			private static bool Prefix()
			{
				return !PortalStationGUI.IsPortalGUIVisible();
			}
		}

		[HarmonyPatch(typeof(PlayerController), "FixedUpdate")]
		private static class StationPlayerControllerOverride
		{
			private static bool Prefix()
			{
				return !PortalStationGUI.IsPortalGUIVisible();
			}
		}

		[HarmonyPatch(typeof(Game), "Logout")]
		private static class LogoutPatch
		{
			private static void Postfix()
			{
				SaveFavorites();
			}
		}

		[HarmonyPatch(typeof(Player), "OnSpawned")]
		private static class SetLocalPlayerPatch
		{
			[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				if (Object.op_Implicit((Object)(object)__instance) && __instance.m_customData.TryGetValue(PortalStation._FavoriteKey, out var value))
				{
					IDeserializer deserializer = new DeserializerBuilder().Build();
					PortalStationGUI.Favorites = deserializer.Deserialize<List<string>>(value);
				}
			}
		}

		public static void SaveFavorites()
		{
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return;
			}
			try
			{
				ISerializer serializer = new SerializerBuilder().Build();
				string value = serializer.Serialize(PortalStationGUI.Favorites);
				Player.m_localPlayer.m_customData[PortalStation._FavoriteKey] = value;
			}
			catch
			{
				AishoPortalsPlugin.AishoPortalsLogger.LogDebug((object)"Failed to save favorite portals");
			}
		}
	}
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public static class PlayerEffects
	{
		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)]
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static class ZNetScene_Awake_Patch
		{
			[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
			private static void Postfix(ZNetScene __instance)
			{
				//IL_006f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0074: Unknown result type (might be due to invalid IL or missing references)
				//IL_007a: Unknown result type (might be due to invalid IL or missing references)
				//IL_009f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ed: 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_024c: Expected O, but got Unknown
				//IL_0256: Unknown result type (might be due to invalid IL or missing references)
				//IL_025b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0262: Unknown result type (might be due to invalid IL or missing references)
				//IL_0269: Unknown result type (might be due to invalid IL or missing references)
				//IL_0271: Expected O, but got Unknown
				//IL_0273: Unknown result type (might be due to invalid IL or missing references)
				//IL_0278: Unknown result type (might be due to invalid IL or missing references)
				//IL_027f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0286: Unknown result type (might be due to invalid IL or missing references)
				//IL_028e: Expected O, but got Unknown
				//IL_0290: Unknown result type (might be due to invalid IL or missing references)
				//IL_0295: Unknown result type (might be due to invalid IL or missing references)
				//IL_029c: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ab: Expected O, but got Unknown
				//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
				//IL_02be: Expected O, but got Unknown
				//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
				//IL_02e4: Expected O, but got Unknown
				//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
				//IL_0304: Expected O, but got Unknown
				//IL_030e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0313: Unknown result type (might be due to invalid IL or missing references)
				//IL_031b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0323: Expected O, but got Unknown
				if (Object.op_Implicit((Object)(object)__instance))
				{
					GameObject prefab = __instance.GetPrefab("vfx_prespawn");
					GameObject prefab2 = __instance.GetPrefab("sfx_prespawn");
					GameObject prefab3 = __instance.GetPrefab("vfx_Potion_eitr_minor");
					GameObject val = Object.Instantiate<GameObject>(prefab3, AishoPortalsPlugin._root.transform, false);
					((Object)val).name = "vfx_preteleport";
					ParticleSystem[] componentsInChildren = val.GetComponentsInChildren<ParticleSystem>();
					foreach (ParticleSystem val2 in componentsInChildren)
					{
						MainModule main = val2.main;
						MinMaxGradient startColor = default(MinMaxGradient);
						((MinMaxGradient)(ref startColor)).mode = (ParticleSystemGradientMode)0;
						((MinMaxGradient)(ref startColor)).color = new Color(0f, 0.7f, 1f, 1f);
						((MainModule)(ref main)).startColor = startColor;
					}
					Light[] componentsInChildren2 = val.GetComponentsInChildren<Light>();
					foreach (Light val3 in componentsInChildren2)
					{
						val3.color = new Color(0f, 0.6f, 1f, 1f);
					}
					GameObject val4 = Object.Instantiate<GameObject>(val, AishoPortalsPlugin._root.transform, false);
					((Object)val4).name = "vfx_preteleport_smoke";
					Object.Destroy((Object)(object)((Component)val.transform.Find("soft cloud")).gameObject);
					Object.Destroy((Object)(object)((Component)val.transform.Find("flare")).gameObject);
					Object.Destroy((Object)(object)((Component)val4.transform.Find("trails")).gameObject);
					Object.Destroy((Object)(object)((Component)val4.transform.Find("flakes")).gameObject);
					Object.Destroy((Object)(object)((Component)val4.transform.Find("flare")).gameObject);
					Object.Destroy((Object)(object)((Component)val4.transform.Find("Point light")).gameObject);
					if (!__instance.m_prefabs.Contains(val))
					{
						__instance.m_prefabs.Add(val);
					}
					__instance.m_namedPrefabs[StringExtensionMethods.GetStableHashCode(((Object)val).name)] = val;
					if (!__instance.m_prefabs.Contains(val4))
					{
						__instance.m_prefabs.Add(val4);
					}
					__instance.m_namedPrefabs[StringExtensionMethods.GetStableHashCode(((Object)val4).name)] = val4;
					EffectList val5 = new EffectList();
					val5.m_effectPrefabs = (EffectData[])(object)new EffectData[3]
					{
						new EffectData
						{
							m_prefab = prefab,
							m_enabled = true,
							m_attach = true
						},
						new EffectData
						{
							m_prefab = prefab2,
							m_enabled = true,
							m_attach = true
						},
						new EffectData
						{
							m_prefab = val,
							m_enabled = true,
							m_attach = true
						}
					};
					m_startEffects = val5;
					val5 = new EffectList();
					val5.m_effectPrefabs = (EffectData[])(object)new EffectData[1]
					{
						new EffectData
						{
							m_prefab = val4,
							m_enabled = true,
							m_attach = true
						}
					};
					m_midEffects = val5;
					GameObject prefab4 = __instance.GetPrefab("sfx_fader_bell");
					val5 = new EffectList();
					val5.m_effectPrefabs = (EffectData[])(object)new EffectData[1]
					{
						new EffectData
						{
							m_prefab = prefab4,
							m_enabled = true
						}
					};
					m_stopEffects = val5;
				}
			}
		}

		public static EffectList m_startEffects;

		public static EffectList m_midEffects;

		public static EffectList m_stopEffects;
	}
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	public class PortalStation : MonoBehaviour, Interactable, Hoverable, TextReceiver
	{
		public static readonly int _prop_station_name = StringExtensionMethods.GetStableHashCode("stationName");

		public static readonly int _prop_station_code = StringExtensionMethods.GetStableHashCode("stationNetwork");

		public static readonly string _FavoriteKey = "PortalStationFavorites";

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		public static PortalStation m_currentStation;

		private const float use_distance = 5f;

		private ZNetView _znv = null;

		public Transform m_effects = null;

		public ParticleSystem[] m_particles = null;

		public Light m_light = null;

		public Material m_rune = null;

		public Color m_color;

		private void Awake()
		{
			_znv = ((Component)this).GetComponent<ZNetView>();
			if (_znv.IsValid())
			{
				LoadEffects();
				_znv.Register<string>("RPC_SetStationName", (Action<long, string>)RPC_SetStationName);
				_znv.Register<bool>("RPC_SetStationNetwork", (Action<long, bool>)RPC_SetStationNetwork);
				_znv.Register("RPC_ActivateEffects", (Action<long>)RPC_ActivateEffects);
				_znv.Register("RPC_DeactivateEffects", (Action<long>)RPC_DeactivateEffects);
				if (_znv.IsOwner() && Object.op_Implicit((Object)(object)Player.m_localPlayer) && Utility.IsNullOrWhiteSpace(_znv.GetZDO().GetString(_prop_station_name, "")))
				{
					_znv.GetZDO().Set(_prop_station_name, Player.m_localPlayer.GetPlayerName() + " Portal");
				}
			}
		}

		private void LoadEffects()
		{
			m_effects = ((Component)this).transform.Find("fx_activate");
			m_particles = ((Component)m_effects).GetComponentsInChildren<ParticleSystem>();
			m_light = ((Component)m_effects).GetComponentInChildren<Light>();
			Transform val = m_effects.Find("emission");
			m_rune = ((Renderer)((Component)val).GetComponent<MeshRenderer>()).material;
		}

		public void ActivateEffects()
		{
			_znv.InvokeRPC("RPC_ActivateEffects", Array.Empty<object>());
		}

		private void RPC_ActivateEffects(long sender)
		{
			((Component)m_effects).gameObject.SetActive(true);
		}

		public void DeactivateEffects()
		{
			_znv.InvokeRPC("RPC_DeactivateEffects", Array.Empty<object>());
		}

		private void RPC_DeactivateEffects(long sender)
		{
			((Component)m_effects).gameObject.SetActive(false);
		}

		private void OnDestroy()
		{
			PortalStationGUI.HidePortalGUI();
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			if (hold)
			{
				return false;
			}
			if (alt)
			{
				TextInput.instance.RequestText((TextReceiver)(object)this, Localization.instance.Localize("$hud_rename"), 40);
				return true;
			}
			if (!InUseDistance(user))
			{
				return false;
			}
			m_currentStation = this;
			return PortalStationGUI.ShowPortalGUI(_znv);
		}

		public void RPC_SetStationName(long sender, string value)
		{
			if (_znv.IsValid() && _znv.IsOwner() && !(GetStationName() == value))
			{
				_znv.GetZDO().Set(_prop_station_name, value);
			}
		}

		public void RPC_SetStationNetwork(long sender, bool value)
		{
			Piece val = default(Piece);
			if (_znv.IsValid() && _znv.IsOwner() && ((Component)this).TryGetComponent<Piece>(ref val) && val.IsCreator())
			{
				_znv.GetZDO().Set(_prop_station_code, value);
			}
		}

		private string GetStationName()
		{
			return _znv.GetZDO().GetString(_prop_station_name, "");
		}

		private bool InUseDistance(Humanoid human)
		{
			//IL_0006: 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)
			return Vector3.Distance(((Component)human).transform.position, ((Component)this).transform.position) <= 5f;
		}

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

		public string GetHoverText()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(GetText() + "\n");
			stringBuilder.Append("[<color=yellow><b>$KEY_Use</b></color>] $hud_select\n");
			stringBuilder.Append("[<color=yellow><b>L.Shift + $KEY_Use</b></color>] $hud_rename");
			return Localization.instance.Localize(stringBuilder.ToString());
		}

		public string GetHoverName()
		{
			return "";
		}

		public string GetText()
		{
			return (!_znv.IsValid()) ? "" : _znv.GetZDO().GetString(_prop_station_name, "");
		}

		public void SetText(string text)
		{
			if (_znv.IsValid() && !string.IsNullOrWhiteSpace(text))
			{
				_znv.InvokeRPC("RPC_SetStationName", new object[1] { text });
			}
		}
	}
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public static class PortalStationGUI
	{
		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		private static ZNetView currentPortalStation;

		private const float portal_exit_distance = 1f;

		public static List<string> Favorites = new List<string>();

		private static HashSet<ZDO> SortStations(HashSet<ZDO> list)
		{
			return new HashSet<ZDO>(list.OrderBy([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (ZDO zdo) => zdo.GetString(PortalStation._prop_station_name, "")).ToList());
		}

		public static void OnFilterInput(string input)
		{
			if ((Object)(object)currentPortalStation != (Object)null)
			{
				GetDestinations(currentPortalStation, input);
			}
		}

		private static void SetFavorite(ZDO zdo)
		{
			if (Favorites.Contains(zdo.GetString(PortalStation._prop_station_name, "")))
			{
				Favorites.Remove(zdo.GetString(PortalStation._prop_station_name, ""));
			}
			else
			{
				Favorites.Add(zdo.GetString(PortalStation._prop_station_name, ""));
			}
			Patches.SaveFavorites();
		}

		public static void SetToggleValue()
		{
			if (!((Object)(object)currentPortalStation == (Object)null) && currentPortalStation.IsValid())
			{
				long playerID = Player.m_localPlayer.GetPlayerID();
				long @long = currentPortalStation.GetZDO().GetLong(ZDOVars.s_creator, 0L);
				if (playerID == @long)
				{
					bool flag = !currentPortalStation.GetZDO().GetBool(PortalStation._prop_station_code, false);
					currentPortalStation.GetZDO().Set(PortalStation._prop_station_code, flag);
					LoadUI.ToggleOn.SetActive(flag);
					LoadUI.ToggleOff.SetActive(!flag);
					LoadUI.m_public_text.text = Localization.instance.Localize(flag ? "$text_public" : "$text_private");
				}
			}
		}

		private static void SetToggleVisibility(bool toggle)
		{
			LoadUI.m_public_button.SetActive(toggle);
			LoadUI.m_public_text_go.SetActive(toggle);
		}

		public static bool ShowPortalGUI(ZNetView znv)
		{
			if (!Object.op_Implicit((Object)(object)znv))
			{
				return false;
			}
			if (!znv.IsValid())
			{
				return false;
			}
			znv.ClaimOwnership();
			LoadUI.PortalGUI.SetActive(true);
			currentPortalStation = znv;
			GetDestinations(znv);
			LoadUI.m_title.text = "Portal";
			bool @bool = znv.GetZDO().GetBool(PortalStation._prop_station_code, false);
			LoadUI.ToggleOn.SetActive(@bool);
			LoadUI.ToggleOff.SetActive(!@bool);
			LoadUI.m_public_text.text = Localization.instance.Localize(@bool ? "$text_public" : "$text_private");
			SetToggleVisibility(toggle: true);
			return true;
		}

		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(2)]
		private static ItemDrop GetFuelItem()
		{
			if (!Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return null;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(AishoPortalsPlugin._DeviceFuel.Value);
			if (!Object.op_Implicit((Object)(object)prefab))
			{
				GameObject prefab2 = ZNetScene.instance.GetPrefab("Coins");
				return prefab2.GetComponent<ItemDrop>();
			}
			ItemDrop val = default(ItemDrop);
			return (!prefab.TryGetComponent<ItemDrop>(ref val)) ? null : val;
		}

		private static void GetDestinations(ZNetView znv, string filter = "")
		{
			if ((Object)(object)znv == (Object)null || !znv.IsValid())
			{
				return;
			}
			DestroyDestinations();
			ItemDrop fuelItem = GetFuelItem();
			if ((Object)(object)fuelItem == (Object)null)
			{
				return;
			}
			HashSet<ZDO> source = SortStations(FindDestinations());
			foreach (ZDO item in source.Where([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (ZDO x) => Favorites.Contains(x.GetString(PortalStation._prop_station_name, ""))))
			{
				GetDestination(item, znv, filter, fuelItem, isFavorite: true);
			}
			foreach (ZDO item2 in source.Where([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (ZDO x) => !Favorites.Contains(x.GetString(PortalStation._prop_station_name, ""))))
			{
				GetDestination(item2, znv, filter, fuelItem, isFavorite: false);
			}
			if (AishoPortalsPlugin._PortalToPlayers.Value == AishoPortalsPlugin.Toggle.Off || !Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return;
			}
			foreach (ZNetPeer item3 in from peer in ZNet.instance.GetPeers()
				where peer.IsReady()
				select peer)
			{
				CreatePlayerDestination(item3, filter, fuelItem);
			}
		}

		private static HashSet<ZDO> FindDestinations()
		{
			List<ZDO> list = new List<ZDO>();
			foreach (string item in Stations.PrefabsToSearch)
			{
				int num = 0;
				while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative(item, list, ref num))
				{
				}
			}
			return new HashSet<ZDO>(list);
		}

		private static void DestroyDestinations()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			foreach (Transform item in (Transform)LoadUI.ItemListRoot)
			{
				Transform val = item;
				Object.Destroy((Object)(object)((Component)val).gameObject);
			}
		}

		private static void CreatePlayerDestination(ZNetPeer peer, string filter, ItemDrop fuel)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			if (peer.m_characterID == ((Character)Player.m_localPlayer).GetZDOID() || peer.m_playerName == "Stranger")
			{
				return;
			}
			string playerName = peer.m_playerName;
			if (!Utility.IsNullOrWhiteSpace(playerName) && (Utility.IsNullOrWhiteSpace(filter) || playerName.ToLower().Contains(filter.ToLower())))
			{
				int cost = Teleportation.CalculateFuelCost(Vector3.Distance(peer.m_refPos, ((Component)Player.m_localPlayer).transform.position));
				CreateDestination(cost, playerName, fuel, out var image, out var favoriteButton, out var teleportButton);
				((Graphic)image).color = Color.black;
				((Selectable)favoriteButton).interactable = false;
				((UnityEvent)teleportButton.onClick).AddListener((UnityAction)delegate
				{
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					TeleportWithCost(peer.m_refPos, cost, fuel);
				});
			}
		}

		private static bool isInGroup(long creator)
		{
			return API.FindGroupMemberByPlayerId(creator).HasValue;
		}

		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(2)]
		private static bool isInGuild(Player creator)
		{
			Guild ownGuild = API.GetOwnGuild();
			if (ownGuild == null || (Object)(object)creator == (Object)null)
			{
				return false;
			}
			return ownGuild.Members.Any([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (KeyValuePair<PlayerReference, GuildMember> member) => member.Key.name == creator.GetPlayerName());
		}

		private static bool isPublic(ZDO zdo)
		{
			return zdo.GetBool(PortalStation._prop_station_code, false);
		}

		private static bool isCreator(long creator)
		{
			return creator == Player.m_localPlayer.GetPlayerID();
		}

		private static void GetDestination(ZDO zdo, ZNetView znv, string filter, ItemDrop fuel, bool isFavorite)
		{
			//IL_0036: 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_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Expected O, but got Unknown
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Expected O, but got Unknown
			if (!zdo.IsValid() || zdo.m_uid == znv.GetZDO().m_uid)
			{
				return;
			}
			long @long = zdo.GetLong(ZDOVars.s_creator, 0L);
			if (!isPublic(zdo) && !isCreator(@long) && !isInGroup(@long) && !isInGuild(Player.GetPlayer(@long)))
			{
				return;
			}
			string @string = zdo.GetString(PortalStation._prop_station_name, "");
			if (!Utility.IsNullOrWhiteSpace(@string) && (Utility.IsNullOrWhiteSpace(filter) || @string.ToLower().Contains(filter.ToLower())))
			{
				int cost = Teleportation.CalculateFuelCost(Vector3.Distance(zdo.GetPosition(), ((Component)Player.m_localPlayer).transform.position));
				CreateDestination(cost, @string, fuel, out var image, out var favoriteButton, out var teleportButton);
				((Graphic)image).color = (isFavorite ? Color.white : Color.black);
				((UnityEvent)favoriteButton.onClick).AddListener((UnityAction)delegate
				{
					SetFavorite(zdo);
					GetDestinations(znv, filter);
				});
				((UnityEvent)teleportButton.onClick).AddListener((UnityAction)delegate
				{
					TeleportWithCost(zdo, cost, fuel);
				});
			}
		}

		private static void CreateDestination(int cost, string name, ItemDrop fuel, out Image image, out Button favoriteButton, out Button teleportButton)
		{
			GameObject val = Object.Instantiate<GameObject>(LoadUI.PortalGUI_Item, (Transform)(object)LoadUI.ItemListRoot);
			((Component)Utils.FindChild(val.transform, "$part_StationName", (IterativeSearchType)0)).GetComponent<Text>().text = name;
			((Component)Utils.FindChild(val.transform, "$part_FuelImage", (IterativeSearchType)0)).GetComponent<Image>().sprite = fuel.m_itemData.GetIcon();
			((Component)Utils.FindChild(val.transform, "$part_FuelCount", (IterativeSearchType)0)).GetComponent<Text>().text = cost.ToString();
			if (AishoPortalsPlugin._PortalUseFuel.Value == AishoPortalsPlugin.Toggle.Off)
			{
				((Component)Utils.FindChild(val.transform, "$part_FuelElement", (IterativeSearchType)0)).gameObject.SetActive(false);
			}
			Transform val2 = Utils.FindChild(val.transform, "$part_FavoriteButton", (IterativeSearchType)0);
			image = ((Component)val2.GetChild(0)).GetComponent<Image>();
			favoriteButton = ((Component)val2).GetComponent<Button>();
			teleportButton = ((Component)Utils.FindChild(val.transform, "$part_TeleportButton", (IterativeSearchType)0)).GetComponent<Button>();
		}

		private static void TeleportWithCost(Vector3 location, int cost, ItemDrop fuel)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			if (!Teleportation.IsTeleportable(Player.m_localPlayer))
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, "$msg_noteleport", 0, (Sprite)null);
				return;
			}
			int fuelAmount = Teleportation.GetFuelAmount((Humanoid)(object)Player.m_localPlayer, fuel);
			if (fuelAmount < cost && !Player.m_localPlayer.NoCostCheat())
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, "$msg_notenoughfuel", 0, (Sprite)null);
				return;
			}
			if (!Player.m_localPlayer.NoCostCheat())
			{
				Teleportation.ConsumeFuel(Player.m_localPlayer, fuel, cost);
			}
			((MonoBehaviour)AishoPortalsPlugin._Plugin).StartCoroutine(StartTeleportation(location + new Vector3(0f, 1f, 0f), ((Component)Player.m_localPlayer).transform.rotation, distant: true));
		}

		private static IEnumerator StartTeleportation(Vector3 pos, Quaternion rot, bool distant)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)currentPortalStation == (Object)null)
			{
				yield break;
			}
			HidePortalGUI();
			yield return (object)new WaitForSeconds(1f);
			Player.m_localPlayer.StartEmote("kneel", true);
			Transform transform2 = ((Component)Player.m_localPlayer).transform;
			GameObject[] startEffects = PlayerEffects.m_startEffects.Create(transform2.position, transform2.rotation, transform2, 1f, -1);
			if ((Object)(object)PortalStation.m_currentStation != (Object)null)
			{
				PortalStation.m_currentStation.ActivateEffects();
			}
			yield return (object)new WaitForSeconds(8f);
			GameObject[] midEffects = PlayerEffects.m_midEffects.Create(transform2.position, transform2.rotation, transform2, 1f, -1);
			yield return (object)new WaitForSeconds(2f);
			GameObject[] array = startEffects;
			ZNetView znv = default(ZNetView);
			foreach (GameObject effect in array)
			{
				if (effect.TryGetComponent<ZNetView>(ref znv) && znv.IsValid())
				{
					znv.ClaimOwnership();
					znv.Destroy();
					znv = null;
				}
			}
			GameObject[] array2 = midEffects;
			ZNetView znv2 = default(ZNetView);
			foreach (GameObject effect2 in array2)
			{
				if (effect2.TryGetComponent<ZNetView>(ref znv2) && znv2.IsValid())
				{
					znv2.ClaimOwnership();
					znv2.Destroy();
					znv2 = null;
				}
			}
			((Character)Player.m_localPlayer).TeleportTo(pos, rot, distant);
			yield return (object)new WaitForSeconds(2f);
			PlayerEffects.m_stopEffects.Create(pos, rot, (Transform)null, 1f, -1);
			if ((Object)(object)PortalStation.m_currentStation != (Object)null)
			{
				PortalStation.m_currentStation.DeactivateEffects();
			}
		}

		private static void TeleportWithCost(ZDO zdo, int cost, ItemDrop fuel)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			TeleportWithCost(zdo.GetPosition(), cost, fuel);
		}

		public static void HidePortalGUI()
		{
			if (Object.op_Implicit((Object)(object)LoadUI.PortalGUI))
			{
				LoadUI.PortalGUI.SetActive(false);
			}
		}

		public static bool IsPortalGUIVisible()
		{
			return Object.op_Implicit((Object)(object)LoadUI.PortalGUI) && LoadUI.PortalGUI.activeSelf;
		}

		public static void UpdateGUI()
		{
			if (Input.GetKeyDown((KeyCode)27) && IsPortalGUIVisible())
			{
				HidePortalGUI();
				Menu.instance.OnClose();
			}
		}
	}
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public static class PieceEffectsSetter
	{
		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)]
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static class ZNetSceneAwakePatch
		{
			[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
			private static void Postfix(ZNetScene __instance)
			{
				AddEffects(__instance);
			}
		}

		public static readonly List<GameObject> PrefabsToSet = new List<GameObject>();

		private static void AddEffects(ZNetScene __instance)
		{
			if (!Object.op_Implicit((Object)(object)__instance))
			{
				return;
			}
			foreach (GameObject item in PrefabsToSet)
			{
				GameObject prefab = __instance.GetPrefab(((Object)item).name);
				SetWearNTearScript(__instance, prefab, "vfx_RockHit", "sfx_rock_destroyed", "vfx_RockHit", "sfx_rock_hit", "vfx_Place_throne02", 0f);
				SetPieceScript(__instance, prefab, "vfx_Place_stone_wall_2x1", "sfx_build_hammer_stone");
			}
		}

		private static void AddSFX(ZNetScene scene, GameObject prefab)
		{
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			GameObject prefab2 = scene.GetPrefab("portal_wood");
			Transform val = Utils.FindChild(prefab2.transform, "SFX", (IterativeSearchType)0);
			AudioSource val2 = default(AudioSource);
			if (Object.op_Implicit((Object)(object)val) && ((Component)val).TryGetComponent<AudioSource>(ref val2))
			{
				Transform val3 = Utils.FindChild(prefab.transform, "SFX", (IterativeSearchType)0);
				if (Object.op_Implicit((Object)(object)val3))
				{
					AudioSource val4 = ((Component)val3).gameObject.AddComponent<AudioSource>();
					val4.clip = val2.clip;
					val4.outputAudioMixerGroup = val2.outputAudioMixerGroup;
					val4.mute = val2.mute;
					val4.bypassEffects = val2.bypassEffects;
					val4.bypassReverbZones = val2.bypassReverbZones;
					val4.playOnAwake = val2.playOnAwake;
					val4.loop = val2.loop;
					val4.priority = val2.priority;
					val4.pitch = val2.pitch;
					val4.panStereo = val2.panStereo;
					val4.spatialBlend = val2.spatialBlend;
					val4.reverbZoneMix = val2.reverbZoneMix;
					val4.dopplerLevel = val2.dopplerLevel;
					val4.spread = val2.spread;
					val4.rolloffMode = val2.rolloffMode;
					val4.minDistance = val2.minDistance;
					val4.maxDistance = val2.maxDistance;
				}
			}
		}

		private static void SetWearNTearScript(ZNetScene scene, GameObject prefab, string destroyedEffectName1, string destroyEffectName2, string hitEffectName1, string hitEffectName2, string switchEffectName, float health)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0041: 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_004d: 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_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: 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_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Expected O, but got Unknown
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: 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_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Expected O, but got Unknown
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Expected O, but got Unknown
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Expected O, but got Unknown
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Expected O, but got Unknown
			GameObject prefab2 = scene.GetPrefab(destroyedEffectName1);
			GameObject prefab3 = scene.GetPrefab(destroyEffectName2);
			if (!Object.op_Implicit((Object)(object)prefab2) || !Object.op_Implicit((Object)(object)prefab3))
			{
				return;
			}
			EffectList val = new EffectList();
			val.m_effectPrefabs = (EffectData[])(object)new EffectData[2]
			{
				new EffectData
				{
					m_prefab = prefab2,
					m_enabled = true,
					m_variant = -1,
					m_attach = false,
					m_inheritParentRotation = false,
					m_inheritParentScale = false,
					m_randomRotation = false,
					m_scale = false,
					m_childTransform = ""
				},
				new EffectData
				{
					m_prefab = prefab3,
					m_enabled = true,
					m_variant = -1,
					m_attach = false,
					m_inheritParentRotation = false,
					m_inheritParentScale = false,
					m_randomRotation = false,
					m_scale = false,
					m_childTransform = ""
				}
			};
			EffectList destroyedEffect = val;
			GameObject prefab4 = scene.GetPrefab(hitEffectName1);
			GameObject prefab5 = scene.GetPrefab(hitEffectName2);
			if (Object.op_Implicit((Object)(object)prefab4) && Object.op_Implicit((Object)(object)prefab5))
			{
				val = new EffectList();
				val.m_effectPrefabs = (EffectData[])(object)new EffectData[2]
				{
					new EffectData
					{
						m_prefab = prefab4,
						m_enabled = true,
						m_variant = -1,
						m_attach = false,
						m_inheritParentRotation = false,
						m_inheritParentScale = false,
						m_randomRotation = false,
						m_scale = false,
						m_childTransform = ""
					},
					new EffectData
					{
						m_prefab = prefab5,
						m_enabled = true,
						m_variant = -1,
						m_attach = false,
						m_inheritParentRotation = false,
						m_inheritParentScale = false,
						m_randomRotation = false,
						m_scale = false,
						m_childTransform = ""
					}
				};
				EffectList hitEffect = val;
				GameObject prefab6 = scene.GetPrefab(switchEffectName);
				val = new EffectList();
				val.m_effectPrefabs = (EffectData[])(object)new EffectData[1]
				{
					new EffectData
					{
						m_prefab = prefab6,
						m_enabled = true,
						m_variant = -1,
						m_attach = false,
						m_inheritParentRotation = false,
						m_inheritParentScale = false,
						m_randomRotation = false,
						m_scale = false,
						m_childTransform = ""
					}
				};
				EffectList switchEffect = val;
				WearNTear component = prefab.GetComponent<WearNTear>();
				component.m_destroyedEffect = destroyedEffect;
				component.m_hitEffect = hitEffect;
				component.m_switchEffect = switchEffect;
				if (health != 0f)
				{
					component.m_health = health;
				}
			}
		}

		private static void SetPieceScript(ZNetScene scene, GameObject prefab, string placementEffectName1, string placementEffectName2)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0041: 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_004d: 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_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: 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_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			GameObject prefab2 = scene.GetPrefab(placementEffectName1);
			GameObject prefab3 = scene.GetPrefab(placementEffectName2);
			if (Object.op_Implicit((Object)(object)prefab2) && Object.op_Implicit((Object)(object)prefab3))
			{
				EffectList val = new EffectList();
				val.m_effectPrefabs = (EffectData[])(object)new EffectData[2]
				{
					new EffectData
					{
						m_prefab = prefab2,
						m_enabled = true,
						m_variant = -1,
						m_attach = false,
						m_inheritParentRotation = false,
						m_inheritParentScale = false,
						m_randomRotation = false,
						m_scale = false,
						m_childTransform = ""
					},
					new EffectData
					{
						m_prefab = prefab3,
						m_enabled = true,
						m_variant = -1,
						m_attach = false,
						m_inheritParentRotation = false,
						m_inheritParentScale = false,
						m_randomRotation = false,
						m_scale = false,
						m_childTransform = ""
					}
				};
				EffectList placeEffect = val;
				Piece component = prefab.GetComponent<Piece>();
				component.m_placeEffect = placeEffect;
				component.m_groundPiece = false;
				component.m_allowAltGroundPlacement = false;
				component.m_cultivatedGroundOnly = false;
				component.m_waterPiece = false;
				component.m_clipGround = true;
				component.m_clipEverything = false;
				component.m_noInWater = false;
				component.m_notOnWood = false;
				component.m_notOnTiltingSurface = false;
				component.m_inCeilingOnly = false;
				component.m_notOnFloor = false;
				component.m_noClipping = false;
				component.m_onlyInTeleportArea = false;
				component.m_allowedInDungeons = false;
				component.m_spaceRequirement = 0f;
				component.m_repairPiece = false;
				component.m_canBeRemoved = true;
				component.m_allowRotatedOverlap = false;
				component.m_vegetationGroundOnly = false;
			}
		}
	}
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	public static class Stations
	{
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)]
		private static class ZNetScene_Awake_Patch
		{
			private static void Postfix()
			{
				InitCoroutine();
			}
		}

		private static readonly List<ZDO> TempZDOs = new List<ZDO>();

		public static readonly List<string> PrefabsToSearch = new List<string>();

		public static void InitCoroutine()
		{
			((MonoBehaviour)AishoPortalsPlugin._Plugin).StartCoroutine(SendStationsToClient());
		}

		private static IEnumerator SendStationsToClient()
		{
			while (true)
			{
				if (Object.op_Implicit((Object)(object)Game.instance) && ZDOMan.instance != null && Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer())
				{
					TempZDOs.Clear();
					foreach (string prefab in PrefabsToSearch)
					{
						int index = 0;
						while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative(prefab, TempZDOs, ref index))
						{
							yield return null;
						}
					}
					foreach (ZDO zdo in TempZDOs)
					{
						ZDOMan.instance.ForceSendZDO(zdo.m_uid);
					}
				}
				yield return (object)new WaitForSeconds(10f);
			}
		}
	}
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	public static class Teleportation
	{
		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		[HarmonyPriority(0)]
		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)]
		private static class CreateConfigsForRestrictiveItems
		{
			[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
			private static void Postfix(ObjectDB __instance)
			{
				if (Object.op_Implicit((Object)(object)ZNetScene.instance))
				{
					CreateOreConfigs(__instance);
				}
			}
		}

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

		private static void CreateOreConfigs(ObjectDB __instance)
		{
			ItemDrop val = default(ItemDrop);
			foreach (GameObject item in __instance.m_items)
			{
				if (item.TryGetComponent<ItemDrop>(ref val) && !val.m_itemData.m_shared.m_teleportable)
				{
					ConfigEntry<string> value = AishoPortalsPlugin._Plugin.config("Teleport Keys", ((Object)item).name ?? "", "", "Set the defeat key to enable teleporting " + ((Object)item).name);
					m_teleportKeys[val.m_itemData.m_shared.m_name] = value;
				}
			}
		}

		private static string GetKey(string itemName)
		{
			ConfigEntry<string> value;
			return m_teleportKeys.TryGetValue(itemName, out value) ? value.Value : "none";
		}

		public static bool IsTeleportable(Player player)
		{
			if (AishoPortalsPlugin._TeleportAnything.Value == AishoPortalsPlugin.Toggle.On)
			{
				return true;
			}
			if (!((Humanoid)player).IsTeleportable())
			{
				return AishoPortalsPlugin._UsePortalKeys.Value == AishoPortalsPlugin.Toggle.On && CheckInventory(((Humanoid)player).GetInventory());
			}
			return true;
		}

		private static bool CheckInventory(Inventory inventory)
		{
			List<string> globalKeys = ZoneSystem.instance.GetGlobalKeys();
			foreach (ItemData item in inventory.m_inventory)
			{
				string key = GetKey(item.m_shared.m_name);
				if (key == "none")
				{
					if (!item.m_shared.m_teleportable)
					{
						return false;
					}
				}
				else if (!globalKeys.Contains(key) && !ZoneSystem.instance.GetGlobalKey(key))
				{
					return false;
				}
			}
			return true;
		}

		public static int GetFuelAmount(Humanoid user, ItemDrop fuelItem)
		{
			return user.GetInventory().CountItems(fuelItem.m_itemData.m_shared.m_name, -1, true);
		}

		public static void ConsumeFuel(Player user, ItemDrop fuelItem, int amount)
		{
			((Humanoid)user).GetInventory().RemoveItem(fuelItem.m_itemData.m_shared.m_name, amount, -1, false);
		}

		public static int CalculateFuelCost(float distance)
		{
			return (AishoPortalsPlugin._PortalUseFuel.Value != 0) ? Mathf.Max(1, Mathf.CeilToInt(distance / 2f) / AishoPortalsPlugin._PortalPerFuelAmount.Value) : 0;
		}
	}
}
namespace AishoPortals.Managers
{
	[PublicAPI]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public class Localizer
	{
		private static readonly Dictionary<string, Dictionary<string, Func<string>>> PlaceholderProcessors;

		private static readonly Dictionary<string, Dictionary<string, string>> loadedTexts;

		private static readonly ConditionalWeakTable<Localization, string> localizationLanguage;

		private static readonly List<WeakReference<Localization>> localizationObjects;

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static readonly List<string> fileExtensions;

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: Expected O, but got Unknown
				if (_plugin == null)
				{
					IEnumerable<TypeInfo> source;
					try
					{
						source = Assembly.GetExecutingAssembly().DefinedTypes.ToList();
					}
					catch (ReflectionTypeLoadException ex)
					{
						source = from t in ex.Types
							where t != null
							select t.GetTypeInfo();
					}
					_plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
				}
				return _plugin;
			}
		}

		private static void UpdatePlaceholderText(Localization localization, string key)
		{
			localizationLanguage.TryGetValue(localization, out var value);
			string text = loadedTexts[value][key];
			if (PlaceholderProcessors.TryGetValue(key, out var value2))
			{
				text = value2.Aggregate(text, [<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (string current, KeyValuePair<string, Func<string>> kv) => current.Replace("{" + kv.Key + "}", kv.Value()));
			}
			localization.AddWord(key, text);
		}

		public static void AddPlaceholder<T>(string key, string placeholder, ConfigEntry<T> config, [<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(new byte[] { 2, 1, 1 })] Func<T, string> convertConfigValue = null)
		{
			if (convertConfigValue == null)
			{
				convertConfigValue = [<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] [return: <58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(1)] (T val) => val.ToString();
			}
			if (!PlaceholderProcessors.ContainsKey(key))
			{
				PlaceholderProcessors[key] = new Dictionary<string, Func<string>>();
			}
			config.SettingChanged += [<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (object _, EventArgs _) =>
			{
				UpdatePlaceholder();
			};
			if (loadedTexts.ContainsKey(Localization.instance.GetSelectedLanguage()))
			{
				UpdatePlaceholder();
			}
			void UpdatePlaceholder()
			{
				PlaceholderProcessors[key][placeholder] = () => convertConfigValue(config.Value);
				UpdatePlaceholderText(Localization.instance, key);
			}
		}

		public static void AddText(string key, string text)
		{
			List<WeakReference<Localization>> list = new List<WeakReference<Localization>>();
			foreach (WeakReference<Localization> localizationObject in localizationObjects)
			{
				if (localizationObject.TryGetTarget(out var target))
				{
					Dictionary<string, string> dictionary = loadedTexts[localizationLanguage.GetOrCreateValue(target)];
					if (!target.m_translations.ContainsKey(key))
					{
						dictionary[key] = text;
						target.AddWord(key, text);
					}
				}
				else
				{
					list.Add(localizationObject);
				}
			}
			foreach (WeakReference<Localization> item in list)
			{
				localizationObjects.Remove(item);
			}
		}

		public static void Load()
		{
			LoadLocalization(Localization.instance, Localization.instance.GetSelectedLanguage());
		}

		private static void LoadLocalization(Localization __instance, string language)
		{
			if (!localizationLanguage.Remove(__instance))
			{
				localizationObjects.Add(new WeakReference<Localization>(__instance));
			}
			localizationLanguage.Add(__instance, language);
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			foreach (string item in from f in Directory.GetFiles(Path.GetDirectoryName(Paths.PluginPath), plugin.Info.Metadata.Name + ".*", SearchOption.AllDirectories)
				where fileExtensions.IndexOf(Path.GetExtension(f)) >= 0
				select f)
			{
				string text = Path.GetFileNameWithoutExtension(item).Split(new char[1] { '.' })[1];
				if (dictionary.ContainsKey(text))
				{
					Debug.LogWarning((object)("Duplicate key " + text + " found for " + plugin.Info.Metadata.Name + ". The duplicate file found at " + item + " will be skipped."));
				}
				else
				{
					dictionary[text] = item;
				}
			}
			byte[] array = LoadTranslationFromAssembly("English");
			if (array == null)
			{
				throw new Exception("Found no English localizations in mod " + plugin.Info.Metadata.Name + ". Expected an embedded resource translations/English.json or translations/English.yml.");
			}
			Dictionary<string, string> dictionary2 = new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>>(Encoding.UTF8.GetString(array));
			if (dictionary2 == null)
			{
				throw new Exception("Localization for mod " + plugin.Info.Metadata.Name + " failed: Localization file was empty.");
			}
			string text2 = null;
			if (language != "English")
			{
				if (dictionary.ContainsKey(language))
				{
					text2 = File.ReadAllText(dictionary[language]);
				}
				else
				{
					byte[] array2 = LoadTranslationFromAssembly(language);
					if (array2 != null)
					{
						text2 = Encoding.UTF8.GetString(array2);
					}
				}
			}
			if (text2 == null && dictionary.ContainsKey("English"))
			{
				text2 = File.ReadAllText(dictionary["English"]);
			}
			if (text2 != null)
			{
				foreach (KeyValuePair<string, string> item2 in new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>>(text2) ?? new Dictionary<string, string>())
				{
					dictionary2[item2.Key] = item2.Value;
				}
			}
			loadedTexts[language] = dictionary2;
			foreach (KeyValuePair<string, string> item3 in dictionary2)
			{
				UpdatePlaceholderText(__instance, item3.Key);
			}
		}

		static Localizer()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			PlaceholderProcessors = new Dictionary<string, Dictionary<string, Func<string>>>();
			loadedTexts = new Dictionary<string, Dictionary<string, string>>();
			localizationLanguage = new ConditionalWeakTable<Localization, string>();
			localizationObjects = new List<WeakReference<Localization>>();
			fileExtensions = new List<string> { ".json", ".yml" };
			Harmony val = new Harmony("org.bepinex.helpers.LocalizationManager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalization", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		[return: <58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		private static byte[] LoadTranslationFromAssembly(string language)
		{
			foreach (string fileExtension in fileExtensions)
			{
				byte[] array = ReadEmbeddedFileBytes("translations." + language + fileExtension);
				if (array != null)
				{
					return array;
				}
			}
			return null;
		}

		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(2)]
		public static byte[] ReadEmbeddedFileBytes([<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(1)] string resourceFileName, Assembly containingAssembly = null)
		{
			using MemoryStream memoryStream = new MemoryStream();
			if ((object)containingAssembly == null)
			{
				containingAssembly = Assembly.GetCallingAssembly();
			}
			string text = containingAssembly.GetManifestResourceNames().FirstOrDefault([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (string str) => str.EndsWith(resourceFileName, StringComparison.Ordinal));
			if (text != null)
			{
				containingAssembly.GetManifestResourceStream(text)?.CopyTo(memoryStream);
			}
			return (memoryStream.Length == 0L) ? null : memoryStream.ToArray();
		}
	}
	[PublicAPI]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public static class MaterialReplacer
	{
		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)]
		public enum ShaderType
		{
			PieceShader,
			VegetationShader,
			RockShader,
			RugShader,
			GrassShader,
			CustomCreature,
			UseUnityShader
		}

		private static readonly Dictionary<GameObject, bool> ObjectToSwap;

		private static readonly Dictionary<string, Material> OriginalMaterials;

		private static readonly Dictionary<GameObject, ShaderType> ObjectsForShaderReplace;

		private static readonly HashSet<Shader> CachedShaders;

		private static bool hasRun;

		static MaterialReplacer()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			CachedShaders = new HashSet<Shader>();
			hasRun = false;
			OriginalMaterials = new Dictionary<string, Material>();
			ObjectToSwap = new Dictionary<GameObject, bool>();
			ObjectsForShaderReplace = new Dictionary<GameObject, ShaderType>();
			Harmony val = new Harmony("org.bepinex.helpers.PieceManager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZoneSystem), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(MaterialReplacer), "ReplaceAllMaterialsWithOriginal", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		public static void RegisterGameObjectForShaderSwap(GameObject go, ShaderType type)
		{
			if (!ObjectsForShaderReplace.ContainsKey(go))
			{
				ObjectsForShaderReplace.Add(go, type);
			}
		}

		public static void RegisterGameObjectForMatSwap(GameObject go, bool isJotunnMock = false)
		{
			if (!ObjectToSwap.ContainsKey(go))
			{
				ObjectToSwap.Add(go, isJotunnMock);
			}
		}

		private static void GetAllMaterials()
		{
			Material[] array = Resources.FindObjectsOfTypeAll<Material>();
			foreach (Material val in array)
			{
				OriginalMaterials[((Object)val).name] = val;
			}
		}

		[HarmonyPriority(700)]
		private static void ReplaceAllMaterialsWithOriginal()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			if ((int)SystemInfo.graphicsDeviceType == 4 || hasRun)
			{
				return;
			}
			if (OriginalMaterials.Count == 0)
			{
				GetAllMaterials();
			}
			foreach (KeyValuePair<GameObject, bool> item in ObjectToSwap)
			{
				GameObject key = item.Key;
				bool value = item.Value;
				ProcessGameObjectMaterials(key, value);
			}
			AssetBundle[] array = Resources.FindObjectsOfTypeAll<AssetBundle>();
			AssetBundle[] array2 = array;
			foreach (AssetBundle val in array2)
			{
				IEnumerable<Shader> enumerable3;
				try
				{
					IEnumerable<Shader> enumerable2;
					if (!val.isStreamedSceneAssetBundle || !Object.op_Implicit((Object)(object)val))
					{
						IEnumerable<Shader> enumerable = val.LoadAllAssets<Shader>();
						enumerable2 = enumerable;
					}
					else
					{
						enumerable2 = from shader in ((IEnumerable<string>)val.GetAllAssetNames()).Select((Func<string, Shader>)val.LoadAsset<Shader>)
							where (Object)(object)shader != (Object)null
							select shader;
					}
					enumerable3 = enumerable2;
				}
				catch (Exception)
				{
					continue;
				}
				if (enumerable3 == null)
				{
					continue;
				}
				foreach (Shader item2 in enumerable3)
				{
					CachedShaders.Add(item2);
				}
			}
			foreach (KeyValuePair<GameObject, ShaderType> item3 in ObjectsForShaderReplace)
			{
				GameObject key2 = item3.Key;
				ShaderType value2 = item3.Value;
				ProcessGameObjectShaders(key2, value2);
			}
			hasRun = true;
		}

		private static void ProcessGameObjectMaterials(GameObject go, bool isJotunnMock)
		{
			Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true);
			Renderer[] array = componentsInChildren;
			foreach (Renderer val in array)
			{
				Material[] sharedMaterials = val.sharedMaterials.Select([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (Material material) => ReplaceMaterial(material, isJotunnMock)).ToArray();
				val.sharedMaterials = sharedMaterials;
			}
		}

		private static Material ReplaceMaterial(Material originalMaterial, bool isJotunnMock)
		{
			string text = (isJotunnMock ? "JVLmock_" : "_REPLACE_");
			if (!((Object)originalMaterial).name.StartsWith(text, StringComparison.Ordinal))
			{
				return originalMaterial;
			}
			string text2 = ((Object)originalMaterial).name.Replace(" (Instance)", "").Replace(text, "");
			if (OriginalMaterials.TryGetValue(text2, out var value))
			{
				return value;
			}
			Debug.LogWarning((object)("No suitable material found to replace: " + text2));
			return originalMaterial;
		}

		private static void ProcessGameObjectShaders(GameObject go, ShaderType shaderType)
		{
			Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true);
			Renderer[] array = componentsInChildren;
			foreach (Renderer val in array)
			{
				Material[] sharedMaterials = val.sharedMaterials;
				foreach (Material val2 in sharedMaterials)
				{
					if ((Object)(object)val2 != (Object)null)
					{
						val2.shader = GetShaderForType(val2.shader, shaderType, ((Object)val2.shader).name);
					}
				}
			}
		}

		private static Shader GetShaderForType(Shader orig, ShaderType shaderType, string originalShaderName)
		{
			return (Shader)(shaderType switch
			{
				ShaderType.PieceShader => FindShaderWithName(orig, "Custom/Piece"), 
				ShaderType.VegetationShader => FindShaderWithName(orig, "Custom/Vegetation"), 
				ShaderType.RockShader => FindShaderWithName(orig, "Custom/StaticRock"), 
				ShaderType.RugShader => FindShaderWithName(orig, "Custom/Rug"), 
				ShaderType.GrassShader => FindShaderWithName(orig, "Custom/Grass"), 
				ShaderType.CustomCreature => FindShaderWithName(orig, "Custom/Creature"), 
				ShaderType.UseUnityShader => FindShaderWithName(orig, ((Object)(object)FindShaderWithName(orig, originalShaderName) != (Object)null) ? originalShaderName : "ToonDeferredShading2017"), 
				_ => FindShaderWithName(orig, "Standard"), 
			});
		}

		public static Shader FindShaderWithName(Shader origShader, string name)
		{
			foreach (Shader cachedShader in CachedShaders)
			{
				if (((Object)cachedShader).name == name)
				{
					return cachedShader;
				}
			}
			return origShader;
		}
	}
	[PublicAPI]
	public enum CraftingTable
	{
		None,
		[InternalName("piece_workbench")]
		Workbench,
		[InternalName("piece_cauldron")]
		Cauldron,
		[InternalName("forge")]
		Forge,
		[InternalName("piece_artisanstation")]
		ArtisanTable,
		[InternalName("piece_stonecutter")]
		StoneCutter,
		[InternalName("piece_magetable")]
		MageTable,
		[InternalName("blackforge")]
		BlackForge,
		Custom
	}
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	public class InternalName : Attribute
	{
		public readonly string internalName;

		public InternalName(string internalName)
		{
			this.internalName = internalName;
		}
	}
	[PublicAPI]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public class ExtensionList
	{
		public readonly List<ExtensionConfig> ExtensionStations = new List<ExtensionConfig>();

		public void Set(CraftingTable table, int maxStationDistance = 5)
		{
			ExtensionStations.Add(new ExtensionConfig
			{
				Table = table,
				maxStationDistance = maxStationDistance
			});
		}

		public void Set(string customTable, int maxStationDistance = 5)
		{
			ExtensionStations.Add(new ExtensionConfig
			{
				Table = CraftingTable.Custom,
				custom = customTable,
				maxStationDistance = maxStationDistance
			});
		}
	}
	public struct ExtensionConfig
	{
		public CraftingTable Table;

		public float maxStationDistance;

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		public string custom;
	}
	[PublicAPI]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public class CraftingStationList
	{
		public readonly List<CraftingStationConfig> Stations = new List<CraftingStationConfig>();

		public void Set(CraftingTable table)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = table
			});
		}

		public void Set(string customTable)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = CraftingTable.Custom,
				custom = customTable
			});
		}
	}
	public struct CraftingStationConfig
	{
		public CraftingTable Table;

		public int level;

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		public string custom;
	}
	[PublicAPI]
	public enum BuildPieceCategory
	{
		Misc = 0,
		Crafting = 1,
		BuildingWorkbench = 2,
		BuildingStonecutter = 3,
		Furniture = 4,
		All = 100,
		Custom = 99
	}
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	[PublicAPI]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	public class RequiredResourcesList
	{
		public readonly List<Requirement> Requirements = new List<Requirement>();

		public void Add(string item, int amount, bool recover)
		{
			Requirements.Add(new Requirement
			{
				itemName = item,
				amount = amount,
				recover = recover
			});
		}
	}
	public struct Requirement
	{
		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(1)]
		public string itemName;

		public int amount;

		public bool recover;
	}
	public struct SpecialProperties
	{
		[Description("Admins should be the only ones that can build this piece.")]
		public bool AdminOnly;

		[Description("Turns off generating a config for this build piece.")]
		public bool NoConfig;
	}
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[PublicAPI]
	public class BuildingPieceCategory
	{
		public BuildPieceCategory Category;

		public string custom = "";

		public void Set(BuildPieceCategory category)
		{
			Category = category;
		}

		public void Set(string customCategory)
		{
			Category = BuildPieceCategory.Custom;
			custom = customCategory;
		}
	}
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[PublicAPI]
	public class PieceTool
	{
		public readonly HashSet<string> Tools = new HashSet<string>();

		public void Add(string tool)
		{
			Tools.Add(tool);
		}
	}
	[PublicAPI]
	[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
	[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(1)]
	public class BuildPiece
	{
		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
		internal class PieceConfig
		{
			public ConfigEntry<string> craft = null;

			public ConfigEntry<BuildPieceCategory> category = null;

			public ConfigEntry<string> customCategory = null;

			public ConfigEntry<string> tools = null;

			public ConfigEntry<CraftingTable> extensionTable = null;

			public ConfigEntry<string> customExtentionTable = null;

			public ConfigEntry<float> maxStationDistance = null;

			public ConfigEntry<CraftingTable> table = null;

			public ConfigEntry<string> customTable = null;
		}

		[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
			public string Category;

			[UsedImplicitly]
			[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(new byte[] { 2, 1 })]
			public Action<ConfigEntryBase> CustomDrawer;
		}

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(0)]
		private class SerializedRequirements
		{
			public readonly List<Requirement> Reqs;

			public SerializedRequirements(List<Requirement> reqs)
			{
				Reqs = reqs;
			}

			public SerializedRequirements(string reqs)
			{
				Reqs = reqs.Split(new char[1] { ',' }).Select([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (string r) =>
				{
					string[] array = r.Split(new char[1] { ':' });
					Requirement result = default(Requirement);
					result.itemName = array[0];
					result.amount = ((array.Length <= 1 || !int.TryParse(array[1], out var result2)) ? 1 : result2);
					bool result3 = default(bool);
					result.recover = array.Length <= 2 || !bool.TryParse(array[2], out result3) || result3;
					return result;
				}).ToList();
			}

			public override string ToString()
			{
				return string.Join(",", Reqs.Select([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}:{r.recover}"));
			}

			[return: <58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
			public static ItemDrop fetchByName(ObjectDB objectDB, string name)
			{
				GameObject itemPrefab = objectDB.GetItemPrefab(name);
				ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val == (Object)null)
				{
					Debug.LogWarning((object)(((!string.IsNullOrWhiteSpace(((Object)plugin).name)) ? ("[" + ((Object)plugin).name + "]") : "") + " The required item '" + name + "' does not exist."));
				}
				return val;
			}

			public static Requirement[] toPieceReqs(SerializedRequirements craft)
			{
				Dictionary<string, Requirement> dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func<Requirement, string>)([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (Requirement r) => r.itemName), (Func<Requirement, Requirement>)([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (Requirement r) =>
				{
					//IL_000d: Unknown result type (might be due to invalid IL or missing references)
					//IL_0012: Unknown result type (might be due to invalid IL or missing references)
					//IL_001e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0025: Unknown result type (might be due to invalid IL or missing references)
					ItemDrop val = ResItem(r);
					return (val == null) ? ((Requirement)null) : new Requirement
					{
						m_amount = r.amount,
						m_resItem = val,
						m_recover = r.recover
					};
				}));
				return dictionary.Values.Where([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (Requirement v) => v != null).ToArray();
				[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(2)]
				static ItemDrop ResItem(Requirement r)
				{
					return fetchByName(ObjectDB.instance, r.itemName);
				}
			}
		}

		public List<string> PlaceEffects = new List<string>();

		public List<string> HitEffects = new List<string>();

		public List<string> DestroyedEffects = new List<string>();

		public List<string> SwitchEffects = new List<string>();

		public List<string> RandomSpeakEffects = new List<string>();

		internal static readonly List<BuildPiece> registeredPieces = new List<BuildPiece>();

		private static readonly Dictionary<Piece, BuildPiece> pieceMap = new Dictionary<Piece, BuildPiece>();

		internal static Dictionary<BuildPiece, PieceConfig> pieceConfigs = new Dictionary<BuildPiece, PieceConfig>();

		internal List<Conversion> Conversions = new List<Conversion>();

		internal List<ItemConversion> conversions = new List<ItemConversion>();

		[Description("Disables generation of the configs for your pieces. This is global, this turns it off for all pieces in your mod.")]
		public static bool ConfigurationEnabled = true;

		public readonly GameObject Prefab;

		[Description("Specifies the resources needed to craft the piece.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the building piece should need.")]
		public readonly RequiredResourcesList RequiredItems = new RequiredResourcesList();

		[Description("Sets the category for the building piece.")]
		public readonly BuildingPieceCategory Category = new BuildingPieceCategory();

		[Description("Specifies the tool needed to build your piece.\nUse .Add to add a tool.")]
		public readonly PieceTool Tool = new PieceTool();

		[Description("Specifies the crafting station needed to build your piece.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.")]
		public CraftingStationList Crafting = new CraftingStationList();

		[Description("Makes this piece a station extension")]
		public ExtensionList Extension = new ExtensionList();

		[Description("Change the extended/special properties of your build piece.")]
		public SpecialProperties SpecialProperties;

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		[Description("Specifies a config entry which toggles whether a recipe is active.")]
		public ConfigEntryBase RecipeIsActive = null;

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		private LocalizeKey _name;

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		private LocalizeKey _description;

		internal string[] activeTools = null;

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		private static object configManager;

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		private static Localization _english;

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		internal static BaseUnityPlugin _plugin = null;

		private static bool hasConfigSync = true;

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		private static object _configSync;

		public LocalizeKey Name
		{
			get
			{
				LocalizeKey name = _name;
				if (name != null)
				{
					return name;
				}
				Piece component = Prefab.GetComponent<Piece>();
				if (component.m_name.StartsWith("$"))
				{
					_name = new LocalizeKey(component.m_name);
				}
				else
				{
					string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_");
					_name = new LocalizeKey(text).English(component.m_name);
					component.m_name = text;
				}
				return _name;
			}
		}

		public LocalizeKey Description
		{
			get
			{
				LocalizeKey description = _description;
				if (description != null)
				{
					return description;
				}
				Piece component = Prefab.GetComponent<Piece>();
				if (component.m_description.StartsWith("$"))
				{
					_description = new LocalizeKey(component.m_description);
				}
				else
				{
					string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_") + "_description";
					_description = new LocalizeKey(text).English(component.m_description);
					component.m_description = text;
				}
				return _description;
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		internal static BaseUnityPlugin plugin
		{
			get
			{
				//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: Expected O, but got Unknown
				if (_plugin != null)
				{
					return _plugin;
				}
				IEnumerable<TypeInfo> source;
				try
				{
					source = Assembly.GetExecutingAssembly().DefinedTypes.ToList();
				}
				catch (ReflectionTypeLoadException ex)
				{
					source = from t in ex.Types
						where t != null
						select t.GetTypeInfo();
				}
				_plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
				return _plugin;
			}
		}

		[<58442400-41e8-471d-b095-2aec51fe8fb7>Nullable(2)]
		private static object configSync
		{
			[<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(2)]
			get
			{
				if (_configSync != null || !hasConfigSync)
				{
					return _configSync;
				}
				Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
				if ((object)type != null)
				{
					_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " PieceManager");
					type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
					type.GetProperty("IsLocked").SetValue(_configSync, true);
				}
				else
				{
					hasConfigSync = false;
				}
				return _configSync;
			}
		}

		public BuildPiece(string assetBundleFileName, string prefabName, string folderName = "assets")
			: this(PiecePrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName)
		{
		}

		public BuildPiece(AssetBundle bundle, string prefabName)
		{
			Prefab = PiecePrefabManager.RegisterPrefab(bundle, prefabName);
			registeredPieces.Add(this);
		}

		internal static void Patch_FejdStartup(FejdStartup __instance)
		{
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Expected O, but got Unknown
			//IL_0389: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Expected O, but got Unknown
			//IL_0431: Unknown result type (might be due to invalid IL or missing references)
			//IL_040b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0410: Unknown result type (might be due to invalid IL or missing references)
			//IL_048c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0496: Expected O, but got Unknown
			//IL_0606: Unknown result type (might be due to invalid IL or missing references)
			//IL_0610: Expected O, but got Unknown
			//IL_08ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_08f4: Expected O, but got Unknown
			//IL_067b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0685: Expected O, but got Unknown
			//IL_0721: Unknown result type (might be due to invalid IL or missing references)
			//IL_072b: Expected O, but got Unknown
			//IL_095f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0969: Expected O, but got Unknown
			//IL_0b7e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b88: Expected O, but got Unknown
			//IL_0c18: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c22: Expected O, but got Unknown
			Type configManagerType = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<1ef46c97-e28c-4f32-bcc5-73706b23911b>NullableContext(0)] (Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager");
			configManager = ((configManagerType == null) ? null : Chainloader.ManagerObject.GetComponent(configManagerType));
			foreach (BuildPiece registeredPiece in registeredPieces)
			{
				registeredPiece.activeTools = registeredPiece.Tool.Tools.DefaultIfEmpty("Hammer").ToArray();
				if (registeredPiece.Category.Category != BuildPieceCategory.Custom)
				{
					registeredPiece.Prefab.GetComponent<Piece>().m_category = (PieceCategory)registeredPiece.Category.Category;
				}
				else
				{
					registeredPiece.Prefab.GetComponent<Piece>().m_category = PiecePrefabManager.GetCategory(registeredPiece.Category.custom);
				}
			}
			if (!ConfigurationEnabled)
			{
				return;
			}
			bool saveOnConfigSet = plugin.Config.SaveOnConfigSet;
			plugin.Config.SaveOnConfigSet = false;
			foreach (BuildPiece registeredPiece2 in registeredPieces)
			{
				BuildPiece piece = registeredPiece2;
				if (piece.SpecialProperties.NoConfig)
				{
					continue;
				}
				PieceConfig pieceConfig2 = (pieceConfigs[piece] = new PieceConfig());
				P