Decompiled source of Muckheim v0.2.1

plugins/Muckheim.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("MuckheimCheats")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("Muckheim")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyInformationalVersion("0.2.1")]
[assembly: AssemblyProduct("Muckheim")]
[assembly: AssemblyTitle("Muckheim")]
[assembly: AssemblyVersion("0.2.1.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 Muckheim
{
	internal sealed class BuffChestLabel : MonoBehaviour
	{
		private const float ShowDistance = 50f;

		private const float CheckSeconds = 0.2f;

		private static readonly FieldInfo WorldTextField = AccessTools.Field(typeof(TombStone), "m_worldText");

		private static int _losMask;

		private static bool _warned;

		private static bool _logged;

		private Container _container;

		private GameObject _label;

		private float _nextCheck;

		internal static void Attach(Container container)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			if ((int)SystemInfo.graphicsDeviceType != 4 && !((Object)(object)((Component)container).GetComponent<BuffChestLabel>() != (Object)null))
			{
				((Component)container).gameObject.AddComponent<BuffChestLabel>()._container = container;
			}
		}

		private void Start()
		{
			//IL_0067: 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)
			string text = BuffChests.CostLabel(_container);
			Transform val = Template();
			if (text == null || (Object)(object)val == (Object)null)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			_label = Object.Instantiate<GameObject>(((Component)val).gameObject, ((Component)this).transform);
			((Object)_label).name = "MuckheimBuffChestLabel";
			_label.transform.localPosition = new Vector3(0f, LabelHeight(), 0f);
			_label.transform.localRotation = Quaternion.identity;
			Component val2 = FindText(_label);
			if ((Object)(object)val2 == (Object)null)
			{
				Object.Destroy((Object)(object)_label);
				Object.Destroy((Object)(object)this);
				return;
			}
			AccessTools.Property(((object)val2).GetType(), "text").SetValue(val2, text, null);
			_label.SetActive(false);
			if (_losMask == 0)
			{
				_losMask = LayerMask.GetMask(new string[6] { "Default", "static_solid", "Default_small", "piece", "terrain", "vehicle" });
			}
		}

		private void Update()
		{
			if (!((Object)(object)_label == (Object)null) && !(Time.time < _nextCheck))
			{
				_nextCheck = Time.time + 0.2f;
				if (BuffChests.CostLabel(_container) == null)
				{
					Object.Destroy((Object)(object)_label);
					Object.Destroy((Object)(object)this);
				}
				else
				{
					_label.SetActive(Visible());
				}
			}
		}

		private void OnDestroy()
		{
			if ((Object)(object)_label != (Object)null)
			{
				Object.Destroy((Object)(object)_label);
			}
		}

		private bool Visible()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			Camera mainCamera = Utils.GetMainCamera();
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)mainCamera == (Object)null || (Object)(object)localPlayer == (Object)null)
			{
				return false;
			}
			Vector3 position = _label.transform.position;
			if (Vector3.Distance(((Component)localPlayer).transform.position, ((Component)this).transform.position) > 50f)
			{
				return false;
			}
			RaycastHit val = default(RaycastHit);
			if (Physics.Linecast(((Component)mainCamera).transform.position, position, ref val, _losMask))
			{
				return ((Component)((RaycastHit)(ref val)).collider).transform.IsChildOf(((Component)this).transform);
			}
			return true;
		}

		private float LabelHeight()
		{
			//IL_0006: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			float num = ((Component)this).transform.position.y + 0.8f;
			Collider[] componentsInChildren = ((Component)this).GetComponentsInChildren<Collider>();
			foreach (Collider val in componentsInChildren)
			{
				if (!val.isTrigger)
				{
					float num2 = num;
					Bounds bounds = val.bounds;
					num = Mathf.Max(num2, ((Bounds)(ref bounds)).max.y);
				}
			}
			return num - ((Component)this).transform.position.y + 0.6f;
		}

		private static Transform Template()
		{
			GameObject val = (((Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)Player.m_localPlayer.m_tombstone != (Object)null) ? Player.m_localPlayer.m_tombstone : (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab("Player_tombstone") : null));
			TombStone val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<TombStone>() : null);
			Component val3 = (Component)(((Object)(object)val2 != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
			if ((Object)(object)val3 == (Object)null)
			{
				if (!_warned)
				{
					_warned = true;
					Plugin.Log.LogError((object)"Buff chest label: the gravestone world text was not found; cost labels are disabled.");
				}
				return null;
			}
			Transform val4 = val3.transform;
			while ((Object)(object)val4.parent != (Object)null && (Object)(object)val4.parent != (Object)(object)((Component)val2).transform)
			{
				val4 = val4.parent;
			}
			if (!_logged)
			{
				_logged = true;
				StringBuilder stringBuilder = new StringBuilder();
				Component[] componentsInChildren = ((Component)val4).GetComponentsInChildren<Component>(true);
				foreach (Component val5 in componentsInChildren)
				{
					stringBuilder.Append(((object)val5).GetType().Name).Append(' ');
				}
				Plugin.Log.LogInfo((object)("Buff chest label: cloning gravestone text '" + ((Object)val4).name + "' (" + stringBuilder.ToString().Trim() + ")."));
			}
			return val4;
		}

		private static Component FindText(GameObject root)
		{
			Type fieldType = WorldTextField.FieldType;
			return root.GetComponentInChildren(fieldType, true);
		}
	}
	internal static class BuffChests
	{
		private struct PlannedChest
		{
			public Vector3 Position;

			public float Yaw;

			public int Biome;

			public int Tier;
		}

		private struct PendingClaim
		{
			public int Tier;

			public float Time;

			public int Retries;
		}

		private struct PlacementPass
		{
			public float AboveWater;

			public float BlendScale;

			public float SpacingScale;

			public float MaxStep;

			public double MinLand;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static ConsoleEvent <0>__BuffChestCommand;

			public static Action<ZRpc, ZPackage> <1>__HandleSpawnRequest;

			public static Action<ZRpc, string> <2>__HandleSpawnResponse;
		}

		private const string TierKey = "muckheim_buffchest_tier";

		private const string OpenedKey = "muckheim_buffchest_opened";

		private const string ClaimRpc = "MuckheimBuffChestClaim";

		private const string ResultRpc = "MuckheimBuffChestResult";

		private const string SpawnRequestRpc = "MuckheimBuffChestSpawnRequest";

		private const string SpawnResponseRpc = "MuckheimBuffChestSpawnResponse";

		private const string CoinsPrefab = "Coins";

		private const float ClaimTimeoutSeconds = 10f;

		private const int AttemptsPerChest = 6000;

		private static readonly int TierHash = StringExtensionMethods.GetStableHashCode("muckheim_buffchest_tier");

		private static readonly int OpenedHash = StringExtensionMethods.GetStableHashCode("muckheim_buffchest_opened");

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

		private static readonly Func<Skills, SkillType, Skill> GetSkill = AccessTools.MethodDelegate<Func<Skills, SkillType, Skill>>(AccessTools.Method(typeof(Skills), "GetSkill", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Dictionary<ZDOID, PendingClaim> Pending = new Dictionary<ZDOID, PendingClaim>();

		private static Dictionary<Vector2s, List<PlannedChest>> _plan;

		private static TerrainGenerator _planLayout;

		private static readonly GameObject[] PrefabCache = (GameObject[])(object)new GameObject[8];

		private static bool _warnedLocations;

		private const int NotOwner = -1;

		private const int MaxClaimRetries = 10;

		private const float ClaimRetryDelay = 0.5f;

		private static readonly PlacementPass[] Passes = new PlacementPass[3]
		{
			new PlacementPass
			{
				BlendScale = 1f,
				SpacingScale = 1f,
				MaxStep = 1.2f,
				MinLand = 0.95,
				AboveWater = 1.5f
			},
			new PlacementPass
			{
				BlendScale = 1.75f,
				SpacingScale = 0.5f,
				MaxStep = 2f,
				MinLand = 0.9,
				AboveWater = 0.8f
			},
			new PlacementPass
			{
				BlendScale = 2.25f,
				SpacingScale = 0.25f,
				MaxStep = 3f,
				MinLand = 0.8,
				AboveWater = 0.25f
			}
		};

		internal static void Apply(Harmony harmony)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected O, but got Unknown
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Expected O, but got Unknown
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Expected O, but got Unknown
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Container), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(BuffChests), "ContainerAwakePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Container), "GetHoverText", (Type[])null, (Type[])null), new HarmonyMethod(typeof(BuffChests), "GetHoverTextPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Container), "Interact", (Type[])null, (Type[])null), new HarmonyMethod(typeof(BuffChests), "InteractPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ZoneSystem), "PlaceZoneCtrl", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(BuffChests), "PlaceZoneCtrlPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(BuffChests), "RegisterCommands", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNet), "OnNewConnection", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(BuffChests), "RegisterSpawnRpc", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			HarmonyMethod val = new HarmonyMethod(typeof(BuffChests), "BlockWhileLocked", (Type[])null);
			HarmonyMethod val2 = new HarmonyMethod(typeof(BuffChests), "DamagePrefix", (Type[])null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(WearNTear), "ApplyDamage", (Type[])null, (Type[])null), new HarmonyMethod(typeof(BuffChests), "BlockApplyDamageWhileLocked", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(WearNTear), "Remove", (Type[])null, (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(WearNTear), "Destroy", (Type[])null, (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(WearNTear), "RPC_Damage", (Type[])null, (Type[])null), val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Destructible), "RPC_Damage", (Type[])null, (Type[])null), val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Destructible), "Destroy", (Type[])null, (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static bool IsLockedChest(Component component)
		{
			Container component2 = component.GetComponent<Container>();
			if ((Object)(object)component2 != (Object)null)
			{
				return LockedTier(component2) > 0;
			}
			return false;
		}

		private static bool BlockWhileLocked(Component __instance, MethodBase __originalMethod)
		{
			if (!IsLockedChest(__instance))
			{
				return true;
			}
			Plugin.Log.LogInfo((object)("Buff chest: blocked " + __originalMethod.DeclaringType?.Name + "." + __originalMethod.Name + " on a locked chest."));
			return false;
		}

		private static bool DamagePrefix(Component __instance, HitData hit)
		{
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			Container component = __instance.GetComponent<Container>();
			if ((Object)(object)component == (Object)null)
			{
				return true;
			}
			if (LockedTier(component) > 0)
			{
				Plugin.Log.LogInfo((object)("Buff chest: blocked " + ((object)__instance).GetType().Name + ".RPC_Damage on a locked chest."));
				return false;
			}
			ZNetView val = ContainerView.Invoke(component);
			if ((Object)(object)val == (Object)null || !val.IsValid() || !val.IsOwner() || !val.GetZDO().GetBool(OpenedHash, false) || hit == null || hit.GetTotalDamage() <= 0f || val.GetZDO().GetFloat(ZDOVars.s_health, 1f) <= 0f)
			{
				return true;
			}
			Plugin.Log.LogInfo((object)"Buff chest: an opened chest was hit and broke.");
			WearNTear val2 = (WearNTear)(object)((__instance is WearNTear) ? __instance : null);
			if ((Object)(object)val2 != (Object)null)
			{
				val2.ApplyDamage(float.MaxValue, hit);
			}
			else
			{
				((Destructible)__instance).Destroy(hit);
			}
			return false;
		}

		private static bool BlockApplyDamageWhileLocked(WearNTear __instance, ref bool __result)
		{
			if (!IsLockedChest((Component)(object)__instance))
			{
				return true;
			}
			Plugin.Log.LogInfo((object)"Buff chest: blocked WearNTear.ApplyDamage on a locked chest.");
			__result = false;
			return false;
		}

		internal static string CostLabel(Container container)
		{
			int num = (((Object)(object)container != (Object)null) ? LockedTier(container) : 0);
			if (num == 0)
			{
				return null;
			}
			int cost = BuffChestTable.Tiers[num - 1].Cost;
			if (cost <= 0)
			{
				return "Cost: Free";
			}
			return "Cost: " + cost + "g";
		}

		private static void StripCoins(Container container)
		{
			string text = CoinsName();
			Inventory val = (((Object)(object)container != (Object)null) ? container.GetInventory() : null);
			if (text != null && val != null)
			{
				int num = val.CountItems(text, -1, false);
				if (num > 0)
				{
					val.RemoveItem(text, num, -1, false);
					Plugin.Log.LogInfo((object)("Buff chest: removed " + num + " coins from the loot."));
				}
			}
		}

		private static void FillLoot(Container container, LootTable table, int tier)
		{
			Inventory val = (((Object)(object)container != (Object)null) ? container.GetInventory() : null);
			if (val != null)
			{
				val.RemoveAll();
				List<string> list = AddLoot(val, table, tier, BuffChestTable.LootMultiplier, "Buff chest loot");
				Plugin.Log.LogInfo((object)("Buff chest loot: " + ((list.Count > 0) ? string.Join(", ", list) : "nothing") + "."));
			}
		}

		internal static List<string> AddLoot(Inventory inventory, LootTable table, int draws, float multiplier, string logPrefix)
		{
			List<LootItem> list = table.Items.ToList();
			List<string> list2 = new List<string>();
			for (int i = 0; i < draws; i++)
			{
				if (list.Count <= 0)
				{
					break;
				}
				float num = Random.value * list.Sum((LootItem lootItem2) => lootItem2.Weight);
				LootItem lootItem = list[list.Count - 1];
				foreach (LootItem item in list)
				{
					num -= item.Weight;
					if (num < 0f)
					{
						lootItem = item;
						break;
					}
				}
				if (table.Unique)
				{
					list.Remove(lootItem);
				}
				GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab(lootItem.Item) : null);
				ItemDrop val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val2 == (Object)null)
				{
					Plugin.Log.LogError((object)(logPrefix + ": unknown item " + lootItem.Item + "."));
					continue;
				}
				int num2 = Mathf.Max(1, Mathf.RoundToInt((float)Random.Range(lootItem.Min, lootItem.Max + 1) * multiplier));
				int num3 = Mathf.Max(1, val2.m_itemData.m_shared.m_maxStackSize);
				for (int num4 = num2; num4 > 0; num4 -= num3)
				{
					if (!inventory.AddItem(val, Mathf.Min(num4, num3)))
					{
						Plugin.Log.LogWarning((object)(logPrefix + ": the chest is full; " + lootItem.Item + " was cut short."));
						break;
					}
				}
				list2.Add(num2 + " " + lootItem.Item);
			}
			return list2;
		}

		private static void CheckLootItems()
		{
			if ((Object)(object)ObjectDB.instance == (Object)null)
			{
				return;
			}
			for (int i = 0; i < 8; i++)
			{
				LootTable lootTable = BuffChestTable.LootFor(i);
				if (lootTable == null)
				{
					continue;
				}
				LootItem[] items = lootTable.Items;
				foreach (LootItem lootItem in items)
				{
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(lootItem.Item);
					if ((Object)(object)itemPrefab == (Object)null || (Object)(object)itemPrefab.GetComponent<ItemDrop>() == (Object)null)
					{
						Plugin.Log.LogError((object)("Buff chest loot for " + TerrainGenerator.Order[i] + ": unknown item " + lootItem.Item + "."));
					}
				}
			}
		}

		private static void MakeBuffChest(GameObject chest, int tier, int biome)
		{
			ZNetView component = chest.GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.GetZDO() != null)
			{
				component.GetZDO().Set(TierHash, tier, false);
				Container component2 = chest.GetComponent<Container>();
				LootTable lootTable = BuffChestTable.LootFor(biome);
				if (lootTable != null)
				{
					FillLoot(component2, lootTable, tier);
				}
				else
				{
					StripCoins(component2);
				}
				if ((Object)(object)component2 != (Object)null && component.IsValid())
				{
					BuffChestLabel.Attach(component2);
				}
			}
		}

		private static int LockedTier(Container container)
		{
			ZNetView val = ContainerView.Invoke(container);
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				return 0;
			}
			int num = val.GetZDO().GetInt(TierHash, 0);
			if (num < 1 || num > BuffChestTable.Tiers.Length)
			{
				return 0;
			}
			return num;
		}

		private static void ContainerAwakePostfix(Container __instance)
		{
			ZNetView val = ContainerView.Invoke(__instance);
			if (!((Object)(object)val == (Object)null) && val.GetZDO() != null)
			{
				val.Register<int>("MuckheimBuffChestClaim", (Action<long, int>)delegate(long sender, int tier)
				{
					HandleClaim(__instance, sender, tier);
				});
				val.Register<int>("MuckheimBuffChestResult", (Action<long, int>)delegate(long sender, int tier)
				{
					HandleResult(__instance, tier);
				});
				if (LockedTier(__instance) > 0)
				{
					BuffChestLabel.Attach(__instance);
				}
			}
		}

		private static bool GetHoverTextPrefix(Container __instance, ref string __result)
		{
			int num = LockedTier(__instance);
			if (num == 0)
			{
				return true;
			}
			BuffChestTable.Tier tier = BuffChestTable.Tiers[num - 1];
			string text = ((tier.Cost > 0) ? ("Pay " + tier.Cost + " coins") : "Open (free)");
			__result = Localization.instance.Localize(tier.Name + "\n[<color=yellow><b>$KEY_Use</b></color>] " + text + ": " + tier.RewardText());
			return false;
		}

		private static bool InteractPrefix(Container __instance, Humanoid character, bool hold, ref bool __result)
		{
			int num = LockedTier(__instance);
			if (num == 0)
			{
				return true;
			}
			__result = true;
			if (!hold && (Object)(object)character != (Object)null && (Object)(object)character == (Object)(object)Player.m_localPlayer)
			{
				TryOpen(__instance, Player.m_localPlayer, num);
			}
			return false;
		}

		private static string CoinsName()
		{
			GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab("Coins") : null);
			ItemDrop val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null);
			if (!((Object)(object)val2 != (Object)null))
			{
				return null;
			}
			return val2.m_itemData.m_shared.m_name;
		}

		private static void TryOpen(Container container, Player player, int tier)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			ZNetView val = ContainerView.Invoke(container);
			ZDOID uid = val.GetZDO().m_uid;
			BuffChestTable.Tier tier2 = BuffChestTable.Tiers[tier - 1];
			if (Pending.TryGetValue(uid, out var value))
			{
				if (Time.realtimeSinceStartup - value.Time < 10f)
				{
					return;
				}
				Pending.Remove(uid);
				Refund(player, BuffChestTable.Tiers[value.Tier - 1].Cost);
				Plugin.Log.LogWarning((object)"Buff chest claim timed out; coins refunded.");
			}
			if (tier2.Cost > 0)
			{
				string text = CoinsName();
				if (text == null)
				{
					Plugin.Log.LogError((object)"Buff chest: the Coins item was not found; chests cannot be paid for.");
					return;
				}
				Inventory inventory = ((Humanoid)player).GetInventory();
				int num = inventory.CountItems(text, -1, true);
				if (num < tier2.Cost)
				{
					string text2 = tier2.Name + " costs " + tier2.Cost + " coins (you have " + num + ").";
					((Character)player).Message((MessageType)2, text2, 0, (Sprite)null, false);
					Plugin.Log.LogInfo((object)("Buff chest refused: " + text2));
					return;
				}
				inventory.RemoveItem(text, tier2.Cost, -1, true);
			}
			Pending[uid] = new PendingClaim
			{
				Tier = tier,
				Time = Time.realtimeSinceStartup
			};
			val.InvokeRPC("MuckheimBuffChestClaim", new object[1] { tier });
		}

		private static void HandleClaim(Container container, long sender, int tier)
		{
			ZNetView val = ContainerView.Invoke(container);
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				return;
			}
			if (!val.IsOwner())
			{
				val.InvokeRPC(sender, "MuckheimBuffChestResult", new object[1] { -1 });
				return;
			}
			bool flag = tier >= 1 && val.GetZDO().GetInt(TierHash, 0) == tier;
			if (flag)
			{
				val.GetZDO().Set(TierHash, 0, false);
				val.GetZDO().Set(OpenedHash, true);
				val.GetZDO().Set(ZDOVars.s_health, 1f);
			}
			val.InvokeRPC(sender, "MuckheimBuffChestResult", new object[1] { flag ? tier : 0 });
		}

		private static IEnumerator RetryClaim(Container container, int tier)
		{
			yield return (object)new WaitForSeconds(0.5f);
			ZNetView val = ContainerView.Invoke(container);
			if ((Object)(object)val != (Object)null && val.IsValid() && Pending.ContainsKey(val.GetZDO().m_uid))
			{
				val.InvokeRPC("MuckheimBuffChestClaim", new object[1] { tier });
			}
		}

		private static void HandleResult(Container container, int tier)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			ZNetView val = ContainerView.Invoke(container);
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)val == (Object)null || !val.IsValid() || (Object)(object)localPlayer == (Object)null || !Pending.TryGetValue(val.GetZDO().m_uid, out var value))
			{
				return;
			}
			ZDOID uid = val.GetZDO().m_uid;
			if (tier == -1 && value.Retries < 10)
			{
				value.Retries++;
				value.Time = Time.realtimeSinceStartup;
				Pending[uid] = value;
				Plugin.Log.LogInfo((object)"Buff chest claim reached a peer that no longer owns the chest; retrying.");
				((MonoBehaviour)container).StartCoroutine(RetryClaim(container, value.Tier));
				return;
			}
			Pending.Remove(uid);
			BuffChestTable.Tier tier2 = BuffChestTable.Tiers[value.Tier - 1];
			if (tier != value.Tier)
			{
				Refund(localPlayer, tier2.Cost);
				string text = ((tier == -1) ? "This chest is busy; try again." : "This chest was already opened.");
				((Character)localPlayer).Message((MessageType)2, text, 0, (Sprite)null, false);
				Plugin.Log.LogInfo((object)("Buff chest claim refused: " + text));
			}
			else
			{
				Grant(localPlayer, tier2);
			}
		}

		private static bool Refund(Player player, int coins)
		{
			//IL_0089: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			if (coins <= 0 || (Object)(object)player == (Object)null)
			{
				return true;
			}
			GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab("Coins") : null);
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)("Buff chest: could not give " + coins + " coins; the Coins item was not found."));
				return false;
			}
			if (((Humanoid)player).GetInventory().AddItem(val, coins))
			{
				return true;
			}
			ItemData obj = val.GetComponent<ItemDrop>().m_itemData.Clone();
			obj.m_dropPrefab = val;
			ItemDrop.DropItem(obj, coins, ((Component)player).transform.position + Vector3.up, Quaternion.identity);
			Plugin.Log.LogWarning((object)("Buff chest: inventory full; dropped " + coins + " coins at the player's feet."));
			return false;
		}

		internal unsafe static void Grant(Player player, BuffChestTable.Tier tier, bool announce = true)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: 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_0113: Unknown result type (might be due to invalid IL or missing references)
			Skills skills = ((Character)player).GetSkills();
			List<SkillType> available = (from d in skills.m_skills
				where d != null && (int)d.m_skill != 0 && (int)d.m_skill != 999
				select d.m_skill).Distinct().ToList();
			float cap = BuffChestTable.SkillCap;
			SkillType val = PickSkill(available, (SkillType s) => GetSkill(skills, s).m_level < cap, tier.Pool);
			if ((int)val == 0)
			{
				((Character)player).Message((MessageType)2, "No skill could be raised.", 0, (Sprite)null, false);
				Plugin.Log.LogWarning((object)("Buff chest opened, but no skill was eligible for " + tier.Name + "."));
				return;
			}
			Skill val2 = GetSkill(skills, val);
			float level = val2.m_level;
			val2.m_level = (tier.MaxOut ? cap : Mathf.Min(cap, level + (float)tier.Levels));
			val2.m_accumulator = 0f;
			player.OnSkillLevelup(val, val2.m_level);
			if (announce)
			{
				((Character)player).Message((MessageType)2, tier.Name + ": $skill_" + ((object)(*(SkillType*)(&val))/*cast due to .constrained prefix*/).ToString().ToLowerInvariant() + " " + (int)level + " -> " + (int)val2.m_level, 0, (val2.m_info != null) ? val2.m_info.m_icon : null, false);
			}
			Plugin.Log.LogInfo((object)("Buff chest opened: " + tier.Name + " raised " + ((object)(*(SkillType*)(&val))/*cast due to .constrained prefix*/).ToString() + " from " + (int)level + " to " + (int)val2.m_level + "."));
		}

		private static SkillType PickSkill(List<SkillType> available, Func<SkillType, bool> belowCap, BuffChestTable.SkillPool pool)
		{
			//IL_0089: 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_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			HashSet<SkillType> combat = BuffChestTable.CombatMovementSkills;
			List<SkillType> list = ((pool == BuffChestTable.SkillPool.CombatMovement) ? available.Where(combat.Contains).ToList() : available);
			List<SkillType> list2 = list.Where(belowCap).ToList();
			if (list2.Count > 0)
			{
				list = list2;
			}
			if (list.Count == 0)
			{
				return (SkillType)0;
			}
			float num = Random.value * ((IEnumerable<SkillType>)list).Sum((Func<SkillType, float>)Weight);
			foreach (SkillType item in list)
			{
				num -= Weight(item);
				if (num < 0f)
				{
					return item;
				}
			}
			return list[list.Count - 1];
			float Weight(SkillType s)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				if (pool != BuffChestTable.SkillPool.PreferCombatMovement || !combat.Contains(s))
				{
					return 1f;
				}
				return BuffChestTable.PreferredSkillWeight;
			}
		}

		private static void PlaceZoneCtrlPostfix(ZoneSystem __instance, Vector2s zoneID, SpawnMode mode, List<GameObject> spawnedObjects)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Invalid comparison between Unknown and I4
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Invalid comparison between Unknown and I4
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Invalid comparison between Unknown and I4
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Invalid comparison between Unknown and I4
			if (((int)mode != 0 && (int)mode != 2) || TerrainPatcher.Layout == null)
			{
				return;
			}
			if (!__instance.LocationsGenerated)
			{
				if (!_warnedLocations)
				{
					_warnedLocations = true;
					Plugin.Log.LogWarning((object)"Buff chests: a zone generated before locations; it gets no chests.");
				}
			}
			else
			{
				if (!Plan(__instance).TryGetValue(zoneID, out var value))
				{
					return;
				}
				int num = 0;
				foreach (PlannedChest item in value)
				{
					GameObject val = ResolvePrefab(item.Biome);
					if ((Object)(object)val == (Object)null)
					{
						continue;
					}
					if ((int)mode == 2)
					{
						ZNetView.StartGhostInit();
					}
					try
					{
						GameObject val2 = Object.Instantiate<GameObject>(val, item.Position, Quaternion.Euler(0f, item.Yaw, 0f));
						ZNetView component = val2.GetComponent<ZNetView>();
						if ((Object)(object)component != (Object)null && component.GetZDO() != null)
						{
							MakeBuffChest(val2, item.Tier, item.Biome);
							num++;
						}
						if ((int)mode == 2)
						{
							spawnedObjects.Add(val2);
						}
					}
					finally
					{
						if ((int)mode == 2)
						{
							ZNetView.FinishGhostInit();
						}
					}
				}
				Plugin.Log.LogInfo((object)("Buff chests: spawned " + num + " in zone " + zoneID.x + "," + zoneID.y + "."));
			}
		}

		internal static void ResetCaches()
		{
			Array.Clear(PrefabCache, 0, PrefabCache.Length);
			_plan = null;
			_planLayout = null;
		}

		private static GameObject ResolvePrefab(int biome)
		{
			if ((Object)(object)PrefabCache[biome] != (Object)null)
			{
				return PrefabCache[biome];
			}
			GameObject val = null;
			string text = null;
			foreach (string item in BuffChestTable.PrefabsFor(biome).Concat(new string[1] { BuffChestTable.FallbackPrefab }))
			{
				val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(item) : null);
				if ((Object)(object)val != (Object)null && (Object)(object)val.GetComponent<Container>() != (Object)null && (Object)(object)val.GetComponent<ZNetView>() != (Object)null)
				{
					text = item;
					break;
				}
				val = null;
			}
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)("Buff chests: no chest prefab found for " + TerrainGenerator.Order[biome] + "."));
				return null;
			}
			string text2 = BuffChestTable.PrefabsFor(biome).FirstOrDefault() ?? BuffChestTable.FallbackPrefab;
			if (text == text2)
			{
				Plugin.Log.LogInfo((object)("Buff chests: " + TerrainGenerator.Order[biome] + " uses " + text + "."));
			}
			else
			{
				Plugin.Log.LogWarning((object)("Buff chests: " + TerrainGenerator.Order[biome] + " uses " + text + " because " + text2 + " is not a chest prefab."));
			}
			PrefabCache[biome] = val;
			return val;
		}

		private static Dictionary<Vector2s, List<PlannedChest>> Plan(ZoneSystem zs)
		{
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			TerrainGenerator layout = TerrainPatcher.Layout;
			if (_plan != null && _planLayout == layout)
			{
				return _plan;
			}
			for (int i = 0; i < 8; i++)
			{
				ResolvePrefab(i);
			}
			CheckLootItems();
			LocationLoot.CheckItems();
			WorldGenerator instance = WorldGenerator.instance;
			Random random = new Random(instance.GetSeed() ^ 0x43485354);
			List<Vector4> source = ((IEnumerable<LocationInstance>)zs.m_locationInstances.Values).Select((Func<LocationInstance, Vector4>)((LocationInstance l) => new Vector4(l.m_position.x, l.m_position.z, Mathf.Min(40f, Mathf.Max(l.m_location.m_exteriorRadius, l.m_location.m_interiorRadius)) + 6f, 0f))).ToList();
			float num = (float)(layout.Radius * 1.8);
			List<Vector2> list = new List<Vector2>();
			Dictionary<Vector2s, List<PlannedChest>> dictionary = new Dictionary<Vector2s, List<PlannedChest>>();
			StringBuilder stringBuilder = new StringBuilder("Buff chests planned (biome | placed/wanted | relaxed):");
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			int num6 = 0;
			int num7 = 0;
			int num8 = 0;
			Color val = default(Color);
			Vector3 val2 = default(Vector3);
			for (int num9 = 0; num9 < 8; num9++)
			{
				int num10 = 0;
				int num11 = 0;
				int num12 = 0;
				for (int num13 = 1; num13 <= BuffChestTable.Tiers.Length; num13++)
				{
					for (int num14 = 0; num14 < BuffChestTable.Tiers[num13 - 1].PerBiome; num14++)
					{
						num11++;
						bool flag = false;
						for (int num15 = 0; num15 < Passes.Length; num15++)
						{
							if (flag)
							{
								break;
							}
							PlacementPass placementPass = Passes[num15];
							float num16 = Mathf.Min(0.49f, BuffChestTable.MaxBorderBlend * placementPass.BlendScale);
							float num17 = BuffChestTable.MinSpacing * placementPass.SpacingScale;
							float spacing2 = num17 * num17;
							for (int num18 = 0; num18 < 6000; num18++)
							{
								if (flag)
								{
									break;
								}
								float num19 = (float)(random.NextDouble() * 2.0 - 1.0) * num;
								float num20 = (float)(random.NextDouble() * 2.0 - 1.0) * num;
								TerrainGenerator.Sample sample = layout.Lookup(num19, num20);
								if (sample.Biome != num9 || sample.Blend > (double)num16 || sample.Land < placementPass.MinLand)
								{
									num4++;
									continue;
								}
								Vector2 p2 = new Vector2(num19, num20);
								if (source.Any(delegate(Vector4 l)
								{
									//IL_0000: 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_000c: Unknown result type (might be due to invalid IL or missing references)
									//IL_0012: Unknown result type (might be due to invalid IL or missing references)
									//IL_0017: Unknown result type (might be due to invalid IL or missing references)
									//IL_001c: Unknown result type (might be due to invalid IL or missing references)
									//IL_0024: Unknown result type (might be due to invalid IL or missing references)
									//IL_002a: Unknown result type (might be due to invalid IL or missing references)
									Vector2 val3 = new Vector2(l.x, l.y) - p2;
									return ((Vector2)(ref val3)).sqrMagnitude < l.z * l.z;
								}))
								{
									num5++;
									continue;
								}
								if (list.Any(delegate(Vector2 o)
								{
									//IL_0000: Unknown result type (might be due to invalid IL or missing references)
									//IL_0002: 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)
									//IL_000c: Unknown result type (might be due to invalid IL or missing references)
									Vector2 val3 = o - p2;
									return ((Vector2)(ref val3)).sqrMagnitude < spacing2;
								}))
								{
									num6++;
									continue;
								}
								float height = instance.GetHeight(num19, num20, ref val);
								if (height < zs.m_waterLevel + placementPass.AboveWater)
								{
									num7++;
									continue;
								}
								if (!Flat(instance, num19, num20, height, placementPass.MaxStep))
								{
									num8++;
									continue;
								}
								((Vector3)(ref val2))..ctor(num19, height, num20);
								Vector2s zone = ZoneSystem.GetZone(val2);
								list.Add(p2);
								if (!dictionary.TryGetValue(zone, out var value))
								{
									value = (dictionary[zone] = new List<PlannedChest>());
								}
								value.Add(new PlannedChest
								{
									Position = val2,
									Yaw = (float)(random.NextDouble() * 360.0),
									Biome = num9,
									Tier = num13
								});
								num10++;
								if (num15 > 0)
								{
									num12++;
								}
								flag = true;
							}
						}
					}
				}
				stringBuilder.Append("\n  ").Append(TerrainGenerator.Order[num9]).Append(" | ")
					.Append(num10)
					.Append('/')
					.Append(num11)
					.Append(" | ")
					.Append(num12);
				num2 += num10;
				num3 += num11;
			}
			stringBuilder.Append("\n  total | ").Append(num2).Append('/')
				.Append(num3)
				.Append("\n  rejected samples: biome/border ")
				.Append(num4)
				.Append(", location ")
				.Append(num5)
				.Append(", spacing ")
				.Append(num6)
				.Append(", water ")
				.Append(num7)
				.Append(", slope ")
				.Append(num8);
			if (num2 < num3)
			{
				Plugin.Log.LogWarning((object)stringBuilder.ToString());
			}
			else
			{
				Plugin.Log.LogInfo((object)stringBuilder.ToString());
			}
			_plan = dictionary;
			_planLayout = layout;
			return dictionary;
		}

		internal static List<KeyValuePair<Vector3, int>> UnclaimedChests()
		{
			//IL_0113: 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_0146: Unknown result type (might be due to invalid IL or missing references)
			List<KeyValuePair<Vector3, int>> list = new List<KeyValuePair<Vector3, int>>();
			ZoneSystem instance = ZoneSystem.instance;
			if ((Object)(object)instance == (Object)null || ZDOMan.instance == null || BuffChestTable.Tiers == null)
			{
				return list;
			}
			if (AccessTools.Field(typeof(ZDOMan), "m_objectsByID").GetValue(ZDOMan.instance) is Dictionary<ZDOID, ZDO> dictionary)
			{
				foreach (ZDO value in dictionary.Values)
				{
					int num = value.GetInt(TierHash, 0);
					if (num >= 1 && num <= BuffChestTable.Tiers.Length)
					{
						list.Add(new KeyValuePair<Vector3, int>(value.GetPosition(), num));
					}
				}
			}
			if (TerrainPatcher.Layout != null && instance.LocationsGenerated)
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(ZoneSystem), "IsZoneGenerated", new Type[1] { typeof(Vector2s) }, (Type[])null);
				foreach (KeyValuePair<Vector2s, List<PlannedChest>> item in Plan(instance))
				{
					if ((bool)methodInfo.Invoke(instance, new object[1] { item.Key }))
					{
						continue;
					}
					foreach (PlannedChest item2 in item.Value)
					{
						list.Add(new KeyValuePair<Vector3, int>(item2.Position, item2.Tier));
					}
				}
			}
			return list;
		}

		private static bool Flat(WorldGenerator wg, float x, float z, float h, float maxStep)
		{
			if (Mathf.Abs(wg.GetHeight(x + 2f, z) - h) < maxStep && Mathf.Abs(wg.GetHeight(x - 2f, z) - h) < maxStep && Mathf.Abs(wg.GetHeight(x, z + 2f) - h) < maxStep)
			{
				return Mathf.Abs(wg.GetHeight(x, z - 2f) - h) < maxStep;
			}
			return false;
		}

		private static void RegisterCommands()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			if (!(AccessTools.Field(typeof(Terminal), "commands").GetValue(null) is IDictionary<string, ConsoleCommand> dictionary))
			{
				Plugin.Log.LogError((object)"Terminal command registry not found; buffchest was not registered.");
				return;
			}
			object obj = <>O.<0>__BuffChestCommand;
			if (obj == null)
			{
				ConsoleEvent val = BuffChestCommand;
				<>O.<0>__BuffChestCommand = val;
				obj = (object)val;
			}
			dictionary["buffchest"] = new ConsoleCommand("buffchest", "[tier N | open | hit [damage] | coins N] Spawn a locked buff chest, open or hit the nearest one, or add coins.", (ConsoleEvent)obj, true, false, false, false, false, true, (ConsoleOptionsFetcher)null, false, false, false);
			Terminal val2 = Object.FindFirstObjectByType<Terminal>();
			if ((Object)(object)val2 != (Object)null)
			{
				AccessTools.Method(typeof(Terminal), "updateCommandList", (Type[])null, (Type[])null).Invoke(val2, null);
			}
		}

		private static void BuffChestCommand(ConsoleEventArgs args)
		{
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: 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)
			//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Unknown result type (might be due to invalid IL or missing references)
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0313: Unknown result type (might be due to invalid IL or missing references)
			//IL_031b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_0355: Unknown result type (might be due to invalid IL or missing references)
			//IL_0356: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Expected O, but got Unknown
			//IL_038d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0394: Expected O, but got Unknown
			//IL_039e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a6: Unknown result type (might be due to invalid IL or missing references)
			Player player = Player.m_localPlayer;
			if ((Object)(object)player == (Object)null)
			{
				args.Context.AddString("buffchest: no local player.");
				return;
			}
			string text = ((args.Length > 1) ? args[1].ToLowerInvariant() : "");
			if (text == "coins" && args.Length > 2 && int.TryParse(args[2], out var result) && result > 0)
			{
				args.Context.AddString(Refund(player, result) ? ("buffchest: added " + result + " coins.") : ("buffchest: inventory full; dropped " + result + " coins on the ground."));
				return;
			}
			if (text == "hit")
			{
				Container val = (from c in Object.FindObjectsByType<Container>((FindObjectsSortMode)0)
					where ((Component)c).GetComponent<IDestructible>() != null && Vector3.Distance(((Component)c).transform.position, ((Component)player).transform.position) < 10f
					orderby Vector3.Distance(((Component)c).transform.position, ((Component)player).transform.position)
					select c).FirstOrDefault();
				if ((Object)(object)val == (Object)null)
				{
					args.Context.AddString("buffchest: no damageable chest within 10 m.");
					return;
				}
				float result2 = 0f;
				bool flag = args.Length > 2 && float.TryParse(args[2], out result2) && result2 > 0f;
				HitData val2 = new HitData
				{
					m_point = ((Component)val).transform.position,
					m_dir = Vector3.down,
					m_toolTier = (short)((!flag) ? 100 : 0)
				};
				val2.m_damage.m_blunt = (flag ? result2 : 100000f);
				if (!flag)
				{
					val2.m_damage.m_chop = 100000f;
					val2.m_damage.m_pickaxe = 100000f;
				}
				((Component)val).GetComponent<IDestructible>().Damage(val2);
				args.Context.AddString("buffchest: hit " + Utils.GetPrefabName(((Object)((Component)val).gameObject).name) + ((LockedTier(val) > 0) ? " (locked)." : " (unlocked)."));
				return;
			}
			if (text == "open")
			{
				Container val3 = (from c in Object.FindObjectsByType<Container>((FindObjectsSortMode)0)
					where LockedTier(c) > 0 && Vector3.Distance(((Component)c).transform.position, ((Component)player).transform.position) < 10f
					orderby Vector3.Distance(((Component)c).transform.position, ((Component)player).transform.position)
					select c).FirstOrDefault();
				if ((Object)(object)val3 == (Object)null)
				{
					args.Context.AddString("buffchest: no locked buff chest within 10 m.");
					return;
				}
				int num = LockedTier(val3);
				args.Context.AddString("buffchest: opening " + BuffChestTable.Tiers[num - 1].Name + ".");
				TryOpen(val3, player, num);
				return;
			}
			if (!int.TryParse(text, out result) || result < 1 || result > BuffChestTable.Tiers.Length)
			{
				args.Context.AddString("Usage: buffchest <1-" + BuffChestTable.Tiers.Length + "> | open | coins <n>");
				return;
			}
			Vector3 val4 = ((Component)player).transform.position + ((Component)player).transform.forward * 5f;
			val4.y = ZoneSystem.instance.GetGroundHeight(val4);
			Quaternion val5 = Quaternion.LookRotation(-((Component)player).transform.forward);
			if (ZNet.instance.IsServer())
			{
				args.Context.AddString(SpawnByCommand(result, val4, val5));
				return;
			}
			ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
			if (serverPeer == null || !serverPeer.IsReady())
			{
				args.Context.AddString("buffchest: the server connection is not ready.");
				return;
			}
			ZPackage val6 = new ZPackage();
			val6.Write(result);
			val6.Write(val4);
			val6.Write(val5);
			serverPeer.m_rpc.Invoke("MuckheimBuffChestSpawnRequest", new object[1] { val6 });
			args.Context.AddString("buffchest: requested a chest from the server.");
		}

		private static void RegisterSpawnRpc(ZNetPeer peer)
		{
			peer.m_rpc.Register<ZPackage>("MuckheimBuffChestSpawnRequest", (Action<ZRpc, ZPackage>)HandleSpawnRequest);
			peer.m_rpc.Register<string>("MuckheimBuffChestSpawnResponse", (Action<ZRpc, string>)HandleSpawnResponse);
		}

		private static void HandleSpawnRequest(ZRpc rpc, ZPackage request)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			ZNet instance = ZNet.instance;
			if (!((Object)(object)instance == (Object)null) && instance.IsServer())
			{
				int tier = request.ReadInt();
				Vector3 pos = request.ReadVector3();
				Quaternion rotation = request.ReadQuaternion();
				string text = (instance.IsAdmin(rpc.GetSocket().GetHostName()) ? SpawnByCommand(tier, pos, rotation) : "buffchest: you are not a server admin.");
				Plugin.Log.LogInfo((object)("buffchest request: " + text));
				rpc.Invoke("MuckheimBuffChestSpawnResponse", new object[1] { text });
			}
		}

		private static void HandleSpawnResponse(ZRpc rpc, string result)
		{
			ZNetPeer val = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetServerPeer() : null);
			if (val != null && val.m_rpc == rpc)
			{
				if ((Object)(object)Console.instance != (Object)null)
				{
					((Terminal)Console.instance).AddString(result);
				}
				else
				{
					Plugin.Log.LogInfo((object)result);
				}
			}
		}

		private static string SpawnByCommand(int tier, Vector3 pos, Quaternion rotation)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			if (tier < 1 || tier > BuffChestTable.Tiers.Length)
			{
				return "buffchest: tier must be 1-" + BuffChestTable.Tiers.Length + ".";
			}
			int biome = ((TerrainPatcher.Layout != null) ? TerrainPatcher.Layout.Lookup(pos.x, pos.z).Biome : 0);
			GameObject val = ResolvePrefab(biome);
			if ((Object)(object)val == (Object)null)
			{
				return "buffchest: no chest prefab available.";
			}
			MakeBuffChest(Object.Instantiate<GameObject>(val, pos, rotation), tier, biome);
			Plugin.Log.LogInfo((object)("Buff chest spawned by command: " + BuffChestTable.Tiers[tier - 1].Name + " (" + ((Object)val).name + ")."));
			return "buffchest: spawned " + BuffChestTable.Tiers[tier - 1].Name + ".";
		}
	}
	internal static class BuffChestTable
	{
		internal enum SkillPool
		{
			Any,
			PreferCombatMovement,
			CombatMovement
		}

		internal sealed class Configuration
		{
			public float SkillCap { get; set; }

			public int GoldDropMin { get; set; }

			public int GoldDropMax { get; set; }

			public float MinSpacing { get; set; }

			public float MaxBorderBlend { get; set; }

			public float PreferredSkillWeight { get; set; } = 1f;

			public string[] CombatMovementSkills { get; set; }

			public Tier[] Tiers { get; set; }

			public Dictionary<string, string[]> ChestPrefabs { get; set; }

			public string FallbackPrefab { get; set; }

			public float LootMultiplier { get; set; } = 1f;

			public Dictionary<string, LootTable> LootTables { get; set; }
		}

		public sealed class Tier
		{
			public string Name { get; set; }

			public int Cost { get; set; } = -1;

			public int PerBiome { get; set; } = -1;

			public int Levels { get; set; }

			public bool MaxOut { get; set; }

			public string Skills
			{
				get
				{
					return Pool.ToString();
				}
				set
				{
					switch ((value ?? "").Trim().ToLowerInvariant())
					{
					case "any":
						Pool = SkillPool.Any;
						break;
					case "prefer_combat_movement":
						Pool = SkillPool.PreferCombatMovement;
						break;
					case "combat_movement":
						Pool = SkillPool.CombatMovement;
						break;
					default:
						throw new InvalidDataException("Unknown buff chest skill pool: " + value);
					}
				}
			}

			[YamlIgnore]
			internal SkillPool Pool { get; set; }

			internal string RewardText()
			{
				string text = ((Pool == SkillPool.CombatMovement) ? "a random combat/movement skill" : "a random skill");
				if (!MaxOut)
				{
					return "+" + Levels + " levels in " + text;
				}
				return "max out " + text;
			}
		}

		private static string[][] _prefabsByBiome;

		private static LootTable[] _lootByBiome = new LootTable[0];

		internal static float SkillCap { get; private set; } = 100f;

		internal static int GoldDropMin { get; private set; }

		internal static int GoldDropMax { get; private set; }

		internal static float MinSpacing { get; private set; }

		internal static float MaxBorderBlend { get; private set; }

		internal static float PreferredSkillWeight { get; private set; }

		internal static HashSet<SkillType> CombatMovementSkills { get; private set; }

		internal static Tier[] Tiers { get; private set; }

		internal static string FallbackPrefab { get; private set; }

		internal static float LootMultiplier { get; private set; } = 1f;

		internal static LootTable LootFor(int biome)
		{
			if (biome < 0 || biome >= _lootByBiome.Length)
			{
				return null;
			}
			return _lootByBiome[biome];
		}

		internal static string[] PrefabsFor(int biome)
		{
			if (biome < 0 || biome >= _prefabsByBiome.Length)
			{
				return new string[0];
			}
			return _prefabsByBiome[biome];
		}

		internal static void Parse(TextReader reader)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			//IL_00dc: 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_00e7: Invalid comparison between Unknown and I4
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			Configuration configuration = ((BuilderSkeleton<DeserializerBuilder>)new DeserializerBuilder()).WithNamingConvention(UnderscoredNamingConvention.Instance).WithDuplicateKeyChecking().Build()
				.Deserialize<Configuration>(reader);
			if (configuration == null || configuration.SkillCap < 100f || configuration.GoldDropMin < 0 || configuration.GoldDropMax < configuration.GoldDropMin || configuration.MinSpacing < 0f || configuration.MaxBorderBlend <= 0f || configuration.MaxBorderBlend > 0.5f || configuration.PreferredSkillWeight < 1f || configuration.Tiers == null || configuration.Tiers.Length == 0 || configuration.ChestPrefabs == null || string.IsNullOrWhiteSpace(configuration.FallbackPrefab))
			{
				throw new InvalidDataException("The buff chest table requires a skill cap >= 100, a valid gold range, placement values, tiers and chest prefabs.");
			}
			HashSet<SkillType> hashSet = new HashSet<SkillType>();
			string[] array = configuration.CombatMovementSkills ?? new string[0];
			foreach (string text in array)
			{
				if (!Enum.TryParse<SkillType>(text, ignoreCase: true, out SkillType result) || (int)result == 0 || (int)result == 999)
				{
					throw new InvalidDataException("Unknown combat/movement skill in the buff chest table: " + text);
				}
				hashSet.Add(result);
			}
			for (int j = 0; j < configuration.Tiers.Length; j++)
			{
				Tier tier = configuration.Tiers[j];
				if (tier == null || string.IsNullOrWhiteSpace(tier.Name) || tier.Cost < 0 || tier.PerBiome < 0 || (!tier.MaxOut && tier.Levels <= 0))
				{
					throw new InvalidDataException("Buff chest tier " + j + " requires a name, cost >= 0, per_biome >= 0 and levels > 0 (or max_out).");
				}
				if (tier.Pool != SkillPool.Any && hashSet.Count == 0)
				{
					throw new InvalidDataException("Buff chest tier " + j + " uses combat/movement skills but none are listed.");
				}
			}
			string[][] array2 = new string[8][];
			for (int k = 0; k < array2.Length; k++)
			{
				array2[k] = ((configuration.ChestPrefabs.TryGetValue(TerrainGenerator.Order[k], out var value) && value != null) ? value.Where((string p) => !string.IsNullOrWhiteSpace(p)).ToArray() : new string[0]);
			}
			foreach (string key in configuration.ChestPrefabs.Keys)
			{
				if (Array.IndexOf(TerrainGenerator.Order, key) < 0)
				{
					throw new InvalidDataException("Unknown biome in buff chest prefabs: " + key);
				}
			}
			if (configuration.LootMultiplier <= 0f)
			{
				throw new InvalidDataException("The buff chest loot_multiplier must be > 0.");
			}
			LootTable[] array3 = new LootTable[8];
			foreach (KeyValuePair<string, LootTable> item in configuration.LootTables ?? new Dictionary<string, LootTable>())
			{
				int num = Array.IndexOf(TerrainGenerator.Order, item.Key);
				if (num < 0)
				{
					throw new InvalidDataException("Unknown biome in buff chest loot tables: " + item.Key);
				}
				item.Value?.Validate("Buff chest loot for " + item.Key);
				array3[num] = item.Value;
			}
			SkillCap = configuration.SkillCap;
			GoldDropMin = configuration.GoldDropMin;
			GoldDropMax = configuration.GoldDropMax;
			MinSpacing = configuration.MinSpacing;
			MaxBorderBlend = configuration.MaxBorderBlend;
			PreferredSkillWeight = configuration.PreferredSkillWeight;
			CombatMovementSkills = hashSet;
			Tiers = configuration.Tiers;
			FallbackPrefab = configuration.FallbackPrefab;
			_prefabsByBiome = array2;
			_lootByBiome = array3;
			LootMultiplier = configuration.LootMultiplier;
		}

		internal static void WriteClientPart(ZPackage pkg)
		{
			//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)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected I4, but got Unknown
			pkg.Write(SkillCap);
			pkg.Write(GoldDropMin);
			pkg.Write(GoldDropMax);
			pkg.Write(PreferredSkillWeight);
			pkg.Write(CombatMovementSkills.Count);
			foreach (SkillType combatMovementSkill in CombatMovementSkills)
			{
				pkg.Write((int)combatMovementSkill);
			}
			pkg.Write(Tiers.Length);
			Tier[] tiers = Tiers;
			foreach (Tier tier in tiers)
			{
				pkg.Write(tier.Name);
				pkg.Write(tier.Cost);
				pkg.Write(tier.Levels);
				pkg.Write(tier.MaxOut);
				pkg.Write((int)tier.Pool);
			}
		}

		internal static void ReadClientPart(ZPackage pkg)
		{
			float num = pkg.ReadSingle();
			int num2 = pkg.ReadInt();
			int num3 = pkg.ReadInt();
			float preferredSkillWeight = pkg.ReadSingle();
			HashSet<SkillType> hashSet = new HashSet<SkillType>();
			for (int num4 = pkg.ReadInt(); num4 > 0; num4--)
			{
				hashSet.Add((SkillType)pkg.ReadInt());
			}
			Tier[] array = new Tier[pkg.ReadInt()];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new Tier
				{
					Name = pkg.ReadString(),
					Cost = pkg.ReadInt(),
					Levels = pkg.ReadInt(),
					MaxOut = pkg.ReadBool(),
					Pool = (SkillPool)pkg.ReadInt()
				};
			}
			if (num < 100f || num2 < 0 || num3 < num2 || array.Length == 0)
			{
				throw new InvalidDataException("The server sent an invalid buff chest table.");
			}
			SkillCap = num;
			GoldDropMin = num2;
			GoldDropMax = num3;
			PreferredSkillWeight = preferredSkillWeight;
			CombatMovementSkills = hashSet;
			Tiers = array;
			MinSpacing = 0f;
			MaxBorderBlend = 0f;
			FallbackPrefab = null;
			_prefabsByBiome = new string[0][];
			_lootByBiome = new LootTable[0];
			LootMultiplier = 1f;
		}
	}
	internal static class CoastalTerrain
	{
		internal const float OceanFloor = -25f;

		internal static float Height(double land, float inlandHeight)
		{
			double num = ((land < 0.0) ? 0.0 : ((land > 1.0) ? 1.0 : land));
			double num2 = num * num * (3.0 - 2.0 * num);
			return (float)(-25.0 + (double)(inlandHeight - -25f) * num2);
		}
	}
	internal static class DayNightCycle
	{
		public const long DayLengthSeconds = 480L;

		private const long PreviousDayLengthSeconds = 1800L;

		public static void Apply(Harmony harmony)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(EnvMan), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(ZNet), "Awake", (Type[])null, (Type[])null);
			if (methodInfo == null || methodInfo2 == null)
			{
				Plugin.Log.LogError((object)"Day/night initialization methods not found; custom day/night cycle is NOT active.");
				return;
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(DayNightCycle), "InitializeEnvironment", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(DayNightCycle), "InitializeNetworkTime", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)$"Day/night cycle uses a {480L}-second day and normal network time.");
		}

		private static void InitializeEnvironment(EnvMan __instance)
		{
			__instance.m_dayLengthSec = 480L;
		}

		private static void InitializeNetworkTime(ZNet __instance)
		{
			if (__instance.IsServer())
			{
				__instance.SetNetTime(__instance.GetTimeSeconds() * 480.0 / 1800.0);
			}
		}
	}
	internal sealed class DeathRevival : MonoBehaviour
	{
		private sealed class Participant
		{
			internal string Key;

			internal int Kind;

			internal long PlayerId;

			internal ZDOID DummyId;

			internal string Name;

			internal ZDO Data;

			internal RevivalParticipant<string> Rules;

			internal ZDOID GraveId;

			internal Vector3 GravePosition;

			internal bool HasGrave;

			internal bool PendingRespawn;

			internal bool HasReviver;

			internal bool WasOnline;

			internal ZDOID LastDeathId;
		}

		private sealed class StatusEntry
		{
			internal string Name;

			internal float Remaining;

			internal Vector3 Position;

			internal bool HasReviver;

			internal float ReviveRemaining;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static Action<ZRpc, ZPackage> <0>__HandleStateRequest;

			public static Action<ZRpc, ZPackage> <1>__HandleStateResponse;

			public static Action<ZRpc, ZPackage> <2>__HandlePlayerDeath;

			public static Action<ZRpc, ZPackage> <3>__HandleDummyDeath;

			public static Action<ZRpc, ZPackage> <4>__HandleRespawned;

			public static Action<ZRpc, int> <5>__HandleRespawnCheat;

			public static Action<ZRpc, int, string> <6>__HandleRespawnCheatResult;

			public static ConsoleEvent <7>__RespawnCheatCommand;
		}

		private const string StateRequestRpc = "Muckheim_RevivalStateRequest";

		private const string StateResponseRpc = "Muckheim_RevivalState";

		private const string PlayerDeathRpc = "Muckheim_RevivalPlayerDeath";

		private const string DummyDeathRpc = "Muckheim_RevivalDummyDeath";

		private const string RespawnedRpc = "Muckheim_RevivalRespawned";

		private const string RespawnCheatRpc = "Muckheim_RevivalRespawnCheat";

		private const string RespawnCheatResultRpc = "Muckheim_RevivalRespawnCheatResult";

		private static readonly int StateMarker = StringExtensionMethods.GetStableHashCode("muckheim_revival_state");

		private const string StateKind = "muckheim_revival_kind";

		private const string StateIdentity = "muckheim_revival_identity";

		private const string StatePlayerId = "muckheim_revival_player_id";

		private const string StateDummyId = "muckheim_revival_dummy_id";

		private const string StateDelay = "muckheim_revival_delay";

		private const string StateHasDied = "muckheim_revival_has_died";

		private const string StateDead = "muckheim_revival_dead";

		private const string StatePending = "muckheim_revival_pending";

		private const string StateGrave = "muckheim_revival_grave_id";

		private const string StateLastDeath = "muckheim_revival_last_death";

		private const string StateGravePosition = "muckheim_revival_grave_pos";

		private const string StateName = "muckheim_revival_name";

		private const string WorldGameOver = "muckheim_revival_game_over";

		private const string WorldSunrise = "muckheim_revival_sunrise";

		private static readonly int GraveMarker = StringExtensionMethods.GetStableHashCode("muckheim_revival_grave");

		private const string GraveReserved = "muckheim_revival_reserved";

		private const string GravePlayerId = "muckheim_revival_owner";

		private const string GraveRemaining = "muckheim_revival_remaining";

		private const string GraveReviving = "muckheim_revival_progress";

		private const string GraveRespawnReady = "muckheim_revival_respawn_ready";

		private const int PlayerKind = 1;

		private const int DummyKind = 2;

		private const int WorldKind = 0;

		private const float ServerTickSeconds = 0.2f;

		private const float StateSyncSeconds = 0.75f;

		private const float ClientRequestSeconds = 4f;

		private const float GraveSearchDistance = 16f;

		private const float RespawnRequestTimeoutSeconds = 10f;

		private static DeathRevival _instance;

		private static bool _localStateKnown;

		private static bool _localDead;

		private static bool _localDeathConfirmed;

		private static bool _localPendingRespawn;

		private static bool _localHasGrave;

		private static bool _localGameOver;

		private static bool _localHasReviver;

		private static float _localReviveRemaining;

		private static int _localDelay;

		private static float _localRemaining;

		private static Vector3 _localGravePosition;

		private static long _localDeathPlayerId;

		private static ZDOID _localDeathId;

		private static ZDOID _localDeathGraveId;

		private static Vector3 _localDeathPosition;

		private static readonly List<StatusEntry> _statusEntries = new List<StatusEntry>();

		private static ZDOID _lastCreatedGraveId;

		private static long _lastCreatedGraveOwner;

		private static float _lastCreatedGraveAt;

		private readonly Dictionary<string, Participant> _participants = new Dictionary<string, Participant>();

		private readonly Dictionary<string, Vector3> _livingPositions = new Dictionary<string, Vector3>();

		private readonly HashSet<string> _onlinePlayers = new HashSet<string>();

		private readonly HashSet<string> _livingPlayers = new HashSet<string>();

		private readonly Dictionary<ZRpc, long> _peerPlayerIds = new Dictionary<ZRpc, long>();

		private ZDO _worldData;

		private ZRpc _requestedPeer;

		private long _requestedPlayerId;

		private int _clientRequestAttempts;

		private int _deathReportAttempts;

		private float _nextClientRequest;

		private float _nextDeathReport;

		private float _nextServerTick;

		private float _nextStateSync;

		private float _localSpawnWait;

		private float _lastServerTick;

		private int _nextRespawnRequestId;

		private int _pendingRespawnRequestId;

		private ZRpc _pendingRespawnPeer;

		private Terminal _pendingRespawnTerminal;

		private float _pendingRespawnDeadline;

		private long _lastSunriseIndex;

		private long _loadedWorldUid;

		private bool _serverReady;

		private bool _gameOver;

		private bool _loggedPersistenceFailure;

		private bool _loggedClientRequestFailure;

		private bool _wasClientWaiting;

		private readonly HudText _statusText = new HudText("MuckheimRevivalStatus", 0.15f, 0.8f);

		internal static bool ServerGameOver
		{
			get
			{
				if ((Object)(object)_instance != (Object)null && _instance._serverReady)
				{
					return _instance._gameOver;
				}
				return false;
			}
		}

		internal static void Apply(Harmony harmony)
		{
			Patch(harmony, typeof(ZNet), "OnNewConnection", "RegisterRpc", postfix: true);
			Patch(harmony, typeof(Player), "OnDeath", "PlayerDeathPrefix", postfix: false);
			Patch(harmony, typeof(Player), "OnDeath", "PlayerDeathPostfix", postfix: true);
			Patch(harmony, typeof(Player), "OnSpawned", "PlayerSpawnedPostfix", postfix: true);
			Patch(harmony, typeof(Terminal), "InitTerminal", "RegisterCommands", postfix: true);
			Patch(harmony, typeof(Player), "CreateTombStone", "CreateTombStonePrefix", postfix: false);
			Patch(harmony, typeof(TombStone), "Setup", "TombStoneSetupPostfix", postfix: true);
			Patch(harmony, typeof(TombStone), "UpdateDespawn", "TombStoneDespawnPrefix", postfix: false);
			Patch(harmony, typeof(Game), "FindSpawnPoint", "FindSpawnPointPrefix", postfix: false);
			Patch(harmony, typeof(GameCamera), "UpdateCamera", "UpdateCameraPrefix", postfix: false);
			Patch(harmony, typeof(Hud), "UpdateBlackScreen", "UpdateBlackScreenPostfix", postfix: true);
		}

		private static void Patch(Harmony harmony, Type type, string methodName, string patchName, bool postfix)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(type, methodName, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Plugin.Log.LogError((object)(type.Name + "." + methodName + " not found; death/revival integration is incomplete."));
				return;
			}
			HarmonyMethod val = new HarmonyMethod(typeof(DeathRevival), patchName, (Type[])null);
			if (postfix)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			else
			{
				harmony.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private void Awake()
		{
			_instance = this;
		}

		private void Update()
		{
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			if (_pendingRespawnPeer != null && (!_pendingRespawnPeer.IsConnected() || Time.realtimeSinceStartup >= _pendingRespawnDeadline))
			{
				CompleteRespawnCheat("Respawn failed: no response from the server.");
			}
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				ResetClientState();
				_serverReady = false;
				_loadedWorldUid = 0L;
				return;
			}
			if (ZNet.instance.IsServer())
			{
				if (!EnsureServerStore())
				{
					return;
				}
				UpdateServer();
				UpdateLocalServerState();
			}
			else
			{
				UpdateClient();
			}
			if ((_localDead || _localPendingRespawn) && _localHasGrave)
			{
				ZNet.instance.SetReferencePosition(_localGravePosition);
			}
		}

		private void UpdateServer()
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (!(realtimeSinceStartup < _nextServerTick))
			{
				float elapsed = ((_lastServerTick == 0f) ? 0f : Mathf.Min(5f, realtimeSinceStartup - _lastServerTick));
				_lastServerTick = realtimeSinceStartup;
				_nextServerTick = realtimeSinceStartup + 0.2f;
				RefreshOnlineParticipants();
				ProcessSunrises();
				TickParticipants(elapsed);
				UpdateGraves();
				CheckGameOver();
				if (realtimeSinceStartup >= _nextStateSync)
				{
					_nextStateSync = realtimeSinceStartup + 0.75f;
					SyncPeers();
				}
			}
		}

		private bool EnsureServerStore()
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			long worldUID = ZNet.instance.GetWorldUID();
			if (_serverReady && _loadedWorldUid == worldUID)
			{
				return true;
			}
			if (ZDOMan.instance == null || worldUID == 0L)
			{
				return false;
			}
			_participants.Clear();
			_worldData = FindWorldData();
			if (_worldData == null)
			{
				_worldData = CreatePersistentZdo(Vector3.zero);
				if (_worldData == null)
				{
					return PersistenceFailure("Could not create persistent death/revival world state.");
				}
				_worldData.Set(StateMarker, true);
				_worldData.Set("muckheim_revival_kind", 0);
				_worldData.Set("muckheim_revival_identity", "world");
			}
			_gameOver = _worldData.GetBool("muckheim_revival_game_over", false);
			long num = SunriseIndex(ZNet.instance.GetTimeSeconds());
			_lastSunriseIndex = _worldData.GetLong("muckheim_revival_sunrise", num);
			_worldData.Set("muckheim_revival_sunrise", _lastSunriseIndex);
			LoadParticipants();
			_loadedWorldUid = worldUID;
			_serverReady = true;
			_lastServerTick = Time.realtimeSinceStartup;
			Plugin.Log.LogInfo((object)("Death/revival state loaded for world " + worldUID + "."));
			return true;
		}

		private bool PersistenceFailure(string message)
		{
			if (!_loggedPersistenceFailure)
			{
				Plugin.Log.LogError((object)(message + " Respawns remain blocked until persistence is available."));
				_loggedPersistenceFailure = true;
			}
			_serverReady = false;
			return false;
		}

		private ZDO FindWorldData()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			foreach (ZDOID item in ZDOExtraData.GetAllZDOIDsWithHash((Type)3, StateMarker))
			{
				ZDO zDO = ZDOMan.instance.GetZDO(item);
				if (zDO != null && zDO.IsValid() && zDO.GetBool(StateMarker, false) && zDO.GetInt("muckheim_revival_kind", -1) == 0 && zDO.GetString("muckheim_revival_identity", "") == "world")
				{
					return zDO;
				}
			}
			return null;
		}

		private void LoadParticipants()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			foreach (ZDOID item in ZDOExtraData.GetAllZDOIDsWithHash((Type)3, StateMarker))
			{
				ZDO zDO = ZDOMan.instance.GetZDO(item);
				if (zDO == null || !zDO.IsValid() || !zDO.GetBool(StateMarker, false))
				{
					continue;
				}
				int num = zDO.GetInt("muckheim_revival_kind", -1);
				if (num != 1 && num != 2)
				{
					continue;
				}
				string text = zDO.GetString("muckheim_revival_identity", "");
				int delaySeconds = zDO.GetInt("muckheim_revival_delay", 30);
				bool hasDied = zDO.GetBool("muckheim_revival_has_died", false);
				bool flag = zDO.GetBool("muckheim_revival_dead", false);
				ZDOID zDOID = zDO.GetZDOID("muckheim_revival_grave_id");
				Vector3 vec = zDO.GetVec3("muckheim_revival_grave_pos", Vector3.zero);
				if (string.IsNullOrEmpty(text))
				{
					Plugin.Log.LogError((object)"Ignoring a persisted revival participant with no identity.");
					continue;
				}
				Participant participant = new Participant
				{
					Key = text,
					Kind = num,
					PlayerId = zDO.GetLong("muckheim_revival_player_id", 0L),
					DummyId = zDO.GetZDOID("muckheim_revival_dummy_id"),
					Name = zDO.GetString("muckheim_revival_name", "Unknown"),
					Data = zDO,
					Rules = RevivalParticipant<string>.Restore(delaySeconds, hasDied, flag),
					GraveId = zDOID,
					LastDeathId = zDO.GetZDOID("muckheim_revival_last_death"),
					GravePosition = vec,
					HasGrave = (!((ZDOID)(ref zDOID)).IsNone() || (flag && IsValidPosition(vec))),
					PendingRespawn = zDO.GetBool("muckheim_revival_pending", false)
				};
				if (flag)
				{
					participant.Rules.RestartCountdown();
				}
				_participants[text] = participant;
				SaveParticipant(participant);
			}
		}

		private void RefreshOnlineParticipants()
		{
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: 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_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0373: Unknown result type (might be due to invalid IL or missing references)
			//IL_0397: Unknown result type (might be due to invalid IL or missing references)
			_onlinePlayers.Clear();
			_livingPlayers.Clear();
			_livingPositions.Clear();
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer == null || !peer.IsReady())
				{
					continue;
				}
				if (!_peerPlayerIds.TryGetValue(peer.m_rpc, out var value))
				{
					_onlinePlayers.Add("J:" + peer.m_uid);
					_livingPlayers.Add("J:" + peer.m_uid);
					continue;
				}
				string text = PlayerKey(value);
				_onlinePlayers.Add(text);
				if (((ZDOID)(ref peer.m_characterID)).IsNone())
				{
					continue;
				}
				ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID);
				if (zDO != null && zDO.IsValid())
				{
					if (zDO.GetBool(ZDOVars.s_dead, false))
					{
						ZDO val = FindGrave(value, zDO.GetPosition());
						RecordPlayerDeath(value, peer.m_playerName, zDO.GetPosition(), val?.m_uid ?? ZDOID.None, zDO.m_uid);
					}
					else
					{
						_livingPlayers.Add(text);
						_livingPositions[text] = zDO.GetPosition();
					}
				}
			}
			Game instance = Game.instance;
			PlayerProfile val2 = (((Object)(object)instance != (Object)null) ? instance.GetPlayerProfile() : null);
			Player localPlayer = Player.m_localPlayer;
			if (val2 != null && (Object.op_Implicit((Object)(object)localPlayer) || ZNet.IsSinglePlayer))
			{
				long playerID = val2.GetPlayerID();
				if (playerID != 0L)
				{
					string text2 = PlayerKey(playerID);
					_onlinePlayers.Add(text2);
					if (Object.op_Implicit((Object)(object)localPlayer) && !((Character)localPlayer).IsDead())
					{
						_livingPlayers.Add(text2);
						_livingPositions[text2] = ((Component)localPlayer).transform.position;
					}
					else if (Object.op_Implicit((Object)(object)localPlayer) && ((Character)localPlayer).IsDead())
					{
						ZDO val3 = FindGrave(playerID, ((Component)localPlayer).transform.position);
						RecordPlayerDeath(playerID, val2.GetName(), ((Component)localPlayer).transform.position, val3?.m_uid ?? ZDOID.None, ((Component)localPlayer).GetComponent<ZNetView>().GetZDO().m_uid);
					}
				}
			}
			foreach (string onlinePlayer in _onlinePlayers)
			{
				if (_participants.TryGetValue(onlinePlayer, out var value2))
				{
					if (value2.Rules.IsDead && !value2.WasOnline)
					{
						value2.Rules.RestartCountdown();
						SaveParticipant(value2);
					}
					value2.WasOnline = true;
				}
			}
			foreach (Participant value3 in _participants.Values)
			{
				if (value3.Kind == 1 && !_onlinePlayers.Contains(value3.Key))
				{
					value3.WasOnline = false;
				}
			}
			foreach (ZDO item in TestDummies.AllParticipants())
			{
				if (!item.GetBool(ZDOVars.s_dead, false))
				{
					string text3 = DummyKey(item.m_uid);
					_livingPlayers.Add(text3);
					_livingPositions[text3] = item.GetPosition();
				}
				else
				{
					RecordDummyDeath(item);
				}
			}
		}

		private void ProcessSunrises()
		{
			long num = SunriseIndex(ZNet.instance.GetTimeSeconds());
			if (num > _lastSunriseIndex)
			{
				int count = (int)Math.Min(2147483647L, num - _lastSunriseIndex);
				foreach (Participant value in _participants.Values)
				{
					value.Rules.Sunrise(count);
					SaveParticipant(value);
				}
				_lastSunriseIndex = num;
				_worldData.Set("muckheim_revival_sunrise", _lastSunriseIndex);
				Plugin.Log.LogInfo((object)("Applied " + count + " sunrise penalty reduction(s)."));
			}
			else if (num < _lastSunriseIndex)
			{
				_lastSunriseIndex = num;
				_worldData.Set("muckheim_revival_sunrise", num);
			}
		}

		private static long SunriseIndex(double time)
		{
			return (long)Math.Floor((time - 120.0) / 480.0);
		}

		private void TickParticipants(float elapsed)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			foreach (Participant item in _participants.Values.ToList())
			{
				if (!item.Rules.IsDead || (item.Kind == 2 && !TestDummies.IsDummy(ZDOMan.instance.GetZDO(item.DummyId))))
				{
					continue;
				}
				Vector3 val = (item.HasGrave ? GetCurrentGravePosition(item) : item.GravePosition);
				List<string> list = new List<string>();
				bool flag = false;
				if (item.HasGrave)
				{
					foreach (KeyValuePair<string, Vector3> livingPosition in _livingPositions)
					{
						if (!(livingPosition.Key == item.Key))
						{
							Vector3 val2 = livingPosition.Value - val;
							if (RevivalRules.IsWithinRevivalRadiusSquared(((Vector3)(ref val2)).sqrMagnitude))
							{
								list.Add(livingPosition.Key);
								flag = true;
							}
						}
					}
				}
				item.HasReviver = item.Rules.RemainingSeconds <= 0.0 && flag;
				bool isDead = item.Rules.IsDead;
				if (item.Rules.Update(elapsed, list))
				{
					if (item.Kind == 2)
					{
						if (!TestDummies.Revive(ZDOMan.instance.GetZDO(item.DummyId)))
						{
							item.Rules = RevivalParticipant<string>.Restore(item.Rules.DelaySeconds, hasDied: true, isDead: true);
							Plugin.Log.LogError((object)("Could not reactivate revived test dummy " + item.Key + "."));
							SaveParticipant(item);
							continue;
						}
					}
					else
					{
						item.PendingRespawn = true;
					}
					Plugin.Log.LogInfo((object)(item.Name + " was revived."));
				}
				if (isDead)
				{
					SaveParticipant(item);
				}
			}
		}

		private void UpdateGraves()
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			foreach (Participant value in _participants.Values)
			{
				if (!value.HasGrave)
				{
					continue;
				}
				if (value.Kind == 2)
				{
					ZDO zDO = ZDOMan.instance.GetZDO(value.DummyId);
					if (zDO != null && zDO.IsValid())
					{
						value.GravePosition = zDO.GetPosition();
						SaveParticipant(value);
					}
					continue;
				}
				ZDO zDO2 = ZDOMan.instance.GetZDO(value.GraveId);
				if (zDO2 != null && zDO2.IsValid())
				{
					zDO2.SetOwner(ZDOMan.GetSessionID());
					zDO2.Set(GraveMarker, true);
					zDO2.Set("muckheim_revival_reserved", value.Rules.IsDead || value.PendingRespawn);
					zDO2.Set("muckheim_revival_owner", value.PlayerId);
					zDO2.Set("muckheim_revival_remaining", (float)value.Rules.RemainingSeconds);
					zDO2.Set("muckheim_revival_progress", value.HasReviver);
					zDO2.Set("muckheim_revival_respawn_ready", value.PendingRespawn);
					value.GravePosition = zDO2.GetPosition();
					SaveParticipant(value);
				}
			}
		}

		private void CheckGameOver()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (_gameOver)
			{
				return;
			}
			HashSet<string> hashSet = new HashSet<string>(_onlinePlayers);
			foreach (ZDO item in TestDummies.AllParticipants())
			{
				hashSet.Add(DummyKey(item.m_uid));
			}
			int num = 0;
			foreach (string item2 in hashSet)
			{
				if (_livingPlayers.Contains(item2) || !_participants.TryGetValue(item2, out var value) || !value.Rules.IsDead)
				{
					num++;
				}
			}
			if (RevivalRules.IsGameOver(hashSet.Count, num))
			{
				_gameOver = true;
				_worldData.Set("muckheim_revival_game_over", true);
				Plugin.Log.LogError((object)"Game over: no living participants remain online. A new Muckheim world starts shortly.");
				SyncPeers();
			}
		}

		private void SyncPeers()
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null || !instance.IsServer())
			{
				return;
			}
			foreach (ZNetPeer peer in instance.GetPeers())
			{
				if (peer != null && peer.IsReady() && _peerPlayerIds.TryGetValue(peer.m_rpc, out var value))
				{
					SendState(peer.m_rpc, value);
				}
			}
		}

		private void SendState(ZRpc rpc, long playerId)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			val.Write(_gameOver);
			val.Write(playerId);
			Participant value;
			bool flag = _participants.TryGetValue(PlayerKey(playerId), out value);
			val.Write(flag);
			(flag ? new RevivalStateWire
			{
				Dead = value.Rules.IsDead,
				Delay = value.Rules.DelaySeconds,
				Remaining = (float)value.Rules.RemainingSeconds,
				Pending = value.PendingRespawn,
				HasGrave = value.HasGrave,
				GravePosition = value.GravePosition,
				Name = value.Name,
				HasReviver = value.HasReviver,
				ReviveRemaining = (float)value.Rules.ReviveRemainingSeconds
			} : RevivalStateWire.NewPlayer()).Write(val);
			List<Participant> list = _participants.Values.Where((Participant p) => p.Rules.IsDead && p.HasGrave).ToList();
			val.Write(list.Count);
			foreach (Participant item in list)
			{
				val.Write(item.Name ?? "Unknown");
				val.Write((float)item.Rules.RemainingSeconds);
				val.Write(item.GravePosition);
				val.Write(item.HasReviver);
				val.Write((float)item.Rules.ReviveRemainingSeconds);
			}
			rpc.Invoke("Muckheim_RevivalState", new object[1] { val });
		}

		private void UpdateLocalServerState()
		{
			Game instance = Game.instance;
			PlayerProfile val = (((Object)(object)instance != (Object)null) ? instance.GetPlayerProfile() : null);
			if (val != null)
			{
				if (_participants.TryGetValue(PlayerKey(val.GetPlayerID()), out var value))
				{
					SetLocalState(value, _gameOver);
					return;
				}
				_localStateKnown = _serverReady;
				_localDead = false;
				_localDeathConfirmed = false;
				_localPendingRespawn = false;
				_localHasGrave = false;
				_localGameOver = _gameOver;
				_localDelay = 30;
				_localRemaining = 0f;
				_localHasReviver = false;
				_localReviveRemaining = 5f;
			}
		}

		private static void SetLocalState(Participant participant, bool gameOver)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			_localStateKnown = true;
			_localDead = participant.Rules.IsDead;
			_localDeathConfirmed = participant.Rules.IsDead;
			_localPendingRespawn = participant.PendingRespawn;
			_localHasGrave = participant.HasGrave;
			_localGameOver = gameOver;
			_localDelay = participant.Rules.DelaySeconds;
			_localRemaining = (float)participant.Rules.RemainingSeconds;
			_localGravePosition = participant.GravePosition;
			_localHasReviver = participant.HasReviver;
			_localReviveRemaining = (float)participant.Rules.ReviveRemainingSeconds;
		}

		private void UpdateClient()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Invalid comparison between Unknown and I4
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Expected O, but got Unknown
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			ZNet instance = ZNet.instance;
			Game instance2 = Game.instance;
			PlayerProfile val = (((Object)(object)instance2 != (Object)null) ? instance2.GetPlayerProfile() : null);
			if (val == null || (int)ZNet.GetConnectionStatus() != 2)
			{
				_requestedPeer = null;
				_requestedPlayerId = 0L;
				ResetClientState();
				return;
			}
			ZNetPeer serverPeer = instance.GetServerPeer();
			if (serverPeer == null || !serverPeer.IsReady())
			{
				return;
			}
			long playerID = val.GetPlayerID();
			if (_requestedPeer != serverPeer.m_rpc || _requestedPlayerId != playerID)
			{
				_requestedPeer = serverPeer.m_rpc;
				_requestedPlayerId = playerID;
				_clientRequestAttempts = 0;
				_localStateKnown = false;
				_localDead = false;
				_localDeathConfirmed = false;
				_localPendingRespawn = false;
				_nextClientRequest = 0f;
			}
			if (!_localStateKnown && Time.realtimeSinceStartup >= _nextClientRequest)
			{
				_nextClientRequest = Time.realtimeSinceStartup + 4f;
				_clientRequestAttempts++;
				if (!_loggedClientRequestFailure && _clientRequestAttempts >= 3)
				{
					Plugin.Log.LogError((object)"No revival authorization has arrived from the server; respawn remains blocked.");
					_loggedClientRequestFailure = true;
				}
				ZPackage val2 = new ZPackage();
				val2.Write(playerID);
				serverPeer.m_rpc.Invoke("Muckheim_RevivalStateRequest", new object[1] { val2 });
			}
			if (!_localDead || _localDeathConfirmed || !(Time.realtimeSinceStartup >= _nextDeathReport))
			{
				return;
			}
			if ((Object)(object)_instance != (Object)null)
			{
				_instance._nextDeathReport = Time.realtimeSinceStartup + 4f;
				_instance._deathReportAttempts++;
				if (!_instance._loggedClientRequestFailure && _instance._deathReportAttempts >= 3)
				{
					Plugin.Log.LogError((object)"The server has not acknowledged the death report; respawn remains blocked.");
					_instance._loggedClientRequestFailure = true;
				}
			}
			SendDeathReport(_localDeathPlayerId, _localDeathPosition, _localDeathGraveId, _localDeathId);
		}

		private static void ResetClientState()
		{
			_localStateKnown = false;
			_localDead = false;
			_localDeathConfirmed = false;
			_localPendingRespawn = false;
			_localHasGrave = false;
			_localGameOver = false;
			_localHasReviver = false;
			_statusEntries.Clear();
		}

		private static void RegisterRpc(ZNetPeer peer)
		{
			peer.m_rpc.Register<ZPackage>("Muckheim_RevivalStateRequest", (Action<ZRpc, ZPackage>)HandleStateRequest);
			peer.m_rpc.Register<ZPackage>("Muckheim_RevivalState", (Action<ZRpc, ZPackage>)HandleStateResponse);
			peer.m_rpc.Register<ZPackage>("Muckheim_RevivalPlayerDeath", (Action<ZRpc, ZPackage>)HandlePlayerDeath);
			peer.m_rpc.Register<ZPackage>("Muckheim_RevivalDummyDeath", (Action<ZRpc, ZPackage>)HandleDummyDeath);
			peer.m_rpc.Register<ZPackage>("Muckheim_RevivalRespawned", (Action<ZRpc, ZPackage>)HandleRespawned);
			peer.m_rpc.Register<int>("Muckheim_RevivalRespawnCheat", (Action<ZRpc, int>)HandleRespawnCheat);
			peer.m_rpc.Register<int, string>("Muckheim_RevivalRespawnCheatResult", (Action<ZRpc, int, string>)HandleRespawnCheatResult);
		}

		private static void RegisterCommands()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			if (!(AccessTools.Field(typeof(Terminal), "commands").GetValue(null) is IDictionary<string, ConsoleCommand> dictionary))
			{
				Plugin.Log.LogError((object)"Terminal command registry not found; the respawn cheat was not registered.");
				return;
			}
			object obj = <>O.<7>__RespawnCheatCommand;
			if (obj == null)
			{
				ConsoleEvent val = RespawnCheatCommand;
				<>O.<7>__RespawnCheatCommand = val;
				obj = (object)val;
			}
			dictionary["respawn"] = new ConsoleCommand("respawn", "Instantly respawn yourself.", (ConsoleEvent)obj, true, false, false, false, false, true, (ConsoleOptionsFetcher)null, false, false, false);
			Terminal val2 = Object.FindFirstObjectByType<Terminal>();
			if ((Object)(object)val2 != (Object)null)
			{
				AccessTools.Method(typeof(Terminal), "updateCommandList", (Type[])null, (Type[])null).Invoke(val2, null);
			}
		}

		private static void RespawnCheatCommand(ConsoleEventArgs args)
		{
			if ((Object)(object)_instance == (Object)null || (Object)(object)ZNet.instance == (Object)null)
			{
				args.Context.AddString("Respawn failed: no world is connected.");
				return;
			}
			PlayerProfile val = (((Object)(object)Game.instance == (Object)null) ? null : Game.instance.GetPlayerProfile());
			if (val == null || val.GetPlayerID() == 0L)
			{
				args.Context.AddString("Respawn failed: your player identity is unavailable.");
				return;
			}
			if (ZNet.instance.IsServer())
			{
				args.Context.AddString(_instance.ForceRespawn(val.GetPlayerID()));
				return;
			}
			ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
			if (serverPeer == null || !serverPeer.IsReady())
			{
				args.Context.AddString("Respawn failed: server connection is not ready.");
				return;
			}
			if (_instance._pendingRespawnPeer != null)
			{
				args.Context.AddString("A respawn request is already pending.");
				return;
			}
			_instance._pendingRespawnPeer = serverPeer.m_rpc;
			_instance._pendingRespawnTerminal = args.Context;
			_instance._pendingRespawnRequestId = ++_instance._nextRespawnRequestId;
			_instance._pendingRespawnDeadline = Time.realtimeSinceStartup + 10f;
			serverPeer.m_rpc.Invoke("Muckheim_RevivalRespawnCheat", new object[1] { _instance._pendingRespawnRequestId });
		}

		private static void HandleRespawnCheat(ZRpc rpc, int requestId)
		{
			DeathRevival instance = _instance;
			ZNet instance2 = ZNet.instance;
			ZNetPeer val = FindPeer(rpc);
			long value;
			string text = (((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || !instance2.IsServer() || val == null || !val.IsReady()) ? "Respawn failed: server connection is not ready." : (instance._peerPlayerIds.TryGetValue(rpc, out value) ? instance.ForceRespawn(value) : "Respawn failed: your player identity is not registered."));
			rpc.Invoke("Muckheim_RevivalRespawnCheatResult", new object[2] { requestId, text });
		}

		private static void HandleRespawnCheatResult(ZRpc rpc, int requestId, string result)
		{
			if ((Object)(object)_instance == (Object)null || _instance._pendingRespawnPeer != rpc || _instance._pendingRespawnRequestId != requestId)
			{
				Plugin.Log.LogWarning((object)"Received an unexpected respawn cheat response.");
			}
			else
			{
				_instance.CompleteRespawnCheat(result);
			}
		}

		private void CompleteRespawnCheat(string result)
		{
			if ((Object)(object)_pendingRespawnTerminal != (Object)null)
			{
				_pendingRespawnTerminal.AddString(result);
			}
			else
			{
				Plugin.Log.LogWarning((object)result);
			}
			_pendingRespawnPeer = null;
			_pendingRespawnTerminal = null;
		}

		internal unsafe static string ReviveNearestDummy(Vector3 position)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			DeathRevival instance = _instance;
			if ((Object)(object)instance == (Object)null || !instance._serverReady)
			{
				return "Dummy revive failed: the revival system is not ready.";
			}
			var anon = (from p in instanc

plugins/YamlDotNet.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.CodeAnalysis;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.BufferedDeserialization;
using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators;
using YamlDotNet.Serialization.Callbacks;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("13.7.1.0")]
[assembly: AssemblyInformationalVersion("13.7.1")]
[assembly: AssemblyTitle("YamlDotNet")]
[assembly: AssemblyDescription("The YamlDotNet library.")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YamlDotNet")]
[assembly: AssemblyCopyright("Copyright (c) Antoine Aubry and contributors 2008 - 2019")]
[assembly: AssemblyTrademark("")]
[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo("YamlDotNet.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010065e52a453dde5c5b4be5bbe2205755727fce80244b79b894faf8793d80f7db9a96d360b51c220782db32aacee4cb5b8a91bee33aeec700e1f21895c4baadef501eeeac609220d1651603b378173811ee5bb6a002df973d38821bd2fef820c00c174a69faec326a1983b570f07ec66147026b9c8753465de3a8d0c44b613b02af")]
[assembly: TargetFramework(".NETFramework,Version=v4.7", FrameworkDisplayName = ".NET Framework 4.7")]
[assembly: AssemblyVersion("13.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace YamlDotNet
{
	internal sealed class CultureInfoAdapter : CultureInfo
	{
		private readonly IFormatProvider provider;

		public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider)
			: base(baseCulture.LCID)
		{
			this.provider = provider;
		}

		public override object? GetFormat(Type? formatType)
		{
			return provider.GetFormat(formatType);
		}
	}
	internal static class ReflectionExtensions
	{
		private static readonly FieldInfo? RemoteStackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);

		public static Type? BaseType(this Type type)
		{
			return type.BaseType;
		}

		public static bool IsValueType(this Type type)
		{
			return type.IsValueType;
		}

		public static bool IsGenericType(this Type type)
		{
			return type.IsGenericType;
		}

		public static bool IsGenericTypeDefinition(this Type type)
		{
			return type.IsGenericTypeDefinition;
		}

		public static bool IsInterface(this Type type)
		{
			return type.IsInterface;
		}

		public static bool IsEnum(this Type type)
		{
			return type.IsEnum;
		}

		public static bool IsDbNull(this object value)
		{
			return value is DBNull;
		}

		public static bool HasDefaultConstructor(this Type type, bool allowPrivateConstructors)
		{
			BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
			if (allowPrivateConstructors)
			{
				bindingFlags |= BindingFlags.NonPublic;
			}
			if (!type.IsValueType)
			{
				return type.GetConstructor(bindingFlags, null, Type.EmptyTypes, null) != null;
			}
			return true;
		}

		public static TypeCode GetTypeCode(this Type type)
		{
			return Type.GetTypeCode(type);
		}

		public static PropertyInfo? GetPublicProperty(this Type type, string name)
		{
			return type.GetProperty(name);
		}

		public static FieldInfo? GetPublicStaticField(this Type type, string name)
		{
			return type.GetField(name, BindingFlags.Static | BindingFlags.Public);
		}

		public static IEnumerable<PropertyInfo> GetProperties(this Type type, bool includeNonPublic)
		{
			BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
			if (includeNonPublic)
			{
				bindingFlags |= BindingFlags.NonPublic;
			}
			if (!type.IsInterface)
			{
				return type.GetProperties(bindingFlags);
			}
			return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany((Type i) => i.GetProperties(bindingFlags));
		}

		public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type)
		{
			return type.GetProperties(includeNonPublic: false);
		}

		public static IEnumerable<FieldInfo> GetPublicFields(this Type type)
		{
			return type.GetFields(BindingFlags.Instance | BindingFlags.Public);
		}

		public static IEnumerable<MethodInfo> GetPublicStaticMethods(this Type type)
		{
			return type.GetMethods(BindingFlags.Static | BindingFlags.Public);
		}

		public static MethodInfo GetPrivateStaticMethod(this Type type, string name)
		{
			return type.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'.");
		}

		public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes)
		{
			return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null);
		}

		public static MethodInfo? GetPublicInstanceMethod(this Type type, string name)
		{
			return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public);
		}

		public static Exception Unwrap(this TargetInvocationException ex)
		{
			Exception innerException = ex.InnerException;
			if (innerException == null)
			{
				return ex;
			}
			if (RemoteStackTraceField != null)
			{
				RemoteStackTraceField.SetValue(innerException, innerException.StackTrace + "\r\n");
			}
			return innerException;
		}

		public static bool IsInstanceOf(this Type type, object o)
		{
			return type.IsInstanceOfType(o);
		}

		public static Attribute[] GetAllCustomAttributes<TAttribute>(this PropertyInfo property)
		{
			return Attribute.GetCustomAttributes(property, typeof(TAttribute), inherit: true);
		}
	}
	internal static class PropertyInfoExtensions
	{
		public static object? ReadValue(this PropertyInfo property, object target)
		{
			return property.GetValue(target, null);
		}
	}
	internal static class StandardRegexOptions
	{
		public const RegexOptions Compiled = RegexOptions.Compiled;
	}
}
namespace YamlDotNet.Serialization
{
	public abstract class BuilderSkeleton<TBuilder> where TBuilder : BuilderSkeleton<TBuilder>
	{
		internal INamingConvention namingConvention = NullNamingConvention.Instance;

