Decompiled source of EnvoysOfOdin v0.1.3

plugins/EnvoysOfOdin.dll

Decompiled 13 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyMetadata("PlanetRadialRewrite", "off")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace EnvoysOfOdin
{
	internal static class Access
	{
		internal struct Fighter
		{
			internal long Player;

			internal string Name;

			internal bool Online;

			internal bool HasPosition;

			internal Vector3 Position;
		}

		internal static bool MayUseStone(int stoneTeam, int myTeam, bool serverHasMod)
		{
			if (serverHasMod && stoneTeam != 0)
			{
				if (myTeam != 0)
				{
					return myTeam == stoneTeam;
				}
				return false;
			}
			return true;
		}

		internal static bool Earned(string power, Func<string, string> keyOf, ICollection<string> teamKeys, bool teamView)
		{
			if (!teamView)
			{
				return true;
			}
			string text = keyOf(power);
			if (text != null)
			{
				return teamKeys?.Contains(text) ?? false;
			}
			return true;
		}

		internal static HashSet<long> Participants(IEnumerable<Fighter> fighters, ICollection<string> hitBy, Vector3 where, float near)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			HashSet<long> hashSet = new HashSet<long>();
			foreach (Fighter fighter in fighters)
			{
				if (fighter.Online && fighter.Player != 0L)
				{
					bool num = fighter.Name != null && hitBy.Contains(fighter.Name);
					bool flag = near > 0f && fighter.HasPosition && Vector3.Distance(fighter.Position, where) <= near;
					if (num || flag)
					{
						hashSet.Add(fighter.Player);
					}
				}
			}
			return hashSet;
		}
	}
	internal static class Bosses
	{
		private static readonly Dictionary<string, string> fallback;

		internal static readonly Dictionary<string, string> PowerKey;

		internal static readonly Dictionary<string, string> KeyName;

		private static readonly HashSet<string> keys;

		internal static readonly List<GameObject> StonePrefabs;

		internal static IEnumerable<string> Keys => keys;

		internal static bool TeamView
		{
			get
			{
				if (Client.ServerHasMod && Client.Rules.PerTeam && Client.View != null)
				{
					return (Object)(object)Player.m_localPlayer != (Object)null;
				}
				return false;
			}
		}

		static Bosses()
		{
			fallback = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
			{
				{ "GP_Eikthyr", "defeated_eikthyr" },
				{ "GP_TheElder", "defeated_gdking" },
				{ "GP_Bonemass", "defeated_bonemass" },
				{ "GP_Moder", "defeated_dragon" },
				{ "GP_Yagluth", "defeated_goblinking" },
				{ "GP_Queen", "defeated_queen" },
				{ "GP_Fader", "defeated_fader" },
				{ "GP_Ashlands", "defeated_fader" }
			};
			PowerKey = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			KeyName = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			StonePrefabs = new List<GameObject>();
			string[] names = Enum.GetNames(typeof(GlobalKeys));
			foreach (string text in names)
			{
				if (text.StartsWith("defeated_", StringComparison.OrdinalIgnoreCase))
				{
					keys.Add(text.ToLowerInvariant());
				}
			}
		}

		internal static bool IsBossKey(string key)
		{
			if (!string.IsNullOrEmpty(key))
			{
				return keys.Contains(key.Trim());
			}
			return false;
		}

		internal static void Learn(ZNetScene scene)
		{
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Invalid comparison between Unknown and I4
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			StonePrefabs.Clear();
			foreach (GameObject prefab in scene.m_prefabs)
			{
				if ((Object)(object)prefab == (Object)null)
				{
					continue;
				}
				Character component = prefab.GetComponent<Character>();
				if (!((Object)(object)component != (Object)null) || string.IsNullOrEmpty(component.m_defeatSetGlobalKey))
				{
					continue;
				}
				string text = component.m_defeatSetGlobalKey.ToLowerInvariant();
				keys.Add(text);
				KeyName[text] = component.m_name;
				CharacterDrop component2 = prefab.GetComponent<CharacterDrop>();
				if (!((Object)(object)component2 != (Object)null))
				{
					continue;
				}
				foreach (Drop drop in component2.m_drops)
				{
					if ((Object)(object)drop?.m_prefab != (Object)null)
					{
						ItemDrop component3 = drop.m_prefab.GetComponent<ItemDrop>();
						if (component3 != null && (int)(component3.m_itemData?.m_shared?.m_itemType).GetValueOrDefault() == 13)
						{
							dictionary[((Object)drop.m_prefab).name] = text;
						}
					}
				}
			}
			foreach (GameObject prefab2 in scene.m_prefabs)
			{
				if ((Object)(object)prefab2 == (Object)null)
				{
					continue;
				}
				BossStone component4 = prefab2.GetComponent<BossStone>();
				ItemStand val = (((Object)(object)component4 != (Object)null) ? component4.m_itemStand : null);
				if ((Object)(object)val == (Object)null || (Object)(object)val.m_guardianPower == (Object)null)
				{
					continue;
				}
				StonePrefabs.Add(prefab2);
				foreach (ItemDrop supportedItem in val.m_supportedItems)
				{
					if ((Object)(object)supportedItem != (Object)null && dictionary.TryGetValue(((Object)supportedItem).name, out var value))
					{
						PowerKey[((Object)val.m_guardianPower).name] = value;
					}
				}
			}
			foreach (KeyValuePair<string, string> item in fallback)
			{
				if (!PowerKey.ContainsKey(item.Key))
				{
					PowerKey[item.Key] = item.Value;
				}
			}
			Plugin.Log(string.Format("bosses: {0} defeat keys; powers {1}; {2} guardian stones ({3})", keys.Count, string.Join(", ", PowerKey.Select((KeyValuePair<string, string> p) => p.Key + "=" + p.Value)), StonePrefabs.Count, string.Join(", ", StonePrefabs.Select((GameObject s) => ((Object)s).name))));
		}

		internal static string KeyOf(string power)
		{
			if (string.IsNullOrEmpty(power))
			{
				return null;
			}
			if (!PowerKey.TryGetValue(Utils.GetPrefabName(power), out var value))
			{
				return null;
			}
			return value;
		}

		internal static string BossName(string key)
		{
			string text;
			if (key == null || !KeyName.TryGetValue(key, out var value))
			{
				text = key;
				if (text == null)
				{
					return "";
				}
			}
			else
			{
				text = value;
			}
			return text;
		}

		internal static bool Earned(string power)
		{
			return Access.Earned(power, KeyOf, Client.View?.Keys, TeamView);
		}

		internal static void KeysChanged()
		{
			Player localPlayer = Player.m_localPlayer;
			if (localPlayer != null)
			{
				localPlayer.UpdateEvents();
			}
		}
	}
	[HarmonyPatch]
	internal static class KeyView
	{
		internal static bool Raw;

		private static bool Seen(string key, out bool has)
		{
			has = false;
			if (Raw || !Bosses.TeamView || !Bosses.IsBossKey(key))
			{
				return false;
			}
			has = Client.View.Keys.Contains(key.Trim().ToLowerInvariant());
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		private static void ByName(string name, ref string value, ref bool __result)
		{
			if (Seen(name, out var has))
			{
				if (has && !__result)
				{
					value = "";
				}
				if (!has)
				{
					value = null;
				}
				__result = has;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ZoneSystem), "GetGlobalKey", new Type[] { typeof(GlobalKeys) })]
		private unsafe static void ByEnum(GlobalKeys key, ref bool __result)
		{
			if (Seen(((object)(*(GlobalKeys*)(&key))/*cast due to .constrained prefix*/).ToString(), out var has))
			{
				__result = has;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ZoneSystem), "GetGlobalKeyExact")]
		private static void Exact(string fullLine, ref bool __result)
		{
			if (Seen(fullLine, out var has))
			{
				__result = has;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ZoneSystem), "GetGlobalKeys")]
		private static void List(ref List<string> __result)
		{
			if (Raw || !Bosses.TeamView || __result == null)
			{
				return;
			}
			__result.RemoveAll((string k) => Bosses.IsBossKey(k) && !Client.View.Keys.Contains(k.ToLowerInvariant()));
			foreach (string key in Client.View.Keys)
			{
				if (!__result.Contains(key))
				{
					__result.Add(key);
				}
			}
		}
	}
	internal static class Client
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static PopupButtonCallback <>9__43_0;

			public static PopupButtonCallback <>9__43_1;

			internal void <AskLeave>b__43_0()
			{
				UnifiedPopup.Pop();
				Leave();
			}

			internal void <AskLeave>b__43_1()
			{
				UnifiedPopup.Pop();
			}
		}

		internal static TeamView View;

		internal static HostRules Rules = new HostRules();

		internal static bool ServerHasMod;

		private static HostRules lastRules;

		private static bool startAsked;

		private static bool startGiven;

		private static bool startOk;

		private static bool gaveUp;

		private static Vector3 startPoint;

		private static float askedAt;

		private static float waitSince;

		private static ulong sentParty;

		private static float nextPartyCheck;

		private static readonly Queue<(long player, string name)> asks = new Queue<(long, string)>();

		private static bool asking;

		private static readonly HashSet<long> shown = new HashSet<long>();

		private const float GiveUpAfter = 30f;

		private const float NoModAfter = 6f;

		private static long Server
		{
			get
			{
				if (ZRoutedRpc.instance == null)
				{
					return 0L;
				}
				return ZRoutedRpc.instance.GetServerPeerID();
			}
		}

		private static PlayerProfile Profile
		{
			get
			{
				if (!((Object)(object)Game.instance != (Object)null))
				{
					return null;
				}
				return Game.instance.GetPlayerProfile();
			}
		}

		internal static long Me
		{
			get
			{
				if (!((Object)(object)Player.m_localPlayer != (Object)null))
				{
					PlayerProfile profile = Profile;
					if (profile == null)
					{
						return 0L;
					}
					return profile.GetPlayerID();
				}
				return Player.m_localPlayer.GetPlayerID();
			}
		}

		internal static bool HaveAsks
		{
			get
			{
				if (asks.Count <= 0)
				{
					if (View != null)
					{
						return View.Asks > 0;
					}
					return false;
				}
				return true;
			}
		}

		internal static void Register()
		{
			View = null;
			Rules = new HostRules();
			ServerHasMod = false;
			lastRules = null;
			startAsked = (startGiven = (startOk = (gaveUp = false)));
			sentParty = 0uL;
			asks.Clear();
			asking = false;
			shown.Clear();
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != null)
			{
				instance.Register<ZPackage>("EoO_State", (Action<long, ZPackage>)OnState);
				instance.Register<ZPackage>("EoO_Start", (Action<long, ZPackage>)OnStart);
				instance.Register<ZPackage>("EoO_Asked", (Action<long, ZPackage>)OnAsked);
				instance.Register<string, string>("EoO_Msg", (Action<long, string, string>)OnMessage);
			}
		}

		internal static void Forget()
		{
			View = null;
			ServerHasMod = false;
			asks.Clear();
			asking = false;
		}

		internal static bool Member(int team)
		{
			if (View != null && team != 0)
			{
				return View.Id == team;
			}
			return false;
		}

		internal static bool Hello(bool wantStart, bool afterDeath)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			PlayerProfile profile = Profile;
			if (profile == null || ZRoutedRpc.instance == null || Server == 0L)
			{
				return false;
			}
			ulong num = (sentParty = SteamParty.PartyId);
			ZPackage val = new ZPackage();
			val.Write((byte)3);
			val.Write(profile.GetPlayerID());
			val.Write(profile.GetName() ?? "");
			val.Write((long)num);
			val.Write(wantStart);
			val.Write(afterDeath);
			ZRoutedRpc.instance.InvokeRoutedRPC(Server, "EoO_Hello", new object[1] { val });
			return true;
		}

		internal static bool OwnStart(bool afterDeath, out Vector3 point, out bool wait)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			point = Vector3.zero;
			wait = false;
			if (gaveUp)
			{
				return false;
			}
			if (ServerHasMod && (!Rules.RandomStart || (afterDeath && Rules.RespawnWithoutBed == Plugin.Respawn.GameStart)))
			{
				return false;
			}
			if (!startAsked)
			{
				if (waitSince == 0f)
				{
					waitSince = Time.unscaledTime;
				}
				if (!Hello(wantStart: true, afterDeath))
				{
					if (Time.unscaledTime - waitSince > 30f)
					{
						gaveUp = true;
						return false;
					}
					wait = true;
					return false;
				}
				startAsked = true;
				askedAt = Time.unscaledTime;
				Plugin.Debug("asked the server for a start point");
			}
			if (!startGiven)
			{
				if (Time.unscaledTime - askedAt > (ServerHasMod ? 30f : 6f))
				{
					gaveUp = true;
					Plugin.Log(ServerHasMod ? "the server gave no start point in time: the game's start" : "no answer from the server (no Envoys of Odin there?): the game's start");
					return false;
				}
				wait = true;
				return false;
			}
			if (!startOk)
			{
				Done();
				return false;
			}
			point = startPoint;
			return true;
		}

		internal static void Done()
		{
			startAsked = (startGiven = (startOk = false));
			waitSince = 0f;
		}

		private static void OnStart(long sender, ZPackage p)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (sender != Server)
			{
				return;
			}
			try
			{
				startOk = p.ReadBool();
				startPoint = p.ReadVector3();
				startGiven = true;
				ServerHasMod = true;
				Plugin.Debug("start point from the server: " + (startOk ? ((object)Unsafe.As<Vector3, Vector3>(ref startPoint)/*cast due to .constrained prefix*/).ToString() : "none, the game's"));
			}
			catch (Exception ex)
			{
				Plugin.Warn("start: " + ex.Message);
			}
		}

		private static void OnState(long sender, ZPackage p)
		{
			if (sender != Server)
			{
				return;
			}
			try
			{
				if (p.ReadByte() == 3)
				{
					Rules = HostRules.Read(p);
					gaveUp = false;
					ServerHasMod = true;
					TeamView view = View;
					View = (p.ReadBool() ? TeamView.Read(p) : null);
					if (lastRules == null || !Rules.SameRecipes(lastRules))
					{
						Pieces.ApplyRecipes();
					}
					lastRules = Rules;
					KeysToCharacter();
					TempleStones.Apply();
					Plugin.Debug((View == null) ? "no team" : string.Format("team {0} '{1}': {2} member(s), bosses {3}", View.Id, View.Name, View.Members.Count, string.Join(", ", View.Keys)));
					if (view != null && View != null && view.Keys.Count != View.Keys.Count)
					{
						Bosses.KeysChanged();
					}
					else if (view == null)
					{
						Bosses.KeysChanged();
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Warn("state: " + ex.Message);
			}
		}

		internal static void KeysToCharacter()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || View == null || !Rules.PerTeam || !Rules.KeysToCharacter)
			{
				return;
			}
			foreach (string key in View.Keys)
			{
				if (!((Humanoid)localPlayer).HaveUniqueKey(key))
				{
					((Humanoid)localPlayer).AddUniqueKey(key);
				}
			}
		}

		internal static void Ask(int team)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (!ServerHasMod)
			{
				Message("eoo_msg_noserver");
				return;
			}
			ZPackage val = new ZPackage();
			val.Write((byte)3);
			val.Write(team);
			ZRoutedRpc.instance.InvokeRoutedRPC(Server, "EoO_Ask", new object[1] { val });
		}

		internal static void Leave()
		{
			//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((byte)3);
			ZRoutedRpc.instance.InvokeRoutedRPC(Server, "EoO_Leave", new object[1] { val });
		}

		private static void Answer(long player, bool accept)
		{
			//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((byte)3);
			val.Write(player);
			val.Write(accept);
			ZRoutedRpc.instance.InvokeRoutedRPC(Server, "EoO_Answer", new object[1] { val });
		}

		private static void OnAsked(long sender, ZPackage p)
		{
			if (sender != Server)
			{
				return;
			}
			try
			{
				for (int num = p.ReadInt(); num > 0; num--)
				{
					long player = p.ReadLong();
					string text = p.ReadString();
					if (!asks.Any(((long player, string name) a) => a.player == player))
					{
						asks.Enqueue((player, text));
						if (shown.Add(player))
						{
							Player localPlayer = Player.m_localPlayer;
							if (localPlayer != null)
							{
								((Character)localPlayer).Message((MessageType)2, Words.T("eoo_notice", text), 0, (Sprite)null, false);
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Warn("asked: " + ex.Message);
			}
		}

		internal static void ShowAsks()
		{
			if (asks.Count == 0)
			{
				Hello(wantStart: false, afterDeath: false);
			}
		}

		private static void OnMessage(long sender, string key, string arg)
		{
			if (sender == Server)
			{
				Message(key, arg);
			}
		}

		internal static void Message(string key, string arg = "")
		{
			string text = Words.T(key, (Localization.instance != null) ? Localization.instance.Localize(arg ?? "") : (arg ?? ""));
			Player localPlayer = Player.m_localPlayer;
			if (localPlayer != null)
			{
				((Character)localPlayer).Message((MessageType)2, text, 0, (Sprite)null, false);
			}
		}

		internal static void Tick()
		{
			//IL_00e8: 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_0100: Expected O, but got Unknown
			//IL_0100: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			if ((Object)(object)ZNet.instance == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			if (Time.unscaledTime >= nextPartyCheck)
			{
				nextPartyCheck = Time.unscaledTime + 5f;
				if (ServerHasMod && SteamParty.PartyId != sentParty)
				{
					Hello(wantStart: false, afterDeath: false);
				}
			}
			if (!asking && asks.Count > 0 && UnifiedPopup.IsAvailable() && !UnifiedPopup.IsVisible() && !InventoryGui.IsVisible() && !Menu.IsVisible())
			{
				(long, string) tuple = asks.Dequeue();
				long player = tuple.Item1;
				string item = tuple.Item2;
				asking = true;
				UnifiedPopup.Push((PopupBase)new YesNoPopup(Words.T("eoo_ask_header"), Words.T("eoo_ask_text", item), (PopupButtonCallback)delegate
				{
					UnifiedPopup.Pop();
					asking = false;
					Answer(player, accept: true);
				}, (PopupButtonCallback)delegate
				{
					UnifiedPopup.Pop();
					asking = false;
					Answer(player, accept: false);
				}, false, false));
				UnifiedPopup instance = UnifiedPopup.instance;
				if ((Object)(object)instance != (Object)null)
				{
					if ((Object)(object)instance.buttonRightText != (Object)null)
					{
						instance.buttonRightText.text = Words.T("eoo_ask_accept");
					}
					if ((Object)(object)instance.buttonLeftText != (Object)null)
					{
						instance.buttonLeftText.text = Words.T("eoo_ask_decline");
					}
				}
			}
			if (asking && !UnifiedPopup.IsVisible())
			{
				asking = false;
			}
		}

		internal static void AskLeave()
		{
			//IL_0061: 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_006c: Expected O, but got Unknown
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			if (View == null || View.Members.Count < 2 || !UnifiedPopup.IsAvailable())
			{
				return;
			}
			string text = Words.T("eoo_leave_header");
			string text2 = Words.T("eoo_leave_text", View.Name);
			object obj = <>c.<>9__43_0;
			if (obj == null)
			{
				PopupButtonCallback val = delegate
				{
					UnifiedPopup.Pop();
					Leave();
				};
				<>c.<>9__43_0 = val;
				obj = (object)val;
			}
			object obj2 = <>c.<>9__43_1;
			if (obj2 == null)
			{
				PopupButtonCallback val2 = delegate
				{
					UnifiedPopup.Pop();
				};
				<>c.<>9__43_1 = val2;
				obj2 = (object)val2;
			}
			UnifiedPopup.Push((PopupBase)new YesNoPopup(text, text2, (PopupButtonCallback)obj, (PopupButtonCallback)obj2, false, false));
		}
	}
	[HarmonyPatch]
	internal static class Hooks
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(Game), "Start")]
		private static void Session()
		{
			Server.Register();
			Client.Register();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Game), "OnDestroy")]
		private static void Gone()
		{
			Server.Forget();
			Client.Forget();
			TempleStones.Forget();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "OnSpawned")]
		private static void Spawned(Player __instance)
		{
			if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
			{
				Pieces.ApplyRecipes();
				Client.Hello(wantStart: false, afterDeath: false);
				Client.KeysToCharacter();
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Game), "FindSpawnPoint")]
		private static bool Start(Game __instance, ref Vector3 point, ref bool usedLogoutPoint, float dt, ref bool __result)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PlayerProfile playerProfile = __instance.m_playerProfile;
				bool respawnAfterDeath = __instance.m_respawnAfterDeath;
				if (playerProfile == null || (!respawnAfterDeath && playerProfile.HaveLogoutPoint()) || playerProfile.HaveCustomSpawnPoint())
				{
					return true;
				}
				if ((Object)(object)ZNet.instance == (Object)null || ZRoutedRpc.instance == null || (Object)(object)ZNetScene.instance == (Object)null)
				{
					return true;
				}
				if (!Client.OwnStart(respawnAfterDeath, out var point2, out var wait))
				{
					if (!wait)
					{
						return true;
					}
					__instance.m_respawnWait += dt;
					point = Vector3.zero;
					usedLogoutPoint = false;
					__result = false;
					return false;
				}
				__instance.m_respawnWait += dt;
				ZNet.instance.SetReferencePosition(point2);
				usedLogoutPoint = false;
				point = Vector3.zero;
				__result = false;
				if (!ZNetScene.instance.IsAreaReady(point2))
				{
					return false;
				}
				float y = default(float);
				if (!Planet.Active && ZoneSystem.instance.GetGroundHeight(point2, ref y))
				{
					point2.y = y;
				}
				point = point2 + Vector3.up * (Planet.Active ? 0f : 1f);
				if (Planet.Active)
				{
					point = point2 + Planet.Up(point2) * 1f;
				}
				__result = true;
				Client.Done();
				Plugin.Log(string.Format("spawn at the team's start meadows: {0}{1}", point, respawnAfterDeath ? " (after a death with no bed)" : ""));
				return false;
			}
			catch (Exception ex)
			{
				Plugin.Warn("spawn: " + ex.Message);
				Client.Done();
				return true;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Character), "OnDeath")]
		private static void Death(Character __instance)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (__instance.IsPlayer() || string.IsNullOrEmpty(__instance.m_defeatSetGlobalKey))
				{
					return;
				}
				ZNetView nview = __instance.m_nview;
				if ((Object)(object)nview == (Object)null || !nview.IsValid() || !nview.IsOwner() || ZRoutedRpc.instance == null || (Object)(object)ZNet.instance == (Object)null)
				{
					return;
				}
				ZDO zDO = nview.GetZDO();
				List<string> list = new List<string>();
				foreach (PlayerInfo player in ZNet.instance.GetPlayerList())
				{
					if (!string.IsNullOrEmpty(player.m_name) && zDO.GetBool(ZDOVars.s_attackers + player.m_name, false))
					{
						list.Add(player.m_name);
					}
				}
				ZPackage val = new ZPackage();
				val.Write((byte)3);
				val.Write(__instance.m_defeatSetGlobalKey);
				val.Write(__instance.m_name ?? "");
				val.Write(((Component)__instance).transform.position);
				val.Write(list.Count);
				foreach (string item in list)
				{
					val.Write(item);
				}
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "EoO_Boss", new object[1] { val });
				Plugin.Debug("boss " + __instance.m_defeatSetGlobalKey + " down, hit by " + string.Join(", ", list));
			}
			catch (Exception ex)
			{
				Plugin.Warn("boss death: " + ex.Message);
			}
		}

		private static bool OursOrTemple(ItemStand stand, out StoneMark mark)
		{
			mark = ((Component)stand).GetComponentInParent<StoneMark>();
			if (!((Object)(object)mark != (Object)null))
			{
				return Client.Rules.TempleNeedsKill;
			}
			return true;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ItemStand), "Interact")]
		private static bool Interact(ItemStand __instance, Humanoid user, bool hold, bool alt, ref bool __result)
		{
			if ((Object)(object)user != (Object)(object)Player.m_localPlayer || (Object)(object)__instance.m_guardianPower == (Object)null || !Client.ServerHasMod)
			{
				return true;
			}
			StoneMark componentInParent = ((Component)__instance).GetComponentInParent<StoneMark>();
			if ((Object)(object)componentInParent != (Object)null && !componentInParent.MayUse)
			{
				((Character)user).Message((MessageType)2, Words.T("eoo_msg_notmember", Pieces.TeamNameOf(componentInParent.nview)), 0, (Sprite)null, false);
				__result = true;
				return false;
			}
			if (__instance.HaveAttachment() && !hold && OursOrTemple(__instance, out var _) && !Bosses.Earned(((Object)__instance.m_guardianPower).name))
			{
				string text = Localization.instance.Localize(Bosses.BossName(Bosses.KeyOf(((Object)__instance.m_guardianPower).name)));
				((Character)user).Message((MessageType)2, Words.T("eoo_msg_notearned", text), 0, (Sprite)null, false);
				__result = false;
				return false;
			}
			return true;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ItemStand), "UseItem")]
		private static bool UseItem(ItemStand __instance, Humanoid user, ref bool __result)
		{
			if ((Object)(object)user != (Object)(object)Player.m_localPlayer || !Client.ServerHasMod)
			{
				return true;
			}
			StoneMark componentInParent = ((Component)__instance).GetComponentInParent<StoneMark>();
			if ((Object)(object)componentInParent == (Object)null || componentInParent.MayUse)
			{
				return true;
			}
			((Character)user).Message((MessageType)2, Words.T("eoo_msg_notmember", Pieces.TeamNameOf(componentInParent.nview)), 0, (Sprite)null, false);
			__result = true;
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ItemStand), "GetHoverText")]
		private static void Hover(ItemStand __instance, ref string __result)
		{
			if (!((Object)(object)__instance.m_guardianPower == (Object)null) && Client.ServerHasMod && !((Object)(object)Player.m_localPlayer == (Object)null))
			{
				StoneMark componentInParent = ((Component)__instance).GetComponentInParent<StoneMark>();
				StoneMark mark;
				if ((Object)(object)componentInParent != (Object)null && !componentInParent.MayUse)
				{
					__result = Localization.instance.Localize(__instance.m_name + "\n") + Words.T("eoo_msg_notmember", Pieces.TeamNameOf(componentInParent.nview));
				}
				else if (__instance.HaveAttachment() && OursOrTemple(__instance, out mark) && !Bosses.Earned(((Object)__instance.m_guardianPower).name))
				{
					string text = Localization.instance.Localize(Bosses.BossName(Bosses.KeyOf(((Object)__instance.m_guardianPower).name)));
					__result = Localization.instance.Localize("<color=orange>" + __instance.m_guardianPower.m_name + "</color>\n") + Words.T("eoo_msg_notearned", text);
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Player), "StartGuardianPower")]
		private static bool Power(Player __instance, ref bool __result)
		{
			if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)__instance.m_guardianSE == (Object)null || !Client.ServerHasMod)
			{
				return true;
			}
			if (Bosses.Earned(((Object)__instance.m_guardianSE).name))
			{
				return true;
			}
			((Character)__instance).Message((MessageType)2, "$eoo_msg_power_notearned", 0, (Sprite)null, false);
			__result = false;
			return false;
		}
	}
	internal sealed class TeamData
	{
		internal int Id;

		internal long Owner;

		internal string Name = "";

		internal readonly List<(long id, string name)> Members = new List<(long, string)>();

		internal readonly HashSet<string> Keys = new HashSet<string>();

		internal bool HasStart;

		internal Vector3 Start;

		internal ulong Party;

		internal bool Has(long player)
		{
			return Members.Any(((long id, string name) m) => m.id == player);
		}

		internal string NameOf(long player)
		{
			return Members.FirstOrDefault(((long id, string name) m) => m.id == player).name ?? "";
		}
	}
	internal sealed class Ledger
	{
		internal enum RequestResult
		{
			Sent,
			AlreadyMember,
			NoTeam,
			AlreadyAsked
		}

		internal const byte Format = 1;

		internal int NextId = 1;

		internal readonly Dictionary<int, TeamData> Teams = new Dictionary<int, TeamData>();

		internal readonly Dictionary<long, int> PlayerTeam = new Dictionary<long, int>();

		internal readonly HashSet<string> Legacy = new HashSet<string>();

		internal bool LegacyTaken;

		internal readonly Dictionary<long, (int team, string name)> Pending = new Dictionary<long, (int, string)>();

		internal TeamData TeamOf(long player)
		{
			if (!PlayerTeam.TryGetValue(player, out var value) || !Teams.TryGetValue(value, out var value2))
			{
				return null;
			}
			return value2;
		}

		internal bool Known(long player)
		{
			return TeamOf(player) != null;
		}

		internal TeamData Ensure(long player, string name, ulong party)
		{
			TeamData team = TeamOf(player);
			if (team != null)
			{
				Rename(team, player, name);
				if (party != 0L && team.Party != party && team.Members.Count == 1 && team.Keys.Count == 0)
				{
					TeamData teamData = Teams.Values.FirstOrDefault((TeamData t) => t.Party == party && t.Id != team.Id);
					if (teamData != null)
					{
						Move(player, name, teamData);
						return teamData;
					}
					team.Party = party;
				}
				return team;
			}
			if (party != 0L)
			{
				TeamData teamData2 = Teams.Values.FirstOrDefault((TeamData t) => t.Party == party);
				if (teamData2 != null)
				{
					Move(player, name, teamData2);
					return teamData2;
				}
			}
			team = NewTeam(player, name);
			team.Party = party;
			return team;
		}

		private TeamData NewTeam(long owner, string name)
		{
			TeamData teamData = new TeamData
			{
				Id = NextId++,
				Owner = owner,
				Name = (name ?? "")
			};
			teamData.Members.Add((owner, name ?? ""));
			Teams[teamData.Id] = teamData;
			PlayerTeam[owner] = teamData.Id;
			return teamData;
		}

		private static void Rename(TeamData team, long player, string name)
		{
			if (!string.IsNullOrEmpty(name))
			{
				int num = team.Members.FindIndex(((long id, string name) m) => m.id == player);
				if (num >= 0 && team.Members[num].name != name)
				{
					team.Members[num] = (player, name);
				}
				if (team.Owner == player)
				{
					team.Name = name;
				}
			}
		}

		private void Move(long player, string name, TeamData to)
		{
			TeamData teamData = TeamOf(player);
			if (teamData != to)
			{
				if (teamData != null)
				{
					Remove(teamData, player);
				}
				to.Members.Add((player, name ?? ""));
				PlayerTeam[player] = to.Id;
				Pending.Remove(player);
			}
		}

		private void Remove(TeamData team, long player)
		{
			team.Members.RemoveAll(((long id, string name) m) => m.id == player);
			PlayerTeam.Remove(player);
			if (team.Members.Count == 0)
			{
				Teams.Remove(team.Id);
				{
					foreach (long item in (from p in Pending
						where p.Value.team == team.Id
						select p.Key).ToList())
					{
						Pending.Remove(item);
					}
					return;
				}
			}
			if (team.Owner == player)
			{
				team.Owner = team.Members[0].id;
				team.Name = team.Members[0].name;
			}
		}

		internal RequestResult Request(long player, string name, int teamId)
		{
			if (!Teams.TryGetValue(teamId, out var value))
			{
				return RequestResult.NoTeam;
			}
			if (value.Has(player))
			{
				return RequestResult.AlreadyMember;
			}
			if (Pending.TryGetValue(player, out (int, string) value2) && value2.Item1 == teamId)
			{
				return RequestResult.AlreadyAsked;
			}
			Pending[player] = (teamId, name ?? "");
			return RequestResult.Sent;
		}

		internal bool Answer(long owner, long player, bool accept, out TeamData team)
		{
			team = null;
			if (!Pending.TryGetValue(player, out (int, string) value) || !Teams.TryGetValue(value.Item1, out team) || team.Owner != owner)
			{
				team = null;
				return false;
			}
			Pending.Remove(player);
			if (accept)
			{
				Move(player, value.Item2, team);
			}
			return true;
		}

		internal List<(long player, string name, int team)> AsksFor(long owner)
		{
			TeamData value;
			return (from p in Pending
				where Teams.TryGetValue(p.Value.team, out value) && value.Owner == owner
				select (Key: p.Key, name: p.Value.name, team: p.Value.team)).ToList();
		}

		internal TeamData Leave(long player)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			TeamData teamData = TeamOf(player);
			if (teamData == null || teamData.Members.Count < 2)
			{
				return teamData;
			}
			string name = teamData.NameOf(player);
			Remove(teamData, player);
			TeamData teamData2 = NewTeam(player, name);
			teamData2.HasStart = teamData.HasStart;
			teamData2.Start = teamData.Start;
			return teamData2;
		}

		internal List<TeamData> Credit(IEnumerable<long> players, string key)
		{
			List<TeamData> list = new List<TeamData>();
			foreach (long player in players)
			{
				TeamData teamData = TeamOf(player);
				if (teamData != null && teamData.Keys.Add(key) && !list.Contains(teamData))
				{
					list.Add(teamData);
				}
			}
			return list;
		}

		internal HashSet<string> View(TeamData team, bool legacy)
		{
			IEnumerable<string> collection;
			if (team == null)
			{
				collection = Enumerable.Empty<string>();
			}
			else
			{
				IEnumerable<string> keys = team.Keys;
				collection = keys;
			}
			HashSet<string> hashSet = new HashSet<string>(collection);
			if (legacy)
			{
				hashSet.UnionWith(Legacy);
			}
			return hashSet;
		}

		internal void Write(ZPackage p)
		{
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			p.Write((byte)1);
			p.Write(NextId);
			p.Write(LegacyTaken);
			p.Write(Legacy.Count);
			foreach (string item in Legacy)
			{
				p.Write(item);
			}
			p.Write(Teams.Count);
			foreach (TeamData value in Teams.Values)
			{
				p.Write(value.Id);
				p.Write(value.Owner);
				p.Write(value.Name ?? "");
				p.Write(value.Members.Count);
				foreach (var member in value.Members)
				{
					p.Write(member.id);
					p.Write(member.name ?? "");
				}
				p.Write(value.Keys.Count);
				foreach (string key in value.Keys)
				{
					p.Write(key);
				}
				p.Write(value.HasStart);
				p.Write(value.Start);
				p.Write((long)value.Party);
			}
			p.Write(Pending.Count);
			foreach (KeyValuePair<long, (int, string)> item2 in Pending)
			{
				p.Write(item2.Key);
				p.Write(item2.Value.Item1);
				p.Write(item2.Value.Item2 ?? "");
			}
		}

		internal static Ledger Read(ZPackage p)
		{
			//IL_00f1: 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)
			Ledger ledger = new Ledger();
			if (p.ReadByte() != 1)
			{
				throw new FormatException("unknown ledger format");
			}
			ledger.NextId = p.ReadInt();
			ledger.LegacyTaken = p.ReadBool();
			for (int num = p.ReadInt(); num > 0; num--)
			{
				ledger.Legacy.Add(p.ReadString());
			}
			for (int num2 = p.ReadInt(); num2 > 0; num2--)
			{
				TeamData teamData = new TeamData
				{
					Id = p.ReadInt(),
					Owner = p.ReadLong(),
					Name = p.ReadString()
				};
				for (int num3 = p.ReadInt(); num3 > 0; num3--)
				{
					teamData.Members.Add((p.ReadLong(), p.ReadString()));
				}
				for (int num4 = p.ReadInt(); num4 > 0; num4--)
				{
					teamData.Keys.Add(p.ReadString());
				}
				teamData.HasStart = p.ReadBool();
				teamData.Start = p.ReadVector3();
				teamData.Party = (ulong)p.ReadLong();
				ledger.Teams[teamData.Id] = teamData;
				foreach (var member in teamData.Members)
				{
					ledger.PlayerTeam[member.id] = teamData.Id;
				}
				ledger.NextId = Math.Max(ledger.NextId, teamData.Id + 1);
			}
			for (int num5 = p.ReadInt(); num5 > 0; num5--)
			{
				long key = p.ReadLong();
				int num6 = p.ReadInt();
				string item = p.ReadString();
				if (ledger.Teams.ContainsKey(num6))
				{
					ledger.Pending[key] = (num6, item);
				}
			}
			return ledger;
		}
	}
	internal sealed class TeamView
	{
		internal const byte Format = 1;

		internal int Id;

		internal long Owner;

		internal string Name = "";

		internal readonly List<(long id, string name)> Members = new List<(long, string)>();

		internal readonly HashSet<string> Keys = new HashSet<string>();

		internal int Asks;

		internal static void Write(ZPackage p, TeamData team, HashSet<string> keys, int asks)
		{
			p.Write((byte)1);
			p.Write(team.Id);
			p.Write(team.Owner);
			p.Write(team.Name ?? "");
			p.Write(team.Members.Count);
			foreach (var member in team.Members)
			{
				p.Write(member.id);
				p.Write(member.name ?? "");
			}
			p.Write(keys.Count);
			foreach (string key in keys)
			{
				p.Write(key);
			}
			p.Write(asks);
		}

		internal static TeamView Read(ZPackage p)
		{
			if (p.ReadByte() != 1)
			{
				return null;
			}
			TeamView teamView = new TeamView
			{
				Id = p.ReadInt(),
				Owner = p.ReadLong(),
				Name = p.ReadString()
			};
			for (int num = p.ReadInt(); num > 0; num--)
			{
				teamView.Members.Add((p.ReadLong(), p.ReadString()));
			}
			for (int num2 = p.ReadInt(); num2 > 0; num2--)
			{
				teamView.Keys.Add(p.ReadString());
			}
			teamView.Asks = p.ReadInt();
			return teamView;
		}
	}
	internal static class SteamParty
	{
		private const BindingFlags Static = BindingFlags.Static | BindingFlags.Public;

		private static Type api;

		private static bool looked;

		private static Func<bool> inParty;

		private static Func<ulong> partyId;

		private static float warned;

		internal static ulong PartyId
		{
			get
			{
				Look();
				if (partyId == null)
				{
					return 0uL;
				}
				try
				{
					return (inParty != null && !inParty()) ? 0 : partyId();
				}
				catch (Exception ex)
				{
					if (Time.unscaledTime > warned)
					{
						warned = Time.unscaledTime + 60f;
						Plugin.Warn("SteamFriends party: " + ex.Message);
					}
					return 0uL;
				}
			}
		}

		private static void Look()
		{
			if (!looked)
			{
				looked = true;
				api = AccessTools.TypeByName("SteamFriendsTab.PartyApi");
				if (!(api == null))
				{
					inParty = Getter<bool>("InParty");
					partyId = Getter<ulong>("PartyId");
					Plugin.Log((partyId != null) ? "SteamFriends' party is read (PartyApi)" : "SteamFriends has no PartyApi.PartyId: parties are not teams");
				}
			}
		}

		private static Func<T> Getter<T>(string name)
		{
			MethodInfo methodInfo = api?.GetProperty(name, BindingFlags.Static | BindingFlags.Public)?.GetGetMethod();
			if ((object)methodInfo == null || !(methodInfo.ReturnType == typeof(T)))
			{
				return null;
			}
			return (Func<T>)Delegate.CreateDelegate(typeof(Func<T>), methodInfo);
		}
	}
	internal static class Planet
	{
		private delegate bool GeneratedSample(Vector3 direction, out float height, out Biome biome);

		private const BindingFlags Static = BindingFlags.Static | BindingFlags.Public;

		private static readonly Type Api = AccessTools.TypeByName("PlanetPrototype.PlanetApi");

		private static readonly Func<bool> active = Getter<bool>("Active");

		private static readonly Func<float> radius = Getter<float>("Radius");

		private static readonly Func<Vector3> startDirection = Getter<Vector3>("StartDirection");

		private static readonly Func<Vector3, Vector3> up = Function<Func<Vector3, Vector3>>("Up", new Type[1] { typeof(Vector3) });

		private static readonly Func<Vector3, Vector2> latLon = Function<Func<Vector3, Vector2>>("LatLon", new Type[1] { typeof(Vector3) });

		private static readonly Func<float, float, float, Vector3> fromLatLon = Function<Func<float, float, float, Vector3>>("FromLatLon", new Type[3]
		{
			typeof(float),
			typeof(float),
			typeof(float)
		});

		private static readonly GeneratedSample sample = Function<GeneratedSample>("GeneratedSample", new Type[3]
		{
			typeof(Vector3),
			typeof(float).MakeByRefType(),
			typeof(Biome).MakeByRefType()
		});

		internal static bool Active
		{
			get
			{
				if (active != null && active() && sample != null && fromLatLon != null && latLon != null && startDirection != null)
				{
					return radius != null;
				}
				return false;
			}
		}

		internal static float Radius
		{
			get
			{
				if (radius == null)
				{
					return 0f;
				}
				return radius();
			}
		}

		internal static Vector3 StartDirection
		{
			get
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				if (startDirection == null)
				{
					return Vector3.up;
				}
				return startDirection();
			}
		}

		private static Func<T> Getter<T>(string name)
		{
			MethodInfo methodInfo = Api?.GetProperty(name, BindingFlags.Static | BindingFlags.Public)?.GetGetMethod();
			if ((object)methodInfo == null)
			{
				return null;
			}
			return (Func<T>)Delegate.CreateDelegate(typeof(Func<T>), methodInfo);
		}

		private static T Function<T>(string name, params Type[] parameters) where T : Delegate
		{
			MethodInfo methodInfo = Api?.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameters, null);
			if ((object)methodInfo == null)
			{
				return null;
			}
			return (T)Delegate.CreateDelegate(typeof(T), methodInfo, throwOnBindFailure: false);
		}

		internal static Vector3 Up(Vector3 point)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			if (up == null)
			{
				return Vector3.up;
			}
			return up(point);
		}

		internal static bool Sample(Vector3 direction, out float aboveSea, out bool meadows)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			aboveSea = 0f;
			meadows = false;
			if (sample == null || !sample(direction, out aboveSea, out var biome))
			{
				return false;
			}
			meadows = (int)biome == 1;
			return true;
		}

		internal static Vector3 PointAt(Vector3 direction, float aboveSea)
		{
			//IL_0007: 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_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = latLon(((Vector3)(ref direction)).normalized * Radius);
			return fromLatLon(val.x, val.y, aboveSea);
		}
	}
	internal static class Rpc
	{
		internal const string Hello = "EoO_Hello";

		internal const string State = "EoO_State";

		internal const string Start = "EoO_Start";

		internal const string Boss = "EoO_Boss";

		internal const string Ask = "EoO_Ask";

		internal const string Asked = "EoO_Asked";

		internal const string Answer = "EoO_Answer";

		internal const string Leave = "EoO_Leave";

		internal const string Msg = "EoO_Msg";

		internal const byte Format = 3;
	}
	internal sealed class HostRules
	{
		internal bool RandomStart = true;

		internal bool PerTeam = true;

		internal bool KeysToCharacter = true;

		internal bool TempleNeedsKill = true;

		internal bool HideTempleStones = true;

		internal Plugin.Respawn RespawnWithoutBed;

		internal int StoneRadius = 25;

		internal string ShrineRecipe = "Stone:20,Wood:10";

		internal string StoneRecipe = "Stone:15,Wood:5";

		internal Dictionary<string, string> StoneRecipes = Defaults();

		internal string RecipesKey => ShrineRecipe + "|" + StoneRecipe + "|" + string.Join(";", from p in StoneRecipes
			orderby p.Key
			select p.Key + "=" + p.Value);

		private static Dictionary<string, string> Defaults()
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			(string, string, string, string)[] biomeStones = RecipeText.BiomeStones;
			for (int i = 0; i < biomeStones.Length; i++)
			{
				(string, string, string, string) tuple = biomeStones[i];
				dictionary[tuple.Item1] = tuple.Item4;
			}
			return dictionary;
		}

		internal static HostRules Local()
		{
			if (Plugin.RandomStart != null)
			{
				return new HostRules
				{
					RandomStart = Plugin.RandomStart.Value,
					PerTeam = Plugin.PerTeam.Value,
					KeysToCharacter = Plugin.KeysToCharacter.Value,
					TempleNeedsKill = Plugin.TempleNeedsKill.Value,
					HideTempleStones = Plugin.HideTempleStones.Value,
					RespawnWithoutBed = Plugin.RespawnWithoutBed.Value,
					StoneRadius = Plugin.StoneRadius.Value,
					ShrineRecipe = Plugin.ShrineRecipe.Value,
					StoneRecipe = Plugin.StoneRecipe.Value,
					StoneRecipes = Plugin.StoneRecipes.ToDictionary((KeyValuePair<string, ConfigEntry<string>> p) => p.Key, (KeyValuePair<string, ConfigEntry<string>> p) => p.Value.Value)
				};
			}
			return new HostRules();
		}

		internal void Write(ZPackage p)
		{
			p.Write(RandomStart);
			p.Write(PerTeam);
			p.Write(KeysToCharacter);
			p.Write(TempleNeedsKill);
			p.Write(HideTempleStones);
			p.Write((int)RespawnWithoutBed);
			p.Write(StoneRadius);
			p.Write(ShrineRecipe ?? "");
			p.Write(StoneRecipe ?? "");
			p.Write(StoneRecipes.Count);
			foreach (KeyValuePair<string, string> stoneRecipe in StoneRecipes)
			{
				p.Write(stoneRecipe.Key);
				p.Write(stoneRecipe.Value ?? "");
			}
		}

		internal static HostRules Read(ZPackage p)
		{
			HostRules hostRules = new HostRules
			{
				RandomStart = p.ReadBool(),
				PerTeam = p.ReadBool(),
				KeysToCharacter = p.ReadBool(),
				TempleNeedsKill = p.ReadBool(),
				HideTempleStones = p.ReadBool(),
				RespawnWithoutBed = (Plugin.Respawn)p.ReadInt(),
				StoneRadius = p.ReadInt(),
				ShrineRecipe = p.ReadString(),
				StoneRecipe = p.ReadString()
			};
			hostRules.StoneRecipes = new Dictionary<string, string>();
			for (int num = p.ReadInt(); num > 0; num--)
			{
				string key = p.ReadString();
				string value = p.ReadString();
				hostRules.StoneRecipes[key] = value;
			}
			return hostRules;
		}

		internal bool SameRecipes(HostRules o)
		{
			if (o != null)
			{
				return o.RecipesKey == RecipesKey;
			}
			return false;
		}
	}
	internal static class Pieces
	{
		internal const string ShrineName = "EoO_Shrine";

		internal const string TeamKey = "eoo_team";

		internal const string TeamNameKey = "eoo_teamname";

		private static GameObject holder;

		internal static GameObject Shrine;

		internal static GameObject Ledger;

		internal static readonly List<GameObject> Stones = new List<GameObject>();

		private static readonly HashSet<int> ours = new HashSet<int>();

		private static string applied;

		private static readonly Dictionary<string, string> DefaultStoneRecipes = RecipeText.BiomeStones.ToDictionary(((string key, string biomeEn, string biomeRu, string recipe) s) => s.key, ((string key, string biomeEn, string biomeRu, string recipe) s) => s.recipe);

		private static bool ItemsReady
		{
			get
			{
				if ((Object)(object)ObjectDB.instance != (Object)null && ObjectDB.instance.m_items != null && ObjectDB.instance.m_items.Count > 0)
				{
					return (Object)(object)ObjectDB.instance.GetItemPrefab("Wood") != (Object)null;
				}
				return false;
			}
		}

		internal static bool IsStone(Piece piece)
		{
			if ((Object)(object)piece != (Object)null)
			{
				return (Object)(object)((Component)piece).GetComponent<StoneMark>() != (Object)null;
			}
			return false;
		}

		internal static bool IsShrine(Piece piece)
		{
			if ((Object)(object)piece != (Object)null)
			{
				return (Object)(object)((Component)piece).GetComponent<Shrine>() != (Object)null;
			}
			return false;
		}

		internal static void Register(ZNetScene scene)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			Bosses.Learn(scene);
			if ((Object)(object)holder == (Object)null)
			{
				holder = new GameObject("EnvoysOfOdin prefabs");
				holder.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)holder);
			}
			if ((Object)(object)Ledger == (Object)null)
			{
				Ledger = new GameObject("EoO_Ledger");
				Ledger.transform.SetParent(holder.transform, false);
				Ledger.AddComponent<ZNetView>().m_persistent = true;
			}
			if ((Object)(object)Shrine == (Object)null)
			{
				try
				{
					Shrine = BuildShrine(scene);
				}
				catch (Exception ex)
				{
					Plugin.Warn("the Shrine of Odin was not made: " + ex);
					Shrine = null;
				}
			}
			if (Stones.Count == 0)
			{
				Words.Stones.Clear();
				foreach (GameObject stonePrefab in Bosses.StonePrefabs)
				{
					try
					{
						GameObject val = BuildStone(stonePrefab);
						if ((Object)(object)val != (Object)null)
						{
							Stones.Add(val);
						}
					}
					catch (Exception ex2)
					{
						Plugin.Warn("the stone from " + ((Object)stonePrefab).name + " was not made: " + ex2.Message);
					}
				}
				Words.Refresh();
			}
			foreach (GameObject item in ((IEnumerable<GameObject>)(object)new GameObject[2] { Ledger, Shrine }).Concat(Stones))
			{
				if (!((Object)(object)item == (Object)null))
				{
					if (!scene.m_prefabs.Contains(item))
					{
						scene.m_prefabs.Add(item);
					}
					scene.m_namedPrefabs[StringExtensionMethods.GetStableHashCode(((Object)item).name)] = item;
					ours.Add(StringExtensionMethods.GetStableHashCode(((Object)item).name));
				}
			}
			ApplyRecipes();
			Hammer();
		}

		private static void Strip(GameObject go)
		{
			GuidePoint[] componentsInChildren = go.GetComponentsInChildren<GuidePoint>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
		}

		private static GameObject BuildShrine(ZNetScene scene)
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			GameObject prefab = scene.GetPrefab("StartPlatform");
			if ((Object)(object)prefab == (Object)null)
			{
				Plugin.Warn("the game has no StartPlatform prefab: no Shrine of Odin");
				return null;
			}
			GameObject val = Object.Instantiate<GameObject>(prefab, holder.transform, false);
			((Object)val).name = "EoO_Shrine";
			Strip(val);
			BossStone[] componentsInChildren = val.GetComponentsInChildren<BossStone>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
			ItemStand[] componentsInChildren2 = val.GetComponentsInChildren<ItemStand>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
			}
			Piece obj = val.GetComponent<Piece>() ?? val.AddComponent<Piece>();
			obj.m_name = "$eoo_shrine";
			obj.m_description = "$eoo_shrine_desc";
			obj.m_icon = Icon(scene, "Thunderstone");
			obj.m_category = (PieceCategory)0;
			obj.m_groundOnly = true;
			obj.m_noInWater = true;
			obj.m_clipGround = true;
			obj.m_canBeRemoved = true;
			obj.m_allowedInDungeons = false;
			obj.m_placeEffect = PlaceEffect(scene);
			val.AddComponent<Shrine>();
			Plugin.Log("EoO_Shrine made from StartPlatform");
			return val;
		}

		private static GameObject BuildStone(GameObject src)
		{
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			ItemStand itemStand = src.GetComponent<BossStone>().m_itemStand;
			GameObject val = Object.Instantiate<GameObject>(src, holder.transform, false);
			((Object)val).name = "EoO_" + ((Object)src).name;
			Strip(val);
			val.GetComponent<BossStone>().m_setsWorldKey = "";
			string name = ((Object)itemStand.m_guardianPower).name;
			string text = "eoo_stone_" + name.ToLowerInvariant();
			Words.Stones.Add((text, itemStand.m_guardianPower.m_name));
			Piece obj = val.GetComponent<Piece>() ?? val.AddComponent<Piece>();
			obj.m_name = "$" + text;
			obj.m_description = "$eoo_stone_desc";
			Sprite[] array = ((IEnumerable<ItemDrop>)itemStand.m_supportedItems).FirstOrDefault((Func<ItemDrop, bool>)((ItemDrop i) => (Object)(object)i != (Object)null))?.m_itemData?.m_shared?.m_icons;
			obj.m_icon = ((array != null && array.Length != 0) ? array[0] : (((Object)(object)Shrine != (Object)null) ? Shrine.GetComponent<Piece>().m_icon : null));
			obj.m_category = (PieceCategory)0;
			obj.m_groundOnly = true;
			obj.m_noInWater = true;
			obj.m_clipGround = true;
			obj.m_canBeRemoved = true;
			obj.m_allowedInDungeons = false;
			obj.m_placeEffect = (EffectList)(((Object)(object)Shrine != (Object)null) ? ((object)Shrine.GetComponent<Piece>().m_placeEffect) : ((object)new EffectList()));
			val.AddComponent<StoneMark>().Power = name;
			return val;
		}

		private static Sprite Icon(ZNetScene scene, string item)
		{
			GameObject prefab = scene.GetPrefab(item);
			Sprite[] array = ((prefab == null) ? null : prefab.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_icons);
			if (array == null || array.Length == 0)
			{
				return null;
			}
			return array[0];
		}

		private static EffectList PlaceEffect(ZNetScene scene)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			GameObject prefab = scene.GetPrefab("stone_wall_1x1");
			Piece val = ((prefab != null) ? prefab.GetComponent<Piece>() : null);
			if (!((Object)(object)val != (Object)null))
			{
				return new EffectList();
			}
			return val.m_placeEffect;
		}

		internal static void Hammer()
		{
			GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab("Hammer") : null);
			PieceTable val2 = ((!((Object)(object)val != (Object)null)) ? null : val.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_buildPieces);
			if ((Object)(object)val2 == (Object)null)
			{
				return;
			}
			foreach (GameObject item in ((IEnumerable<GameObject>)(object)new GameObject[1] { Shrine }).Concat(Stones))
			{
				if ((Object)(object)item != (Object)null && !val2.m_pieces.Contains(item))
				{
					val2.m_pieces.Add(item);
				}
			}
		}

		internal static void ApplyRecipes()
		{
			if (!ItemsReady)
			{
				return;
			}
			HostRules hostRules = (Client.ServerHasMod ? Client.Rules : HostRules.Local());
			string text = hostRules.RecipesKey + "|" + ((Object)ObjectDB.instance).GetInstanceID() + "|" + Stones.Count + "|" + ((Object)(object)Shrine != (Object)null);
			if (text == applied)
			{
				return;
			}
			string shrineRecipe = hostRules.ShrineRecipe;
			ConfigEntry<string> shrineRecipe2 = Plugin.ShrineRecipe;
			Requirement[] array = Requirements(shrineRecipe, ((shrineRecipe2 != null) ? ((ConfigEntryBase)shrineRecipe2).DefaultValue : null) as string);
			if ((Object)(object)Shrine != (Object)null && array != null)
			{
				Shrine.GetComponent<Piece>().m_resources = array;
			}
			StringBuilder stringBuilder = new StringBuilder("costs: shrine " + Describe(array));
			foreach (GameObject stone in Stones)
			{
				string text2 = Bosses.KeyOf(stone.GetComponent<StoneMark>().Power);
				string recipe = RecipeText.StoneFor(text2, hostRules.StoneRecipes, hostRules.StoneRecipe);
				Dictionary<string, string> defaultStoneRecipes = DefaultStoneRecipes;
				ConfigEntry<string> stoneRecipe = Plugin.StoneRecipe;
				string fallback = RecipeText.StoneFor(text2, defaultStoneRecipes, ((stoneRecipe != null) ? ((ConfigEntryBase)stoneRecipe).DefaultValue : null) as string);
				Requirement[] array2 = Requirements(recipe, fallback);
				if (array2 != null)
				{
					stone.GetComponent<Piece>().m_resources = array2;
				}
				stringBuilder.Append("; " + ((Object)stone).name + " (" + (text2 ?? "?") + ") " + Describe(array2));
			}
			applied = text;
			Plugin.Debug(stringBuilder.ToString());
		}

		private static string Describe(Requirement[] r)
		{
			if (r != null)
			{
				return string.Join(", ", r.Select((Requirement x) => ((Object)x.m_resItem).name + ":" + x.m_amount));
			}
			return "(kept)";
		}

		private static Requirement[] Requirements(string recipe, string fallback)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			List<Requirement> list = new List<Requirement>();
			foreach (var item3 in RecipeText.Parse(recipe))
			{
				string item = item3.name;
				int item2 = item3.amount;
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(item);
				ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Warn("recipe: no item '" + item + "' in the game (the setting's value: '" + recipe + "')");
				}
				else
				{
					list.Add(new Requirement
					{
						m_resItem = val,
						m_amount = item2,
						m_recover = true
					});
				}
			}
			if (list.Count == 0)
			{
				if (fallback == null || !(fallback != recipe))
				{
					return null;
				}
				return Requirements(fallback, null);
			}
			return list.ToArray();
		}

		internal static int TeamOf(ZNetView nview)
		{
			if (!((Object)(object)nview != (Object)null) || !nview.IsValid())
			{
				return 0;
			}
			return nview.GetZDO().GetInt("eoo_team", 0);
		}

		internal static string TeamNameOf(ZNetView nview)
		{
			if (!((Object)(object)nview != (Object)null) || !nview.IsValid())
			{
				return "";
			}
			return nview.GetZDO().GetString("eoo_teamname", "");
		}

		internal static bool NearOwnShrine(Vector3 point)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (Client.View == null)
			{
				return false;
			}
			float num = Client.Rules.StoneRadius;
			foreach (Shrine item in EnvoysOfOdin.Shrine.All)
			{
				if ((Object)(object)item != (Object)null && Client.Member(TeamOf(item.nview)) && Vector3.Distance(((Component)item).transform.position, point) <= num)
				{
					return true;
				}
			}
			return false;
		}
	}
	public sealed class StoneMark : MonoBehaviour, IRemoved
	{
		public string Power;

		internal ZNetView nview;

		internal ItemStand stand;

		internal int Team => Pieces.TeamOf(nview);

		internal bool MayUse => Access.MayUseStone(Team, (Client.View != null) ? Client.View.Id : 0, Client.ServerHasMod);

		private void Awake()
		{
			nview = ((Component)this).GetComponent<ZNetView>();
			stand = ((Component)this).GetComponentInChildren<ItemStand>();
		}

		public void OnRemoved()
		{
			if (!((Object)(object)stand == (Object)null) && !((Object)(object)nview == (Object)null) && nview.IsValid() && stand.HaveAttachment())
			{
				nview.ClaimOwnership();
				stand.DropItem();
			}
		}
	}
	public sealed class Shrine : MonoBehaviour, Hoverable, Interactable
	{
		internal static readonly List<Shrine> All = new List<Shrine>();

		internal ZNetView nview;

		private void Awake()
		{
			nview = ((Component)this).GetComponent<ZNetView>();
			All.Add(this);
		}

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

		public string GetHoverName()
		{
			return Localization.instance.Localize("$eoo_shrine");
		}

		public string GetHoverText()
		{
			Localization l = Localization.instance;
			int num = Pieces.TeamOf(nview);
			string value = Pieces.TeamNameOf(nview);
			StringBuilder stringBuilder = new StringBuilder("$eoo_shrine");
			if (num == 0)
			{
				stringBuilder.Append("\n$eoo_noteam");
				return l.Localize(stringBuilder.ToString());
			}
			if (Client.Member(num))
			{
				TeamView v = Client.View;
				stringBuilder.Append("\n$eoo_yourteam: ").Append(v.Name);
				stringBuilder.Append("\n$eoo_members: ").Append(string.Join(", ", v.Members.Select(((long id, string name) m) => m.name)));
				List<string> list = (from k in Bosses.Keys
					where v.Keys.Contains(k)
					select l.Localize(Bosses.BossName(k))).Distinct().ToList();
				stringBuilder.Append("\n$eoo_bosses: ").Append((list.Count > 0) ? string.Join(", ", list) : "$eoo_none");
				if (v.Owner == Client.Me && Client.HaveAsks)
				{
					stringBuilder.Append("\n[<color=yellow><b>$KEY_Use</b></color>] $eoo_show_asks");
				}
				if (v.Members.Count > 1)
				{
					stringBuilder.Append("\n[<color=yellow><b>$KEY_AltPlace + $KEY_Use</b></color>] $eoo_leave");
				}
			}
			else
			{
				stringBuilder.Append("\n$eoo_team: ").Append(value);
				stringBuilder.Append("\n[<color=yellow><b>$KEY_Use</b></color>] $eoo_ask");
			}
			return l.Localize(stringBuilder.ToString());
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			if (hold || (Object)(object)user != (Object)(object)Player.m_localPlayer)
			{
				return false;
			}
			int num = Pieces.TeamOf(nview);
			if (num == 0)
			{
				return false;
			}
			if (!Client.ServerHasMod)
			{
				Client.Message("eoo_msg_noserver");
				return true;
			}
			if (Client.Member(num))
			{
				if (alt)
				{
					Client.AskLeave();
					return true;
				}
				if (Client.View.Owner == Client.Me)
				{
					Client.ShowAsks();
					return true;
				}
				return false;
			}
			Client.Ask(num);
			return true;
		}

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

		public float GetHoverOffset()
		{
			return 0f;
		}
	}
	[HarmonyPatch]
	internal static class PieceHooks
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static void Scene(ZNetScene __instance)
		{
			Pieces.Register(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		private static void Db()
		{
			Pieces.ApplyRecipes();
			Pieces.Hammer();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
		private static void DbCopy()
		{
			Pieces.ApplyRecipes();
			Pieces.Hammer();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Piece), "SetCreator")]
		private static void Creator(Piece __instance)
		{
			if (Pieces.IsShrine(__instance) || Pieces.IsStone(__instance))
			{
				ZNetView nview = __instance.m_nview;
				if (!((Object)(object)nview == (Object)null) && nview.IsValid() && nview.IsOwner() && Client.View != null && nview.GetZDO().GetInt("eoo_team", 0) == 0)
				{
					nview.GetZDO().Set("eoo_team", Client.View.Id);
					nview.GetZDO().Set("eoo_teamname", Client.View.Name ?? "");
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Player), "TryPlacePiece")]
		private static bool Place(Player __instance, Piece piece, ref bool __result)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			bool num = Pieces.IsShrine(piece);
			bool flag = Pieces.IsStone(piece);
			if ((!num && !flag) || !Client.ServerHasMod)
			{
				return true;
			}
			if (Client.View == null)
			{
				((Character)__instance).Message((MessageType)2, "$eoo_msg_unknown", 0, (Sprite)null, false);
				__result = false;
				return false;
			}
			if (flag && (Object)(object)__instance.m_placementGhost != (Object)null && !Pieces.NearOwnShrine(__instance.m_placementGhost.transform.position))
			{
				((Character)__instance).Message((MessageType)2, "$eoo_msg_needshrine", 0, (Sprite)null, false);
				__result = false;
				return false;
			}
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
		private static void Ghost(Player __instance)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: 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)
			GameObject placementGhost = __instance.m_placementGhost;
			if (!((Object)(object)placementGhost == (Object)null) && Client.ServerHasMod && (int)__instance.m_placementStatus == 0 && Pieces.IsStone(placementGhost.GetComponent<Piece>()) && !Pieces.NearOwnShrine(placementGhost.transform.position))
			{
				__instance.m_placementStatus = (PlacementStatus)1;
				__instance.SetPlacementGhostValid(false);
			}
		}
	}
	[BepInPlugin("chistix.envoysofodin", "Envoys of Odin", "0.1.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal enum Respawn
		{
			TeamStart,
			GameStart
		}

		public const string Guid = "chistix.envoysofodin";

		public const string Version = "0.1.3";

		private static ManualLogSource log;

		internal static ConfigEntry<bool> RandomStart;

		internal static ConfigEntry<bool> PerTeam;

		internal static ConfigEntry<bool> KeepOldKills;

		internal static ConfigEntry<bool> KeysToCharacter;

		internal static ConfigEntry<bool> TempleNeedsKill;

		internal static ConfigEntry<bool> HideTempleStones;

		internal static ConfigEntry<bool> PartyIsTeam;

		internal static ConfigEntry<bool> DebugLog;

		internal static ConfigEntry<Respawn> RespawnWithoutBed;

		internal static ConfigEntry<int> KeepFromTemple;

		internal static ConfigEntry<int> MemberSpread;

		internal static ConfigEntry<int> Candidates;

		internal static ConfigEntry<int> NearRadius;

		internal static ConfigEntry<int> StoneRadius;

		internal static ConfigEntry<int> GridStep;

		internal static ConfigEntry<string> ShrineRecipe;

		internal static ConfigEntry<string> StoneRecipe;

		internal static readonly Dictionary<string, ConfigEntry<string>> StoneRecipes = new Dictionary<string, ConfigEntry<string>>();

		private const string HostEn = " The world's host's value counts (alone - yours; on a server - the server's).";

		private const string HostRu = " Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).";

		private void Awake()
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Expected O, but got Unknown
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Expected O, but got Unknown
			//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ef: Expected O, but got Unknown
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			log = ((BaseUnityPlugin)this).Logger;
			RandomStart = ((BaseUnityPlugin)this).Config.Bind<bool>("Start", "RandomStart", true, "A new character lands at a random point of the start meadows (the meadows of the start's own island or continent), not at the start temple. Members of one team land together. The world's host's value counts (alone - yours; on a server - the server's).\nНовый персонаж прилетает в случайную точку стартовых лугов (луга острова или материка, где старт игры), а не к стартовому храму. Команда появляется рядом. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			RespawnWithoutBed = ((BaseUnityPlugin)this).Config.Bind<Respawn>("Start", "RespawnWithoutBed", Respawn.TeamStart, "Death with no bed: TeamStart - at the team's start; GameStart - at the start temple, as the game does. A bed is always the game's own. The world's host's value counts (alone - yours; on a server - the server's).\nСмерть без кровати: TeamStart — у старта команды; GameStart — у стартового храма, как в игре. Кровать всегда работает как в игре. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			KeepFromTemple = ((BaseUnityPlugin)this).Config.Bind<int>("Start", "KeepFromTemple", 150, new ConfigDescription("How far from the start temple a team's start must be, m. The world's host's value counts (alone - yours; on a server - the server's).\nНасколько далеко от стартового храма должен быть старт команды, м. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 2000), Array.Empty<object>()));
			MemberSpread = ((BaseUnityPlugin)this).Config.Bind<int>("Start", "MemberSpread", 10, new ConfigDescription("Members of a team land this far from the team's start at most, m. The world's host's value counts (alone - yours; on a server - the server's).\nУчастники команды появляются не дальше этого от старта команды, м. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 60), Array.Empty<object>()));
			Candidates = ((BaseUnityPlugin)this).Config.Bind<int>("Start", "Candidates", 12, new ConfigDescription("A new team's start: of this many random meadow points the one farthest from the other teams (1 - fully random). The world's host's value counts (alone - yours; on a server - the server's).\nСтарт новой команды: из стольких случайных точек лугов берётся самая далёкая от других команд (1 — совсем случайно). Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 64), Array.Empty<object>()));
			GridStep = ((BaseUnityPlugin)this).Config.Bind<int>("Start", "GridStep", 48, new ConfigDescription("The step of the search for the start meadows, m (smaller - finer and slower; narrow land bridges are crossed only by a fine step). The world's host's value counts (alone - yours; on a server - the server's).\nШаг поиска стартовых лугов, м (меньше — точнее и дольше; узкие перешейки проходятся только мелким шагом). Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(16, 256), Array.Empty<object>()));
			PerTeam = ((BaseUnityPlugin)this).Config.Bind<bool>("Progress", "PerTeamProgress", true, "The bosses' victories are a team's own: what the game opens for a victory (defeated_* keys: the trader's goods, raids, spawns, tutorials) and the gods' powers come only with the team's own kill. The world's host's value counts (alone - yours; on a server - the server's).\nПобеды над боссами у каждой команды свои: всё, что игра открывает за победу (ключи defeated_*: товары торговца, набеги, появление существ, подсказки), и силы богов — только после своего убийства. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			KeepOldKills = ((BaseUnityPlugin)this).Config.Bind<bool>("Progress", "KeepOldWorldKills", true, "Bosses slain in this world before the mod came (the keys it had then) count for every team. The world's host's value counts (alone - yours; on a server - the server's).\nБоссы, убитые в этом мире до установки мода (ключи, что уже были), засчитываются всем командам. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			NearRadius = ((BaseUnityPlugin)this).Config.Bind<int>("Progress", "NearRadius", 50, new ConfigDescription("A boss counts for everyone who hit it and everyone this near when it fell, m, and for their teams. The world's host's value counts (alone - yours; on a server - the server's).\nУбийство босса засчитывается всем, кто его бил, и всем, кто был ближе этого в момент смерти, м, и их командам. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300), Array.Empty<object>()));
			KeysToCharacter = ((BaseUnityPlugin)this).Config.Bind<bool>("Progress", "TeamKeysToCharacter", true, "A member also gets the team's victories as the character's own keys (the game's raids by player progress read them). The world's host's value counts (alone - yours; on a server - the server's).\nУчастник получает победы команды и как ключи своего персонажа (по ним игра выбирает набеги по прогрессу игрока). Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			TempleNeedsKill = ((BaseUnityPlugin)this).Config.Bind<bool>("Progress", "StartTempleNeedsKill", true, "When the start temple's stones are shown (HideTempleStones off): their powers too need the team's own kill. The world's host's value counts (alone - yours; on a server - the server's).\nЕсли камни стартового храма видны (HideTempleStones выключено): их силы тоже только после убийства босса своей командой. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			HideTempleStones = ((BaseUnityPlugin)this).Config.Bind<bool>("Shrine", "HideTempleStones", true, "The start temple's guardian stones are hidden for every player: each team has its own stones at its shrine. Nothing is removed from the world: trophies hung there stay, and without the mod (or with this off) the stones are back. The world's host's value counts (alone - yours; on a server - the server's).\nКамни силы стартового храма скрыты у всех игроков: у каждой команды свои камни у святилища. Из мира ничего не удаляется: повешенные там трофеи остаются, а без мода (или с выключенной настройкой) камни возвращаются. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			ShrineRecipe = ((BaseUnityPlugin)this).Config.Bind<string>("Shrine", "Recipe", "Stone:20,Wood:10", "The Shrine of Odin's cost (hammer, no station): prefab:amount, comma-separated. The world's host's value counts (alone - yours; on a server - the server's).\nСтоимость святилища Одина (молот, без станции): префаб:количество через запятую. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			StoneRecipe = ((BaseUnityPlugin)this).Config.Bind<string>("Shrine", "StoneRecipe", "Stone:15,Wood:5", "The cost of a guardian stone whose boss has no line in [Stones] (a boss the game or a mod adds later): prefab:amount, comma-separated. The world's host's value counts (alone - yours; on a server - the server's).\nСтоимость камня силы босса, которого нет в [Stones] (босс, добавленный игрой или модом позже): префаб:количество через запятую. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			(string, string, string, string)[] biomeStones = RecipeText.BiomeStones;
			for (int i = 0; i < biomeStones.Length; i++)
			{
				var (text, text2, text3, text4) = biomeStones[i];
				StoneRecipes[text] = ((BaseUnityPlugin)this).Config.Bind<string>("Stones", text, text4, "The guardian stone of this boss (" + text2 + "): its biome's resources, prefab:amount, comma-separated. The world's host's value counts (alone - yours; on a server - the server's).\nКамень силы этого босса (" + text3 + "): ресурсы его биома, префаб:количество через запятую. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			}
			StoneRadius = ((BaseUnityPlugin)this).Config.Bind<int>("Shrine", "StoneRadius", 25, new ConfigDescription("Guardian stones are built this near the team's shrine, m. The world's host's value counts (alone - yours; on a server - the server's).\nКамни силы ставятся не дальше этого от святилища команды, м. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 100), Array.Empty<object>()));
			PartyIsTeam = ((BaseUnityPlugin)this).Config.Bind<bool>("SteamFriends", "PartyIsTeam", true, "With SteamFriends: a party that comes into the world together is one team. The world's host's value counts (alone - yours; on a server - the server's).\nСо SteamFriends: отряд, вошедший в мир вместе, — одна команда. Действует значение хоста мира (в одиночной игре — ваше; на сервере — серверное).");
			DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DebugLog", false, "Write the teams' steps to the log.\nПисать шаги команд в журнал.");
			((BaseUnityPlugin)this).Config.SettingChanged += delegate(object _, SettingChangedEventArgs args)
			{
				if (args.ChangedSetting.Definition.Section != "General")
				{
					Server.RulesChanged();
				}
			};
			Words.Ensure();
			new Harmony("chistix.envoysofodin").PatchAll(typeof(Plugin).Assembly);
			log.LogInfo((object)"Envoys of Odin 0.1.3");
		}

		private void Update()
		{
			Client.Tick();
			Server.Tick();
		}

		internal static void Log(string text)
		{
			ManualLogSource obj = log;
			if (obj != null)
			{
				obj.LogInfo((object)text);
			}
		}

		internal static void Warn(string text)
		{
			ManualLogSource obj = log;
			if (obj != null)
			{
				obj.LogWarning((object)text);
			}
		}

		internal static void Debug(string text)
		{
			if (DebugLog != null && DebugLog.Value)
			{
				ManualLogSource obj = log;
				if (obj != null)
				{
					obj.LogInfo((object)text);
				}
			}
		}
	}
	internal static class RecipeText
	{
		internal static readonly (string key, string biomeEn, string biomeRu, string recipe)[] BiomeStones = new(string, string, string, string)[8]
		{
			("defeated_eikthyr", "Meadows", "Луга", "Stone:15,Wood:10,Flint:5"),
			("defeated_gdking", "Black Forest", "Чёрный лес", "Stone:15,RoundLog:10,GreydwarfEye:5"),
			("defeated_bonemass", "Swamp", "Болото", "Stone:15,ElderBark:10,Guck:5"),
			("defeated_dragon", "Mountains", "Горы", "Stone:15,Obsidian:10,Crystal:3"),
			("defeated_goblinking", "Plains", "Равнины", "Stone:15,Tar:5,BlackMetalScrap:5"),
			("defeated_queen", "Mistlands", "Туманные земли", "BlackMarble:15,YggdrasilWood:10,Carapace:5"),
			("defeated_fader", "Ashlands", "Пепельные земли", "Grausten:15,Blackwood:10,CharredBone:5"),
			("defeated_frozenking", "Deep North", "Глубокий Север", "Stone:15,Frostwood:10,Ice:5")
		};

		internal static List<(string name, int amount)> Parse(string text)
		{
			List<(string, int)> list = new List<(string, int)>();
			if (string.IsNullOrWhiteSpace(text))
			{
				return list;
			}
			string[] array = text.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split(':');
				string text2 = array2[0].Trim();
				int result = 1;
				if (text2.Length != 0 && (array2.Length <= 1 || (int.TryParse(array2[1].Trim(), out result) && result >= 1)))
				{
					list.Add((text2, Math.Min(result, 9999)));
				}
			}
			return list;
		}

		internal static string StoneFor(string key, IDictionary<string, string> own, string general)
		{
			if (key == null || own == null || !own.TryGetValue(key, out var value) || Parse(value).Count <= 0)
			{
				return general;
			}
			return value;
		}
	}
	internal static class Server
	{
		internal const string StorePrefab = "EoO_Ledger";

		private static readonly Vector3 StorePosition = new Vector3(-987650f, 0f, 987650f);

		private const string StoreKey = "eoo_ledger";

		private static Ledger ledger;

		private static ZDO store;

		private static readonly Dictionary<long, (long player, string name)> peers = new Dictionary<long, (long, string)>();

		private static readonly List<(long peer, long player, bool afterDeath)> waitingStart = new List<(long, long, bool)>();

		private static StartMeadows meadows;

		private static ISurface surface;

		private static Task<StartMeadows> finding;

		private static readonly Random random = new Random();

		internal static bool IsServer
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return ZNet.instance.IsServer();
				}
				return false;
			}
		}

		internal static Ledger Book => ledger;

		internal static void Register()
		{
			peers.Clear();
			waitingStart.Clear();
			ledger = null;
			store = null;
			meadows = null;
			surface = null;
			finding = null;
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != null)
			{
				instance.Register<ZPackage>("EoO_Hello", (Action<long, ZPackage>)OnHello);
				instance.Register<ZPackage>("EoO_Boss", (Action<long, ZPackage>)OnBoss);
				instance.Register<ZPackage>("EoO_Ask", (Action<long, ZPackage>)OnAsk);
				instance.Register<ZPackage>("EoO_Answer", (Action<long, ZPackage>)OnAnswer);
				instance.Register<ZPackage>("EoO_Leave", (Action<long, ZPackage>)OnLeave);
			}
		}

		internal static void Forget()
		{
			peers.Clear();
			waitingStart.Clear();
			ledger = null;
			store = null;
			meadows = null;
			surface = null;
			finding = null;
		}

		internal static void Tick()
		{
			if (IsServer && finding != null && finding.IsCompleted)
			{
				try
				{
					meadows = finding.Result;
				}
				catch (Exception ex)
				{
					Plugin.Warn("start meadows: " + ex.GetBaseException().Message);
					meadows = new StartMeadows(surface);
				}
				finding = null;
				Plugin.Log($"start meadows: {meadows.Meadows.Count} meadow cells on {meadows.LandCells} land cells of the start's land");
				AnswerWaiting();
			}
		}

		private static bool Ready()
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			if (ledger != null)
			{
				return true;
			}
			if (!IsServer || ZDOMan.instance == null || (Object)(object)ZoneSystem.instance == (Object)null)
			{
				return false;
			}
			int stableHashCode = StringExtensionMethods.GetStableHashCode("EoO_Ledger");
			foreach (ZDO value in ZDOMan.instance.m_objectsByID.Values)
			{
				if (value.GetPrefab() == stableHashCode)
				{
					store = value;
					break;
				}
			}
			ZDO obj = store;
			byte[] array = ((obj != null) ? obj.GetByteArray("eoo_ledger", (byte[])null) : null);
			if (array != null)
			{
				try
				{
					ledger = Ledger.Read(new ZPackage(array));
				}
				catch (Exception ex)
				{
					Plugin.Warn("the book of teams was not read, a new one is started: " + ex.Message);
					ledger = null;
				}
			}
			if (ledger == null)
			{
				ledger = new Ledger();
			}
			if (!ledger.LegacyTaken)
			{
				KeyView.Raw = true;
				try
				{
					foreach (string globalKey in ZoneSystem.instance.GetGlobalKeys())
					{
						if (Bosses.IsBossKey(globalKey))
						{
							ledger.Legacy.Add(globalKey.ToLowerInvariant());
						}
					}
				}
				finally
				{
					KeyView.Raw = false;
				}
				ledger.LegacyTaken = true;
				Plugin.Log("book of teams started" + ((ledger.Legacy.Count > 0) ? ("; the world's old victories: " + string.Join(", ", ledger.Legacy)) : ""));
			}
			Save();
			return true;
		}

		private static void Save()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			if (ledger != null && ZDOMan.instance != null)
			{
				if (store == null || !store.IsValid())
				{
					store = ZDOMan.instance.CreateNewZDO(StorePosition, StringExtensionMethods.GetStableHashCode("EoO_Ledger"));
					store.Persistent = true;
					store.SetPrefab(StringExtensionMethods.GetStableHashCode("EoO_Ledger"));
					store.SetOwner(ZDOMan.GetSessionID());
				}
				ZPackage val = new ZPackage();
				ledger.Write(val);
				store.Set("eoo_ledger", val.GetArray());
			}
		}

		private static bool Known(long peer, out long player, out string name)
		{
			if (peers.TryGetValue(peer, out (long, string) value))
			{
				(player, name) = value;
				return true;
			}
			player = 0L;
			name = "";
			return false;
		}

		private static IEnumerable<long> PeersOf(long player)
		{
			return from p in peers
				where p.Value.player == player && Online(p.Key)
				select p.Key;
		}

		private static bool Online(long peer)
		{
			if (peer != ZNet.GetUID())
			{
				return ZNet.instance.GetPeer(peer) != null;
			}
			return !ZNet.instance.IsDedicated();
		}

		private static bool Position(long peer, out Vector3 position)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (peer == ZNet.GetUID())
			{
				position = (((Object)(object)Player.m_localPlayer != (Object)null) ? ((Component)Player.m_localPlayer).transform.position : Vector3.zero);
				return (Object)(object)Player.m_localPlayer != (Object)null;
			}
			ZNetPeer peer2 = ZNet.instance.GetPeer(peer);
			position = peer2?.m_refPos ?? Vector3.zero;
			return peer2 != null;
		}

		private static void SendState(long peer, TeamData team)
		{
			//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((byte)3);
			HostRules.Local().Write(val);
			val.Write(team != null);
			if (team != null)
			{
				long player;
				string name;
				int asks = ((Known(peer, out player, out name) && team.Owner == player) ? ledger.AsksFor(player).Count : 0);
				TeamView.Write(val, team, ledger.View(team, Plugin.KeepOldKills.Value), asks);
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(peer, "EoO_State", new object[1] { val });
		}

		private static void Broadcast(TeamData team)
		{
			if (team == null)
			{
				return;
			}
			foreach (var member in team.Members)
			{
				foreach (long item in PeersOf(member.id).ToList())
				{
					SendState(item, team);
				}
			}
		}

		private static void Message(long player, string key, string arg = "")
		{
			foreach (long item in PeersOf(player).ToList())
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(item, "EoO_Msg", new object[2]
				{
					key,
					arg ?? ""
				});
			}
		}

		private static void SendAsks(long owner)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			List<(long, string, int)> list = ledger.AsksFor(owner);
			if (list.Count == 0)
			{
				return;
			}
			foreach (long item in PeersOf(owner).ToList())
			{
				ZPackage val = new ZPackage();
				val.Write(list.Count);
				foreach (var item2 in list)
				{
					val.Write(item2.Item1);
					val.Write(item2.Item2 ?? "");
				}
				ZRoutedRpc.instance.InvokeRoutedRPC(item, "EoO_Asked", new object[1] { val });
			}
		}

		internal static void RulesChanged()
		{
			if (!IsServer || ledger == null || ZRoutedRpc.instance == null)
			{
				return;
			}
			foreach (KeyValuePair<long, (long, string)> item in peers.ToList())
			{
				if (Online(item.Key))
				{
					SendState(item.Key, ledger.TeamOf(item.Value.Item1));
				}
			}
		}

		private static void OnHello(long sender, ZPackage p)
		{
			if (!IsServer || !Ready())
			{
				return;
			}
			try
			{
				if (p.ReadByte() != 3)
				{
					return;
				}
				long num = p.ReadLong();
				string text = p.ReadString();
				ulong num2 = (ulong)p.ReadLong();
				bool flag = p.ReadBool();
				bool item = p.ReadBool();
				if (num != 0L)
				{
					peers[sender] = (num, text);
					TeamData teamData = ledger.TeamOf(num);
					TeamData teamData2 = ledger.Ensure(num, text, Plugin.PartyIsTeam.Value ? num2 : 0);
					Save();
					if (teamData != null && teamData != teamData2)
					{
						Broadcast(teamData);
						Message(num, "eoo_msg_party");
					}
					else if (teamData == null && num2 != 0L && teamData2.Members.Count > 1)
					{
						Message(num, "eoo_msg_party");
					}
					Broadcast(teamData2);
					SendState(sender, teamData2);
					if (teamData2.Owner == num)
					{
						SendAsks(num);
					}
					if (flag)
					{
						waitingStart.Add((sender, num, item));
						AnswerWaiting();
					}
					Plugin.Debug(string.Format("hello: {0} ({1}) in team {2} '{3}' of {4}{5}{6}", text, num, teamData2.Id, teamData2.Name, teamData2.Members.Count, (num2 != 0L) ? (", party " + num2) : "", flag ? ", wants a start" : ""));
				}
			}
			catch (Exception ex)
			{
				Plugin.Warn("hello: " + ex.Message);
			}
		}

		private static void AnswerWaiting()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			if (waitingStart.Count == 0)
			{
				return;
			}
			if (!Plugin.RandomStart.Value)
			{
				foreach (var item in waitingStart)
				{
					SendStart(item.peer, ok: false, Vector3.zero);
				}
				waitingStart.Clear();
				return;
			}
			if (meadows == null)
			{
				FindMeadows();
				if (meadows == null)
				{
					return;
				}
			}
			foreach (var item2 in waitingStart.ToList())
			{
				TeamData team = ledger.TeamOf(item2.player);
				if (team == null)
				{
					SendStart(item2.peer, ok: false, Vector3.zero);
					continue;
				}
				if (!team.HasStart)
				{
					List<Vector3> others = (from t in ledger.Teams.Values
						where t.HasStart && t != team
						select t.Start).ToList();
					if (meadows.Pick(others, random, Plugin.Candidates.Value, out var point))
					{
						team.HasStart = true;
						team.Start = point;
						Save();
						Plugin.Log($"team {team.Id} '{team.Name}' starts at {point}");
					}
				}
				if (!team.HasStart)
				{
					SendStart(item2.peer, ok: false, Vector3.zero);
					continue;
				}
				Vector3 point2 = StartMeadows.Near(surface, team.Start, random, (team.Members.Count > 1 || item2.afterDeath) ? 2 : 0, Plugin.MemberSpread.Value);
				SendStart(item2.peer, ok: true, point2);
			}
			waitingStart.Clear();
		}

		private static void SendStart(long peer, bool ok, Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			val.Write(ok);
			val.Write(point);
			ZRoutedRpc.instance.InvokeRoutedRPC(peer, "EoO_Start", new object[1] { val });
		}

		private static void FindMeadows()
		{
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			if (finding != null)
			{
				return;
			}
			float step = Plugin.GridStep.Value;
			float keep = Plugin.KeepFromTemple.Value;
			if (Planet.Active)
			{
				surface = new SphereSurface(Planet.Radius, step, Planet.Sample, Planet.PointAt);
				Vector3 start = Planet.StartDirection * Planet.Radius;
				meadows = StartMeadows.Find(surface, start, 1.5f, 80f, keep);
				Plugin.Log($"start meadows (planet): {meadows.Meadows.Count} meadow cells on {meadows.LandCells} land cells");
				return;
			}
			WorldGenerator gen = WorldGenerator.instance;
			Vector3 temple = default(Vector3);
			if (gen == null || !ZoneSystem.instance.GetLocationIcon(((Object)(object)Game.instance != (Object)null) ? Game.instance.m_StartLocation : "StartTemple", ref temple))
			{
				temple = Vector3.zero;
			}
			if (gen == null)
			{
				meadows = new StartMeadows(null);
				return;
			}
			float waterLevel = ZoneSystem.instance.m_waterLevel;
			surface = new FlatSurface(step, 10000f, waterLevel, (float x, float z) => gen.GetHeight(x, z), (float x, float z) => (int)gen.GetBiome(x, z, 0.02f, false) == 1);
			ISurface s = surface;
			finding = Task.Run(() => StartMeadows.Find(s, temple, 1.5f, 60f, keep));
		}

		private static void OnBoss(long sender, ZPackage p)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			if (!IsServer || !Ready())
			{
				return;
			}
			try
			{
				if (p.ReadByte() != 3)
				{
					return;
				}
				string text = p.ReadString().ToLowerInvariant();
				string arg = p.ReadString();
				Vector3 val = p.ReadVector3();
				HashSet<string> hashSet = new HashSet<string>();
				for (int num = p.ReadInt(); num > 0; num--)
				{
					hashSet.Add(p.ReadString());
				}
				if (!Bosses.IsBossKey(text))
				{
					return;
				}
				HashSet<long> hashSet2 = Access.Participants(peers.ToList().Select(delegate(KeyValuePair<long, (long player, string name)> pair)
				{
					//IL_005a: 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)
					Vector3 position;
					bool hasPosition = Position(pair.Key, out position);
					return new Access.Fighter
					{
						Player = pair.Value.player,
						Name = pair.Value.name,
						Online = Online(pair.Key),
						HasPosition = hasPosition,
						Position = position
					};
				}).ToList(), hashSet, val, Plugin.NearRadius.Value);
				List<TeamData> list = ledger.Credit(hashSet2, text);
				if (list.Count > 0)
				{
					Save();
				}
				foreach (TeamData item in list)
				{
					Broadcast(item);
				}
				for