Decompiled source of LeMatrix v1.0.5

LeMatrix.dll

Decompiled 5 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LeMatrix.Core;
using Unity.AI.Navigation;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LeMatrix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.5.0")]
[assembly: AssemblyInformationalVersion("1.0.5")]
[assembly: AssemblyProduct("LeMatrix")]
[assembly: AssemblyTitle("LeMatrix")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Anthropic Claude (Claude Opus 5.5 and other Claude models, via Claude Code); designed and tested by the author")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")]
[assembly: AssemblyVersion("1.0.5.0")]
namespace LeMatrix
{
	public static class Api
	{
		public const int ApiVersion = 1;

		public static bool Available
		{
			get
			{
				try
				{
					string why;
					return Director.CanStartIgnoringInside(out why);
				}
				catch
				{
					return false;
				}
			}
		}

		public static bool ShowRooms
		{
			get
			{
				try
				{
					return Plugin.ShowRooms != null && Plugin.ShowRooms.Value;
				}
				catch
				{
					return false;
				}
			}
			set
			{
				try
				{
					if (Plugin.ShowRooms != null)
					{
						Plugin.ShowRooms.Value = value;
					}
				}
				catch (Exception e)
				{
					Safe.Report("Api.ShowRooms", e);
				}
			}
		}

		public static bool Trigger(int rooms)
		{
			try
			{
				bool result;
				if (!Director.CanStart(out var why))
				{
					Director.NoteResult("Trigger refused: " + why);
					result = false;
				}
				else
				{
					result = Director.StartEvent(Math.Max(1, Math.Min(5, rooms)), "DNC trigger", out why);
				}
				try
				{
					RoomView.OnTrigger();
				}
				catch (Exception e)
				{
					Safe.Report("Api.Trigger note", e);
				}
				return result;
			}
			catch (Exception e2)
			{
				Safe.Report("Api.Trigger", e2);
				return false;
			}
		}

		public static bool TriggerFor(int rooms, ulong playerClientId)
		{
			try
			{
				bool result;
				if (!Director.CanStart(out var why))
				{
					Director.NoteResult("Trigger refused: " + why);
					result = false;
				}
				else
				{
					result = Director.StartEvent(Math.Max(1, Math.Min(5, rooms)), "DNC trigger", playerClientId, out why);
				}
				try
				{
					RoomView.OnTrigger();
				}
				catch (Exception e)
				{
					Safe.Report("Api.TriggerFor note", e);
				}
				return result;
			}
			catch (Exception e2)
			{
				Safe.Report("Api.TriggerFor", e2);
				return false;
			}
		}

		public static bool RestoreWhenUnseen()
		{
			try
			{
				return Director.RestoreWhenUnseen();
			}
			catch (Exception e)
			{
				Safe.Report("Api.RestoreWhenUnseen", e);
				return false;
			}
		}

		public static bool RestoreImmediately()
		{
			try
			{
				return Director.RestoreImmediately();
			}
			catch (Exception e)
			{
				Safe.Report("Api.RestoreImmediately", e);
				return false;
			}
		}

		public static string[] Status()
		{
			try
			{
				return Net.IsHost ? Director.Status() : new string[1] { "LeMatrix: host only" };
			}
			catch (Exception ex)
			{
				Safe.Report("Api.Status", ex);
				return new string[1] { "LeMatrix status failed: " + ex.Message };
			}
		}

		public static string[] Survey()
		{
			try
			{
				return Net.IsHost ? Director.RunSurvey(log: true) : new string[1] { "LeMatrix: host only" };
			}
			catch (Exception ex)
			{
				Safe.Report("Api.Survey", ex);
				return new string[1] { "LeMatrix survey failed: " + ex.Message };
			}
		}

		internal static void UpdateState()
		{
			if (Plugin.ShowInPerfWatcher == null || !Plugin.ShowInPerfWatcher.Value)
			{
				return;
			}
			Day today = Director.Today;
			MatrixState.Rolled = today?.RollHit ?? false;
			MatrixState.PlannedAt = today?.PlannedAt ?? (-1f);
			int num = 0;
			int num2 = 0;
			foreach (Rec rec in Director.Recs)
			{
				if (rec.IsCommitted)
				{
					num++;
				}
				else if (!rec.IsOver)
				{
					num2++;
				}
			}
			MatrixState.Active = num;
			MatrixState.Pending = num2;
			MatrixState.LastResult = ((today != null) ? today.LastResult : "");
		}
	}
	public static class MatrixState
	{
		public static bool Rolled;

		public static float PlannedAt = -1f;

		public static int Active;

		public static int Pending;

		public static string LastResult = "";
	}
	internal enum RecState
	{
		Preparing,
		Prepared,
		Querying,
		Active,
		RestoreQuerying,
		Done,
		Cancelled
	}
	internal sealed class Rec
	{
		public int Id;

		public RunMode Mode;

		public Pick Pick;

		public SwapPlan Plan;

		public PrepareMsg Msg;

		public RecState State;

		public float Since;

		public float UnseenSince = -1f;

		public float RestoreAt;

		public float CommittedAt;

		public readonly HashSet<ulong> AcksPending = new HashSet<ulong>();

		public bool LocalReady;

		public string NackReason;

		public int QueryId;

		public readonly HashSet<ulong> AnswersPending = new HashSet<ulong>();

		public bool AnySeen;

		public float QuerySent;

		public Box Bounds;

		public List<int> RoomTiles = new List<int>();

		public List<Vector3> KeptDoorPositions = new List<Vector3>();

		public string Waiting = "";

		public string Label = "";

		public string Cluster = "";

		public bool IsCommitted
		{
			get
			{
				if (State != RecState.Active)
				{
					return State == RecState.RestoreQuerying;
				}
				return true;
			}
		}

		public bool IsOver
		{
			get
			{
				if (State != RecState.Done)
				{
					return State == RecState.Cancelled;
				}
				return true;
			}
		}
	}
	internal sealed class ClientReport
	{
		public string Version = "";

		public int Protocol;

		public int DayKey;

		public int Count;

		public uint Hash;

		public bool Enabled;
	}
	internal sealed class Day
	{
		public int DayKey;

		public uint Hash;

		public int Count;

		public bool Allowed;

		public string NotAllowedWhy;

		public bool Rolled;

		public bool RollHit;

		public double RollValue;

		public float PlannedAt = -1f;

		public int EventsDone;

		public bool EventRunning;

		public float LastEventEnd = -1000f;

		public bool Disabled;

		public string DisabledWhy;

		public bool Ended;

		public bool SurveyDue;

		public float LandedAt = -1f;

		public bool LoggedWaitingInside;

		public bool LoggedClients;

		public string LastResult = "";

		public bool InfoDue;
	}
	internal static class Director
	{
		internal static DungeonView View;

		internal static int DayKey = int.MinValue;

		internal static readonly Dictionary<int, LocalSwap> Local = new Dictionary<int, LocalSwap>();

		private static bool _reportDue;

		private static bool _announced;

		private static float _reportAt;

		internal static Day Today;

		internal static readonly List<Rec> Recs = new List<Rec>();

		internal static readonly Dictionary<ulong, ClientReport> Reports = new Dictionary<ulong, ClientReport>();

		private static readonly Queue<Action> Applies = new Queue<Action>();

		private static readonly Random Rng = new Random(Guid.NewGuid().GetHashCode());

		private static int _nextId = 1;

		private static int _nextQuery = 1;

		private static int _nextEvent = 1;

		private static float _nextTick;

		private static float _pauseUntil;

		private static bool[] _seen;

		private static ContentScan _scan;

		private static float _scanAt = -10f;

		private static readonly Dictionary<ulong, float> _requested = new Dictionary<ulong, float>();

		internal static MonoBehaviour Runner;

		internal static void OnLevelGenerated()
		{
			ClearAll("new level");
			Dungeon val = DungeonView.CurrentDungeon();
			if (!((Object)(object)val == (Object)null))
			{
				View = DungeonView.Build(val);
				DayKey = (((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.randomMapSeed : 0);
				_reportDue = true;
				_reportAt = Time.time + 1f;
				if (Net.IsHost)
				{
					NewDay();
				}
			}
		}

		private static void NewDay()
		{
			Day day = (Today = new Day
			{
				DayKey = DayKey
			});
			day.Hash = View.Fingerprint(out day.Count);
			day.Allowed = View.InteriorAllowed(out var why);
			day.NotAllowedWhy = why;
			RunMode value = Plugin.Mode.Value;
			string text = "Day " + DayKey + " on " + View.Interior + " (flow " + View.FlowName + ", " + View.Tiles.Count + " tiles, " + View.Conns.Count + " links), mode " + value.ToString() + ": ";
			L.Debug("Day " + DayKey + ": " + View.RootDescription() + ((View.RootIssue != null) ? (" (" + View.RootIssue + ")") : "") + ".");
			if (!Plugin.Enabled.Value)
			{
				day.LastResult = "disabled in config";
				L.Info(text + "LeMatrix is disabled in config.");
				return;
			}
			day.InfoDue = true;
			if (value == RunMode.Survey || Plugin.SurveyOnLoad.Value)
			{
				day.SurveyDue = true;
			}
			if (value == RunMode.Survey)
			{
				day.LastResult = "survey mode (no events)";
				L.Info(text + "survey mode, no event today.");
				return;
			}
			if (!day.Allowed)
			{
				day.LastResult = "no event: " + why;
				L.Info(text + "no event, " + why + ".");
				return;
			}
			day.Rolled = true;
			day.RollValue = Rng.NextDouble() * 100.0;
			day.RollHit = day.RollValue < (double)Plugin.DayChancePercent.Value;
			if (day.RollHit)
			{
				day.PlannedAt = RandomTime(Plugin.WindowStart.Value);
			}
			day.LastResult = (day.RollHit ? ("event planned at " + day.PlannedAt.ToString("0.00")) : "no event today");
			L.Info(text + "roll " + day.RollValue.ToString("0.0") + " vs " + Plugin.DayChancePercent.Value + "% -> " + (day.RollHit ? ("event planned at " + day.PlannedAt.ToString("0.00") + " of the day.") : "no event."));
			if (day.RollHit)
			{
				Safe.Run("catalogue", delegate
				{
					Catalogue catalogue = View.GetCatalogue();
					L.Debug("Catalogue: " + catalogue.Entries.Count + " prefabs in " + catalogue.BuildMs.ToString("0.0") + " ms");
				});
			}
		}

		private static float RandomTime(float from)
		{
			float num = Mathf.Clamp01(Mathf.Max(from, Plugin.WindowStart.Value));
			float num2 = Mathf.Clamp01(Plugin.WindowEnd.Value);
			if (num2 < num)
			{
				num2 = num;
			}
			return num + (float)Rng.NextDouble() * (num2 - num);
		}

		internal static void ClearAll(string why)
		{
			if (Local.Count > 0 || Recs.Count > 0)
			{
				L.Debug("Clearing (" + why + ")");
			}
			LocalRestoreAll();
			Recs.Clear();
			Applies.Clear();
			NavUpdater.Clear();
			Holder.Clear();
			Components.ClearCache();
			View = null;
			Today = null;
			_seen = null;
			_scan = null;
			_reportDue = false;
		}

		internal static void LocalRestoreAll()
		{
			foreach (KeyValuePair<int, LocalSwap> item in Local.ToList())
			{
				LocalSwap value = item.Value;
				try
				{
					value.Cancelled = true;
					if (value.Committed)
					{
						string text = value.Restore();
						if (text != null)
						{
							L.Warn("Restore of change #" + item.Key + " was incomplete: " + text);
						}
					}
					else
					{
						value.Destroy();
					}
				}
				catch (Exception e)
				{
					Safe.Report("LocalRestoreAll", e);
				}
			}
			Local.Clear();
		}

		internal static void EndOfLevel(string why)
		{
			SafetyRestoreAll(why);
			if (Today != null)
			{
				Today.Ended = true;
			}
		}

		internal static void NoteTeleport(float seconds)
		{
			float num = Time.time + seconds;
			if (num > _pauseUntil)
			{
				_pauseUntil = num;
			}
		}

		internal static void Update()
		{
			L.Flush();
			Net.EnsureRegistered();
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening || (Object)(object)StartOfRound.Instance == (Object)null)
			{
				if (View != null || Local.Count > 0 || Recs.Count > 0)
				{
					ClearAll("left the game");
				}
				Reports.Clear();
				_announced = false;
				return;
			}
			if (View != null && (Object)(object)View.Dungeon == (Object)null)
			{
				ClearAll("dungeon unloaded");
			}
			if (_reportDue && Time.time >= _reportAt && View != null && Net.IsClientOnly)
			{
				_reportDue = false;
				SendReport();
			}
			if (singleton.IsServer)
			{
				if (!_announced)
				{
					_announced = true;
					L.Info("LeMatrix 1.0.5 active on the host: mode " + Plugin.Mode.Value.ToString() + (Plugin.Enabled.Value ? "" : " (disabled)") + ", day chance " + Plugin.DayChancePercent.Value + "%, rooms " + Plugin.MinRooms.Value + "-" + Plugin.MaxRooms.Value + ", navmesh " + Plugin.Navmesh.Value.ToString() + ".");
				}
				if (Time.time >= _nextTick)
				{
					_nextTick = Time.time + 0.25f;
					Safe.Run("HostTick", HostTick);
				}
				if (Applies.Count > 0)
				{
					Action a = Applies.Dequeue();
					Safe.Run("apply", a);
				}
			}
		}

		internal static void LateUpdate()
		{
			NavUpdater.Tick();
		}

		private static void SendReport()
		{
			int count;
			uint v = View.Fingerprint(out count);
			ByteWriter byteWriter = Net.Msg(Op.DayReport);
			byteWriter.Str("1.0.5");
			byteWriter.I32(1);
			byteWriter.I32(DayKey);
			byteWriter.I32(count);
			byteWriter.U32(v);
			byteWriter.Bool(Plugin.Enabled.Value);
			Net.ToHost(byteWriter);
		}

		private static void HostTick()
		{
			Day today = Today;
			StartOfRound instance = StartOfRound.Instance;
			if (today == null || View == null || (Object)(object)instance == (Object)null)
			{
				return;
			}
			_seen = null;
			if (instance.shipHasLanded && today.LandedAt < 0f)
			{
				today.LandedAt = Time.time;
			}
			if (today.SurveyDue && today.LandedAt >= 0f && Time.time - today.LandedAt > 3f)
			{
				today.SurveyDue = false;
				Safe.Run("Survey", delegate
				{
					RunSurvey(log: true);
				});
			}
			if (today.InfoDue && today.LandedAt >= 0f && Time.time - today.LandedAt > 3f && (Object)(object)Runner != (Object)null)
			{
				today.InfoDue = false;
				Runner.StartCoroutine(LandingInfo(View, today));
			}
			PruneDisconnected();
			Schedule(today, instance);
			foreach (Rec r in Recs.ToList())
			{
				Safe.Run("Step", delegate
				{
					Step(r);
				});
			}
			Recs.RemoveAll((Rec rec) => rec.IsOver);
			if (today.EventRunning && Recs.Count == 0)
			{
				EventFinished(today);
			}
			Api.UpdateState();
		}

		private static void PruneDisconnected()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			HashSet<ulong> ids = new HashSet<ulong>(singleton.ConnectedClientsIds);
			foreach (Rec rec in Recs)
			{
				rec.AcksPending.RemoveWhere((ulong id) => !ids.Contains(id));
				rec.AnswersPending.RemoveWhere((ulong id) => !ids.Contains(id));
			}
		}

