Decompiled source of SilentVanillaMaps v1.3.5

SilentVanillaMaps.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Silent")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.3.5.0")]
[assembly: AssemblyInformationalVersion("1.3.5")]
[assembly: AssemblyProduct("SilentVanilla Maps")]
[assembly: AssemblyTitle("SilentVanillaMaps")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.3.5.0")]
[module: UnverifiableCode]
namespace SVMaps
{
	[BepInPlugin("silent.vanilla.maps", "SilentVanilla Maps", "1.3.5")]
	public class Plugin : BaseUnityPlugin
	{
		internal enum SVMapMode
		{
			Vanilla,
			AllRandom,
			Districts,
			LongRun,
			Stairs
		}

		private sealed class SVMapPlan
		{
			public LevelGenerator Generator;

			public Level Level;

			public int[,] ZoneCells;

			public bool[,] ForcedPassage;

			public bool[,] ItemFreeCells;

			public List<Level> ZoneSources = new List<Level>();

			public bool OptimizeAllowed = true;

			private readonly Dictionary<Level, MergedPools> zonePoolByLevel = new Dictionary<Level, MergedPools>();

			private readonly Dictionary<long, CategoryUsage> usageByKey = new Dictionary<long, CategoryUsage>();

			public int ZoneCount => ZoneSources.Count;

			public MergedPools GetZonePools(int zone)
			{
				if (zone < 0 || zone >= ZoneSources.Count)
				{
					return null;
				}
				Level val = ZoneSources[zone];
				if (!zonePoolByLevel.TryGetValue(val, out var value) || value == null)
				{
					value = BuildCurrentLevelPools(val);
					zonePoolByLevel[val] = value;
				}
				return value;
			}

			public int GetZone(int x, int y)
			{
				if (ZoneCells == null || x < 0 || y < 0 || x >= ZoneCells.GetLength(0) || y >= ZoneCells.GetLength(1))
				{
					return -2;
				}
				return ZoneCells[x, y];
			}

			public void SetZone(int x, int y, int zone)
			{
				if (ZoneCells != null && x >= 0 && y >= 0 && x < ZoneCells.GetLength(0) && y < ZoneCells.GetLength(1))
				{
					ZoneCells[x, y] = zone;
				}
			}

			public void SetForcedPassage(int x, int y, bool value)
			{
				if (ForcedPassage != null && x >= 0 && y >= 0 && x < ForcedPassage.GetLength(0) && y < ForcedPassage.GetLength(1))
				{
					ForcedPassage[x, y] = value;
				}
			}

			public void SetItemFree(int x, int y, bool value)
			{
				if (ItemFreeCells != null && x >= 0 && y >= 0 && x < ItemFreeCells.GetLength(0) && y < ItemFreeCells.GetLength(1))
				{
					ItemFreeCells[x, y] = value;
				}
			}

			public bool IsItemFree(int x, int y)
			{
				if (ItemFreeCells != null && x >= 0 && y >= 0 && x < ItemFreeCells.GetLength(0) && y < ItemFreeCells.GetLength(1))
				{
					return ItemFreeCells[x, y];
				}
				return false;
			}

			public bool IsForcedPassage(LevelGenerator generator, Tile[,] levelGrid, int x, int y)
			{
				if (ForcedPassage == null || x < 0 || y < 0 || x >= ForcedPassage.GetLength(0) || y >= ForcedPassage.GetLength(1) || !ForcedPassage[x, y])
				{
					return false;
				}
				return VanillaPassageTopologyHolds(generator, levelGrid, x, y);
			}

			public CategoryUsage GetUsage(Type targetType, int zone)
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				long key = (long)zone * 8L + (long)targetType;
				if (!usageByKey.TryGetValue(key, out var value) || value == null)
				{
					value = new CategoryUsage();
					usageByKey[key] = value;
				}
				return value;
			}
		}

		private class RoomEntry
		{
			public PrefabRef PrefabRef;

			public Level SourceLevel;

			public RoomEntry(PrefabRef prefabRef, Level sourceLevel)
			{
				PrefabRef = prefabRef;
				SourceLevel = sourceLevel;
			}
		}

		private class CategoryUsage
		{
			public readonly HashSet<string> UsedPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		}

		private class CategoryPool
		{
			public readonly List<RoomEntry> Entries = new List<RoomEntry>();

			private readonly HashSet<string> uniquePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

			public int UniqueCount => uniquePaths.Count;

			public void Add(RoomEntry entry)
			{
				if (entry != null && IsValidPrefabRef(entry.PrefabRef))
				{
					Entries.Add(entry);
					uniquePaths.Add(((PrefabRef<GameObject>)(object)entry.PrefabRef).ResourcePath);
				}
			}

			public bool ContainsResourcePath(string resourcePath)
			{
				if (!string.IsNullOrEmpty(resourcePath))
				{
					return uniquePaths.Contains(resourcePath);
				}
				return false;
			}

			public RoomEntry ChoosePreferDifferentSource(HashSet<Level> avoidSourceLevels, CategoryUsage usage, RoomEntry currentEntry)
			{
				if (Entries.Count <= 0)
				{
					return null;
				}
				if (usage != null && usage.UsedPaths.Count >= UniqueCount)
				{
					usage.UsedPaths.Clear();
				}
				List<RoomEntry> list = BuildCandidateList(avoidSourceLevels, usage, enforceAvoidSources: true);
				if (list.Count <= 0)
				{
					list = BuildCandidateList(avoidSourceLevels, usage, enforceAvoidSources: false);
				}
				if (list.Count <= 0)
				{
					list = BuildCandidateList(null, usage, enforceAvoidSources: true);
				}
				if (list.Count <= 0)
				{
					list = new List<RoomEntry>(Entries);
				}
				if (currentEntry != null)
				{
					int num = CalculateConflictScore(currentEntry, avoidSourceLevels);
					List<RoomEntry> list2 = new List<RoomEntry>();
					for (int i = 0; i < list.Count; i++)
					{
						RoomEntry roomEntry = list[i];
						if (roomEntry != null && CalculateConflictScore(roomEntry, avoidSourceLevels) < num)
						{
							list2.Add(roomEntry);
						}
					}
					if (list2.Count <= 0)
					{
						return currentEntry;
					}
					list = list2;
				}
				RoomEntry roomEntry2 = list[Random.Range(0, list.Count)];
				if (roomEntry2 != null && usage != null && !string.IsNullOrEmpty(((PrefabRef<GameObject>)(object)roomEntry2.PrefabRef).ResourcePath))
				{
					usage.UsedPaths.Add(((PrefabRef<GameObject>)(object)roomEntry2.PrefabRef).ResourcePath);
				}
				return roomEntry2;
			}

			private List<RoomEntry> BuildCandidateList(HashSet<Level> avoidSourceLevels, CategoryUsage usage, bool enforceAvoidSources)
			{
				List<RoomEntry> list = new List<RoomEntry>();
				for (int i = 0; i < Entries.Count; i++)
				{
					RoomEntry roomEntry = Entries[i];
					if (roomEntry != null && IsValidPrefabRef(roomEntry.PrefabRef) && (!enforceAvoidSources || avoidSourceLevels == null || avoidSourceLevels.Count <= 0 || !((Object)(object)roomEntry.SourceLevel != (Object)null) || !avoidSourceLevels.Contains(roomEntry.SourceLevel)) && (usage == null || !usage.UsedPaths.Contains(((PrefabRef<GameObject>)(object)roomEntry.PrefabRef).ResourcePath)))
					{
						list.Add(roomEntry);
					}
				}
				return list;
			}

			private int CalculateConflictScore(RoomEntry entry, HashSet<Level> avoidSourceLevels)
			{
				if (entry == null || (Object)(object)entry.SourceLevel == (Object)null || avoidSourceLevels == null || avoidSourceLevels.Count <= 0)
				{
					return 0;
				}
				return avoidSourceLevels.Contains(entry.SourceLevel) ? 1 : 0;
			}
		}

		private class MergedPools
		{
			public List<Level> SourceLevels = new List<Level>();

			public CategoryPool StartRooms = new CategoryPool();

			public CategoryPool NormalRooms = new CategoryPool();

			public CategoryPool PassageRooms = new CategoryPool();

			public CategoryPool DeadEndRooms = new CategoryPool();

			public CategoryPool ExtractionRooms = new CategoryPool();

			public CategoryPool SpecialRooms = new CategoryPool();
		}

		[HarmonyPatch(typeof(RunManager), "SetRunLevel")]
		private static class Patch_RunManager_SetRunLevel
		{
			private static bool Prefix(RunManager __instance)
			{
				try
				{
					if ((Object)(object)__instance == (Object)null || __instance.levels == null || __instance.levels.Count == 0)
					{
						return true;
					}
					SVMapMode sVMapMode = PickModeForRound();
					if (sVMapMode == SVMapMode.Vanilla)
					{
						Level val = null;
						List<Level> list = new List<Level>();
						for (int i = 0; i < __instance.levels.Count; i++)
						{
							Level val2 = __instance.levels[i];
							if ((Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)__instance.previousRunLevel)
							{
								list.Add(val2);
							}
						}
						val = (__instance.levelCurrent = ((list.Count <= 0) ? __instance.previousRunLevel : list[Random.Range(0, list.Count)]));
						ModesByLevel[__instance.levelCurrent] = SVMapMode.Vanilla;
						if (DebugLog != null && DebugLog.Value && LogSource != null)
						{
							LogSource.LogInfo((object)("[SilentVanilla] Maps: round = default vanilla (vanilla level " + SafeLevelName(val) + ")."));
						}
						return false;
					}
					Level val3 = FindMuseumBaseLevel();
					if ((Object)(object)val3 == (Object)null)
					{
						return true;
					}
					__instance.levelCurrent = val3;
					ModesByLevel[val3] = sVMapMode;
					if (DebugLog != null && DebugLog.Value && LogSource != null)
					{
						LogSource.LogInfo((object)("[SilentVanilla] Maps: round = " + ModeToString(sVMapMode) + " (museum base " + SafeLevelName(val3) + ")."));
					}
					return false;
				}
				catch (Exception ex)
				{
					if (LogSource != null)
					{
						LogSource.LogError((object)("SetRunLevel round decision failed\n" + ex));
					}
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(LevelGenerator), "StartRoomGeneration")]
		private static class Patch_LevelGenerator_StartRoomGeneration
		{
			private static bool Prefix(LevelGenerator __instance, ref IEnumerator __result)
			{
				try
				{
					bool num = (Object)(object)__instance != (Object)null && ShouldApply(__instance.Level);
					SetRoomMergedMapActiveProperty(num);
					if (!num)
					{
						return true;
					}
					__result = StartRoomGenerationOverride(__instance);
					return false;
				}
				catch (Exception ex)
				{
					if (LogSource != null)
					{
						ManualLogSource logSource = LogSource;
						string text = "StartRoomGeneration Prefix failed\n";
						logSource.LogError((object)(text + ex));
					}
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(LevelGenerator), "ModuleGeneration")]
		private static class Patch_LevelGenerator_ModuleGeneration
		{
			private static bool Prefix(LevelGenerator __instance, ref IEnumerator __result)
			{
				try
				{
					if ((Object)(object)__instance == (Object)null || !ShouldApply(__instance.Level))
					{
						return true;
					}
					__result = ModuleGenerationOverride(__instance);
					return false;
				}
				catch (Exception ex)
				{
					if (LogSource != null)
					{
						ManualLogSource logSource = LogSource;
						string text = "ModuleGeneration Prefix failed\n";
						logSource.LogError((object)(text + ex));
					}
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(LevelGenerator), "TileGeneration")]
		private static class Patch_LevelGenerator_TileGeneration
		{
			private static bool Prefix(LevelGenerator __instance, ref IEnumerator __result)
			{
				try
				{
					if ((Object)(object)__instance == (Object)null || !ShouldApply(__instance.Level))
					{
						return true;
					}
					SVMapMode modeForLevel = GetModeForLevel(__instance.Level);
					if (modeForLevel != SVMapMode.Districts && modeForLevel != SVMapMode.LongRun)
					{
						if ((Object)(object)RunManager.instance == (Object)null || RunManager.instance.levelsCompleted <= 5)
						{
							return true;
						}
						__result = TileGenerationOverride(__instance);
						return false;
					}
					__result = TileGenerationOverride(__instance);
					return false;
				}
				catch (Exception ex)
				{
					if (LogSource != null)
					{
						ManualLogSource logSource = LogSource;
						string text = "TileGeneration Prefix failed\n";
						logSource.LogError((object)(text + ex));
					}
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(ValuableDirector), "SetupHost")]
		private static class Patch_ValuableDirector_SetupHost
		{
			private static void Prefix()
			{
				try
				{
					PrepareMergedValuablePresets(((Object)(object)LevelGenerator.Instance != (Object)null) ? LevelGenerator.Instance.Level : null);
					ScaleValuableSpawnLimits();
				}
				catch (Exception ex)
				{
					if (LogSource != null)
					{
						ManualLogSource logSource = LogSource;
						string text = "PrepareMergedValuablePresets failed\n";
						logSource.LogError((object)(text + ex));
					}
				}
			}
		}

		[HarmonyPatch(typeof(RunManager), "UpdateSteamRichPresence")]
		private static class Patch_RunManager_UpdateSteamRichPresence
		{
			private static void Postfix(RunManager __instance)
			{
				UpdateRoomMergedMapActiveProperty();
			}
		}

		[HarmonyPatch(typeof(LevelGenerator), "SpawnConnectObject")]
		private static class Patch_LevelGenerator_SpawnConnectObject
		{
			private static void Postfix(LevelGenerator __instance, Vector3 position, Vector3 rotation)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					if (ShouldSanitizeMergedConnectObjects(__instance))
					{
						SanitizeSpawnedConnectObject(__instance, position);
					}
				}
				catch (Exception ex)
				{
					if (LogSource != null)
					{
						ManualLogSource logSource = LogSource;
						string text = "SpawnConnectObject sanitize failed\n";
						logSource.LogError((object)(text + ex));
					}
				}
			}
		}

		private static class MapAnnounce
		{
			private const float ScreenWaitMax = 15f;

			private const float SettleSeconds = 1f;

			private const float TypingWaitMax = 5f;

			internal static void Install()
			{
				SceneManager.sceneLoaded += OnSceneLoaded;
			}

			private static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				if ((int)mode == 0 && !((Object)(object)Instance == (Object)null))
				{
					((MonoBehaviour)Instance).StartCoroutine(Post());
				}
			}

			private static IEnumerator Post()
			{
				RunManager manager = null;
				try
				{
					manager = RunManager.instance;
				}
				catch (Exception)
				{
				}
				if ((Object)(object)manager == (Object)null || !IsGenerationAuthority())
				{
					yield break;
				}
				Level level = manager.levelCurrent;
				if ((Object)(object)level == (Object)null || !SemiFunc.RunIsLevel(level))
				{
					yield break;
				}
				float waited = 0f;
				while ((Object)(object)TruckScreenText.instance == (Object)null && waited < 15f)
				{
					waited += Time.deltaTime;
					yield return null;
				}
				if (!((Object)(object)TruckScreenText.instance == (Object)null))
				{
					yield return (object)new WaitForSeconds(1f);
					waited = 0f;
					while (TruckScreenText.instance.isTyping && !TaxmanQuietStart.SuppressActive() && waited < 5f)
					{
						waited += Time.deltaTime;
						yield return null;
					}
					string text = ModeToString(GetModeForLevel(level));
					string text2 = char.ToUpper(text[0]) + text.Substring(1);
					int num = manager.levelsCompleted + 1;
					Say("<b>==========  LEVEL " + num + "  ==========</b>\n<color=#00FF00>» " + text2 + "</color>");
					if (DebugLog != null && DebugLog.Value && LogSource != null)
					{
						LogSource.LogInfo((object)("[SilentVanilla] Maps: announced level " + num + ": " + text2));
					}
				}
			}

			private static void Say(string text)
			{
				try
				{
					TruckScreenText instance = TruckScreenText.instance;
					if ((Object)(object)instance != (Object)null)
					{
						instance.MessageSendCustom(string.Empty, text, 0);
						LogSource.LogInfo((object)("[SilentVanilla] Maps: truck screen page sent (" + text.Split('\n')[0] + ")"));
					}
				}
				catch (Exception)
				{
				}
			}
		}

		[HarmonyPatch(typeof(Module), "ModuleConnectionSetRPC")]
		private static class Patch_Module_ModuleConnectionSetRPC
		{
			private static void Postfix(Module __instance)
			{
				try
				{
					RemoveOuterDoorObjectsFromModule(__instance);
				}
				catch (Exception ex)
				{
					if (LogSource != null)
					{
						ManualLogSource logSource = LogSource;
						string text = "RemoveOuterDoorObjects failed\n";
						logSource.LogError((object)(text + ex));
					}
				}
			}
		}

		[HarmonyPatch(typeof(RunManager), "Awake")]
		private static class Patch_RunManager_Awake
		{
			private static void Postfix(RunManager __instance)
			{
				try
				{
					if (!((Object)(object)__instance == (Object)null) && !poolDumpDone && DebugLog != null && DebugLog.Value && LogSource != null)
					{
						poolDumpDone = true;
						DumpLevelPools("RUN-ROTATION", __instance.levels);
						DumpLevelPools("SHOP", __instance.levelShop);
						DumpLevelPools("ARENA", __instance.levelArena);
						DumpPhotonPrefabPool();
						LogSource.LogInfo((object)"[SVMaps][Dump] module pool dump complete.");
					}
				}
				catch (Exception ex)
				{
					if (LogSource != null)
					{
						LogSource.LogError((object)("Module pool dump failed\n" + ex));
					}
				}
			}
		}

		private static readonly Dictionary<Level, SVMapMode> ModesByLevel = new Dictionary<Level, SVMapMode>();

		private static SVMapPlan ActivePlan;

		public const string PluginGuid = "silent.vanilla.maps";

		public const string PluginName = "[SilentVanilla] Maps";

		public const string PluginVersion = "1.3.5";

		internal const string MergedMapPresenceName = "SilentVanilla Maps";

		internal const string RoomPropertyMergedMapActiveKey = "SV_Maps_Active";

		internal static readonly string[] TargetLoadingTextureNames = new string[5] { "level arctic 01", "level wizard 01", "level museum 01", "level manor 01", "level sunstone 01" };

		internal static readonly string[] SafeMergedVanillaLevelNames = new string[5] { "arctic", "wizard", "museum", "manor", "sunstone" };

		internal static Plugin Instance;

		internal static ManualLogSource LogSource;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> DebugLog;

		internal static ConfigEntry<bool> RemoveOuterDoorObjects;

		internal static ConfigEntry<bool> ModeVanillaEnabled;

		internal static ConfigEntry<bool> ModeAllRandomEnabled;

		internal static ConfigEntry<bool> ModeDistrictsEnabled;

		internal static ConfigEntry<bool> ModeLongRunEnabled;

		internal static ConfigEntry<bool> ModeStairsEnabled;

		private const bool RandomizeStartRoomsValue = true;

		private const bool FullyRandomIgnoreDifficultyTierValue = true;

		private const bool NoRepeatUntilPoolExhaustedValue = false;

		private const bool PreferDifferentAdjacentSourceLevelValue = true;

		private const int AdjacencyImprovePassesValue = 2;

		private const string OuterDoorNameKeywordsValue = "door,gate,hatch";

		private const bool LongRunAllowDeadEndsValue = false;

		private const bool LongRunAllowSpecialRoomsValue = false;

		private const int DistrictConnectorHallwaysValue = 2;

		private const string MuseumLevelNameKeyword = "museum";

		private static readonly Dictionary<Level, List<LevelValuables>> OriginalValuablePresetsByLevel = new Dictionary<Level, List<LevelValuables>>();

		private static bool reflectionReady;

		private Harmony harmony;

		private static FieldRef<LevelGenerator, bool> WaitingForSubCoroutineRef;

		private static FieldRef<LevelGenerator, int> PassageAmountRef;

		private static FieldRef<LevelGenerator, Tile[,]> LevelGridRef;

		private static FieldRef<LevelGenerator, Vector3[]> ModuleRotationsRef;

		private static FieldRef<LevelGenerator, PrefabRef> DebugStartRoomRef;

		private static FieldRef<LevelGenerator, PrefabRef> DebugModuleRef;

		private static FieldRef<LevelGenerator, bool> DebugNormalRef;

		private static FieldRef<LevelGenerator, bool> DebugPassageRef;

		private static FieldRef<LevelGenerator, bool> DebugDeadEndRef;

		private static FieldRef<Module, int> GridXRef;

		private static FieldRef<Module, int> GridYRef;

		private static FieldRef<Module, bool> ConnectingTopRef;

		private static FieldRef<Module, bool> ConnectingRightRef;

		private static FieldRef<Module, bool> ConnectingBottomRef;

		private static FieldRef<Module, bool> ConnectingLeftRef;

		private static FieldRef<Module, bool> FirstRef;

		private static FieldRef<LevelGenerator, int> DeadEndAmountRef;

		private static FieldRef<LevelGenerator, int> ExtractionAmountRef;

		private static FieldRef<LevelGenerator, int> SpecialAmountRef;

		private static FieldRef<ValuableDirector, int> TotalMaxAmountRef;

		private static FieldInfo LevelLoadingGraphic01Field;

		private static FieldInfo LevelLoadingGraphic02Field;

		private static FieldInfo LevelLoadingGraphic03Field;

		private static bool poolDumpDone;

		private static readonly string[] StairsNormalRooms = new string[17]
		{
			"Long Stairs", "The Pit", "Tall Cafe", "Pillars", "The Loft", "Balconies", "Central Cutout Column", "Vent to Drop", "Broken Barricade", "Thinking Chamber",
			"Sludge Pits of Joy", "Upstairs Classroom", "Big Cauldron", "East Wing Lobby", "Catwalks", "Magic Plant School", "Vents"
		};

		private static readonly string[] StairsPassageRooms = new string[15]
		{
			"Stair Passage", "Two Ways", "Tower", "Downhell", "Elevator to Sub Floor", "Side Abyss", "Bridge", "Pit Passage", "Nook Pits", "Ground Floor Attic",
			"Stairs Hangout Hall", "Common Room", "Deathpit Stairs", "Deathpit Corridor", "Catwalk LS"
		};

		private static readonly string[] StairsDeadEndRooms = new string[12]
		{
			"Upper Level", "Death Pit", "The Maw", "Collapsed Garage", "Basement Deep", "Bottomless Basement", "Outside Deathpit", "Stairs into Hell", "Dormitory with Hole", "Sludge Pits",
			"Wide Stairs and bedroom", "Stairway and Deathpit"
		};

		private static readonly string[] StairsExtractionRooms = new string[10] { "Stair Extract 1", "Stair Extract 2", "Stair Extract 3", "Perilous Staircase", "Wide Hole", "Stairway", "Stair Room", "Class Stair", "Upstairs", "Down Sludge" };

		private static readonly string[] LongRunNormalRooms = new string[40]
		{
			"Cross Corridors", "Diagonal Hallway", "Hallway Siderooms", "Relaxation Rooms", "The Loft", "Book Basement", "Central Mines", "Curved Walkways", "Double Column", "Split Column Display",
			"Roundabout", "Roundabout Tunnels", "Balconies", "Tall Cafe", "Hallway", "Lecture Hall", "Storage", "Classroom", "Cubicles", "Upstairs Classroom",
			"Cafeteria", "Two rooms and a corridor", "Warehouse", "Storage Room", "Center Specimen", "Cafe", "Big Kitchen", "Congregation Room", "Master Bedroom", "Octagon Library",
			"Sauna Shower", "Bunk Beds", "Treasure Trove", "Recreational Room", "East Wing Lobby", "Thinking Chamber", "Cooling Center", "Botanical Sector", "Cylinder Chamber", "Water Restaurant"
		};

		private static readonly string[] LongRunDeadEndRooms = new string[17]
		{
			"Small Bedroom", "Small Kitchen", "Wardrobe", "Attic", "Boiler Room", "Hidden Safe Bedroom", "Sauna", "Maintenance Room", "Small gallery", "Bar and Storage",
			"Shooting Range", "Dorm", "Great Library", "Headmaster's Study", "Small Office", "Single Bedroom", "Lower Labs"
		};

		private static readonly string[] DistrictsNormalRooms = new string[32]
		{
			"Cafe", "Curved Walkways", "Cylinder Chamber", "Double Column", "Roundabout", "Water Restaurant", "Balconies", "Tall Cafe", "Corner Pits", "Pits on All Sides",
			"Big Kitchen", "Congregation Room", "Master Bedroom", "Octagon Library", "Sauna Shower", "Book Basement", "Relaxation Rooms", "Bunk Beds", "Long Stairs", "Treasure Trove",
			"Classroom", "Lecture Hall", "Recreational Room", "Big Cauldron", "East Wing Lobby", "Thinking Chamber", "Upstairs Classroom", "Cafeteria", "Warehouse", "Center Specimen",
			"Cooling Center", "Botanical Sector"
		};

		private static readonly HashSet<string> StairsKeywordTokens = new HashSet<string>(new string[27]
		{
			"stair", "stairs", "staircase", "staircases", "stairway", "stairways", "pit", "pits", "hole", "holes",
			"shaft", "shafts", "basement", "basements", "loft", "lofts", "balcony", "balconies", "catwalk", "catwalks",
			"upstairs", "downstairs", "elevator", "mezzanine", "canyon", "chasm", "gorge"
		});

		private void Awake()
		{
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Expected O, but got Unknown
			try
			{
				Instance = this;
				LogSource = ((BaseUnityPlugin)this).Logger;
				((Component)this).transform.parent = null;
				((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
				Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
				Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master switch for [SilentVanilla] Maps custom generation.");
				DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "DebugLog", false, "Verbose logging for diagnosing problems.");
				RemoveOuterDoorObjects = ((BaseUnityPlugin)this).Config.Bind<bool>("Doors", "RemoveOuterDoorObjects", true, "Disable outer-side door objects on unconnected module edges.");
				ModeVanillaEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Maps", "ModeVanillaEnabled", true, "Default Vanilla: unmodified vanilla maps, vanilla level selection - no custom generation at all.");
				ModeAllRandomEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Maps", "ModeAllRandomEnabled", true, "AllRandom: all vanilla maps interleaved into one map (the original all-merge behavior).");
				ModeDistrictsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Maps", "ModeDistrictsEnabled", false, "Districts: the map is split into 4 contiguous zones (one per vanilla map), joined by item-free hallways.");
				ModeLongRunEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Maps", "ModeLongRunEnabled", false, "Long Run: one straight line of rooms; only extraction rooms sit on the sides.");
				ModeStairsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Maps", "ModeStairsEnabled", false, "Stairs: only rooms with staircases and holes, by name for the four classic maps plus automatic keyword matching so new maps join too. Extraction platforms and start rooms stay vanilla.");
				TaxmanQuietStart.QuietSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Taxman", "QuietSeconds", 15f, "Seconds the vanilla Taxman's scripted pages stay invisible at the start of every phase (level, store, truck). The pages still type and drive the game normally; only their text is muted so [SilentVanilla] messages show first. 0 disables muting.");
				reflectionReady = TryInitializeReflectionRefs();
				if (!reflectionReady)
				{
					LogSource.LogError((object)"Reflection initialization failed. Generation override disabled.");
				}
				harmony = new Harmony("silent.vanilla.maps");
				harmony.PatchAll();
				SVPresentation.Install();
				MapAnnounce.Install();
				LogSource.LogInfo((object)"[SilentVanilla] Maps loaded for REPO 0.4.4 - map merge engine v4.0.0.");
			}
			catch (Exception ex)
			{
				ManualLogSource logger = ((BaseUnityPlugin)this).Logger;
				string text = "Awake failed\n";
				logger.LogError((object)(text + ex));
			}
		}

		private static bool TryInitializeReflectionRefs()
		{
			try
			{
				WaitingForSubCoroutineRef = AccessTools.FieldRefAccess<LevelGenerator, bool>("waitingForSubCoroutine");
				PassageAmountRef = AccessTools.FieldRefAccess<LevelGenerator, int>("PassageAmount");
				LevelGridRef = AccessTools.FieldRefAccess<LevelGenerator, Tile[,]>("LevelGrid");
				ModuleRotationsRef = AccessTools.FieldRefAccess<LevelGenerator, Vector3[]>("ModuleRotations");
				DebugStartRoomRef = AccessTools.FieldRefAccess<LevelGenerator, PrefabRef>("DebugStartRoom");
				DebugModuleRef = AccessTools.FieldRefAccess<LevelGenerator, PrefabRef>("DebugModule");
				DebugNormalRef = AccessTools.FieldRefAccess<LevelGenerator, bool>("DebugNormal");
				DebugPassageRef = AccessTools.FieldRefAccess<LevelGenerator, bool>("DebugPassage");
				DebugDeadEndRef = AccessTools.FieldRefAccess<LevelGenerator, bool>("DebugDeadEnd");
				DeadEndAmountRef = AccessTools.FieldRefAccess<LevelGenerator, int>("DeadEndAmount");
				ExtractionAmountRef = AccessTools.FieldRefAccess<LevelGenerator, int>("ExtractionAmount");
				SpecialAmountRef = AccessTools.FieldRefAccess<LevelGenerator, int>("SpecialAmount");
				TotalMaxAmountRef = AccessTools.FieldRefAccess<ValuableDirector, int>("totalMaxAmount");
				GridXRef = AccessTools.FieldRefAccess<Module, int>("GridX");
				GridYRef = AccessTools.FieldRefAccess<Module, int>("GridY");
				ConnectingTopRef = AccessTools.FieldRefAccess<Module, bool>("ConnectingTop");
				ConnectingRightRef = AccessTools.FieldRefAccess<Module, bool>("ConnectingRight");
				ConnectingBottomRef = AccessTools.FieldRefAccess<Module, bool>("ConnectingBottom");
				ConnectingLeftRef = AccessTools.FieldRefAccess<Module, bool>("ConnectingLeft");
				FirstRef = AccessTools.FieldRefAccess<Module, bool>("First");
				LevelLoadingGraphic01Field = AccessTools.Field(typeof(Level), "LoadingGraphic01");
				LevelLoadingGraphic02Field = AccessTools.Field(typeof(Level), "LoadingGraphic02");
				LevelLoadingGraphic03Field = AccessTools.Field(typeof(Level), "LoadingGraphic03");
				if ((LevelLoadingGraphic01Field == null || LevelLoadingGraphic02Field == null || LevelLoadingGraphic03Field == null) && LogSource != null)
				{
					LogSource.LogWarning((object)"Level.LoadingGraphic fields were not found. Loading image replacement will use current LoadingUI images as fallback.");
				}
				return true;
			}
			catch (Exception ex)
			{
				if (LogSource != null)
				{
					ManualLogSource logSource = LogSource;
					string text = "TryInitializeReflectionRefs failed\n";
					logSource.LogError((object)(text + ex));
				}
				return false;
			}
		}

		internal static bool ShouldApply(Level level)
		{
			if (!reflectionReady || Enabled == null || !Enabled.Value)
			{
				return false;
			}
			if ((Object)(object)RunManager.instance == (Object)null || (Object)(object)level == (Object)null)
			{
				return false;
			}
			if (GetModeForLevel(level) == SVMapMode.Vanilla)
			{
				return false;
			}
			if (IsAlwaysExcludedLevel(level))
			{
				return false;
			}
			if (IsGenerationAuthority())
			{
				return IsMergedSessionActiveForLevel(level);
			}
			return false;
		}

		internal static bool ShouldApplyClientVisuals(Level level)
		{
			if (Enabled == null || !Enabled.Value)
			{
				return false;
			}
			if ((Object)(object)RunManager.instance == (Object)null || (Object)(object)level == (Object)null)
			{
				return false;
			}
			if (IsAlwaysExcludedLevel(level))
			{
				return false;
			}
			if (!PhotonNetwork.InRoom)
			{
				return IsMergedSessionActiveForLevel(level);
			}
			if (IsGenerationAuthority())
			{
				return IsMergedSessionActiveForLevel(level);
			}
			return IsRoomMergedMapActive();
		}

		internal static bool ShouldSanitizeMergedConnectObjects(LevelGenerator generator)
		{
			if ((Object)(object)generator == (Object)null)
			{
				return false;
			}
			Level val = generator.Level;
			if ((Object)(object)val == (Object)null && (Object)(object)RunManager.instance != (Object)null)
			{
				val = RunManager.instance.levelCurrent;
			}
			return ShouldApplyClientVisuals(val);
		}

		internal static bool IsGenerationAuthority()
		{
			if (PhotonNetwork.InRoom)
			{
				return PhotonNetwork.IsMasterClient;
			}
			return true;
		}

		private static bool IsRoomMergedMapActive()
		{
			if (!PhotonNetwork.InRoom || PhotonNetwork.CurrentRoom == null || ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties == null)
			{
				return false;
			}
			if (!((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)"SV_Maps_Active", out object value))
			{
				return false;
			}
			if (value is bool)
			{
				return (bool)value;
			}
			bool result = false;
			return value != null && bool.TryParse(value.ToString(), out result) && result;
		}

		private static bool IsMergedSessionActiveForLevel(Level level)
		{
			if ((Object)(object)level == (Object)null || IsAlwaysExcludedLevel(level))
			{
				return false;
			}
			return IsEligibleMergedSourceLevel(level);
		}

		private static void SetRoomMergedMapActiveProperty(bool active)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			if (IsGenerationAuthority() && PhotonNetwork.InRoom && PhotonNetwork.CurrentRoom != null && IsRoomMergedMapActive() != active)
			{
				Hashtable val = new Hashtable();
				val[(object)"SV_Maps_Active"] = active;
				PhotonNetwork.CurrentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
				if (DebugLog != null && DebugLog.Value && LogSource != null)
				{
					LogSource.LogInfo((object)("Updated room merged-map flag: " + active));
				}
			}
		}

		private static void UpdateRoomMergedMapActiveProperty()
		{
			if (Enabled != null && Enabled.Value && !((Object)(object)RunManager.instance == (Object)null))
			{
				if (GetModeForLevel(RunManager.instance.levelCurrent) == SVMapMode.Vanilla)
				{
					SetRoomMergedMapActiveProperty(active: false);
				}
				else
				{
					SetRoomMergedMapActiveProperty(IsMergedSessionActiveForLevel(RunManager.instance.levelCurrent));
				}
			}
		}

		internal static string GetMergedMapPresenceName()
		{
			return "[SilentVanilla] Maps";
		}

		internal static List<Level> CollectSourceLevels(Level baseLevel)
		{
			List<Level> result = new List<Level>();
			if ((Object)(object)RunManager.instance == (Object)null)
			{
				return result;
			}
			if (RunManager.instance.levels != null)
			{
				for (int i = 0; i < RunManager.instance.levels.Count; i++)
				{
					AddSourceLevelIfEligible(result, RunManager.instance.levels[i]);
				}
			}
			Level[] array = Resources.FindObjectsOfTypeAll<Level>();
			if (array != null)
			{
				for (int j = 0; j < array.Length; j++)
				{
					AddSourceLevelIfEligible(result, array[j]);
				}
			}
			AddSourceLevelIfEligible(result, baseLevel);
			AddSourceLevelIfEligible(result, RunManager.instance.levelCurrent);
			return result;
		}

		private static void AddSourceLevelIfEligible(List<Level> result, Level level)
		{
			if (result != null && IsEligibleMergedSourceLevel(level) && !result.Contains(level))
			{
				result.Add(level);
			}
		}

		private static bool IsAlwaysExcludedLevel(Level level)
		{
			if ((Object)(object)level == (Object)null)
			{
				return true;
			}
			if ((Object)(object)RunManager.instance == (Object)null)
			{
				return false;
			}
			if ((Object)(object)level == (Object)(object)RunManager.instance.levelMainMenu || (Object)(object)level == (Object)(object)RunManager.instance.levelSplashScreen || (Object)(object)level == (Object)(object)RunManager.instance.levelTutorial || (Object)(object)level == (Object)(object)RunManager.instance.levelLobbyMenu)
			{
				return true;
			}
			if ((Object)(object)level == (Object)(object)RunManager.instance.levelLobby || (Object)(object)level == (Object)(object)RunManager.instance.levelRecording)
			{
				return true;
			}
			if (IsLevelInList(level, RunManager.instance.levelArena))
			{
				return true;
			}
			return IsLevelInList(level, RunManager.instance.levelShop);
		}

		private static bool IsLevelInList(Level level, List<Level> levels)
		{
			if ((Object)(object)level == (Object)null || levels == null)
			{
				return false;
			}
			for (int i = 0; i < levels.Count; i++)
			{
				if ((Object)(object)level == (Object)(object)levels[i])
				{
					return true;
				}
			}
			return false;
		}

		private static void DumpLevelPools(string category, List<Level> list)
		{
			if (list == null)
			{
				LogSource.LogInfo((object)("[SVMaps][Dump] " + category + ": (null)"));
				return;
			}
			for (int i = 0; i < list.Count; i++)
			{
				Level val = list[i];
				if ((Object)(object)val == (Object)null)
				{
					LogSource.LogInfo((object)("[SVMaps][Dump] " + category + "[" + i + "]: (null level)"));
					continue;
				}
				LogSource.LogInfo((object)("[SVMaps][Dump] " + category + "[" + i + "] name=" + SafeLevelName(val) + " narrative=" + (val.NarrativeName ?? string.Empty)));
				DumpOneList(val, "StartRooms", val.StartRooms);
				DumpOneList(val, "Normal1", val.ModulesNormal1);
				DumpOneList(val, "Normal2", val.ModulesNormal2);
				DumpOneList(val, "Normal3", val.ModulesNormal3);
				DumpOneList(val, "Passage1", val.ModulesPassage1);
				DumpOneList(val, "Passage2", val.ModulesPassage2);
				DumpOneList(val, "Passage3", val.ModulesPassage3);
				DumpOneList(val, "DeadEnd1", val.ModulesDeadEnd1);
				DumpOneList(val, "DeadEnd2", val.ModulesDeadEnd2);
				DumpOneList(val, "DeadEnd3", val.ModulesDeadEnd3);
				DumpOneList(val, "Extraction1", val.ModulesExtraction1);
				DumpOneList(val, "Extraction2", val.ModulesExtraction2);
				DumpOneList(val, "Extraction3", val.ModulesExtraction3);
				DumpOneList(val, "Special", val.ModulesSpecial);
				DumpOneList(val, "Mega1", val.ModulesMega1);
				DumpOneList(val, "Mega2", val.ModulesMega2);
				DumpOneList(val, "Mega3", val.ModulesMega3);
			}
		}

		private static void DumpOneList(Level level, string listName, List<PrefabRef> sourceList)
		{
			if (sourceList == null || sourceList.Count == 0)
			{
				LogSource.LogInfo((object)("[SVMaps][Dump]   " + SafeLevelName(level) + " / " + listName + ": (empty)"));
				return;
			}
			List<string> list = new List<string>();
			for (int i = 0; i < sourceList.Count; i++)
			{
				PrefabRef val = sourceList[i];
				if (val != null && ((PrefabRef<GameObject>)(object)val).ResourcePath != null)
				{
					list.Add(((PrefabRef<GameObject>)(object)val).ResourcePath);
				}
			}
			LogSource.LogInfo((object)("[SVMaps][Dump]   " + SafeLevelName(level) + " / " + listName + " (" + list.Count + "): " + string.Join(", ", list)));
		}

		private static void DumpPhotonPrefabPool()
		{
			try
			{
				object obj = null;
				try
				{
					PropertyInfo property = typeof(PhotonNetwork).GetProperty("PrefabPool", BindingFlags.Static | BindingFlags.Public);
					if (property != null && property.GetMethod != null && property.GetMethod.IsStatic)
					{
						obj = property.GetValue(null);
					}
				}
				catch (Exception)
				{
				}
				if (LogSource != null)
				{
					LogSource.LogInfo((object)("[SVMaps][Dump] Photon PrefabPool: " + ((obj != null) ? obj.GetType().FullName : "(null)")));
				}
				if (obj == null)
				{
					return;
				}
				List<string> list = new List<string>();
				BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
				Type type = obj.GetType();
				while (type != null)
				{
					FieldInfo[] fields = type.GetFields(bindingAttr);
					foreach (FieldInfo fieldInfo in fields)
					{
						if (!fieldInfo.FieldType.IsGenericType || fieldInfo.FieldType.GetGenericTypeDefinition() != typeof(Dictionary<, >))
						{
							continue;
						}
						Type[] genericArguments = fieldInfo.FieldType.GetGenericArguments();
						if (genericArguments.Length != 2 || !(genericArguments[0] == typeof(string)) || !(fieldInfo.GetValue(obj) is IDictionary dictionary))
						{
							continue;
						}
						foreach (object key in dictionary.Keys)
						{
							if (key is string item)
							{
								list.Add(item);
							}
						}
					}
					type = type.BaseType;
				}
				list.Sort(StringComparer.OrdinalIgnoreCase);
				if (LogSource != null)
				{
					LogSource.LogInfo((object)("[SVMaps][Dump] Photon spawnable prefab keys (" + list.Count + "):"));
					for (int j = 0; j < list.Count; j++)
					{
						LogSource.LogInfo((object)("[SVMaps][Dump]   prefab[" + j + "]: " + list[j]));
					}
				}
			}
			catch (Exception ex2)
			{
				if (LogSource != null)
				{
					LogSource.LogError((object)("Photon prefab pool dump failed\n" + ex2));
				}
			}
		}

		private static Level FindMuseumBaseLevel()
		{
			if ((Object)(object)RunManager.instance == (Object)null || RunManager.instance.levels == null)
			{
				return null;
			}
			for (int i = 0; i < RunManager.instance.levels.Count; i++)
			{
				Level val = RunManager.instance.levels[i];
				if ((Object)(object)val != (Object)null && ((((Object)val).name != null && ((Object)val).name.IndexOf("museum", StringComparison.OrdinalIgnoreCase) >= 0) || (val.NarrativeName != null && val.NarrativeName.IndexOf("museum", StringComparison.OrdinalIgnoreCase) >= 0)))
				{
					return val;
				}
			}
			return null;
		}

		private static bool IsEligibleMergedSourceLevel(Level level)
		{
			if ((Object)(object)level == (Object)null || (Object)(object)RunManager.instance == (Object)null)
			{
				return false;
			}
			if (IsAlwaysExcludedLevel(level))
			{
				return false;
			}
			if (!HasMergeableRoomPools(level))
			{
				return false;
			}
			return IsSafeTargetVanillaLevel(level);
		}

		private static bool IsSafeTargetVanillaLevel(Level level)
		{
			if ((Object)(object)level == (Object)null)
			{
				return false;
			}
			if (IsTargetLoadingTextureName(GetLevelLoadingTextureName(level, 1)))
			{
				return true;
			}
			if (IsSafeTargetVanillaLevelName(level.NarrativeName))
			{
				return true;
			}
			return IsSafeTargetVanillaLevelName(((Object)level).name);
		}

		private static bool IsSafeTargetVanillaLevelName(string levelName)
		{
			if (string.IsNullOrWhiteSpace(levelName))
			{
				return false;
			}
			string text = NormalizeTextureName(levelName);
			text = text.Replace("level - ", string.Empty).Trim();
			text = text.Replace("level ", string.Empty).Trim();
			for (int i = 0; i < SafeMergedVanillaLevelNames.Length; i++)
			{
				if (string.Equals(text, SafeMergedVanillaLevelNames[i], StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			for (int j = 0; j < SafeMergedVanillaLevelNames.Length; j++)
			{
				if (SafeMergedVanillaLevelNames[j].Length >= 4 && text.IndexOf(SafeMergedVanillaLevelNames[j], StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return true;
				}
			}
			return false;
		}

		private static bool HasMergeableRoomPools(Level level)
		{
			if ((Object)(object)level == (Object)null)
			{
				return false;
			}
			if (HasPrefabRefList(level.StartRooms))
			{
				return true;
			}
			if (HasPrefabRefList(level.ModulesNormal1) || HasPrefabRefList(level.ModulesNormal2) || HasPrefabRefList(level.ModulesNormal3))
			{
				return true;
			}
			if (HasPrefabRefList(level.ModulesPassage1) || HasPrefabRefList(level.ModulesPassage2) || HasPrefabRefList(level.ModulesPassage3))
			{
				return true;
			}
			if (HasPrefabRefList(level.ModulesDeadEnd1) || HasPrefabRefList(level.ModulesDeadEnd2) || HasPrefabRefList(level.ModulesDeadEnd3))
			{
				return true;
			}
			if (HasPrefabRefList(level.ModulesExtraction1) || HasPrefabRefList(level.ModulesExtraction2) || HasPrefabRefList(level.ModulesExtraction3))
			{
				return true;
			}
			return HasPrefabRefList(level.ModulesSpecial);
		}

		private static bool HasPrefabRefList(List<PrefabRef> prefabRefs)
		{
			if (prefabRefs == null || prefabRefs.Count <= 0)
			{
				return false;
			}
			for (int i = 0; i < prefabRefs.Count; i++)
			{
				if (IsValidPrefabRef(prefabRefs[i]))
				{
					return true;
				}
			}
			return false;
		}

		private static bool IsValidPrefabRef(PrefabRef prefabRef)
		{
			if (prefabRef == null)
			{
				return false;
			}
			if (!((PrefabRef<GameObject>)(object)prefabRef).IsValid())
			{
				return false;
			}
			return !string.IsNullOrEmpty(((PrefabRef<GameObject>)(object)prefabRef).ResourcePath);
		}

		private static void PrepareMergedValuablePresets(Level baseLevel)
		{
			if ((Object)(object)baseLevel == (Object)null)
			{
				return;
			}
			CacheOriginalValuablePresets(baseLevel);
			if (!ShouldApply(baseLevel))
			{
				RestoreOriginalValuablePresets(baseLevel);
				return;
			}
			List<LevelValuables> list = BuildMergedValuablePresets(baseLevel);
			if (list.Count <= 0)
			{
				RestoreOriginalValuablePresets(baseLevel);
				return;
			}
			baseLevel.ValuablePresets = list;
			if (DebugLog != null && DebugLog.Value && LogSource != null)
			{
				LogSource.LogInfo((object)("Merged valuable preset count: " + list.Count));
			}
		}

		private static void ScaleValuableSpawnLimits()
		{
			LevelGenerator instance = LevelGenerator.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)ValuableDirector.instance == (Object)null || TotalMaxAmountRef == null || !ShouldApply(instance.Level) || !IsGenerationAuthority())
			{
				return;
			}
			int num = Mathf.Max(1, instance.ModuleAmount);
			float num2 = Mathf.Max(1f, (float)num / 15f);
			if (!(num2 <= 1.05f))
			{
				ValuableDirector instance2 = ValuableDirector.instance;
				int num3 = TotalMaxAmountRef.Invoke(instance2);
				TotalMaxAmountRef.Invoke(instance2) = Mathf.Max(num3, Mathf.RoundToInt((float)num3 * num2));
				instance2.tinyMaxAmountCurve1 = ScaleCurve(instance2.tinyMaxAmountCurve1, num2 * 1.5f);
				instance2.tinyMaxAmountCurve2 = ScaleCurve(instance2.tinyMaxAmountCurve2, num2 * 1.5f);
				instance2.smallMaxAmountCurve1 = ScaleCurve(instance2.smallMaxAmountCurve1, num2 * 1.25f);
				instance2.smallMaxAmountCurve2 = ScaleCurve(instance2.smallMaxAmountCurve2, num2 * 1.25f);
				instance2.mediumMaxAmountCurve1 = ScaleCurve(instance2.mediumMaxAmountCurve1, num2);
				instance2.mediumMaxAmountCurve2 = ScaleCurve(instance2.mediumMaxAmountCurve2, num2);
				instance2.bigMaxAmountCurve1 = ScaleCurve(instance2.bigMaxAmountCurve1, num2);
				instance2.bigMaxAmountCurve2 = ScaleCurve(instance2.bigMaxAmountCurve2, num2);
				instance2.wideMaxAmountCurve1 = ScaleCurve(instance2.wideMaxAmountCurve1, num2);
				instance2.wideMaxAmountCurve2 = ScaleCurve(instance2.wideMaxAmountCurve2, num2);
				instance2.tallMaxAmountCurve1 = ScaleCurve(instance2.tallMaxAmountCurve1, num2);
				instance2.tallMaxAmountCurve2 = ScaleCurve(instance2.tallMaxAmountCurve2, num2);
				instance2.veryTallMaxAmountCurve1 = ScaleCurve(instance2.veryTallMaxAmountCurve1, num2);
				instance2.veryTallMaxAmountCurve2 = ScaleCurve(instance2.veryTallMaxAmountCurve2, num2);
				if (DebugLog != null && DebugLog.Value && LogSource != null)
				{
					LogSource.LogInfo((object)("[SilentVanilla] Maps: valuable budgets scaled x" + num2.ToString("0.##") + " (tiny x" + (num2 * 1.5f).ToString("0.##") + ") for " + num + " modules; item cap " + TotalMaxAmountRef.Invoke(instance2)));
				}
			}
		}

		private static AnimationCurve ScaleCurve(AnimationCurve source, float multiplier)
		{
			//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_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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			if (source == null || source.keys == null || source.keys.Length == 0)
			{
				return source;
			}
			Keyframe[] array = (Keyframe[])(object)new Keyframe[source.keys.Length];
			for (int i = 0; i < source.keys.Length; i++)
			{
				Keyframe val = source.keys[i];
				((Keyframe)(ref val)).value = ((Keyframe)(ref val)).value * multiplier;
				array[i] = val;
			}
			return new AnimationCurve(array)
			{
				preWrapMode = source.preWrapMode,
				postWrapMode = source.postWrapMode
			};
		}

		private static List<LevelValuables> BuildMergedValuablePresets(Level baseLevel)
		{
			List<LevelValuables> list = new List<LevelValuables>();
			List<Level> list2 = CollectValuableSourceLevels(baseLevel);
			for (int i = 0; i < list2.Count; i++)
			{
				List<LevelValuables> originalValuablePresets = GetOriginalValuablePresets(list2[i]);
				for (int j = 0; j < originalValuablePresets.Count; j++)
				{
					LevelValuables val = originalValuablePresets[j];
					if ((Object)(object)val != (Object)null)
					{
						list.Add(val);
					}
				}
			}
			if (DebugLog != null && DebugLog.Value && LogSource != null)
			{
				LogSource.LogInfo((object)("Merged valuable source level count: " + list2.Count));
			}
			return list;
		}

		internal static List<Level> CollectValuableSourceLevels(Level baseLevel)
		{
			List<Level> result = new List<Level>();
			if ((Object)(object)RunManager.instance == (Object)null)
			{
				return result;
			}
			if (RunManager.instance.levels != null)
			{
				for (int i = 0; i < RunManager.instance.levels.Count; i++)
				{
					AddValuableSourceLevelIfEligible(result, RunManager.instance.levels[i]);
				}
			}
			Level[] array = Resources.FindObjectsOfTypeAll<Level>();
			if (array != null)
			{
				for (int j = 0; j < array.Length; j++)
				{
					AddValuableSourceLevelIfEligible(result, array[j]);
				}
			}
			AddValuableSourceLevelIfEligible(result, baseLevel);
			AddValuableSourceLevelIfEligible(result, RunManager.instance.levelCurrent);
			return result;
		}

		private static void AddValuableSourceLevelIfEligible(List<Level> result, Level level)
		{
			if (result != null && !((Object)(object)level == (Object)null) && IsEligibleMergedSourceLevel(level) && HasAnyValuablePresets(level) && !result.Contains(level))
			{
				result.Add(level);
			}
		}

		private static bool HasAnyValuablePresets(Level level)
		{
			List<LevelValuables> originalValuablePresets = GetOriginalValuablePresets(level);
			if (originalValuablePresets == null || originalValuablePresets.Count <= 0)
			{
				return false;
			}
			for (int i = 0; i < originalValuablePresets.Count; i++)
			{
				if ((Object)(object)originalValuablePresets[i] != (Object)null)
				{
					return true;
				}
			}
			return false;
		}

		private static void CacheOriginalValuablePresets(Level level)
		{
			if (!((Object)(object)level == (Object)null) && !OriginalValuablePresetsByLevel.ContainsKey(level))
			{
				OriginalValuablePresetsByLevel[level] = CloneValuablePresetList(level.ValuablePresets);
			}
		}

		private static List<LevelValuables> GetOriginalValuablePresets(Level level)
		{
			if ((Object)(object)level == (Object)null)
			{
				return new List<LevelValuables>();
			}
			CacheOriginalValuablePresets(level);
			if (!OriginalValuablePresetsByLevel.TryGetValue(level, out var value) || value == null)
			{
				return new List<LevelValuables>();
			}
			return CloneValuablePresetList(value);
		}

		private static void RestoreOriginalValuablePresets(Level level)
		{
			if (!((Object)(object)level == (Object)null) && OriginalValuablePresetsByLevel.TryGetValue(level, out var value) && value != null)
			{
				level.ValuablePresets = CloneValuablePresetList(value);
			}
		}

		private static List<LevelValuables> CloneValuablePresetList(List<LevelValuables> source)
		{
			List<LevelValuables> list = new List<LevelValuables>();
			if (source == null)
			{
				return list;
			}
			for (int i = 0; i < source.Count; i++)
			{
				if ((Object)(object)source[i] != (Object)null)
				{
					list.Add(source[i]);
				}
			}
			return list;
		}

		private static MergedPools BuildMergedPools(Level baseLevel)
		{
			List<Level> list = CollectSourceLevels(baseLevel);
			HashSet<string> excludedPaths = ParseExcludedPaths();
			MergedPools mergedPools = new MergedPools();
			mergedPools.SourceLevels = list;
			for (int i = 0; i < list.Count; i++)
			{
				Level val = list[i];
				AddListToCategoryPool(mergedPools.StartRooms, val, val.StartRooms, excludedPaths, allowDuplicatePaths: false);
			}
			for (int j = 0; j < list.Count; j++)
			{
				Level val2 = list[j];
				if (true)
				{
					AddListToCategoryPool(mergedPools.NormalRooms, val2, val2.ModulesNormal1, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.NormalRooms, val2, val2.ModulesNormal2, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.NormalRooms, val2, val2.ModulesNormal3, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.PassageRooms, val2, val2.ModulesPassage1, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.PassageRooms, val2, val2.ModulesPassage2, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.PassageRooms, val2, val2.ModulesPassage3, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.DeadEndRooms, val2, val2.ModulesDeadEnd1, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.DeadEndRooms, val2, val2.ModulesDeadEnd2, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.DeadEndRooms, val2, val2.ModulesDeadEnd3, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.ExtractionRooms, val2, val2.ModulesExtraction1, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.ExtractionRooms, val2, val2.ModulesExtraction2, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.ExtractionRooms, val2, val2.ModulesExtraction3, excludedPaths, allowDuplicatePaths: false);
				}
				else
				{
					AddListToCategoryPool(mergedPools.NormalRooms, val2, val2.ModulesNormal1, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.PassageRooms, val2, val2.ModulesPassage1, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.DeadEndRooms, val2, val2.ModulesDeadEnd1, excludedPaths, allowDuplicatePaths: false);
					AddListToCategoryPool(mergedPools.ExtractionRooms, val2, val2.ModulesExtraction1, excludedPaths, allowDuplicatePaths: false);
				}
				AddListToCategoryPool(mergedPools.SpecialRooms, val2, val2.ModulesSpecial, excludedPaths, allowDuplicatePaths: false);
			}
			if (DebugLog != null && DebugLog.Value && LogSource != null)
			{
				LogSource.LogInfo((object)("Merged source level count: " + list.Count));
				LogSource.LogInfo((object)("MergedStartRooms: " + mergedPools.StartRooms.UniqueCount));
				LogSource.LogInfo((object)("MergedNormalRooms: " + mergedPools.NormalRooms.UniqueCount));
				LogSource.LogInfo((object)("MergedPassageRooms: " + mergedPools.PassageRooms.UniqueCount));
				LogSource.LogInfo((object)("MergedDeadEndRooms: " + mergedPools.DeadEndRooms.UniqueCount));
				LogSource.LogInfo((object)("MergedExtractionRooms: " + mergedPools.ExtractionRooms.UniqueCount));
				LogSource.LogInfo((object)("MergedSpecialRooms: " + mergedPools.SpecialRooms.UniqueCount));
			}
			return mergedPools;
		}

		private static void AddListToCategoryPool(CategoryPool pool, Level sourceLevel, List<PrefabRef> sourceList, HashSet<string> excludedPaths, bool allowDuplicatePaths)
		{
			if (pool == null || (Object)(object)sourceLevel == (Object)null || sourceList == null)
			{
				return;
			}
			for (int i = 0; i < sourceList.Count; i++)
			{
				PrefabRef val = sourceList[i];
				if (IsValidPrefabRef(val))
				{
					string resourcePath = ((PrefabRef<GameObject>)(object)val).ResourcePath;
					if ((excludedPaths == null || !excludedPaths.Contains(resourcePath)) && (allowDuplicatePaths || !pool.ContainsResourcePath(resourcePath)))
					{
						pool.Add(new RoomEntry(val, sourceLevel));
					}
				}
			}
		}

		private static string ModeToString(SVMapMode mode)
		{
			return mode switch
			{
				SVMapMode.Vanilla => "default vanilla", 
				SVMapMode.Districts => "districts", 
				SVMapMode.LongRun => "long run", 
				SVMapMode.Stairs => "stairs", 
				_ => "all random", 
			};
		}

		private static SVMapMode PickModeForRound()
		{
			List<SVMapMode> list = new List<SVMapMode>();
			if (ModeVanillaEnabled == null || ModeVanillaEnabled.Value)
			{
				list.Add(SVMapMode.Vanilla);
			}
			if (ModeAllRandomEnabled == null || ModeAllRandomEnabled.Value)
			{
				list.Add(SVMapMode.AllRandom);
			}
			if (ModeDistrictsEnabled != null && ModeDistrictsEnabled.Value)
			{
				list.Add(SVMapMode.Districts);
			}
			if (ModeLongRunEnabled != null && ModeLongRunEnabled.Value)
			{
				list.Add(SVMapMode.LongRun);
			}
			if (ModeStairsEnabled != null && ModeStairsEnabled.Value)
			{
				list.Add(SVMapMode.Stairs);
			}
			if (list.Count <= 0)
			{
				return SVMapMode.Vanilla;
			}
			return list[Random.Range(0, list.Count)];
		}

		private static void RollModeForLevel(Level level)
		{
			if (!((Object)(object)level == (Object)null))
			{
				SVMapMode sVMapMode = PickModeForRound();
				ModesByLevel[level] = sVMapMode;
				if (DebugLog != null && DebugLog.Value && LogSource != null)
				{
					LogSource.LogInfo((object)("[SilentVanilla] Maps: level " + SafeLevelName(level) + " mode = " + ModeToString(sVMapMode)));
				}
			}
		}

		private static SVMapMode GetModeForLevel(Level level)
		{
			SVMapMode result = SVMapMode.Vanilla;
			if (!((Object)(object)level == (Object)null))
			{
				if (ModesByLevel.TryGetValue(level, out var value))
				{
					result = value;
				}
				else
				{
					if (IsGenerationAuthority())
					{
						RollModeForLevel(level);
						ModesByLevel.TryGetValue(level, out value);
					}
					result = value;
				}
			}
			return result;
		}

		private static SVMapPlan GetPlanForGenerator(LevelGenerator generator)
		{
			SVMapPlan activePlan = ActivePlan;
			if (activePlan == null || (Object)(object)generator == (Object)null)
			{
				return null;
			}
			if (!((Object)(object)activePlan.Generator == (Object)(object)generator))
			{
				return null;
			}
			return activePlan;
		}

		private static int ComputeVanillaModuleAmounts(LevelGenerator generator, out int deadEndAmount, out int extractionAmount, out int specialAmount)
		{
			int num = generator.ModuleAmount;
			deadEndAmount = 0;
			extractionAmount = 0;
			specialAmount = (((Object)(object)generator.Level != (Object)null) ? generator.Level.ModulesSpecialAmount : 0);
			if (num > 4)
			{
				num = Mathf.Min(5 + RunManager.instance.levelsCompleted, 10);
				if (RunManager.instance.levelsCompleted >= 10)
				{
					num += Mathf.Min(RunManager.instance.levelsCompleted - 9, 5);
				}
				num = Mathf.CeilToInt((float)num * generator.DebugLevelSize);
				if (GetDebugModule(generator) == null)
				{
					deadEndAmount = Mathf.CeilToInt((float)num / 3f);
					if (num >= 15)
					{
						extractionAmount = 4;
					}
					else if (num >= 10)
					{
						extractionAmount = 3;
					}
					else if (num >= 8)
					{
						extractionAmount = 2;
					}
					else if (num >= 6)
					{
						extractionAmount = 1;
					}
				}
			}
			if (SemiFunc.IsLevelShop(generator.Level))
			{
				deadEndAmount = 1;
			}
			ApplyVanillaAmounts(generator, num, deadEndAmount, extractionAmount, specialAmount);
			return num;
		}

		private static void EscalateModuleBudget(LevelGenerator generator, SVMapMode mode, ref int num, ref int deadEndAmount, ref int extractionAmount, ref int specialAmount)
		{
			if ((Object)(object)RunManager.instance == (Object)null || mode == SVMapMode.Vanilla)
			{
				return;
			}
			int levelsCompleted = RunManager.instance.levelsCompleted;
			float num2 = Mathf.Min(10f, Mathf.Max(5f, 4f + (float)levelsCompleted * 0.35f));
			bool flag = GetDebugModule(generator) == null;
			if (mode == SVMapMode.LongRun)
			{
				int num3 = Mathf.Min(60, Mathf.Max(10, 8 + Mathf.RoundToInt((float)levelsCompleted * 2.5f)));
				if (num3 > num)
				{
					num = num3;
					if (flag)
					{
						deadEndAmount = 0;
						extractionAmount = Mathf.Clamp(Mathf.RoundToInt((float)num / num2), 3, 6);
						specialAmount = 0;
					}
					ApplyVanillaAmounts(generator, num, deadEndAmount, extractionAmount, specialAmount);
					if (DebugLog != null && DebugLog.Value && LogSource != null)
					{
						LogSource.LogInfo((object)("[SilentVanilla] Maps: long run budget for level " + (levelsCompleted + 1) + " -> rooms " + num + ", " + num2.ToString("0.#") + " room gap, extraction " + extractionAmount));
					}
				}
				return;
			}
			int num4 = num + Mathf.Max(0, levelsCompleted - 5) * 2;
			if (num4 <= num)
			{
				return;
			}
			num4 = Mathf.Min(60, num4);
			if (num4 > num)
			{
				num = num4;
				if (flag)
				{
					deadEndAmount = Mathf.CeilToInt((float)num / 3f);
					extractionAmount = Mathf.Max(extractionAmount, Mathf.Min(6, Mathf.RoundToInt((float)num / num2)));
				}
				ApplyVanillaAmounts(generator, num, deadEndAmount, extractionAmount, specialAmount);
				if (DebugLog != null && DebugLog.Value && LogSource != null)
				{
					LogSource.LogInfo((object)("[SilentVanilla] Maps: budget escalated for level " + (levelsCompleted + 1) + " -> modules " + num + ", dead ends " + deadEndAmount + ", extraction " + extractionAmount + ", special " + specialAmount));
				}
			}
		}

		private static void ApplyVanillaAmounts(LevelGenerator generator, int moduleAmount, int deadEndAmount, int extractionAmount, int specialAmount)
		{
			generator.ModuleAmount = moduleAmount;
			if (DeadEndAmountRef != null && ExtractionAmountRef != null && SpecialAmountRef != null)
			{
				DeadEndAmountRef.Invoke(generator) = deadEndAmount;
				ExtractionAmountRef.Invoke(generator) = extractionAmount;
				SpecialAmountRef.Invoke(generator) = specialAmount;
			}
		}

		private static Tile[,] AllocateModeGrid(LevelGenerator generator, int levelWidth, int levelHeight)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			Tile[,] array = new Tile[levelWidth, levelHeight];
			for (int i = 0; i < levelWidth; i++)
			{
				for (int j = 0; j < levelHeight; j++)
				{
					Tile val = new Tile();
					val.x = i;
					val.y = j;
					val.active = false;
					array[i, j] = val;
				}
			}
			LevelGridRef.Invoke(generator) = array;
			return array;
		}

		private static Tile ModeGridGetTile(Tile[,] levelGrid, int x, int y)
		{
			if (levelGrid == null)
			{
				return null;
			}
			if (x < 0 || y < 0 || x >= levelGrid.GetLength(0) || y >= levelGrid.GetLength(1))
			{
				return null;
			}
			return levelGrid[x, y];
		}

		private static void ModeSetExtractionTile(SVMapPlan plan, Tile[,] levelGrid, Type _type, Tile _tile, List<Tile> _extractionTiles, List<Tile> _possibleExtractionTiles)
		{
			//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)
			_tile.type = _type;
			_tile.active = true;
			_extractionTiles.Add(_tile);
			_possibleExtractionTiles.Remove(_tile);
			bool flag = false;
			while (!flag)
			{
				flag = true;
				for (int i = 0; i < _possibleExtractionTiles.Count; i++)
				{
					Tile val = _possibleExtractionTiles[i];
					if (ModeGridGetTile(levelGrid, val.x, val.y - 1) == _tile || ModeGridGetTile(levelGrid, val.x + 1, val.y) == _tile || ModeGridGetTile(levelGrid, val.x, val.y + 1) == _tile || ModeGridGetTile(levelGrid, val.x - 1, val.y) == _tile)
					{
						_possibleExtractionTiles.Remove(val);
						flag = false;
						break;
					}
				}
			}
			if (plan == null || plan.ZoneCells == null)
			{
				return;
			}
			int num = -1;
			int[] array = new int[4] { 0, 1, 0, -1 };
			int[] array2 = new int[4] { 1, 0, -1, 0 };
			for (int j = 0; j < array.Length; j++)
			{
				Tile val2 = ModeGridGetTile(levelGrid, _tile.x + array[j], _tile.y + array2[j]);
				if (val2 != null && val2.active)
				{
					num = plan.GetZone(_tile.x + array[j], _tile.y + array2[j]);
					if (num == -2)
					{
						num = -1;
					}
					break;
				}
			}
			if (num < 0)
			{
				num = -1;
			}
			plan.SetZone(_tile.x, _tile.y, num);
		}

		private static bool VanillaPassageTopologyHolds(LevelGenerator generator, Tile[,] levelGrid, int x, int y)
		{
			bool result = false;
			if (!((Object)(object)generator == (Object)null) && levelGrid != null && x >= 0 && y >= 0 && x < generator.LevelWidth && y < generator.LevelHeight)
			{
				bool flag = levelGrid[x, y] != null && levelGrid[x, y].first;
				bool num = GridCheckActive(generator, levelGrid, x, y + 1) && (GridCheckActive(generator, levelGrid, x, y - 1) || flag) && !GridCheckActive(generator, levelGrid, x + 1, y) && !GridCheckActive(generator, levelGrid, x - 1, y);
				bool flag2 = !flag && GridCheckActive(generator, levelGrid, x + 1, y) && GridCheckActive(generator, levelGrid, x - 1, y) && !GridCheckActive(generator, levelGrid, x, y + 1) && !GridCheckActive(generator, levelGrid, x, y - 1);
				result = num || flag2;
			}
			return result;
		}

		private static void StripItemSpawnSpots(GameObject roomObject)
		{
			if ((Object)(object)roomObject == (Object)null)
			{
				return;
			}
			ValuableVolume[] componentsInChildren = roomObject.GetComponentsInChildren<ValuableVolume>(true);
			int num = 0;
			if (componentsInChildren != null)
			{
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					Object.Destroy((Object)(object)componentsInChildren[i]);
					num++;
				}
			}
			ItemVolume[] componentsInChildren2 = roomObject.GetComponentsInChildren<ItemVolume>(true);
			int num2 = 0;
			if (componentsInChildren2 != null)
			{
				for (int j = 0; j < componentsInChildren2.Length; j++)
				{
					Object.Destroy((Object)(object)componentsInChildren2[j]);
					num2++;
				}
			}
			if (DebugLog != null && DebugLog.Value && LogSource != null && (num > 0 || num2 > 0))
			{
				LogSource.LogInfo((object)("[SilentVanilla] Maps: connector emptied (valuable spots removed: " + num + ", item spots removed: " + num2 + ")"));
			}
		}

		private static string NormalizeRoomName(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return string.Empty;
			}
			return text.ToLowerInvariant().Replace('_', ' ').Replace('-', ' ')
				.Replace('.', ' ')
				.Replace(',', ' ')
				.Trim();
		}

		private static bool MatchesCuratedRoomName(string resourcePath, string curatedName)
		{
			if (string.IsNullOrEmpty(resourcePath) || string.IsNullOrEmpty(curatedName))
			{
				return false;
			}
			string text = NormalizeRoomName(resourcePath);
			string text2 = NormalizeRoomName(curatedName);
			if (text.Contains(text2))
			{
				return true;
			}
			return text.Replace(" ", string.Empty).Contains(text2.Replace(" ", string.Empty));
		}

		private static void FillCuratedCategoryPool(CategoryPool pool, Level sourceLevel, List<PrefabRef> sourceList, string[] curatedNames)
		{
			if (pool == null || (Object)(object)sourceLevel == (Object)null || sourceList == null)
			{
				return;
			}
			for (int i = 0; i < sourceList.Count; i++)
			{
				PrefabRef val = sourceList[i];
				if (!IsValidPrefabRef(val) || ((PrefabRef<GameObject>)(object)val).ResourcePath == null)
				{
					continue;
				}
				if (curatedNames != null)
				{
					bool flag = false;
					for (int j = 0; j < curatedNames.Length; j++)
					{
						if (MatchesCuratedRoomName(((PrefabRef<GameObject>)(object)val).ResourcePath, curatedNames[j]))
						{
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						continue;
					}
				}
				pool.Add(new RoomEntry(val, sourceLevel));
			}
		}

		private static bool IsStairsKeywordRoom(string resourcePath)
		{
			if (string.IsNullOrEmpty(resourcePath))
			{
				return false;
			}
			string text = NormalizeRoomName(resourcePath);
			if (text.Length == 0)
			{
				return false;
			}
			string[] array = text.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				if (StairsKeywordTokens.Contains(array[i]))
				{
					return true;
				}
			}
			return false;
		}

		private static int AddStairsKeywordRooms(MergedPools pools, List<Level> sources)
		{
			int num = 0;
			for (int i = 0; i < sources.Count; i++)
			{
				Level val = sources[i];
				if (!((Object)(object)val == (Object)null) && !IsAlwaysExcludedLevel(val))
				{
					num += AddStairsKeywordCategory(pools.NormalRooms, val, val.ModulesNormal1);
					num += AddStairsKeywordCategory(pools.NormalRooms, val, val.ModulesNormal2);
					num += AddStairsKeywordCategory(pools.NormalRooms, val, val.ModulesNormal3);
					num += AddStairsKeywordCategory(pools.PassageRooms, val, val.ModulesPassage1);
					num += AddStairsKeywordCategory(pools.PassageRooms, val, val.ModulesPassage2);
					num += AddStairsKeywordCategory(pools.PassageRooms, val, val.ModulesPassage3);
					num += AddStairsKeywordCategory(pools.DeadEndRooms, val, val.ModulesDeadEnd1);
					num += AddStairsKeywordCategory(pools.DeadEndRooms, val, val.ModulesDeadEnd2);
					num += AddStairsKeywordCategory(pools.DeadEndRooms, val, val.ModulesDeadEnd3);
					num += AddStairsKeywordCategory(pools.ExtractionRooms, val, val.ModulesExtraction1);
					num += AddStairsKeywordCategory(pools.ExtractionRooms, val, val.ModulesExtraction2);
					num += AddStairsKeywordCategory(pools.ExtractionRooms, val, val.ModulesExtraction3);
				}
			}
			return num;
		}

		private static int AddStairsKeywordCategory(CategoryPool pool, Level sourceLevel, List<PrefabRef> sourceList)
		{
			if (pool == null || (Object)(object)sourceLevel == (Object)null || sourceList == null)
			{
				return 0;
			}
			int num = 0;
			for (int i = 0; i < sourceList.Count; i++)
			{
				PrefabRef val = sourceList[i];
				if (IsValidPrefabRef(val) && ((PrefabRef<GameObject>)(object)val).ResourcePath != null && IsStairsKeywordRoom(((PrefabRef<GameObject>)(object)val).ResourcePath) && !pool.ContainsResourcePath(((PrefabRef<GameObject>)(object)val).ResourcePath))
				{
					pool.Add(new RoomEntry(val, sourceLevel));
					num++;
				}
			}
			return num;
		}

		private static void FillCuratedPoolFromLevels(MergedPools pools, List<Level> sources, string[] normalNames, string[] passageNames, string[] deadEndNames, string[] extractionNames)
		{
			HashSet<string> excludedPaths = ParseExcludedPaths();
			for (int i = 0; i < sources.Count; i++)
			{
				Level val = sources[i];
				if (!((Object)(object)val == (Object)null) && !IsAlwaysExcludedLevel(val))
				{
					pools.SourceLevels.Add(val);
					FillCuratedCategoryPool(pools.NormalRooms, val, val.ModulesNormal1, normalNames);
					FillCuratedCategoryPool(pools.NormalRooms, val, val.ModulesNormal2, normalNames);
					FillCuratedCategoryPool(pools.NormalRooms, val, val.ModulesNormal3, normalNames);
					FillCuratedCategoryPool(pools.PassageRooms, val, val.ModulesPassage1, passageNames);
					FillCuratedCategoryPool(pools.PassageRooms, val, val.ModulesPassage2, passageNames);
					FillCuratedCategoryPool(pools.PassageRooms, val, val.ModulesPassage3, passageNames);
					FillCuratedCategoryPool(pools.DeadEndRooms, val, val.ModulesDeadEnd1, deadEndNames);
					FillCuratedCategoryPool(pools.DeadEndRooms, val, val.ModulesDeadEnd2, deadEndNames);
					FillCuratedCategoryPool(pools.DeadEndRooms, val, val.ModulesDeadEnd3, deadEndNames);
					FillCuratedCategoryPool(pools.ExtractionRooms, val, val.ModulesExtraction1, extractionNames);
					FillCuratedCategoryPool(pools.ExtractionRooms, val, val.ModulesExtraction2, extractionNames);
					FillCuratedCategoryPool(pools.ExtractionRooms, val, val.ModulesExtraction3, extractionNames);
					AddListToCategoryPool(pools.StartRooms, val, val.StartRooms, excludedPaths, allowDuplicatePaths: false);
				}
			}
		}

		private static MergedPools BuildCuratedPools(SVMapMode mode, Level baseLevel)
		{
			string[] array = null;
			string[] array2 = null;
			string[] array3 = null;
			string[] array4 = null;
			string text = "curated";
			switch (mode)
			{
			case SVMapMode.Districts:
				array = DistrictsNormalRooms;
				text = "districts";
				break;
			case SVMapMode.LongRun:
				array = LongRunNormalRooms;
				array3 = LongRunDeadEndRooms;
				text = "long run";
				break;
			case SVMapMode.Stairs:
				array = StairsNormalRooms;
				array2 = StairsPassageRooms;
				array3 = StairsDeadEndRooms;
				array4 = StairsExtractionRooms;
				text = "stairs & holes";
				break;
			}
			MergedPools mergedPools = new MergedPools();
			if ((Object)(object)RunManager.instance == (Object)null || RunManager.instance.levels == null)
			{
				return null;
			}
			List<Level> sources = CollectSourceLevels(baseLevel);
			FillCuratedPoolFromLevels(mergedPools, sources, array, array2, array3, array4);
			if (mode == SVMapMode.Stairs)
			{
				int num = AddStairsKeywordRooms(mergedPools, sources);
				if (num > 0)
				{
					LogSource.LogInfo((object)("[SVMaps][stairs & holes] keyword sweep added " + num + " rooms from newer maps."));
				}
			}
			MergedPools mergedPools2 = BuildMergedPools(baseLevel);
			if (array != null && mergedPools.NormalRooms.Entries.Count == 0)
			{
				CopyCategoryEntries(mergedPools2.NormalRooms, mergedPools.NormalRooms);
				LogSource.LogWarning((object)("[SVMaps][" + text + "] no curated normal rooms matched; falling back to the full merged normal pool."));
			}
			if (array2 != null && mergedPools.PassageRooms.Entries.Count == 0)
			{
				CopyCategoryEntries(mergedPools2.PassageRooms, mergedPools.PassageRooms);
				LogSource.LogWarning((object)("[SVMaps][" + text + "] no curated passage rooms matched; falling back to the full merged passage pool."));
			}
			if (array3 != null && mergedPools.DeadEndRooms.Entries.Count == 0)
			{
				CopyCategoryEntries(mergedPools2.DeadEndRooms, mergedPools.DeadEndRooms);
				LogSource.LogWarning((object)("[SVMaps][" + text + "] no curated dead-end rooms matched; falling back to the full merged dead-end pool."));
			}
			if (array4 != null && mergedPools.ExtractionRooms.Entries.Count == 0)
			{
				CopyCategoryEntries(mergedPools2.ExtractionRooms, mergedPools.ExtractionRooms);
				LogSource.LogWarning((object)("[SVMaps][" + text + "] no curated extraction rooms matched; falling back to the full merged extraction pool."));
			}
			return mergedPools;
		}

		private static void CopyCategoryEntries(CategoryPool fromPool, CategoryPool toPool)
		{
			if (fromPool == null || toPool == null || fromPool.Entries == null)
			{
				return;
			}
			for (int i = 0; i < fromPool.Entries.Count; i++)
			{
				RoomEntry roomEntry = fromPool.Entries[i];
				if (roomEntry != null && roomEntry.PrefabRef != null && !toPool.ContainsResourcePath(((PrefabRef<GameObject>)(object)roomEntry.PrefabRef).ResourcePath))
				{
					toPool.Add(roomEntry);
				}
			}
		}

		private static MergedPools BuildSessionPools(Level level)
		{
			SVMapMode modeForLevel = GetModeForLevel(level);
			if (modeForLevel == SVMapMode.Districts || modeForLevel == SVMapMode.LongRun || modeForLevel == SVMapMode.Stairs)
			{
				MergedPools mergedPools = BuildCuratedPools(modeForLevel, level);
				if (mergedPools != null)
				{
					return mergedPools;
				}
			}
			return BuildMergedPools(level);
		}

		private static MergedPools ResolveStartRoomPools(LevelGenerator generator, Level level)
		{
			MergedPools result = BuildSessionPools(level);
			SVMapPlan planForGenerator = GetPlanForGenerator(generator);
			if (planForGenerator != null && planForGenerator.ZoneCount > 0)
			{
				MergedPools zonePools = planForGenerator.GetZonePools(0);
				if (zonePools != null && zonePools.StartRooms.UniqueCount > 0)
				{
					result = zonePools;
				}
			}
			return result;
		}

		internal static IEnumerator TileGenerationOverride(LevelGenerator generator)
		{
			SetWaitingForSubCoroutine(generator, value: true);
			try
			{
				if (!((Object)(object)generator == (Object)null) && !((Object)(object)generator.Level == (Object)null))
				{
					generator.State = (LevelState)2;
					Level level = generator.Level;
					SVMapMode modeForLevel = GetModeForLevel(level);
					int deadEndAmount;
					int extractionAmount;
					int specialAmount;
					int num = ComputeVanillaModuleAmounts(generator, out deadEndAmount, out extractionAmount, out specialAmount);
					EscalateModuleBudget(generator, modeForLevel, ref num, ref deadEndAmount, ref extractionAmount, ref specialAmount);
					bool flag = modeForLevel == SVMapMode.LongRun;
					bool flag2 = modeForLevel == SVMapMode.Districts;
					SVMapPlan plan = new SVMapPlan
					{
						Generator = generator,
						Level = level,
						OptimizeAllowed = true
					};
					int levelWidth = Mathf.Max(2, Mathf.CeilToInt((float)generator.LevelWidth * generator.DebugLevelSize));
					int levelHeight = Mathf.Max(2, Mathf.CeilToInt((float)generator.LevelHeight * generator.DebugLevelSize));
					Tile[,] levelGrid;
					if (flag)
					{
						bool flag3 = false;
						if (0 == 0)
						{
							deadEndAmount = 0;
						}
						if (!flag3)
						{
							specialAmount = 0;
						}
						levelWidth = Mathf.Max(3, levelWidth);
						levelHeight = Mathf.Max(levelHeight, num + 2);
						generator.LevelWidth = levelWidth;
						generator.LevelHeight = levelHeight;
						Tile[,] array = AllocateModeGrid(generator, levelWidth, levelHeight);
						levelGrid = array;
						int num2 = levelWidth / 2;
						array[num2, 0].active = true;
						array[num2, 0].first = true;
						for (int i = 1; i < num; i++)
						{
							array[num2, i].active = true;
						}
					}
					else
					{
						int num3 = 2;
						List<Level> list = CollectSourceLevels(level);
						ListExtension.Shuffle<Level>((IList<Level>)list);
						int num4 = ((!flag2) ? 1 : list.Count);
						bool flag4 = num < 4 || num4 < 2;
						while (!flag4 && num3 > 0 && num < num4 + num3 * (num4 - 1))
						{
							num3--;
						}
						if (num3 <= 0)
						{
							flag4 = true;
						}
						int num5 = 0;
						int num6;
						if (!flag4)
						{
							num6 = num3 * (num4 - 1);
							num5 = num - num6;
							if (num5 < num4)
							{
								flag4 = true;
							}
						}
						else
						{
							num6 = 0;
						}
						levelHeight = Mathf.Max(levelHeight, Mathf.CeilToInt((float)num / 2f) + 2);
						levelWidth = (generator.LevelWidth = Mathf.Max(levelWidth, Mathf.CeilToInt((float)num / 3f) + 2));
						generator.LevelHeight = levelHeight;
						Tile[,] array2 = AllocateModeGrid(generator, levelWidth, levelHeight);
						levelGrid = array2;
						int num7 = levelWidth / 2;
						array2[num7, 0].active = true;
						array2[num7, 0].first = true;
						int num8 = num - 1;
						int num9 = 0;
						int num10 = 1;
						int[] array3 = null;
						if (!flag4)
						{
							plan.ZoneSources = list.GetRange(0, num4);
							plan.ZoneCells = new int[levelWidth, levelHeight];
							for (int j = 0; j < levelWidth; j++)
							{
								for (int k = 0; k < levelHeight; k++)
								{
									plan.ZoneCells[j, k] = -2;
								}
							}
							plan.ZoneCells[num7, 0] = 0;
							plan.ForcedPassage = new bool[levelWidth, levelHeight];
							plan.ItemFreeCells = new bool[levelWidth, levelHeight];
							plan.ItemFreeCells = new bool[levelWidth, levelHeight];
							plan.OptimizeAllowed = false;
							int num11 = num5 / num4;
							int num12 = num5 - num11 * num4;
							array3 = new int[num4];
							for (int l = 0; l < num4; l++)
							{
								array3[l] = num11 + ((l < num12) ? 1 : 0);
							}
						}
						int num13 = num7;
						int num14 = 0;
						int num15 = ((!flag4) ? num6 : 0);
						while (num8 > 0)
						{
							if (!flag4 && num9 < num4 - 1 && num10 >= array3[num9] && num15 >= num3)
							{
								bool flag5 = false;
								int num16 = 0;
								int num17 = 0;
								for (int m = 0; m < 24; m++)
								{
									if (flag5)
									{
										break;
									}
									switch (Random.Range(0, 4))
									{
									case 0:
										num16 = -1;
										break;
									case 1:
										num16 = 1;
										break;
									case 2:
										num17 = 1;
										break;
									default:
										num17 = -1;
										break;
									}
									int num18 = num13;
									int num19 = num14;
									bool flag6 = true;
									for (int n = 0; n < num3; n++)
									{
										num18 += num16;
										num19 += num17;
										if (num18 < 0 || num18 >= levelWidth || num19 < 0 || num19 >= levelHeight || array2[num18, num19].active)
										{
											flag6 = false;
											break;
										}
									}
									if (flag6)
									{
										for (int num20 = 0; num20 < num3; num20++)
										{
											num13 += num16;
											num14 += num17;
											array2[num13, num14].active = true;
											plan.ZoneCells[num13, num14] = -1;
											plan.ItemFreeCells[num13, num14] = true;
											plan.ForcedPassage[num13, num14] = true;
											num8--;
										}
										flag5 = true;
									}
								}
								if (flag5)
								{
									num9++;
									num10 = 0;
									num15 -= num3;
									int num21 = num13 + num16;
									int num22 = num14 + num17;
									if (num8 > 0 && num21 >= 0 && num21 < levelWidth && num22 >= 0 && num22 < levelHeight && !array2[num21, num22].active)
									{
										num13 = num21;
										num14 = num22;
										array2[num13, num14].active = true;
										plan.ZoneCells[num13, num14] = num9;
										num10++;
										num8--;
									}
									continue;
								}
							}
							int num23 = -999;
							int num24 = -999;
							while (num13 + num23 < 0 || num13 + num23 >= levelWidth || num14 + num24 < 0 || num14 + num24 >= levelHeight)
							{
								num23 = 0;
								num24 = 0;
								int num25 = Random.Range(0, 4);
								if (num14 == 1)
								{
									num25 = Random.Range(0, 3);
								}
								switch (num25)
								{
								case 0:
									num23--;
									break;
								case 1:
									num23++;
									break;
								case 2:
									num24++;
									break;
								default:
									num24--;
									break;
								}
							}
							num13 += num23;
							num14 += num24;
							if (!array2[num13, num14].active)
							{
								array2[num13, num14].active = true;
								if (!flag4)
								{
									plan.ZoneCells[num13, num14] = num9;
								}
								num10++;
								num8--;
							}
						}
						if (DebugLog != null && DebugLog.Value && LogSource != null && !flag4)
						{
							LogSource.LogInfo((object)("[SilentVanilla] Maps: districts planned (zones=" + num4 + ", connector = 2 hallways)"));
						}
					}
					ActivePlan = plan;
					yield return null;
					List<Tile> possibleExtractionTiles = new List<Tile>();
					for (int num26 = 0; num26 < levelWidth; num26++)
					{
						for (int num27 = 0; num27 < levelHeight; num27++)
						{
							if (!levelGrid[num26, num27].active)
							{
								int num28 = 0;
								Tile val = ModeGridGetTile(levelGrid, num26, num27 + 1);
								if (val != null && val.active)
								{
									num28++;
								}
								Tile val2 = ModeGridGetTile(levelGrid, num26 + 1, num27);
								if (val2 != null && val2.active)
								{
									num28++;
								}
								Tile val3 = ModeGridGetTile(levelGrid, num26, num27 - 1);
								if (val3 != null && val3.active)
								{
									num28++;
								}
								Tile val4 = ModeGridGetTile(levelGrid, num26 - 1, num27);
								if (val4 != null && val4.active)
								{
									num28++;
								}
								if (num28 == 1)
								{
									possibleExtractionTiles.Add(levelGrid[num26, num27]);
								}
							}
						}
					}
					yield return null;
					int num29 = extractionAmount;
					Tile val5 = new Tile();
					val5.x = levelWidth / 2;
					val5.y = -1;
					List<Tile> extractionTiles = new List<Tile> { val5 };
					if (flag)
					{
						int num30 = levelWidth / 2;
						int num31 = num29;
						int num32 = Mathf.Min(5, num / 3);
						int num33 = Mathf.Min(3, num / 4);
						if (num - num32 - num33 < num31)
						{
							num32 = 1;
							num33 = 1;
						}
						int num34 = num - num32 - num33;
						for (int num35 = 1; num35 <= num31; num35++)
						{
							int y = num32 + Mathf.Clamp(Mathf.RoundToInt(((float)num35 - 0.5f) * (float)(num34 + 1) / (float)num31), 0, num34);
							Tile val6 = ModeGridGetTile(levelGrid, (num35 % 2 == 1) ? (num30 - 1) : (num30 + 1), y);
							if (val6 != null && !val6.active)
							{
								ModeSetExtractionTile(plan, levelGrid, (Type)3, val6, extractionTiles, possibleExtractionTiles);
							}
						}
					}
					else
					{
						while (num29 > 0 && possibleExtractionTiles.Count > 0)
						{
							Tile tile = null;
							float num36 = 0f;
							foreach (Tile item in possibleExtractionTiles)
							{
								float num37 = 9999999f;
								foreach (Tile item2 in extractionTiles)
								{
									float num38 = Vector2.Distance(new Vector2((float)item2.x, (float)item2.y), new Vector2((float)item.x, (float)item.y));
									if (num38 < num37)
									{
										num37 = num38;
									}
								}
								if (num37 > num36)
								{
									num36 = num37;
									tile = item;
								}
							}
							ModeSetExtractionTile(plan, levelGrid, (Type)3, tile, extractionTiles, possibleExtractionTiles);
							num29--;
						}
					}
					yield return null;
					int num39 = specialAmount;
					while (num39 > 0 && possibleExtractionTiles.Count > 0)
					{
						Tile tile2 = possibleExtractionTiles[Random.Range(0, possibleExtractionTiles.Count)];
						ModeSetExtractionTile(plan, levelGrid, (Type)4, tile2, extractionTiles, possibleExtractionTiles);
						num39--;
					}
					yield return null;
					int num40 = deadEndAmount;
					while (num40 > 0 && possibleExtractionTiles.Count > 0)
					{
						Tile tile3 = possibleExtractionTiles[Random.Range(0, possibleExtractionTiles.Count)];
						ModeSetExtractionTile(plan, levelGrid, (Type)2, tile3, extractionTiles, possibleExtractionTiles);
						num40--;
					}
					yield return null;
				}
				else
				{
					yield return null;
				}
			}
			finally
			{
				SetWaitingForSubCoroutine(generator, value: false);
			}
		}

		internal static IEnumerator StartRoomGenerationOverride(LevelGenerator generator)
		{
			SetWaitingForSubCoroutine(generator, value: true);
			try
			{
				if (!((Object)(object)generator == (Object)null) && !((Object)(object)generator.Level == (Object)null))
				{
					generator.State = (LevelState)3;
					Level level = generator.Level;
					MergedPools mergedPools = ResolveStartRoomPools(generator, level);
					RoomEntry roomEntry = null;
					PrefabRef debugStartRoom = GetDebugStartRoom(generator);
					if (IsValidPrefabRef(debugStartRoom))
					{
						roomEntry = new RoomEntry(debugStartRoom, level);
					}
					else
					{
						CategoryPool categoryPool = BuildCurrentLevelStartPool(level);
						if (mergedPools != null && mergedPools.StartRooms != null && mergedPools.StartRooms.Entries.Count > 0)
						{
							categoryPool = mergedPools.StartRooms;
						}
						if ((categoryPool == null || categoryPool.Entries.Count <= 0) && mergedPools != null && mergedPools.NormalRooms != null && mergedPools.NormalRooms.Entries.Count > 0)
						{
							categoryPool = mergedPools.NormalRooms;
						}
						if (categoryPool != null && categoryPool.Entries.Count > 0)
						{
							roomEntry = categoryPool.ChoosePreferDifferentSource(new HashSet<Level>(), new CategoryUsage(), null);
						}
					}
					PrefabRef val = roomEntry?.PrefabRef;
					if (!IsValidPrefabRef(val) && level.StartRooms != null && level.StartRooms.Count > 0)
					{
						List<PrefabRef> list = new List<PrefabRef>(level.StartRooms);
						ListExtension.Shuffle<PrefabRef>((IList<PrefabRef>)list);
						val = list[0];
					}
					if (IsValidPrefabRef(val))
					{
						GameObject val2 = SpawnRoomObject(val, Vector3.zero, Quaternion.identity);
						if ((Object)(object)val2 != (Object)null && (Object)(object)generator.LevelParent != (Object)null)
						{
							val2.transform.parent = generator.LevelParent.transform;
						}
						if (LogSource != null && DebugLog != null && DebugLog.Value)
						{
							LogSource.LogInfo((object)("Merged start room: " + ((PrefabRef<GameObject>)(object)val).ResourcePath + " / SourceLevel=" + SafeLevelName(roomEntry?.SourceLevel)));
						}
					}
					yield return null;
				}
				else
				{
					yield return null;
				}
			}
			finally
			{
				SetWaitingForSubCoroutine(generator, value: false);
			}
		}

		internal static IEnumerator ModuleGenerationOverride(LevelGenerator generator)
		{
			SetWaitingForSubCoroutine(generator, value: true);
			try
			{
				if (!((Object)(object)generator == (Object)null) && !((Object)(object)generator.Level == (Object)null))
				{
					generator.State = (LevelState)4;
					Level level = generator.Level;
					Tile[,] levelGrid = ((LevelGridRef != null) ? LevelGridRef.Invoke(generator) : null);
					int levelWidth = generator.LevelWidth;
					int levelHeight = generator.LevelHeight;
					PrefabRef debugModule = GetDebugModule(generator);
					bool debugForced = IsValidPrefabRef(debugModule);
					SVMapPlan plan = GetPlanForGenerator(generator);
					MergedPools pools = BuildSessionPools(level);
					bool flag = pools != null && pools.NormalRooms != null && pools.NormalRooms.Entries.Count > 0;
					if (levelGrid == null || levelWidth <= 0 || levelHeight <= 0 || (!debugForced && !flag))
					{
						yield break;
					}
					CategoryUsage normalUsage = new CategoryUsage();
					CategoryUsage passageUsage = new CategoryUsage();
					CategoryUsage deadEndUsage = new CategoryUsage();
					CategoryUsage extractionUsage = new CategoryUsage();
					CategoryUsage specialUsage = new CategoryUsage();
					RoomEntry[,] plannedEntries = new RoomEntry[levelWidth, levelHeight];
					Type[,] plannedTypes = new Type[levelWidth, levelHeight];
					for (int x = 0; x < levelWidth; x++)
					{
						for (int y = 0; y < levelHeight; y++)
						{
							Tile val = levelGrid[x, y];
							if (val == null || !val.active)
							{
								continue;
							}
							Type val2 = ResolveTargetModuleType(generator, levelGrid, x, y);
							if (plan != null && (int)val2 == 0 && plan.IsForcedPassage(generator, levelGrid, x, y))
							{
								val2 = (Type)1;
							}
							plannedTypes[x, y] = val2;
							RoomEntry roomEntry;
							if (debugForced)
							{
								roomEntry = new RoomEntry(debugModule, level);
							}
							else
							{
								MergedPools pools2 = pools;
								CategoryUsage usage = GetUsageForType(val2, normalUsage, passageUsage, deadEndUsage, extractionUsage, specialUsage);
								if (plan != null && plan.ZoneCells != null)
								{
									int zone = plan.GetZone(x, y);
									MergedPools mergedPools = ((zone >= 0) ? plan.GetZonePools(zone) : null);
									bool flag2 = false;
									if (mergedPools != null)
									{
										CategoryPool poolForType = GetPoolForType(mergedPools, val2);
										flag2 = poolForType != null && poolForType.Entries != null && poolForType.Entries.Count > 0;
									}
									if (flag2)
									{
										pools2 = mergedPools;
										usage = plan.GetUsage(val2, zone);
									}
								}
								roomEntry = ChooseRoomEntry(GetPoolForType(pools2, val2), pools2, val2, null, usage);
							}
							plannedEntries[x, y] = roomEntry;
							yield return null;
						}
					}
					yield return null;
					if (!debugForced && (plan == null || plan.OptimizeAllowed))
					{
						OptimizePlannedEntries(levelGrid, plannedEntries, plannedTypes, pools, levelWidth, levelHeight);
					}
					yield return null;
					Vector3 position = default(Vector3);
					for (int x = 0; x < levelWidth; x++)
					{
						for (int y = 0; y < levelHeight; y++)
						{
							Tile val3 = levelGrid[x, y];
							if (val3 != null && val3.active)
							{
								yield return null;
								float num = LevelGenerator.ModuleWidth * LevelGenerator.TileSize;
								((Vector3)(ref position))..ctor((float)x * num - (float)(levelWidth / 2) * num, 0f, (float)y * num + num / 2f);
								Vector3 rotation = ResolveRotation(generator, levelGrid, x, y, plannedTypes[x, y]);
								GameObject val4 = SpawnMergedModule(generator, levelGrid, x, y, position, rotation, plannedTypes[x, y], plannedEntries[x, y]);
								if ((Object)(object)val4 != (Object)null && plan != null && plan.IsItemFree(x, y))
								{
									StripItemSpawnSpots(val4);
								}
							}
						}
					}
					yield return null;
				}
				else
				{
					yield return null;
				}
			}
			finally
			{
				SetWaitingForSubCoroutine(generator, value: false);
			}
		}

		private static void SetWaitingForSubCoroutine(LevelGenerator generator, bool value)
		{
			if (!((Object)(object)generator == (Object)null) && WaitingForSubCoroutineRef != null)
			{
				WaitingForSubCoroutineRef.Invoke(generator) = value;
			}
		}

		private static PrefabRef GetDebugStartRoom(LevelGenerator generator)
		{
			if ((Object)(object)generator == (Object)null || DebugStartRoomRef == null)
			{
				return null;
			}
			return DebugStartRoomRef.Invoke(generator);
		}

		private static PrefabRef GetDebugModule(LevelGenerator generator)
		{
			if ((Object)(object)generator == (Object)null || DebugModuleRef == null)
			{
				return null;
			}
			return DebugModuleRef.Invoke(generator);
		}

		private static bool GetDebugNormal(LevelGenerator generator)
		{
			if ((Object)(object)generator != (Object)null && DebugNormalRef != null)
			{
				return DebugNormalRef.Invoke(generator);
			}
			return false;
		}

		private static bool GetDebugPassage(LevelGenerator generator)
		{
			if ((Object)(object)generator != (Object)null && DebugPassageRef != null)
			{
				return DebugPassageRef.Invoke(generator);
			}
			return false;
		}

		private static bool GetDebugDeadEnd(LevelGenerator generator)
		{
			if ((Object)(object)generator != (Object)null && DebugDeadEndRef != null)
			{
				return DebugDeadEndRef.Invoke(generator);
			}
			return false;
		}

		private static void OptimizePlannedEntries(Tile[,] levelGrid, RoomEntry[,] plannedEntries, Type[,] plannedTypes, MergedPools pools, int width, int height)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			int num = 2;
			if (num <= 0)
			{
				return;
			}
			for (int i = 0; i < num; i++)
			{
				bool flag = false;
				for (int j = 0; j < width; j++)
				{
					for (int k = 0; k < height; k++)
					{
						Tile val = levelGrid[j, k];
						if (val == null || !val.active)
						{
							continue;
						}
						RoomEntry roomEntry = plannedEntries[j, k];
						if (roomEntry == null)
						{
							continue;
						}
						HashSet<Level> hashSet = CollectAdjacentSourceLevels(plannedEntries, width, height, j, k);
						if (hashSet.Count > 0 && (!((Object)(object)roomEntry.SourceLevel != (Object)null) || hashSet.Contains(roomEntry.SourceLevel)))
						{
							RoomEntry roomEntry2 = GetPoolForType(pools, plannedTypes[j, k])?.ChoosePreferDifferentSource(hashSet, null, roomEntry);
							if (roomEntry2 != null && IsValidPrefabRef(roomEntry2.PrefabRef) && roomEntry2 != roomEntry && !((Object)(object)roomEntry2.SourceLevel == (Object)(object)roomEntry.SourceLevel))
							{
								plannedEntries[j, k] = roomEntry2;
								flag = true;
							}
						}
					}
				}
				if (!flag)
				{
					break;
				}
			}
		}

		private static HashSet<Level> CollectAdjacentSourceLevels(RoomEntry[,] plannedEntries, int width, int height, int x, int y)
		{
			HashSet<Level> result = new HashSet<Level>();
			AddPlannedNeighborSourceLevel(plannedEntries, width, height, x, y - 1, result);
			AddPlannedNeighborSourceLevel(plannedEntries, width, height, x - 1, y, result);
			AddPlannedNeighborSourceLevel(plannedEntries, width, height, x + 1, y, result);
			AddPlannedNeighborSourceLevel(plannedEntries, width, height, x, y + 1, result);
			return result;
		}

		private static void AddPlannedNeighborSourceLevel(RoomEntry[,] plannedEntries, int width, int height, int x, int y, HashSet<Level> result)
		{
			if (plannedEntries != null && result != null && x >= 0 && x < width && y >= 0 && y < height)
			{
				RoomEntry roomEntry = plannedEntries[x, y];
				if (roomEntry != null && !((Object)(object)roomEntry.SourceLevel == (Object)null))
				{
					result.Add(roomEntry.SourceLevel);
				}
			}
		}

		private static CategoryPool GetPoolForType(MergedPools pools, Type targetType)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected I4, but got Unknown
			if (pools == null)
			{
				return null;
			}
			return (targetType - 1) switch
			{
				0 => pools.PassageRooms, 
				1 => pools.DeadEndRooms, 
				2 => pools.ExtractionRooms, 
				3 => pools.SpecialRooms, 
				_ => pools.NormalRooms, 
			};
		}

		private static CategoryUsage GetUsageForType(Type targetType, CategoryUsage normalUsage, CategoryUsage passageUsage, CategoryUsage deadEndUsage, CategoryUsage extractionUsage, CategoryUsage specialUsage)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected I4, but got Unknown
			return (targetType - 1) switch
			{
				0 => passageUsage, 
				1 => deadEndUsage, 
				2 => extractionUsage, 
				3 => specialUsage, 
				_ => normalUsage, 
			};
		}

		private static Type ResolveTargetModuleType(LevelGenerator generator, Tile[,] levelGrid, int x, int y)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Invalid comparison between Unknown and I4
			Tile val = levelGrid[x, y];
			if (val != null)
			{
				if (!GetDebugNormal(generator) && !GetDebugPassage(generator) && !GetDebugDeadEnd(generator))
				{
					if ((int)val.type == 3)
					{
						return (Type)3;
					}
					if ((int)val.type == 2)
					{
						return (Type)2;
					}
					if ((int)val.type == 4)
					{
						return (Type)4;
					}
				}
				if (!GetDebugDeadEnd(generator))
				{
					if (!GetDebugNormal(generator) && (GetDebugPassage(generator) || PassageAmountRef.Invoke(generator) < generator.Level.PassageMaxAmount))
					{
						bool num = GetDebugPassage(generator) || (GridCheckActive(generator, levelGrid, x, y + 1) && (GridCheckActive(generator, levelGrid, x, y - 1) || val.first) && !GridCheckActive(generator, levelGrid, x + 1, y) && !GridCheckActive(generator, levelGrid, x - 1, y));
						bool flag = !val.first && GridCheckActive(generator, levelGrid, x + 1, y) && GridCheckActive(generator, levelGrid, x - 1, y) && !GridCheckActive(generator, levelGrid, x, y + 1) && !GridCheckActive(generator, levelGrid, x, y - 1);
						if (num || flag)
						{
							PassageAmountRef.Invoke(generator)++;
							return (Type)1;
						}
					}
					return (Type)0;
				}
				return (Type)2;
			}
			return (Type)0;
		}

		private static Vector3 ResolveRotation(LevelGenerator generator, Tile[,] levelGrid, int x, int y, Type targetType)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_001f: 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_000d: Invalid comparison between Unknown and I4
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Invalid comparison between Unknown and I4
			//IL_0098: 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_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: 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_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			if ((int)targetType == 3 || (int)targetType == 2 || (int)targetType == 4)
			{
				if (GridCheckActive(generator, levelGrid, x, y - 1))
				{
					return Vector3.zero;
				}
				Vector3 result = default(Vector3);
				if (GridCheckActive(generator, levelGrid, x - 1, y))
				{
					((Vector3)(ref result))..ctor(0f, 90f, 0f);
				}
				else if (GridCheckActive(generator, levelGrid, x, y + 1))
				{
					((Vector3)(ref result))..ctor(0f, 180f, 0f);
				}
				else
				{
					if (!GridCheckActive(generator, levelGrid, x + 1, y))
					{
						return Vector3.zero;
					}
					((Vector3)(ref result))..ctor(0f, -90f, 0f);
				}
				return result;
			}
			if ((int)targetType == 1)
			{
				bool num = GridCheckActive(generator, levelGrid, x, y + 1) && (GridCheckActive(generator, levelGrid, x, y - 1) || levelGrid[x, y].first) && !GridCheckActive(generator, levelGrid, x + 1, y) && !GridCheckActive(generator, levelGrid, x - 1, y);
				bool flag = !levelGrid[x, y].first && GridCheckActive(generator, levelGrid, x + 1, y) && GridCheckActive(generator, levelGrid, x - 1, y) && !GridCheckActive(generator, levelGrid, x, y + 1) && !GridCheckActive(generator, levelGrid, x, y - 1);
				if (num)
				{
					if (Random.Range(0, 100) >= 50)
					{
						return Vector3.zero;
					}
					return new Vector3(0f, 180f, 0f);
				}
				if (flag)
				{
					if (Random.Range(0, 100) >= 50)
					{
						return new Vector3(0f, 90f, 0f);
					}
					return new Vector3(0f, -90f, 0f);
				}
			}
			Vector3[] array = ModuleRotationsRef.Invok