		internal ITypeResolver typeResolver;

		internal readonly YamlAttributeOverrides overrides;

		internal readonly LazyComponentRegistrationList<Nothing, IYamlTypeConverter> typeConverterFactories;

		internal readonly LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories;

		internal bool ignoreFields;

		internal bool includeNonPublicProperties;

		internal Settings settings;

		internal YamlFormatter yamlFormatter = YamlFormatter.Default;

		protected abstract TBuilder Self { get; }

		internal BuilderSkeleton(ITypeResolver typeResolver)
		{
			overrides = new YamlAttributeOverrides();
			typeConverterFactories = new LazyComponentRegistrationList<Nothing, IYamlTypeConverter>
			{
				{
					typeof(YamlDotNet.Serialization.Converters.GuidConverter),
					(Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false)
				},
				{
					typeof(SystemTypeConverter),
					(Nothing _) => new SystemTypeConverter()
				}
			};
			typeInspectorFactories = new LazyComponentRegistrationList<ITypeInspector, ITypeInspector>();
			this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
			settings = new Settings();
		}

		public TBuilder IgnoreFields()
		{
			ignoreFields = true;
			return Self;
		}

		public TBuilder IncludeNonPublicProperties()
		{
			includeNonPublicProperties = true;
			return Self;
		}