		private static void Schedule(Day t, StartOfRound sor)
		{
			if (t.Ended || t.Disabled || !t.RollHit || t.EventRunning || Recs.Count > 0 || !Plugin.Enabled.Value || Plugin.Mode.Value == RunMode.Survey || !sor.shipHasLanded || sor.shipIsLeaving || sor.inShipPhase || (Object)(object)TimeOfDay.Instance == (Object)null || t.EventsDone >= Plugin.MaxEventsPerDay.Value)
			{
				return;
			}
			float normalizedTimeOfDay = TimeOfDay.Instance.normalizedTimeOfDay;
			if (normalizedTimeOfDay < t.PlannedAt)
			{
				return;
			}
			if (normalizedTimeOfDay > Plugin.WindowEnd.Value)
			{
				t.RollHit = false;
				t.LastResult = "dropped: nobody went inside before the window closed";
				L.Info("Event dropped: nobody was inside before " + Plugin.WindowEnd.Value.ToString("0.00") + " of the day.");
			}
			else
			{
				if (t.EventsDone > 0 && Time.time - t.LastEventEnd < 90f)
				{
					return;
				}
				string why;
				if (InsidePlayerTiles().Count == 0)
				{
					if (!t.LoggedWaitingInside)
					{
						t.LoggedWaitingInside = true;
						L.Info("Event time reached; waiting for someone to go inside.");
					}
				}
				else if (!CanStart(out why))
				{
					if (!t.LoggedClients)
					{
						t.LoggedClients = true;
						L.Info("Event can't start yet: " + why);
					}
					if (!why.StartsWith("client"))
					{
						t.RollHit = false;
						t.LastResult = "no event: " + why;
					}
				}
				else if (!StartEvent(0, "daily roll", out why))
				{
					t.RollHit = false;
					t.LastResult = "no event: " + why;
				}
			}
		}

		private static void EventFinished(Day t)
		{
			t.EventRunning = false;
			t.EventsDone++;
			t.LastEventEnd = Time.time;
			L.Info("Event over: every changed room is back.");
			if (t.EventsDone < Plugin.MaxEventsPerDay.Value && t.Rolled)
			{
				double num = Rng.NextDouble() * 100.0;
				t.RollHit = num < (double)Plugin.DayChancePercent.Value;
				float num2 = (((Object)(object)TimeOfDay.Instance != (Object)null) ? TimeOfDay.Instance.normalizedTimeOfDay : 0f);
				if (t.RollHit)
				{
					t.PlannedAt = RandomTime(num2);
				}
				L.Info("Extra event roll " + num.ToString("0.0") + " vs " + Plugin.DayChancePercent.Value + "% -> " + (t.RollHit ? ("planned at " + t.PlannedAt.ToString("0.00") + " (at least 90 s from now).") : "no more events today."));
			}
			else
			{
				t.RollHit = false;
			}
		}

		internal static bool CanStart(out string why)
		{
			why = null;
			StartOfRound instance = StartOfRound.Instance;
			if (!Net.IsHost)
			{
				why = "host only";
				return false;
			}
			if (!Plugin.Enabled.Value)
			{
				why = "disabled in config";
				return false;
			}
			if (Plugin.Mode.Value == RunMode.Survey)
			{
				why = "Mode is Survey";
				return false;
			}
			if (View == null || Today == null || (Object)(object)instance == (Object)null)
			{
				why = "no interior loaded";
				return false;
			}
			if (!instance.shipHasLanded || instance.shipIsLeaving || instance.inShipPhase || Today.Ended)
			{
				why = "not in a landed round";
				return false;
			}
			if (!Today.Allowed)
			{
				why = Today.NotAllowedWhy;
				return false;
			}
			if (Today.Disabled)
			{
				why = "off for today (" + Today.DisabledWhy + ")";
				return false;
			}
			if (Recs.Count > 0 || Today.EventRunning)
			{
				why = "an event is already running";
				return false;
			}
			if (InsidePlayerTiles().Count == 0)
			{
				why = "nobody alive is inside";
				return false;
			}
			if (Plugin.Mode.Value == RunMode.Live && !ClientsOk(out why))
			{
				return false;
			}
			return true;
		}

		internal static bool CanStartIgnoringInside(out string why)
		{
			why = null;
			StartOfRound instance = StartOfRound.Instance;
			if (!Net.IsHost)
			{
				why = "host only";
				return false;
			}
			if (!Plugin.Enabled.Value || Plugin.Mode.Value == RunMode.Survey)
			{
				why = "disabled or Survey mode";
				return false;
			}
			if (View == null || Today == null || (Object)(object)instance == (Object)null || !instance.shipHasLanded || instance.shipIsLeaving || Today.Ended)
			{
				why = "not in a landed round";
				return false;
			}
			if (!Today.Allowed)
			{
				why = Today.NotAllowedWhy;
				return false;
			}
			if (Plugin.Mode.Value == RunMode.Live && !ClientsOk(out why))
			{
				return false;
			}
			return true;
		}

		internal static void NoteResult(string s)
		{
			if (Today != null)
			{
				Today.LastResult = s;
			}
			L.Info(s);
		}

		internal static bool ClientsOk(out string why)
		{
			why = null;
			foreach (ulong item in Net.RemoteClients())
			{
				if (!Reports.TryGetValue(item, out var value) || value.DayKey != Today.DayKey)
				{
					why = "client " + item + " hasn't reported LeMatrix for today (missing the mod, or still loading)";
					if (!_requested.TryGetValue(item, out var value2) || Time.time - value2 > 5f)
					{
						_requested[item] = Time.time;
						Net.ToClient(item, Net.Msg(Op.ReportRequest));
					}
					return false;
				}
				if (value.Version != "1.0.5" || value.Protocol != 1)
				{
					why = "client " + item + " has LeMatrix " + value.Version + " (host 1.0.5)";
					return false;
				}
				if (!value.Enabled)
				{
					why = "LeMatrix is disabled on client " + item;
					return false;
				}
				if (value.Count != Today.Count || value.Hash != Today.Hash)
				{
					why = "client " + item + "'s interior doesn't match the host's (tile fingerprint)";
					return false;
				}
			}
			return true;
		}

		internal static List<int> InsidePlayerTiles()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			List<int> list = new List<int>();
			if (View == null)
			{
				return list;
			}
			foreach (PlayerControllerB item in InsidePlayers())
			{
				list.Add(View.TileAt(((Component)item).transform.position));
			}
			return list;
		}

