Decompiled source of Wayshrine v1.1.2

AzuWayshrine.dll

Decompiled a year ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using PieceManager;
using ServerSync;
using TMPro;
using UnityEngine;
using Wayshrine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AzuWayshrine")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("AzuWayshrine")]
[assembly: AssemblyCopyright("Copyright © Azumatt 2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e76c0c3d-6f23-4b5b-8a13-9c4565d4063f")]
[assembly: AssemblyFileVersion("1.1.2")]
[assembly: AssemblyCompany("Azumatt")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.2.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<e78f24b2-865b-4b19-b581-664b6b6a1ceb>Embedded]
	internal sealed class <e78f24b2-865b-4b19-b581-664b6b6a1ceb>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<e78f24b2-865b-4b19-b581-664b6b6a1ceb>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <70a37419-71ab-4d38-8b06-13d69148464f>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <70a37419-71ab-4d38-8b06-13d69148464f>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <70a37419-71ab-4d38-8b06-13d69148464f>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<e78f24b2-865b-4b19-b581-664b6b6a1ceb>Embedded]
	[CompilerGenerated]
	internal sealed class <5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(0)]
[HarmonyPatch]
[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
public class WayEntryDetector : MonoBehaviour
{
	public CapsuleCollider m_wayTELEPORT;

	private void OnTriggerEnter(Collider collider)
	{
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_0173: Unknown result type (might be due to invalid IL or missing references)
		//IL_016b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_017d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a5: 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_01ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: 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_0110: Unknown result type (might be due to invalid IL or missing references)
		Player component = ((Component)collider).GetComponent<Player>();
		if ((Object)(object)component == (Object)null || (Object)(object)Player.m_localPlayer != (Object)(object)component)
		{
			return;
		}
		Player localPlayer = Player.m_localPlayer;
		PlayerProfile playerProfile = Game.instance.GetPlayerProfile();
		if (!((Humanoid)Player.m_localPlayer).IsTeleportable() && !WayshrinePlugin.Teleportable.Value)
		{
			((Character)Player.m_localPlayer).Message((MessageType)2, "$msg_noteleport", 0, (Sprite)null);
			return;
		}
		if (!MinimapPatches.CheckTeleportCost())
		{
			((Character)Player.m_localPlayer).Message((MessageType)2, $"$wayshrine_cost_error : {WayshrinePlugin.ChargeItemAmount.Value} {MinimapPatches._itemName}", 0, (Sprite)null);
			return;
		}
		ConfigEntry<bool> originalFunc = WayshrinePlugin.OriginalFunc;
		if (originalFunc != null && originalFunc.Value)
		{
			GameObject prefab = ZNetScene.instance.GetPrefab("fx_dragon_land");
			GameObject prefab2 = ZNetScene.instance.GetPrefab("vfx_bifrost");
			ZNetScene.instance.GetPrefab("sfx_thunder");
			if (!object.Equals(prefab, null) && !object.Equals(prefab2, null))
			{
				originalFunc = WayshrinePlugin.DisableBifrostEffect;
				if (originalFunc != null && !originalFunc.Value)
				{
					Vector3 position = ((Component)Player.m_localPlayer).transform.position;
					Object.Instantiate<GameObject>(prefab, position, Quaternion.identity);
					try
					{
						prefab2.GetComponentInChildren<AudioSource>().outputAudioMixerGroup = AudioMan.instance.m_ambientMixer;
					}
					catch
					{
						Debug.LogError((object)"AzuWayshrine: AudioMan.instance.m_ambientMixer could not be assigned on outputAudioMixerGroup of vfx_bifrost");
					}
					Object.Instantiate<GameObject>(prefab2, position, Quaternion.identity);
				}
			}
			((Character)localPlayer).Message((MessageType)2, Util.GetLocalized("$activated_heimdall"), 0, (Sprite)null);
			Vector3 val = (playerProfile.HaveCustomSpawnPoint() ? playerProfile.GetCustomSpawnPoint() : playerProfile.GetHomePoint());
			((Character)localPlayer).TeleportTo(val, Quaternion.identity, false);
			((Character)localPlayer).m_lastGroundTouch = 0f;
		}
		MinimapPatches.IsHeimdallMode = true;
		Minimap.instance.ShowPointOnMap(((Component)this).transform.position);
		foreach (KeyValuePair<Vector3, WayshrineCustomBehaviour.WayshrineInfo> wayshrine in WayshrineCustomBehaviour.Wayshrines)
		{
			WayshrineCustomBehaviour component2 = wayshrine.Value.Prefab.GetComponent<WayshrineCustomBehaviour>();
			WayshrineCustomBehaviour.pins.Add(Minimap.instance.AddPin(wayshrine.Key, component2.pinType, Util.GetLocalized(wayshrine.Value.Prefab.GetComponent<Piece>().m_name), false, false, 0L, ""));
		}
	}

	private void OnTriggerExit(Collider collider)
	{
	}
}
namespace PieceManager
{
	[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
	[PublicAPI]
	[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(0)]
	public static class MaterialReplacer
	{
		[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(0)]
		public enum ShaderType
		{
			PieceShader,
			VegetationShader,
			RockShader,
			RugShader,
			GrassShader,
			CustomCreature,
			UseUnityShader
		}

		private static Dictionary<GameObject, bool> _objectToSwap;

		internal static Dictionary<string, Material> originalMaterials;

		private static Dictionary<GameObject, ShaderType> _objectsForShaderReplace;

		private static bool hasRun;

		static MaterialReplacer()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			originalMaterials = new Dictionary<string, Material>();
			_objectToSwap = new Dictionary<GameObject, bool>();
			_objectsForShaderReplace = new Dictionary<GameObject, ShaderType>();
			new Harmony("org.bepinex.helpers.PieceManager").Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZoneSystem), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(MaterialReplacer), "ReplaceAllMaterialsWithOriginal", (Type[])null, (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()
		{
			if (hasRun)
			{
				return;
			}
			if (originalMaterials.Count <= 0)
			{
				GetAllMaterials();
			}
			foreach (Renderer item in _objectToSwap.SelectMany([<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(0)] (KeyValuePair<GameObject, bool> gameObject) => gameObject.Key.GetComponentsInChildren<Renderer>(true)))
			{
				_objectToSwap.TryGetValue(((Component)item).gameObject, out var value);
				Material[] array = (Material[])(object)new Material[item.sharedMaterials.Length];
				int num = 0;
				Material[] sharedMaterials = item.sharedMaterials;
				foreach (Material val in sharedMaterials)
				{
					string text = (value ? "JVLmock_" : "_REPLACE_");
					if (!((Object)val).name.StartsWith(text, StringComparison.Ordinal))
					{
						continue;
					}
					string text2 = ((Object)item.material).name.Replace(" (Instance)", string.Empty).Replace(text, "");
					string text3 = ((Object)val).name.Replace(" (Instance)", string.Empty).Replace(text, "");
					if (originalMaterials.ContainsKey(text3))
					{
						if (num <= item.materials.Length)
						{
							array[num] = originalMaterials[text3];
						}
					}
					else
					{
						Debug.LogWarning((object)("No suitable material found to replace: " + text3));
						originalMaterials[text3] = array[num];
					}
					if (originalMaterials.ContainsKey(text2))
					{
						item.material = originalMaterials[text2];
					}
					else
					{
						Debug.LogWarning((object)("No suitable material found to replace: " + text2));
						originalMaterials[text2] = item.material;
					}
					num++;
				}
				item.materials = array;
				item.sharedMaterials = array;
			}
			foreach (Renderer item2 in _objectsForShaderReplace.SelectMany([<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(0)] (KeyValuePair<GameObject, ShaderType> gameObject) => gameObject.Key.GetComponentsInChildren<Renderer>(true)))
			{
				_objectsForShaderReplace.TryGetValue(((Component)((Component)item2).gameObject.transform.root).gameObject, out var value2);
				if ((Object)(object)item2 == (Object)null)
				{
					continue;
				}
				Material[] sharedMaterials = item2.sharedMaterials;
				foreach (Material val2 in sharedMaterials)
				{
					if ((Object)(object)val2 == (Object)null)
					{
						continue;
					}
					string name = ((Object)val2.shader).name;
					switch (value2)
					{
					case ShaderType.PieceShader:
						val2.shader = Shader.Find("Custom/Piece");
						break;
					case ShaderType.VegetationShader:
						val2.shader = Shader.Find("Custom/Vegetation");
						break;
					case ShaderType.RockShader:
						val2.shader = Shader.Find("Custom/StaticRock");
						break;
					case ShaderType.RugShader:
						val2.shader = Shader.Find("Custom/Rug");
						break;
					case ShaderType.GrassShader:
						val2.shader = Shader.Find("Custom/Grass");
						break;
					case ShaderType.CustomCreature:
						val2.shader = Shader.Find("Custom/Creature");
						break;
					case ShaderType.UseUnityShader:
						if ((Object)(object)Shader.Find(name) != (Object)null)
						{
							val2.shader = Shader.Find(name);
						}
						break;
					default:
						val2.shader = Shader.Find("ToonDeferredShading2017");
						break;
					}
				}
			}
			hasRun = true;
		}
	}
}
namespace Wayshrine
{
	[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
	[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(0)]
	public static class Assets
	{
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(0)]
		public static class Wayshrine_ZNetScene_Awake_Patch
		{
			[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
			public static bool Prefix(ZNetScene __instance)
			{
				if (!AssetsLoaded)
				{
					LoadAssets();
				}
				foreach (GameObject wayshrines in wayshrinesList)
				{
					__instance.m_prefabs.Add(wayshrines);
				}
				__instance.m_prefabs.Add(vfx_bifrost);
				WayshrinePlugin.waylogger.LogDebug((object)"Loading the prefabs");
				return true;
			}
		}

		[HarmonyPatch(typeof(ZoneSystem), "SetupLocations")]
		[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(0)]
		private static class ZoneSystemSetupLocationsPatch
		{
			private static readonly Dictionary<string, Biome> biomeMapping = new Dictionary<string, Biome>
			{
				{
					"Frost",
					(Biome)64
				},
				{
					"Ashland",
					(Biome)32
				},
				{
					"Plains",
					(Biome)16
				},
				{
					"Wayshrine",
					(Biome)8
				},
				{
					"Skull_2",
					(Biome)512
				}
			};

			private static void Prefix(ZoneSystem __instance)
			{
				//IL_0019: 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_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
				foreach (GameObject wayshrines in wayshrinesList)
				{
					Biome biome = (Biome)2;
					foreach (KeyValuePair<string, Biome> item in biomeMapping)
					{
						if (((Object)wayshrines).name.Contains(item.Key))
						{
							biome = item.Value;
							break;
						}
					}
					Location component = wayshrines.GetComponent<Location>();
					component.m_clearArea = true;
					component.m_exteriorRadius = 16f;
					component.m_noBuild = true;
					GameObject[] array = Resources.FindObjectsOfTypeAll<GameObject>();
					foreach (GameObject val in array)
					{
						if (((Object)val).name == "_Locations")
						{
							Transform val2 = val.transform.Find("Misc");
							if (val2 != null)
							{
								WayshrinePlugin.waylogger.LogDebug((object)"Adding the shit");
								((Object)Object.Instantiate<GameObject>(wayshrines, val2, true)).name = ((Object)wayshrines).name;
								__instance.m_locations.Add(CreateZoneLocation(biome, ((Object)wayshrines).name));
							}
						}
					}
				}
			}

			private static ZoneLocation CreateZoneLocation(Biome biome, string prefabName)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: 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_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0042: 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_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_0066: Unknown result type (might be due to invalid IL or missing references)
				//IL_0072: Expected O, but got Unknown
				return new ZoneLocation
				{
					m_randomRotation = true,
					m_minAltitude = 10f,
					m_maxAltitude = 1000f,
					m_maxDistance = 1500f,
					m_quantity = 5,
					m_biome = biome,
					m_prefabName = prefabName,
					m_enable = true,
					m_minDistanceFromSimilar = 1000f,
					m_prioritized = true,
					m_forestTresholdMax = 5f,
					m_forestTresholdMin = 0f
				};
			}
		}

		private static int MinimapPinId = 180;

		public static GameObject wayshrine = null;

		private static GameObject wayshrine_ash = null;

		private static GameObject wayshrine_plains = null;

		private static GameObject wayshrine_frost = null;

		private static GameObject wayshrine_skull = null;

		private static GameObject wayshrine_skull_2 = null;

		private static GameObject vfx_bifrost = null;

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

		private static bool AssetsLoaded;

		private static AssetBundle GetAssetBundleFromResources(string filename)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string name = executingAssembly.GetManifestResourceNames().Single([<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(0)] (string str) => str.EndsWith(filename));
			using Stream stream = executingAssembly.GetManifestResourceStream(name);
			return AssetBundle.LoadFromStream(stream);
		}

		private static void InitAssets(GameObject wayshrineGO)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			MaterialReplacer.RegisterGameObjectForShaderSwap(wayshrineGO, MaterialReplacer.ShaderType.PieceShader);
			WayshrineCustomBehaviour wayshrineCustomBehaviour = wayshrineGO.AddComponent<WayshrineCustomBehaviour>();
			wayshrineGO.AddComponent<Location>();
			Piece component = wayshrineGO.GetComponent<Piece>();
			component.m_description = "Call to Heimdall, for he shall take you home";
			component.m_canBeRemoved = false;
			((StaticTarget)component).m_primaryTarget = false;
			((StaticTarget)component).m_randomTarget = true;
			component.m_enabled = true;
			wayshrinesList.Add(wayshrineGO);
			wayshrineCustomBehaviour.pinType = (PinType)(MinimapPinId++);
		}

		public static void LoadAssets()
		{
			AssetBundle assetBundleFromResources = GetAssetBundleFromResources("azuwayshrine");
			wayshrine = assetBundleFromResources.LoadAsset<GameObject>("Wayshrine");
			wayshrine_ash = assetBundleFromResources.LoadAsset<GameObject>("Wayshrine_Ashlands");
			wayshrine_frost = assetBundleFromResources.LoadAsset<GameObject>("Wayshrine_Frost");
			wayshrine_plains = assetBundleFromResources.LoadAsset<GameObject>("Wayshrine_Plains");
			wayshrine_skull = assetBundleFromResources.LoadAsset<GameObject>("Wayshrine_Skull");
			wayshrine_skull_2 = assetBundleFromResources.LoadAsset<GameObject>("Wayshrine_Skull_2");
			vfx_bifrost = assetBundleFromResources.LoadAsset<GameObject>("vfx_bifrost");
			InitAssets(wayshrine);
			InitAssets(wayshrine_ash);
			InitAssets(wayshrine_frost);
			InitAssets(wayshrine_plains);
			InitAssets(wayshrine_skull);
			InitAssets(wayshrine_skull_2);
			assetBundleFromResources.Unload(false);
			AssetsLoaded = true;
		}
	}
	[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(0)]
	[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
	[HarmonyPatch]
	public class WayshrineCustomBehaviour : MonoBehaviour, Hoverable, Interactable
	{
		[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(0)]
		public struct WayshrineInfo
		{
			[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(1)]
			public GameObject Prefab;

			public Quaternion Rotation;
		}

		public static readonly Dictionary<Vector3, WayshrineInfo> Wayshrines = new Dictionary<Vector3, WayshrineInfo>();

		public static readonly List<PinData> pins = new List<PinData>();

		[TextArea]
		private ZNetView _zNetView;

		private Piece piece;

		public PinType pinType;

		private Piece wayshrinePiece;

		public string GetHoverText()
		{
			return Util.GetLocalized(piece.m_name + "\n[<color=yellow><b>$KEY_Use</b></color>] $wayshrine_activate");
		}

		public string GetHoverName()
		{
			return Util.GetLocalized(piece.m_name);
		}

		public bool Interact(Humanoid character, bool hold, bool alt)
		{
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: 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_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			if (hold)
			{
				return true;
			}
			Player localPlayer = Player.m_localPlayer;
			PlayerProfile playerProfile = Game.instance.GetPlayerProfile();
			if (!((Humanoid)Player.m_localPlayer).IsTeleportable() && !WayshrinePlugin.Teleportable.Value)
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, "$msg_noteleport", 0, (Sprite)null);
				return true;
			}
			if (!MinimapPatches.CheckTeleportCost())
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, $"$wayshrine_cost_error : {WayshrinePlugin.ChargeItemAmount.Value} {MinimapPatches._itemName}", 0, (Sprite)null);
				return true;
			}
			ConfigEntry<bool> originalFunc = WayshrinePlugin.OriginalFunc;
			if (originalFunc != null && originalFunc.Value)
			{
				GameObject prefab = ZNetScene.instance.GetPrefab("fx_dragon_land");
				GameObject prefab2 = ZNetScene.instance.GetPrefab("vfx_bifrost");
				ZNetScene.instance.GetPrefab("sfx_thunder");
				if (!object.Equals(prefab, null) && !object.Equals(prefab2, null))
				{
					originalFunc = WayshrinePlugin.DisableBifrostEffect;
					if (originalFunc != null && !originalFunc.Value)
					{
						Vector3 position = ((Component)Player.m_localPlayer).transform.position;
						Object.Instantiate<GameObject>(prefab, position, Quaternion.identity);
						try
						{
							prefab2.GetComponentInChildren<AudioSource>().outputAudioMixerGroup = AudioMan.instance.m_ambientMixer;
						}
						catch
						{
							Debug.LogError((object)"AzuWayshrine: AudioMan.instance.m_ambientMixer could not be assigned on outputAudioMixerGroup of vfx_bifrost");
						}
						Object.Instantiate<GameObject>(prefab2, position, Quaternion.identity);
					}
				}
				((Character)character).Message((MessageType)2, Util.GetLocalized("$activated_heimdall"), 0, (Sprite)null);
				Vector3 val = (playerProfile.HaveCustomSpawnPoint() ? playerProfile.GetCustomSpawnPoint() : playerProfile.GetHomePoint());
				((Character)localPlayer).TeleportTo(val, Quaternion.identity, false);
				((Character)localPlayer).m_lastGroundTouch = 0f;
				return true;
			}
			MinimapPatches.IsHeimdallMode = true;
			Minimap.instance.ShowPointOnMap(((Component)this).transform.position);
			foreach (KeyValuePair<Vector3, WayshrineInfo> wayshrine in Wayshrines)
			{
				WayshrineCustomBehaviour component = wayshrine.Value.Prefab.GetComponent<WayshrineCustomBehaviour>();
				pins.Add(Minimap.instance.AddPin(wayshrine.Key, component.pinType, Util.GetLocalized(wayshrine.Value.Prefab.GetComponent<Piece>().m_name), false, false, 0L, ""));
			}
			return false;
		}

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

		private void Awake()
		{
			piece = ((Component)this).GetComponent<Piece>();
			_zNetView = ((Component)this).GetComponent<ZNetView>();
			ZDO zDO = _zNetView.GetZDO();
			if (zDO != null && zDO.IsValid())
			{
				if (zDO.OwnerRevision == 0)
				{
					zDO.IncreaseOwnerRevision();
					Util.SendWayshrines(ZRoutedRpc.Everybody, new List<ZDO> { zDO });
				}
			}
			else
			{
				Object.DestroyImmediate((Object)(object)this);
			}
		}

		public void OnDestroy()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			if (Wayshrines.ContainsKey(((Component)this).transform.position))
			{
				ZPackage val = new ZPackage();
				val.Write(1);
				val.Write(((Component)this).transform.position);
				val.Write(((Component)this).transform.rotation);
				val.Write(0);
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "RequestWayZDOs", new object[1] { val });
			}
		}

		public void Start()
		{
			if (WayshrinePlugin.isAdmin)
			{
				wayshrinePiece = ((Component)this).GetComponent<Piece>();
				wayshrinePiece.m_canBeRemoved = true;
			}
			Util.SendWayshrines(0L);
		}
	}
	[HarmonyPatch(typeof(Terminal), "InitTerminal")]
	public static class WayInitTerminal_Patch
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__0_0;

			internal void <Postfix>b__0_0(ConsoleEventArgs args)
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Expected O, but got Unknown
				ZRoutedRpc.instance.InvokeRoutedRPC("DeleteWayZDOs", new object[1] { (object)new ZPackage() });
				Terminal context = args.Context;
				if (context != null)
				{
					context.AddString("<color=yellow>Delete Wayshrines called. Trying to delete all ZDOs</color>");
				}
				ZDOMan.instance.SendDestroyed();
				Util.SendWayshrines(0L);
			}
		}

		private static void Postfix()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					//IL_0012: Unknown result type (might be due to invalid IL or missing references)
					//IL_0018: Expected O, but got Unknown
					ZRoutedRpc.instance.InvokeRoutedRPC("DeleteWayZDOs", new object[1] { (object)new ZPackage() });
					Terminal context = args.Context;
					if (context != null)
					{
						context.AddString("<color=yellow>Delete Wayshrines called. Trying to delete all ZDOs</color>");
					}
					ZDOMan.instance.SendDestroyed();
					Util.SendWayshrines(0L);
				};
				<>c.<>9__0_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("delway", "Delete Wayshrines and Wayshrine Pins", (ConsoleEvent)obj, true, true, true, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}
	}
	[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(0)]
	[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
	internal static class ZNetExt
	{
		[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(0)]
		public enum ZNetInstanceType
		{
			Local,
			Client,
			Server
		}

		public static bool IsLocalInstance(this ZNet znet)
		{
			if (znet.IsServer())
			{
				return !znet.IsDedicated();
			}
			return false;
		}

		public static bool IsClientInstance(this ZNet znet)
		{
			if (!znet.IsServer())
			{
				return !znet.IsDedicated();
			}
			return false;
		}

		public static bool IsServerInstance(this ZNet znet)
		{
			if (znet.IsServer())
			{
				return znet.IsDedicated();
			}
			return false;
		}

		public static ZNetInstanceType GetInstanceType(this ZNet znet)
		{
			if (znet.IsLocalInstance())
			{
				return ZNetInstanceType.Local;
			}
			if (!znet.IsClientInstance())
			{
				return ZNetInstanceType.Server;
			}
			return ZNetInstanceType.Client;
		}

		public static bool IsAdmin(this ZNet znet, long uid)
		{
			return znet.ListContainsId(znet.m_adminList, znet.GetPeer(uid).m_socket.GetHostName());
		}

		public static bool IsAdmin(this ZNet znet, [<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(2)] ZRpc rpc)
		{
			if (rpc != null)
			{
				return znet.ListContainsId(znet.m_adminList, znet.GetPeer(rpc).m_socket.GetHostName());
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Game), "_RequestRespawn")]
	public class SendWayshrinesGameRespawnPatch
	{
		[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
		private static void Postfix(Game __instance)
		{
			if (ZNet.instance.IsServer())
			{
				Util.SendWayshrines(0L);
			}
		}
	}
	public static class MinimapPatches
	{
		[HarmonyPatch(typeof(Minimap), "SetMapMode")]
		public class Minimap_SetMapMode_Patch
		{
			private static void Postfix(MapMode mode)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Invalid comparison between Unknown and I4
				if ((int)mode != 2)
				{
					LeaveHeimdallMode();
				}
			}
		}

		[HarmonyPatch(typeof(Minimap), "Start")]
		public class MMStart_Patch
		{
			[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
			private static void Postfix(Minimap __instance, out bool[] ___m_visibleIconTypes)
			{
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				//IL_005c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				//IL_006e: Unknown result type (might be due to invalid IL or missing references)
				___m_visibleIconTypes = new bool[200];
				for (int i = 0; i < 200; i++)
				{
					__instance.m_visibleIconTypes[i] = true;
				}
				foreach (GameObject wayshrines in Assets.wayshrinesList)
				{
					Sprite icon = wayshrines.GetComponent<Piece>().m_icon;
					__instance.m_icons.Add(new SpriteData
					{
						m_name = wayshrines.GetComponent<WayshrineCustomBehaviour>().pinType,
						m_icon = icon
					});
				}
			}
		}

		[HarmonyPatch(typeof(Minimap), "OnMapLeftClick")]
		private class OnMapLeftClick_Patch
		{
			private static bool Prefix()
			{
				WayshrinePlugin.waylogger.LogDebug((object)("Map Left Click: HeimdallMode is " + IsHeimdallMode));
				if (!IsHeimdallMode)
				{
					return true;
				}
				DoBiFrostStuff();
				return false;
			}
		}

		[HarmonyPatch(typeof(Minimap), "OnMapDblClick")]
		private class OnMapDblClick_Patch
		{
			private static bool Prefix()
			{
				return !IsHeimdallMode;
			}
		}

		[HarmonyPatch(typeof(Minimap), "OnMapRightClick")]
		private class OnMapRightClick_Patch
		{
			private static bool Prefix()
			{
				return !IsHeimdallMode;
			}
		}

		[HarmonyPatch(typeof(Minimap), "OnMapMiddleClick")]
		private class OnMapMiddleClick_Patch
		{
			private static bool Prefix()
			{
				return !IsHeimdallMode;
			}
		}

		public static bool IsHeimdallMode;

		[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(2)]
		internal static string _itemName;

		private static void LeaveHeimdallMode()
		{
			IsHeimdallMode = false;
			foreach (PinData pin in WayshrineCustomBehaviour.pins)
			{
				Minimap.instance.RemovePin(pin);
			}
			WayshrineCustomBehaviour.pins.Clear();
		}

		private static async void DoBiFrostStuff()
		{
			if (!((Humanoid)Player.m_localPlayer).IsTeleportable() && !WayshrinePlugin.Teleportable.Value)
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, "$msg_noteleport", 0, (Sprite)null);
				return;
			}
			if (!CheckTeleportCost())
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, $"$wayshrine_cost_error : {WayshrinePlugin.ChargeItemAmount.Value} {_itemName}", 0, (Sprite)null);
				return;
			}
			foreach (PinData pin in WayshrineCustomBehaviour.pins)
			{
				pin.m_save = true;
			}
			Minimap instance = Minimap.instance;
			PinData closestPin = instance.GetClosestPin(instance.ScreenToWorldPoint(Input.mousePosition), instance.m_removeRadius * (instance.m_largeZoom * 2f));
			WayshrinePlugin.waylogger.LogDebug((object)("Closest Pin grabbed " + closestPin.m_name));
			foreach (PinData pin2 in WayshrineCustomBehaviour.pins)
			{
				pin2.m_save = false;
			}
			if (closestPin == null || !WayshrineCustomBehaviour.Wayshrines.TryGetValue(closestPin.m_pos, out var value))
			{
				return;
			}
			Vector3 pos2 = closestPin.m_pos;
			Quaternion rotation = value.Rotation;
			Vector3 pos = pos2 + ((Quaternion)(ref rotation)).normalized * Vector3.forward + Vector3.up;
			Minimap.instance.SetMapMode((MapMode)1);
			LeaveHeimdallMode();
			await Task.Delay(TimeSpan.FromSeconds(2.0));
			((Character)Player.m_localPlayer).Message((MessageType)2, "Heimdall opens the Bifrost: Teleporting", 0, (Sprite)null);
			await Task.Delay(TimeSpan.FromSeconds(2.0));
			GameObject prefab = ZNetScene.instance.GetPrefab("fx_dragon_land");
			GameObject prefab2 = ZNetScene.instance.GetPrefab("vfx_bifrost");
			ZNetScene.instance.GetPrefab("sfx_thunder");
			if (!object.Equals(prefab, null) && !object.Equals(prefab2, null))
			{
				ConfigEntry<bool> disableBifrostEffect = WayshrinePlugin.DisableBifrostEffect;
				if (disableBifrostEffect != null && !disableBifrostEffect.Value)
				{
					Vector3 position = ((Component)Player.m_localPlayer).transform.position;
					Object.Instantiate<GameObject>(prefab, position, Quaternion.identity);
					try
					{
						prefab2.GetComponentInChildren<AudioSource>().outputAudioMixerGroup = AudioMan.instance.m_ambientMixer;
					}
					catch
					{
						Debug.LogError((object)"AzuWayshrine: AudioMan.instance.m_ambientMixer could not be assigned on outputAudioMixerGroup of vfx_bifrost");
					}
					GameObject obj2 = Object.Instantiate<GameObject>(prefab2, position, Quaternion.identity);
					obj2.AddComponent<TimedDestruction>().m_timeout = 4f;
					obj2.GetComponent<TimedDestruction>().m_triggerOnAwake = true;
				}
			}
			await Task.Delay(TimeSpan.FromSeconds(1.0));
			Player localPlayer = Player.m_localPlayer;
			WayshrinePlugin.waylogger.LogDebug((object)("Calling BiFrost on: " + localPlayer.GetPlayerName()));
			((Character)Player.m_localPlayer).TeleportTo(new Vector3(pos.x + 1.5f, pos.y, pos.z + 1.5f), rotation, true);
			((Character)localPlayer).m_lastGroundTouch = 0f;
		}

		internal static bool CheckTeleportCost()
		{
			if (!WayshrinePlugin.ShouldCost.Value)
			{
				return true;
			}
			ItemDrop component = ZNetScene.instance.GetPrefab(WayshrinePlugin.ChargeItem.Value).GetComponent<ItemDrop>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return false;
			}
			_itemName = Localization.instance.Localize(component.m_itemData.m_shared.m_name);
			if (((Humanoid)Player.m_localPlayer).GetInventory().CountItems(component.m_itemData.m_shared.m_name, -1, true) >= WayshrinePlugin.ChargeItemAmount.Value)
			{
				((Humanoid)Player.m_localPlayer).GetInventory().RemoveItem(component.m_itemData.m_shared.m_name, WayshrinePlugin.ChargeItemAmount.Value, -1, true);
				((Character)Player.m_localPlayer).ShowRemovedMessage(component.m_itemData, WayshrinePlugin.ChargeItemAmount.Value);
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch]
	public class PlayerPatches
	{
		[HarmonyPatch(typeof(Player), "OnSpawned")]
		public static class Wayshrine_OnSpawned_Patch
		{
			[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
			public static void Postfix(Player __instance)
			{
				if (ZNet.instance.IsLocalInstance())
				{
					WayshrinePlugin.isAdmin = true;
					WayshrinePlugin.waylogger.LogDebug((object)"Local Play Detected setting Admin: True");
				}
				if (!WayshrinePlugin.isAdmin || WayshrinePlugin.hammerAdded)
				{
					return;
				}
				_hammer = ZNetScene.instance.GetPrefab("Hammer").GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces;
				if (_hammer != null && _hammer.m_pieces.Contains(Assets.wayshrine))
				{
					return;
				}
				foreach (GameObject wayshrines in Assets.wayshrinesList)
				{
					_hammer?.m_pieces.Add(wayshrines);
					wayshrines.GetComponent<Piece>().m_canBeRemoved = true;
				}
				WayshrinePlugin.hammerAdded = true;
			}
		}

		[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(2)]
		private static PieceTable _hammer;
	}
	[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
	[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(0)]
	public class AdminSyncing
	{
		private static bool isServer;

		[HarmonyPriority(700)]
		internal static void AdminStatusSync(ZNet __instance)
		{
			isServer = __instance.IsServer();
			ZRoutedRpc.instance.Register<ZPackage>("Azumatt.Wayshrine WayAdminStatusSync", (Action<long, ZPackage>)RPC_AdminPieceAddRemove);
			if (isServer)
			{
				((MonoBehaviour)ZNet.instance).StartCoroutine(WatchAdminListChanges());
			}
			static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Expected O, but got Unknown
				ZPackage val = new ZPackage();
				val.Write(isAdmin);
				((MonoBehaviour)ZNet.instance).StartCoroutine(sendZPackage(peers, val));
			}
			static IEnumerator WatchAdminListChanges()
			{
				List<string> CurrentList = new List<string>(ZNet.instance.m_adminList.GetList());
				while (true)
				{
					yield return (object)new WaitForSeconds(30f);
					if (!ZNet.instance.m_adminList.GetList().SequenceEqual(CurrentList))
					{
						CurrentList = new List<string>(ZNet.instance.m_adminList.GetList());
						List<ZNetPeer> list = (from p in ZNet.instance.GetPeers()
							where ZNet.instance.ListContainsId(ZNet.instance.m_adminList, p.m_rpc.GetSocket().GetHostName())
							select p).ToList();
						SendAdmin(ZNet.instance.GetPeers().Except(list).ToList(), isAdmin: false);
						SendAdmin(list, isAdmin: true);
					}
				}
			}
		}

		private static IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] array = package.GetArray();
			if (array != null && array.LongLength > 10000)
			{
				ZPackage val = new ZPackage();
				val.Write(4);
				MemoryStream memoryStream = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal))
				{
					deflateStream.Write(array, 0, array.Length);
				}
				val.Write(memoryStream.ToArray());
				package = val;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select TellPeerAdminStatus(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private static IEnumerator<bool> TellPeerAdminStatus(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc != null)
			{
				SendPackage(package);
			}
			void SendPackage(ZPackage pkg)
			{
				string text = "Azumatt.Wayshrine WayAdminStatusSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			yield break;
		}

		internal static void RPC_AdminPieceAddRemove(long sender, ZPackage package)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			ZNetPeer peer = ZNet.instance.GetPeer(sender);
			bool flag = false;
			try
			{
				flag = package.ReadBool();
			}
			catch
			{
			}
			if (isServer)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "Azumatt.Wayshrine WayAdminStatusSync", new object[1] { (object)new ZPackage() });
				if (ZNet.instance.m_adminList.Contains(peer.m_rpc.GetSocket().GetHostName()))
				{
					ZPackage val = new ZPackage();
					val.Write(true);
					peer.m_rpc.Invoke("Azumatt.Wayshrine WayAdminStatusSync", new object[1] { val });
				}
				return;
			}
			foreach (GameObject wayshrines in Assets.wayshrinesList)
			{
				Piece component = wayshrines.GetComponent<Piece>();
				string name = component.m_name;
				Localization.instance.Localize(name).Trim();
				if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || (Object)(object)ObjectDB.instance.GetItemPrefab("Wood") == (Object)null)
				{
					continue;
				}
				Piece[] array = Object.FindObjectsOfType<Piece>();
				foreach (Piece val2 in array)
				{
					if (flag)
					{
						if (val2.m_name == name)
						{
							val2.m_enabled = true;
						}
					}
					else if (val2.m_name == name)
					{
						val2.m_enabled = false;
					}
				}
				List<GameObject> pieces = ObjectDB.instance.GetItemPrefab("Hammer").GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces.m_pieces;
				if (flag)
				{
					if (!pieces.Contains(ZNetScene.instance.GetPrefab(((Object)component).name)))
					{
						pieces.Add(ZNetScene.instance.GetPrefab(((Object)component).name));
					}
				}
				else if (pieces.Contains(ZNetScene.instance.GetPrefab(((Object)component).name)))
				{
					pieces.Remove(ZNetScene.instance.GetPrefab(((Object)component).name));
				}
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
	[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(0)]
	internal class RegisterClientRPCPatch
	{
		private static void Postfix(ZNet __instance, ZNetPeer peer)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			if (!__instance.IsServer())
			{
				peer.m_rpc.Register<ZPackage>("Azumatt.Wayshrine WayAdminStatusSync", (Action<ZRpc, ZPackage>)RPC_InitialAdminSync);
				return;
			}
			ZPackage val = new ZPackage();
			val.Write(__instance.m_adminList.Contains(peer.m_rpc.GetSocket().GetHostName()));
			peer.m_rpc.Invoke("Azumatt.Wayshrine WayAdminStatusSync", new object[1] { val });
		}

		private static void RPC_InitialAdminSync(ZRpc rpc, ZPackage package)
		{
			AdminSyncing.RPC_AdminPieceAddRemove(0L, package);
		}
	}
	[HarmonyPatch(typeof(ZNet), "Awake")]
	internal static class ZNetAwakePatch
	{
		[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
		private static void Postfix(ZNet __instance)
		{
			AdminSyncing.AdminStatusSync(__instance);
		}
	}
	[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(0)]
	[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
	public static class Util
	{
		public static string GetLocalized(string param)
		{
			return Localization.instance.Localize(param);
		}

		public static void SendWayshrines(long target)
		{
			List<ZDO> list = new List<ZDO>();
			foreach (GameObject wayshrines in Assets.wayshrinesList)
			{
				GetAllZDOsWithPrefab(((Object)wayshrines).name, list);
			}
			SendWayshrines(target, list);
		}

		public static void GetAllZDOsWithPrefab(string prefab, List<ZDO> zdos)
		{
			int stableHashCode = StringExtensionMethods.GetStableHashCode(prefab);
			foreach (ZDO value in ZDOMan.instance.m_objectsByID.Values)
			{
				if (value.GetPrefab() == stableHashCode)
				{
					zdos.Add(value);
				}
			}
		}

		public static void SendWayshrines(long target, List<ZDO> wayshrineZDOs)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			val.Write(wayshrineZDOs.Count);
			foreach (ZDO wayshrineZDO in wayshrineZDOs)
			{
				val.Write(wayshrineZDO.m_position);
				val.Write(wayshrineZDO.GetRotation());
				val.Write(wayshrineZDO.GetPrefab());
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(target, "RequestWayZDOs", new object[1] { val });
		}

		public static void ReadWayshrines(long target, ZPackage package)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			for (int num = package.ReadInt(); num > 0; num--)
			{
				Vector3 key = package.ReadVector3();
				Quaternion rotation = package.ReadQuaternion();
				int num2 = package.ReadInt();
				if (num2 == 0)
				{
					WayshrineCustomBehaviour.Wayshrines.Remove(key);
				}
				else
				{
					WayshrineCustomBehaviour.Wayshrines[key] = new WayshrineCustomBehaviour.WayshrineInfo
					{
						Prefab = ZNetScene.instance.GetPrefab(num2),
						Rotation = rotation
					};
				}
			}
		}

		public static void DeleteWayZDOs(long sender, ZPackage pkg)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			if (ZNet.m_isServer)
			{
				WayshrinePlugin.waylogger.LogMessage((object)"Deleting wayshrines");
			}
			List<ZDO> list = new List<ZDO>();
			foreach (GameObject wayshrines in Assets.wayshrinesList)
			{
				GetAllZDOsWithPrefab(((Object)wayshrines).name, list);
			}
			if (list.Count == 0)
			{
				return;
			}
			foreach (ZDO item in list)
			{
				ZDOMan.instance.m_destroySendList.Add(item.m_uid);
			}
			foreach (PinData pin in WayshrineCustomBehaviour.pins)
			{
				Minimap.instance.RemovePin(pin);
			}
			WayshrineCustomBehaviour.pins.Clear();
			SendWayshrines(0L);
		}
	}
	[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
	[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(0)]
	[BepInPlugin("Azumatt.Wayshrine", "AzuWayshrine", "1.1.2")]
	public class WayshrinePlugin : BaseUnityPlugin
	{
		internal const string ModName = "AzuWayshrine";

		internal const string ModVersion = "1.1.2";

		internal const string ModGUID = "Azumatt.Wayshrine";

		public static bool isAdmin = false;

		public static bool hammerAdded = false;

		public static Sprite way_icon = null;

		public static Sprite way_icon_ash = null;

		public static Sprite way_icon_frost = null;

		public static Sprite way_icon_plains = null;

		public static Sprite way_icon_skull = null;

		public static Sprite way_icon_skull_2 = null;

		private static string ConfigFileName = "Azumatt.Wayshrine.cfg";

		private static string ConfigFileFullPath;

		private static string LangFileFullPath;

		public static readonly ManualLogSource waylogger;

		private static readonly ConfigSync configSync;

		private static ConfigFile _localizationFile;

		private static readonly Dictionary<string, ConfigEntry<string>> MLocalizedStrings;

		private static ConfigEntry<bool> _serverConfigLocked;

		public static ConfigEntry<bool> OriginalFunc;

		public static ConfigEntry<bool> DisableBifrostEffect;

		public static ConfigEntry<bool> Teleportable;

		public static ConfigEntry<bool> ShouldCost;

		public static ConfigEntry<string> ChargeItem;

		public static ConfigEntry<int> ChargeItemAmount;

		private ConfigEntry<T> config<[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			configSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public void Awake()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			Harmony val = new Harmony("Azumatt.Wayshrine");
			_localizationFile = new ConfigFile(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), "Azumatt.Wayshrine.Localization.cfg"), false);
			Assets.LoadAssets();
			_serverConfigLocked = config("General", "Force Server Config", value: true, "Force Server Config");
			configSync.AddLockingConfigEntry<bool>(_serverConfigLocked);
			OriginalFunc = config("General", "Original Function", value: false, "Use the original functionality of the Wayshrines, unlink them and only take you to spawn or home");
			DisableBifrostEffect = config("General", "Disable Bifrost Effect", value: false, "Disable the bifrost effect on teleport");
			Teleportable = config("General", "AllowTeleport", value: false, "Enable teleport with restricted items");
			ShouldCost = config("Wayshrine Cost", "Should Cost?", value: false, "Should using the wayshrines cost the player something from their inventory?");
			ChargeItem = config("Wayshrine Cost", "Cost Item", "Coins", "Item needed to use the wayshrine. Limit is 1 item: Goes by prefab name. List of vanilla items here: https://github.com/Valheim-Modding/Wiki/wiki/ObjectDB-Table");
			ChargeItemAmount = config("Wayshrine Cost", "Cost Item Amount", 5, "Amount of the Item needed to teleport using a wayshrine.");
			SetupWatcher();
			val.PatchAll(executingAssembly);
			Localize();
		}

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

		private static void Localize()
		{
			try
			{
				LocalizeWord("piece_azuwayshrine", "Wayshrine");
				LocalizeWord("piece_azuwayshrine_ashlands", "Ashlands Wayshrine");
				LocalizeWord("piece_azuwayshrine_frost", "Frost Wayshrine");
				LocalizeWord("piece_azuwayshrine_plains", "Plains Wayshrine");
				LocalizeWord("piece_azuwayshrine_skull", "Skull Wayshrine");
				LocalizeWord("piece_azuwayshrine_skull_2", "Skull Wayshrine");
				LocalizeWord("wayshrine_activate", "Activate");
				LocalizeWord("activated_heimdall", "Heimdall opens the Bifrost!");
				LocalizeWord("wayshrine_description", "Call to Heimdall, for he shall take you home");
				LocalizeWord("wayshrine_cost_error", "Required Items needed");
			}
			catch (Exception arg)
			{
				waylogger.LogError((object)$"Localizing your values failed! {arg}");
			}
		}

		private static void LocalizeWord(string key, string val)
		{
			if (!MLocalizedStrings.ContainsKey(key))
			{
				string selectedLanguage = Localization.instance.GetSelectedLanguage();
				ConfigEntry<string> val2 = _localizationFile.Bind<string>(selectedLanguage, key, val, (ConfigDescription)null);
				Localization.instance.AddWord(key, val2.Value);
				MLocalizedStrings.Add(key, val2);
			}
		}

		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;
			FileSystemWatcher fileSystemWatcher2 = new FileSystemWatcher(Paths.ConfigPath, "Azumatt.Wayshrine.Localization.cfg");
			fileSystemWatcher2.Created += ReadLangValues;
			fileSystemWatcher2.Renamed += ReadLangValues;
			fileSystemWatcher2.IncludeSubdirectories = true;
			fileSystemWatcher2.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher2.EnableRaisingEvents = true;
		}

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

		private void ReadLangValues(object sender, FileSystemEventArgs e)
		{
			if (!File.Exists(LangFileFullPath))
			{
				return;
			}
			try
			{
				_localizationFile.Reload();
				foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in _localizationFile)
				{
					ConfigEntryBase value = item.Value;
					if (!(value.SettingType != typeof(string)))
					{
						ConfigEntry<string> val = (ConfigEntry<string>)(object)value;
						if (!MLocalizedStrings.ContainsKey(((ConfigEntryBase)val).Definition.Key))
						{
							string selectedLanguage = Localization.instance.GetSelectedLanguage();
							ConfigEntry<string> val2 = _localizationFile.Bind<string>(selectedLanguage, ((ConfigEntryBase)val).Definition.Key, val.Value, (ConfigDescription)null);
							Localization.instance.AddWord(((ConfigEntryBase)val).Definition.Key, val2.Value);
							MLocalizedStrings.Add(((ConfigEntryBase)val).Definition.Key, val2);
						}
						else if (MLocalizedStrings.ContainsKey(((ConfigEntryBase)val).Definition.Key))
						{
							Localization.instance.AddWord(((ConfigEntryBase)val).Definition.Key, val.Value);
						}
					}
				}
				_localizationFile.Save();
			}
			catch
			{
				waylogger.LogError((object)"There was an issue loading your Azumatt.Wayshrine.Localization.cfg");
				waylogger.LogError((object)"Please check your config entries for spelling and format!");
			}
		}

		static WayshrinePlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			string configPath2 = Paths.ConfigPath;
			directorySeparatorChar = Path.DirectorySeparatorChar;
			LangFileFullPath = configPath2 + directorySeparatorChar + "Azumatt.Wayshrine.Localization.cfg";
			waylogger = Logger.CreateLogSource("AzuWayshrine");
			configSync = new ConfigSync("Azumatt.Wayshrine")
			{
				DisplayName = "AzuWayshrine",
				CurrentVersion = "1.1.2",
				MinimumRequiredVersion = "1.1.2"
			};
			_localizationFile = null;
			MLocalizedStrings = new Dictionary<string, ConfigEntry<string>>();
			_serverConfigLocked = null;
			OriginalFunc = null;
			DisableBifrostEffect = null;
			Teleportable = null;
			ShouldCost = null;
			ChargeItem = null;
			ChargeItemAmount = null;
		}
	}
}
namespace Wayshrine.Patches
{
	public static class WayshrineZdoDataBuffer
	{
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private class StartBufferingOnNewConnection
		{
			[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (!__instance.IsServer())
				{
					peer.m_rpc.Register<ZPackage>("ZDOData", (Action<ZRpc, ZPackage>)((ZRpc _, [<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(1)] ZPackage package) =>
					{
						PackageBuffer.Add(package);
					}));
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class WayshrineClearPackageBufferOnShutdown
		{
			private static void Postfix()
			{
				PackageBuffer.Clear();
			}
		}

		[HarmonyPatch(typeof(ZDOMan), "AddPeer")]
		private class WayshrineEvaluateBufferedPackages
		{
			[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
			private static void Postfix(ZDOMan __instance, ZNetPeer netPeer)
			{
				foreach (ZPackage item in PackageBuffer)
				{
					__instance.RPC_ZDOData(netPeer.m_rpc, item);
				}
				PackageBuffer.Clear();
			}
		}

		[<70a37419-71ab-4d38-8b06-13d69148464f>Nullable(1)]
		private static readonly List<ZPackage> PackageBuffer = new List<ZPackage>();
	}
	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	public static class PatchZNetRPC_PeerInfo
	{
		[<5bfa5f97-a973-45fb-b886-a3d73b0b2481>NullableContext(1)]
		[UsedImplicitly]
		private static void Postfix(ZNet __instance, ZRpc rpc)
		{
			if (__instance.IsServer())
			{
				Util.SendWayshrines(__instance.GetPeer(rpc).m_uid);
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "Awake")]
	public static class PatchWayshrineRPCRegistration
	{
		private static void Postfix()
		{
			ZRoutedRpc.instance.Register<ZPackage>("RequestWayZDOs", (Action<long, ZPackage>)Util.ReadWayshrines);
			ZRoutedRpc.instance.Register<ZPackage>("DeleteWayZDOs", (Action<long, ZPackage>)Util.DeleteWayZDOs);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class 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)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0)
			: base(configSync, identifier, typeof(T), priority)
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZRpc rpc2 = rpc;
				ZNet __instance2 = __instance;
				Dictionary<Assembly, BufferingSocket> __state2 = __state;
				ZNetPeer peer;
				if (__instance2.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance2).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc2.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc2.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ConfigEntry<T> configEntry2 = configEntry;
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry2);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry2.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			CustomSyncedValueBase customValue2 = customValue;
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue2);
			allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority));
			customValue2.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue2);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			OwnConfigEntryBase config2 = config;
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZNetPeer peer2 = peer;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer2.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer2.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer2.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout");
						peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer2);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			ZPackage package2 = package;
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package2.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package2 = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package2)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[PublicAPI]
	[HarmonyPatch]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			ZRpc rpc2 = rpc;
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout(true, true);
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string