Decompiled source of PortalStations v1.2.4

PortalStations.dll

Decompiled 2 weeks 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 BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Groups;
using Guilds;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using PieceManager;
using PortalStations;
using PortalStations.Stations;
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.Callbacks;
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("PortalStations")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("PortalStations")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("E0E2F92E-557C-4A05-9D89-AA92A0BD75C4")]
[assembly: AssemblyFileVersion("1.2.4")]
[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.2.4.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<12174f0c-09c2-49e2-bb20-e9f2b907e228>Embedded]
	internal sealed class <12174f0c-09c2-49e2-bb20-e9f2b907e228>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<12174f0c-09c2-49e2-bb20-e9f2b907e228>Embedded]
	[CompilerGenerated]
	internal sealed class <52a82b40-b23a-499d-b080-7fe0304b9b11>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <52a82b40-b23a-499d-b080-7fe0304b9b11>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <52a82b40-b23a-499d-b080-7fe0304b9b11>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<12174f0c-09c2-49e2-bb20-e9f2b907e228>Embedded]
	[CompilerGenerated]
	internal sealed class <e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace PortalStations
{
	[BepInPlugin("RustyMods.PortalStations", "PortalStations", "1.2.4")]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class PortalStationsPlugin : BaseUnityPlugin
	{
		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)]
		public enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order = null;

			[UsedImplicitly]
			public bool? Browsable = null;

			[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(2)]
			[UsedImplicitly]
			public string Category = null;

			[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(new byte[] { 2, 1 })]
			[UsedImplicitly]
			public Action<ConfigEntryBase> CustomDrawer = null;
		}

		internal const string ModName = "PortalStations";

		internal const string ModVersion = "1.2.4";

		internal const string Author = "RustyMods";

		private const string ModGUID = "RustyMods.PortalStations";

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

		private static readonly string ConfigFileFullPath;

		internal static string ConnectionError;

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

		public static readonly ManualLogSource PortalStationsLogger;

		private static readonly ConfigSync ConfigSync;

		public static PortalStationsPlugin _plugin;

		public static AssetBundle _asset;

		public static GameObject _root;

		public static Texture PlatformMoss;

		public static Texture PlatformNormal;

		private static ConfigEntry<Toggle> _serverConfigLocked;

		public static ConfigEntry<Toggle> _TeleportAnything;

		public static ConfigEntry<string> _DeviceFuel;

		public static ConfigEntry<Toggle> _DeviceUseFuel;

		public static ConfigEntry<int> _DevicePerFuelAmount;

		public static ConfigEntry<int> _DeviceAdditionalDistancePerUpgrade;

		public static ConfigEntry<Toggle> _PortalToPlayers;

		public static ConfigEntry<Toggle> _PortalUseFuel;

		public static ConfigEntry<int> _PortalPerFuelAmount;

		public static ConfigEntry<Toggle> _UsePortalKeys;

		public static ConfigEntry<string> _StationTitle;

		public static ConfigEntry<string> _PortableStationTitle;

		public static ConfigEntry<string> _StationDestinationText;

		public static ConfigEntry<string> _StationCloseText;

		public static ConfigEntry<string> _StationFilterText;

		public static ConfigEntry<string> _StationSetNameText;

		public static ConfigEntry<string> _StationUseText;

		public static ConfigEntry<string> _StationRenameText;

		public static ConfigEntry<string> _NotEnoughFuelText;

		public static ConfigEntry<string> _PublicText;

		public static ConfigEntry<string> _PrivateText;

		public static ConfigEntry<Toggle> _OnlyAdminRename;

		public static ConfigEntry<float> _PortalVolume;

		public static ConfigEntry<float> _PersonalPortalDurabilityDrain;

		public static ConfigEntry<Toggle> _OnlyAdminBuilds;

		public void Awake()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			_plugin = this;
			_asset = GetAssetBundle("portal_station_assets");
			_root = new GameObject("root");
			Object.DontDestroyOnLoad((Object)(object)_root);
			_root.SetActive(false);
			PlatformMoss = _asset.LoadAsset<Texture>("tex_stone_moss");
			PlatformNormal = _asset.LoadAsset<Texture>("normal_portal_platform");
			_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);
			InitPieces();
			InitItems();
			InitConfigs();
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
			SetupWatcher();
			_harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PortalStationsPlugin), "ClonedPieces", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private void InitPieces()
		{
			BuildPiece buildPiece = new BuildPiece("portal_station_assets", "portalstation");
			buildPiece.Name.English("Ancient Portal");
			buildPiece.Description.English("Teleportation portal");
			buildPiece.RequiredItems.Add("Stone", 20, recover: true);
			buildPiece.RequiredItems.Add("SurtlingCore", 2, recover: true);
			buildPiece.RequiredItems.Add("FineWood", 20, recover: true);
			buildPiece.RequiredItems.Add("GreydwarfEye", 10, recover: true);
			buildPiece.Category.Set(BuildPieceCategory.Misc);
			buildPiece.Crafting.Set(PieceManager.CraftingTable.Workbench);
			MaterialReplacer.RegisterGameObjectForMatSwap(((Component)Utils.FindChild(buildPiece.Prefab.transform, "vanilla_effects", (IterativeSearchType)0)).gameObject);
			buildPiece.Prefab.AddComponent<PortalStation>();
			PieceEffectsSetter.PrefabsToSet.Add(buildPiece.Prefab);
			PortalStations.Stations.Stations.PrefabsToSearch.Add(((Object)buildPiece.Prefab).name);
			BuildPiece buildPiece2 = new BuildPiece("portal_station_assets", "portalStationOne");
			buildPiece2.Name.English("Chained Portal");
			buildPiece2.Description.English("Teleportation portal");
			buildPiece2.RequiredItems.Add("Stone", 20, recover: true);
			buildPiece2.RequiredItems.Add("SurtlingCore", 2, recover: true);
			buildPiece2.RequiredItems.Add("FineWood", 20, recover: true);
			buildPiece2.RequiredItems.Add("GreydwarfEye", 10, recover: true);
			buildPiece2.Category.Set(BuildPieceCategory.Misc);
			buildPiece2.Crafting.Set(PieceManager.CraftingTable.Workbench);
			MaterialReplacer.RegisterGameObjectForMatSwap(((Component)Utils.FindChild(buildPiece2.Prefab.transform, "vanilla_effects", (IterativeSearchType)0)).gameObject);
			buildPiece2.Prefab.AddComponent<PortalStation>();
			PieceEffectsSetter.PrefabsToSet.Add(buildPiece2.Prefab);
			PortalStations.Stations.Stations.PrefabsToSearch.Add(((Object)buildPiece2.Prefab).name);
			BuildPiece buildPiece3 = new BuildPiece("portal_station_assets", "portalPlatform");
			buildPiece3.Name.English("Platform Portal");
			buildPiece3.Description.English("Teleportation portal");
			buildPiece3.RequiredItems.Add("Stone", 20, recover: true);
			buildPiece3.RequiredItems.Add("SurtlingCore", 2, recover: true);
			buildPiece3.RequiredItems.Add("FineWood", 20, recover: true);
			buildPiece3.RequiredItems.Add("GreydwarfEye", 10, recover: true);
			buildPiece3.Category.Set(BuildPieceCategory.Misc);
			buildPiece3.Crafting.Set(PieceManager.CraftingTable.Workbench);
			MaterialReplacer.RegisterGameObjectForShaderSwap(((Component)Utils.FindChild(buildPiece3.Prefab.transform, "model", (IterativeSearchType)0)).gameObject, MaterialReplacer.ShaderType.RockShader);
			MaterialReplacer.RegisterGameObjectForMatSwap(((Component)Utils.FindChild(buildPiece3.Prefab.transform, "vanilla_effects", (IterativeSearchType)0)).gameObject);
			buildPiece3.Prefab.AddComponent<PortalStation>();
			PieceEffectsSetter.PrefabsToSet.Add(buildPiece3.Prefab);
			PortalStations.Stations.Stations.PrefabsToSearch.Add(((Object)buildPiece3.Prefab).name);
			BuildPiece buildPiece4 = new BuildPiece("portal_station_assets", "portalStationDoor");
			buildPiece4.Name.English("Gate Portal");
			buildPiece4.Description.English("Teleportation portal");
			buildPiece4.RequiredItems.Add("Stone", 20, recover: true);
			buildPiece4.RequiredItems.Add("SurtlingCore", 2, recover: true);
			buildPiece4.RequiredItems.Add("FineWood", 20, recover: true);
			buildPiece4.RequiredItems.Add("GreydwarfEye", 10, recover: true);
			buildPiece4.Category.Set(BuildPieceCategory.Misc);
			buildPiece4.Crafting.Set(PieceManager.CraftingTable.Workbench);
			MaterialReplacer.RegisterGameObjectForMatSwap(((Component)Utils.FindChild(buildPiece4.Prefab.transform, "model", (IterativeSearchType)0)).gameObject);
			MaterialReplacer.RegisterGameObjectForMatSwap(((Component)Utils.FindChild(buildPiece4.Prefab.transform, "vanilla_effects", (IterativeSearchType)0)).gameObject);
			buildPiece4.Prefab.AddComponent<PortalStation>();
			PieceEffectsSetter.PrefabsToSet.Add(buildPiece4.Prefab);
			PortalStations.Stations.Stations.PrefabsToSearch.Add(((Object)buildPiece4.Prefab).name);
		}

		public static void ClonedPieces(ZNetScene __instance)
		{
			if (Object.op_Implicit((Object)(object)__instance))
			{
				Clone(__instance, "portal_stone", "PortalStation_Stone", "Stone Portal Station");
				Clone(__instance, "portal_wood", "PortalStation_Wood", "Wood Portal Station");
				Clone(__instance, "portal", "PortalStation_Blue", "Portal Station Stone");
				PortalStations.Stations.Stations.InitCoroutine();
			}
		}

		private static void Clone(ZNetScene __instance, string prefabName, string newName, string displayName)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			GameObject prefab = __instance.GetPrefab(prefabName);
			if (!Object.op_Implicit((Object)(object)prefab))
			{
				return;
			}
			GameObject val = Object.Instantiate<GameObject>(prefab, _root.transform, false);
			((Object)val).name = newName;
			TeleportWorld component = val.GetComponent<TeleportWorld>();
			PortalStation portalStation = val.AddComponent<PortalStation>();
			portalStation.m_model = val.GetComponentInChildren<MeshRenderer>();
			portalStation.m_baseColor = component.m_colorTargetfound;
			Object.Destroy((Object)(object)component);
			TeleportWorldTrigger componentInChildren = val.GetComponentInChildren<TeleportWorldTrigger>();
			if (Object.op_Implicit((Object)(object)componentInChildren))
			{
				Object.Destroy((Object)(object)((Component)componentInChildren).gameObject);
			}
			EffectFade componentInChildren2 = val.GetComponentInChildren<EffectFade>();
			if (Object.op_Implicit((Object)(object)componentInChildren2))
			{
				Object.Destroy((Object)(object)componentInChildren2);
			}
			Piece piece = default(Piece);
			if (val.TryGetComponent<Piece>(ref piece))
			{
				ConfigEntry<string> display = _plugin.config(newName, "Display Name", displayName, "Set display name");
				piece.m_name = display.Value;
				display.SettingChanged += [<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (object sender, EventArgs args) =>
				{
					piece.m_name = display.Value;
				};
				ConfigEntry<string> recipe = _plugin.config(newName, "Recipe", "GreydwarfEye:10,FineWood:20,SurtlingCore:2", "Set recipe");
				piece.m_resources = GetRequirements(recipe.Value).ToArray();
				recipe.SettingChanged += [<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (object sender, EventArgs args) =>
				{
					piece.m_resources = GetRequirements(recipe.Value).ToArray();
				};
				PortalStations.Stations.Stations.PrefabsToSearch.Add(((Object)val).name);
				RegisterToScene(val);
				RegisterToHammer(val);
			}
		}

		private static List<Requirement> GetRequirements(string config)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			List<Requirement> list = new List<Requirement>();
			string[] array = config.Split(new char[1] { ',' });
			ItemDrop resItem = default(ItemDrop);
			foreach (string text in array)
			{
				string[] array2 = text.Split(new char[1] { ':' });
				if (array2.Length == 2)
				{
					GameObject prefab = ZNetScene.instance.GetPrefab(array2[0]);
					if (Object.op_Implicit((Object)(object)prefab) && prefab.TryGetComponent<ItemDrop>(ref resItem))
					{
						list.Add(new Requirement
						{
							m_resItem = resItem,
							m_amount = ((!int.TryParse(array2[1], out var result)) ? 1 : result),
							m_recover = true,
							m_amountPerLevel = 1,
							m_extraAmountOnlyOneIngredient = 1
						});
					}
				}
			}
			return list;
		}

		private static void RegisterToHammer(GameObject prefab)
		{
			GameObject prefab2 = ZNetScene.instance.GetPrefab("Hammer");
			ItemDrop val = default(ItemDrop);
			if (Object.op_Implicit((Object)(object)prefab2) && prefab2.TryGetComponent<ItemDrop>(ref val) && !val.m_itemData.m_shared.m_buildPieces.m_pieces.Contains(prefab))
			{
				val.m_itemData.m_shared.m_buildPieces.m_pieces.Add(prefab);
			}
		}

		private static void RegisterToScene(GameObject prefab)
		{
			if (!ZNetScene.instance.m_prefabs.Contains(prefab))
			{
				ZNetScene.instance.m_prefabs.Add(prefab);
			}
			ZNetScene.instance.m_namedPrefabs[StringExtensionMethods.GetStableHashCode(((Object)prefab).name)] = prefab;
		}

		private void InitItems()
		{
			Item item = new Item("portal_station_assets", "item_personalteleportationdevice");
			item.Name.English("Portable Portal");
			item.Description.English("Travel made easy");
			item.Crafting.Add(ItemManager.CraftingTable.Forge, 2);
			item.RequiredItems.Add("SurtlingCore", 3);
			item.RequiredItems.Add("LeatherScraps", 30);
			item.RequiredItems.Add("Iron", 5);
			item.RequiredItems.Add("YmirRemains", 10);
			item.CraftAmount = 1;
			item.RequiredUpgradeItems.Add("SurtlingCore", 2);
			item.RequiredUpgradeItems.Add("LeatherScraps", 5);
			item.RequiredUpgradeItems.Add("Iron", 2);
			item.RequiredUpgradeItems.Add("YmirRemains", 3);
			item.RequiredUpgradeItems.Free = false;
			item.MaximumRequiredStationLevel = 2;
			item.Configurable = Configurability.Recipe;
			MaterialReplacer.RegisterGameObjectForMatSwap(((Component)Utils.FindChild(item.Prefab.transform, "SurtlingCores", (IterativeSearchType)0)).gameObject);
		}

		private void Update()
		{
			PortalStationGUI.UpdateGUI();
		}

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

		private static AssetBundle GetAssetBundle(string fileName)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string name = executingAssembly.GetManifestResourceNames().Single([<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (string str) => str.EndsWith(fileName));
			using Stream stream = executingAssembly.GetManifestResourceStream(name);
			return AssetBundle.LoadFromStream(stream);
		}

		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
			{
				PortalStationsLogger.LogDebug((object)"ReadConfigValues called");
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch
			{
				PortalStationsLogger.LogError((object)("There was an issue loading your " + ConfigFileName));
				PortalStationsLogger.LogError((object)"Please check your config entries for spelling and format!");
			}
		}

		private void InitConfigs()
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Expected O, but got Unknown
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Expected O, but got Unknown
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Expected O, but got Unknown
			_TeleportAnything = config("Settings", "1 - Teleport Anything", Toggle.Off, "If on, portal station allows to teleport without restrictions");
			_DeviceUseFuel = config("Settings", "2 - Portable Portal Use Fuel", Toggle.On, "If on, personal teleportation device uses fuel");
			_DeviceFuel = config("Settings", "3 - Portable Portal Fuel", "Coins", "Set the prefab name of the fuel item required to teleport");
			_DevicePerFuelAmount = config("Settings", "4 - Portable Portal Fuel Distance", 1, new ConfigDescription("Fuel cost to travel, higher value increases range per fuel", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50), Array.Empty<object>()));
			_DeviceAdditionalDistancePerUpgrade = config("Settings", "5 - Portable Portal Upgrade Boost", 1, new ConfigDescription("Cost reduction multiplier per item upgrade level", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50), Array.Empty<object>()));
			_PortalToPlayers = config("Settings", "6 - Portal To Players", Toggle.Off, "If on, portal shows players as destination options");
			_OnlyAdminRename = config("Settings", "7 - Only Admin Renames", Toggle.Off, "If on, only admins with no cost cheat on can rename portals");
			_PortalUseFuel = config("Settings", "8 - Portal Use Fuel", Toggle.Off, "If on, static portals require fuel");
			_PortalPerFuelAmount = config("Settings", "9 - Portal Fuel Distance", 10, new ConfigDescription("Fuel cost per distance", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 101), Array.Empty<object>()));
			_PortalVolume = config("Settings", "8 - Portal Volume", 0.8f, new ConfigDescription("Set the volume of the portal effects", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()), synchronizedSetting: false);
			_PersonalPortalDurabilityDrain = config("Settings", "9 - Portable Portal Durability Drain", 10f, new ConfigDescription("Set the durability drain per portable portal usage", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			_UsePortalKeys = config("Teleport Keys", "0 - Use Keys", Toggle.Off, "If on, portal checks keys to portal player if carrying ores, dragon eggs, etc...");
			_StationTitle = config("Localization", "0 - Station Title", "Portal Station", "Station name on user interface", synchronizedSetting: false);
			_PortableStationTitle = config("Localization", "1 - Portable Station Title", "Teleporter", "Portable Portal name on user interface", synchronizedSetting: false);
			_StationDestinationText = config("Localization", "2 - Destination Text", "Destinations", "Text display for destinations on user interface", synchronizedSetting: false);
			_StationCloseText = config("Localization", "3 - Close Text", "Close", "Text display for close button on user interface", synchronizedSetting: false);
			_StationFilterText = config("Localization", "4 - Filter Text", "Filter", "Text display for filter on user interface", synchronizedSetting: false);
			_StationRenameText = config("Localization", "5 - Rename Text", "Rename Portal", "Text display on pop up to rename portal", synchronizedSetting: false);
			_StationUseText = config("Localization", "6 - Use Text", "Use portal", "Text display when hover over station to use portal", synchronizedSetting: false);
			_StationSetNameText = config("Localization", "7 - Set Name Text", "Set Name", "Text display when hover over station to rename", synchronizedSetting: false);
			_NotEnoughFuelText = config("Localization", "8 - Not Enough Fuel", "Not Enough Fuel", "Text that appears on portable portal GUI if user does not have enough fuel", synchronizedSetting: false);
			_PublicText = config("Localization", "9 - Public Text", "Public", "Text display for public toggle", synchronizedSetting: false);
			_PrivateText = config("Localization", "9 - Private Text", "Private", "Text display for private toggle", synchronizedSetting: false);
			_OnlyAdminBuilds = config("General", "Only Admin Can Build", Toggle.Off, "Set visibility of portals in build menu");
		}

		private ConfigEntry<T> config<[<52a82b40-b23a-499d-b080-7fe0304b9b11>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<[<52a82b40-b23a-499d-b080-7fe0304b9b11>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 PortalStationsPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			ConnectionError = "";
			PortalStationsLogger = Logger.CreateLogSource("PortalStations");
			ConfigSync = new ConfigSync("RustyMods.PortalStations")
			{
				DisplayName = "PortalStations",
				CurrentVersion = "1.2.4",
				MinimumRequiredVersion = "1.2.4"
			};
			_plugin = null;
			_asset = null;
			_root = null;
			PlatformMoss = null;
			PlatformNormal = null;
			_serverConfigLocked = null;
			_TeleportAnything = null;
			_DeviceFuel = null;
			_DeviceUseFuel = null;
			_DevicePerFuelAmount = null;
			_DeviceAdditionalDistancePerUpgrade = null;
			_PortalToPlayers = null;
			_PortalUseFuel = null;
			_PortalPerFuelAmount = null;
			_UsePortalKeys = null;
			_StationTitle = null;
			_PortableStationTitle = null;
			_StationDestinationText = null;
			_StationCloseText = null;
			_StationFilterText = null;
			_StationSetNameText = null;
			_StationUseText = null;
			_StationRenameText = null;
			_NotEnoughFuelText = null;
			_PublicText = null;
			_PrivateText = null;
			_OnlyAdminRename = null;
			_PortalVolume = null;
			_PersonalPortalDurabilityDrain = null;
			_OnlyAdminBuilds = null;
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	public static class RegisterAndCheckVersion
	{
		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>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
			PortalStationsPlugin.PortalStationsLogger.LogDebug((object)"Registering version RPC handler");
			peer.m_rpc.Register<ZPackage>("PortalStations_VersionCheck", (Action<ZRpc, ZPackage>)RpcHandlers.RPC_PortalStations_Version);
			PortalStationsPlugin.PortalStationsLogger.LogInfo((object)"Invoking version check");
			ZPackage val = new ZPackage();
			val.Write("1.2.4");
			val.Write(RpcHandlers.ComputeHashForMod().Replace("-", ""));
			peer.m_rpc.Invoke("PortalStations_VersionCheck", new object[1] { val });
		}
	}
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>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;
			}
			PortalStationsPlugin.PortalStationsLogger.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(), "PortalStationsRequestAdminSync", new object[1] { (object)new ZPackage() });
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
	public class ShowConnectionError
	{
		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>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" + PortalStationsPlugin.ConnectionError;
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "Disconnect")]
	public static class RemoveDisconnectedPeerFromVerified
	{
		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			if (__instance.IsServer())
			{
				PortalStationsPlugin.PortalStationsLogger.LogInfo((object)("Peer (" + peer.m_rpc.m_socket.GetHostName() + ") disconnected, removing from validated list"));
				RpcHandlers.ValidatedPeers.Remove(peer.m_rpc);
			}
		}
	}
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	public static class RpcHandlers
	{
		public static readonly List<ZRpc> ValidatedPeers = new List<ZRpc>();

		public static void RPC_PortalStations_Version(ZRpc rpc, ZPackage pkg)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = ComputeHashForMod().Replace("-", "");
			PortalStationsPlugin.PortalStationsLogger.LogInfo((object)("Version check, local: 1.2.4,  remote: " + text));
			if (text2 != text3 || text != "1.2.4")
			{
				PortalStationsPlugin.ConnectionError = "PortalStations Installed: 1.2.4 " + text3 + "\n Needed: " + text + " " + text2;
				if (ZNet.instance.IsServer())
				{
					PortalStationsPlugin.PortalStationsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting..."));
					rpc.Invoke("Error", new object[1] { 3 });
				}
			}
			else if (!ZNet.instance.IsServer())
			{
				PortalStationsPlugin.PortalStationsLogger.LogInfo((object)"Received same version from server!");
			}
			else
			{
				PortalStationsPlugin.PortalStationsLogger.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 PortalStations.Stations
{
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	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 = PortalStationsPlugin._StationFilterText.Value;
			((Component)Utils.FindChild(PortalGUI.transform, "$text_destinations", (IterativeSearchType)0)).GetComponent<Text>().text = PortalStationsPlugin._StationDestinationText.Value;
			m_title.text = PortalStationsPlugin._StationTitle.Value;
			m_public_text.text = PortalStationsPlugin._PublicText.Value;
		}

		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 = PortalStationsPlugin._StationCloseText.Value;
			}
		}

		private static void SetVariables(InventoryGui instance)
		{
			PortalGUI = Object.Instantiate<GameObject>(PortalStationsPlugin._asset.LoadAsset<GameObject>("portalstation_gui"), ((Component)instance).transform, false);
			PortalGUI_Item = Object.Instantiate<GameObject>(PortalStationsPlugin._asset.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, [<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(2)] Font font)
		{
			foreach (Text val in array)
			{
				val.font = font;
			}
		}

		[return: <52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(2)]
		private static Font GetFont(string name)
		{
			return ((IEnumerable<Font>)Resources.FindObjectsOfTypeAll<Font>()).FirstOrDefault((Func<Font, bool>)([<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (Font x) => ((Object)x).name == name));
		}
	}
	public static class Patches
	{
		[HarmonyPatch(typeof(InventoryGui), "Awake")]
		private static class AttachPortalStationGUI
		{
			[<e3bdd204-0f1c-4e12-899f-2c56d5387028>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
		{
			[<e3bdd204-0f1c-4e12-899f-2c56d5387028>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);
				}
			}
		}

		[HarmonyPatch(typeof(PieceTable), "GetPiecesInSelectedCategory")]
		private static class PieceTableGetPiecesPatch
		{
			[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
			private static void Postfix(ref List<Piece> __result)
			{
				if (PortalStationsPlugin._OnlyAdminBuilds.Value == PortalStationsPlugin.Toggle.Off || Player.m_localPlayer.NoCostCheat())
				{
					return;
				}
				List<Piece> list = new List<Piece>();
				foreach (Piece item in __result)
				{
					if (!PieceEffectsSetter.PrefabsToSet.Contains(((Component)item).gameObject))
					{
						list.Add(item);
					}
				}
				__result = list;
			}
		}

		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
			{
				PortalStationsPlugin.PortalStationsLogger.LogDebug((object)"Failed to save favorite portals");
			}
		}
	}
	public static class PersonalTeleportationDevice
	{
		[HarmonyPatch(typeof(Humanoid), "UseItem")]
		private static class UsePersonalPortalDevice
		{
			[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
			private static bool Prefix(Humanoid __instance, ItemData item)
			{
				if (item.m_shared.m_name != "$item_personal_teleportation_device")
				{
					return true;
				}
				UseItem(__instance, item);
				return false;
			}
		}

		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
		private static void UseItem(Humanoid user, ItemData item)
		{
			if (!(item.m_durability < item.m_shared.m_durabilityDrain))
			{
				item.m_durability -= PortalStationsPlugin._PersonalPortalDurabilityDrain.Value;
				PortalStationGUI.ShowPortalGUI(user, item);
			}
		}
	}
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	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";

		private const float use_distance = 5f;

		private ZNetView _znv = null;

		public float m_fadeDuration = 1f;

		public ParticleSystem[] m_particles = null;

		public Light m_light = null;

		public AudioSource m_audioSource = null;

		[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(2)]
		public Material m_rune;

		[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(2)]
		public MeshRenderer m_model;

		private bool m_vanilla;

		public Color m_baseColor;

		public float m_lightBaseIntensity;

		public bool m_active = true;

		public float m_intensity;

		private void Awake()
		{
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			Transform val = Utils.FindChild(((Component)this).transform, "Portal Effects", (IterativeSearchType)0);
			if (!Object.op_Implicit((Object)(object)val))
			{
				val = Utils.FindChild(((Component)this).transform, "_target_found_red", (IterativeSearchType)0);
				if (!Object.op_Implicit((Object)(object)val))
				{
					val = Utils.FindChild(((Component)this).transform, "_target_found", (IterativeSearchType)0);
					if (!Object.op_Implicit((Object)(object)val))
					{
						return;
					}
				}
			}
			GameObject gameObject = ((Component)val).gameObject;
			m_particles = gameObject.GetComponentsInChildren<ParticleSystem>();
			m_light = gameObject.GetComponentInChildren<Light>();
			m_audioSource = gameObject.GetComponentInChildren<AudioSource>();
			Transform val2 = Utils.FindChild(((Component)this).transform, "emissive", (IterativeSearchType)0);
			if (Object.op_Implicit((Object)(object)val2))
			{
				m_rune = ((Renderer)((Component)val2).GetComponent<MeshRenderer>()).material;
				m_baseColor = m_rune.color;
				m_rune.color = new Color(m_baseColor.r, m_baseColor.g, m_baseColor.b, 0f);
			}
			else if ((Object)(object)m_model != (Object)null)
			{
				m_rune = ((Renderer)m_model).material;
				m_vanilla = true;
			}
			if (Object.op_Implicit((Object)(object)m_light))
			{
				m_lightBaseIntensity = m_light.intensity;
				m_light.intensity = 0f;
			}
			if (Object.op_Implicit((Object)(object)m_audioSource))
			{
				m_audioSource.volume = 0f;
			}
			SetActive(active: false);
			_znv = ((Component)this).GetComponent<ZNetView>();
			if (_znv.IsValid())
			{
				_znv.Register<string>("RPC_SetStationName", (Action<long, string>)RPC_SetStationName);
				_znv.Register<bool>("RPC_SetStationNetwork", (Action<long, bool>)RPC_SetStationNetwork);
				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");
				}
			}
		}

		public void Update()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			Player closestPlayer = Player.GetClosestPlayer(((Component)this).transform.position, 5f);
			bool active = Object.op_Implicit((Object)(object)closestPlayer) && Teleportation.IsTeleportable(closestPlayer);
			SetActive(active);
			m_intensity = Mathf.MoveTowards(m_intensity, m_active ? 1f : 0f, Time.deltaTime / m_fadeDuration);
			if (Object.op_Implicit((Object)(object)m_light))
			{
				m_light.intensity = m_intensity * m_lightBaseIntensity;
				((Behaviour)m_light).enabled = (double)m_light.intensity > 0.0;
			}
			if (Object.op_Implicit((Object)(object)m_audioSource))
			{
				m_audioSource.volume = m_intensity * PortalStationsPlugin._PortalVolume.Value;
			}
			if (m_rune != null)
			{
				if (m_vanilla)
				{
					m_rune.SetColor("_EmissionColor", Color.Lerp(Color.black, m_baseColor, m_intensity));
				}
				else
				{
					m_rune.color = new Color(m_baseColor.r, m_baseColor.g, m_baseColor.b, m_intensity * 1f);
				}
			}
		}

		public void SetActive(bool active)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (m_active != active)
			{
				m_active = active;
				ParticleSystem[] particles = m_particles;
				foreach (ParticleSystem val in particles)
				{
					EmissionModule emission = val.emission;
					((EmissionModule)(ref emission)).enabled = active;
				}
			}
		}

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

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			if (hold)
			{
				return false;
			}
			if (alt)
			{
				if (PortalStationsPlugin._OnlyAdminRename.Value == PortalStationsPlugin.Toggle.On && !Player.m_localPlayer.NoCostCheat())
				{
					return false;
				}
				TextInput.instance.RequestText((TextReceiver)(object)this, PortalStationsPlugin._StationRenameText.Value, 40);
				return true;
			}
			return InUseDistance(user) && 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()
		{
			if (PortalStationsPlugin._OnlyAdminRename.Value == PortalStationsPlugin.Toggle.On && !Player.m_localPlayer.NoCostCheat())
			{
				return _znv.GetZDO().GetString(_prop_station_name, "") + "\n" + Localization.instance.Localize("[<color=yellow><b>$KEY_Use</b></color>] " + PortalStationsPlugin._StationUseText.Value);
			}
			return _znv.GetZDO().GetString(_prop_station_name, "") + "\n" + Localization.instance.Localize("[<color=yellow><b>$KEY_Use</b></color>] " + PortalStationsPlugin._StationUseText.Value) + "\n" + Localization.instance.Localize("[<color=yellow><b>L.Shift + $KEY_Use</b></color>] " + PortalStationsPlugin._StationSetNameText.Value);
		}

		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 });
			}
		}
	}
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	public static class PortalStationGUI
	{
		[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(2)]
		private static ZNetView currentPortalStation;

		[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(2)]
		private static ItemData currentDevice;

		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([<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (ZDO zdo) => zdo.GetString(PortalStation._prop_station_name, "")).ToList());
		}

		public static void OnFilterInput(string input)
		{
			if (currentDevice != null)
			{
				GetDestinations((Humanoid)(object)Player.m_localPlayer, currentDevice, 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 = (flag ? PortalStationsPlugin._PublicText.Value : PortalStationsPlugin._PrivateText.Value);
				}
			}
		}

		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) || !znv.IsValid())
			{
				return false;
			}
			znv.ClaimOwnership();
			LoadUI.PortalGUI.SetActive(true);
			currentPortalStation = znv;
			currentDevice = null;
			GetDestinations(znv);
			LoadUI.m_title.text = PortalStationsPlugin._StationTitle.Value;
			bool @bool = znv.GetZDO().GetBool(PortalStation._prop_station_code, false);
			LoadUI.ToggleOn.SetActive(@bool);
			LoadUI.ToggleOff.SetActive(!@bool);
			LoadUI.m_public_text.text = (@bool ? PortalStationsPlugin._PublicText.Value : PortalStationsPlugin._PrivateText.Value);
			SetToggleVisibility(toggle: true);
			return true;
		}

		public static void ShowPortalGUI(Humanoid user, ItemData item)
		{
			LoadUI.m_title.text = PortalStationsPlugin._PortableStationTitle.Value;
			LoadUI.PortalGUI.SetActive(true);
			SetToggleVisibility(toggle: false);
			GetDestinations(user, item);
			currentDevice = item;
			currentPortalStation = null;
		}

		private static void GetDestinations(Humanoid user, ItemData deviceData, string filter = "")
		{
			DestroyDestinations();
			ItemDrop fuelItem = GetFuelItem();
			if ((Object)(object)fuelItem == (Object)null)
			{
				return;
			}
			HashSet<ZDO> source = FindDestinations();
			foreach (ZDO item in source.Where([<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (ZDO x) => Favorites.Contains(x.GetString(PortalStation._prop_station_name, ""))))
			{
				CreateDestination(item, user, deviceData, filter, fuelItem, isFavorite: true);
			}
			foreach (ZDO item2 in source.Where([<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (ZDO x) => !Favorites.Contains(x.GetString(PortalStation._prop_station_name, ""))))
			{
				CreateDestination(item2, user, deviceData, filter, fuelItem, isFavorite: false);
			}
			if (PortalStationsPlugin._PortalToPlayers.Value == PortalStationsPlugin.Toggle.Off)
			{
				return;
			}
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				CreateDestination(allPlayer, user, deviceData, filter, fuelItem);
			}
		}

		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(2)]
		private static ItemDrop GetFuelItem()
		{
			if (!Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return null;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(PortalStationsPlugin._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([<e3bdd204-0f1c-4e12-899f-2c56d5387028>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([<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (ZDO x) => !Favorites.Contains(x.GetString(PortalStation._prop_station_name, ""))))
			{
				GetDestination(item2, znv, filter, fuelItem, isFavorite: false);
			}
			if (PortalStationsPlugin._PortalToPlayers.Value == PortalStationsPlugin.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 CreateDestination(ZDO zdo, Humanoid user, ItemData device, string filter, ItemDrop fuel, bool isFavorite)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Expected O, but got Unknown
			if (!zdo.IsValid() || zdo.m_uid == ((Character)user).GetZDOID())
			{
				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(device, Vector3.Distance(zdo.GetPosition(), ((Component)user).transform.position));
				GameObject val = Object.Instantiate<GameObject>(LoadUI.PortalGUI_Item, (Transform)(object)LoadUI.ItemListRoot);
				((Component)Utils.FindChild(val.transform, "$part_StationName", (IterativeSearchType)0)).GetComponent<Text>().text = @string;
				((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 (PortalStationsPlugin._DeviceUseFuel.Value == PortalStationsPlugin.Toggle.Off)
				{
					((Component)Utils.FindChild(val.transform, "$part_FuelElement", (IterativeSearchType)0)).gameObject.SetActive(false);
				}
				Transform val2 = Utils.FindChild(val.transform, "$part_FavoriteButton", (IterativeSearchType)0);
				((Graphic)((Component)val2.GetChild(0)).GetComponent<Image>()).color = (isFavorite ? Color.white : Color.black);
				((UnityEvent)((Component)val2).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					SetFavorite(zdo);
					GetDestinations(user, device, filter);
				});
				((UnityEvent)((Component)Utils.FindChild(val.transform, "$part_TeleportButton", (IterativeSearchType)0)).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					TeleportWithCost(zdo, cost, fuel);
				});
			}
		}

		private static void CreateDestination(Player player, Humanoid user, ItemData device, string filter, ItemDrop fuel)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Expected O, but got Unknown
			if (((Character)player).GetZDOID() == ((Character)user).GetZDOID())
			{
				return;
			}
			string playerName = player.GetPlayerName();
			if (!Utility.IsNullOrWhiteSpace(playerName) && (Utility.IsNullOrWhiteSpace(filter) || playerName.ToLower().Contains(filter.ToLower())))
			{
				int cost = Teleportation.CalculateFuelCost(device, Vector3.Distance(((Component)player).transform.position, ((Component)user).transform.position));
				GameObject val = Object.Instantiate<GameObject>(LoadUI.PortalGUI_Item, (Transform)(object)LoadUI.ItemListRoot);
				((Component)Utils.FindChild(val.transform, "$part_StationName", (IterativeSearchType)0)).GetComponent<Text>().text = playerName;
				((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 (PortalStationsPlugin._PortalUseFuel.Value == PortalStationsPlugin.Toggle.Off)
				{
					((Component)Utils.FindChild(val.transform, "$part_FuelElement", (IterativeSearchType)0)).gameObject.SetActive(false);
				}
				Transform val2 = Utils.FindChild(val.transform, "$part_FavoriteButton", (IterativeSearchType)0);
				((Component)val2).gameObject.SetActive(false);
				((Graphic)((Component)val2.GetChild(0)).GetComponent<Image>()).color = Color.black;
				((Selectable)((Component)val2).GetComponent<Button>()).interactable = false;
				((UnityEvent)((Component)Utils.FindChild(val.transform, "$part_TeleportButton", (IterativeSearchType)0)).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					TeleportWithCost(((Component)player).transform.position, cost, fuel);
				});
			}
		}

		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 Groups.API.FindGroupMemberByPlayerId(creator).HasValue;
		}

		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(2)]
		private static bool isInGuild(Player creator)
		{
			Guild ownGuild = Guilds.API.GetOwnGuild();
			if (ownGuild == null || (Object)(object)creator == (Object)null)
			{
				return false;
			}
			return ownGuild.Members.Any<KeyValuePair<Guilds.PlayerReference, GuildMember>>([<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (KeyValuePair<Guilds.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 (PortalStationsPlugin._PortalUseFuel.Value == PortalStationsPlugin.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_008d: 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_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			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, PortalStationsPlugin._NotEnoughFuelText.Value, 0, (Sprite)null);
				return;
			}
			if (!Player.m_localPlayer.NoCostCheat())
			{
				Teleportation.ConsumeFuel(Player.m_localPlayer, fuel, cost);
			}
			((Character)Player.m_localPlayer).TeleportTo(location + new Vector3(0f, 1f, 0f), ((Component)Player.m_localPlayer).transform.rotation, true);
			HidePortalGUI();
		}

		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();
			}
		}
	}
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	public static class PieceEffectsSetter
	{
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)]
		private static class ZNetSceneAwakePatch
		{
			[<e3bdd204-0f1c-4e12-899f-2c56d5387028>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");
				AddSFX(__instance, item);
			}
		}

		private static void AddSFX(ZNetScene scene, GameObject prefab)
		{
			//IL_0155: 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.volume = PortalStationsPlugin._PortalVolume.Value;
					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;
			}
		}
	}
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	public static class Stations
	{
		private static readonly List<ZDO> TempZDOs = new List<ZDO>();

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

		public static void InitCoroutine()
		{
			((MonoBehaviour)PortalStationsPlugin._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);
			}
		}
	}
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	public static class Teleportation
	{
		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		[HarmonyPriority(0)]
		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)]
		private static class CreateConfigsForRestrictiveItems
		{
			[<e3bdd204-0f1c-4e12-899f-2c56d5387028>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 = PortalStationsPlugin._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 (PortalStationsPlugin._TeleportAnything.Value == PortalStationsPlugin.Toggle.On)
			{
				return true;
			}
			if (!((Humanoid)player).IsTeleportable())
			{
				return PortalStationsPlugin._UsePortalKeys.Value == PortalStationsPlugin.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(ItemData deviceData, float distance)
		{
			if (PortalStationsPlugin._DeviceUseFuel.Value == PortalStationsPlugin.Toggle.Off)
			{
				return 0;
			}
			float num = PortalStationsPlugin._DevicePerFuelAmount.Value + Math.Max(0, deviceData.m_quality - 1) * PortalStationsPlugin._DeviceAdditionalDistancePerUpgrade.Value;
			return Mathf.Max(1, Mathf.CeilToInt(distance / 2f / num));
		}

		public static int CalculateFuelCost(float distance)
		{
			return (PortalStationsPlugin._PortalUseFuel.Value != 0) ? Mathf.Max(1, Mathf.CeilToInt(distance / 2f) / PortalStationsPlugin._PortalPerFuelAmount.Value) : 0;
		}
	}
}
namespace PieceManager
{
	[PublicAPI]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	public static class MaterialReplacer
	{
		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>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([<e3bdd204-0f1c-4e12-899f-2c56d5387028>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);
						if (shaderType == ShaderType.RockShader && ((Object)go.transform.parent).name == "portalPlatform")
						{
							val2.SetTexture("_MossTex", PortalStationsPlugin.PlatformMoss);
							val2.SetFloat("_MossTransition", 0.9f);
							val2.SetFloat("_MossBlend", 0.1f);
							val2.SetFloat("_MossNormal", 0.263f);
							val2.SetTexture("_BumpMap", PortalStationsPlugin.PlatformNormal);
							val2.SetFloat("_AddSnow", 1f);
							val2.SetFloat("_AddRain", 1f);
							val2.SetFloat("_TriplanarScale", 1f);
						}
					}
				}
			}
		}

		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,
		[InternalName("piece_preptable")]
		FoodPreparationTable,
		[InternalName("piece_MeadCauldron")]
		MeadKetill,
		Custom
	}
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	public class InternalName : Attribute
	{
		public readonly string internalName;

		public InternalName(string internalName)
		{
			this.internalName = internalName;
		}
	}
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[PublicAPI]
	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;

		[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(2)]
		public string custom;
	}
	[PublicAPI]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>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;

		[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(2)]
		public string custom;
	}
	[PublicAPI]
	public enum BuildPieceCategory
	{
		Misc = 0,
		Crafting = 1,
		BuildingWorkbench = 2,
		BuildingStonecutter = 3,
		Furniture = 4,
		All = 100,
		Custom = 99
	}
	[PublicAPI]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	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
	{
		[<52a82b40-b23a-499d-b080-7fe0304b9b11>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;
	}
	[PublicAPI]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	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;
		}
	}
	[PublicAPI]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	public class PieceTool
	{
		public readonly HashSet<string> Tools = new HashSet<string>();

		public void Add(string tool)
		{
			Tools.Add(tool);
		}
	}
	[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(1)]
	[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(0)]
	[PublicAPI]
	public class BuildPiece
	{
		[<52a82b40-b23a-499d-b080-7fe0304b9b11>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;
		}

		[<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(2)]
			public string Category;

			[<52a82b40-b23a-499d-b080-7fe0304b9b11>Nullable(new byte[] { 2, 1 })]
			[UsedImplicitly]
			public Action<ConfigEntryBase> CustomDrawer;
		}

		[<52a82b40-b23a-499d-b080-7fe0304b9b11>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([<e3bdd204-0f1c-4e12-899f-2c56d5387028>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([<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}:{r.recover}"));
			}

			[return: <52a82b40-b23a-499d-b080-7fe0304b9b11>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>)([<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (Requirement r) => r.itemName), (Func<Requirement, Requirement>)([<e3bdd204-0f1c-4e12-899f-2c56d5387028>NullableContext(0)] (Requirement r) =>
				{
					//IL_000d: Unknown result type (might be due