Decompiled source of Dungeons v1.0.1

meadworks.dungeons.dll

Decompiled 29 minutes ago
using System;
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.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using MeadWorks.Core;
using MeadWorks.UI;
using Microsoft.CodeAnalysis;
using SoftReferenceableAssets;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("expDARE")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2026 expDARE")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("meadworks.dungeons")]
[assembly: AssemblyTitle("meadworks.dungeons")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[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 MeadWorks.Dungeons
{
	public static class CampRespawn
	{
		public struct RespawnState
		{
			public bool Released;

			public ZDOID Old;
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(CreatureSpawner), "UpdateSpawner")]
			[HarmonyPrefix]
			private static void Update(CreatureSpawner __instance, out RespawnState __state)
			{
				__state = Before(__instance);
			}

			[HarmonyPatch(typeof(CreatureSpawner), "UpdateSpawner")]
			[HarmonyFinalizer]
			private static void Updated(CreatureSpawner __instance, RespawnState __state)
			{
				After(__instance, __state);
			}

			[HarmonyPatch(typeof(Group), "SpawnWeighted")]
			[HarmonyPrefix]
			private static bool GroupRoll(Group __instance, bool __runOriginal = true)
			{
				if (!__runOriginal)
				{
					return false;
				}
				CreatureSpawner releasing = _releasing;
				if (!RespawnRules.TakesGroupSpawn((Object)(object)releasing != (Object)null, (Object)(object)releasing != (Object)null && releasing.m_spawnGroup == __instance))
				{
					return true;
				}
				releasing.Spawn();
				return false;
			}
		}

		private static readonly int StampKey = StringExtensionMethods.GetStableHashCode("meadworks.dungeons.gone");

		private static Setting<bool> _camps;

		private static Setting<float> _campDays;

		private static Setting<bool> _dungeons;

		private static Setting<float> _dungeonDays;

		private static Setting<float> _guard;

		private static Harmony _harmony;

		private static readonly List<Piece> PieceBuffer = new List<Piece>();

		private static CreatureSpawner _releasing;

		public static bool DebugInterior;

		public static bool Enabled
		{
			get
			{
				if (_camps == null || !_camps.Value)
				{
					if (_dungeons != null)
					{
						return _dungeons.Value;
					}
					return false;
				}
				return true;
			}
		}

		public static void Init(SettingsPage page, ConfigFile config)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			RespawnConfig.Bind(config, delegate
			{
				_camps = page.Toggle("respawn_camps", "Respawn camps", true, (SettingPolicy)1, false);
				_campDays = page.Slider("respawn_camp_days", "Camp respawn days", 10f, 1f, 30f, 1f, (SettingPolicy)1, false);
				_dungeons = page.Toggle("respawn_dungeons", "Respawn dungeons", true, (SettingPolicy)1, false);
				_dungeonDays = page.Slider("respawn_dungeon_days", "Dungeon respawn days", 10f, 1f, 30f, 1f, (SettingPolicy)1, false);
				_guard = page.Slider("respawn_guard", "Keep clear of bases (m)", 40f, 10f, 100f, 5f, (SettingPolicy)1, true);
			});
			_harmony = new Harmony("expdare.meadworks.dungeons.camprespawn");
			_harmony.PatchAll(typeof(Patches));
			LedgerTrack.Patch(_harmony, "dungeons camp respawn");
			Ledger.Add("dungeons camp respawn state", (Action)delegate
			{
				DebugInterior = false;
				_camps = null;
				_campDays = null;
				_dungeons = null;
				_dungeonDays = null;
				_guard = null;
				_releasing = null;
			});
		}

		public static bool Interior(CreatureSpawner s)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			if (!DebugInterior)
			{
				return Character.InInterior(((Component)s).transform.position);
			}
			return true;
		}

		private static bool KindOn(CreatureSpawner s)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (_camps != null && _dungeons != null && !DungeonReset.OwnsRenewal(((Component)s).transform.position))
			{
				return RespawnRules.KindEnabled(Interior(s), _camps.Value, _dungeons.Value);
			}
			return false;
		}

		private static int DaysOf(CreatureSpawner s)
		{
			return RefillRules.ClampDays(RespawnRules.KindDays(Interior(s), _campDays.Value, _dungeonDays.Value));
		}

		public static int Stamp(CreatureSpawner s)
		{
			if ((Object)(object)s == (Object)null || (Object)(object)s.m_nview == (Object)null || !s.m_nview.IsValid() || s.m_nview.GetZDO() == null)
			{
				return -1;
			}
			return s.m_nview.GetZDO().GetInt(StampKey, -1);
		}

		public static void SetStamp(CreatureSpawner s, int day)
		{
			if (!((Object)(object)s == (Object)null) && !((Object)(object)s.m_nview == (Object)null) && s.m_nview.IsValid() && s.m_nview.GetZDO() != null)
			{
				ZDO zDO = s.m_nview.GetZDO();
				if (zDO.GetInt(StampKey, -1) != day)
				{
					zDO.Set(StampKey, day, false);
				}
			}
		}

		private static Character CreatureOf(CreatureSpawner s)
		{
			if (!((Object)(object)s.m_creaturePrefab != (Object)null))
			{
				return null;
			}
			return s.m_creaturePrefab.GetComponent<Character>();
		}

		public static bool IsCandidate(CreatureSpawner s)
		{
			if ((Object)(object)s == (Object)null || (Object)(object)s.m_nview == (Object)null || !s.m_nview.IsValid() || s.m_nview.GetZDO() == null)
			{
				return false;
			}
			Character val = CreatureOf(s);
			bool isBoss = (Object)(object)val != (Object)null && (val.IsBoss() || !string.IsNullOrEmpty(val.m_bossEvent) || RespawnRules.IsOneTime(((Object)s.m_creaturePrefab).name));
			return RespawnRules.IsCandidate(s.m_respawnTimeMinuts <= 0f, s.HasSpawned(), (Object)(object)val != (Object)null, isBoss);
		}

		public static bool CreatureAlive(CreatureSpawner s)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)s == (Object)null || (Object)(object)s.m_nview == (Object)null || !s.m_nview.IsValid() || s.m_nview.GetZDO() == null || ZDOMan.instance == null)
			{
				return true;
			}
			ZDOID connectionZDOID = s.m_nview.GetZDO().GetConnectionZDOID((ConnectionType)3);
			if (!((ZDOID)(ref connectionZDOID)).IsNone())
			{
				return ZDOMan.instance.GetZDO(connectionZDOID) != null;
			}
			return false;
		}

		public static bool BaseNear(Vector3 p)
		{
			//IL_0019: 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)
			if (_guard == null)
			{
				return true;
			}
			float num = RespawnRules.ClampGuard(_guard.Value);
			if ((Object)(object)EffectArea.IsPointInsideArea(p, (Type)4, num) != (Object)null)
			{
				return true;
			}
			PieceBuffer.Clear();
			Piece.GetAllPiecesInRadius(p, num, PieceBuffer);
			foreach (Piece item in PieceBuffer)
			{
				if ((Object)(object)item != (Object)null && item.GetCreator() != 0L)
				{
					return true;
				}
			}
			return false;
		}

		private static bool GameWouldSpawn(CreatureSpawner s)
		{
			//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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)EnvMan.instance == (Object)null)
			{
				return false;
			}
			Vector3 position = ((Component)s).transform.position;
			if (!s.m_spawnAtDay && EnvMan.IsDay())
			{
				return false;
			}
			if (!s.m_spawnAtNight && EnvMan.IsNight())
			{
				return false;
			}
			if (!(s.m_triggerNoise > 0f))
			{
				return Player.IsPlayerInRange(position, s.m_triggerDistance);
			}
			return Player.IsPlayerInRange(position, s.m_triggerDistance, s.m_triggerNoise);
		}

		public static float NearestPlayer(Vector3 p)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			float num = float.MaxValue;
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (!((Object)(object)allPlayer == (Object)null))
				{
					float num2 = Vector3.Distance(((Component)allPlayer).transform.position, p);
					if (num2 < num)
					{
						num = num2;
					}
				}
			}
			return num;
		}

		public static RespawnState Before(CreatureSpawner s)
		{
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			RespawnState result = default(RespawnState);
			if (!Enabled || _campDays == null || _dungeonDays == null || _guard == null || ZDOMan.instance == null || (Object)(object)EnvMan.instance == (Object)null || (Object)(object)s == (Object)null || (Object)(object)ZNet.instance == (Object)null || (Object)(object)s.m_nview == (Object)null || !s.m_nview.IsValid() || !s.m_nview.IsOwner())
			{
				return result;
			}
			if (!KindOn(s) || !IsCandidate(s))
			{
				return result;
			}
			int num = ChestRefill.Today();
			int days = DaysOf(s);
			bool creatureAlive = CreatureAlive(s);
			switch (RespawnRules.Step(enabled: true, isOwner: true, candidate: true, creatureAlive, Stamp(s), num, days, playerNear: false, baseNear: false))
			{
			case RespawnAct.ClearStamp:
				SetStamp(s, -1);
				return result;
			case RespawnAct.Stamp:
				SetStamp(s, num);
				return result;
			case RespawnAct.Release:
				if (GameWouldSpawn(s))
				{
					Vector3 position = ((Component)s).transform.position;
					bool flag = RespawnRules.PlayerNear(NearestPlayer(position));
					bool flag2 = BaseNear(position);
					bool dungeonOccupied = !flag && !flag2 && DungeonGuard.Blocked(s.m_nview, delegate
					{
						if ((Object)(object)s != (Object)null)
						{
							s.UpdateSpawner();
						}
					});
					RespawnAct respawnAct = RespawnRules.Step(enabled: true, isOwner: true, candidate: true, creatureAlive, Stamp(s), num, days, flag, flag2, dungeonOccupied);
					if (respawnAct != RespawnAct.Release)
					{
						return result;
					}
					ZDO zDO = s.m_nview.GetZDO();
					RespawnState result2 = new RespawnState
					{
						Released = true,
						Old = zDO.GetConnectionZDOID((ConnectionType)3)
					};
					zDO.SetConnection((ConnectionType)0, ZDOID.None);
					_releasing = s;
					return result2;
				}
				goto default;
			default:
				return result;
			}
		}

		public static void After(CreatureSpawner s, RespawnState state)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Invalid comparison between Unknown and I4
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			if (!state.Released)
			{
				return;
			}
			_releasing = null;
			if (!((Object)(object)s == (Object)null) && !((Object)(object)s.m_nview == (Object)null) && s.m_nview.IsValid() && s.m_nview.GetZDO() != null)
			{
				ZDO zDO = s.m_nview.GetZDO();
				bool spawnedNow = (int)zDO.GetConnectionType() == 3;
				if (RespawnRules.End(released: true, spawnedNow) == ReleaseEnd.ClearStamp)
				{
					SetStamp(s, -1);
					MwLog.Debug((object)("dungeons respawn " + ((Object)s).name));
				}
				else
				{
					zDO.SetConnection((ConnectionType)3, state.Old);
				}
			}
		}
	}
	public static class ChestRefill
	{
		private static class Patches
		{
			[HarmonyPatch(typeof(Container), "GetHoverText")]
			[HarmonyPostfix]
			private static void Hover(Container __instance, ref string __result)
			{
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				if (Enabled && _days != null && !((Object)(object)ZNet.instance == (Object)null) && !((Object)(object)EnvMan.instance == (Object)null) && EnvMan.instance.m_dayLengthSec > 0 && __instance.m_inventory != null && IsWorldChest(__instance) && !DungeonReset.OwnsRenewal(((Component)__instance).transform.position))
				{
					string text = RefillRules.HoverText(Enabled, worldChest: true, __instance.m_nview.GetZDO().GetBool(ZDOVars.s_addedDefaultItems, false), __instance.m_inventory.NrOfItems(), Stamp(__instance), ZNet.instance.GetTimeSeconds() / (double)EnvMan.instance.m_dayLengthSec, RefillRules.ClampDays(_days.Value), Phrase);
					if (text.Length > 0)
					{
						__result = __result + "\n" + text;
					}
				}
			}

			[HarmonyPatch(typeof(Container), "Save")]
			[HarmonyPostfix]
			private static void Save(Container __instance)
			{
				Saved(__instance);
			}

			[HarmonyPatch(typeof(Container), "Awake")]
			[HarmonyPostfix]
			private static void Awake(Container __instance)
			{
				RegisterWords();
				Check(__instance);
			}

			[HarmonyPatch(typeof(Container), "RPC_RequestOpen")]
			[HarmonyPrefix]
			private static void RequestOpen(Container __instance)
			{
				Check(__instance);
			}

			[HarmonyPatch(typeof(Container), "RPC_RequestStack")]
			[HarmonyPrefix]
			private static void RequestStack(Container __instance)
			{
				Check(__instance);
			}

			[HarmonyPatch(typeof(Container), "RPC_RequestTakeAll")]
			[HarmonyPrefix]
			private static void RequestTakeAll(Container __instance)
			{
				Check(__instance);
			}

			[HarmonyPatch(typeof(Container), "CheckForChanges")]
			[HarmonyPrefix]
			private static void KeepEmpty(Container __instance, out bool? __state)
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				__state = __instance.m_autoDestroyEmpty;
				if (__state.Value && Enabled && !DungeonReset.OwnsRenewal(((Component)__instance).transform.position) && RefillRules.KeepEmpty(enabled: true, (Object)(object)__instance.m_nview != (Object)null && __instance.m_nview.IsValid() && __instance.m_nview.IsOwner(), IsWorldChest(__instance)))
				{
					__instance.m_autoDestroyEmpty = false;
				}
			}

			[HarmonyPatch(typeof(Container), "CheckForChanges")]
			[HarmonyFinalizer]
			private static void RestoreEmptyDestroy(Container __instance, bool? __state)
			{
				if (__state.HasValue)
				{
					__instance.m_autoDestroyEmpty = __state.Value;
				}
			}

			[HarmonyPatch(typeof(Container), "CheckForChanges")]
			[HarmonyPostfix]
			private static void Tick(Container __instance)
			{
				Ticked(__instance);
			}
		}

		private static readonly int StampKey = StringExtensionMethods.GetStableHashCode("meadworks.dungeons.emptied");

		private static Setting<bool> _on;

		private static Setting<float> _days;

		private static Harmony _harmony;

		internal static bool TickPaused;

		public static bool Enabled
		{
			get
			{
				if (_on != null)
				{
					return _on.Value;
				}
				return false;
			}
		}

		public static void Init(SettingsPage page)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			_on = page.Toggle("chest_refill", "Refill loot chests", true, (SettingPolicy)1, false);
			_days = page.Slider("chest_days", "Refill after days", 10f, 1f, 30f, 1f, (SettingPolicy)1, false);
			_harmony = new Harmony("expdare.meadworks.dungeons.chestrefill");
			_harmony.PatchAll(typeof(Patches));
			LedgerTrack.Patch(_harmony, "dungeons chest refill");
			Localization.OnLanguageChange = (Action)Delegate.Combine(Localization.OnLanguageChange, new Action(RegisterWords));
			LedgerTrack.Subscription("dungeons chest words", (Action)delegate
			{
				Localization.OnLanguageChange = (Action)Delegate.Remove(Localization.OnLanguageChange, new Action(RegisterWords));
			});
			Ledger.Add("dungeons chest refill state", (Action)delegate
			{
				_on = null;
				_days = null;
			});
			RegisterWords();
		}

		private static void RegisterWords()
		{
			Localization instance = Localization.m_instance;
			if (instance == null)
			{
				return;
			}
			bool flag = false;
			foreach (KeyValuePair<string, string> word in RefillRules.Words)
			{
				if (!instance.m_translations.ContainsKey(word.Key))
				{
					instance.AddWord(word.Key, Lang.Derived(word.Key, word.Value));
					flag = true;
				}
			}
			if (flag)
			{
				instance.m_cache.EvictAll();
			}
		}

		private static string Phrase(string key, string fallback)
		{
			Localization instance = Localization.m_instance;
			if (instance != null && instance.m_translations.ContainsKey(key))
			{
				return instance.Localize("$" + key);
			}
			return fallback;
		}

		public static int Today()
		{
			if (!((Object)(object)EnvMan.instance != (Object)null) || !((Object)(object)ZNet.instance != (Object)null))
			{
				return -1;
			}
			return EnvMan.instance.GetDay();
		}

		public static int Stamp(Container c)
		{
			if ((Object)(object)c == (Object)null || (Object)(object)c.m_nview == (Object)null || !c.m_nview.IsValid() || c.m_nview.GetZDO() == null)
			{
				return -1;
			}
			return c.m_nview.GetZDO().GetInt(StampKey, -1);
		}

		public static void SetStamp(Container c, int day)
		{
			if ((Object)(object)c == (Object)null || (Object)(object)c.m_nview == (Object)null || !c.m_nview.IsValid() || c.m_nview.GetZDO() == null)
			{
				return;
			}
			ZDO zDO = c.m_nview.GetZDO();
			if (zDO.GetInt(StampKey, -1) != day)
			{
				bool num = c.m_lastRevision == zDO.DataRevision;
				zDO.Set(StampKey, day, false);
				if (num && c.m_nview.IsOwner())
				{
					c.m_lastRevision = zDO.DataRevision;
				}
			}
		}

		public static bool IsWorldChest(Container c)
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Invalid comparison between Unknown and I4
			if ((Object)(object)c == (Object)null || (Object)(object)c.m_nview == (Object)null || !c.m_nview.IsValid() || c.m_nview.GetZDO() == null)
			{
				return false;
			}
			Piece componentInParent = ((Component)c).GetComponentInParent<Piece>();
			bool playerBuilt = RefillRules.IsPlayerBuilt(c.m_nview.GetZDO().GetLong(ZDOVars.s_creator, 0L), (Object)(object)componentInParent != (Object)null && componentInParent.GetCreator() != 0);
			bool special = RefillRules.IsSpecial((Object)(object)((Component)c).GetComponent<TombStone>() != (Object)null, (Object)(object)c.m_wagon != (Object)null, (Object)(object)c.m_rootObjectOverride != (Object)null, (int)c.m_privacy == 2);
			bool hasDefaults = c.m_defaultItems != null && c.m_defaultItems.m_drops != null && c.m_defaultItems.m_drops.Count > 0;
			return RefillRules.IsWorldChest(playerBuilt, special, hasDefaults);
		}

		private static void Saved(Container c)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (Enabled && !((Object)(object)c == (Object)null) && !((Object)(object)c.m_nview == (Object)null) && c.m_nview.IsValid() && c.m_nview.IsOwner() && !DungeonReset.OwnsRenewal(((Component)c).transform.position) && c.m_inventory != null && IsWorldChest(c))
			{
				if (c.m_inventory.NrOfItems() > 0)
				{
					SetStamp(c, -1);
				}
				else if (Stamp(c) == -1 && c.m_nview.GetZDO().GetBool(ZDOVars.s_addedDefaultItems, false))
				{
					SetStamp(c, Today());
				}
			}
		}

		private static void Ticked(Container c)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (!Enabled || (Object)(object)c == (Object)null || _days == null || TickPaused || DungeonReset.OwnsRenewal(((Component)c).transform.position))
			{
				return;
			}
			ZNetView nview = c.m_nview;
			if ((Object)(object)nview == (Object)null || !nview.IsValid() || nview.GetZDO() == null || !nview.IsOwner())
			{
				return;
			}
			int num = Stamp(c);
			bool worldChest = false;
			int num2 = -1;
			bool flag = false;
			if (num == -1)
			{
				flag = nview.GetZDO().GetBool(ZDOVars.s_addedDefaultItems, false);
				num2 = ((c.m_inventory == null) ? (-1) : c.m_inventory.NrOfItems());
				if (flag && num2 == 0)
				{
					worldChest = IsWorldChest(c);
				}
			}
			if (RefillRules.OwnerTick(num, Today(), RefillRules.ClampDays(_days.Value), worldChest, num2, flag))
			{
				Check(c);
			}
		}

		public static bool Check(Container c)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (!Enabled || _days == null || (Object)(object)c == (Object)null || c.m_inventory == null || (Object)(object)ZNet.instance == (Object)null)
			{
				return false;
			}
			if (DungeonReset.OwnsRenewal(((Component)c).transform.position))
			{
				return false;
			}
			if ((Object)(object)c.m_nview == (Object)null || !c.m_nview.IsValid())
			{
				return false;
			}
			ZDO zDO = c.m_nview.GetZDO();
			if (zDO == null || !c.m_nview.IsOwner() || !zDO.GetBool(ZDOVars.s_addedDefaultItems, false))
			{
				return false;
			}
			if (!IsWorldChest(c))
			{
				return false;
			}
			bool flag = c.IsInUse() || zDO.GetInt(ZDOVars.s_inUse, 0) == 1;
			int num = Today();
			if (flag || num < 0)
			{
				return false;
			}
			c.Load();
			int days = RefillRules.ClampDays(_days.Value);
			bool dungeonOccupied = c.m_inventory.NrOfItems() == 0 && RefillRules.Decide(Stamp(c), num, days) == RefillStep.Refill && DungeonGuard.Blocked(c.m_nview, delegate
			{
				if ((Object)(object)c != (Object)null)
				{
					Check(c);
				}
			});
			switch (RefillRules.OwnerStep(isOwner: true, flag, c.m_inventory.NrOfItems(), Stamp(c), num, days, dungeonOccupied))
			{
			case OwnerAct.None:
				return false;
			case OwnerAct.ClearStamp:
				SetStamp(c, -1);
				return false;
			case OwnerAct.WriteStamp:
				SetStamp(c, num);
				return false;
			default:
			{
				AutomaticChestLoot.Run(zDO, (Action)c.AddDefaultItems);
				bool flag2 = c.m_inventory.NrOfItems() > 0;
				SetStamp(c, flag2 ? (-1) : num);
				MwLog.Debug((object)("dungeons chest refill " + ((Object)c).name + " items=" + c.m_inventory.NrOfItems()));
				return flag2;
			}
			}
		}
	}
	internal static class DungeonAdmission
	{
		private sealed class Pending
		{
			internal ZDOID Proxy;

			internal Teleport Door;

			internal int Token;

			internal float Until;
		}

		private readonly struct Reservation
		{
			internal readonly ZDOID Proxy;

			internal readonly float Until;

			internal Reservation(ZDOID proxy, float until)
			{
				//IL_0001: 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)
				Proxy = proxy;
				Until = until;
			}
		}

		private static class Patches
		{
			[HarmonyPrefix]
			[HarmonyPatch(typeof(Teleport), "Interact")]
			private static bool Enter(Teleport __instance, Humanoid character, bool hold, bool __runOriginal)
			{
				//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_0064: Unknown result type (might be due to invalid IL or missing references)
				//IL_0104: Unknown result type (might be due to invalid IL or missing references)
				//IL_0109: 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_007d: Unknown result type (might be due to invalid IL or missing references)
				if (!__runOriginal)
				{
					return false;
				}
				if (hold || !DungeonReset.Enabled || (Object)(object)character == (Object)null || (Object)(object)character != (Object)(object)Player.m_localPlayer || _passing == __instance)
				{
					return true;
				}
				if (!DungeonReset.TryEntrance(__instance, out var proxy))
				{
					if (Character.InInterior(((Component)__instance).transform.position) || (Object)(object)__instance.m_targetPoint == (Object)null || !Character.InInterior(((Component)__instance.m_targetPoint).transform.position))
					{
						return true;
					}
					Location zoneLocation = Location.GetZoneLocation(((Component)__instance.m_targetPoint).transform.position);
					if (!((Object)(object)zoneLocation == (Object)null))
					{
						return !DungeonResetRules.Targets(Utils.GetPrefabName(((Component)zoneLocation).gameObject)).Enabled;
					}
					return true;
				}
				ZNet instance = ZNet.instance;
				Vector3 position = ((Component)character).transform.position;
				if (instance.IsServer())
				{
					return Reserve(ZNet.GetUID(), proxy, position, position);
				}
				if (_rpc == null || (_pending != null && Time.realtimeSinceStartup < _pending.Until))
				{
					return false;
				}
				_pending = new Pending
				{
					Door = __instance,
					Proxy = proxy.m_uid,
					Token = ++_serial,
					Until = Time.realtimeSinceStartup + 4f
				};
				_rpc.InvokeRoutedRPC(_rpc.GetServerPeerID(), "MW_Dungeons_Enter", new object[2] { proxy.m_uid, _pending.Token });
				return false;
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(Teleport), "Interact")]
			private static void TrackExit(Teleport __instance, Humanoid character, bool __result)
			{
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				if (__result && DungeonReset.Enabled && !ZNet.instance.IsServer() && !((Object)(object)character != (Object)(object)Player.m_localPlayer) && !((Object)(object)__instance.m_targetPoint == (Object)null) && Character.InInterior(((Component)__instance).transform.position) && !Character.InInterior(((Component)__instance.m_targetPoint).transform.position) && DungeonReset.TryEntrance(__instance.m_targetPoint, out var _))
				{
					_clientInterior = ZoneSystem.GetZone(((Component)__instance).transform.position);
				}
			}

			[HarmonyPrefix]
			[HarmonyPatch(typeof(ZNet), "SendServerSyncPlayerData")]
			private static bool FlushBeforeExit(ZNet __instance, ZNetPeer peer, bool __runOriginal)
			{
				//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_001b: 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_002b: 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_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0076: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0090: Unknown result type (might be due to invalid IL or missing references)
				//IL_009f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
				if (!__runOriginal || !DungeonReset.Enabled || __instance.IsServer())
				{
					return __runOriginal;
				}
				Vector3 referencePosition = __instance.GetReferencePosition();
				if (Character.InInterior(referencePosition) && DungeonReset.OwnsRenewal(referencePosition))
				{
					_clientInterior = ZoneSystem.GetZone(referencePosition);
					return true;
				}
				if (!_clientInterior.HasValue)
				{
					return true;
				}
				ZDOMan instance = ZDOMan.instance;
				ZDOPeer val = instance.FindPeer(peer.m_rpc);
				if (val == null)
				{
					return false;
				}
				instance.SendZDOs(val, true);
				Vector2s value = _clientInterior.Value;
				foreach (ZDOID item in instance.m_clientChangeQueue)
				{
					ZDO zDO = instance.GetZDO(item);
					if (zDO != null && DungeonOccupancy.Inside(zDO.GetPosition(), value))
					{
						return false;
					}
				}
				instance.SendDestroyed();
				_clientInterior = null;
				return true;
			}
		}

		private const string Request = "MW_Dungeons_Enter";

		private const string Reply = "MW_Dungeons_EnterReply";

		private static readonly Dictionary<long, Reservation> Reservations = new Dictionary<long, Reservation>();

		private static ZRoutedRpc _rpc;

		private static Pending _pending;

		private static Teleport _passing;

		private static Vector2s? _clientInterior;

		private static int _serial;

		internal static void Init()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			Harmony val = new Harmony("expdare.meadworks.dungeons.dungeonadmission");
			val.PatchAll(typeof(Patches));
			LedgerTrack.Patch(val, "dungeons entrance admission");
			Ledger.Add("dungeons entrance state", (Action)delegate
			{
				Attach(null);
			});
		}

		internal static void Attach(ZRoutedRpc rpc)
		{
			if (_rpc != rpc)
			{
				if (_rpc != null)
				{
					_rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Dungeons_Enter"));
					_rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Dungeons_EnterReply"));
				}
				ClearWorld();
				_rpc = rpc;
				if (rpc != null)
				{
					RoutedRpcGuard.Register(new string[2] { "MW_Dungeons_Enter", "MW_Dungeons_EnterReply" });
					rpc.Register<ZDOID, int>("MW_Dungeons_Enter", (Action<long, ZDOID, int>)OnRequest);
					rpc.Register<ZDOID, int, bool>("MW_Dungeons_EnterReply", (Action<long, ZDOID, int, bool>)OnReply);
				}
			}
		}

		internal static void ClearWorld()
		{
			Reservations.Clear();
			_pending = null;
			_passing = null;
			_clientInterior = null;
		}

		internal static bool Blocks(ZDOID proxy)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			foreach (Reservation value in Reservations.Values)
			{
				if (value.Proxy == proxy)
				{
					return true;
				}
			}
			return false;
		}

		internal static ZDO OnDeparture(long peer)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (!Reservations.TryGetValue(peer, out var value))
			{
				return null;
			}
			Reservations.Remove(peer);
			ZDOMan instance = ZDOMan.instance;
			if (instance == null)
			{
				return null;
			}
			return instance.GetZDO(value.Proxy);
		}

		internal static void Observe(long peer, Vector3 position, Vector3 reference)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (!Reservations.TryGetValue(peer, out var value))
			{
				return;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(value.Proxy);
			if (zDO == null)
			{
				Reservations.Remove(peer);
				return;
			}
			Vector2s zone = ZoneSystem.GetZone(zDO.GetPosition());
			if (DungeonAdmissionRules.Release(DungeonOccupancy.Known(position) && DungeonOccupancy.Known(reference), DungeonOccupancy.Inside(position, zone), DungeonOccupancy.Inside(reference, zone), Time.realtimeSinceStartup >= value.Until))
			{
				Reservations.Remove(peer);
				DungeonReset.Check(zDO);
			}
		}

		private static bool Reserve(long peer, ZDO proxy, Vector3 position, Vector3 reference)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			if (proxy == null || !DungeonReset.IsLocationProxy(proxy) || !DungeonReset.Targets(proxy).Enabled || DungeonSwap.Busy || !AtEntrance(position, proxy) || !AtEntrance(reference, proxy))
			{
				return false;
			}
			Reservation value;
			bool num = Reservations.TryGetValue(peer, out value);
			if (!DungeonAdmissionRules.MayReserve(num, num && value.Proxy == proxy.m_uid) || !DungeonReset.Enroll(proxy))
			{
				return false;
			}
			Reservations[peer] = new Reservation(proxy.m_uid, Time.realtimeSinceStartup + 12f);
			return true;
		}

		private static bool AtEntrance(Vector3 position, ZDO proxy)
		{
			//IL_0000: 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_0010: 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)
			if (DungeonOccupancy.Known(position) && !Character.InInterior(position))
			{
				Vector3 val = position - proxy.GetPosition();
				return ((Vector3)(ref val)).sqrMagnitude <= 576f;
			}
			return false;
		}

		private static void OnRequest(long sender, ZDOID id, int token)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			ZNet instance = ZNet.instance;
			if (DungeonReset.Enabled && !((Object)(object)instance == (Object)null) && instance.IsServer())
			{
				ZNetPeer peer = instance.GetPeer(sender);
				ZDO val = DungeonOccupancy.PeerCharacter(peer);
				bool flag = val != null && Reserve(sender, ZDOMan.instance.GetZDO(id), val.GetPosition(), peer.m_refPos);
				_rpc.InvokeRoutedRPC(sender, "MW_Dungeons_EnterReply", new object[3] { id, token, flag });
			}
		}

		private static void OnReply(long sender, ZDOID id, int token, bool granted)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			Pending pending = _pending;
			Player localPlayer = Player.m_localPlayer;
			if (_rpc == null || pending == null || sender != _rpc.GetServerPeerID() || pending.Proxy != id || pending.Token != token)
			{
				return;
			}
			_pending = null;
			if (!granted || !DungeonReset.Enabled || Time.realtimeSinceStartup >= pending.Until || (Object)(object)localPlayer == (Object)null || (Object)(object)pending.Door == (Object)null || ((Character)localPlayer).IsTeleporting())
			{
				return;
			}
			Vector3 val = ((Component)localPlayer).transform.position - ((Component)pending.Door).transform.position;
			if (((Vector3)(ref val)).sqrMagnitude > 36f || !DungeonReset.TryEntrance(pending.Door, out var proxy) || proxy.m_uid != id)
			{
				return;
			}
			_passing = pending.Door;
			try
			{
				pending.Door.Interact((Humanoid)(object)localPlayer, false, false);
			}
			finally
			{
				_passing = null;
			}
		}
	}
	public static class DungeonAdmissionRules
	{
		public const float ReplySeconds = 4f;

		public const float LeaseSeconds = 12f;

		public const float EntranceRange = 24f;

		public const float UseRange = 6f;

		public static bool MayReserve(bool hasReservation, bool sameDungeon)
		{
			return !hasReservation || sameDungeon;
		}

		public static bool Release(bool known, bool characterInside, bool referenceInside, bool leaseEnded)
		{
			if (known && characterInside == referenceInside)
			{
				return characterInside || leaseEnded;
			}
			return false;
		}
	}
	internal static class DungeonCarry
	{
		private sealed class Stack
		{
			internal byte[] Bytes;

			internal int CellOffset;

			internal int CountOffset;

			internal bool Compact;

			internal int Count;

			internal int Maximum;
		}

		private const int Width = 5;

		private const int Height = 2;

		private const int Capacity = 10;

		private const int MaximumChests = 32;

		private static readonly int ChestHash = StringExtensionMethods.GetStableHashCode("piece_chest_wood");

		internal static string LastMiss;

		internal static List<byte[]> Pack(DungeonContents.Plan contents)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			SortedDictionary<int, List<Stack>> sortedDictionary = new SortedDictionary<int, List<Stack>>();
			foreach (var item2 in contents.Carry)
			{
				ZPackage val = new ZPackage(item2.Bytes);
				int num = val.ReadInt();
				if (num < 100 || num > 110)
				{
					throw new InvalidDataException("chest format");
				}
				bool flag = num >= 108;
				int num2 = (flag ? val.ReadUShort() : val.ReadInt());
				if (num2 <= 0 || num2 > item2.Bytes.Length)
				{
					throw new InvalidDataException("chest count");
				}
				if (!sortedDictionary.TryGetValue(num, out var value))
				{
					sortedDictionary.Add(num, value = new List<Stack>());
				}
				HashSet<Vector2i> hashSet = new HashSet<Vector2i>();
				for (int i = 0; i < num2; i++)
				{
					Vector2i cell;
					Stack item = ReadStack(val, item2.Bytes, num, flag, out cell);
					if (!hashSet.Add(cell))
					{
						throw new InvalidDataException("duplicate chest slot");
					}
					value.Add(item);
				}
				if (val.GetPos() != item2.Bytes.Length)
				{
					throw new InvalidDataException("extra chest inventory data");
				}
			}
			List<byte[]> list = new List<byte[]>();
			foreach (KeyValuePair<int, List<Stack>> item3 in sortedDictionary)
			{
				bool compact = item3.Key >= 108;
				List<byte[]> list2 = new List<byte[]>();
				foreach (Stack item4 in item3.Value)
				{
					int num3 = (32 - list.Count) * 10 - list2.Count;
					if (DungeonSwapRules.SplitCount(item4.Count, item4.Maximum) > num3)
					{
						throw new InvalidDataException("too many carry chests");
					}
					int num4 = item4.Count;
					while (num4 > 0)
					{
						int num5 = Math.Min(num4, item4.Maximum);
						list2.Add(WithPlacement(item4, list2.Count, num5));
						num4 -= num5;
						if (list2.Count == 10)
						{
							list.Add(WriteChest(item3.Key, compact, list2));
							list2.Clear();
						}
					}
				}
				if (list2.Count != 0)
				{
					list.Add(WriteChest(item3.Key, compact, list2));
				}
			}
			return list;
		}

		private static Stack ReadStack(ZPackage input, byte[] bytes, int version, bool compact, out Vector2i cell)
		{
			//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_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			int pos = input.GetPos();
			int num;
			int num2;
			int cellOffset;
			int countOffset;
			if (compact)
			{
				ValueTuple<int, ItemData> valueTuple = ItemData.Load(input, (Item)version);
				int item = valueTuple.Item1;
				ItemData item2 = valueTuple.Item2;
				num = item;
				num2 = item2.m_stack;
				cell = item2.m_gridPos;
				cellOffset = 4;
				byte b = bytes[pos + 7];
				countOffset = (((b & 8) == 0) ? (-1) : (8 + (((b & 4) != 0) ? 2 : 0)));
			}
			else
			{
				num = StringExtensionMethods.GetStableHashCode(input.ReadString());
				countOffset = input.GetPos() - pos;
				num2 = input.ReadInt();
				input.ReadSingle();
				cellOffset = input.GetPos() - pos;
				cell = input.ReadVector2i();
				input.ReadBool();
				if (version >= 101)
				{
					input.ReadInt();
				}
				if (version >= 102)
				{
					input.ReadInt();
				}
				if (version >= 103)
				{
					input.ReadLong();
					input.ReadString();
				}
				if (version >= 104)
				{
					int num3 = input.ReadInt();
					if (num3 < 0 || num3 > bytes.Length)
					{
						throw new InvalidDataException("legacy custom fields");
					}
					for (int i = 0; i < num3; i++)
					{
						input.ReadString();
						input.ReadString();
					}
				}
				if (version >= 105)
				{
					input.ReadInt();
				}
				if (version >= 106)
				{
					input.ReadBool();
				}
				if (version == 107)
				{
					input.ReadBool();
				}
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(num);
			ItemDrop val = (((Object)(object)itemPrefab == (Object)null) ? null : itemPrefab.GetComponent<ItemDrop>());
			if (num == 0 || (Object)(object)val == (Object)null || num2 <= 0 || cell.x < 0 || cell.y < 0)
			{
				throw new InvalidDataException("chest item prefab, count or slot");
			}
			ItemData itemData = val.m_itemData;
			int num4 = Math.Min(65535, InventoryPersistence.NativeMaximum?.Invoke(itemData) ?? itemData.m_shared.m_maxStackSize);
			if (num4 <= 0)
			{
				throw new InvalidDataException("chest item stack limit");
			}
			byte[] array = new byte[input.GetPos() - pos];
			Buffer.BlockCopy(bytes, pos, array, 0, array.Length);
			return new Stack
			{
				Bytes = array,
				CellOffset = cellOffset,
				CountOffset = countOffset,
				Compact = compact,
				Count = num2,
				Maximum = num4
			};
		}

		private static byte[] WithPlacement(Stack stack, int index, int count)
		{
			byte[] array = (byte[])stack.Bytes.Clone();
			using MemoryStream memoryStream = new MemoryStream(array);
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
			memoryStream.Position = stack.CellOffset;
			if (stack.Compact)
			{
				binaryWriter.Write((byte)(index % 5));
				binaryWriter.Write((byte)(index / 5));
			}
			else
			{
				binaryWriter.Write(index % 5);
				binaryWriter.Write(index / 5);
			}
			if (stack.CountOffset >= 0)
			{
				memoryStream.Position = stack.CountOffset;
				if (stack.Compact)
				{
					binaryWriter.Write((ushort)count);
				}
				else
				{
					binaryWriter.Write(count);
				}
			}
			return array;
		}

		private static byte[] WriteChest(int version, bool compact, List<byte[]> slots)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			using MemoryStream memoryStream = new MemoryStream();
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
			binaryWriter.Write(version);
			if (compact)
			{
				binaryWriter.Write((ushort)slots.Count);
			}
			else
			{
				binaryWriter.Write(slots.Count);
			}
			foreach (byte[] slot in slots)
			{
				binaryWriter.Write(slot);
			}
			byte[] array = memoryStream.ToArray();
			ZPackage val = new ZPackage(array);
			val.ReadInt();
			int num = (compact ? val.ReadUShort() : val.ReadInt());
			for (int i = 0; i < num; i++)
			{
				byte[] second = slots[i];
				Vector2i cell;
				Stack stack = ReadStack(val, array, version, compact, out cell);
				if (cell.x != i % 5 || cell.y != i / 5 || stack.Count > stack.Maximum || !stack.Bytes.SequenceEqual(second))
				{
					throw new InvalidDataException("carry chest verification");
				}
			}
			if (num != slots.Count || val.GetPos() != array.Length)
			{
				throw new InvalidDataException("carry chest length");
			}
			return array;
		}

		internal unsafe static bool Place(Room start, IReadOnlyList<byte[]> packed, IReadOnlyList<ZDO> generated)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Invalid comparison between Unknown and I4
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: 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)
			LastMiss = null;
			if (packed.Count == 0)
			{
				return true;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(ChestHash);
			Container val = (((Object)(object)prefab == (Object)null) ? null : prefab.GetComponent<Container>());
			ZNetView val2 = (((Object)(object)prefab == (Object)null) ? null : prefab.GetComponent<ZNetView>());
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || !val2.m_persistent || val.m_width < 5 || val.m_height < 2 || (int)val.m_privacy != 2)
			{
				LastMiss = "wood chest prefab unusable";
				return false;
			}
			string misses;
			List<Vector3> list = Spots(start, packed.Count, generated, out misses);
			if (list.Count != packed.Count)
			{
				string[] obj = new string[9]
				{
					packed.Count.ToString(),
					" chests, ",
					list.Count.ToString(),
					" spots in ",
					((Object)start).name,
					" ",
					null,
					null,
					null
				};
				Vector3Int size = start.m_size;
				obj[6] = ((object)(*(Vector3Int*)(&size))/*cast due to .constrained prefix*/).ToString();
				obj[7] = "; ";
				obj[8] = misses;
				LastMiss = string.Concat(obj);
				return false;
			}
			for (int i = 0; i < packed.Count; i++)
			{
				ZDO obj2 = ZDOMan.instance.CreateNewZDO(list[i], ChestHash);
				obj2.SetPrefab(ChestHash);
				obj2.Persistent = true;
				obj2.Type = val2.m_type;
				obj2.Distant = val2.m_distant;
				obj2.SetRotation(((Component)start).transform.rotation);
				obj2.Set(ZDOVars.s_addedDefaultItems, true);
				obj2.Set(DungeonContents.PlayerFilledKey, true);
				obj2.Set(ZDOVars.s_items, packed[i]);
				if (!obj2.GetByteArray(ZDOVars.s_items, (byte[])null).SequenceEqual(packed[i]))
				{
					return false;
				}
			}
			return true;
		}

		private static List<Vector3> Spots(Room start, int count, IReadOnlyList<ZDO> generated, out string misses)
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: 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_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			RoomConnection entrance = start.GetEntrance();
			Transform origin = ((Component)start).transform;
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			misses = "no entrance";
			if ((Object)(object)entrance == (Object)null)
			{
				return list;
			}
			List<Vector3> list2 = new List<Vector3>();
			for (int i = 1 - ((Vector3Int)(ref start.m_size)).x / 2; i < ((Vector3Int)(ref start.m_size)).x / 2; i++)
			{
				for (int j = 1 - ((Vector3Int)(ref start.m_size)).z / 2; j < ((Vector3Int)(ref start.m_size)).z / 2; j++)
				{
					list2.Add(origin.TransformPoint(new Vector3((float)i, 0f, (float)j)));
				}
			}
			Vector3 entry = ((Component)entrance).transform.position;
			list2.Sort((Vector3 a, Vector3 b) => HorizontalDistance(a, entry).CompareTo(HorizontalDistance(b, entry)));
			Physics.SyncTransforms();
			Collider[] componentsInChildren = ((Component)start).GetComponentsInChildren<Collider>();
			RoomConnection[] connections = start.GetConnections();
			float num5 = 3f + Math.Max(2f, ((Vector3Int)(ref start.m_size)).y);
			Ray val = default(Ray);
			RaycastHit val3 = default(RaycastHit);
			Vector3 val4;
			foreach (Vector3 candidate in list2)
			{
				if (Array.Exists(connections, (RoomConnection p) => HorizontalDistance(candidate, ((Component)p).transform.position) < 2.25f))
				{
					num++;
					continue;
				}
				((Ray)(ref val))..ctor(new Vector3(candidate.x, entry.y + 3f, candidate.z), Vector3.down);
				float num6 = float.NegativeInfinity;
				Collider[] array = componentsInChildren;
				foreach (Collider val2 in array)
				{
					if (!val2.isTrigger && val2.Raycast(val, ref val3, num5) && !(((RaycastHit)(ref val3)).normal.y < 0.8f))
					{
						num6 = Math.Max(num6, ((RaycastHit)(ref val3)).point.y);
					}
				}
				if (float.IsNegativeInfinity(num6))
				{
					num2++;
					continue;
				}
				Vector3 feet = new Vector3(candidate.x, num6 + 0.05f, candidate.z);
				bool flag = true;
				foreach (ZDO item in generated)
				{
					val4 = feet - item.GetPosition();
					if (((Vector3)(ref val4)).sqrMagnitude < 2.25f)
					{
						flag = false;
						break;
					}
				}
				if (!flag || list.Exists((Vector3 p) => HorizontalDistance(feet, p) < 2.25f))
				{
					num3++;
					continue;
				}
				if (Array.Exists(Physics.OverlapBox(feet + Vector3.up * 0.65f, new Vector3(0.65f, 0.6f, 0.55f), origin.rotation, -1, (QueryTriggerInteraction)1), (Collider collider) => ((Component)collider).transform.IsChildOf(origin)))
				{
					num4++;
					continue;
				}
				list.Add(feet);
				if (list.Count != count)
				{
					continue;
				}
				break;
			}
			string[] obj = new string[14]
			{
				"candidates ",
				list2.Count.ToString(),
				" port ",
				num.ToString(),
				" no floor ",
				num2.ToString(),
				" taken ",
				num3.ToString(),
				" blocked ",
				num4.ToString(),
				" entry y ",
				entry.y.ToString("0.0"),
				" room y ",
				null
			};
			val4 = origin.position;
			obj[13] = val4.y.ToString("0.0");
			misses = string.Concat(obj);
			return list;
		}

		private static float HorizontalDistance(Vector3 a, Vector3 b)
		{
			//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_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			float num = a.x - b.x;
			float num2 = a.z - b.z;
			return num * num + num2 * num2;
		}
	}
	internal static class DungeonContents
	{
		internal sealed class Plan
		{
			internal readonly List<ZDO> Retire = new List<ZDO>();

			internal readonly List<(ZDO Source, byte[] Bytes)> Carry = new List<(ZDO, byte[])>();

			internal bool PlayerProperty;

			internal bool OpenChest;

			internal bool WaitingForDrop;
		}

		private static class Patches
		{
			[HarmonyPrefix]
			[HarmonyPatch(typeof(ZoneSystem), "SpawnLocation")]
			private static void BeginLocation(ZoneLocation location, SpawnMode mode, out bool __state)
			{
				//IL_001a: 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_001f: Invalid comparison between Unknown and I4
				__state = _qualifiedLocation;
				_qualifiedLocation = DungeonReset.Enabled && ZNet.instance.IsServer() && ((int)mode == 0 || (int)mode == 2) && DungeonResetRules.Targets(location.m_prefab.Name).Enabled;
			}

			[HarmonyFinalizer]
			[HarmonyPatch(typeof(ZoneSystem), "SpawnLocation")]
			private static void EndLocation(bool __state)
			{
				_qualifiedLocation = __state;
			}

			[HarmonyPrefix]
			[HarmonyPatch(typeof(DungeonGenerator), "Generate", new Type[]
			{
				typeof(int),
				typeof(SpawnMode)
			})]
			private static void BeginGeneration(DungeonGenerator __instance, SpawnMode mode, out List<ZDOID> __state)
			{
				//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_0033: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_0048: Invalid comparison between Unknown and I4
				//IL_0051: Unknown result type (might be due to invalid IL or missing references)
				__state = _capture;
				_capture = null;
				Vector3 position = ((Component)__instance).transform.position;
				if (!DungeonSwap.Busy && DungeonReset.Enabled && ZNet.instance.IsServer() && Character.InInterior(position) && (int)__instance.m_algorithm == 0 && ((int)mode == 0 || (int)mode == 2) && (_qualifiedLocation || DungeonReset.FindProxy(position) != null))
				{
					_capture = new List<ZDOID>();
				}
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(DungeonGenerator), "Generate", new Type[]
			{
				typeof(int),
				typeof(SpawnMode)
			})]
			private static void FinishGeneration(DungeonGenerator __instance, bool __runOriginal)
			{
				if (__runOriginal && _capture != null)
				{
					WriteMembers(__instance.m_nview.GetZDO(), _capture);
				}
			}

			[HarmonyFinalizer]
			[HarmonyPatch(typeof(DungeonGenerator), "Generate", new Type[]
			{
				typeof(int),
				typeof(SpawnMode)
			})]
			private static void EndGeneration(List<ZDOID> __state)
			{
				_capture = __state;
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(ZDOMan), "CreateNewZDO", new Type[]
			{
				typeof(Vector3),
				typeof(int)
			})]
			private static void RememberCreated(ZDO __result)
			{
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				if (__result != null)
				{
					DungeonSwap.RememberCreated(__result);
					if (_capture != null)
					{
						_capture.Add(__result.m_uid);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPatch(typeof(ZDO), "Set", new Type[]
			{
				typeof(int),
				typeof(byte[])
			})]
			private static void BeforeInventoryWrite(ZDO __instance, int hash, out byte[] __state)
			{
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				__state = null;
				if (hash == ZDOVars.s_items && !_rearrangingChest && !AutomaticChestLoot.IsWriting(__instance) && !((Object)(object)ZNetScene.instance == (Object)null) && __instance.IsOwner() && !__instance.GetBool(PlayerFilledKey, false) && __instance.GetBool(ZDOVars.s_addedDefaultItems, false) && __instance.GetLong(ZDOVars.s_creator, 0L) == 0L && __instance.IsValid())
				{
					GameObject prefab = ZNetScene.instance.GetPrefab(__instance.GetPrefab());
					if ((Object)(object)prefab != (Object)null && IsLootChest(prefab.GetComponent<Container>()) && DungeonReset.TracksDeposits(__instance.GetPosition()))
					{
						__state = __instance.GetByteArray(hash, (byte[])null) ?? Array.Empty<byte>();
					}
				}
			}

			[HarmonyPostfix]
			[HarmonyPriority(0)]
			[HarmonyPatch(typeof(ZDO), "Set", new Type[]
			{
				typeof(int),
				typeof(byte[])
			})]
			private unsafe static void AfterInventoryWrite(ZDO __instance, int hash, byte[] __state, bool __runOriginal)
			{
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				if (!__runOriginal || __state == null)
				{
					return;
				}
				byte[] byteArray = __instance.GetByteArray(hash, (byte[])null);
				if (byteArray != null && byteArray != __state)
				{
					Container component = ZNetScene.instance.GetPrefab(__instance.GetPrefab()).GetComponent<Container>();
					bool flag;
					try
					{
						flag = DungeonContentsRules.HasDeposit(Units(__state, component), Units(byteArray, component));
					}
					catch (Exception ex)
					{
						ZDOID uid = __instance.m_uid;
						MwLog.Debug((object)("dungeons reset inventory comparison failed " + ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString() + " " + ex.GetType().Name));
						flag = true;
					}
					if (flag)
					{
						__instance.Set(PlayerFilledKey, true);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPatch(typeof(InventoryGrid), "DropItem")]
			private static void BeginDrag(InventoryGrid __instance, Inventory fromInventory, out bool __state)
			{
				__state = _rearrangingChest;
				_rearrangingChest |= __instance.GetInventory() == fromInventory;
			}

			[HarmonyFinalizer]
			[HarmonyPatch(typeof(InventoryGrid), "DropItem")]
			private static void EndDrag(bool __state)
			{
				_rearrangingChest = __state;
			}
		}

		private static readonly int GenerationKey = StringExtensionMethods.GetStableHashCode("meadworks.dungeons.reset.generation");

		private static readonly int OriginKey = StringExtensionMethods.GetStableHashCode("meadworks.dungeons.reset.origin");

		private static readonly int CoverageKey = StringExtensionMethods.GetStableHashCode("meadworks.dungeons.reset.loot_coverage");

		internal static readonly int PlayerFilledKey = StringExtensionMethods.GetStableHashCode("meadworks.dungeons.reset.player_filled");

		private static readonly Dictionary<long, HashSet<ZDOID>> Generations = new Dictionary<long, HashSet<ZDOID>>();

		private static readonly DungeonLootCoverage Coverage = new DungeonLootCoverage();

		private static bool _qualifiedLocation;

		private static bool _rearrangingChest;

		private static List<ZDOID> _capture;

		internal static void Init()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			Harmony val = new Harmony("expdare.meadworks.dungeons.dungeoncontents");
			val.PatchAll(typeof(Patches));
			LedgerTrack.Patch(val, "dungeons reset contents");
			Ledger.Add("dungeons contents state", (Action)ClearWorld);
		}

		internal static void ClearWorld()
		{
			Generations.Clear();
			_capture = null;
			_qualifiedLocation = false;
			_rearrangingChest = false;
			EndCoverage();
		}

		internal static void EndCoverage()
		{
			Coverage.End();
		}

		internal static void IndexMember(ZDO zdo)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			long num = zdo.GetLong(OriginKey, 0L);
			if (num != 0L)
			{
				if (!Generations.TryGetValue(num, out var value))
				{
					Generations.Add(num, value = new HashSet<ZDOID>());
				}
				value.Add(zdo.m_uid);
			}
		}

		internal static void WriteMembers(ZDO generator, List<ZDOID> members)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			long num;
			do
			{
				num = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0);
			}
			while (num == 0L || Generations.ContainsKey(num));
			foreach (ZDOID member in members)
			{
				ZDO zDO = ZDOMan.instance.GetZDO(member);
				if (zDO != null)
				{
					zDO.Set(OriginKey, num);
					IndexMember(zDO);
				}
			}
			generator.Set(GenerationKey, num);
			generator.Set(CoverageKey, Coverage.Current());
		}

		internal static void ForgetMembers(ZDO generator)
		{
			Generations.Remove(generator.GetLong(GenerationKey, 0L));
		}

		private static string PrefabLabel(GameObject prefab, ZDO zdo)
		{
			if (!((Object)(object)prefab == (Object)null))
			{
				return ((Object)prefab).name;
			}
			return zdo.GetPrefab().ToString();
		}

		internal unsafe static Plan Inspect(ZDO generator, HashSet<ZDOID> staged = null)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: 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)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0448: Unknown result type (might be due to invalid IL or missing references)
			//IL_044d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0585: Unknown result type (might be due to invalid IL or missing references)
			//IL_058a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0611: Unknown result type (might be due to invalid IL or missing references)
			//IL_0616: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cc: Unknown result type (might be due to invalid IL or missing references)
			ZNet instance = ZNet.instance;
			ZDOMan instance2 = ZDOMan.instance;
			ZNetScene instance3 = ZNetScene.instance;
			if ((Object)(object)instance == (Object)null || !instance.IsServer() || instance2 == null || (Object)(object)instance3 == (Object)null)
			{
				return null;
			}
			List<ZDO> list = new List<ZDO>();
			Vector2s zone = ZoneSystem.GetZone(generator.GetPosition());
			instance2.FindSectorObjects(zone, new SimulationDistance(0, 0, false), list, (List<ZDO>)null);
			long num = generator.GetLong(GenerationKey, 0L);
			bool flag = num == 0;
			bool flag2 = flag || Coverage.CarryUnmarked(generator.GetLong(CoverageKey, 0L));
			DungeonLegacyContents dungeonLegacyContents = (flag ? DungeonLegacyContents.Read(generator) : null);
			if (flag && dungeonLegacyContents == null)
			{
				Vector2s val = zone;
				MwLog.Debug((object)("dungeons reset cannot read the native contents of the generator at " + ((object)(*(Vector2s*)(&val))/*cast due to .constrained prefix*/).ToString()));
				return null;
			}
			HashSet<ZDO> hashSet = new HashSet<ZDO>();
			HashSet<ZDO> hashSet2 = new HashSet<ZDO>();
			foreach (ZDO item in list)
			{
				if (item != generator && (staged == null || !staged.Contains(item.m_uid)) && Character.InInterior(item.GetPosition()) && !(ZoneSystem.GetZone(item.GetPosition()) != zone))
				{
					hashSet.Add(item);
					if (flag && dungeonLegacyContents.Contains(item))
					{
						hashSet2.Add(item);
					}
					if (!flag && item.GetLong(OriginKey, 0L) == num)
					{
						hashSet2.Add(item);
					}
				}
			}
			if (!flag && Generations.TryGetValue(num, out var value))
			{
				foreach (ZDOID item2 in value)
				{
					ZDO zDO = instance2.GetZDO(item2);
					if (zDO != null && zDO != generator && zDO.GetLong(OriginKey, 0L) == num)
					{
						hashSet.Add(zDO);
						if (Character.InInterior(zDO.GetPosition()))
						{
							hashSet2.Add(zDO);
						}
					}
				}
			}
			foreach (ZDO item3 in new List<ZDO>(hashSet2))
			{
				GameObject prefab = instance3.GetPrefab(item3.GetPrefab());
				if ((Object)(object)prefab == (Object)null || (Object)(object)prefab.GetComponent<CreatureSpawner>() == (Object)null || item3.GetLong(ZDOVars.s_creator, 0L) != 0L)
				{
					continue;
				}
				ZDO zDO2 = instance2.GetZDO(item3.GetConnectionZDOID((ConnectionType)3));
				if (zDO2 == null)
				{
					continue;
				}
				GameObject prefab2 = instance3.GetPrefab(zDO2.GetPrefab());
				Character val2 = (((Object)(object)prefab2 == (Object)null) ? null : prefab2.GetComponent<Character>());
				if (!((Object)(object)val2 == (Object)null) && !(val2 is Player) && !val2.IsBoss())
				{
					hashSet.Add(zDO2);
					if (Character.InInterior(zDO2.GetPosition()))
					{
						hashSet2.Add(zDO2);
					}
				}
			}
			Plan plan = new Plan();
			long ticks = instance.GetTime().Ticks;
			bool zoneLoaded = ZoneSystem.instance.IsZoneLoaded(zone);
			foreach (ZDO item4 in hashSet)
			{
				GameObject prefab3 = instance3.GetPrefab(item4.GetPrefab());
				bool flag3 = item4.GetLong(ZDOVars.s_creator, 0L) != 0L || item4.GetBool(ZDOVars.s_tamed, false) || ((Object)(object)prefab3 != (Object)null && (Object)(object)prefab3.GetComponent<TombStone>() != (Object)null);
				ItemDrop val3 = (((Object)(object)prefab3 == (Object)null) ? null : prefab3.GetComponent<ItemDrop>());
				DungeonHold dungeonHold = ((!((Object)(object)val3 == (Object)null)) ? LooseItemHold(item4, val3, ticks, zoneLoaded) : DungeonHold.None);
				bool flag4 = item4.GetBool(PlayerFilledKey, false);
				bool flag5 = (Object)(object)prefab3 != (Object)null && (flag4 || IsLootChest(prefab3.GetComponent<Container>()));
				byte[] array = (flag5 ? item4.GetByteArray(ZDOVars.s_items, (byte[])null) : null);
				bool flag6 = (Object)(object)prefab3 != (Object)null && hashSet2.Contains(item4);
				if (!ReadItemCount(array, out var count) || (flag5 && array == null && item4.GetString(ZDOVars.s_items, "").Length != 0))
				{
					ZDOID uid = item4.m_uid;
					MwLog.Debug((object)("dungeons reset cannot read loot chest " + ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString() + " prefab=" + item4.GetPrefab()));
					plan.PlayerProperty = true;
					continue;
				}
				if (flag6 && flag5 && item4.GetBool(ZDOVars.s_inUse, false))
				{
					plan.OpenChest = true;
				}
				if (!flag3 && flag5 && count > 0 && (flag4 || flag2) && !flag6)
				{
					ZDOID uid = item4.m_uid;
					MwLog.Debug((object)("dungeons reset cannot transfer unmatched loot chest " + ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString() + " prefab=" + item4.GetPrefab()));
					plan.PlayerProperty = true;
					continue;
				}
				switch (DungeonContentsRules.Decide(flag3, (Object)(object)val3 != (Object)null, dungeonHold == DungeonHold.None, flag6, flag5, count > 0, flag4, flag2))
				{
				case DungeonContentAction.Block:
					if (!flag3 && dungeonHold == DungeonHold.Occupied)
					{
						plan.WaitingForDrop = true;
					}
					else
					{
						plan.PlayerProperty = true;
					}
					MwLog.Debug((object)("dungeons reset held by " + PrefabLabel(prefab3, item4) + " at " + ((object)item4.GetPosition()/*cast due to .constrained prefix*/).ToString() + (flag3 ? " (player property)" : " (loose item)")));
					break;
				case DungeonContentAction.Carry:
					plan.Carry.Add((item4, array));
					plan.Retire.Add(item4);
					break;
				case DungeonContentAction.Retire:
					plan.Retire.Add(item4);
					break;
				default:
					if ((Object)(object)prefab3 == (Object)null || (Object)(object)prefab3.GetComponent<Player>() == (Object)null)
					{
						ZDOID uid = item4.m_uid;
						MwLog.Debug((object)("dungeons reset retaining object " + ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString() + " prefab=" + item4.GetPrefab()));
					}
					break;
				}
			}
			return plan;
		}

		private static DungeonHold LooseItemHold(ZDO zdo, ItemDrop prefab, long now, bool zoneLoaded)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			if (!prefab.m_autoDestroy || !DungeonContentsRules.IsOldDrop(zdo.GetLong(ZDOVars.s_spawnTime, 0L), now) || zdo.GetBool(ZDOVars.s_piece, false))
			{
				return DungeonContentsRules.LooseItemHold(ageEligible: false, zoneLoaded, hasInstance: false, nativeCanDespawn: false);
			}
			ZNetView val = ZNetScene.instance.FindInstance(zdo);
			ItemDrop val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponent<ItemDrop>());
			bool nativeCanDespawn = (Object)(object)val2 != (Object)null && !val2.IsInsideBase() && !Player.IsPlayerInRange(zdo.GetPosition(), 25f) && !val2.InTar() && !val2.IsPiece();
			return DungeonContentsRules.LooseItemHold(ageEligible: true, zoneLoaded, (Object)(object)val2 != (Object)null, nativeCanDespawn);
		}

		private static bool IsLootChest(Container chest)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Invalid comparison between Unknown and I4
			if ((Object)(object)chest != (Object)null && (Object)(object)((Component)chest).GetComponent<TombStone>() == (Object)null && (Object)(object)chest.m_wagon == (Object)null && (Object)(object)chest.m_rootObjectOverride == (Object)null && (int)chest.m_privacy == 2 && chest.m_defaultItems != null && chest.m_defaultItems.m_drops != null)
			{
				return chest.m_defaultItems.m_drops.Count != 0;
			}
			return false;
		}

		private static bool ReadItemCount(byte[] data, out int count)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Invalid comparison between Unknown and I4
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Invalid comparison between Unknown and I4
			count = 0;
			if (data == null)
			{
				return true;
			}
			if (data.Length < 6)
			{
				return false;
			}
			ZPackage val = new ZPackage(data);
			Item val2 = (Item)val.ReadInt();
			if ((int)val2 > 110)
			{
				return false;
			}
			if ((int)val2 < 108 && data.Length < 8)
			{
				return false;
			}
			count = (((int)val2 >= 108) ? val.ReadUShort() : val.ReadInt());
			if (count >= 0)
			{
				return count <= data.Length;
			}
			return false;
		}

		private static Dictionary<(int Prefab, int Quality, int Variant, int WorldLevel), long> Units(byte[] data, Container chest)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//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_00b6: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<(int, int, int, int), long> counts = new Dictionary<(int, int, int, int), long>();
			if (data.Length == 0)
			{
				return counts;
			}
			if (!ReadItemCount(data, out var count))
			{
				throw new InvalidDataException();
			}
			ZPackage val = new ZPackage(data);
			Item val2 = (Item)val.ReadInt();
			if ((int)val2 < 108)
			{
				val.SetPos(0);
				Inventory val3 = new Inventory("", (Sprite)null, chest.m_width, chest.m_height);
				val3.Load(val);
				foreach (ItemData allItem in val3.GetAllItems())
				{
					Add(StringExtensionMethods.GetStableHashCode(((Object)allItem.m_dropPrefab).name), allItem);
				}
			}
			else
			{
				val.ReadUShort();
				for (int i = 0; i < count; i++)
				{
					var (hash, item) = ItemData.Load(val, val2);
					Add(hash, item);
				}
			}
			return counts;
			void Add(int item2, ItemData val4)
			{
				(int, int, int, int) key = (item2, val4.m_quality, val4.m_variant, val4.m_worldLevel);
				counts.TryGetValue(key, out var value);
				counts[key] = value + val4.m_stack;
			}
		}
	}
	public enum DungeonContentAction
	{
		Keep,
		Retire,
		Carry,
		Block
	}
	public sealed class DungeonLootCoverage
	{
		private long _period;

		public void End()
		{
			_period = 0L;
		}

		public long Current()
		{
			while (_period == 0L)
			{
				_period = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0);
			}
			return _period;
		}

		public bool CarryUnmarked(long layoutPeriod)
		{
			return layoutPeriod != Current();
		}
	}
	public static class DungeonContentsRules
	{
		public const long DespawnAge = 36000000000L;

		public static bool IsOldDrop(long spawnedAt, long now)
		{
			if (spawnedAt > 0 && now >= spawnedAt)
			{
				return now - spawnedAt >= 36000000000L;
			}
			return false;
		}

		public static DungeonHold LooseItemHold(bool ageEligible, bool zoneLoaded, bool hasInstance, bool nativeCanDespawn)
		{
			if (ageEligible && (hasInstance ? nativeCanDespawn : (!zoneLoaded)))
			{
				return DungeonHold.None;
			}
			if (zoneLoaded && (!ageEligible || hasInstance))
			{
				return DungeonHold.Property;
			}
			return DungeonHold.Occupied;
		}

		public static DungeonContentAction Decide(bool playerProperty, bool looseItem, bool canDespawn, bool layoutOwned, bool lootChest, bool hasItems, bool playerFilled, bool legacyLayout)
		{
			if (playerProperty)
			{
				return DungeonContentAction.Block;
			}
			if (looseItem)
			{
				if (!canDespawn)
				{
					return DungeonContentAction.Block;
				}
				return DungeonContentAction.Retire;
			}
			if (!layoutOwned)
			{
				return DungeonContentAction.Keep;
			}
			if (!(lootChest && hasItems) || !(playerFilled || legacyLayout))
			{
				return DungeonContentAction.Retire;
			}
			return DungeonContentAction.Carry;
		}

		public static bool HasDeposit<T>(IReadOnlyDictionary<T, long> before, IReadOnlyDictionary<T, long> after)
		{
			foreach (KeyValuePair<T, long> item in after)
			{
				if (!before.TryGetValue(item.Key, out var value) || item.Value > value)
				{
					return true;
				}
			}
			return false;
		}
	}
	internal static class DungeonGuard
	{
		private sealed class Pending
		{
			public int Token;

			public float Until;

			public Action Retry;
		}

		private const string QueryRpc = "MW_Dungeons_ClearQuery";

		private const string ReplyRpc = "MW_Dungeons_ClearReply";

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

		private static readonly List<ZDOID> Expired = new List<ZDOID>();

		private static ZRoutedRpc _rpc;

		private static ZDOID _permitted;

		private static int _token;

		private static bool _enabled;

		public static void Init()
		{
			_enabled = true;
			Ledger.Add("dungeons occupancy", (Action)delegate
			{
				//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)
				_enabled = false;
				Unregister();
				Requests.Clear();
				_permitted = ZDOID.None;
			});
		}

		private static void Unregister()
		{
			if (_rpc != null)
			{
				DungeonAdmission.Attach(null);
				DungeonSweep.Attach(null);
				_rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Dungeons_ClearQuery"));
				_rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Dungeons_ClearReply"));
				_rpc = null;
			}
		}

		public static void Tick()
		{
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			if (!_enabled)
			{
				return;
			}
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != _rpc)
			{
				Unregister();
				Requests.Clear();
				_rpc = instance;
				DungeonAdmission.Attach(instance);
				DungeonSweep.Attach(instance);
				if (instance != null)
				{
					RoutedRpcGuard.Register(new string[2] { "MW_Dungeons_ClearQuery", "MW_Dungeons_ClearReply" });
					instance.Register<ZDOID, int>("MW_Dungeons_ClearQuery", (Action<long, ZDOID, int>)Query);
					instance.Register<ZDOID, int, bool>("MW_Dungeons_ClearReply", (Action<long, ZDOID, int, bool>)Reply);
				}
			}
			Expired.Clear();
			foreach (KeyValuePair<ZDOID, Pending> request in Requests)
			{
				if (Time.time > request.Value.Until)
				{
					Expired.Add(request.Key);
				}
			}
			foreach (ZDOID item in Expired)
			{
				Requests.Remove(item);
			}
		}

		private static bool PlayerInside(Location location, Vector3 position)
		{
			//IL_0008: 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_0018: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			return DungeonGuardRules.Blocks(targetInterior: true, (Object)(object)location != (Object)null, Character.InInterior(position), (Object)(object)location != (Object)null && ZoneSystem.GetZone(position) == ZoneSystem.GetZone(((Component)location).transform.position));
		}

		private static bool Occupied(Vector3 position, bool server)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			Location location = Location.GetLocation(position, true);
			if ((Object)(object)location == (Object)null || !location.m_hasInterior)
			{
				return true;
			}
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if ((Object)(object)allPlayer != (Object)null && PlayerInside(location, ((Component)allPlayer).transform.position))
				{
					return true;
				}
			}
			if (!server)
			{
				return false;
			}
			foreach (ZDO allCharacterZDO in ZNet.instance.GetAllCharacterZDOS())
			{
				if (PlayerInside(location, allCharacterZDO.GetPosition()))
				{
					return true;
				}
			}
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer.IsReady() && PlayerInside(location, peer.m_refPos))
				{
					return true;
				}
			}
			return false;
		}

		internal static bool OccupiedForReset(Vector2s zone)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: 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_010e: 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)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null || !instance.IsServer())
			{
				return true;
			}
			Player localPlayer = Player.m_localPlayer;
			if (!instance.IsDedicated() && ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsTeleporting() || !DungeonOccupancy.Known(((Component)localPlayer).transform.position)))
			{
				return true;
			}
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if ((Object)(object)allPlayer != (Object)null && DungeonOccupancy.Inside(((Component)allPlayer).transform.position, zone))
				{
					return true;
				}
			}
			foreach (ZDO allCharacterZDO in instance.GetAllCharacterZDOS())
			{
				if (DungeonOccupancy.Inside(allCharacterZDO.GetPosition(), zone))
				{
					return true;
				}
			}
			foreach (ZNetPeer peer in instance.GetPeers())
			{
				ZDO val = DungeonOccupancy.PeerCharacter(peer);
				if (val == null)
				{
					return true;
				}
				Vector3 position = val.GetPosition();
				Vector3 refPos = peer.m_refPos;
				if (DungeonOccupancyRules.Blocks(DungeonOccupancy.Known(position) && DungeonOccupancy.Known(refPos), DungeonOccupancy.Inside(position, zone), DungeonOccupancy.Inside(refPos, zone)))
				{
					return true;
				}
			}
			return false;
		}

		public static bool Blocked(ZNetView view, Action retry)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//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)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)view).transform.position;
			if (!Character.InInterior(position))
			{
				return false;
			}
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return true;
			}
			if (instance.IsServer())
			{
				return Occupied(position, server: true);
			}
			if (Occupied(position, server: false))
			{
				return true;
			}
			ZDOID uid = view.GetZDO().m_uid;
			if (_permitted == uid)
			{
				_permitted = ZDOID.None;
				return false;
			}
			Tick();
			if (_rpc == null || Requests.ContainsKey(uid) || Requests.Count >= 128)
			{
				return true;
			}
			Pending pending = new Pending
			{
				Token = ++_token,
				Until = Time.time + 5f,
				Retry = retry
			};
			Requests.Add(uid, pending);
			_rpc.InvokeRoutedRPC(_rpc.GetServerPeerID(), "MW_Dungeons_ClearQuery", new object[2] { uid, pending.Token });
			return true;
		}

		private static void Query(long sender, ZDOID id, int token)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			ZNet instance = ZNet.instance;
			ZDO val = ((ZDOMan.instance == null) ? null : ZDOMan.instance.GetZDO(id));
			if (val != null && DungeonGuardRules.AcceptRequest((Object)(object)instance != (Object)null && instance.IsServer(), sender, val.GetOwner()))
			{
				Vector3 position = val.GetPosition();
				bool flag = Character.InInterior(position) && !Occupied(position, server: true);
				_rpc.InvokeRoutedRPC(sender, "MW_Dungeons_ClearReply", new object[3] { id, token, flag });
			}
		}

		private static void Reply(long sender, ZDOID id, int token, bool clear)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: 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_0035: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			if (_rpc == null || !Requests.TryGetValue(id, out var value) || !DungeonGuardRules.AcceptReply(sender, _rpc.GetServerPeerID(), token, value.Token))
			{
				return;
			}
			Requests.Remove(id);
			if (!clear || Time.time > value.Until)
			{
				return;
			}
			_permitted = id;
			try
			{
				value.Retry();
			}
			finally
			{
				_permitted = ZDOID.None;
			}
		}
	}
	public static class DungeonGuardRules
	{
		public static bool Blocks(bool targetInterior, bool locationKnown, bool playerInterior, bool sameLocation)
		{
			if (targetInterior)
			{
				if (locationKnown)
				{
					return playerInterior && sameLocation;
				}
				return true;
			}
			return false;
		}

		public static bool AcceptRequest(bool server, long sender, long owner)
		{
			if (server && sender != 0L)
			{
				return sender == owner;
			}
			return false;
		}

		public static bool AcceptReply(long sender, long server, int token, int pendingToken)
		{
			if (server != 0L && sender == server)
			{
				return token == pendingToken;
			}
			return false;
		}
	}
	internal static class DungeonLayout
	{
		internal readonly struct Placement
		{
			internal readonly int Hash;

			internal readonly Vector3 Position;

			internal readonly Quaternion Rotation;

			internal Placement(int hash, Vector3 position, Quaternion rotation)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				Hash = hash;
				Position = position;
				Rotation = rotation;
			}
		}

		internal static List<Placement> Read(ZDO generator)
		{
			string reason;
			return Read(generator, out reason);
		}

		internal static List<Placement> Read(ZDO generator, out string reason)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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)
			List<Placement> list = Rooms(generator, out reason);
			if (list == null)
			{
				return null;
			}
			for (int i = 0; i < list.Count; i++)
			{
				Placement placement = list[i];
				if (placement.Hash == 0 || !DungeonOccupancy.Known(placement.Position))
				{
					string[] obj = new string[8]
					{
						"room ",
						i.ToString(),
						" of ",
						list.Count.ToString(),
						" hash ",
						null,
						null,
						null
					};
					int hash = placement.Hash;
					obj[5] = hash.ToString();
					obj[6] = " at ";
					obj[7] = ((object)placement.Position/*cast due to .constrained prefix*/).ToString();
					reason = string.Concat(obj);
					return null;
				}
			}
			return list;
		}

		internal static List<Placement> Rooms(ZDO generator, out string reason)
		{
			//IL_00af: 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_00c6: 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)
			byte[] byteArray = generator.GetByteArray(ZDOVars.s_roomData, (byte[])null);
			if (byteArray != null)
			{
				return DungeonLayoutRules.DecodeRooms(byteArray, out reason)?.Select((DungeonLayoutRules.RoomRecord r) => new Placement(r.Hash, new Vector3(r.X, r.Y, r.Z), Quaternion.Euler(r.Pitch, r.Yaw, r.Roll))).ToList();
			}
			int num = generator.GetInt(ZDOVars.s_rooms, 0);
			if (num <= 0 || num > 512)
			{
				reason = "room count " + num + " (no room data)";
				return null;
			}
			List<Placement> list = new List<Placement>(num);
			for (int num2 = 0; num2 < num; num2++)
			{
				string text = "room" + num2;
				list.Add(new Placement(generator.GetInt(text, 0), generator.GetVec3(text + "_pos", Vector3.zero), generator.GetQuaternion(text + "_rot", Quaternion.identity)));
			}
			reason = null;
			return list;
		}

		internal static bool Same(IReadOnlyList<Placement> left, IReadOnlyList<Placement> right)
		{
			if (left.Count != right.Count)
			{
				return false;
			}
			List<Placement> list = new List<Placement>(right);
			foreach (Placement first in left)
			{
				int num = list.FindIndex(delegate(Placement second)
				{
					//IL_0019: Unknown result type (might be due to invalid IL or missing references)
					//IL_001f: 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_0029: Unknown result type (might be due to invalid IL or missing references)
					//IL_003e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0044: Unknown result type (might be due to invalid IL or missing references)
					if (first.Hash == second.Hash)
					{
						Vector3 val = first.Position - second.Position;
						if (((Vector3)(ref val)).sqrMagnitude < 0.0025f)
						{
							return Quaternion.Angle(first.Rotation, second.Rotation) < 1f;
						}
					}
					return false;
				});
				if (num < 0)
				{
					return false;
				}
				list.RemoveAt(num);
			}
			return true;
		}

		internal static int Placed(List<Room> placed)
		{
			return DungeonLayoutRules.PlacedRooms(placed.Count, placed.Count((Room r) => r.m_endCap || r.m_divider));
		}

		internal static int Traversable(DungeonGenerator generator, List<Room> placed)
		{
			string fault;
			return Traversable(generator, placed, out fault);
		}

		internal unsafe static int Traversable(DungeonGenerator generator, List<Room> placed, out string fault)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: 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_00aa: 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_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: 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_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_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			fault = null;
			if (placed.Count < 2 || placed.Count > 512 || !placed[0].m_entrance)
			{
				fault = "placed " + placed.Count + ((placed.Count > 0 && !placed[0].m_entrance) ? ", first not entrance" : "");
				return 0;
			}
			RoomConnection entrance = placed[0].GetEntrance();
			Vector3 val;
			if (!((Object)(object)entrance == (Object)null))
			{
				val = ((Component)entrance).transform.position - ((Component)generator).transform.position;
				if (!(((Vector3)(ref val)).sqrMagnitude > 0.01f))
				{
					Bounds val2 = default(Bounds);
					((Bounds)(ref val2))..ctor(generator.m_zoneCenter, generator.m_zoneSize + Vector3.one * 0.02f);
					Vector2s zone = ZoneSystem.GetZone(((Component)generator).transform.position);
					foreach (Room item in placed)
					{
						if (!DungeonOccupancy.Inside(((Component)item).transform.position, zone) || !Inside(val2, item))
						{
							string[] obj = new string[6]
							{
								"room ",
								((Object)item).name,
								" at ",
								null,
								null,
								null
							};
							val = ((Component)item).transform.position;
							obj[3] = ((object)(*(Vector3*)(&val))/*cast due to .constrained prefix*/).ToString();
							obj[4] = " outside ";
							object obj2;
							if (!DungeonOccupancy.Inside(((Component)item).transform.position, zone))
							{
								obj2 = "zone";
							}
							else
							{
								Bounds val3 = val2;
								obj2 = "bounds " + ((object)(*(Bounds*)(&val3))/*cast due to .constrained prefix*/).ToString();
							}
							obj[5] = (string)obj2;
							fault = string.Concat(obj);
							return 0;
						}
					}
					Room[] array = placed.Where((Room r) => !r.m_endCap && !r.m_divider).ToArray();
					if (array.Length < 2 || (Object)(object)array[0] != (Object)(object)placed[0])
					{
						fault = "rooms " + array.Length;
						return 0;
					}
					if (generator.m_minRequiredRooms > 0 && array.Count((Room r) => generator.m_requiredRooms.Contains(((Object)((Component)r).gameObject).name)) < generator.m_minRequiredRooms)
					{
						fault = "required rooms missing";
						return 0;
					}
					List<(int, int)> list = new List<(int, int)>();
					RoomConnection[][] array2 = array.Select((Room room) => room.GetConnections()).ToArray();
					for (int num = 0; num < array.Length; num++)
					{
						for (int num2 = num + 1; num2 < array.Length; num2++)
						{
							RoomConnection[] array3 = array2[num];
							foreach (RoomConnection port in array3)
							{
								if (!port.m_entrance && array2[num2].Any((RoomConnection other) => !other.m_entrance && other.m_type == port.m_type && port.TestContact(other) && Vector3.Dot(((Component)port).transform.forward, ((Component)other).transform.forward) < -0.9f))
								{
									list.Add((num, num2));
									break;
								}
							}
						}
					}
					int num4 = DungeonLayoutRules.Reachable(array.Length, list);
					if (num4 != array.Length)
					{
						fault = "reached " + num4 + " of " + array.Length;
					}
					if (num4 != array.Length)
					{
						return 0;
					}
					return num4;
				}
			}
			object obj3;
			if (!((Object)(object)entrance == (Object)null))
			{
				val = ((Component)entrance).transform.position;
				string? text = ((object)(*(Vector3*)(&val))/*cast due to .constrained prefix*/).ToString();
				val = ((Component)generator).transform.position;
				obj3 = "entrance at " + text + " generator at " + ((object)(*(Vector3*)(&val))/*cast due to .constrained prefix*/).ToString();
			}
			else
			{
				obj3 = "no entrance";
			}
			fault = (string)obj3;
			return 0;
		}

		private static bool Inside(Bounds bounds, Room room)
		{
			//IL_0056: 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)
			//IL_0065: 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_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			if (DungeonLayoutRules.PivotOnly(((Vector3Int)(ref room.m_size)).x, ((Vector3Int)(ref room.m_size)).z))
			{
				return ((Bounds)(ref bounds)).Contains(