		internal static List<PlayerControllerB> InsidePlayers()
		{
			List<PlayerControllerB> list = new List<PlayerControllerB>();
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || View == null)
			{
				return list;
			}
			PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if (Viewers.Alive(val) && val.isInsideFactory)
				{
					list.Add(val);
				}
			}
			return list;
		}

		private static HashSet<int> CommittedEdges(Rec except)
		{
			HashSet<int> hashSet = new HashSet<int>();
			foreach (Rec rec in Recs)
			{
				if (rec == except || !rec.IsCommitted)
				{
					continue;
				}
				foreach (int removedEdge in rec.Plan.RemovedEdges)
				{
					hashSet.Add(removedEdge);
				}
			}
			return hashSet;
		}

		private static ContentScan Scan()
		{
			if (_scan == null || Time.time - _scanAt > 1f)
			{
				_scan = ContentScan.Take();
				_scanAt = Time.time;
			}
			return _scan;
		}

		private static PickSettings PickSettingsFromConfig()
		{
			PickSettings pickSettings = new PickSettings();
			pickSettings.ExitWeights = ListParse.Doubles(Plugin.ExitWeights.Value, new double[7] { 0.0, 20.0, 8.0, 3.0, 1.0, 0.0, 0.0 });
			pickSettings.RouteBonus = Math.Max(0f, Plugin.RouteBonus.Value);
			pickSettings.CutClosestBonus = Math.Max(0f, Plugin.CutClosestExitBonus.Value);
			pickSettings.ModeWeights = new double[3]
			{
				Plugin.ModeSameLinks.Value,
				Plugin.ModeFewerLinks.Value,
				Plugin.ModeSealOnly.Value
			};
			pickSettings.MinRooms = Plugin.MinRooms.Value;
			pickSettings.MaxRooms = Plugin.MaxRooms.Value;
			pickSettings.CandidateLimit = Plugin.CandidateTiles.Value;
			pickSettings.ClusterRadius = Plugin.ClusterRadius.Value;
			pickSettings.DifferentPrefabBonus = Math.Max(1f, Plugin.DifferentPrefabBonus.Value);
			pickSettings.ExitNeighbourBonus = Math.Max(1f, Plugin.ExitNeighbourBonus.Value);
			return pickSettings;
		}

		internal static bool StartEvent(int forcedCount, string source, out string why)
		{
			return StartEvent(forcedCount, source, ulong.MaxValue, out why);
		}

		internal static bool StartEvent(int forcedCount, string source, ulong targetClient, out string why)
		{
			why = null;
			Stopwatch stopwatch = Stopwatch.StartNew();
			View.RefreshExits();
			ContentScan scan = Scan();
			List<PlayerControllerB> list = InsidePlayers();
			int num = -1;
			if (targetClient != ulong.MaxValue)
			{
				num = list.FindIndex((PlayerControllerB val) => val.playerClientId == targetClient);
				if (num < 0)
				{
					why = "the picked player isn't alive inside";
					Today.LastResult = "no event (" + source + "): " + why;
					L.Info("Event (" + source + ") not started: " + why + ".");
					return false;
				}
			}
			bool[] seenNow = null;
			try
			{
				seenNow = Viewers.Seen(View, Viewers.HostEyes(View), Plugin.AdjacentCountsAsSeen.Value, Plugin.PortalMargin.Value, radar: false, requireLivingInShip: true);
			}
			catch (Exception e)
			{
				Safe.Report("StartEvent seen", e);
			}
			Catalogue cat = View.GetCatalogue();
			SearchSettings settings = Rooms.Settings(View);
			Dictionary<Doorway, SealSource> seals = new Dictionary<Doorway, SealSource>();
			Dictionary<int, RoomDef> rooms = new Dictionary<int, RoomDef>();
			SearchStats stats = new SearchStats();
			PickResult pickResult = Picker.Pick(new PickWorld
			{
				Graph = View.Graph,
				PlayerTiles = list.Select((PlayerControllerB val) => View.TileAt(((Component)val).transform.position)).ToList(),
				Target = num,
				Seen = (int t) => seenNow != null && t >= 0 && t < seenNow.Length && seenNow[t],
				ActiveRemovedEdges = CommittedEdges(null),
				BusyTiles = new HashSet<int>(Recs.Select((Rec r) => r.Pick.Tile)),
				Eligible = (int t) => Rooms.Ineligible(View, t, scan) == null && scan.Inside(View.Bounds[t].Expanded(0.25), includeMoving: true, UsedDoorPositions(t)) == null && Viewers.Occupied(View.Bounds[t]) == null,
				PlansFor = delegate(int t)
				{
					RoomDef roomDef = Rooms.Describe(View, t, scan, seals, Rng);
					rooms[t] = roomDef;
					return PlanSearch.Search(roomDef, cat.Entries.Select((CatEntry catEntry) => catEntry.Def).ToList(), settings, stats);
				}
			}, PickSettingsFromConfig(), Rng, forcedCount);
			double totalMilliseconds = stopwatch.Elapsed.TotalMilliseconds;
			string text = ((Plugin.Mode.Value == RunMode.Live) ? "" : ("[" + Plugin.Mode.Value.ToString() + "] "));
			if (pickResult.FailReason != null)
			{
				why = pickResult.FailReason;
				Today.LastResult = "no event (" + source + "): " + why;
				L.Info(text + "Event (" + source + ") not started: " + why + TargetText(pickResult, list) + ". Checked " + pickResult.Candidates + " rooms near the target, " + pickResult.CandidatesWithPlans + " had plans; " + totalMilliseconds.ToString("0.0") + " ms.");
				return false;
			}
			Today.EventRunning = true;
			int num2 = _nextEvent++;
			string text2 = ((pickResult.TargetIndex >= 0 && pickResult.TargetIndex < list.Count) ? list[pickResult.TargetIndex].playerUsername : "?");
			string text3 = ((!pickResult.DeadEnd) ? "no dead end" : (pickResult.Unreachable ? "dead end (closest exit cut off)" : ("dead end (+" + pickResult.Detour + " hop detour)")));
			string cluster = "event " + num2 + " around " + text2 + ", " + text3;
			L.Info(text + "Event (" + source + "): cluster of " + pickResult.Picks.Count + " of " + pickResult.Target + " rooms" + TargetText(pickResult, list) + "; " + text3 + (pickResult.HasExitNeighbour ? ", includes the room in front of that exit" : "") + "; from " + pickResult.CandidatesWithPlans + "/" + pickResult.Candidates + " candidates, planned in " + totalMilliseconds.ToString("0.0") + " ms" + ((pickResult.Notes.Count > 0) ? (" (" + string.Join("; ", pickResult.Notes) + ")") : "") + ".");
			foreach (Pick p in pickResult.Picks)
			{
				Safe.Run("CreateRec", delegate
				{
					CreateRec(p, rooms[p.Tile], seals, cluster);
				});
			}
			Today.LastResult = "event running (" + source + ", " + Recs.Count + " rooms)";
			if (Recs.Count == 0)
			{
				Today.EventRunning = false;
				why = "no room could be prepared";
				return false;
			}
			return true;
		}

		private static string TargetText(PickResult pick, List<PlayerControllerB> inside)
		{
			if (pick == null || pick.TargetIndex < 0 || pick.TargetIndex >= inside.Count)
			{
				return "";
			}
			string text = ((pick.TargetExit >= 0 && pick.TargetExit < View.ExitNames.Count) ? View.ExitNames[pick.TargetExit] : "no exit");
			return " around " + inside[pick.TargetIndex].playerUsername + " (tile " + pick.TargetTile + ", " + text + " " + pick.TargetExitHops + " hops away)";
		}

		private static List<Vector3> UsedDoorPositions(int t)
		{
			Tile val = View.Tiles[t];
			if (!((Object)(object)val == (Object)null))
			{
				return (from d in val.UsedDoorways
					where (Object)(object)d != (Object)null
					select ((Component)d).transform.position).ToList();
			}
			return new List<Vector3>();
		}

		private static void CreateRec(Pick p, RoomDef room, Dictionary<Doorway, SealSource> seals, string cluster)
		{
			//IL_0326: Unknown result type (might be due to invalid IL or missing references)
			Tile val = View.Tiles[p.Tile];
			SwapPlan plan = p.Plan;
			Catalogue catalogue = View.GetCatalogue();
			PrepareMsg prepareMsg = new PrepareMsg
			{
				SwapId = _nextId++,
				DayKey = DayKey,
				Tile = p.Tile,
				OrigPrefab = ((Object)val.Prefab).name,
				Mode = plan.Mode,
				Seed = Rng.Next()
			};
			prepareMsg.Drop.AddRange(plan.Drop);
			if (plan.Mode != SwapMode.SealOnly)
			{
				CatEntry catEntry = catalogue.Entries[plan.PrefabKey];
				if (catEntry.Set >= 0)
				{
					prepareMsg.SetIndex = catEntry.Set;
					prepareMsg.WeightIndex = catEntry.Weight;
				}
				else if ((Object)(object)catEntry.Prefab != (Object)(object)val.Prefab)
				{
					L.Warn("Skipped tile " + p.Tile + ": its replacement can't be referenced.");
					return;
				}
				prepareMsg.Prefab = ((Object)catEntry.Prefab).name;
				prepareMsg.Px = (float)plan.Pos.X;
				prepareMsg.Py = (float)plan.Pos.Y;
				prepareMsg.Pz = (float)plan.Pos.Z;
				prepareMsg.Yaw = (float)plan.Yaw;
				foreach (int[] item in plan.Keep)
				{
					prepareMsg.Keep.Add(new int[2]
					{
						item[0],
						item[1]
					});
				}
				prepareMsg.Extra.AddRange(plan.Extra);
			}
			foreach (int item2 in plan.Drop)
			{
				Doorway val2 = val.AllDoorways[item2];
				Doorway connectedDoorway = val2.ConnectedDoorway;
				AddSeal(prepareMsg, connectedDoorway, seals);
				if (plan.Mode == SwapMode.SealOnly)
				{
					AddSeal(prepareMsg, val2, seals);
				}
			}
			Rec rec = new Rec
			{
				Id = prepareMsg.SwapId,
				Mode = Plugin.Mode.Value,
				Pick = p,
				Plan = plan,
				Msg = prepareMsg,
				State = RecState.Preparing,
				Since = Time.time
			};
			rec.Bounds = Box.Union(View.Bounds[p.Tile], View.ToWorld(plan.NewBounds));
			rec.Cluster = cluster ?? "";
			rec.RoomTiles = Viewers.RoomTiles(View, p.Tile, rec.Bounds);
			HashSet<int> hashSet = new HashSet<int>(plan.Drop);
			foreach (Doorway usedDoorway in val.UsedDoorways)
			{
				if ((Object)(object)usedDoorway != (Object)null && !hashSet.Contains(val.AllDoorways.IndexOf(usedDoorway)))
				{
					rec.KeptDoorPositions.Add(((Component)usedDoorway).transform.position);
				}
			}
			string text = ((plan.Mode == SwapMode.SealOnly) ? "seal one link" : (plan.Mode.ToString() + " -> " + prepareMsg.Prefab + " (yaw " + prepareMsg.Yaw.ToString("0") + ", keeps " + plan.Keep.Count + ", seals " + plan.Drop.Count + ", blocks " + plan.Extra.Count + " extra)"));
			rec.Label = "#" + rec.Id + " tile " + p.Tile + " " + ((Object)val.Prefab).name + ": " + text;
			Recs.Add(rec);
			string text2 = ((rec.Mode == RunMode.Live) ? "" : ("[" + rec.Mode.ToString() + "] "));
			L.Info(text2 + "Planned " + rec.Label + "; " + p.Hops + " hops from an exit, " + p.TargetHops + " from the target" + (p.OnRoute ? ", on the target's route" : "") + ((plan.Mode == SwapMode.SealOnly) ? "" : (plan.OwnPrefab ? ", own prefab turned" : ", different prefab")) + ".");
			if (rec.Mode == RunMode.Live)
			{
				foreach (ulong item3 in Net.RemoteClients())
				{
					rec.AcksPending.Add(item3);
				}
				ByteWriter w = Net.Msg(Op.Prepare);
				prepareMsg.Write(w);
				Net.ToClients(w);
			}
			if (rec.Mode == RunMode.Live || rec.Mode == RunMode.PrepareTest)
			{
				StartLocalPrepare(rec);
			}
		}

		private static void AddSeal(PrepareMsg msg, Doorway d, Dictionary<Doorway, SealSource> seals)
		{
			if (!seals.TryGetValue(d, out var value) || value == null)
			{
				value = (seals[d] = View.SealFor(d, Rng));
			}
			if (value == null)
			{
				throw new InvalidOperationException("no blocker for a doorway that was marked sealable");
			}
			msg.Seals.Add(new SealSpec
			{
				Tile = View.IndexOf(d.Tile),
				Door = d.Tile.AllDoorways.IndexOf(d),
				Kind = value.Kind,
				Index = value.Index,
				Blocker = ((Object)value.Prefab).name
			});
		}

		private static void StartLocalPrepare(Rec r)
		{
			LocalSwap localSwap = new LocalSwap(r.Msg, View);
			Local[r.Id] = localSwap;
			Stopwatch sw = Stopwatch.StartNew();
			Runner.StartCoroutine(localSwap.Prepare(delegate(bool ok, string why)
			{
				r.LocalReady = ok;
				if (!ok)
				{
					r.NackReason = "host: " + why;
				}
				L.Debug("Prepared #" + r.Id + " on the host in " + sw.Elapsed.TotalMilliseconds.ToString("0") + " ms (" + (ok ? "ok" : why) + ")");
			}));
		}

		private static void Step(Rec r)
		{
			float time = Time.time;
			switch (r.State)
			{
			case RecState.Preparing:
				if (r.Mode == RunMode.DryRun)
				{
					r.State = RecState.Prepared;
					r.Since = time;
				}
				else if (r.NackReason != null)
				{
					Cancel(r, "prepare failed: " + r.NackReason);
				}
				else if (r.LocalReady && r.AcksPending.Count == 0)
				{
					if (r.Mode == RunMode.PrepareTest)
					{
						L.Info("[PrepareTest] Built " + r.Label + " hidden on the host without errors; destroying it again.");
						Cancel(r, null);
					}
					else
					{
						r.State = RecState.Prepared;
						r.Since = time;
					}
				}
				else if (time - r.Since > 10f)
				{
					Cancel(r, "no prepare reply within 10 s");
				}
				break;
			case RecState.Prepared:
				if (time - r.Since > Plugin.PendingTimeoutSeconds.Value)
				{
					Cancel(r, "couldn't change it unseen within " + Plugin.PendingTimeoutSeconds.Value.ToString("0") + " s (last: " + r.Waiting + ")");
				}
				else if (Hold(r, restore: false))
				{
					if (r.Mode == RunMode.DryRun)
					{
						L.Info("[DryRun] Would change " + r.Label + " now (unseen for " + Plugin.UnseenHoldSeconds.Value.ToString("0.0") + " s).");
						Activated(r);
					}
					else
					{
						Ask(r, restore: false);
					}
				}
				break;
			case RecState.Querying:
			case RecState.RestoreQuerying:
			{
				bool flag = r.State == RecState.RestoreQuerying;
				if (r.AnswersPending.Contains(ulong.MaxValue))
				{
					break;
				}
				if (r.AnySeen || time - r.QuerySent > 0.5f)
				{
					if (r.AnySeen)
					{
						r.Waiting = "a client can see it";
					}
					else
					{
						r.Waiting = "client didn't answer in time";
					}
					r.State = ((!flag) ? RecState.Prepared : RecState.Active);
					r.UnseenSince = -1f;
				}
				else if (r.AnswersPending.Count == 0)
				{
					Enqueue(r, flag);
				}
				break;
			}
			case RecState.Active:
				if (time < r.RestoreAt)
				{
					r.Waiting = "timer";
				}
				else if (Hold(r, restore: true))
				{
					if (r.Mode == RunMode.DryRun)
					{
						L.Info("[DryRun] Would restore " + r.Label + " now, " + (time - r.CommittedAt).ToString("0") + " s after the change.");
						r.State = RecState.Done;
					}
					else
					{
						Ask(r, restore: true);
					}
				}
				break;
			}
		}

		private static bool Hold(Rec r, bool restore)
		{
			if (!CanChange(r, restore, out var why))
			{
				r.UnseenSince = -1f;
				r.Waiting = why;
				return false;
			}
			if (r.UnseenSince < 0f)
			{
				r.UnseenSince = Time.time;
			}
			r.Waiting = "holding";
			return Time.time - r.UnseenSince >= Plugin.UnseenHoldSeconds.Value;
		}

		private static void Ask(Rec r, bool restore)
		{
			List<ulong> list = Net.RemoteClients();
			if (!Plugin.ClientVeto.Value || list.Count == 0)
			{
				r.QuerySent = Time.time;
				r.AnySeen = false;
				r.AnswersPending.Clear();
				r.State = (restore ? RecState.RestoreQuerying : RecState.Querying);
				Enqueue(r, restore);
				return;
			}
			r.QueryId = _nextQuery++;
			r.AnswersPending.Clear();
			foreach (ulong item in list)
			{
				r.AnswersPending.Add(item);
			}
			r.AnySeen = false;
			r.QuerySent = Time.time;
			r.State = (restore ? RecState.RestoreQuerying : RecState.Querying);
			QueryMsg queryMsg = new QueryMsg();
			queryMsg.QueryId = r.QueryId;
			queryMsg.SwapId = r.Id;
			queryMsg.ForRestore = restore;
			queryMsg.Adjacent = Plugin.AdjacentCountsAsSeen.Value;
			queryMsg.Radar = Plugin.RadarCountsAsViewer.Value;
			queryMsg.Margin = Plugin.PortalMargin.Value;
			queryMsg.MinX = (float)r.Bounds.Min.X;
			queryMsg.MinY = (float)r.Bounds.Min.Y;
			queryMsg.MinZ = (float)r.Bounds.Min.Z;
			queryMsg.MaxX = (float)r.Bounds.Max.X;
			queryMsg.MaxY = (float)r.Bounds.Max.Y;
			queryMsg.MaxZ = (float)r.Bounds.Max.Z;
			ByteWriter w = Net.Msg(Op.Query);
			queryMsg.Write(w);
			Net.ToClients(w);
		}

		private static void Enqueue(Rec r, bool restore)
		{
			if (r.AnswersPending.Count > 0)
			{
				return;
			}
			r.AnswersPending.Add(ulong.MaxValue);
			Applies.Enqueue(delegate
			{
				r.AnswersPending.Remove(ulong.MaxValue);
				if (restore)
				{
					ApplyRestore(r);
				}
				else
				{
					ApplyCommit(r);
				}
			});
		}

		internal static bool CanChange(Rec r, bool restore, out string why)
		{
			why = null;
			StartOfRound instance = StartOfRound.Instance;
			if (Time.time < _pauseUntil)
			{
				why = "teleport pause";
				return false;
			}
			if ((Object)(object)instance == (Object)null || !instance.shipHasLanded || instance.shipIsLeaving)
			{
				why = "ship not landed";
				return false;
			}
			if (_seen == null)
			{
				_seen = Viewers.Seen(View, Viewers.HostEyes(View), Plugin.AdjacentCountsAsSeen.Value, Plugin.PortalMargin.Value, Plugin.RadarCountsAsViewer.Value, requireLivingInShip: true);
			}
			foreach (int roomTile in r.RoomTiles)
			{
				if (roomTile >= 0 && roomTile < _seen.Length && _seen[roomTile])
				{
					why = "in view";
					return false;
				}
			}
			string text = Viewers.Occupied(r.Bounds);
			if (text != null)
			{
				why = text;
				return false;
			}
			if (restore)
			{
				return true;
			}
			string text2 = Scan().Inside(r.Bounds.Expanded(0.25), includeMoving: true, r.KeptDoorPositions);
			if (text2 != null)
			{
				why = "has " + text2;
				return false;
			}
			if (!Picker.PlanAllowed(View.Graph, InsidePlayerTiles(), CommittedEdges(r), r.Plan, out why))
			{
				return false;
			}
			return true;
		}

		private static void ApplyCommit(Rec r)
		{
			if (r.State != RecState.Querying)
			{
				return;
			}
			_seen = null;
			if (!CanChange(r, restore: false, out var why))
			{
				r.State = RecState.Prepared;
				r.UnseenSince = -1f;
				r.Waiting = why;
				return;
			}
			if (!Local.TryGetValue(r.Id, out var value) || !value.Ready)
			{
				Cancel(r, "host copy isn't ready");
				return;
			}
			ByteWriter byteWriter = Net.Msg(Op.Commit);
			byteWriter.I32(r.Id);
			Net.ToClients(byteWriter);
			Stopwatch stopwatch = Stopwatch.StartNew();
			try
			{
				value.Commit();
			}
			catch (Exception ex)
			{
				Fail(r, "commit on the host failed: " + ex);
				return;
			}
			L.Info("Changed " + r.Label + " (" + stopwatch.Elapsed.TotalMilliseconds.ToString("0.0") + " ms on the host).");
			Activated(r);
		}

		private static void Activated(Rec r)
		{
			r.State = RecState.Active;
			r.CommittedAt = Time.time;
			float value = Plugin.RestoreMinSeconds.Value;
			float num = Math.Max(value, Plugin.RestoreMaxSeconds.Value);
			r.RestoreAt = Time.time + value + (float)Rng.NextDouble() * (num - value);
			r.UnseenSince = -1f;
		}

		private static void ApplyRestore(Rec r)
		{
			if (r.State != RecState.RestoreQuerying)
			{
				return;
			}
			_seen = null;
			if (!CanChange(r, restore: true, out var why))
			{
				r.State = RecState.Active;
				r.UnseenSince = -1f;
				r.Waiting = why;
				return;
			}
			ByteWriter byteWriter = Net.Msg(Op.Restore);
			byteWriter.I32(r.Id);
			Net.ToClients(byteWriter);
			string text = null;
			if (Local.TryGetValue(r.Id, out var value))
			{
				text = value.Restore();
				Local.Remove(r.Id);
			}
			r.State = RecState.Done;
			L.Info("Restored " + r.Label + " after " + (Time.time - r.CommittedAt).ToString("0") + " s.");
			if (text != null)
			{
				DisableDay("restore of #" + r.Id + " was incomplete on the host: " + text);
			}
		}

		private static void Cancel(Rec r, string why)
		{
			if (r.Mode == RunMode.Live)
			{
				ByteWriter byteWriter = Net.Msg(Op.Cancel);
				byteWriter.I32(r.Id);
				Net.ToClients(byteWriter);
			}
			if (Local.TryGetValue(r.Id, out var value))
			{
				value.Cancelled = true;
				if (value.Committed)
				{
					value.Restore();
				}
				else
				{
					value.Destroy();
				}
				Local.Remove(r.Id);
			}
			r.State = RecState.Cancelled;
			if (why != null)
			{
				L.Info(((r.Mode == RunMode.Live) ? "" : ("[" + r.Mode.ToString() + "] ")) + "Dropped " + r.Label + ": " + why + ".");
			}
		}

		private static void Fail(Rec r, string why)
		{
			ByteWriter byteWriter = Net.Msg(Op.RestoreNow);
			byteWriter.I32(r.Id);
			Net.ToClients(byteWriter);
			if (Local.TryGetValue(r.Id, out var value))
			{
				value.Cancelled = true;
				if (value.Committed)
				{
					value.Restore();
				}
				else
				{
					value.Destroy();
				}
				Local.Remove(r.Id);
			}
			r.State = RecState.Cancelled;
			DisableDay(why);
		}

		internal static void DisableDay(string why)
		{
			if (Today != null)
			{
				Today.Disabled = true;
				Today.DisabledWhy = why;
				Today.LastResult = "off for today: " + why;
			}
			L.Warn("LeMatrix is off for the rest of the day: " + why);
			SafetyRestoreAll("LeMatrix switched off for the day");
		}

		internal static void SafetyRestoreAll(string why)
		{
			if (!Net.IsHost)
			{
				LocalRestoreAll();
				return;
			}
			bool flag = Recs.Any((Rec r) => r.IsCommitted);
			bool flag2 = Recs.Any((Rec r) => r.Mode == RunMode.Live);
			if (Recs.Count > 0)
			{
				L.Info((flag2 ? "" : ("[" + Recs[0].Mode.ToString() + "] ")) + (flag ? ((flag2 ? "Restoring" : "Would restore") + " every changed room now (" + why + ").") : ("Dropping pending room changes (" + why + ").")));
			}
			if (flag2 || Local.Count > 0)
			{
				ByteWriter byteWriter = Net.Msg(Op.RestoreNow);
				byteWriter.I32(-1);
				Net.ToClients(byteWriter);
			}
			LocalRestoreAll();
			foreach (Rec rec in Recs)
			{
				rec.State = (rec.IsCommitted ? RecState.Done : RecState.Cancelled);
			}
			Recs.Clear();
			Applies.Clear();
			if (Today != null && Today.EventRunning)
			{
				EventFinished(Today);
			}
		}

		internal static void OnMessage(ulong sender, byte[] bytes)
		{
			ByteReader byteReader = new ByteReader(bytes);
			Op op = (Op)byteReader.U8();
			if (Net.IsHost)
			{
				if (sender != 0L)
				{
					HostReceive(sender, op, byteReader);
				}
			}
			else if (sender == 0L)
			{
				ClientReceive(op, byteReader);
			}
		}

		private static Rec Find(int id)
		{
			return Recs.FirstOrDefault((Rec x) => x.Id == id);
		}

		private static void HostReceive(ulong sender, Op op, ByteReader r)
		{
			switch (op)
			{
			case Op.DayReport:
			{
				ClientReport clientReport = new ClientReport
				{
					Version = r.Str(),
					Protocol = r.I32(),
					DayKey = r.I32(),
					Count = r.I32(),
					Hash = r.U32(),
					Enabled = r.Bool()
				};
				Reports[sender] = clientReport;
				L.Debug("Client " + sender + " reported LeMatrix " + clientReport.Version + ", day " + clientReport.DayKey + ", " + clientReport.Count + " tiles, enabled " + clientReport.Enabled);
				if (Today != null && clientReport.DayKey == Today.DayKey && (clientReport.Hash != Today.Hash || clientReport.Count != Today.Count))
				{
					L.Info("Client " + sender + "'s interior doesn't match the host's (" + clientReport.Count + " vs " + Today.Count + " tiles); LeMatrix stays off while they're connected today.");
				}
				break;
			}
			case Op.PrepareAck:
			{
				int num = r.I32();
				bool flag = r.Bool();
				string text2 = r.Str();
				Rec rec2 = Find(num);
				if (rec2 == null)
				{
					if (flag)
					{
						ByteWriter byteWriter = Net.Msg(Op.Cancel);
						byteWriter.I32(num);
						Net.ToClient(sender, byteWriter);
					}
				}
				else
				{
					rec2.AcksPending.Remove(sender);
					if (!flag && rec2.NackReason == null)
					{
						rec2.NackReason = "client " + sender + ": " + text2;
					}
				}
				break;
			}
			case Op.Answer:
			{
				int qid = r.I32();
				bool flag2 = r.Bool();
				Rec rec3 = Recs.FirstOrDefault((Rec x) => x.QueryId == qid);
				if (rec3 != null)
				{
					rec3.AnswersPending.Remove(sender);
					if (!flag2)
					{
						rec3.AnySeen = true;
					}
				}
				break;
			}
			case Op.Error:
			{
				int id = r.I32();
				string text = r.Str();
				L.Warn("Client " + sender + " reported a LeMatrix error on change #" + id + ": " + text);
				Rec rec = Find(id);
				if (rec != null)
				{
					Fail(rec, "client " + sender + " error: " + text);
				}
				else
				{
					DisableDay("client " + sender + " error: " + text);
				}
				break;
			}
			}
		}

		private static void ClientReceive(Op op, ByteReader r)
		{
			switch (op)
			{
			case Op.ReportRequest:
				_reportDue = true;
				_reportAt = Time.time;
				break;
			case Op.Prepare:
			{
				PrepareMsg msg = PrepareMsg.Read(r);
				if (!Plugin.Enabled.Value)
				{
					Ack(msg.SwapId, ok: false, "LeMatrix disabled on this client");
				}
				else if (View == null)
				{
					Ack(msg.SwapId, ok: false, "no interior loaded");
				}
				else if (msg.DayKey != DayKey)
				{
					Ack(msg.SwapId, ok: false, "different day");
				}
				else if (!Local.ContainsKey(msg.SwapId))
				{
					LocalSwap localSwap = new LocalSwap(msg, View);
					Local[msg.SwapId] = localSwap;
					Runner.StartCoroutine(localSwap.Prepare(delegate(bool ok, string why)
					{
						Ack(msg.SwapId, ok, why ?? "");
					}));
				}
				break;
			}
			case Op.Query:
			{
				QueryMsg queryMsg = QueryMsg.Read(r);
				bool v = false;
				if (Local.TryGetValue(queryMsg.SwapId, out var value5) && View != null)
				{
					try
					{
						v = Viewers.LocalClear(View, queryMsg, value5.Msg.Tile);
					}
					catch (Exception ex2)
					{
						v = false;
						SendError(queryMsg.SwapId, "query: " + ex2.Message);
					}
				}
				ByteWriter byteWriter = Net.Msg(Op.Answer);
				byteWriter.I32(queryMsg.QueryId);
				byteWriter.Bool(v);
				Net.ToHost(byteWriter);
				break;
			}
			case Op.Commit:
			{
				int num2 = r.I32();
				if (!Local.TryGetValue(num2, out var value3) || !value3.Ready)
				{
					SendError(num2, "commit for a change this client hasn't prepared");
					break;
				}
				try
				{
					value3.Commit();
					break;
				}
				catch (Exception ex)
				{
					Local.Remove(num2);
					SendError(num2, "commit failed: " + ex.Message);
					break;
				}
			}
			case Op.Restore:
			{
				int num = r.I32();
				if (Local.TryGetValue(num, out var value2))
				{
					string text = (value2.Committed ? value2.Restore() : null);
					if (!value2.Committed)
					{
						value2.Destroy();
					}
					Local.Remove(num);
					if (text != null)
					{
						SendError(num, "restore incomplete: " + text);
					}
				}
				break;
			}
			case Op.RestoreNow:
			{
				int num3 = r.I32();
				LocalSwap value4;
				if (num3 < 0)
				{
					LocalRestoreAll();
				}
				else if (Local.TryGetValue(num3, out value4))
				{
					value4.Cancelled = true;
					if (value4.Committed)
					{
						value4.Restore();
					}
					else
					{
						value4.Destroy();
					}
					Local.Remove(num3);
				}
				break;
			}
			case Op.Cancel:
			{
				int key = r.I32();
				if (Local.TryGetValue(key, out var value))
				{
					value.Cancelled = true;
					if (value.Committed)
					{
						value.Restore();
					}
					else
					{
						value.Destroy();
					}
					Local.Remove(key);
				}
				break;
			}
			case Op.PrepareAck:
			case Op.Answer:
				break;
			}
		}

		private static void Ack(int id, bool ok, string why)
		{
			ByteWriter byteWriter = Net.Msg(Op.PrepareAck);
			byteWriter.I32(id);
			byteWriter.Bool(ok);
			byteWriter.Str(why);
			Net.ToHost(byteWriter);
		}

		private static void SendError(int id, string text)
		{
			ByteWriter byteWriter = Net.Msg(Op.Error);
			byteWriter.I32(id);
			byteWriter.Str((text.Length > 400) ? text.Substring(0, 400) : text);
			Net.ToHost(byteWriter);
		}

		internal static string[] RunSurvey(bool log)
		{
			List<string> list = new List<string>();
			if (View == null)
			{
				list.Add("No interior loaded.");
				return list.ToArray();
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			View.RefreshExits();
			ContentScan contentScan = ContentScan.Take();
			Catalogue cat = View.GetCatalogue();
			SearchSettings s = Rooms.Settings(View);
			Dictionary<Doorway, SealSource> seals = new Dictionary<Doorway, SealSource>();
			int[] array = View.Graph.HopsFromExits();
			PickSettings s2 = PickSettingsFromConfig();
			string why;
			bool flag = View.InteriorAllowed(out why);
			list.Add("Survey of " + View.Interior + " (flow " + View.FlowName + "): " + View.Tiles.Count + " tiles, " + View.Conns.Count + " links, " + (flag ? "allowed" : ("not allowed (" + why + ")")) + ".");
			int num = 0;
			HashSet<string> hashSet = new HashSet<string>();
			for (int i = 0; i < View.Tiles.Count; i++)
			{
				if ((Object)(object)View.Tiles[i] != (Object)null && !V3.IsOne(View.TileScale[i]))
				{
					num++;
					hashSet.Add(View.TileScale[i].ToString());
				}
			}
			list.Add("Root: " + View.RootDescription() + ((View.RootIssue != null) ? (" (" + View.RootIssue + ")") : "") + "; scaled tiles: " + num + ((num > 0) ? (" (" + string.Join(", ", hashSet) + ")") : "") + ".");
			list.Add("Exits: " + ((View.Graph.Exits.Count == 0) ? "none found" : string.Join(", ", View.Graph.Exits.Select((int t, int index) => View.ExitNames[index] + " in tile " + t))) + ((View.Graph.Exits.Count == 1) ? " (single exit: its route is never touched)" : "") + ".");
			int num2 = cat.Entries.Count((CatEntry e) => e.Def.Usable);
			IEnumerable<string> values = from e in cat.Entries
				where !e.Def.Usable
				group e by e.Reject into g
				select g.Count() + " " + g.Key;
			list.Add("Candidate prefabs: " + num2 + " usable of " + cat.Entries.Count + ((num2 < cat.Entries.Count) ? (" (rejected: " + string.Join(", ", values) + ")") : "") + "; catalogue built in " + cat.BuildMs.ToString("0.0") + " ms.");
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			List<string> list2 = new List<string>();
			HashSet<int> hashSet2 = new HashSet<int>();
			int num3 = 0;
			SearchStats searchStats = new SearchStats();
			int num4 = 0;
			int num5 = 0;
			int num6 = 0;
			int num7 = 0;
			int num8 = 0;
			List<string> list3 = new List<string>();
			double num9 = 0.0;
			for (int num10 = 0; num10 < View.Tiles.Count; num10++)
			{
				string text = Rooms.Ineligible(View, num10, contentScan) ?? contentScan.Inside(View.Bounds[num10].Expanded(0.25), includeMoving: true, UsedDoorPositions(num10));
				if (text != null)
				{
					dictionary.TryGetValue(text, out var value);
					dictionary[text] = value + 1;
					if (num10 < array.Length && array[num10] >= 1 && array[num10] <= 2 && list2.Count < 16)
					{
						list2.Add("tile " + num10 + " " + (((Object)(object)View.Tiles[num10] != (Object)null && (Object)(object)View.Tiles[num10].Prefab != (Object)null) ? ((Object)View.Tiles[num10].Prefab).name : "?") + " (" + array[num10] + " hop" + ((array[num10] == 1) ? "" : "s") + "): " + text);
					}
					continue;
				}
				num4++;
				SearchStats searchStats2 = new SearchStats();
				double totalMilliseconds = stopwatch.Elapsed.TotalMilliseconds;
				List<SwapPlan> list4 = PlanSearch.Search(Rooms.Describe(View, num10, contentScan, seals, null), cat.Entries.Select((CatEntry e) => e.Def).ToList(), s, searchStats2);
				num9 += stopwatch.Elapsed.TotalMilliseconds - totalMilliseconds;
				searchStats.Add(searchStats2);
				int num11 = list4.Count((SwapPlan p) => p.Mode == SwapMode.SameLinks);
				int num12 = list4.Count((SwapPlan p) => p.Mode == SwapMode.FewerLinks);
				int num13 = list4.Count((SwapPlan p) => p.Mode == SwapMode.SealOnly);
				foreach (SwapPlan item in list4)
				{
					if (item.Mode != SwapMode.SealOnly)
					{
						hashSet2.Add(item.PrefabKey);
					}
				}
				if (list4.Any((SwapPlan p) => p.Mode != SwapMode.SealOnly) && list4.Where((SwapPlan p) => p.Mode != SwapMode.SealOnly).All((SwapPlan p) => p.OwnPrefab))
				{
					num3++;
				}
				if (num11 > 0)
				{
					num5++;
				}
				if (num12 > 0)
				{
					num6++;
				}
				if (num11 == 0 && num12 == 0 && num13 > 0)
				{
					num7++;
				}
				if (list4.Count == 0)
				{
					num8++;
					dictionary.TryGetValue("no plan", out var value2);
					dictionary["no plan"] = value2 + 1;
				}
				SwapPlan swapPlan = (from p in list4
					where p.Mode != SwapMode.SealOnly
					orderby p.Mode, p.Keep.Count descending
					select p).FirstOrDefault();
				string text2 = ((array[num10] < 0) ? "unreachable" : (array[num10] + " hops" + ((Picker.BaseWeight(array[num10], s2) > 0.0) ? "" : " (too far, weight 0)")));
				list3.Add("  tile " + num10 + " " + ((Object)View.Tiles[num10].Prefab).name + ": " + text2 + ", SameLinks " + num11 + ", FewerLinks " + num12 + ", seals " + num13 + ((swapPlan != null) ? (", best " + cat.NameOf(swapPlan.PrefabKey) + " (" + swapPlan.Mode.ToString() + ")") : ""));
			}
			list.Add("Eligible tiles: " + num4 + " of " + View.Tiles.Count + ". Not eligible: " + ((dictionary.Count == 0) ? "none" : string.Join(", ", from kv in dictionary
				orderby kv.Value descending
				select kv.Value + " " + kv.Key)) + ".");
			list.Add("Tiles with a SameLinks (corridor) option: " + num5 + "; with FewerLinks: " + num6 + "; seal only: " + num7 + "; nothing: " + num8 + ".");
			list.Add("Plan search: " + num9.ToString("0.0") + " ms for " + num4 + " tiles (" + searchStats.Anchors + " anchor pairs); rejected: rotation " + searchStats.RejRotation + ", tags " + searchStats.RejTags + ", can't seal " + searchStats.RejCannotDrop + ", open extra doorway " + searchStats.RejExtraOpen + ", outside the room " + searchStats.RejOutside + ", overlap " + searchStats.RejOverlap + ", other scale " + searchStats.RejScale + ".");
			list.Add("Replacement variety: " + hashSet2.Count + " distinct prefabs used by plans (" + string.Join(", ", from k in hashSet2
				select cat.NameOf(k) into x
				orderby x
				select x) + "); " + num3 + " eligible rooms can only become their own prefab turned.");
			list.Add((list2.Count == 0) ? "Rooms 1-2 hops from an exit: none blocked." : ("Rooms 1-2 hops from an exit that can't change: " + string.Join("; ", list2) + "."));
			if (Plugin.RequireWithinOriginalBounds.Value && searchStats.OutsideButOtherwiseValid > 0)
			{
				list.Add("Turning RequireWithinOriginalBounds off would add up to " + searchStats.OutsideButOtherwiseValid + " more options (untested in game).");
			}
			list.AddRange(list3);
			list.Add("Survey took " + stopwatch.Elapsed.TotalMilliseconds.ToString("0") + " ms.");
			if (log)
			{
				foreach (string item2 in list)
				{
					L.Info("[Survey] " + item2);
				}
			}
			return list.ToArray();
		}

		private static IEnumerator LandingInfo(DungeonView v, Day day)
		{
			ContentScan scan = null;
			SearchSettings settings = null;
			int[] hops = null;
			PickSettings ps = null;
			List<PrefabDef> defs = null;
			bool flag = false;
			try
			{
				v.RefreshExits();
				scan = ContentScan.Take();
				Catalogue catalogue = v.GetCatalogue();
				defs = catalogue.Entries.Select((CatEntry catEntry) => catEntry.Def).ToList();
				settings = Rooms.Settings(v);
				hops = v.Graph.HopsFromExits();
				ps = PickSettingsFromConfig();
				flag = true;
			}
			catch (Exception e)
			{
				Safe.Report("LandingInfo setup", e);
			}
			if (!flag)
			{
				yield break;
			}
			yield return null;
			Dictionary<Doorway, SealSource> seals = new Dictionary<Doorway, SealSource>();
			int n = 0;
			int m = 0;
			int eligible = 0;
			Stopwatch budget = Stopwatch.StartNew();
			for (int t = 0; t < v.Tiles.Count; t++)
			{
				if (View != v || Today != day)
				{
					yield break;
				}
				try
				{
					if (t < hops.Length && Picker.BaseWeight(hops[t], ps) > 0.0 && Rooms.Ineligible(v, t, scan) == null)
					{
						eligible++;
						List<SwapPlan> list = PlanSearch.Search(Rooms.Describe(v, t, scan, seals, null), defs, settings, new SearchStats());
						if (list.Count > 0)
						{
							n++;
						}
						if (list.Any((SwapPlan pl) => pl.Mode == SwapMode.SameLinks))
						{
							m++;
						}
					}
				}
				catch (Exception e2)
				{
					Safe.Report("LandingInfo tile", e2);
				}
				if (budget.Elapsed.TotalMilliseconds > 4.0)
				{
					yield return null;
					budget.Reset();
					budget.Start();
				}
			}
			string text = "";
			if (v.RootIssue != null)
			{
				text = text + "; " + v.RootIssue;
			}
			else if (v.Root.TiltDegrees() > 0.5)
			{
				text = text + "; dungeon root tilted " + v.Root.TiltDegrees().ToString("0.0") + " degrees (handled)";
			}
			int num = 0;
			for (int num2 = 0; num2 < v.TileScale.Length; num2++)
			{
				if ((Object)(object)v.Tiles[num2] != (Object)null && !V3.IsOne(v.TileScale[num2]))
				{
					num++;
				}
			}
			if (num > 0)
			{
				text = text + "; " + num + " tiles scaled";
			}
			if (!day.Allowed)
			{
				text += "; interior not in Allow, no events here";
			}
			L.Info("LeMatrix: " + v.Interior + " has " + n + " swappable rooms near exits (" + m + " with corridor swaps)" + text + ".");
		}

		internal static List<int> CandidateTiles()
		{
			List<int> list = new List<int>();
			if (View == null)
			{
				return list;
			}
			View.RefreshExits();
			ContentScan contentScan = ContentScan.Take();
			List<PrefabDef> prefabs = View.GetCatalogue().Entries.Select((CatEntry e) => e.Def).ToList();
			SearchSettings s = Rooms.Settings(View);
			Dictionary<Doorway, SealSource> seals = new Dictionary<Doorway, SealSource>();
			int[] array = View.Graph.HopsFromExits();
			PickSettings s2 = PickSettingsFromConfig();
			for (int num = 0; num < View.Tiles.Count; num++)
			{
				if (num < array.Length && !(Picker.BaseWeight(array[num], s2) <= 0.0) && (Rooms.Ineligible(View, num, contentScan) ?? contentScan.Inside(View.Bounds[num].Expanded(0.25), includeMoving: true, UsedDoorPositions(num))) == null && PlanSearch.Search(Rooms.Describe(View, num, contentScan, seals, null), prefabs, s, new SearchStats()).Count > 0)
				{
					list.Add(num);
				}
			}
			return list;
		}

		internal static string[] Status()
		{
			List<string> list = new List<string>();
			list.Add("LeMatrix 1.0.5, mode " + Plugin.Mode.Value.ToString() + (Plugin.Enabled.Value ? "" : " (disabled)") + (Net.IsHost ? "" : ", not the host"));
			if (View == null)
			{
				list.Add("No interior loaded.");
				return list.ToArray();
			}
			list.Add("Interior: " + View.Interior + " (flow " + View.FlowName + "), " + View.Tiles.Count + " tiles.");
			Day today = Today;
			if (today == null)
			{
				return list.ToArray();
			}
			if (!today.Allowed)
			{
				list.Add("Not allowed here: " + today.NotAllowedWhy);
			}
			if (today.Rolled)
			{
				list.Add("Roll " + today.RollValue.ToString("0.0") + " vs " + Plugin.DayChancePercent.Value + "%" + (today.RollHit ? (", event planned at " + today.PlannedAt.ToString("0.00")) : ", no event") + (((Object)(object)TimeOfDay.Instance != (Object)null) ? (" (now " + TimeOfDay.Instance.normalizedTimeOfDay.ToString("0.00") + ")") : "") + "; events so far " + today.EventsDone + ".");
			}
			if (today.Disabled)
			{
				list.Add("Off for today: " + today.DisabledWhy);
			}
			list.Add((Plugin.Mode.Value != RunMode.Live) ? ("Clients: not needed in " + Plugin.Mode.Value.ToString() + ".") : (ClientsOk(out var why) ? "Clients: ready." : ("Clients: " + why)));
			if (Time.time < _pauseUntil)
			{
				list.Add("Teleport pause: " + (_pauseUntil - Time.time).ToString("0.0") + " s.");
			}
			foreach (Rec rec in Recs)
			{
				string text = ((rec.State == RecState.Active && Time.time < rec.RestoreAt) ? ("changed, restore allowed in " + (rec.RestoreAt - Time.time).ToString("0") + " s") : rec.State.ToString());
				list.Add(rec.Label + (string.IsNullOrEmpty(rec.Cluster) ? "" : (" [" + rec.Cluster + "]")) + ": " + text + (string.IsNullOrEmpty(rec.Waiting) ? "" : (" (waiting: " + rec.Waiting + ")")));
			}
			list.Add("Last: " + today.LastResult);
			return list.ToArray();
		}

		internal static bool RestoreWhenUnseen()
		{
			if (!Net.IsHost)
			{
				return false;
			}
			int num = 0;
			foreach (Rec rec in Recs)
			{
				if (rec.IsCommitted)
				{
					rec.RestoreAt = Time.time;
					num++;
				}
			}
			L.Info("Restore when unseen requested (" + num + " rooms).");
			return num > 0;
		}

		internal static bool RestoreImmediately()
		{
			if (!Net.IsHost)
			{
				return false;
			}
			bool result = Recs.Count > 0;
			SafetyRestoreAll("restore now requested (testing)");
			return result;
		}
	}
	internal static class Hooks
	{
		internal static void AfterFinishGeneratingLevel()
		{
			Safe.Run("FinishGeneratingLevel", Director.OnLevelGenerated);
		}

		internal static void BeforeShipLeave()
		{
			Safe.Run("ShipLeave", delegate
			{
				Director.SafetyRestoreAll("ship leaving");
			});
		}

		internal static void BeforeLevelEnd()
		{
			Safe.Run("LevelEnd", delegate
			{
				Director.EndOfLevel("level ending");
			});
		}

		internal static void AfterEntranceTeleport()
		{
			Safe.Run("EntranceTeleport", delegate
			{
				Director.NoteTeleport(Plugin.TeleportCooldownSeconds.Value);
			});
		}

		internal static void AfterTeleporterPressed(ShipTeleporter __instance)
		{
			Safe.Run("ShipTeleporter", delegate
			{
				int num;
				float seconds;
				if ((Object)(object)__instance != (Object)null)
				{
					num = (__instance.isInverseTeleporter ? 1 : 0);
					if (num != 0)
					{
						seconds = Mathf.Max(10f, Plugin.TeleportCooldownSeconds.Value);
						goto IL_003f;
					}
				}
				else
				{
					num = 0;
				}
				seconds = Plugin.TeleportCooldownSeconds.Value;
				goto IL_003f;
				IL_003f:
				Director.NoteTeleport(seconds);
				if (num != 0 && Plugin.RestoreOnInverseTeleport.Value && Net.IsHost)
				{
					Director.SafetyRestoreAll("inverse teleporter pressed");
				}
			});
		}
	}
	internal static class Net
	{
		internal const string Channel = "jacob.lematrix";

		private static CustomMessagingManager _on;

		internal static bool IsHost
		{
			get
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton != (Object)null && singleton.IsListening)
				{
					return singleton.IsServer;
				}
				return false;
			}
		}

		internal static bool IsClientOnly
		{
			get
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton != (Object)null && singleton.IsListening && !singleton.IsServer)
				{
					return singleton.IsConnectedClient;
				}
				return false;
			}
		}

		internal static void EnsureRegistered()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.CustomMessagingManager == null)
			{
				_on = null;
			}
			else if (_on != singleton.CustomMessagingManager)
			{
				_on = singleton.CustomMessagingManager;
				try
				{
					_on.RegisterNamedMessageHandler("jacob.lematrix", new HandleNamedMessageDelegate(Receive));
				}
				catch (Exception ex)
				{
					L.Warn("Couldn't register the LeMatrix message: " + ex.Message);
				}
			}
		}

		private static void Receive(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
				if (num >= 1 && num <= 65536)
				{
					byte[] bytes = new byte[num];
					((FastBufferReader)(ref reader)).ReadBytesSafe(ref bytes, num, 0);
					Director.OnMessage(sender, bytes);
				}
			}
			catch (Exception e)
			{
				Safe.Report("Net.Receive", e);
			}
		}

		private unsafe static void Send(ulong client, byte[] bytes)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.CustomMessagingManager == null)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(bytes.Length + 8, (Allocator)2, bytes.Length + 64);
			try
			{
				int num = bytes.Length;
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(bytes, bytes.Length, 0);
				singleton.CustomMessagingManager.SendNamedMessage("jacob.lematrix", client, val, (NetworkDelivery)4);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		internal static void ToHost(ByteWriter w)
		{
			try
			{
				Send(0uL, w.ToArray());
			}
			catch (Exception e)
			{
				Safe.Report("Net.ToHost", e);
			}
		}

		internal static void ToClient(ulong id, ByteWriter w)
		{
			if (id == 0L)
			{
				return;
			}
			try
			{
				Send(id, w.ToArray());
			}
			catch (Exception e)
			{
				Safe.Report("Net.ToClient", e);
			}
		}

		internal static void ToClients(ByteWriter w)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				return;
			}
			byte[] bytes = w.ToArray();
			foreach (ulong connectedClientsId in singleton.ConnectedClientsIds)
			{
				if (connectedClientsId != 0L)
				{
					try
					{
						Send(connectedClientsId, bytes);
					}
					catch (Exception e)
					{
						Safe.Report("Net.ToClients", e);
					}
				}
			}
		}

		internal static List<ulong> RemoteClients()
		{
			List<ulong> list = new List<ulong>();
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				return list;
			}
			foreach (ulong connectedClientsId in singleton.ConnectedClientsIds)
			{
				if (connectedClientsId != 0L)
				{
					list.Add(connectedClientsId);
				}
			}
			return list;
		}

		internal static ByteWriter Msg(Op op)
		{
			ByteWriter byteWriter = new ByteWriter();
			byteWriter.U8((byte)op);
			return byteWriter;
		}
	}
	public enum RunMode
	{
		Survey,
		DryRun,
		PrepareTest,
		Live
	}
	public enum NavmeshMode
	{
		Surface,
		Local,
		Off
	}
	public enum LogDetail
	{
		Off,
		Info,
		Verbose
	}
	[BepInPlugin("jacob.lematrix", "LeMatrix", "1.0.5")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "jacob.lematrix";

		public const string Name = "LeMatrix";

		public const string Version = "1.0.5";

		public const int Protocol = 1;

		internal static Plugin Instance;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<RunMode> Mode;

		internal static ConfigEntry<float> DayChancePercent;

		internal static ConfigEntry<float> WindowStart;

		internal static ConfigEntry<float> WindowEnd;

		internal static ConfigEntry<int> MaxEventsPerDay;

		internal static ConfigEntry<int> MinRooms;

		internal static ConfigEntry<int> MaxRooms;

		internal static ConfigEntry<float> RestoreMinSeconds;

		internal static ConfigEntry<float> RestoreMaxSeconds;

		internal static ConfigEntry<string> ExitWeights;

		internal static ConfigEntry<float> RouteBonus;

		internal static ConfigEntry<float> CutClosestExitBonus;

		internal static ConfigEntry<float> ModeSameLinks;

		internal static ConfigEntry<float> ModeFewerLinks;

		internal static ConfigEntry<float> ModeSealOnly;

		internal static ConfigEntry<bool> AllowRotatedSelf;

		internal static ConfigEntry<int> CandidateTiles;

		internal static ConfigEntry<int> ClusterRadius;

		internal static ConfigEntry<float> DifferentPrefabBonus;

		internal static ConfigEntry<float> ExitNeighbourBonus;

		internal const string OldExitWeights = "0,8,5,3,2,1,1";

		internal const string NewExitWeights = "0,20,8,3,1,0,0";

		internal const string OldAllowedComponents = "JLL.Components.JModConfigGrabber";

		internal const string DefaultAllowedComponents = "JLL.Components.JModConfigGrabber, JLL.Components.Filters.LevelFilter, JLL.Components.Filters.DateFilter, JLL.Components.Filters.PlayerFilter, JLL.Components.JWeatherObject, JLL.Components.JMaterialReplacer, JLL.Components.RandomClipPlayer, JLL.Components.DayCycleAnimator, JLL.Components.DelayScript, JLL.Components.JLevelEventTriggers, WesleysInteriorTools.Features.MaterialReplacer, WesleysInteriorTools.Features.Hyxifier, WesleysInteriorTools.Features.MassAudioManager, WesleysInteriorTools.Features.AnimationAudioPlayer, UnityMeshSimplifier.LODBackupComponent, itolib.Behaviours.Helpers.SpecificDoorway";

		internal static ConfigEntry<bool> AdjacentCountsAsSeen;

		internal static ConfigEntry<bool> RadarCountsAsViewer;

		internal static ConfigEntry<bool> ClientVeto;

		internal static ConfigEntry<float> UnseenHoldSeconds;

		internal static ConfigEntry<float> PortalMargin;

		internal static ConfigEntry<float> TeleportCooldownSeconds;

		internal static ConfigEntry<float> PendingTimeoutSeconds;

		internal static ConfigEntry<bool> RestoreOnInverseTeleport;

		internal static ConfigEntry<bool> RequireWithinOriginalBounds;

		internal static ConfigEntry<NavmeshMode> Navmesh;

		internal static ConfigEntry<bool> AsyncInstantiate;

		internal static ConfigEntry<string> InteriorAllow;

		internal static ConfigEntry<string> InteriorDeny;

		internal static ConfigEntry<bool> AllowModdedComponents;

		internal static ConfigEntry<string> AllowedComponents;

		internal static readonly HashSet<string> AllowedComponentNames = new HashSet<string>(StringComparer.Ordinal);

		internal static ConfigEntry<LogDetail> LogLevel;

		internal static ConfigEntry<bool> SurveyOnLoad;

		internal static ConfigEntry<bool> ShowInPerfWatcher;

		internal static ConfigEntry<bool> ShowRooms;

		internal static ConfigEntry<bool> ShowRoomsWithDayInfo;

		internal static ConfigEntry<bool> ShowCandidates;

		internal static void RebuildAllowedComponents()
		{
			AllowedComponentNames.Clear();
			string[] array = (AllowedComponents.Value ?? "").Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length > 0)
				{
					AllowedComponentNames.Add(text);
				}
			}
		}

		private void Awake()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Expected O, but got Unknown
			Instance = this;
			L.Src = ((BaseUnityPlugin)this).Logger;
			BindConfig();
			Harmony h = new Harmony("jacob.lematrix");
			Patch(h, typeof(RoundManager), "FinishGeneratingLevel", null, "AfterFinishGeneratingLevel");
			Patch(h, typeof(StartOfRound), "ShipLeave", "BeforeShipLeave");
			Patch(h, typeof(StartOfRound), "ShipLeaveAutomatically", "BeforeShipLeave");
			Patch(h, typeof(StartOfRound), "ShipHasLeft", "BeforeLevelEnd");
			Patch(h, typeof(RoundManager), "UnloadSceneObjectsEarly", "BeforeLevelEnd");
			Patch(h, typeof(RoundManager), "DespawnPropsAtEndOfRound", "BeforeLevelEnd");
			Patch(h, typeof(EntranceTeleport), "TeleportPlayer", null, "AfterEntranceTeleport");
			Patch(h, typeof(EntranceTeleport), "TeleportPlayerClientRpc", null, "AfterEntranceTeleport");
			Patch(h, typeof(ShipTeleporter), "PressTeleportButtonOnLocalClient", null, "AfterTeleporterPressed");
			Patch(h, typeof(ShipTeleporter), "PressTeleportButtonClientRpc", null, "AfterTeleporterPressed");
			GameObject val = new GameObject("LeMatrixRunner")
			{
				hideFlags = (HideFlags)61
			};
			Object.DontDestroyOnLoad((Object)val);
			val.AddComponent<Runner>();
		}

		private void BindConfig()
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Expected O, but got Unknown
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Expected O, but got Unknown
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Expected O, but got Unknown
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Expected O, but got Unknown
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Expected O, but got Unknown
			//IL_035e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Expected O, but got Unknown
			//IL_0390: Unknown result type (might be due to invalid IL or missing references)
			//IL_039a: Expected O, but got Unknown
			//IL_03cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d7: Expected O, but got Unknown
			//IL_040a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0414: Expected O, but got Unknown
			//IL_04a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b1: Expected O, but got Unknown
			//IL_04e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ee: Expected O, but got Unknown
			//IL_0521: Unknown result type (might be due to invalid IL or missing references)
			//IL_052b: Expected O, but got Unknown
			//IL_059e: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a8: Expected O, but got Unknown
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master switch.");
			Mode = ((BaseUnityPlugin)this).Config.Bind<RunMode>("General", "Mode", RunMode.Live, "Survey = never swaps, writes the Survey to the log each landing. DryRun = rolls, plans and waits like the real thing but only logs what it would do; nothing changes in the world and nothing is sent to clients. PrepareTest = DryRun plus building each replacement hidden on the host and destroying it again (tests the build step, still invisible). Live = the real event (default). Survey, DryRun and PrepareTest are for testing.");
			DayChancePercent = ((BaseUnityPlugin)this).Config.Bind<float>("Event", "DayChancePercent", 4f, new ConfigDescription("Chance per landed day (0 to 100, decimals allowed).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			WindowStart = ((BaseUnityPlugin)this).Config.Bind<float>("Event", "WindowStart", 0.15f, new ConfigDescription("Earliest trigger, as a fraction of the day.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			WindowEnd = ((BaseUnityPlugin)this).Config.Bind<float>("Event", "WindowEnd", 0.8f, new ConfigDescription("Latest trigger. The event is dropped if nobody has gone inside by then.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			MaxEventsPerDay = ((BaseUnityPlugin)this).Config.Bind<int>("Event", "MaxEventsPerDay", 1, new ConfigDescription("Extra events need their own roll and start at least 90 s after the previous one restores.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 5), Array.Empty<object>()));
			MinRooms = ((BaseUnityPlugin)this).Config.Bind<int>("Rooms", "MinRooms", 1, new ConfigDescription("Fewest rooms per event (count is uniform between Min and Max).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 5), Array.Empty<object>()));
			MaxRooms = ((BaseUnityPlugin)this).Config.Bind<int>("Rooms", "MaxRooms", 5, new ConfigDescription("Most rooms per event (hard cap 5).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 5), Array.Empty<object>()));
			RestoreMinSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Rooms", "RestoreMinSeconds", 10f, new ConfigDescription("Shortest time before a room may restore.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 600f), Array.Empty<object>()));
			RestoreMaxSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Rooms", "RestoreMaxSeconds", 30f, new ConfigDescription("Longest time before a room may restore.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 600f), Array.Empty<object>()));
			ExitWeights = ((BaseUnityPlugin)this).Config.Bind<string>("Rooms", "ExitWeights", "0,20,8,3,1,0,0", "Weight by hops from the nearest exit tile (index = hops). Beyond the list = 0. Hop 0 (the exit tile) is never used. 1.0.4 default: hop 1 (the room right in front of an exit) dominates. Rooms on the target's route always count.");
			if (ExitWeights.Value.Replace(" ", "") == "0,8,5,3,2,1,1")
			{
				ExitWeights.Value = "0,20,8,3,1,0,0";
				L.Warn("LeMatrix 1.0.4: ExitWeights was the old default; changed to 0,20,8,3,1,0,0.");
			}
			RouteBonus = ((BaseUnityPlugin)this).Config.Bind<float>("Rooms", "RouteBonus", 2f, "Weight multiplier for tiles on a player's shortest route to their closest exit.");
			CutClosestExitBonus = ((BaseUnityPlugin)this).Config.Bind<float>("Rooms", "CutClosestExitBonus", 3f, "Weight multiplier for rooms and plans that cut a player off from their closest exit while another exit stays reachable.");
			ModeSameLinks = ((BaseUnityPlugin)this).Config.Bind<float>("Rooms", "ModeSameLinks", 30f, "Weight for swaps that keep every connection (corridor for corridor).");
			ModeFewerLinks = ((BaseUnityPlugin)this).Config.Bind<float>("Rooms", "ModeFewerLinks", 50f, "Weight for swaps that keep some connections and seal others.");
			ModeSealOnly = ((BaseUnityPlugin)this).Config.Bind<float>("Rooms", "ModeSealOnly", 20f, "Weight for sealing one connection without replacing the room.");
			AllowRotatedSelf = ((BaseUnityPlugin)this).Config.Bind<bool>("Rooms", "AllowRotatedSelf", true, "Allow the room's own prefab turned by 90/180/270 degrees as a candidate.");
			CandidateTiles = ((BaseUnityPlugin)this).Config.Bind<int>("Rooms", "CandidateTiles", 20, new ConfigDescription("How many of the highest-weighted rooms near the target get a full plan search per event.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 60), Array.Empty<object>()));
			ClusterRadius = ((BaseUnityPlugin)this).Config.Bind<int>("Rooms", "ClusterRadius", 6, new ConfigDescription("1.0.4: an event's rooms form one connected cluster within this many hops of the target player.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 15), Array.Empty<object>()));
			DifferentPrefabBonus = ((BaseUnityPlugin)this).Config.Bind<float>("Rooms", "DifferentPrefabBonus", 3f, new ConfigDescription("1.0.4: weight multiplier for a different prefab over the room's own prefab turned.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 20f), Array.Empty<object>()));
			ExitNeighbourBonus = ((BaseUnityPlugin)this).Config.Bind<float>("Rooms", "ExitNeighbourBonus", 3f, new ConfigDescription("1.0.4: weight multiplier for the room right next to the target's closest exit.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 20f), Array.Empty<object>()));
			AdjacentCountsAsSeen = ((BaseUnityPlugin)this).Config.Bind<bool>("Visibility", "AdjacentCountsAsSeen", true, "Tiles next to a viewer's tile count as seen (latency margin).");
			RadarCountsAsViewer = ((BaseUnityPlugin)this).Config.Bind<bool>("Visibility", "RadarCountsAsViewer", true, "The ship radar view counts when someone alive is in the ship.");
			ClientVeto = ((BaseUnityPlugin)this).Config.Bind<bool>("Visibility", "ClientVeto", true, "Ask every client before committing or restoring.");
			UnseenHoldSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Visibility", "UnseenHoldSeconds", 1f, new ConfigDescription("How long a room must stay unseen before a change.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 30f), Array.Empty<object>()));
			PortalMargin = ((BaseUnityPlugin)this).Config.Bind<float>("Visibility", "PortalMargin", 0.5f, new ConfigDescription("Extra metres added round every doorway opening in the line-of-sight test (bigger = more cautious).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>()));
			TeleportCooldownSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Safety", "TeleportCooldownSeconds", 3f, new ConfigDescription("No commits or restores within this long of any entrance or ship teleport (10 s after an inverse teleporter press).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>()));
			RestoreOnInverseTeleport = ((BaseUnityPlugin)this).Config.Bind<bool>("Safety", "RestoreOnInverseTeleport", true, "Restore everything when an inverse teleporter is pressed.");
			RequireWithinOriginalBounds = ((BaseUnityPlugin)this).Config.Bind<bool>("Safety", "RequireWithinOriginalBounds", true, "A replacement must fit inside the original room's box. Keeps culling, visibility and AI nodes valid. The Survey shows how many extra options turning this off would give.");
			PendingTimeoutSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Safety", "PendingTimeoutSeconds", 60f, new ConfigDescription("A prepared room that can't be swapped unseen within this long is dropped.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 600f), Array.Empty<object>()));
			Navmesh = ((BaseUnityPlugin)this).Config.Bind<NavmeshMode>("Navmesh", "Mode", NavmeshMode.Surface, "Surface = NavMeshSurface.UpdateNavMesh on the dungeon surfaces; Local = bounded rebuild round the room under PathfindingLib's lock; Off = no rebuild (testing only).");
			AsyncInstantiate = ((BaseUnityPlugin)this).Config.Bind<bool>("Navmesh", "AsyncInstantiate", true, "Build replacements with Object.InstantiateAsync (off the main thread). Off = plain Instantiate.");
			InteriorAllow = ((BaseUnityPlugin)this).Config.Bind<string>("Interiors", "Allow", "*", "LLL DungeonNames (or DunGen flow names) where LeMatrix may run. * = every interior (the per-room safety checks still decide which rooms can change). The vanilla-only list was: Facility,Facility3Exits,Haunted Mansion,Mineshaft,Expanded facility");
			InteriorDeny = ((BaseUnityPlugin)this).Config.Bind<string>("Interiors", "Deny", "", "Always wins over Allow.");
			AllowModdedComponents = ((BaseUnityPlugin)this).Config.Bind<bool>("Interiors", "AllowModdedComponents", false, "Allow tiles containing components from assemblies outside Unity, DunGen and the game.");
			AllowedComponents = ((BaseUnityPlugin)this).Config.Bind<string>("Interiors", "AllowedComponents", "JLL.Components.JModConfigGrabber, JLL.Components.Filters.LevelFilter, JLL.Components.Filters.DateFilter, JLL.Components.Filters.PlayerFilter, JLL.Components.JWeatherObject, JLL.Components.JMaterialReplacer, JLL.Components.RandomClipPlayer, JLL.Components.DayCycleAnimator, JLL.Components.DelayScript, JLL.Components.JLevelEventTriggers, WesleysInteriorTools.Features.MaterialReplacer, WesleysInteriorTools.Features.Hyxifier, WesleysInteriorTools.Features.MassAudioManager, WesleysInteriorTools.Features.AnimationAudioPlayer, UnityMeshSimplifier.LODBackupComponent, itolib.Behaviours.Helpers.SpecificDoorway", "Full type names of modded components that are safe to copy (comma separated): local only, no network objects, no lasting side effects (they toggle children, swap materials or play sounds when the room loads). Network components (NetworkObject, NetworkBehaviour, InteractTrigger) are always refused. Read on start and when changed.");
			if (AllowedComponents.Value.Trim() == "JLL.Components.JModConfigGrabber")
			{
				AllowedComponents.Value = "JLL.Components.JModConfigGrabber, JLL.Components.Filters.LevelFilter, JLL.Components.Filters.DateFilter, JLL.Components.Filters.PlayerFilter, JLL.Components.JWeatherObject, JLL.Components.JMaterialReplacer, JLL.Components.RandomClipPlayer, JLL.Components.DayCycleAnimator, JLL.Components.DelayScript, JLL.Components.JLevelEventTriggers, WesleysInteriorTools.Features.MaterialReplacer, WesleysInteriorTools.Features.Hyxifier, WesleysInteriorTools.Features.MassAudioManager, WesleysInteriorTools.Features.AnimationAudioPlayer, UnityMeshSimplifier.LODBackupComponent, itolib.Behaviours.Helpers.SpecificDoorway";
				L.Warn("LeMatrix 1.0.4: AllowedComponents was the 1.0.3 default; extended to the reviewed list.");
			}
			RebuildAllowedComponents();
			AllowedComponents.SettingChanged += delegate
			{
				RebuildAllowedComponents();
				Components.ClearCache();
			};
			LogLevel = ((BaseUnityPlugin)this).Config.Bind<LogDetail>("Debug", "LogLevel", LogDetail.Info, "Host log detail: Off, Info, Verbose. Clients never log.");
			SurveyOnLoad = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "SurveyOnLoad", false, "Write the Survey to the host log every level load.");
			ShowRooms = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "ShowRooms", false, "Host only, live. Draws see-through boxes round rooms: red = changed (in DryRun: would have been changed, labelled DryRun), yellow = planned or prepared and waiting to be unseen, green = just restored (fades over 10 s), grey = candidates (see ShowCandidates). Each box is labelled, the Status list sits on the left, the radar gets flat marks, and a 6 s note explains each day's result and each DNC Trigger. Costs nothing while off; nothing runs on a client.");
			ShowRoomsWithDayInfo = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "ShowRoomsWithDayInfo", true, "Host only. Also show the ShowRooms view while PerfWatcher's Day Info panel (I) is open, so I toggles it live. Set false for normal play if you don't want the hidden event spoiled.");
			ShowCandidates = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "ShowCandidates", true, "With the ShowRooms view on in Survey or DryRun mode, also draw grey boxes round the rooms the picker could choose (exit weight above 0, eligible, at least one plan). Counted once per day, 3 s after landing.");
			ShowInPerfWatcher = ((BaseUnityPlugin)this).Config.Bind<bool>("Integration", "ShowInPerfWatcher", false, "Fill LeMatrix.MatrixState for PerfWatcher's Day Info panel.");
		}

		private void Patch(Harmony h, Type type, string method, string prefix = null, string postfix = null)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			MethodInfo methodInfo = AccessTools.Method(type, method, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				L.Warn("Hook target missing: " + type.Name + "." + method + " (that safety feature is off)");
				return;
			}
			try
			{
				h.Patch((MethodBase)methodInfo, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Hooks), prefix, (Type[])null), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Hooks), postfix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				L.Warn("Couldn't hook " + type.Name + "." + method + ": " + ex.Message);
			}
		}
	}
	internal class Runner : MonoBehaviour
	{
		private static readonly Action DoUpdate = Director.Update;

		private static readonly Action DoLateUpdate = Director.LateUpdate;

		private void Awake()
		{
			Director.Runner = (MonoBehaviour)(object)this;
		}

		private void Update()
		{
			Safe.Run("Runner.Update", DoUpdate);
			try
			{
				RoomView.Tick();
			}
			catch (Exception e)
			{
				Safe.Report("RoomView.Tick", e);
			}
		}

		private void LateUpdate()
		{
			Safe.Run("Runner.LateUpdate", DoLateUpdate);
		}
	}
	internal static class L
	{
		internal static ManualLogSource Src;

		private static readonly List<KeyValuePair<bool, string>> Held = new List<KeyValuePair<bool, string>>();

		internal static bool Verbose
		{
			get
			{
				if (Plugin.LogLevel != null)
				{
					return Plugin.LogLevel.Value == LogDetail.Verbose;
				}
				return false;
			}
		}

		private static int Role()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
			{
				return 0;
			}
			if (!singleton.IsServer)
			{
				return -1;
			}
			return 1;
		}

		internal static void Info(string s)
		{
			if (Plugin.LogLevel == null || Plugin.LogLevel.Value != LogDetail.Off)
			{
				Emit(warn: false, s);
			}
		}

		internal static void Debug(string s)
		{
			if (Verbose)
			{
				Emit(warn: false, s);
			}
		}

		internal static void Warn(string s)
		{
			Emit(warn: true, s);
		}

		internal static void Flush()
		{
			int num = Role();
			if (num == 0 || Held.Count == 0)
			{
				return;
			}
			if (num > 0 && Src != null)
			{
				foreach (KeyValuePair<bool, string> item in Held)
				{
					if (item.Key)
					{
						Src.LogWarning((object)item.Value);
					}
					else
					{
						Src.LogInfo((object)item.Value);
					}
				}
			}
			Held.Clear();
		}

		private static void Emit(bool warn, string s)
		{
			int num = Role();
			if (num == 0)
			{
				if (Held.Count < 40)
				{
					Held.Add(new KeyValuePair<bool, string>(warn, s));
				}
				return;
			}
			if (num < 0)
			{
				Held.Clear();
				return;
			}
			Flush();
			if (Src != null)
			{
				if (warn)
				{
					Src.LogWarning((object)s);
				}
				else
				{
					Src.LogInfo((object)s);
				}
			}
		}
	}
	internal static class Safe
	{
		private static readonly HashSet<string> Seen = new HashSet<string>();

		internal static int Errors;

		internal static void Run(string site, Action a)
		{
			try
			{
				a();
			}
			catch (Exception e)
			{
				Report(site, e);
			}
		}

		internal static void Report(string site, Exception e)
		{
			Errors++;
			try
			{
				if (Seen.Add(site))
				{
					L.Warn("Error in " + site + " (handled): " + e);
				}
				else
				{
					L.Debug("Repeat error in " + site + ": " + e.Message);
				}
			}
			catch
			{
			}
		}
	}
	internal static class QuietTypes
	{
		private static readonly Dictionary<string, Type> _hits;

		private static readonly Dictionary<string, int> _misses;

		private static readonly object _lock;

		private static int _generation;

		static QuietTypes()
		{
			_hits = new Dictionary<string, Type>(StringComparer.Ordinal);
			_misses = new Dictionary<string, int>(StringComparer.Ordinal);
			_lock = new object();
			try
			{
				AppDomain.CurrentDomain.AssemblyLoad += delegate
				{
					lock (_lock)
					{
						_generation++;
					}
				};
			}
			catch
			{
			}
		}

		internal static Type Find(string fullName)
		{
			if (string.IsNullOrEmpty(fullName))
			{
				return null;
			}
			int generation;
			lock (_lock)
			{
				if (_hits.TryGetValue(fullName, out var value))
				{
					return value;
				}
				if (_misses.TryGetValue(fullName, out var value2) && value2 == _generation)
				{
					return null;
				}
				generation = _generation;
			}
			Type type = Scan(fullName);
			lock (_lock)
			{
				if (type != null)
				{
					_hits[fullName] = type;
					_misses.Remove(fullName);
				}
				else
				{
					_misses[fullName] = generation;
				}
			}
			return type;
		}

		private static Type Scan(string fullName)
		{
			Assembly[] assemblies;
			try
			{
				assemblies = AppDomain.CurrentDomain.GetAssemblies();
			}
			catch
			{
				return null;
			}
			Assembly[] array = assemblies;
			foreach (Assembly assembly in array)
			{
				Type type = null;
				try
				{
					type = assembly.GetType(fullName, throwOnError: false);
				}
				catch
				{
				}
				if (type != null)
				{
					return type;
				}
			}
			return null;
		}
	}
	internal static class RoomView
	{
		internal sealed class Entry
		{
			public int Id;

			public int Tile;

			public MarkKind Kind;

			public Box Box;

			public Vector3 Anchor;

			public bool DryRun;

			public bool Seen;

			public string Head;

			public string Label;

			public float RestoredAt;

			public RecState LastState = (RecState)(-1);

			public MarkKind LastKind;

			public int LastSec = -2;

			public string LastWaiting;

			public Vector2 Size;

			public string SizeFor;
		}

		internal static readonly List<Entry> Entries = new List<Entry>(16);

		internal static readonly List<Entry> Cands = new List<Entry>(64);

		private static readonly Dictionary<int, Entry> ById = new Dictionary<int, Entry>();

		internal static bool On;

		internal static bool CandsVisible;

		internal static string StatusText;

		internal static string NoteText;

		internal static float NoteUntil;

		private static GameObject _root;

		private static GameObject _worldGo;

		private static GameObject _radarGo;

		private static Mesh _worldMesh;

		private static Mesh _radarMesh;

		private static Material _mat;

		private static bool _matTried;

		private static bool _radarTried;

		private static bool _radarOk;

		private static RoomOverlay _overlay;

		private static float _nextPoll;

		private static float _nextRefresh;

		private static float _nextStatus;

		private static bool _dirty;

		private static DungeonView _forView;

		private static Day _forDay;

		private static Day _notedDay;

		private static bool _candsDone;

		private static int _candCount = -1;

		private static string _seenResult;

		private static readonly V3[] Buf = new V3[Math.Max(96, 20)];

		private static readonly List<Vector3> WV = new List<Vector3>(2048);

		private static readonly List<Vector3> RV = new List<Vector3>(512);

		private static readonly List<Color> WC = new List<Color>(2048);

		private static readonly List<Color> RC = new List<Color>(512);

		private static readonly List<int> WI = new List<int>(3072);

		private static readonly List<int> RI = new List<int>(768);

		private const int MaxBoxes = 400;

		internal static readonly Color Red = new Color(1f, 0.15f, 0.1f, 1f);

		internal static readonly Color Yellow = new Color(1f, 0.85f, 0.1f, 1f);

		internal static readonly Color Green = new Color(0.2f, 1f, 0.3f, 1f);

		internal static readonly Color Grey = new Color(0.65f, 0.65f, 0.65f, 0.55f);

		private static bool _dayTried;

		private static FieldInfo _pwRunner;

		private static FieldInfo _pwDay;

		private static FieldRef<object, bool> _pwOpen;

		internal static Color ColourOf(Entry e)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			switch (e.Kind)
			{
			case MarkKind.Active:
				return Red;
			case MarkKind.Waiting:
				return Yellow;
			case MarkKind.Restored:
			{
				Color green = Green;
				green.a = (float)RoomMarks.RestoredAlpha(Time.time - e.RestoredAt);
				return green;
			}
			default:
				return Grey;
			}
		}

		internal static void Tick()
		{
			if (Plugin.ShowRooms == null)
			{
				return;
			}
			if (!Net.IsHost)
			{
				if (On)
				{
					SetOn(on: false);
				}
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup >= _nextPoll)
			{
				_nextPoll = realtimeSinceStartup + 0.25f;
				bool flag = Plugin.ShowRooms.Value || (Plugin.ShowRoomsWithDayInfo.Value && DayInfoOpen());
				if (flag != On)
				{
					SetOn(flag);
				}
			}
			if (On && realtimeSinceStartup >= _nextRefresh)
			{
				_nextRefresh = realtimeSinceStartup + 0.1f;
				Refresh(realtimeSinceStartup);
			}
		}

		private static void SetOn(bool on)
		{
			On = on;
			if (on)
			{
				EnsureObjects();
				_nextRefresh = 0f;
				_nextStatus = 0f;
				_dirty = true;
				L.Info("ShowRooms view on (host only)" + (((Object)(object)_mat == (Object)null) ? "; no line shader was found, so only the labels, list and notes are drawn" : "") + ".");
			}
			else
			{
				Entries.Clear();
				ById.Clear();
				_forView = null;
				_forDay = null;
				_candsDone = false;
				_candCount = -1;
				Cands.Clear();
				StatusText = null;
				NoteText = null;
				L.Info("ShowRooms view off.");
			}
			if ((Object)(object)_root != (Object)null)
			{
				_root.SetActive(on);
			}
		}

		private static void Refresh(float real)
		{
			DungeonView view = Director.View;
			Day today = Director.Today;
			if (view != _forView || today != _forDay)
			{
				_forView = view;
				_forDay = today;
				Entries.Clear();
				ById.Clear();
				Cands.Clear();
				_candsDone = false;
				_candCount = -1;
				_dirty = true;
			}
			if (view != null && today != null && !_candsDone && today.LandedAt >= 0f && Time.time - today.LandedAt > 3f)
			{
				_candsDone = true;
				Safe.Run("RoomView.Candidates", delegate
				{
					//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
					//IL_00de: Unknown result type (might be due to invalid IL or missing references)
					Stopwatch stopwatch = Stopwatch.StartNew();
					List<int> list = Director.CandidateTiles();
					_candCount = list.Count;
					foreach (int item in list)
					{
						if (Cands.Count >= 200)
						{
							break;
						}
						Box box = view.Bounds[item];
						string text = (((Object)(object)view.Tiles[item] != (Object)null && (Object)(object)view.Tiles[item].Prefab != (Object)null) ? ((Object)view.Tiles[item].Prefab).name : "?");
						Entry entry = new Entry
						{
							Id = -1,
							Tile = item,
							Kind = MarkKind.Candidate,
							Box = box,
							Anchor = Conv.U(box.Center),
							Head = "tile " + item + " " + text
						};
						entry.Label = RoomMarks.Label(entry.Head, MarkKind.Candidate, 0, null, dryRun: false);
						Cands.Add(entry);
					}
					L.Info("ShowRooms: " + list.Count + " candidate rooms on " + view.Interior + " (" + stopwatch.Elapsed.TotalMilliseconds.ToString("0") + " ms, read-only).");
				});
				_dirty = true;
			}
			if (today != null && _notedDay != today && today.LandedAt >= 0f && Time.time - today.LandedAt > 3f)
			{
				_notedDay = today;
				_seenResult = today.LastResult;
				Note(RoomMarks.DayNote(DayInput(view, today)));
			}
			else if (today != null && _notedDay == today && (object)today.LastResult != _seenResult)
			{
				_seenResult = today.LastResult;
				Note(RoomMarks.ResultNote(today.LastResult, Plugin.Mode.Value.ToString()));
			}
			PollRecs();
			RunMode value = Plugin.Mode.Value;
			bool flag = Plugin.ShowCandidates.Value && (value == RunMode.Survey || value == RunMode.DryRun) && Cands.Count > 0;
			if (flag != CandsVisible)
			{
				CandsVisible = flag;
				_dirty = true;
			}
			if (real >= _nextStatus)
			{
				_nextStatus = real + 0.5f;
				try
				{
					StatusText = string.Join("\n", Api.Status());
				}
				catch
				{
					StatusText = null;
				}
			}
			if (_dirty)
			{
				_dirty = false;
				try
				{
					BuildMeshes();
				}
				catch (Exception e)
				{
					Safe.Report("RoomView.Mesh", e);
				}
			}
		}

		private static void PollRecs()
		{
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < Entries.Count; i++)
			{
				Entries[i].Seen = false;
			}
			List<Rec> recs = Director.Recs;
			float time = Time.time;
			for (int j = 0; j < recs.Count; j++)
			{
				Rec rec = recs[j];
				if (rec != null && !rec.IsOver && rec.Plan != null && rec.Msg != null)
				{
					if (!ById.TryGetValue(rec.Id, out var value))
					{
						value = new Entry
						{
							Id = rec.Id,
							Tile = ((rec.Pick != null) ? rec.Pick.Tile : (-1)),
							Head = RoomMarks.WithCluster(RoomMarks.Head(rec.Id, rec.Plan.Mode, rec.Msg.Prefab), rec.Cluster)
						};
						ById[rec.Id] = value;
						Entries.Add(value);
						_dirty = true;
					}
					value.Seen = true;
					value.DryRun = rec.Mode == RunMode.DryRun;
					MarkKind markKind = (rec.IsCommitted ? MarkKind.Active : MarkKind.Waiting);
					if (markKind != value.Kind)
					{
						value.Kind = markKind;
						_dirty = true;
					}
					if (!SameBox(value.Box, rec.Bounds))
					{
						value.Box = rec.Bounds;
						value.Anchor = Conv.U(rec.Bounds.Center);
						_dirty = true;
					}
					int num = ((rec.State == RecState.Active) ? RoomMarks.Countdown(rec.RestoreAt, time) : 0);
					if (value.LastState != rec.State || value.LastKind != markKind || value.LastSec != num || !string.Equals(value.LastWaiting, rec.Waiting))
					{
						value.LastState = rec.State;
						value.LastKind = markKind;
						value.LastSec = num;
						value.LastWaiting = rec.Waiting;
						value.Label = RoomMarks.Label(value.Head, markKind, num, Detail(rec), value.DryRun);
					}
				}
			}
			for (int num2 = Entries.Count - 1; num2 >= 0; num2--)
			{
				Entry entry = Entries[num2];
				if (!entry.Seen)
				{
					if (entry.Kind == MarkKind.Active)
					{
						entry.Kind = MarkKind.Restored;
						entry.RestoredAt = time;
						entry.LastKind = MarkKind.Restored;
						entry.Label = RoomMarks.Label(entry.Head, MarkKind.Restored, 0, null, entry.DryRun);
						_dirty = true;
					}
					else if (entry.Kind == MarkKind.Restored)
					{
						_dirty = true;
						if ((double)(time - entry.RestoredAt) >= 10.0)
						{
							Entries.RemoveAt(num2);
							ById.Remove(entry.Id);
						}
					}
					else
					{
						Entries.RemoveAt(num2);
						ById.Remove(entry.Id);
						_dirty = true;
					}
				}
			}
		}

		private static bool SameBox(Box a, Box b)
		{
			if (a.Min.X == b.Min.X && a.Min.Y == b.Min.Y && a.Min.Z == b.Min.Z && a.Max.X == b.Max.X && a.Max.Y == b.Max.Y)
			{
				return a.Max.Z == b.Max.Z;
			}
			return false;
		}

		private static string Detail(Rec r)
		{
			switch (r.State)
			{
			case RecState.Preparing:
				if (r.Mode != RunMode.PrepareTest)
				{
					return "preparing";
				}
				return "building hidden (PrepareTest)";
			case R