		public TBuilder EnablePrivateConstructors()
		{
			settings.AllowPrivateConstructors = true;
			return Self;
		}

		public TBuilder WithNamingConvention(INamingConvention namingConvention)
		{
			this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention");
			return Self;
		}

		public TBuilder WithTypeResolver(ITypeResolver typeResolver)
		{
			this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
			return Self;
		}

		public abstract TBuilder WithTagMapping(TagName tag, Type type);

		public TBuilder WithAttributeOverride<TClass>(Expression<Func<TClass, object>> propertyAccessor, Attribute attribute)
		{
			overrides.Add(propertyAccessor, attribute);
			return Self;
		}

		public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute)
		{
			overrides.Add(type, member, attribute);
			return Self;
		}

		public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter)
		{
			return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action<IRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where)
		{
			if (typeConverter == null)
			{
				throw new ArgumentNullException("typeConverter");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), (Nothing _) => typeConverter));
			return Self;
		}

		public TBuilder WithTypeConverter<TYamlTypeConverter>(WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) where TYamlTypeConverter : IYamlTypeConverter
		{
			if (typeConverterFactory == null)
			{
				throw new ArgumentNullException("typeConverterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory(wrapped)));
			return Self;
		}

		public TBuilder WithoutTypeConverter<TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter
		{
			return WithoutTypeConverter(typeof(TYamlTypeConverter));
		}

		public TBuilder WithoutTypeConverter(Type converterType)
		{
			if (converterType == null)
			{
				throw new ArgumentNullException("converterType");
			}
			typeConverterFactories.Remove(converterType);
			return Self;
		}

		public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector
		{
			return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<IRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			if (typeInspectorFactory == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory(inner)));
			return Self;
		}

		public TBuilder WithTypeInspector<TTypeInspector>(WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			if (typeInspectorFactory == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory(wrapped, inner)));
			return Self;
		}

		public TBuilder WithoutTypeInspector<TTypeInspector>() where TTypeInspector : ITypeInspector
		{
			return WithoutTypeInspector(typeof(TTypeInspector));
		}

		public TBuilder WithoutTypeInspector(Type inspectorType)
		{
			if (inspectorType == null)
			{
				throw new ArgumentNullException("inspectorType");
			}
			typeInspectorFactories.Remove(inspectorType);
			return Self;
		}

		public TBuilder WithYamlFormatter(YamlFormatter formatter)
		{
			yamlFormatter = formatter ?? throw new ArgumentNullException("formatter");
			return Self;
		}

		protected IEnumerable<IYamlTypeConverter> BuildTypeConverters()
		{
			return typeConverterFactories.BuildComponentList();
		}
	}
	public delegate TComponent WrapperFactory<TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase;
	public delegate TComponent WrapperFactory<TArgument, TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase;
	[Flags]
	public enum DefaultValuesHandling
	{
		Preserve = 0,
		OmitNull = 1,
		OmitDefaults = 2,
		OmitEmptyCollections = 4
	}
	public sealed class Deserializer : IDeserializer
	{
		private readonly IValueDeserializer valueDeserializer;

		public Deserializer()
			: this(new DeserializerBuilder().BuildValueDeserializer())
		{
		}

		private Deserializer(IValueDeserializer valueDeserializer)
		{
			this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer");
		}

		public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer)
		{
			return new Deserializer(valueDeserializer);
		}

		public T Deserialize<T>(string input)
		{
			using StringReader input2 = new StringReader(input);
			return Deserialize<T>(input2);
		}

		public T Deserialize<T>(TextReader input)
		{
			return Deserialize<T>(new Parser(input));
		}

		public T Deserialize<T>(IParser parser)
		{
			return (T)Deserialize(parser, typeof(T));
		}

		public object? Deserialize(string input)
		{
			return Deserialize(input, typeof(object));
		}

		public object? Deserialize(TextReader input)
		{
			return Deserialize(input, typeof(object));
		}

		public object? Deserialize(IParser parser)
		{
			return Deserialize(parser, typeof(object));
		}

		public object? Deserialize(string input, Type type)
		{
			using StringReader input2 = new StringReader(input);
			return Deserialize(input2, type);
		}

		public object? Deserialize(TextReader input, Type type)
		{
			return Deserialize(new Parser(input), type);
		}

		public object? Deserialize(IParser parser, Type type)
		{
			if (parser == null)
			{
				throw new ArgumentNullException("parser");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			YamlDotNet.Core.Events.StreamStart @event;
			bool flag = parser.TryConsume<YamlDotNet.Core.Events.StreamStart>(out @event);
			YamlDotNet.Core.Events.DocumentStart event2;
			bool flag2 = parser.TryConsume<YamlDotNet.Core.Events.DocumentStart>(out event2);
			object result = null;
			if (!parser.Accept<YamlDotNet.Core.Events.DocumentEnd>(out var _) && !parser.Accept<YamlDotNet.Core.Events.StreamEnd>(out var _))
			{
				using SerializerState serializerState = new SerializerState();
				result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer);
				serializerState.OnDeserialization();
			}
			if (flag2)
			{
				parser.Consume<YamlDotNet.Core.Events.DocumentEnd>();
			}
			if (flag)
			{
				parser.Consume<YamlDotNet.Core.Events.StreamEnd>();
			}
			return result;
		}
	}
	public sealed class DeserializerBuilder : BuilderSkeleton<DeserializerBuilder>
	{
		private Lazy<IObjectFactory> objectFactory;

		private readonly LazyComponentRegistrationList<Nothing, INodeDeserializer> nodeDeserializerFactories;

		private readonly LazyComponentRegistrationList<Nothing, INodeTypeResolver> nodeTypeResolverFactories;

		private readonly Dictionary<TagName, Type> tagMappings;

		private readonly Dictionary<Type, Type> typeMappings;

		private readonly ITypeConverter typeConverter;

		private bool ignoreUnmatched;

		private bool duplicateKeyChecking;

		private bool attemptUnknownTypeDeserialization;

		protected override DeserializerBuilder Self => this;

		public DeserializerBuilder()
			: base((ITypeResolver)new StaticTypeResolver())
		{
			typeMappings = new Dictionary<Type, Type>();
			objectFactory = new Lazy<IObjectFactory>(() => new DefaultObjectFactory(typeMappings, settings), isThreadSafe: true);
			tagMappings = new Dictionary<TagName, Type>
			{
				{
					FailsafeSchema.Tags.Map,
					typeof(Dictionary<object, object>)
				},
				{
					FailsafeSchema.Tags.Str,
					typeof(string)
				},
				{
					JsonSchema.Tags.Bool,
					typeof(bool)
				},
				{
					JsonSchema.Tags.Float,
					typeof(double)
				},
				{
					JsonSchema.Tags.Int,
					typeof(int)
				},
				{
					DefaultSchema.Tags.Timestamp,
					typeof(DateTime)
				}
			};
			typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner));
			typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner);
			typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner));
			typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone()));
			typeInspectorFactories.Add(typeof(ReadableAndWritablePropertiesTypeInspector), (ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner));
			nodeDeserializerFactories = new LazyComponentRegistrationList<Nothing, INodeDeserializer>
			{
				{
					typeof(YamlConvertibleNodeDeserializer),
					(Nothing _) => new YamlConvertibleNodeDeserializer(objectFactory.Value)
				},
				{
					typeof(YamlSerializableNodeDeserializer),
					(Nothing _) => new YamlSerializableNodeDeserializer(objectFactory.Value)
				},
				{
					typeof(TypeConverterNodeDeserializer),
					(Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters())
				},
				{
					typeof(NullNodeDeserializer),
					(Nothing _) => new NullNodeDeserializer()
				},
				{
					typeof(ScalarNodeDeserializer),
					(Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter, yamlFormatter)
				},
				{
					typeof(ArrayNodeDeserializer),
					(Nothing _) => new ArrayNodeDeserializer()
				},
				{
					typeof(DictionaryNodeDeserializer),
					(Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value, duplicateKeyChecking)
				},
				{
					typeof(CollectionNodeDeserializer),
					(Nothing _) => new CollectionNodeDeserializer(objectFactory.Value)
				},
				{
					typeof(EnumerableNodeDeserializer),
					(Nothing _) => new EnumerableNodeDeserializer()
				},
				{
					typeof(ObjectNodeDeserializer),
					(Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter)
				}
			};
			nodeTypeResolverFactories = new LazyComponentRegistrationList<Nothing, INodeTypeResolver>
			{
				{
					typeof(MappingNodeTypeResolver),
					(Nothing _) => new MappingNodeTypeResolver(typeMappings)
				},
				{
					typeof(YamlConvertibleTypeResolver),
					(Nothing _) => new YamlConvertibleTypeResolver()
				},
				{
					typeof(YamlSerializableTypeResolver),
					(Nothing _) => new YamlSerializableTypeResolver()
				},
				{
					typeof(TagNodeTypeResolver),
					(Nothing _) => new TagNodeTypeResolver(tagMappings)
				},
				{
					typeof(PreventUnknownTagsNodeTypeResolver),
					(Nothing _) => new PreventUnknownTagsNodeTypeResolver()
				},
				{
					typeof(DefaultContainersNodeTypeResolver),
					(Nothing _) => new DefaultContainersNodeTypeResolver()
				}
			};
			typeConverter = new ReflectionTypeConverter();
		}

		internal ITypeInspector BuildTypeInspector()
		{
			ITypeInspector typeInspector = new WritablePropertiesTypeInspector(typeResolver, includeNonPublicProperties);
			if (!ignoreFields)
			{
				typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector);
			}
			return typeInspectorFactories.BuildComponentChain(typeInspector);
		}

		public DeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization()
		{
			attemptUnknownTypeDeserialization = true;
			return this;
		}

		public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory)
		{
			if (objectFactory == null)
			{
				throw new ArgumentNullException("objectFactory");
			}
			this.objectFactory = new Lazy<IObjectFactory>(() => objectFactory, isThreadSafe: true);
			return this;
		}

		public DeserializerBuilder WithObjectFactory(Func<Type, object> objectFactory)
		{
			if (objectFactory == null)
			{
				throw new ArgumentNullException("objectFactory");
			}
			return WithObjectFactory(new LambdaObjectFactory(objectFactory));
		}

		public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer)
		{
			return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> w)
			{
				w.OnTop();
			});
		}

		public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<IRegistrationLocationSelectionSyntax<INodeDeserializer>> where)
		{
			if (nodeDeserializer == null)
			{
				throw new ArgumentNullException("nodeDeserializer");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), (Nothing _) => nodeDeserializer));
			return this;
		}

		public DeserializerBuilder WithNodeDeserializer<TNodeDeserializer>(WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> where) where TNodeDeserializer : INodeDeserializer
		{
			if (nodeDeserializerFactory == null)
			{
				throw new ArgumentNullException("nodeDeserializerFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory(wrapped)));
			return this;
		}

		public DeserializerBuilder WithoutNodeDeserializer<TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer
		{
			return WithoutNodeDeserializer(typeof(TNodeDeserializer));
		}

		public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType)
		{
			if (nodeDeserializerType == null)
			{
				throw new ArgumentNullException("nodeDeserializerType");
			}
			nodeDeserializerFactories.Remove(nodeDeserializerType);
			return this;
		}

		public DeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action<ITypeDiscriminatingNodeDeserializerOptions> configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1)
		{
			TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions();
			configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions);
			TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength);
			return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> s)
			{
				s.Before<DictionaryNodeDeserializer>();
			});
		}

		public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver)
		{
			return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax<INodeTypeResolver> w)
			{
				w.OnTop();
			});
		}

		public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where)
		{
			if (nodeTypeResolver == null)
			{
				throw new ArgumentNullException("nodeTypeResolver");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), (Nothing _) => nodeTypeResolver));
			return this;
		}

		public DeserializerBuilder WithNodeTypeResolver<TNodeTypeResolver>(WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) where TNodeTypeResolver : INodeTypeResolver
		{
			if (nodeTypeResolverFactory == null)
			{
				throw new ArgumentNullException("nodeTypeResolverFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory(wrapped)));
			return this;
		}

		public DeserializerBuilder WithoutNodeTypeResolver<TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver
		{
			return WithoutNodeTypeResolver(typeof(TNodeTypeResolver));
		}

		public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType)
		{
			if (nodeTypeResolverType == null)
			{
				throw new ArgumentNullException("nodeTypeResolverType");
			}
			nodeTypeResolverFactories.Remove(nodeTypeResolverType);
			return this;
		}

		public override DeserializerBuilder WithTagMapping(TagName tag, Type type)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (tagMappings.TryGetValue(tag, out Type value))
			{
				throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag");
			}
			tagMappings.Add(tag, type);
			return this;
		}

		public DeserializerBuilder WithTypeMapping<TInterface, TConcrete>() where TConcrete : TInterface
		{
			Type typeFromHandle = typeof(TInterface);
			Type typeFromHandle2 = typeof(TConcrete);
			if (!typeFromHandle.IsAssignableFrom(typeFromHandle2))
			{
				throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'.");
			}
			if (typeMappings.ContainsKey(typeFromHandle))
			{
				typeMappings[typeFromHandle] = typeFromHandle2;
			}
			else
			{
				typeMappings.Add(typeFromHandle, typeFromHandle2);
			}
			return this;
		}

		public DeserializerBuilder WithoutTagMapping(TagName tag)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (!tagMappings.Remove(tag))
			{
				throw new KeyNotFoundException($"Tag '{tag}' is not registered");
			}
			return this;
		}

		public DeserializerBuilder IgnoreUnmatchedProperties()
		{
			ignoreUnmatched = true;
			return this;
		}

		public DeserializerBuilder WithDuplicateKeyChecking()
		{
			duplicateKeyChecking = true;
			return this;
		}

		public IDeserializer Build()
		{
			return Deserializer.FromValueDeserializer(BuildValueDeserializer());
		}

		public IValueDeserializer BuildValueDeserializer()
		{
			return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter));
		}
	}
	public sealed class EmissionPhaseObjectGraphVisitorArgs
	{
		private readonly IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors;

		public IObjectGraphVisitor<IEmitter> InnerVisitor { get; private set; }

		public IEventEmitter EventEmitter { get; private set; }

		public ObjectSerializer NestedObjectSerializer { get; private set; }

		public IEnumerable<IYamlTypeConverter> TypeConverters { get; private set; }

		public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor<IEmitter> innerVisitor, IEventEmitter eventEmitter, IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors, IEnumerable<IYamlTypeConverter> typeConverters, ObjectSerializer nestedObjectSerializer)
		{
			InnerVisitor = innerVisitor ?? throw new ArgumentNullException("innerVisitor");
			EventEmitter = eventEmitter ?? throw new ArgumentNullException("eventEmitter");
			this.preProcessingPhaseVisitors = preProcessingPhaseVisitors ?? throw new ArgumentNullException("preProcessingPhaseVisitors");
			TypeConverters = typeConverters ?? throw new ArgumentNullException("typeConverters");
			NestedObjectSerializer = nestedObjectSerializer ?? throw new ArgumentNullException("nestedObjectSerializer");
		}

		public T GetPreProcessingPhaseObjectGraphVisitor<T>() where T : IObjectGraphVisitor<Nothing>
		{
			return preProcessingPhaseVisitors.OfType<T>().Single();
		}
	}
	public abstract class EventInfo
	{
		public IObjectDescriptor Source { get; }

		protected EventInfo(IObjectDescriptor source)
		{
			Source = source ?? throw new ArgumentNullException("source");
		}
	}
	public class AliasEventInfo : EventInfo
	{
		public AnchorName Alias { get; }

		public bool NeedsExpansion { get; set; }

		public AliasEventInfo(IObjectDescriptor source, AnchorName alias)
			: base(source)
		{
			if (alias.IsEmpty)
			{
				throw new ArgumentNullException("alias");
			}
			Alias = alias;
		}
	}
	public class ObjectEventInfo : EventInfo
	{
		public AnchorName Anchor { get; set; }

		public TagName Tag { get; set; }

		protected ObjectEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class ScalarEventInfo : ObjectEventInfo
	{
		public string RenderedValue { get; set; }

		public ScalarStyle Style { get; set; }

		public bool IsPlainImplicit { get; set; }

		public bool IsQuotedImplicit { get; set; }

		public ScalarEventInfo(IObjectDescriptor source)
			: base(source)
		{
			Style = source.ScalarStyle;
			RenderedValue = string.Empty;
		}
	}
	public sealed class MappingStartEventInfo : ObjectEventInfo
	{
		public bool IsImplicit { get; set; }

		public MappingStyle Style { get; set; }

		public MappingStartEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class MappingEndEventInfo : EventInfo
	{
		public MappingEndEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class SequenceStartEventInfo : ObjectEventInfo
	{
		public bool IsImplicit { get; set; }

		public SequenceStyle Style { get; set; }

		public SequenceStartEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class SequenceEndEventInfo : EventInfo
	{
		public SequenceEndEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public interface IAliasProvider
	{
		AnchorName GetAlias(object target);
	}
	public interface IDeserializer
	{
		T Deserialize<T>(string input);

		T Deserialize<T>(TextReader input);

		T Deserialize<T>(IParser parser);

		object? Deserialize(string input);

		object? Deserialize(TextReader input);

		object? Deserialize(IParser parser);

		object? Deserialize(string input, Type type);

		object? Deserialize(TextReader input, Type type);

		object? Deserialize(IParser parser, Type type);
	}
	public interface IEventEmitter
	{
		void Emit(AliasEventInfo eventInfo, IEmitter emitter);

		void Emit(ScalarEventInfo eventInfo, IEmitter emitter);

		void Emit(MappingStartEventInfo eventInfo, IEmitter emitter);

		void Emit(MappingEndEventInfo eventInfo, IEmitter emitter);

		void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter);

		void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter);
	}
	public interface INamingConvention
	{
		string Apply(string value);
	}
	public interface INodeDeserializer
	{
		bool Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value);
	}
	public interface INodeTypeResolver
	{
		bool Resolve(NodeEvent? nodeEvent, ref Type currentType);
	}
	public interface IObjectAccessor
	{
		void Set(string name, object target, object value);

		object? Read(string name, object target);
	}
	public interface IObjectDescriptor
	{
		object? Value { get; }

		Type Type { get; }

		Type StaticType { get; }

		ScalarStyle ScalarStyle { get; }
	}
	public static class ObjectDescriptorExtensions
	{
		public static object NonNullValue(this IObjectDescriptor objectDescriptor)
		{
			return objectDescriptor.Value ?? throw new InvalidOperationException("Attempted to use a IObjectDescriptor of type '" + objectDescriptor.Type.FullName + "' whose Value is null at a point whete it is invalid to do so. This may indicate a bug in YamlDotNet.");
		}
	}
	public interface IObjectFactory
	{
		object Create(Type type);

		object? CreatePrimitive(Type type);

		bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments);

		Type GetValueType(Type type);

		void ExecuteOnDeserializing(object value);

		void ExecuteOnDeserialized(object value);

		void ExecuteOnSerializing(object value);

		void ExecuteOnSerialized(object value);
	}
	public interface IObjectGraphTraversalStrategy
	{
		void Traverse<TContext>(IObjectDescriptor graph, IObjectGraphVisitor<TContext> visitor, TContext context);
	}
	public interface IObjectGraphVisitor<TContext>
	{
		bool Enter(IObjectDescriptor value, TContext context);

		bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context);

		bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context);

		void VisitScalar(IObjectDescriptor scalar, TContext context);

		void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context);

		void VisitMappingEnd(IObjectDescriptor mapping, TContext context);

		void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context);

		void VisitSequenceEnd(IObjectDescriptor sequence, TContext context);
	}
	public interface IPropertyDescriptor
	{
		string Name { get; }

		bool CanWrite { get; }

		Type Type { get; }

		Type? TypeOverride { get; set; }

		int Order { get; set; }

		ScalarStyle ScalarStyle { get; set; }

		T? GetCustomAttribute<T>() where T : Attribute;

		IObjectDescriptor Read(object target);

		void Write(object target, object? value);
	}
	public interface IRegistrationLocationSelectionSyntax<TBaseRegistrationType>
	{
		void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void Before<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void After<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void OnTop();

		void OnBottom();
	}
	public interface ITrackingRegistrationLocationSelectionSyntax<TBaseRegistrationType>
	{
		void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;
	}
	public interface ISerializer
	{
		string Serialize(object? graph);

		string Serialize(object? graph, Type type);

		void Serialize(TextWriter writer, object? graph);

		void Serialize(TextWriter writer, object? graph, Type type);

		void Serialize(IEmitter emitter, object? graph);

		void Serialize(IEmitter emitter, object? graph, Type type);
	}
	public interface ITypeInspector
	{
		IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container);

		IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched);
	}
	public interface ITypeResolver
	{
		Type Resolve(Type staticType, object? actualValue);
	}
	public interface IValueDeserializer
	{
		object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer);
	}
	public interface IValuePromise
	{
		event Action<object?> ValueAvailable;
	}
	public interface IValueSerializer
	{
		void SerializeValue(IEmitter emitter, object? value, Type? type);
	}
	public interface IYamlConvertible
	{
		void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer);

		void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer);
	}
	public delegate object? ObjectDeserializer(Type type);
	public delegate void ObjectSerializer(object? value, Type? type = null);
	[Obsolete("Please use IYamlConvertible instead")]
	public interface IYamlSerializable
	{
		void ReadYaml(IParser parser);

		void WriteYaml(IEmitter emitter);
	}
	public interface IYamlTypeConverter
	{
		bool Accepts(Type type);

		object? ReadYaml(IParser parser, Type type);

		void WriteYaml(IEmitter emitter, object? value, Type type);
	}
	internal sealed class LazyComponentRegistrationList<TArgument, TComponent> : IEnumerable<Func<TArgument, TComponent>>, IEnumerable
	{
		public sealed class LazyComponentRegistration
		{
			public readonly Type ComponentType;

			public readonly Func<TArgument, TComponent> Factory;

			public LazyComponentRegistration(Type componentType, Func<TArgument, TComponent> factory)
			{
				ComponentType = componentType;
				Factory = factory;
			}
		}

		public sealed class TrackingLazyComponentRegistration
		{
			public readonly Type ComponentType;

			public readonly Func<TComponent, TArgument, TComponent> Factory;

			public TrackingLazyComponentRegistration(Type componentType, Func<TComponent, TArgument, TComponent> factory)
			{
				ComponentType = componentType;
				Factory = factory;
			}
		}

		private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax<TComponent>
		{
			private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations;

			private readonly LazyComponentRegistration newRegistration;

			public RegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, LazyComponentRegistration newRegistration)
			{
				this.registrations = registrations;
				this.newRegistration = newRegistration;
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>()
			{
				if (newRegistration.ComponentType != typeof(TRegistrationType))
				{
					registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				}
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries[index] = newRegistration;
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.After<TRegistrationType>()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				int num = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries.Insert(num + 1, newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.Before<TRegistrationType>()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries.Insert(index, newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.OnBottom()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				registrations.entries.Add(newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.OnTop()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				registrations.entries.Insert(0, newRegistration);
			}
		}

		private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax<TComponent>
		{
			private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations;

			private readonly TrackingLazyComponentRegistration newRegistration;

			public TrackingRegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, TrackingLazyComponentRegistration newRegistration)
			{
				this.registrations = registrations;
				this.newRegistration = newRegistration;
			}

			void ITrackingRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>()
			{
				if (newRegistration.ComponentType != typeof(TRegistrationType))
				{
					registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				}
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				Func<TArgument, TComponent> innerComponentFactory = registrations.entries[index].Factory;
				registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg));
			}
		}

		private readonly List<LazyComponentRegistration> entries = new List<LazyComponentRegistration>();

		public int Count => entries.Count;

		public IEnumerable<Func<TArgument, TComponent>> InReverseOrder
		{
			get
			{
				int i = entries.Count - 1;
				while (i >= 0)
				{
					yield return entries[i].Factory;
					int num = i - 1;
					i = num;
				}
			}
		}

		public LazyComponentRegistrationList<TArgument, TComponent> Clone()
		{
			LazyComponentRegistrationList<TArgument, TComponent> lazyComponentRegistrationList = new LazyComponentRegistrationList<TArgument, TComponent>();
			foreach (LazyComponentRegistration entry in entries)
			{
				lazyComponentRegistrationList.entries.Add(entry);
			}
			return lazyComponentRegistrationList;
		}

		public void Clear()
		{
			entries.Clear();
		}

		public void Add(Type componentType, Func<TArgument, TComponent> factory)
		{
			entries.Add(new LazyComponentRegistration(componentType, factory));
		}

		public void Remove(Type componentType)
		{
			for (int i = 0; i < entries.Count; i++)
			{
				if (entries[i].ComponentType == componentType)
				{
					entries.RemoveAt(i);
					return;
				}
			}
			throw new KeyNotFoundException("A component registration of type '" + componentType.FullName + "' was not found.");
		}

		public IRegistrationLocationSelectionSyntax<TComponent> CreateRegistrationLocationSelector(Type componentType, Func<TArgument, TComponent> factory)
		{
			return new RegistrationLocationSelector(this, new LazyComponentRegistration(componentType, factory));
		}

		public ITrackingRegistrationLocationSelectionSyntax<TComponent> CreateTrackingRegistrationLocationSelector(Type componentType, Func<TComponent, TArgument, TComponent> factory)
		{
			return new TrackingRegistrationLocationSelector(this, new TrackingLazyComponentRegistration(componentType, factory));
		}

		public IEnumerator<Func<TArgument, TComponent>> GetEnumerator()
		{
			return entries.Select((LazyComponentRegistration e) => e.Factory).GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		private int IndexOfRegistration(Type registrationType)
		{
			for (int i = 0; i < entries.Count; i++)
			{
				if (registrationType == entries[i].ComponentType)
				{
					return i;
				}
			}
			return -1;
		}

		private void EnsureNoDuplicateRegistrationType(Type componentType)
		{
			if (IndexOfRegistration(componentType) != -1)
			{
				throw new InvalidOperationException("A component of type '" + componentType.FullName + "' has already been registered.");
			}
		}

		private int EnsureRegistrationExists<TRegistrationType>()
		{
			int num = IndexOfRegistration(typeof(TRegistrationType));
			if (num == -1)
			{
				throw new InvalidOperationException("A component of type '" + typeof(TRegistrationType).FullName + "' has not been registered.");
			}
			return num;
		}
	}
	internal static class LazyComponentRegistrationListExtensions
	{
		public static TComponent BuildComponentChain<TComponent>(this LazyComponentRegistrationList<TComponent, TComponent> registrations, TComponent innerComponent)
		{
			return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TComponent, TComponent> factory) => factory(inner));
		}

		public static TComponent BuildComponentChain<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TComponent innerComponent, Func<TComponent, TArgument> argumentBuilder)
		{
			return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TArgument, TComponent> factory) => factory(argumentBuilder(inner)));
		}

		public static List<TComponent> BuildComponentList<TComponent>(this LazyComponentRegistrationList<Nothing, TComponent> registrations)
		{
			return registrations.Select((Func<Nothing, TComponent> factory) => factory(default(Nothing))).ToList();
		}

		public static List<TComponent> BuildComponentList<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TArgument argument)
		{
			return registrations.Select((Func<TArgument, TComponent> factory) => factory(argument)).ToList();
		}
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	public struct Nothing
	{
	}
	public sealed class ObjectDescriptor : IObjectDescriptor
	{
		public object? Value { get; private set; }

		public Type Type { get; private set; }

		public Type StaticType { get; private set; }

		public ScalarStyle ScalarStyle { get; private set; }

		public ObjectDescriptor(object? value, Type type, Type staticType)
			: this(value, type, staticType, ScalarStyle.Any)
		{
		}

		public ObjectDescriptor(object? value, Type type, Type staticType, ScalarStyle scalarStyle)
		{
			Value = value;
			Type = type ?? throw new ArgumentNullException("type");
			StaticType = staticType ?? throw new ArgumentNullException("staticType");
			ScalarStyle = scalarStyle;
		}
	}
	public delegate IObjectGraphTraversalStrategy ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion);
	public sealed class PropertyDescriptor : IPropertyDescriptor
	{
		private readonly IPropertyDescriptor baseDescriptor;

		public string Name { get; set; }

		public Type Type => baseDescriptor.Type;

		public Type? TypeOverride
		{
			get
			{
				return baseDescriptor.TypeOverride;
			}
			set
			{
				baseDescriptor.TypeOverride = value;
			}
		}

		public int Order { get; set; }

		public ScalarStyle ScalarStyle
		{
			get
			{
				return baseDescriptor.ScalarStyle;
			}
			set
			{
				baseDescriptor.ScalarStyle = value;
			}
		}

		public bool CanWrite => baseDescriptor.CanWrite;

		public PropertyDescriptor(IPropertyDescriptor baseDescriptor)
		{
			this.baseDescriptor = baseDescriptor;
			Name = baseDescriptor.Name;
		}

		public void Write(object target, object? value)
		{
			baseDescriptor.Write(target, value);
		}

		public T? GetCustomAttribute<T>() where T : Attribute
		{
			return baseDescriptor.GetCustomAttribute<T>();
		}

		public IObjectDescriptor Read(object target)
		{
			return baseDescriptor.Read(target);
		}
	}
	public sealed class Serializer : ISerializer
	{
		private readonly IValueSerializer valueSerializer;

		private readonly EmitterSettings emitterSettings;

		public Serializer()
			: this(new SerializerBuilder().BuildValueSerializer(), EmitterSettings.Default)
		{
		}

		private Serializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings)
		{
			this.valueSerializer = valueSerializer ?? throw new ArgumentNullException("valueSerializer");
			this.emitterSettings = emitterSettings ?? throw new ArgumentNullException("emitterSettings");
		}

		public static Serializer FromValueSerializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings)
		{
			return new Serializer(valueSerializer, emitterSettings);
		}

		public string Serialize(object? graph)
		{
			using StringWriter stringWriter = new StringWriter();
			Serialize(stringWriter, graph);
			return stringWriter.ToString();
		}

		public string Serialize(object? graph, Type type)
		{
			using StringWriter stringWriter = new StringWriter();
			Serialize(stringWriter, graph, type);
			return stringWriter.ToString();
		}

		public void Serialize(TextWriter writer, object? graph)
		{
			Serialize(new Emitter(writer, emitterSettings), graph);
		}

		public void Serialize(TextWriter writer, object? graph, Type type)
		{
			Serialize(new Emitter(writer, emitterSettings), graph, type);
		}

		public void Serialize(IEmitter emitter, object? graph)
		{
			if (emitter == null)
			{
				throw new ArgumentNullException("emitter");
			}
			EmitDocument(emitter, graph, null);
		}

		public void Serialize(IEmitter emitter, object? graph, Type type)
		{
			if (emitter == null)
			{
				throw new ArgumentNullException("emitter");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			EmitDocument(emitter, graph, type);
		}

		private void EmitDocument(IEmitter emitter, object? graph, Type? type)
		{
			emitter.Emit(new YamlDotNet.Core.Events.StreamStart());
			emitter.Emit(new YamlDotNet.Core.Events.DocumentStart());
			valueSerializer.SerializeValue(emitter, graph, type);
			emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: true));
			emitter.Emit(new YamlDotNet.Core.Events.StreamEnd());
		}
	}
	public sealed class SerializerBuilder : BuilderSkeleton<SerializerBuilder>
	{
		private class ValueSerializer : IValueSerializer
		{
			private readonly IObjectGraphTraversalStrategy traversalStrategy;

			private readonly IEventEmitter eventEmitter;

			private readonly IEnumerable<IYamlTypeConverter> typeConverters;

			private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;

			private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;

			public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable<IYamlTypeConverter> typeConverters, LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories)
			{
				this.traversalStrategy = traversalStrategy;
				this.eventEmitter = eventEmitter;
				this.typeConverters = typeConverters;
				this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories;
				this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories;
			}

			public void SerializeValue(IEmitter emitter, object? value, Type? type)
			{
				Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object));
				Type staticType = type ?? typeof(object);
				ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType);
				List<IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters);
				foreach (IObjectGraphVisitor<Nothing> item in preProcessingPhaseObjectGraphVisitors)
				{
					traversalStrategy.Traverse(graph, item, default(Nothing));
				}
				IObjectGraphVisitor<IEmitter> visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor<IEmitter> inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer));
				traversalStrategy.Traverse(graph, visitor, emitter);
				void NestedObjectSerializer(object? v, Type? t)
				{
					SerializeValue(emitter, v, t);
				}
			}
		}

		private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory;

		private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;

		private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;

		private readonly LazyComponentRegistrationList<IEventEmitter, IEventEmitter> eventEmitterFactories;

		private readonly IDictionary<Type, TagName> tagMappings = new Dictionary<Type, TagName>();

		private readonly IObjectFactory objectFactory;

		private int maximumRecursion = 50;

		private EmitterSettings emitterSettings = EmitterSettings.Default;

		private DefaultValuesHandling defaultValuesHandlingConfiguration;

		private ScalarStyle defaultScalarStyle;

		private bool quoteNecessaryStrings;

		private bool quoteYaml1_1Strings;

		protected override SerializerBuilder Self => this;

		public SerializerBuilder()
			: base((ITypeResolver)new DynamicTypeResolver())
		{
			typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner));
			typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner);
			typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner));
			typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone()));
			preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> { 
			{
				typeof(AnchorAssigner),
				(IEnumerable<IYamlTypeConverter> typeConverters) => new AnchorAssigner(typeConverters)
			} };
			emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>
			{
				{
					typeof(CustomSerializationObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer)
				},
				{
					typeof(AnchorAssigningObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor<AnchorAssigner>())
				},
				{
					typeof(DefaultValuesObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, new DefaultObjectFactory())
				},
				{
					typeof(CommentsObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor)
				}
			};
			eventEmitterFactories = new LazyComponentRegistrationList<IEventEmitter, IEventEmitter> { 
			{
				typeof(TypeAssigningEventEmitter),
				(IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter)
			} };
			objectFactory = new DefaultObjectFactory();
			objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, objectFactory);
		}

		public SerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false)
		{
			quoteNecessaryStrings = true;
			this.quoteYaml1_1Strings = quoteYaml1_1Strings;
			return this;
		}

		public SerializerBuilder WithDefaultScalarStyle(ScalarStyle style)
		{
			defaultScalarStyle = style;
			return this;
		}

		public SerializerBuilder WithMaximumRecursion(int maximumRecursion)
		{
			if (maximumRecursion <= 0)
			{
				throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer.");
			}
			this.maximumRecursion = maximumRecursion;
			return this;
		}

		public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter
		{
			return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory, Action<IRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter
		{
			if (eventEmitterFactory == null)
			{
				throw new ArgumentNullException("eventEmitterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory(inner)));
			return Self;
		}

		public SerializerBuilder WithEventEmitter<TEventEmitter>(WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter
		{
			if (eventEmitterFactory == null)
			{
				throw new ArgumentNullException("eventEmitterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory(wrapped, inner)));
			return Self;
		}

		public SerializerBuilder WithoutEventEmitter<TEventEmitter>() where TEventEmitter : IEventEmitter
		{
			return WithoutEventEmitter(typeof(TEventEmitter));
		}

		public SerializerBuilder WithoutEventEmitter(Type eventEmitterType)
		{
			if (eventEmitterType == null)
			{
				throw new ArgumentNullException("eventEmitterType");
			}
			eventEmitterFactories.Remove(eventEmitterType);
			return this;
		}

		public override SerializerBuilder WithTagMapping(TagName tag, Type type)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (tagMappings.TryGetValue(type, out var value))
			{
				throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type");
			}
			tagMappings.Add(type, tag);
			return this;
		}

		public SerializerBuilder WithoutTagMapping(Type type)
		{
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (!tagMappings.Remove(type))
			{
				throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered");
			}
			return this;
		}

		public SerializerBuilder EnsureRoundtrip()
		{
			objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, objectFactory);
			WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc)
			{
				loc.InsteadOf<TypeAssigningEventEmitter>();
			});
			return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> loc)
			{
				loc.OnBottom();
			});
		}

		public SerializerBuilder DisableAliases()
		{
			preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner));
			emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor));
			return this;
		}

		[Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)]
		public SerializerBuilder EmitDefaults()
		{
			return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve);
		}

		public SerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration)
		{
			defaultValuesHandlingConfiguration = configuration;
			return this;
		}

		public SerializerBuilder JsonCompatible()
		{
			emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName();
			return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w)
			{
				w.InsteadOf<YamlDotNet.Serialization.Converters.GuidConverter>();
			}).WithTypeConverter(new YamlDotNet.Serialization.Converters.DateTimeConverter(DateTimeKind.Utc, null, true)).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner, yamlFormatter), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc)
			{
				loc.InsteadOf<TypeAssigningEventEmitter>();
			});
		}

		public SerializerBuilder WithNewLine(string newLine)
		{
			emitterSettings = emitterSettings.WithNewLine(newLine);
			return this;
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			if (objectGraphVisitor == null)
			{
				throw new ArgumentNullException("objectGraphVisitor");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<IYamlTypeConverter> _) => objectGraphVisitor));
			return this;
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			if (objectGraphVisitorFactory == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<Nothing> wrapped, IEnumerable<IYamlTypeConverter> _) => objectGraphVisitorFactory(wrapped)));
			return this;
		}

		public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor));
		}

		public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType)
		{
			if (objectGraphVisitorType == null)
			{
				throw new ArgumentNullException("objectGraphVisitorType");
			}
			preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType);
			return this;
		}

		public SerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory)
		{
			this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory;
			return this;
		}

		public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			if (objectGraphVisitorFactory == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(args)));
			return this;
		}

		public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			if (objectGraphVisitorFactory == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<IEmitter> wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(wrapped, args)));
			return this;
		}

		public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor));
		}

		public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType)
		{
			if (objectGraphVisitorType == null)
			{
				throw new ArgumentNullException("objectGraphVisitorType");
			}
			emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType);
			return this;
		}

		public SerializerBuilder WithIndentedSequences()
		{
			emitterSettings = emitterSettings.WithIndentedSequences();
			return this;
		}

		public ISerializer Build()
		{
			return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings);
		}

		public IValueSerializer BuildValueSerializer()
		{
			IEnumerable<IYamlTypeConverter> typeConverters = BuildTypeConverters();
			ITypeInspector typeInspector = BuildTypeInspector();
			IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion);
			IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter());
			return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone());
		}

		internal ITypeInspector BuildTypeInspector()
		{
			ITypeInspector typeInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties);
			if (!ignoreFields)
			{
				typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector);
			}
			return typeInspectorFactories.BuildComponentChain(typeInspector);
		}
	}
	public class Settings
	{
		public bool AllowPrivateConstructors { get; set; }
	}
	public abstract class StaticBuilderSkeleton<TBuilder> where TBuilder : StaticBuilderSkeleton<TBuilder>
	{
		internal INamingConvention namingConvention = NullNamingConvention.Instance;

		internal ITypeResolver typeResolver;

		internal readonly LazyComponentRegistrationList<Nothing, IYamlTypeConverter> typeConverterFactories;

		internal readonly LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories;

		internal bool includeNonPublicProperties;

		internal Settings settings;

		internal YamlFormatter yamlFormatter = YamlFormatter.Default;

		protected abstract TBuilder Self { get; }

		internal StaticBuilderSkeleton(ITypeResolver typeResolver)
		{
			typeConverterFactories = new LazyComponentRegistrationList<Nothing, IYamlTypeConverter> { 
			{
				typeof(YamlDotNet.Serialization.Converters.GuidConverter),
				(Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false)
			} };
			typeInspectorFactories = new LazyComponentRegistrationList<ITypeInspector, ITypeInspector>();
			this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
			settings = new Settings();
		}

		public TBuilder WithNamingConvention(INamingConvention namingConvention)
		{
			this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention");
			return Self;
		}

		public TBuilder WithTypeResolver(ITypeResolver typeResolver)
		{
			this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
			return Self;
		}

		public abstract TBuilder WithTagMapping(TagName tag, Type type);

		public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter)
		{
			return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action<IRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where)
		{
			if (typeConverter == null)
			{
				throw new ArgumentNullException("typeConverter");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), (Nothing _) => typeConverter));
			return Self;
		}

		public TBuilder WithTypeConverter<TYamlTypeConverter>(WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) where TYamlTypeConverter : IYamlTypeConverter
		{
			if (typeConverterFactory == null)
			{
				throw new ArgumentNullException("typeConverterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory(wrapped)));
			return Self;
		}

		public TBuilder WithoutTypeConverter<TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter
		{
			return WithoutTypeConverter(typeof(TYamlTypeConverter));
		}

		public TBuilder WithoutTypeConverter(Type converterType)
		{
			if (converterType == null)
			{
				throw new ArgumentNullException("converterType");
			}
			typeConverterFactories.Remove(converterType);
			return Self;
		}

		public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector
		{
			return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<IRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			if (typeInspectorFactory == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory(inner)));
			return Self;
		}

		public TBuilder WithTypeInspector<TTypeInspector>(WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			if (typeInspectorFactory == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory(wrapped, inner)));
			return Self;
		}

		public TBuilder WithoutTypeInspector<TTypeInspector>() where TTypeInspector : ITypeInspector
		{
			return WithoutTypeInspector(typeof(TTypeInspector));
		}

		public TBuilder WithoutTypeInspector(Type inspectorType)
		{
			if (inspectorType == null)
			{
				throw new ArgumentNullException("inspectorType");
			}
			typeInspectorFactories.Remove(inspectorType);
			return Self;
		}

		public TBuilder WithYamlFormatter(YamlFormatter formatter)
		{
			yamlFormatter = formatter ?? throw new ArgumentNullException("formatter");
			return Self;
		}

		protected IEnumerable<IYamlTypeConverter> BuildTypeConverters()
		{
			return typeConverterFactories.BuildComponentList();
		}
	}
	public abstract class StaticContext
	{
		public virtual bool IsKnownType(Type type)
		{
			throw new NotImplementedException();
		}

		public virtual ITypeResolver GetTypeResolver()
		{
			throw new NotImplementedException();
		}

		public virtual StaticObjectFactory GetFactory()
		{
			throw new NotImplementedException();
		}

		public virtual ITypeInspector GetTypeInspector()
		{
			throw new NotImplementedException();
		}
	}
	public sealed class StaticDeserializerBuilder : StaticBuilderSkeleton<StaticDeserializerBuilder>
	{
		private readonly StaticContext context;

		private readonly StaticObjectFactory factory;

		private readonly LazyComponentRegistrationList<Nothing, INodeDeserializer> nodeDeserializerFactories;

		private readonly LazyComponentRegistrationList<Nothing, INodeTypeResolver> nodeTypeResolverFactories;

		private readonly Dictionary<TagName, Type> tagMappings;

		private readonly ITypeConverter typeConverter;

		private readonly Dictionary<Type, Type> typeMappings;

		private bool ignoreUnmatched;

		private bool duplicateKeyChecking;

		private bool attemptUnknownTypeDeserialization;

		protected override StaticDeserializerBuilder Self => this;

		public StaticDeserializerBuilder(StaticContext context)
			: base(context.GetTypeResolver())
		{
			this.context = context;
			factory = context.GetFactory();
			typeMappings = new Dictionary<Type, Type>();
			tagMappings = new Dictionary<TagName, Type>
			{
				{
					FailsafeSchema.Tags.Map,
					typeof(Dictionary<object, object>)
				},
				{
					FailsafeSchema.Tags.Str,
					typeof(string)
				},
				{
					JsonSchema.Tags.Bool,
					typeof(bool)
				},
				{
					JsonSchema.Tags.Float,
					typeof(double)
				},
				{
					JsonSchema.Tags.Int,
					typeof(int)
				},
				{
					DefaultSchema.Tags.Timestamp,
					typeof(DateTime)
				}
			};
			typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner));
			typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner);
			typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner));
			nodeDeserializerFactories = new LazyComponentRegistrationList<Nothing, INodeDeserializer>
			{
				{
					typeof(YamlConvertibleNodeDeserializer),
					(Nothing _) => new YamlConvertibleNodeDeserializer(factory)
				},
				{
					typeof(YamlSerializableNodeDeserializer),
					(Nothing _) => new YamlSerializableNodeDeserializer(factory)
				},
				{
					typeof(TypeConverterNodeDeserializer),
					(Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters())
				},
				{
					typeof(NullNodeDeserializer),
					(Nothing _) => new NullNodeDeserializer()
				},
				{
					typeof(ScalarNodeDeserializer),
					(Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter, yamlFormatter)
				},
				{
					typeof(StaticArrayNodeDeserializer),
					(Nothing _) => new StaticArrayNodeDeserializer(factory)
				},
				{
					typeof(StaticDictionaryNodeDeserializer),
					(Nothing _) => new StaticDictionaryNodeDeserializer(factory, duplicateKeyChecking)
				},
				{
					typeof(StaticCollectionNodeDeserializer),
					(Nothing _) => new StaticCollectionNodeDeserializer(factory)
				},
				{
					typeof(ObjectNodeDeserializer),
					(Nothing _) => new ObjectNodeDeserializer(factory, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter)
				}
			};
			nodeTypeResolverFactories = new LazyComponentRegistrationList<Nothing, INodeTypeResolver>
			{
				{
					typeof(MappingNodeTypeResolver),
					(Nothing _) => new MappingNodeTypeResolver(typeMappings)
				},
				{
					typeof(YamlConvertibleTypeResolver),
					(Nothing _) => new YamlConvertibleTypeResolver()
				},
				{
					typeof(YamlSerializableTypeResolver),
					(Nothing _) => new YamlSerializableTypeResolver()
				},
				{
					typeof(TagNodeTypeResolver),
					(Nothing _) => new TagNodeTypeResolver(tagMappings)
				},
				{
					typeof(PreventUnknownTagsNodeTypeResolver),
					(Nothing _) => new PreventUnknownTagsNodeTypeResolver()
				},
				{
					typeof(DefaultContainersNodeTypeResolver),
					(Nothing _) => new DefaultContainersNodeTypeResolver()
				}
			};
			typeConverter = new NullTypeConverter();
		}

		internal ITypeInspector BuildTypeInspector()
		{
			ITypeInspector typeInspector = context.GetTypeInspector();
			return typeInspectorFactories.BuildComponentChain(typeInspector);
		}

		public StaticDeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization()
		{
			attemptUnknownTypeDeserialization = true;
			return this;
		}

		public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer)
		{
			return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> w)
			{
				w.OnTop();
			});
		}

		public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<IRegistrationLocationSelectionSyntax<INodeDeserializer>> where)
		{
			if (nodeDeserializer == null)
			{
				throw new ArgumentNullException("nodeDeserializer");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), (Nothing _) => nodeDeserializer));
			return this;
		}

		public StaticDeserializerBuilder WithNodeDeserializer<TNodeDeserializer>(WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> where) where TNodeDeserializer : INodeDeserializer
		{
			if (nodeDeserializerFactory == null)
			{
				throw new ArgumentNullException("nodeDeserializerFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory(wrapped)));
			return this;
		}

		public StaticDeserializerBuilder WithoutNodeDeserializer<TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer
		{
			return WithoutNodeDeserializer(typeof(TNodeDeserializer));
		}

		public StaticDeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType)
		{
			if (nodeDeserializerType == null)
			{
				throw new ArgumentNullException("nodeDeserializerType");
			}
			nodeDeserializerFactories.Remove(nodeDeserializerType);
			return this;
		}

		public StaticDeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action<ITypeDiscriminatingNodeDeserializerOptions> configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1)
		{
			TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions();
			configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions);
			TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength);
			return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> s)
			{
				s.Before<DictionaryNodeDeserializer>();
			});
		}

		public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver)
		{
			return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax<INodeTypeResolver> w)
			{
				w.OnTop();
			});
		}

		public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where)
		{
			if (nodeTypeResolver == null)
			{
				throw new ArgumentNullException("nodeTypeResolver");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), (Nothing _) => nodeTypeResolver));
			return this;
		}

		public StaticDeserializerBuilder WithNodeTypeResolver<TNodeTypeResolver>(WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) where TNodeTypeResolver : INodeTypeResolver
		{
			if (nodeTypeResolverFactory == null)
			{
				throw new ArgumentNullException("nodeTypeResolverFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory(wrapped)));
			return this;
		}

		public StaticDeserializerBuilder WithoutNodeTypeResolver<TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver
		{
			return WithoutNodeTypeResolver(typeof(TNodeTypeResolver));
		}

		public StaticDeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType)
		{
			if (nodeTypeResolverType == null)
			{
				throw new ArgumentNullException("nodeTypeResolverType");
			}
			nodeTypeResolverFactories.Remove(nodeTypeResolverType);
			return this;
		}

		public override StaticDeserializerBuilder WithTagMapping(TagName tag, Type type)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (tagMappings.TryGetValue(tag, out Type value))
			{
				throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag");
			}
			tagMappings.Add(tag, type);
			return this;
		}

		public StaticDeserializerBuilder WithTypeMapping<TInterface, TConcrete>() where TConcrete : TInterface
		{
			Type typeFromHandle = typeof(TInterface);
			Type typeFromHandle2 = typeof(TConcrete);
			if (!typeFromHandle.IsAssignableFrom(typeFromHandle2))
			{
				throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'.");
			}
			if (typeMappings.ContainsKey(typeFromHandle))
			{
				typeMappings[typeFromHandle] = typeFromHandle2;
			}
			else
			{
				typeMappings.Add(typeFromHandle, typeFromHandle2);
			}
			return this;
		}

		public StaticDeserializerBuilder WithoutTagMapping(TagName tag)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (!tagMappings.Remove(tag))
			{
				throw new KeyNotFoundException($"Tag '{tag}' is not registered");
			}
			return this;
		}

		public StaticDeserializerBuilder IgnoreUnmatchedProperties()
		{
			ignoreUnmatched = true;
			return this;
		}

		public StaticDeserializerBuilder WithDuplicateKeyChecking()
		{
			duplicateKeyChecking = true;
			return this;
		}

		public IDeserializer Build()
		{
			return Deserializer.FromValueDeserializer(BuildValueDeserializer());
		}

		public IValueDeserializer BuildValueDeserializer()
		{
			return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter));
		}
	}
	public sealed class StaticSerializerBuilder : StaticBuilderSkeleton<StaticSerializerBuilder>
	{
		private class ValueSerializer : IValueSerializer
		{
			private readonly IObjectGraphTraversalStrategy traversalStrategy;

			private readonly IEventEmitter eventEmitter;

			private readonly IEnumerable<IYamlTypeConverter> typeConverters;

			private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;

			private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;

			public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable<IYamlTypeConverter> typeConverters, LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories)
			{
				this.traversalStrategy = traversalStrategy;
				this.eventEmitter = eventEmitter;
				this.typeConverters = typeConverters;
				this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories;
				this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories;
			}

			public void SerializeValue(IEmitter emitter, object? value, Type? type)
			{
				Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object));
				Type staticType = type ?? typeof(object);
				ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType);
				List<IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters);
				foreach (IObjectGraphVisitor<Nothing> item in preProcessingPhaseObjectGraphVisitors)
				{
					traversalStrategy.Traverse(graph, item, default(Nothing));
				}
				IObjectGraphVisitor<IEmitter> visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor<IEmitter> inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer));
				traversalStrategy.Traverse(graph, visitor, emitter);
				void NestedObjectSerializer(object? v, Type? t)
				{
					SerializeValue(emitter, v, t);
				}
			}
		}

		private readonly StaticContext context;

		private readonly StaticObjectFactory factory;

		private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory;

		private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;

		private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;

		private readonly LazyComponentRegistrationList<IEventEmitter, IEventEmitter> eventEmitterFactories;

		private readonly IDictionary<Type, TagName> tagMappings = new Dictionary<Type, TagName>();

		private int maximumRecursion = 50;

		private EmitterSettings emitterSettings = EmitterSettings.Default;

		private DefaultValuesHandling defaultValuesHandlingConfiguration;

		private bool quoteNecessaryStrings;

		private bool quoteYaml1_1Strings;

		private ScalarStyle defaultScalarStyle;

		protected override StaticSerializerBuilder Self => this;

		public StaticSerializerBuilder(StaticContext context)
			: base((ITypeResolver)new DynamicTypeResolver())
		{
			this.context = context;
			factory = context.GetFactory();
			typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner));
			typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner);
			typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner));
			preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> { 
			{
				typeof(AnchorAssigner),
				(IEnumerable<IYamlTypeConverter> typeConverters) => new AnchorAssigner(typeConverters)
			} };
			emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>
			{
				{
					typeof(CustomSerializationObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer)
				},
				{
					typeof(AnchorAssigningObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor<AnchorAssigner>())
				},
				{
					typeof(DefaultValuesObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, factory)
				},
				{
					typeof(CommentsObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor)
				}
			};
			eventEmitterFactories = new LazyComponentRegistrationList<IEventEmitter, IEventEmitter> { 
			{
				typeof(TypeAssigningEventEmitter),
				(IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter)
			} };
			objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, factory);
		}

		public StaticSerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false)
		{
			quoteNecessaryStrings = true;
			this.quoteYaml1_1Strings = quoteYaml1_1Strings;
			return this;
		}

		public StaticSerializerBuilder WithQuotingNecessaryStrings()
		{
			quoteNecessaryStrings = true;
			return this;
		}

		public StaticSerializerBuilder WithDefaultScalarStyle(ScalarStyle style)
		{
			defaultScalarStyle = style;
			return this;
		}

		public StaticSerializerBuilder WithMaximumRecursion(int maximumRecursion)
		{
			if (maximumRecursion <= 0)
			{
				throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer.");
			}
			this.maximumRecursion = maximumRecursion;
			return this;
		}

		public StaticSerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter
		{
			return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> w)
			{
				w.OnTop();
			});
		}

		public StaticSerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory, Action<IRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter
		{
			if (eventEmitterFactory == null)
			{
				throw new ArgumentNullException("eventEmitterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory(inner)));
			return Self;
		}

		public StaticSerializerBuilder WithEventEmitter<TEventEmitter>(WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter
		{
			if (eventEmitterFactory == null)
			{
				throw new ArgumentNullException("eventEmitterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory(wrapped, inner)));
			return Self;
		}

		public StaticSerializerBuilder WithoutEventEmitter<TEventEmitter>() where TEventEmitter : IEventEmitter
		{
			return WithoutEventEmitter(typeof(TEventEmitter));
		}

		public StaticSerializerBuilder WithoutEventEmitter(Type eventEmitterType)
		{
			if (eventEmitterType == null)
			{
				throw new ArgumentNullException("eventEmitterType");
			}
			eventEmitterFactories.Remove(eventEmitterType);
			return this;
		}

		public override StaticSerializerBuilder WithTagMapping(TagName tag, Type type)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (tagMappings.TryGetValue(type, out var value))
			{
				throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type");
			}
			tagMappings.Add(type, tag);
			return this;
		}

		public StaticSerializerBuilder WithoutTagMapping(Type type)
		{
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (!tagMappings.Remove(type))
			{
				throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered");
			}
			return this;
		}

		public StaticSerializerBuilder EnsureRoundtrip()
		{
			objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, factory);
			WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings, quoteNecessaryStrings), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc)
			{
				loc.InsteadOf<TypeAssigningEventEmitter>();
			});
			return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> loc)
			{
				loc.OnBottom();
			});
		}

		public StaticSerializerBuilder DisableAliases()
		{
			preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner));
			emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor));
			return this;
		}

		[Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)]
		public StaticSerializerBuilder EmitDefaults()
		{
			return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve);
		}

		public StaticSerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration)
		{
			defaultValuesHandlingConfiguration = configuration;
			return this;
		}

		public StaticSerializerBuilder JsonCompatible()
		{
			emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName();
			return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w)
			{
				w.InsteadOf<YamlDotNet.Serialization.Converters.GuidConverter>();
			}).WithTypeConverter(new YamlDotNet.Serialization.Converters.DateTimeConverter(DateTimeKind.Utc, null, true)).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner, yamlFormatter), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc)
			{
				loc.InsteadOf<TypeAssigningEventEmitter>();
			});
		}

		public StaticSerializerBuilder WithNewLine(string newLine)
		{
			emitterSettings = emitterSettings.WithNewLine(newLine);
			return this;
		}

		public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>> w)
			{
				w.OnTop();
			});
		}

		public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			if (objectGraphVisitor == null)
			{
				throw new ArgumentNullException("objectGraphVisitor");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<IYamlTypeConverter> _) => objectGraphVisitor));
			return this;
		}

		public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			if (objectGraphVisitorFactory == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<Nothing> wrapped, IEnumerable<IYamlTypeConverter> _) => objectGraphVisitorFactory(wrapped)));
			return this;
		}

		public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor));
		}

		public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType)
		{
			if (objectGraphVisitorType == null)
			{
				throw new ArgumentNullException("objectGraphVisitorType");
			}
			preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType);
			return this;
		}

		public StaticSerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory)
		{
			this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory;
			return this;
		}

		public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax<I