Decompiled source of PerfWatcher v1.5.1

PerfWatcher.dll

Decompiled 5 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using PerfWatcher.DayInfo;
using SizeScaling;
using TMPro;
using Unity.Netcode;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.LowLevel;
using UnityEngine.Profiling;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[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("PerfWatcher")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.5.1.0")]
[assembly: AssemblyInformationalVersion("1.5.1")]
[assembly: AssemblyProduct("PerfWatcher")]
[assembly: AssemblyTitle("PerfWatcher")]
[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.5.1.0")]
namespace PerfWatcher
{
	internal sealed class Context
	{
		public string Scene = "?";

		public string Moon = "";

		public string Interior = "";

		public string Weather = "";

		public string Location = "";

		public string Clock = "";

		public string Role = "offline";

		public string Phase = "";

		public float SizeMult;

		public int Players = 1;

		public bool Multiplayer;

		public bool Generating;

		public double GenStart;

		public int GenStutters;

		public double GenWorst;

		public readonly List<string> FrameEvents = new List<string>();

		private readonly Runner _r;

		private bool _subscribed;

		private DungeonGenerator _gen;

		private bool _hasRound;

		private bool _landed;

		private bool _leaving;

		private bool _orbit;

		private bool _inside;

		private bool _inShip;

		private bool _dead;

		private int _players = -1;

		private int _enemies = -1;

		private SelectableLevel _level;

		private double _nextNames;

		private double _nextSettings;

		private bool _genEndPending;

		private double _genMs;

		private string _genStatus;

		private string _genFlow;

		private string _settings;

		private static PropertyInfo _lllCurrent;

		private static MemberInfo _lllName;

		private static bool _lllTried;

		private static readonly Dictionary<int, string> _weatherNames = new Dictionary<int, string>();

		public Context(Runner r)
		{
			_r = r;
		}

		public void Start()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (!_subscribed)
			{
				SceneManager.sceneLoaded += OnSceneLoaded;
				SceneManager.sceneUnloaded += OnSceneUnloaded;
				_subscribed = true;
			}
			Scene activeScene = SceneManager.GetActiveScene();
			Scene = ((Scene)(ref activeScene)).name;
			_players = -1;
			_enemies = -1;
			_level = null;
			_hasRound = false;
			_settings = null;
			RefreshNames();
			_settings = SettingsString();
		}

		public void Stop()
		{
			if (_subscribed)
			{
				SceneManager.sceneLoaded -= OnSceneLoaded;
				SceneManager.sceneUnloaded -= OnSceneUnloaded;
				_subscribed = false;
			}
			Unhook();
			Generating = false;
			_genEndPending = false;
		}

		private void Unhook()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			if (_gen != null)
			{
				try
				{
					_gen.OnGenerationStatusChanged -= new GenerationStatusDelegate(OnGenStatus);
				}
				catch
				{
				}
				_gen = null;
			}
		}

		private unsafe void OnSceneLoaded(Scene s, LoadSceneMode mode)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((int)mode == 0)
				{
					Scene = ((Scene)(ref s)).name;
				}
				Event("scene_loaded", "\"name\":\"" + Json.Esc(((Scene)(ref s)).name) + "\",\"mode\":\"" + ((object)(*(LoadSceneMode*)(&mode))/*cast due to .constrained prefix*/).ToString() + "\"");
			}
			catch
			{
			}
		}

		private void OnSceneUnloaded(Scene s)
		{
			try
			{
				Event("scene_unloaded", "\"name\":\"" + Json.Esc(((Scene)(ref s)).name) + "\"");
			}
			catch
			{
			}
		}

		private unsafe void OnGenStatus(DungeonGenerator g, GenerationStatus status)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				bool flag = (int)status == 8 || (int)status == 9;
				if (!flag && (int)status != 0 && !Generating)
				{
					Generating = true;
					GenStart = _r.Now;
					GenStutters = 0;
					GenWorst = 0.0;
					_genEndPending = false;
					_genFlow = SafeName((Object)(object)g.DungeonFlow);
					Event("gen_start", "\"flow\":\"" + Json.Esc(_genFlow) + "\",\"size\":" + Json.N(g.LengthMultiplier));
				}
				else if (flag && Generating)
				{
					_genMs = (_r.Now - GenStart) * 1000.0;
					_genStatus = ((object)(*(GenerationStatus*)(&status))/*cast due to .constrained prefix*/).ToString();
					_genEndPending = true;
				}
			}
			catch
			{
			}
		}

		public void EndFrame()
		{
			if (_genEndPending)
			{
				_genEndPending = false;
				Generating = false;
				Interior = InteriorName();
				string text = "\"flow\":\"" + Json.Esc(_genFlow) + "\",\"name\":\"" + Json.Esc(Interior) + "\",\"ms\":" + Json.N(_genMs) + ",\"status\":\"" + _genStatus + "\",\"long\":" + GenStutters + ",\"worst\":" + Json.N(GenWorst);
				Event("gen_end", text);
				if (_r.St.Ep != null)
				{
					_r.St.Ep.Gen = "{" + text + "}";
				}
			}
			FrameEvents.Clear();
		}

		private void Event(string kind, string fields)
		{
			FrameEvents.Add(kind);
			_r.St.Attach(kind, _r.Now);
			Runner.Session?.Context(kind, fields, this);
		}

		private static string SafeName(Object o)
		{
			try
			{
				return (o != (Object)null) ? o.name : "";
			}
			catch
			{
				return "";
			}
		}

		private string InteriorName()
		{
			try
			{
				if (!_lllTried)
				{
					_lllTried = true;
					Type type = ModTimer.FindType("LethalLevelLoader.DungeonManager");
					_lllCurrent = ((type != null) ? AccessTools.Property(type, "CurrentExtendedDungeonFlow") : null);
					Type type2 = ModTimer.FindType("LethalLevelLoader.ExtendedDungeonFlow");
					if (type2 != null)
					{
						_lllName = (MemberInfo)(((object)AccessTools.Property(type2, "DungeonName")) ?? ((object)AccessTools.Field(type2, "dungeonDisplayName")));
					}
				}
				if (_lllCurrent != null && _lllName != null)
				{
					object value = _lllCurrent.GetValue(null, null);
					if (value != null)
					{
						string text = ((_lllName is PropertyInfo propertyInfo) ? propertyInfo.GetValue(value, null) : ((FieldInfo)_lllName).GetValue(value)) as string;
						if (!string.IsNullOrEmpty(text))
						{
							return text;
						}
					}
				}
			}
			catch
			{
			}
			return _genFlow ?? "";
		}

		public void LeverPulled()
		{
			if (_r.St.Ep == null || !(_r.St.Ep.Name == "landing"))
			{
				StartOfRound instance = StartOfRound.Instance;
				Event("lever", "\"moon\":\"" + Json.Esc(((Object)(object)instance != (Object)null) ? LevelName(instance.currentLevel) : "") + "\"");
				_r.St.BeginEpisode("landing", _r.Now);
			}
		}

		public void Poll()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			double now = _r.Now;
			try
			{
				RoundManager instance = RoundManager.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					RuntimeDungeon dungeonGenerator = instance.dungeonGenerator;
					DungeonGenerator val = (((Object)(object)dungeonGenerator != (Object)null) ? dungeonGenerator.Generator : null);
					if (val != _gen)
					{
						Unhook();
						_gen = val;
						if (val != null)
						{
							val.OnGenerationStatusChanged += new GenerationStatusDelegate(OnGenStatus);
						}
					}
					int num = instance.SpawnedEnemies?.Count ?? 0;
					if (_enemies >= 0 && num > _enemies)
					{
						FrameEvents.Add("enemy_spawn");
					}
					_enemies = num;
				}
				StartOfRound instance2 = StartOfRound.Instance;
				if ((Object)(object)instance2 != (Object)null)
				{
					if (!_hasRound)
					{
						_hasRound = true;
						_orbit = instance2.inShipPhase;
						_landed = instance2.shipHasLanded;
						_leaving = instance2.shipIsLeaving;
						_level = instance2.currentLevel;
						_players = instance2.connectedPlayersAmount;
					}
					if (instance2.inShipPhase != _orbit)
					{
						_orbit = instance2.inShipPhase;
						if (_orbit)
						{
							Event("orbit", null);
							_r.St.EndEpisodeAfter(now, 5.0);
						}
						else
						{
							Event("leave_orbit", "\"moon\":\"" + Json.Esc(LevelName(instance2.currentLevel)) + "\"");
							if (_r.St.Ep == null || _r.St.Ep.Name != "landing")
							{
								_r.St.BeginEpisode("landing", now);
							}
						}
					}
					if (instance2.shipHasLanded != _landed)
					{
						_landed = instance2.shipHasLanded;
						if (_landed)
						{
							Event("landed", "\"moon\":\"" + Json.Esc(LevelName(instance2.currentLevel)) + "\"");
							if (_r.St.Ep != null && _r.St.Ep.Name == "landing")
							{
								_r.St.EndEpisodeAfter(now, 2.0);
							}
						}
					}
					if (instance2.shipIsLeaving != _leaving)
					{
						_leaving = instance2.shipIsLeaving;
						if (_leaving)
						{
							Event("takeoff", null);
							_r.St.BeginEpisode("takeoff", now);
						}
					}
					if ((Object)(object)instance2.currentLevel != (Object)(object)_level)
					{
						_level = instance2.currentLevel;
						Event("moon", "\"moon\":\"" + Json.Esc(LevelName(_level)) + "\"");
					}
					int connectedPlayersAmount = instance2.connectedPlayersAmount;
					if (connectedPlayersAmount != _players)
					{
						if (_players >= 0)
						{
							bool flag = connectedPlayersAmount > _players;
							Event(flag ? "player_join" : "player_leave", "\"players\":" + (connectedPlayersAmount + 1));
							if (flag && _r.St.Ep == null)
							{
								_r.St.BeginEpisode("player_join", now);
								_r.St.EndEpisodeAfter(now, 8.0);
							}
						}
						_players = connectedPlayersAmount;
					}
					PlayerControllerB val2 = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
					if ((Object)(object)val2 != (Object)null)
					{
						bool isPlayerDead = val2.isPlayerDead;
						bool flag2 = !isPlayerDead && val2.isInsideFactory;
						bool inShip = !isPlayerDead && val2.isInHangarShipRoom;
						if (flag2 != _inside)
						{
							_inside = flag2;
							Event(flag2 ? "enter_facility" : "exit_facility", null);
						}
						if (isPlayerDead && !_dead)
						{
							Event("local_death", null);
						}
						_inShip = inShip;
						_dead = isPlayerDead;
					}
				}
				else
				{
					_hasRound = false;
				}
			}
			catch
			{
			}
			if (Generating && !_genEndPending && now - GenStart > 120.0)
			{
				_genMs = (now - GenStart) * 1000.0;
				_genStatus = "gave up waiting (120 s)";
				_genEndPending = true;
			}
			if (now >= _nextNames)
			{
				_nextNames = now + 0.25;
				RefreshNames();
			}
			if (now >= _nextSettings)
			{
				_nextSettings = now + 1.0;
				string text = SettingsString();
				if (_settings != null && text != _settings)
				{
					Event("settings", text);
				}
				_settings = text;
			}
		}

		public static string SettingsString()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return "\"res\":\"" + Screen.width + "x" + Screen.height + "\",\"mode\":\"" + ((object)Screen.fullScreenMode/*cast due to .constrained prefix*/).ToString() + "\",\"vsync\":" + QualitySettings.vSyncCount + ",\"fpsCap\":" + Application.targetFrameRate + ",\"quality\":" + QualitySettings.GetQualityLevel();
			}
			catch
			{
				return "";
			}
		}

		private static string LevelName(SelectableLevel l)
		{
			try
			{
				return ((Object)(object)l != (Object)null) ? l.PlanetName : "";
			}
			catch
			{
				return "";
			}
		}

		private void RefreshNames()
		{
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Expected I4, but got Unknown
			try
			{
				StartOfRound instance = StartOfRound.Instance;
				NetworkManager singleton = NetworkManager.Singleton;
				bool flag = (Object)(object)singleton != (Object)null && singleton.IsListening;
				Role = ((!flag) ? "offline" : (singleton.IsHost ? "host" : (singleton.IsClient ? "client" : "server")));
				Players = ((!((Object)(object)instance != (Object)null)) ? 1 : (instance.connectedPlayersAmount + 1));
				Multiplayer = flag && (singleton.IsHost ? (Players > 1) : singleton.IsClient);
				if ((Object)(object)instance == (Object)null)
				{
					Moon = "";
					Phase = "menu";
					Location = "";
					Clock = "";
					Weather = "";
					Interior = "";
					return;
				}
				Moon = LevelName(instance.currentLevel);
				bool flag2 = _r.St.Ep != null && _r.St.Ep.Name == "landing";
				Phase = ((!instance.inShipPhase) ? (instance.shipIsLeaving ? "leaving" : (instance.shipHasLanded ? "landed" : "landing")) : (flag2 ? "loading level" : "orbit"));
				Location = (_dead ? "dead" : (_inside ? "inside" : (_inShip ? "ship" : "outside")));
				TimeOfDay instance2 = TimeOfDay.Instance;
				if ((Object)(object)instance2 != (Object)null)
				{
					Weather = (instance.inShipPhase ? "" : WeatherName((int)instance2.currentLevelWeather));
					if (!instance.inShipPhase)
					{
						float num = 6f + instance2.normalizedTimeOfDay * (float)((instance2.numberOfHours > 0) ? instance2.numberOfHours : 16);
						int num2 = (int)num;
						int num3 = (int)((num - (float)num2) * 60f);
						Clock = num2.ToString("00") + ":" + num3.ToString("00");
					}
					else
					{
						Clock = "";
					}
				}
				RoundManager instance3 = RoundManager.Instance;
				if (instance.inShipPhase)
				{
					Interior = "";
					SizeMult = 0f;
				}
				else if ((Object)(object)instance3 != (Object)null && (Object)(object)instance3.dungeonGenerator != (Object)null && instance3.dungeonGenerator.Generator != null)
				{
					DungeonGenerator generator = instance3.dungeonGenerator.Generator;
					if (string.IsNullOrEmpty(Interior) && instance3.dungeonCompletedGenerating)
					{
						Interior = InteriorName();
					}
					SizeMult = generator.LengthMultiplier;
				}
			}
			catch
			{
			}
		}

		private static string WeatherName(int w)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if (!_weatherNames.TryGetValue(w, out var value))
			{
				value = (_weatherNames[w] = ((w < 0) ? "Clear" : ((object)(LevelWeatherType)w/*cast due to .constrained prefix*/).ToString()));
			}
			return value;
		}

		public string Short()
		{
			if (Phase == "menu")
			{
				return Scene + " · " + Role;
			}
			StringBuilder stringBuilder = new StringBuilder(96);
			stringBuilder.Append(string.IsNullOrEmpty(Moon) ? Scene : Moon);
			if (!string.IsNullOrEmpty(Interior))
			{
				stringBuilder.Append(" · ").Append(Interior);
				if (SizeMult > 0f)
				{
					stringBuilder.Append(" x").Append(SizeMult.ToString("0.##"));
				}
			}
			if (!string.IsNullOrEmpty(Weather))
			{
				stringBuilder.Append(" · ").Append(Weather);
			}
			stringBuilder.Append(" · ").Append(Phase);
			if (!string.IsNullOrEmpty(Location))
			{
				stringBuilder.Append(" · ").Append(Location);
			}
			if (!string.IsNullOrEmpty(Clock))
			{
				stringBuilder.Append(" · ").Append(Clock);
			}
			stringBuilder.Append(" · ").Append(Players).Append((Players == 1) ? " player · " : " players · ")
				.Append(Role);
			return stringBuilder.ToString();
		}

		public void WriteJson(Json j)
		{
			j.S("scene", Scene).S("moon", Moon).S("int", Interior)
				.N("size", SizeMult)
				.S("wx", Weather)
				.S("phase", Phase)
				.S("loc", Location)
				.S("clock", Clock)
				.I("pl", Players)
				.S("role", Role);
		}
	}
	internal sealed class FrameStats
	{
		public const int Cap = 3600;

		public readonly float[] Ms = new float[3600];

		public readonly double[] At = new double[3600];

		public int Head;

		public int Count;

		private readonly float[] _sort = new float[3600];

		public double Fps1s;

		public double AvgMs5s;

		public double Low1Ms;

		public double Low01Ms;

		public double Worst5s;

		public double AvgFpsSession;

		public double HeapMB;

		public double UnityMemMB = -1.0;

		public double AllocMBps = -1.0;

		public double WorkingSetMB = -1.0;

		public double WorkingSetPeakMB = -1.0;

		private Process _proc;

		private float _wsAt = -10f;

		private bool _wsBroken;

		public bool AllocApprox;

		public int Gc60s;

		public int Stutters60s;

		public double FixedPerFrame;

		public double FixedMaxPerFrame;

		public long DrawCalls = -1L;

		public long Batches = -1L;

		public long SetPass = -1L;

		public long Tris = -1L;

		public long Verts = -1L;

		public long Frames;

		public double SessionWorst;

		public int LastGcGen = -1;

		public int IntervalGcs;

		private readonly int[] _gcPrev = new int[3];

		private readonly double[] _gcTimes = new double[256];

		private int _gcHead;

		private int _gcCount;

		private readonly double[] _stTimes = new double[512];

		private int _stHead;

		private int _stCount;

		private ProfilerRecorder _rGcAlloc;

		private ProfilerRecorder _rTotalMem;

		private ProfilerRecorder _rDraw;

		private ProfilerRecorder _rBatch;

		private ProfilerRecorder _rSetPass;

		private ProfilerRecorder _rTris;

		private ProfilerRecorder _rVerts;

		private bool _recOn;

		private int _recFrames;

		private bool _vGcAlloc;

		private bool _vTotalMem;

		private bool _vDraw;

		private bool _vBatch;

		private bool _vSetPass;

		private bool _vTris;

		private bool _vVerts;

		private double _allocSum;

		private long _threadAllocPrev;

		private long _monoPrev;

		private double _accTimeForAlloc;

		private double _fixedSum;

		private int _fixedMax;

		private int _fixedFrames;

		public double SampleWorkingSet()
		{
			if (_wsBroken)
			{
				return -1.0;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup - _wsAt < 1f)
			{
				return WorkingSetMB;
			}
			_wsAt = realtimeSinceStartup;
			try
			{
				if (_proc == null)
				{
					_proc = Process.GetCurrentProcess();
				}
				_proc.Refresh();
				WorkingSetMB = (double)_proc.WorkingSet64 / 1048576.0;
				if (WorkingSetMB > WorkingSetPeakMB)
				{
					WorkingSetPeakMB = WorkingSetMB;
				}
			}
			catch (Exception ex)
			{
				_wsBroken = true;
				WorkingSetMB = -1.0;
				Plugin.Log.LogWarning((object)("Process working set unavailable: " + ex.Message));
			}
			return WorkingSetMB;
		}

		public void Start()
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			Head = 0;
			Count = 0;
			Frames = 0L;
			SessionWorst = 0.0;
			_gcCount = 0;
			_stCount = 0;
			for (int i = 0; i < 3; i++)
			{
				_gcPrev[i] = GC.CollectionCount(i);
			}
			_recOn = true;
			_recFrames = 0;
			_rGcAlloc = Start(ProfilerCategory.Memory, "GC Allocated In Frame");
			_rTotalMem = Start(ProfilerCategory.Memory, "Total Used Memory");
			_rDraw = Start(ProfilerCategory.Render, "Draw Calls Count");
			_rBatch = Start(ProfilerCategory.Render, "Batches Count");
			_rSetPass = Start(ProfilerCategory.Render, "SetPass Calls Count");
			_rTris = Start(ProfilerCategory.Render, "Triangles Count");
			_rVerts = Start(ProfilerCategory.Render, "Vertices Count");
			_vGcAlloc = (_vTotalMem = (_vDraw = (_vBatch = (_vSetPass = (_vTris = (_vVerts = false))))));
			_allocSum = 0.0;
			_accTimeForAlloc = 0.0;
			_monoPrev = Profiler.GetMonoUsedSizeLong();
			try
			{
				_threadAllocPrev = (ModTimer.AllocSupported ? GC.GetAllocatedBytesForCurrentThread() : 0);
			}
			catch
			{
				_threadAllocPrev = 0L;
			}
		}

		private static ProfilerRecorder Start(ProfilerCategory c, string name)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return ProfilerRecorder.StartNew(c, name, 1, (ProfilerRecorderOptions)24);
			}
			catch
			{
				return default(ProfilerRecorder);
			}
		}

		public void Stop()
		{
			_recOn = false;
			Dispose(ref _rGcAlloc);
			Dispose(ref _rTotalMem);
			Dispose(ref _rDraw);
			Dispose(ref _rBatch);
			Dispose(ref _rSetPass);
			Dispose(ref _rTris);
			Dispose(ref _rVerts);
		}

		private static void Dispose(ref ProfilerRecorder r)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (((ProfilerRecorder)(ref r)).Valid)
				{
					((ProfilerRecorder)(ref r)).Dispose();
				}
			}
			catch
			{
			}
			r = default(ProfilerRecorder);
		}

		private static bool Seen(ref ProfilerRecorder r, bool already)
		{
			if (already)
			{
				return true;
			}
			try
			{
				return ((ProfilerRecorder)(ref r)).Valid && ((ProfilerRecorder)(ref r)).LastValue != 0;
			}
			catch
			{
				return false;
			}
		}

		private static long Last(ref ProfilerRecorder r)
		{
			try
			{
				return ((ProfilerRecorder)(ref r)).LastValue;
			}
			catch
			{
				return 0L;
			}
		}

		public void AddFrame(float ms, double now, int fixedSteps)
		{
			Ms[Head] = ms;
			At[Head] = now;
			Head = (Head + 1) % 3600;
			if (Count < 3600)
			{
				Count++;
			}
			Frames++;
			if ((double)ms > SessionWorst)
			{
				SessionWorst = ms;
			}
			_fixedSum += fixedSteps;
			if (fixedSteps > _fixedMax)
			{
				_fixedMax = fixedSteps;
			}
			_fixedFrames++;
			LastGcGen = -1;
			for (int num = 2; num >= 0; num--)
			{
				int num2 = GC.CollectionCount(num);
				if (num2 != _gcPrev[num])
				{
					if (LastGcGen < 0)
					{
						LastGcGen = num;
					}
					_gcPrev[num] = num2;
				}
			}
			if (LastGcGen >= 0)
			{
				IntervalGcs++;
			}
			if (LastGcGen >= 0)
			{
				_gcTimes[_gcHead] = now;
				_gcHead = (_gcHead + 1) % _gcTimes.Length;
				if (_gcCount < _gcTimes.Length)
				{
					_gcCount++;
				}
			}
			if (_recOn)
			{
				_recFrames++;
				if (_recFrames < 240)
				{
					_vGcAlloc = Seen(ref _rGcAlloc, _vGcAlloc);
					_vTotalMem = Seen(ref _rTotalMem, _vTotalMem);
					_vDraw = Seen(ref _rDraw, _vDraw);
					_vBatch = Seen(ref _rBatch, _vBatch);
					_vSetPass = Seen(ref _rSetPass, _vSetPass);
					_vTris = Seen(ref _rTris, _vTris);
					_vVerts = Seen(ref _rVerts, _vVerts);
				}
				if (_vGcAlloc)
				{
					_allocSum += Last(ref _rGcAlloc);
				}
				_accTimeForAlloc += (double)ms / 1000.0;
			}
		}

		public void AddStutterTime(double now)
		{
			_stTimes[_stHead] = now;
			_stHead = (_stHead + 1) % _stTimes.Length;
			if (_stCount < _stTimes.Length)
			{
				_stCount++;
			}
		}

		private static int CountSince(double[] ring, int head, int count, double since)
		{
			int num = 0;
			for (int i = 0; i < count; i++)
			{
				int num2 = (head - 1 - i + ring.Length) % ring.Length;
				if (!(ring[num2] >= since))
				{
					break;
				}
				num++;
			}
			return num;
		}

		public void ComputeFrames(double now, double sessionSeconds, double window)
		{
			int num = 0;
			double num2 = 0.0;
			double num3 = 0.0;
			int num4 = 0;
			double num5 = 0.0;
			for (int i = 0; i < Count; i++)
			{
				int num6 = (Head - 1 - i + 3600) % 3600;
				double num7 = now - At[num6];
				if (num7 > window)
				{
					break;
				}
				float num8 = Ms[num6];
				_sort[num++] = num8;
				num2 += (double)num8;
				if ((double)num8 > num3)
				{
					num3 = num8;
				}
				if (num7 <= 1.0)
				{
					num4++;
					num5 += (double)num8;
				}
			}
			AvgMs5s = ((num > 0) ? (num2 / (double)num) : 0.0);
			Fps1s = ((num5 > 0.0) ? ((double)num4 * 1000.0 / num5) : 0.0);
			Worst5s = num3;
			if (num > 0)
			{
				Array.Sort(_sort, 0, num);
				Low1Ms = _sort[Math.Min(num - 1, (int)Math.Floor((double)num * 0.99))];
				Low01Ms = _sort[Math.Min(num - 1, (int)Math.Floor((double)num * 0.999))];
			}
			else
			{
				Low1Ms = 0.0;
				Low01Ms = 0.0;
			}
			AvgFpsSession = ((sessionSeconds > 0.0) ? ((double)Frames / sessionSeconds) : 0.0);
		}

		public void ComputeRates(double now)
		{
			Gc60s = CountSince(_gcTimes, _gcHead, _gcCount, now - 60.0);
			Stutters60s = CountSince(_stTimes, _stHead, _stCount, now - 60.0);
			HeapMB = (double)Profiler.GetMonoUsedSizeLong() / 1048576.0;
			if (_vTotalMem)
			{
				UnityMemMB = (double)Last(ref _rTotalMem) / 1048576.0;
			}
			else
			{
				long totalAllocatedMemoryLong = Profiler.GetTotalAllocatedMemoryLong();
				UnityMemMB = ((totalAllocatedMemoryLong > 0) ? ((double)totalAllocatedMemoryLong / 1048576.0) : (-1.0));
			}
			if (_accTimeForAlloc > 0.05)
			{
				if (_vGcAlloc)
				{
					AllocMBps = _allocSum / 1048576.0 / _accTimeForAlloc;
					AllocApprox = false;
				}
				else if (ModTimer.AllocSupported)
				{
					long allocatedBytesForCurrentThread = GC.GetAllocatedBytesForCurrentThread();
					if (_threadAllocPrev == 0L)
					{
						_threadAllocPrev = allocatedBytesForCurrentThread;
					}
					AllocMBps = (double)(allocatedBytesForCurrentThread - _threadAllocPrev) / 1048576.0 / _accTimeForAlloc;
					_threadAllocPrev = allocatedBytesForCurrentThread;
					AllocApprox = false;
				}
				else
				{
					long monoUsedSizeLong = Profiler.GetMonoUsedSizeLong();
					long num = monoUsedSizeLong - _monoPrev;
					_monoPrev = monoUsedSizeLong;
					if (num > 0)
					{
						AllocMBps = (double)num / 1048576.0 / _accTimeForAlloc;
						AllocApprox = true;
					}
					else if (AllocMBps < 0.0)
					{
						AllocMBps = -1.0;
					}
				}
				_allocSum = 0.0;
				_accTimeForAlloc = 0.0;
			}
			if (_fixedFrames > 0)
			{
				FixedPerFrame = _fixedSum / (double)_fixedFrames;
				FixedMaxPerFrame = _fixedMax;
			}
			_fixedSum = 0.0;
			_fixedMax = 0;
			_fixedFrames = 0;
			DrawCalls = (_vDraw ? Last(ref _rDraw) : (-1));
			Batches = (_vBatch ? Last(ref _rBatch) : (-1));
			SetPass = (_vSetPass ? Last(ref _rSetPass) : (-1));
			Tris = (_vTris ? Last(ref _rTris) : (-1));
			Verts = (_vVerts ? Last(ref _rVerts) : (-1));
		}

		public void Columns(float[] cols, double now, double seconds)
		{
			Array.Clear(cols, 0, cols.Length);
			int num = cols.Length;
			for (int i = 0; i < Count; i++)
			{
				int num2 = (Head - 1 - i + 3600) % 3600;
				double num3 = now - At[num2];
				if (!(num3 >= seconds))
				{
					int num4 = num - 1 - (int)(num3 / seconds * (double)num);
					if (num4 < 0)
					{
						num4 = 0;
					}
					if (Ms[num2] > cols[num4])
					{
						cols[num4] = Ms[num2];
					}
					continue;
				}
				break;
			}
		}
	}
	internal enum KeyAction
	{
		None,
		Toggle,
		Page,
		Snapshot,
		DayToggle,
		DayView
	}
	internal struct Combo
	{
		public bool Shift;

		public bool Ctrl;

		public bool Alt;

		public Key Key;

		public static Combo Parse(string s, Key fallback)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			Combo result = new Combo
			{
				Key = fallback
			};
			if (string.IsNullOrEmpty(s))
			{
				return result;
			}
			string[] array = s.Split('+');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0)
				{
					continue;
				}
				switch (text.ToLowerInvariant())
				{
				case "shift":
					result.Shift = true;
					continue;
				case "ctrl":
				case "control":
					result.Ctrl = true;
					continue;
				case "alt":
					result.Alt = true;
					continue;
				}
				if (Enum.TryParse<Key>(text, ignoreCase: true, out Key result2) && (int)result2 != 0)
				{
					result.Key = result2;
				}
				else if (text.Length == 1 && char.IsDigit(text[0]) && Enum.TryParse<Key>("Digit" + text, out result2))
				{
					result.Key = result2;
				}
			}
			return result;
		}

		public bool ModsMatch(bool shift, bool ctrl, bool alt)
		{
			if (Shift == shift && Ctrl == ctrl)
			{
				return Alt == alt;
			}
			return false;
		}

		public override string ToString()
		{
			return (Ctrl ? "Ctrl+" : "") + (Shift ? "Shift+" : "") + (Alt ? "Alt+" : "") + ((object)Unsafe.As<Key, Key>(ref Key)/*cast due to .constrained prefix*/).ToString();
		}
	}
	internal static class Keys
	{
		public const string InputUtilsGuid = "com.rune580.LethalCompanyInputUtils";

		private static Combo _toggle;

		private static Combo _page;

		private static Combo _snap;

		private static Combo _day;

		private static Combo _dayView;

		private static object _iu;

		public static void Init()
		{
			_toggle = Combo.Parse(Cfg.ToggleKey.Value, (Key)30);
			_page = Combo.Parse(Cfg.PageKey.Value, (Key)30);
			_snap = Combo.Parse(Cfg.SnapshotKey.Value, (Key)30);
			_day = Combo.Parse(Cfg.DayKey.Value, (Key)23);
			_dayView = Combo.Parse(Cfg.DayViewKey.Value, (Key)23);
			if (Chainloader.PluginInfos.ContainsKey("com.rune580.LethalCompanyInputUtils"))
			{
				try
				{
					_iu = CreateInputUtils();
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("InputUtils keybinds unavailable, using config keys: " + ex.Message));
					_iu = null;
				}
			}
		}

		private static object CreateInputUtils()
		{
			return new PerfInputs();
		}

		public static string Describe()
		{
			if (_iu == null)
			{
				return _toggle.ToString();
			}
			return "the PerfWatcher key (default P, see controls menu)";
		}

		public static string PageHint()
		{
			return _page.ToString();
		}

		public static string SnapHint()
		{
			return _snap.ToString();
		}

		public static KeyAction Poll()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			Keyboard current = Keyboard.current;
			if (current == null)
			{
				return KeyAction.None;
			}
			bool t;
			bool p;
			bool s;
			if (_iu != null)
			{
				ReadInputUtils(out t, out p, out s);
			}
			else
			{
				t = Pressed(current, _toggle.Key);
				p = Pressed(current, _page.Key);
				s = Pressed(current, _snap.Key);
			}
			if (!t && !p && !s)
			{
				return KeyAction.None;
			}
			bool isPressed = current.shiftKey.isPressed;
			bool isPressed2 = current.ctrlKey.isPressed;
			bool isPressed3 = current.altKey.isPressed;
			KeyAction keyAction = KeyAction.None;
			if (s && _snap.ModsMatch(isPressed, isPressed2, isPressed3))
			{
				keyAction = KeyAction.Snapshot;
			}
			else if (p && _page.ModsMatch(isPressed, isPressed2, isPressed3))
			{
				keyAction = KeyAction.Page;
			}
			else if (t && _toggle.ModsMatch(isPressed, isPressed2, isPressed3))
			{
				keyAction = KeyAction.Toggle;
			}
			if (keyAction != KeyAction.None && IsTyping())
			{
				return KeyAction.None;
			}
			return keyAction;
		}

		public static KeyAction PollDay()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			Keyboard current = Keyboard.current;
			if (current == null)
			{
				return KeyAction.None;
			}
			bool flag;
			bool flag2;
			if (_iu != null)
			{
				PerfInputs perfInputs = (PerfInputs)_iu;
				flag = perfInputs.Day != null && perfInputs.Day.WasPressedThisFrame();
				flag2 = perfInputs.DayView != null && perfInputs.DayView.WasPressedThisFrame();
			}
			else
			{
				flag = Pressed(current, _day.Key);
				flag2 = Pressed(current, _dayView.Key);
			}
			if (!flag && !flag2)
			{
				return KeyAction.None;
			}
			bool isPressed = current.shiftKey.isPressed;
			bool isPressed2 = current.ctrlKey.isPressed;
			bool isPressed3 = current.altKey.isPressed;
			KeyAction keyAction = KeyAction.None;
			if (flag2 && _dayView.ModsMatch(isPressed, isPressed2, isPressed3))
			{
				keyAction = KeyAction.DayView;
			}
			else if (flag && _day.ModsMatch(isPressed, isPressed2, isPressed3))
			{
				keyAction = KeyAction.DayToggle;
			}
			if (keyAction != KeyAction.None && IsTyping())
			{
				return KeyAction.None;
			}
			return keyAction;
		}

		private static bool Pressed(Keyboard kb, Key k)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return (int)k != 0 && ((ButtonControl)kb[k]).wasPressedThisFrame;
			}
			catch
			{
				return false;
			}
		}

		private static void ReadInputUtils(out bool t, out bool p, out bool s)
		{
			PerfInputs perfInputs = (PerfInputs)_iu;
			t = perfInputs.Toggle != null && perfInputs.Toggle.WasPressedThisFrame();
			p = perfInputs.Page != null && perfInputs.Page.WasPressedThisFrame();
			s = perfInputs.Snapshot != null && perfInputs.Snapshot.WasPressedThisFrame();
		}

		private static bool IsTyping()
		{
			try
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				PlayerControllerB val = (((Object)(object)instance != (Object)null) ? instance.localPlayerController : null);
				if ((Object)(object)val != (Object)null && (val.isTypingChat || val.inTerminalMenu))
				{
					return true;
				}
				EventSystem current = EventSystem.current;
				if ((Object)(object)current == (Object)null)
				{
					return false;
				}
				GameObject currentSelectedGameObject = current.currentSelectedGameObject;
				if ((Object)(object)currentSelectedGameObject == (Object)null)
				{
					return false;
				}
				TMP_InputField component = currentSelectedGameObject.GetComponent<TMP_InputField>();
				if ((Object)(object)component != (Object)null && component.isFocused)
				{
					return true;
				}
				InputField component2 = currentSelectedGameObject.GetComponent<InputField>();
				return (Object)(object)component2 != (Object)null && component2.isFocused;
			}
			catch
			{
				return false;
			}
		}
	}
	internal class PerfInputs : LcInputActions
	{
		[InputAction("<Keyboard>/p", Name = "PerfWatcher overlay")]
		public InputAction Toggle { get; set; }

		[InputAction("<Keyboard>/p", Name = "PerfWatcher page (+Shift)")]
		public InputAction Page { get; set; }

		[InputAction("<Keyboard>/p", Name = "PerfWatcher snapshot (+Ctrl)")]
		public InputAction Snapshot { get; set; }

		[InputAction("<Keyboard>/i", Name = "Day Info panel")]
		public InputAction Day { get; set; }

		[InputAction("<Keyboard>/i", Name = "Day Info view (+Shift)")]
		public InputAction DayView { get; set; }
	}
	internal sealed class LogCounter : ILogListener, IDisposable
	{
		private sealed class Src
		{
			public int Sec;

			public int Streak;

			public double LastReport = -1000000000.0;

			public string Sample;

			public long Total;
		}

		private readonly object _lk = new object();

		private readonly Dictionary<string, Src> _src = new Dictionary<string, Src>();

		private int _frameCount;

		private readonly string[] _frameSamples = new string[3];

		private int _frameSampleN;

		private int _secTotal;

		public double LinesPerSec;

		public string TopSource;

		public double TopSourceRate;

		public int NetSyncGuardFixes;

		public long TotalLines;

		public void LogEvent(object sender, LogEventArgs e)
		{
			try
			{
				string text = ((e.Source != null) ? e.Source.SourceName : "?");
				lock (_lk)
				{
					if (!_src.TryGetValue(text, out var value))
					{
						value = (_src[text] = new Src());
					}
					value.Sec++;
					value.Total++;
					_secTotal++;
					_frameCount++;
					TotalLines++;
					if (_frameSampleN < 3 || value.Sample == null || value.Sec % 64 == 1 || text == "NetSyncGuard")
					{
						string text2 = Short(text, e.Data);
						if (_frameSampleN < 3)
						{
							_frameSamples[_frameSampleN++] = text2;
						}
						if (value.Sample == null || value.Sec % 64 == 1)
						{
							value.Sample = text2;
						}
						if (text == "NetSyncGuard" && text2.IndexOf("Fixed an object", StringComparison.Ordinal) >= 0)
						{
							NetSyncGuardFixes++;
						}
					}
				}
			}
			catch
			{
			}
		}

		private static string Short(string src, object data)
		{
			string text;
			try
			{
				text = ((data == null) ? "" : data.ToString());
			}
			catch
			{
				text = "?";
			}
			int num = text.IndexOf('\n');
			if (num >= 0)
			{
				text = text.Substring(0, num);
			}
			if (text.Length > 110)
			{
				text = text.Substring(0, 110) + "...";
			}
			return "[" + src + "] " + text.TrimEnd('\r');
		}

		public int TakeFrame(List<string> samplesOut)
		{
			lock (_lk)
			{
				int frameCount = _frameCount;
				if (samplesOut != null)
				{
					for (int i = 0; i < _frameSampleN; i++)
					{
						samplesOut.Add(_frameSamples[i]);
					}
				}
				_frameCount = 0;
				_frameSampleN = 0;
				return frameCount;
			}
		}

		public void RollSecond(double seconds, double now, int spamThreshold, Action<string, double, string, bool> spam)
		{
			lock (_lk)
			{
				if (seconds <= 0.0)
				{
					seconds = 1.0;
				}
				LinesPerSec = (double)_secTotal / seconds;
				_secTotal = 0;
				TopSource = null;
				TopSourceRate = 0.0;
				foreach (KeyValuePair<string, Src> item in _src)
				{
					Src value = item.Value;
					double num = (double)value.Sec / seconds;
					if (num > TopSourceRate)
					{
						TopSourceRate = num;
						TopSource = item.Key;
					}
					if (num >= (double)spamThreshold)
					{
						value.Streak++;
						if (value.Streak >= 3 && now - value.LastReport >= 60.0)
						{
							bool arg = value.LastReport > -100000000.0;
							value.LastReport = now;
							spam?.Invoke(item.Key, num, value.Sample, arg);
						}
					}
					else
					{
						value.Streak = 0;
					}
					value.Sec = 0;
				}
			}
		}

		public void Dispose()
		{
		}
	}
	internal static class MimicLink
	{
		private static bool _looked;

		private static bool _dead;

		private static PropertyInfo _avail;

		private static PropertyInfo _short;

		private static PropertyInfo _full;

		private static PropertyInfo _activity;

		private static PropertyInfo _job;

		private static PropertyInfo _serial;

		private static int _fails;

		private static string _curJob;

		private static int _lastSerial = -1;

		private static double _jobStart;

		private static double _nextPoll;

		private static readonly List<float> _ms = new List<float>(4096);

		private const int MaxFrames = 30000;

		private static bool Ready()
		{
			if (_dead)
			{
				return false;
			}
			if (Cfg.DayShowMimic == null || !Cfg.DayShowMimic.Value)
			{
				return false;
			}
			if (!_looked)
			{
				if (Time.frameCount < 120)
				{
					return false;
				}
				_looked = true;
				try
				{
					Type type = Refl.T("MimicPlus.RadioState");
					if (type == null)
					{
						_dead = true;
						return false;
					}
					FieldInfo field = type.GetField("ApiVersion", BindingFlags.Static | BindingFlags.Public);
					object obj = ((field == null) ? null : (field.IsLiteral ? field.GetRawConstantValue() : field.GetValue(null)));
					if (obj == null || Convert.ToInt32(obj) != 1)
					{
						_dead = true;
						return false;
					}
					_avail = type.GetProperty("Available", BindingFlags.Static | BindingFlags.Public);
					_short = type.GetProperty("ShortLine", BindingFlags.Static | BindingFlags.Public);
					_full = type.GetProperty("FullLines", BindingFlags.Static | BindingFlags.Public);
					_activity = type.GetProperty("ActivityLine", BindingFlags.Static | BindingFlags.Public);
					_job = type.GetProperty("CurrentJob", BindingFlags.Static | BindingFlags.Public);
					_serial = type.GetProperty("JobSerial", BindingFlags.Static | BindingFlags.Public);
					if (_avail == null)
					{
						_dead = true;
						return false;
					}
				}
				catch
				{
					_dead = true;
					return false;
				}
			}
			try
			{
				bool result = (bool)_avail.GetValue(null, null);
				_fails = 0;
				return result;
			}
			catch
			{
				Fail();
				return false;
			}
		}

		private static void Fail()
		{
			if (++_fails >= 3 && !_dead)
			{
				_dead = true;
				Plugin.Log.LogWarning((object)"Mimic+ integration turned off for this session after 3 errors in a row");
			}
		}

		private static object Read(PropertyInfo p)
		{
			if (p == null)
			{
				return null;
			}
			try
			{
				object? value = p.GetValue(null, null);
				_fails = 0;
				return value;
			}
			catch
			{
				Fail();
				return null;
			}
		}

		internal static string ShortLine()
		{
			if (!Ready())
			{
				return null;
			}
			return Read(_short) as string;
		}

		internal static string[] FullLines()
		{
			if (!Ready())
			{
				return null;
			}
			return Read(_full) as string[];
		}

		internal static string ActivityLine()
		{
			if (!Ready())
			{
				return null;
			}
			return Read(_activity) as string;
		}

		internal static string CurrentJob()
		{
			if (!Ready())
			{
				return null;
			}
			return Read(_job) as string;
		}

		internal static int JobSerial()
		{
			if (!Ready())
			{
				return -1;
			}
			object obj = Read(_serial);
			if (obj is int)
			{
				return (int)obj;
			}
			return -1;
		}

		internal static void Frame(double now, double frameMs)
		{
			if (_dead)
			{
				return;
			}
			if (_curJob != null && _ms.Count < 30000)
			{
				_ms.Add((float)frameMs);
			}
			if (!(now < _nextPoll))
			{
				_nextPoll = now + 0.25;
				string text = CurrentJob();
				int num = JobSerial();
				bool flag = !string.IsNullOrEmpty(text);
				bool flag2 = flag && (_curJob == null || (num >= 0 && num != _lastSerial));
				if (_curJob != null && (!flag || flag2))
				{
					End(now);
				}
				if (flag2)
				{
					Start(now, text, num);
				}
				if (num >= 0)
				{
					_lastSerial = num;
				}
			}
		}

		private static void Start(double now, string job, int serial)
		{
			_curJob = job;
			_jobStart = now;
			_ms.Clear();
			SessionLog session = Runner.Session;
			session?.Write(session.J.Begin("mimicplus", now).S("ev", "job start").S("job", job)
				.I("serial", serial)
				.S("clock", DateTime.Now.ToString("HH:mm:ss"))
				.End(), droppable: false);
		}

		private static void End(double now)
		{
			string curJob = _curJob;
			_curJob = null;
			SessionLog session = Runner.Session;
			if (session == null)
			{
				_ms.Clear();
				return;
			}
			Json json = session.J.Begin("mimicplus", now).S("ev", "job end").S("job", curJob)
				.N("dur", now - _jobStart)
				.I("frames", _ms.Count);
			if (_ms.Count > 0)
			{
				double num = 0.0;
				double num2 = 0.0;
				foreach (float m in _ms)
				{
					num += (double)m;
					if ((double)m > num2)
					{
						num2 = m;
					}
				}
				_ms.Sort();
				double v = _ms[Math.Min(_ms.Count - 1, (int)Math.Ceiling((double)_ms.Count * 0.99) - 1)];
				json.N("avgMs", num / (double)_ms.Count).N("p99Ms", v).N("maxMs", num2)
					.N("fps", 1000.0 * (double)_ms.Count / Math.Max(1.0, num));
			}
			session.Write(json.End(), droppable: false);
			_ms.Clear();
		}

		internal static void Close(double now)
		{
			if (_curJob != null)
			{
				End(now);
			}
			_nextPoll = 0.0;
		}
	}
	internal enum BKind : byte
	{
		Frame,
		Patch,
		Life,
		Coro,
		Rpc,
		Game,
		Engine
	}
	internal sealed class Owner
	{
		public int Index;

		public string Name;

		public string Version;

		public string Guid;

		public Assembly Assembly;

		public bool IsMod;

		public bool Partial;

		public string Note;

		public int Methods;

		public int Applied;

		public double FrameMs;

		public double LastSecMsPerFrame;

		public double LastSecCallsPerSec;

		public double Worst10s;

		public double TotalMs;

		public long TotalCalls;

		public double IntervalBase;

		public double FrameMsInterval;

		internal bool InFrame;

		internal double SecMs;

		internal double SecWorst;

		internal long SecCalls;

		internal readonly double[] WorstRing = new double[10];
	}
	internal sealed class Bucket
	{
		public int Index;

		public Owner Owner;

		public string Label;

		public BKind Kind;

		public int Methods;

		public int Applied;

		public double FrameMs;

		public double LastSecMsPerFrame;

		public double LastSecCallsPerSec;

		public double Worst10s;

		public double TotalMs;

		public long TotalCalls;

		public double IntervalBase;

		public double FrameMsInterval;

		internal double SecMs;

		internal double SecWorst;

		internal long SecCalls;

		internal readonly double[] WorstRing = new double[10];

		public string Full => Owner.Name + ": " + Label;
	}
	internal static class ModTimer
	{
		private struct Job
		{
			public MethodBase M;

			public int Bucket;

			public HarmonyMethod Pre;

			public HarmonyMethod Post;

			public byte Prio;
		}

		public const string HarmonyId = "jacob.perfwatcher.timing";

		public const int MaxBuckets = 2048;

		private const int MaxDepth = 96;

		private const int MaxErrors = 20;

		internal static bool Active;

		[ThreadStatic]
		private static bool t_main;

		private static int _depth;

		private static readonly long[] _start = new long[96];

		private static readonly long[] _child = new long[96];

		private static readonly int[] _dyn = new int[96];

		internal static readonly long[] FrameTicks = new long[2048];

		internal static readonly int[] FrameCalls = new int[2048];

		private static readonly int[] _touched = new int[2048];

		private static int _touchedN;

		private static int _errors;

		private static readonly Dictionary<Type, int> _coroBuckets = new Dictionary<Type, int>();

		internal static bool Failed;

		internal static bool Calibrated;

		internal static double BiasTicks;

		internal static double OverheadTicksPerCall;

		internal static readonly List<Owner> Owners = new List<Owner>();

		internal static readonly List<Owner> AllPlugins = new List<Owner>();

		internal static readonly List<Bucket> Buckets = new List<Bucket>();

		internal static readonly Bucket[] ByIndex = new Bucket[2048];

		internal static int PatchErrors;

		internal static string LastPatchError;

		private static int _nextStatic;

		private static int _nextDyn = 1024;

		private static Owner _game;

		private static Owner _dungen;

		private static Owner _netcode;

		private static Owner _unity;

		private static readonly Dictionary<Assembly, Owner> _byAsm = new Dictionary<Assembly, Owner>();

		private static readonly Dictionary<string, Owner> _byGuid = new Dictionary<string, Owner>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, Bucket> _bucketByKey = new Dictionary<string, Bucket>();

		private static readonly string[] ExcludedPrefixes = new string[13]
		{
			"PerfWatcher", "BepInEx", "0Harmony", "HarmonyX", "Harmony", "MonoMod", "Mono.Cecil", "MonoDetour", "MMHOOK", "System",
			"mscorlib", "netstandard", "Mono."
		};

		private static Harmony _harmony;

		private static MethodInfo[] _pre;

		private static MethodInfo[] _post;

		private static bool _pluginsBuilt;

		private static bool _scanned;

		private static bool _sessionPlanned;

		private static List<Assembly> _scanQueue;

		private static int _scanIdx;

		private static readonly List<Job> _staticJobs = new List<Job>();

		private static readonly List<Job> _jobs = new List<Job>();

		private static readonly HashSet<MethodBase> _jobSet = new HashSet<MethodBase>();

		private static int _applyIdx;

		private static readonly List<MethodBase> _applied = new List<MethodBase>();

		private static readonly HashSet<MethodBase> _appliedSet = new HashSet<MethodBase>();

		internal static double PatchMsTotal;

		internal static int PatchCount;

		internal static bool AllocSupported;

		private static bool _allocTested;

		private static readonly string[] FrameNames = new string[4] { "Update", "LateUpdate", "FixedUpdate", "OnGUI" };

		private static readonly string[] LifeNames = new string[7] { "Awake", "Start", "OnEnable", "OnDisable", "OnDestroy", "OnNetworkSpawn", "OnNetworkDespawn" };

		private static readonly KeyValuePair<Type, string>[] GameHeavy = new KeyValuePair<Type, string>[48]
		{
			H(typeof(RoundManager), "GenerateNewFloor"),
			H(typeof(RoundManager), "GeneratedFloorPostProcessing"),
			H(typeof(RoundManager), "SpawnScrapInLevel"),
			H(typeof(RoundManager), "SpawnSyncedProps"),
			H(typeof(RoundManager), "SpawnMapObjects"),
			H(typeof(RoundManager), "SpawnOutsideHazards"),
			H(typeof(RoundManager), "FinishGeneratingLevel"),
			H(typeof(RoundManager), "RefreshEnemiesList"),
			H(typeof(RoundManager), "SetLevelObjectVariables"),
			H(typeof(RoundManager), "DespawnPropsAtEndOfRound"),
			H(typeof(RoundManager), "UnloadSceneObjectsEarly"),
			H(typeof(RoundManager), "LoadNewLevel"),
			H(typeof(RoundManager), "SetPowerOffAtStart"),
			H(typeof(RoundManager), "SetExitIDs"),
			H(typeof(RoundManager), "SetBigDoorCodes"),
			H(typeof(RoundManager), "SetLockedDoors"),
			H(typeof(RoundManager), "SpawnRandomStoryLogs"),
			H(typeof(RoundManager), "SpawnEnemiesOutside"),
			H(typeof(RoundManager), "SpawnDaytimeEnemiesOutside"),
			H(typeof(RoundManager), "PlotOutEnemiesForNextHour"),
			H(typeof(RoundManager), "AdvanceHourAndSpawnNewBatchOfEnemies"),
			H(typeof(RoundManager), "PredictAllOutsideEnemies"),
			H(typeof(RoundManager), "SpawnEnemyGameObject"),
			H(typeof(RoundManager), "SetToCurrentLevelWeather"),
			H(typeof(StartOfRound), "StartGame"),
			H(typeof(StartOfRound), "ShipLeave"),
			H(typeof(StartOfRound), "ShipHasLeft"),
			H(typeof(StartOfRound), "ResetShip"),
			H(typeof(StartOfRound), "ArriveAtLevel"),
			H(typeof(StartOfRound), "ChangeLevel"),
			H(typeof(StartOfRound), "SceneManager_OnLoadComplete1"),
			H(typeof(StartOfRound), "SceneManager_OnLoad"),
			H(typeof(StartOfRound), "SetShipReadyToLand"),
			H(typeof(StartOfRound), "PassTimeToNextDay"),
			H(typeof(StartOfRound), "AutoSaveShipData"),
			H(typeof(StartOfRound), "ReviveDeadPlayers"),
			H(typeof(StartOfRound), "OnShipLandedMiscEvents"),
			H(typeof(StartOfRound), "LoadShipGrabbableItems"),
			H(typeof(StartOfRound), "ResetMiscValues"),
			H(typeof(StartOfRound), "SetMapScreenInfoToCurrentLevel"),
			H(typeof(GameNetworkManager), "SaveGame"),
			H(typeof(GameNetworkManager), "SaveGameValues"),
			H(typeof(GameNetworkManager), "SaveItemsInShip"),
			H(typeof(GameNetworkManager), "SaveLocalPlayerValues"),
			H(typeof(HUDManager), "ApplyPenalty"),
			H(typeof(HUDManager), "FillEndGameStats"),
			H(typeof(TimeOfDay), "SetNewProfitQuota"),
			H(typeof(TimeOfDay), "SetBuyingRateForDay")
		};

		private static readonly double TickMs = 1000.0 / (double)Stopwatch.Frequency;

		private static Owner _self;

		private static int _selfBucket = -1;

		public static double FrameTimedMs;

		public static int FrameCallsTotal;

		public static double SecCallsPerFrame;

		public static readonly List<Bucket> FrameTouched = new List<Bucket>(256);

		private static int _worstPos;

		public static readonly List<Owner> FrameOwners = new List<Owner>(64);

		internal static Owner GameOwner => _game ?? (_game = NewOwner("Game", "", null, isMod: false));

		internal static Owner DunGenOwner => _dungen ?? (_dungen = NewOwner("DunGen", "", null, isMod: false));

		internal static Owner NetcodeOwner => _netcode ?? (_netcode = NewOwner("Netcode", "", null, isMod: false));

		internal static Owner UnityOwner => _unity ?? (_unity = NewOwner("Unity", "", null, isMod: false));

		public static int JobsTotal => _jobs.Count;

		public static int JobsApplied => _applyIdx;

		public static bool WarmingUp
		{
			get
			{
				if (Cfg.PerModTiming.Value && !Failed)
				{
					if (_sessionPlanned)
					{
						return _applyIdx < _jobs.Count;
					}
					return true;
				}
				return false;
			}
		}

		public static bool AnyPatched => _applied.Count > 0;

		public static double PatchMsAvg
		{
			get
			{
				if (PatchCount <= 0)
				{
					return 0.0;
				}
				return PatchMsTotal / (double)PatchCount;
			}
		}

		public static double BiasMs => BiasTicks * TickMs;

		public static double OverheadMsPerCall => OverheadTicksPerCall * TickMs;

		internal static int SelfBucket
		{
			get
			{
				if (_selfBucket < 0)
				{
					_self = NewOwner("PerfWatcher", "1.5.1", null, isMod: false);
					_selfBucket = NewBucket(_self, "warm-up (scanning and patching)", BKind.Engine, dynamic: true)?.Index ?? (-1);
				}
				return _selfBucket;
			}
		}

		public static double OverheadMsPerFrame => SecCallsPerFrame * OverheadMsPerCall;

		public static void MarkMainThread()
		{
			t_main = true;
		}

		public static int Enter()
		{
			if (!Active || !t_main)
			{
				return -1;
			}
			int num = _depth++;
			if (num >= 96)
			{
				return 96;
			}
			_child[num] = 0L;
			_start[num] = Stopwatch.GetTimestamp();
			return num;
		}

		public static void Exit(int slot, int d)
		{
			if (d < 0)
			{
				return;
			}
			try
			{
				long timestamp = Stopwatch.GetTimestamp();
				if (d >= 96)
				{
					_depth = d;
					return;
				}
				long num = timestamp - _start[d];
				_depth = d;
				if (d > 0)
				{
					_child[d - 1] += num;
				}
				if (slot >= 0)
				{
					if (FrameCalls[slot]++ == 0)
					{
						_touched[_touchedN++] = slot;
					}
					FrameTicks[slot] += num - _child[d];
				}
			}
			catch
			{
				Fail();
			}
		}

		internal static int EnterDynPublic(int bucket)
		{
			return EnterDyn(bucket);
		}

		internal static void ExitDynPublic(int d)
		{
			ExitDyn(d);
		}

		private static void AddTicks(int slot, long ticks)
		{
			if (slot >= 0)
			{
				if (FrameCalls[slot]++ == 0)
				{
					_touched[_touchedN++] = slot;
				}
				FrameTicks[slot] += ticks;
			}
		}

		private static int EnterDyn(int bucket)
		{
			int num = Enter();
			if (num >= 0 && num < 96)
			{
				_dyn[num] = bucket;
			}
			return num;
		}

		private static void ExitDyn(int d)
		{
			if (d >= 0)
			{
				Exit((d < 96) ? _dyn[d] : (-1), d);
			}
		}

		private static void Fail()
		{
			_errors++;
			if (_errors > 20)
			{
				Active = false;
				Failed = true;
			}
		}

		private static void CoroPre(IEnumerator enumerator, out int __state)
		{
			__state = -1;
			if (!Active || !t_main || enumerator == null)
			{
				return;
			}
			try
			{
				int num = CoroBucket(enumerator.GetType());
				if (num >= 0)
				{
					__state = EnterDyn(num);
				}
			}
			catch
			{
				Fail();
			}
		}

		private static void CoroPost(int __state)
		{
			ExitDyn(__state);
		}

		private static int CoroBucket(Type t)
		{
			if (_coroBuckets.TryGetValue(t, out var value))
			{
				return value;
			}
			Owner owner = OwnerFor(t.Assembly);
			if (owner == null)
			{
				_coroBuckets[t] = -1;
				return -1;
			}
			Type type = t.DeclaringType ?? t;
			string text = t.Name;
			if (text.StartsWith("<"))
			{
				int num = text.IndexOf('>');
				text = ((num > 1) ? text.Substring(1, num - 1) : text);
			}
			value = NewBucket(owner, "coroutine " + type.Name + "." + text, BKind.Coro, dynamic: true)?.Index ?? (-1);
			_coroBuckets[t] = value;
			return value;
		}

		private static Owner NewOwner(string name, string version, Assembly asm, bool isMod)
		{
			Owner owner = new Owner
			{
				Index = Owners.Count,
				Name = name,
				Version = version,
				Assembly = asm,
				IsMod = isMod
			};
			Owners.Add(owner);
			return owner;
		}

		private static Bucket NewBucket(Owner owner, string label, BKind kind, bool dynamic)
		{
			string key = owner.Index + "|" + label;
			if (_bucketByKey.TryGetValue(key, out var value))
			{
				return value;
			}
			int num;
			if (dynamic)
			{
				if (_nextDyn >= 2048)
				{
					return null;
				}
				num = _nextDyn++;
			}
			else
			{
				if (_nextStatic >= 1023)
				{
					return null;
				}
				num = _nextStatic++;
			}
			value = new Bucket
			{
				Index = num,
				Owner = owner,
				Label = label,
				Kind = kind
			};
			_bucketByKey[key] = value;
			ByIndex[num] = value;
			Buckets.Add(value);
			return value;
		}

		internal static bool Excluded(Assembly a)
		{
			if (a == null || a == typeof(ModTimer).Assembly)
			{
				return true;
			}
			string name = a.GetName().Name;
			string[] excludedPrefixes = ExcludedPrefixes;
			foreach (string value in excludedPrefixes)
			{
				if (name.StartsWith(value, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		internal static Owner OwnerFor(Assembly a)
		{
			if (a == null)
			{
				return null;
			}
			if (_byAsm.TryGetValue(a, out var value))
			{
				return value;
			}
			if (Excluded(a))
			{
				_byAsm[a] = null;
				return null;
			}
			string name = a.GetName().Name;
			value = (name.StartsWith("Assembly-CSharp", StringComparison.Ordinal) ? GameOwner : ((name == "DunGen") ? DunGenOwner : ((name.StartsWith("Unity.Netcode", StringComparison.Ordinal) || name.StartsWith("Facepunch", StringComparison.Ordinal)) ? NetcodeOwner : ((!name.StartsWith("Unity", StringComparison.Ordinal)) ? NewOwner(name, "", a, isMod: true) : UnityOwner))));
			_byAsm[a] = value;
			return value;
		}

		public static void Stop()
		{
			Active = false;
			_sessionPlanned = false;
			_applyIdx = 0;
		}

		public static void TestAlloc()
		{
			if (_allocTested)
			{
				return;
			}
			_allocTested = true;
			try
			{
				long allocatedBytesForCurrentThread = GC.GetAllocatedBytesForCurrentThread();
				byte[] obj = new byte[16384];
				long allocatedBytesForCurrentThread2 = GC.GetAllocatedBytesForCurrentThread();
				GC.KeepAlive(obj);
				AllocSupported = allocatedBytesForCurrentThread2 - allocatedBytesForCurrentThread >= 16384;
			}
			catch
			{
				AllocSupported = false;
			}
		}

		private static KeyValuePair<Type, string> H(Type t, string m)
		{
			return new KeyValuePair<Type, string>(t, m);
		}

		private static void EnsureHarmony()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			if (_harmony == null)
			{
				_harmony = new Harmony("jacob.perfwatcher.timing");
				_pre = new MethodInfo[1024];
				_post = new MethodInfo[1024];
				for (int i = 0; i < 1024; i++)
				{
					_pre[i] = typeof(Slots).GetMethod("P" + i, BindingFlags.Static | BindingFlags.Public);
					_post[i] = typeof(Slots).GetMethod("F" + i, BindingFlags.Static | BindingFlags.Public);
				}
			}
		}

		private static Job StaticJob(MethodBase m, Bucket b, byte prio)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			return new Job
			{
				M = m,
				Bucket = b.Index,
				Prio = prio,
				Pre = new HarmonyMethod(_pre[b.Index])
				{
					priority = 800
				},
				Post = new HarmonyMethod(_post[b.Index])
				{
					priority = 0
				}
			};
		}

		private static void Calibrate()
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			//IL_0082: Expected O, but got Unknown
			Calibrated = true;
			MethodInfo methodInfo = AccessTools.Method(typeof(Calib), "Empty", (Type[])null, (Type[])null);
			int num = 1023;
			try
			{
				long timestamp = Stopwatch.GetTimestamp();
				for (int i = 0; i < 4000; i++)
				{
					Calib.Empty();
				}
				long num2 = Stopwatch.GetTimestamp() - timestamp;
				_harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(_pre[num])
				{
					priority = 800
				}, new HarmonyMethod(_post[num])
				{
					priority = 0
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				bool active = Active;
				Active = true;
				FrameTicks[num] = 0L;
				FrameCalls[num] = 0;
				timestamp = Stopwatch.GetTimestamp();
				for (int j = 0; j < 4000; j++)
				{
					Calib.Empty();
				}
				long num3 = Stopwatch.GetTimestamp() - timestamp;
				Active = active;
				int num4 = FrameCalls[num];
				BiasTicks = ((num4 > 0) ? ((double)FrameTicks[num] / (double)num4) : 0.0);
				OverheadTicksPerCall = Math.Max(0.0, (double)(num3 - num2) / 4000.0);
				_harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, "jacob.perfwatcher.timing");
			}
			catch (Exception ex)
			{
				PatchErrors++;
				LastPatchError = "calibration: " + ex.Message;
				try
				{
					_harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, "jacob.perfwatcher.timing");
				}
				catch
				{
				}
			}
			FrameTicks[num] = 0L;
			FrameCalls[num] = 0;
			_touchedN = 0;
		}

		private static void BuildPlugins()
		{
			_pluginsBuilt = true;
			Dictionary<Assembly, List<PluginInfo>> dictionary = new Dictionary<Assembly, List<PluginInfo>>();
			foreach (PluginInfo value2 in Chainloader.PluginInfos.Values)
			{
				Assembly assembly = null;
				try
				{
					if ((Object)(object)value2.Instance != (Object)null)
					{
						assembly = ((object)value2.Instance).GetType().Assembly;
					}
				}
				catch
				{
				}
				if (assembly == null)
				{
					AllPlugins.Add(new Owner
					{
						Index = -1,
						Name = value2.Metadata.Name,
						Version = value2.Metadata.Version.ToString(),
						Guid = value2.Metadata.GUID,
						Note = "not loaded"
					});
				}
				else
				{
					if (!dictionary.TryGetValue(assembly, out var value))
					{
						value = (dictionary[assembly] = new List<PluginInfo>());
					}
					value.Add(value2);
				}
			}
			foreach (KeyValuePair<Assembly, List<PluginInfo>> item in dictionary)
			{
				PluginInfo val = item.Value[0];
				string name = string.Join("+", item.Value.Select((PluginInfo p) => p.Metadata.Name).ToArray());
				if (Excluded(item.Key))
				{
					if (item.Key != typeof(ModTimer).Assembly)
					{
						AllPlugins.Add(new Owner
						{
							Index = -1,
							Name = name,
							Version = val.Metadata.Version.ToString(),
							Guid = val.Metadata.GUID,
							Note = "library, not timed"
						});
					}
					_byAsm[item.Key] = null;
					continue;
				}
				Owner owner = NewOwner(name, val.Metadata.Version.ToString(), item.Key, isMod: true);
				owner.Guid = val.Metadata.GUID;
				AllPlugins.Add(owner);
				_byAsm[item.Key] = owner;
				foreach (PluginInfo item2 in item.Value)
				{
					_byGuid[item2.Metadata.GUID] = owner;
				}
			}
			_scanQueue = (from kv in _byAsm
				where kv.Value != null
				select kv.Key).ToList();
			if (Cfg.Scope.Value == TimingScope.Full)
			{
				_scanQueue.Add(typeof(RoundManager).Assembly);
				_scanQueue.Add(typeof(RuntimeDungeon).Assembly);
			}
			_scanIdx = 0;
		}

		private static bool Patchable(MethodBase m)
		{
			if (m == null || m.DeclaringType == null || m.IsAbstract || m.ContainsGenericParameters || m.IsGenericMethodDefinition)
			{
				return false;
			}
			if ((m.MethodImplementationFlags & (MethodImplAttributes)4099) != MethodImplAttributes.IL)
			{
				return false;
			}
			if (Excluded(m.DeclaringType.Assembly))
			{
				return false;
			}
			try
			{
				if (m.GetMethodBody() == null)
				{
					return false;
				}
			}
			catch
			{
				return false;
			}
			return true;
		}

		private static void ScanAssembly(Assembly asm)
		{
			Owner owner = OwnerFor(asm);
			if (owner == null)
			{
				return;
			}
			bool flag = !owner.IsMod;
			bool flag2 = Cfg.Scope.Value == TimingScope.Full;
			if (flag && !flag2)
			{
				return;
			}
			Type[] array;
			try
			{
				array = asm.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				array = ex.Types.Where((Type t) => t != null).ToArray();
				owner.Partial = true;
			}
			catch (Exception)
			{
				owner.Note = "not timed (types unreadable)";
				return;
			}
			Type typeFromHandle = typeof(MonoBehaviour);
			Type[] array2 = array;
			foreach (Type type in array2)
			{
				try
				{
					if (type == null || type.IsInterface || type.IsValueType || type.ContainsGenericParameters || !typeFromHandle.IsAssignableFrom(type))
					{
						continue;
					}
					string[] frameNames = FrameNames;
					foreach (string name in frameNames)
					{
						MethodInfo method = type.GetMethod(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
						if (Patchable(method))
						{
							Bucket bucket = NewBucket(owner, "script " + type.Name, BKind.Frame, dynamic: false);
							if (bucket != null)
							{
								_staticJobs.Add(StaticJob(method, bucket, (byte)(flag ? 5u : 3u)));
							}
						}
					}
					if (!flag2)
					{
						continue;
					}
					frameNames = LifeNames;
					foreach (string name2 in frameNames)
					{
						MethodInfo method2 = type.GetMethod(name2, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
						if (Patchable(method2))
						{
							Bucket bucket2 = (flag ? NewBucket(owner, "spawn/init " + type.Name, BKind.Life, dynamic: false) : NewBucket(owner, "spawn/init", BKind.Life, dynamic: false));
							if (bucket2 != null)
							{
								_staticJobs.Add(StaticJob(method2, bucket2, (byte)(flag ? 6u : 4u)));
							}
						}
					}
				}
				catch
				{
					owner.Partial = true;
				}
			}
		}

		private static void PlanSession()
		{
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			_sessionPlanned = true;
			_jobs.Clear();
			_jobSet.Clear();
			_applyIdx = 0;
			bool flag = Cfg.Scope.Value == TimingScope.Full;
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(MonoBehaviour).Assembly.GetType("UnityEngine.SetupCoroutine"), "InvokeMoveNext", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					AddJob(new Job
					{
						M = methodInfo,
						Bucket = -1,
						Prio = 0,
						Pre = new HarmonyMethod(typeof(ModTimer), "CoroPre", (Type[])null)
						{
							priority = 800
						},
						Post = new HarmonyMethod(typeof(ModTimer), "CoroPost", (Type[])null)
						{
							priority = 0
						}
					});
				}
			}
			catch
			{
			}
			if (flag)
			{
				AddNamed(typeof(NetworkManager).Assembly.GetType("Unity.Netcode.NetworkMessageManager"), "ProcessIncomingMessageQueue", NetcodeOwner, "message processing", 1);
				AddNamed(typeof(NetworkSpawnManager), "SpawnNetworkObjectLocallyCommon", NetcodeOwner, "spawn objects", 1);
				AddNamed(typeof(NetworkSpawnManager), "OnDespawnObject", NetcodeOwner, "despawn objects", 1);
				KeyValuePair<Type, string>[] gameHeavy = GameHeavy;
				for (int i = 0; i < gameHeavy.Length; i++)
				{
					KeyValuePair<Type, string> keyValuePair = gameHeavy[i];
					AddNamed(keyValuePair.Key, keyValuePair.Value, GameOwner, keyValuePair.Key.Name + "." + keyValuePair.Value, 1);
				}
			}
			AddExtraMethods();
			try
			{
				foreach (MethodBase item in Harmony.GetAllPatchedMethods().ToList())
				{
					if (item == null)
					{
						continue;
					}
					bool flag2 = Array.IndexOf(FrameNames, item.Name) >= 0 || item.Name == "DoAIInterval";
					if (!flag && !flag2)
					{
						continue;
					}
					Patches patchInfo;
					try
					{
						patchInfo = Harmony.GetPatchInfo(item);
					}
					catch
					{
						continue;
					}
					if (patchInfo == null)
					{
						continue;
					}
					foreach (Patch item2 in patchInfo.Prefixes.Concat(patchInfo.Postfixes))
					{
						if (item2.owner == "jacob.perfwatcher.timing" || item2.owner == "jacob.perfwatcher.hooks")
						{
							continue;
						}
						MethodInfo patchMethod = item2.PatchMethod;
						if (!Patchable(patchMethod) || _jobSet.Contains(patchMethod))
						{
							continue;
						}
						if (!_byAsm.TryGetValue(patchMethod.DeclaringType.Assembly, out var value) && item2.owner != null)
						{
							_byGuid.TryGetValue(item2.owner, out value);
						}
						if (value == null)
						{
							value = OwnerFor(patchMethod.DeclaringType.Assembly);
						}
						if (value != null && value.IsMod)
						{
							Bucket bucket = NewBucket(value, "patch " + ((item.DeclaringType != null) ? item.DeclaringType.Name : "?") + (flag2 ? ("." + item.Name) : ""), BKind.Patch, dynamic: false);
							if (bucket != null)
							{
								AddJob(StaticJob(patchMethod, bucket, 2));
							}
						}
					}
				}
			}
			catch
			{
			}
			foreach (Job staticJob in _staticJobs)
			{
				AddJob(staticJob);
			}
			_jobs.Sort((Job a, Job b) => a.Prio.CompareTo(b.Prio));
			foreach (Bucket bucket2 in Buckets)
			{
				bucket2.Methods = 0;
				bucket2.Applied = 0;
			}
			foreach (Owner owner in Owners)
			{
				owner.Methods = 0;
				owner.Applied = 0;
			}
			foreach (Job job in _jobs)
			{
				if (job.Bucket >= 0 && ByIndex[job.Bucket] != null)
				{
					ByIndex[job.Bucket].Methods++;
					ByIndex[job.Bucket].Owner.Methods++;
				}
			}
			foreach (Owner allPlugin in AllPlugins)
			{
				if (allPlugin.Index >= 0 && allPlugin.Methods == 0 && allPlugin.Note == null)
				{
					allPlugin.Note = "no timed code found";
				}
			}
		}

		private static void AddJob(Job j)
		{
			if (_jobSet.Add(j.M))
			{
				_jobs.Add(j);
			}
		}

		internal static Type FindType(string fullName)
		{
			try
			{
				Type type = Type.GetType(fullName, throwOnError: false);
				if (type != null)
				{
					return type;
				}
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				foreach (Assembly assembly in assemblies)
				{
					try
					{
						type = assembly.GetType(fullName, throwOnError: false);
					}
					catch
					{
						type = null;
					}
					if (type != null)
					{
						return type;
					}
				}
			}
			catch
			{
			}
			return null;
		}

		private static void AddExtraMethods()
		{
			string value = Cfg.ExtraMethods.Value;
			if (string.IsNullOrEmpty(value))
			{
				return;
			}
			string[] array = value.Split(';');
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split(':');
				if (array2.Length != 2)
				{
					continue;
				}
				Type type = FindType(array2[0].Trim());
				if (type == null)
				{
					continue;
				}
				Owner owner = OwnerFor(type.Assembly);
				if (owner == null)
				{
					continue;
				}
				string[] array3 = array2[1].Split(',');
				for (int j = 0; j < array3.Length; j++)
				{
					string text = array3[j].Trim();
					if (text.Length == 0)
					{
						continue;
					}
					try
					{
						foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(type))
						{
							if (!(declaredMethod.Name != text) && Patchable(declaredMethod))
							{
								Bucket bucket = NewBucket(owner, type.Name + "." + text, owner.IsMod ? BKind.Patch : BKind.Game, dynamic: false);
								if (bucket != null)
								{
									AddJob(StaticJob(declaredMethod, bucket, 1));
								}
							}
						}
					}
					catch
					{
					}
				}
			}
		}

		internal static Bucket DynBucket(Owner o, string label)
		{
			return NewBucket(o, label, BKind.Rpc, dynamic: true);
		}

		private static void AddNamed(Type t, string method, Owner o, string label, byte prio)
		{
			try
			{
				if (t == null)
				{
					return;
				}
				MethodInfo methodInfo = AccessTools.DeclaredMethod(t, method, (Type[])null, (Type[])null);
				if (!(methodInfo == null) && !methodInfo.IsAbstract && !methodInfo.ContainsGenericParameters)
				{
					Bucket bucket = NewBucket(o, label, o.IsMod ? BKind.Patch : ((o == NetcodeOwner) ? BKind.Engine : BKind.Game), dynamic: false);
					if (bucket != null)
					{
						AddJob(StaticJob(methodInfo, bucket, prio));
					}
				}
			}
			catch
			{
			}
		}

		public static void Step(bool wantOn, double budgetMs)
		{
			if (!Cfg.PerModTiming.Value || Failed)
			{
				wantOn = false;
			}
			long timestamp = Stopwatch.GetTimestamp();
			long budget = (long)(budgetMs / TickMs);
			if (wantOn)
			{
				try
				{
					StepOn(timestamp, budget);
					return;
				}
				finally
				{
					AddTicks(SelfBucket, Stopwatch.GetTimestamp() - timestamp);
				}
			}
			StepOff(timestamp, budget);
		}

		private static void StepOn(long t0, long budget)
		{
			EnsureHarmony();
			if (!Calibrated)
			{
				Calibrate();
				return;
			}
			if (!_pluginsBuilt)
			{
				BuildPlugins();
				return;
			}
			while (!_scanned && Stopwatch.GetTimestamp() - t0 < budget)
			{
				if (_scanIdx >= _scanQueue.Count)
				{
					_scanned = true;
					break;
				}
				ScanAssembly(_scanQueue[_scanIdx++]);
			}
			if (!_scanned)
			{
				return;
			}
			if (!_sessionPlanned)
			{
				PlanSession();
				Active = true;
				return;
			}
			while (_applyIdx < _jobs.Count && Stopwatch.GetTimestamp() - t0 < budget)
			{
				Job job = _jobs[_applyIdx++];
				Bucket bucket = ((job.Bucket >= 0) ? ByIndex[job.Bucket] : null);
				if (_appliedSet.Contains(job.M))
				{
					if (bucket != null)
					{
						bucket.Applied++;
						bucket.Owner.Applied++;
					}
					continue;
				}
				long timestamp = Stopwatch.GetTimestamp();
				try
				{
					_harmony.Patch(job.M, job.Pre, job.Post, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					_applied.Add(job.M);
					_appliedSet.Add(job.M);
					if (bucket != null)
					{
						bucket.Applied++;
						bucket.Owner.Applied++;
					}
				}
				catch (Exception ex)
				{
					PatchErrors++;
					LastPatchError = job.M.DeclaringType?.ToString() + "." + job.M.Name + ": " + ex.Message;
					Runner.Session?.PatchError(job.M.DeclaringType?.ToString() + "." + job.M.Name, ex.GetType().Name + ": " + Trim(ex.Message));
					if (PatchErrors <= 10)
					{
						Plugin.Log.LogWarning((object)("PerfWatcher couldn't time " + job.M.DeclaringType?.ToString() + "." + job.M.Name + " (" + Trim(ex.Message) + "). That method just isn't timed; nothing else is affected."));
					}
				}
				PatchMsTotal += (double)(Stopwatch.GetTimestamp() - timestamp) * TickMs;
				PatchCount++;
			}
			Active = !Failed;
		}

		private static void StepOff(long t0, long budget)
		{
			Stop();
			if (_applied.Count == 0)
			{
				return;
			}
			while (_applied.Count > 0 && Stopwatch.GetTimestamp() - t0 < budget)
			{
				MethodBase methodBase = _applied[_applied.Count - 1];
				_applied.RemoveAt(_applied.Count - 1);
				_appliedSet.Remove(methodBase);
				try
				{
					_harmony.Unpatch(methodBase, (HarmonyPatchType)0, "jacob.perfwatcher.timing");
				}
				catch
				{
				}
			}
			if (_applied.Count != 0)
			{
				return;
			}
			_appliedSet.Clear();
			try
			{
				_harmony.UnpatchSelf();
			}
			catch
			{
			}
			foreach (Bucket bucket in Buckets)
			{
				bucket.Applied = 0;
			}
			foreach (Owner owner in Owners)
			{
				owner.Applied = 0;
			}
		}

		private static string Trim(string m)
		{
			if (m == null)
			{
				return "";
			}
			int num = m.IndexOf('\n');
			if (num >= 0)
			{
				m = m.Substring(0, num);
			}
			if (m.Length <= 160)
			{
				return m;
			}
			return m.Substring(0, 160);
		}

		public static void EndFrame()
		{
			_depth = 0;
			foreach (Bucket item in FrameTouched)
			{
				item.FrameMs = 0.0;
			}
			foreach (Owner frameOwner in FrameOwners)
			{
				frameOwner.FrameMs = 0.0;
			}
			FrameTouched.Clear();
			FrameOwners.Clear();
			FrameTimedMs = 0.0;
			FrameCallsTotal = 0;
			for (int i = 0; i < _touchedN; i++)
			{
				int num = _touched[i];
				int num2 = FrameCalls[num];
				double num3 = Math.Max(0.0, ((double)FrameTicks[num] - BiasTicks * (double)num2) * TickMs);
				FrameTicks[num] = 0L;
				FrameCalls[num] = 0;
				Bucket bucket = ByIndex[num];
				if (bucket != null)
				{
					FrameTimedMs += num3;
					FrameCallsTotal += num2;
					bucket.FrameMs = num3;
					bucket.TotalMs += num3;
					bucket.TotalCalls += num2;
					bucket.SecMs += num3;
					bucket.SecCalls += num2;
					if (num3 > bucket.SecWorst)
					{
						bucket.SecWorst = num3;
					}
					FrameTouched.Add(bucket);
					Owner owner = bucket.Owner;
					if (!owner.InFrame)
					{
						owner.InFrame = true;
						FrameOwners.Add(owner);
					}
					owner.FrameMs += num3;
					owner.SecCalls += num2;
					owner.TotalCalls += num2;
				}
			}
			_touchedN = 0;
			foreach (Owner frameOwner2 in FrameOwners)
			{
				frameOwner2.InFrame = false;
				frameOwner2.TotalMs += frameOwner2.FrameMs;
				frameOwner2.SecMs += frameOwner2.FrameMs;
				if (frameOwner2.FrameMs > frameOwner2.SecWorst)
				{
					frameOwner2.SecWorst = frameOwner2.FrameMs;
				}
			}
		}

		public static void RollSecond(double seconds, int frames)
		{
			if (frames <= 0)
			{
				frames = 1;
			}
			if (seconds <= 0.0)
			{
				seconds = 1.0;
			}
			long num = 0L;
			_worstPos = (_worstPos + 1) % 10;
			foreach (Bucket bucket in Buckets)
			{
				bucket.WorstRing[_worstPos] = bucket.SecWorst;
				bucket.LastSecMsPerFrame = bucket.SecMs / (double)frames;
				bucket.LastSecCallsPerSec = (double)bucket.SecCalls / seconds;
				double num2 = 0.0;
				for (int i = 0; i < 10; i++)
				{
					if (bucket.WorstRing[i] > num2)
					{
						num2 = bucket.WorstRing[i];
					}
				}
				bucket.Worst10s = num2;
				num += bucket.SecCalls;
				bucket.SecMs = 0.0;
				bucket.SecCalls = 0L;
				bucket.SecWorst = 0.0;
			}
			foreach (Owner owner in Owners)
			{
				owner.WorstRing[_worstPos] = owner.SecWorst;
				owner.LastSecMsPerFrame = owner.SecMs / (double)frames;
				owner.LastSecCallsPerSec = (double)owner.SecCalls / seconds;
				double num3 = 0.0;
				for (int j = 0; j < 10; j++)
				{
					if (owner.WorstRing[j] > num3)
					{
						num3 = owner.WorstRing[j];
					}
				}
				owner.Worst10s = num3;
				owner.SecMs = 0.0;
				owner.SecCalls = 0L;
				owner.SecWorst = 0.0;
			}
			SecCallsPerFrame = (double)num / (double)frames;
		}

		public static void ResetSession()
		{
			foreach (Bucket bucket in Buckets)
			{
				bucket.TotalMs = 0.0;
				bucket.TotalCalls = 0L;
				bucket.LastSecMsPerFrame = 0.0;
				bucket.LastSecCallsPerSec = 0.0;
				bucket.Worst10s = 0.0;
				bucket.FrameMs = 0.0;
				bucket.SecMs = 0.0;
				bucket.SecCalls = 0L;
				bucket.SecWorst = 0.0;
				Array.Clear(bucket.WorstRing, 0, 10);
				bucket.IntervalBase = 0.0;
			}
			foreach (Owner owner in Owners)
			{
				owner.TotalMs = 0.0;
				owner.TotalCalls = 0L;
				owner.LastSecMsPerFrame = 0.0;
				owner.LastSecCallsPerSec = 0.0;
				owner.Worst10s = 0.0;
				owner.FrameMs = 0.0;
				owner.SecMs = 0.0;
				owner.SecCalls = 0L;
				owner.SecWorst = 0.0;
				Array.Clear(owner.WorstRing, 0, 10);
				owner.IntervalBase = 0.0;
			}
			for (int i = 0; i < _touchedN; i++)
			{
				FrameTicks[_touched[i]] = 0L;
				FrameCalls[_touched[i]] = 0;
			}
			_touchedN = 0;
			FrameTouched.Clear();
			FrameOwners.Clear();
		}

		public static int Top<T>(IList<T> src, T[] into, Func<T, double> key, double min = 0.0001) where T : class
		{
			int num = 0;
			int num2 = into.Length;
			for (int i = 0; i < num2; i++)
			{
				into[i] = null;
			}
			for (int j = 0; j < src.Count; j++)
			{
				T val = src[j];
				double num3 = key(val);
				if (!(num3 <= min) && (num != num2 || !(num3 <= key(into[num2 - 1]))))
				{
					if (num < num2)
					{
						num++;
					}
					int num4 = num - 1;
					while (num4 > 0 && key(into[num4 - 1]) < num3)
					{
						into[num4] = into[num4 - 1];
						num4--;
					}
					into[num4] = val;
				}
			}
			return num;
		}
	}
	internal static class Calib
	{
		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void Empty()
		{
		}
	}
	internal static class Hooks
	{
		public const string HarmonyId = "jacob.perfwatcher.hooks";

		private static Harmony _h;

		public static int Spawns;

		public static int Despawns;

		public static void Apply()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			if (_h == null)
			{
				_h = new Harmony("jacob.perfwatcher.hooks");
				TryPatch(typeof(NetworkSpawnManager), "SpawnNetworkObjectLocallyCommon", "OnSpawn");
				TryPatch(typeof(NetworkSpawnManager), "OnDespawnObject", "OnDespawn");
				TryPatch(typeof(StartOfRound), "StartGame", "OnLever", prefix: true);
				TryPatch(typeof(RoundManager), "LoadNewLevel", "OnLever", prefix: true);
			}
		}

		private static void TryPatch(Type t, string method, string patch, bool prefix = false)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(t, method, (Type[])null, (Type[])null);
				if (!(methodInfo == null))
				{
					if (prefix)
					{
						_h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Hooks), patch, (Type[])null)
						{
							priority = 800
						}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
					else
					{
						_h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Hooks), patch, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
				}
			}
			catch (Exception ex)
			{
				Runner.Session?.PatchError(t.Name + "." + method, ex.GetType().Name);
			}
		}

		public static void Remove()
		{
			if (_h != null)
			{
				try
				{
					_h.UnpatchSelf();
				}
				catch
				{
				}
				_h = null;
			}
		}

		private static void OnSpawn()
		{
			Spawns++;
		}

		private static void OnDespawn()
		{
			Despawns++;
		}

		private static void OnLever()
		{
			try
			{
				Runner i = Runner.I;
				if ((Object)(object)i != (Object)null && i.On)
				{
					i.Ctx.LeverPulled();
				}
			}
			catch
			{
			}
		}
	}
	internal sealed class NetStats
	{
		public bool Available;

		public double RttToHost = -1.0;

		public readonly List<KeyValuePair<string, double>> ClientRtts = new List<KeyValuePair<string, double>>();

		public int Spawned = -1;

		public double SpawnsPerSec;

		public double DespawnsPerSec;

		public bool RttEverNonZero;

		public bool NetSyncGuardInstalled;

		public void Start()
		{
			NetSyncGuardInstalled = Chainloader.PluginInfos.ContainsKey("jacob.netsyncguard");
			Hooks.Spawns = 0;
			Hooks.Despawns = 0;
		}

		public void Roll(double seconds, Context ctx)
		{
			if (seconds <= 0.0)
			{
				seconds = 1.0;
			}
			SpawnsPerSec = (double)Hooks.Spawns / seconds;
			DespawnsPerSec = (double)Hooks.Despawns / seconds;
			Hooks.Spawns = 0;
			Hooks.Despawns = 0;
			ClientRtts.Clear();
			RttToHost = -1.0;
			Spawned = -1;
			Available = false;
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
				{
					return;
				}
				Available = ctx.Multiplayer;
				if (singleton.SpawnManager != null)
				{
					Spawned = singleton.SpawnManager.SpawnedObjectsList.Count;
				}
				NetworkTransport val = ((singleton.NetworkConfig != null) ? singleton.NetworkConfig.NetworkTransport : null);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				if (singleton.IsHost || singleton.IsServer)
				{
					foreach (ulong connectedClientsId in singleton.ConnectedClientsIds)
					{
						if (connectedClientsId != singleton.LocalClientId)
						{
							ulong currentRtt = val.GetCurrentRtt(connectedClientsId);
							if (currentRtt != 0)
							{
								RttEverNonZero = true;
							}
							ClientRtts.Add(new KeyValuePair<string, double>(PlayerName(connectedClientsId), currentRtt));
						}
					}
					return;
				}
				ulong currentRtt2 = val.GetCurrentRtt(val.ServerClientId);
				if (currentRtt2 != 0)
				{
					RttEverNonZero = true;
				}
				RttToHost = currentRtt2;
			}
			catch
			{
			}
		}

		private static string PlayerName(ulong clientId)
		{
			try
			{
				StartOfRound instance = StartOfRound.Instance;
				if ((Object)(object)instance != (Object)null && instance.allPlayerScripts != null)
				{
					PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
					foreach (PlayerControllerB val in allPlayerScripts)
					{
						if ((Object)(object)val != (Object)null && val.isPlayerControlled && val.actualClientId == clientId)
						{
							return val.playerUsername;
						}
					}
				}
			}
			catch
			{
			}
			return "client " + clientId;
		}
	}
	internal sealed class Overlay
	{
		private const int GraphW = 240;

		private const int GraphH = 48;

		private const float GraphMaxMs = 66.7f;

		private const string Green = "#7CFC7C";

		private const string Amber = "#FFC04D";

		private const string Red = "#FF5A5A";

		private const string Dim = "#9A9A9A";

		private const string Head = "#8FD3FF";

		private readonly Runner _r;

		private readonly StringBuilder _sb = new StringBuilder(4096);

		private readonly GUIContent _top = new GUIContent();

		private readonly GUIContent _bottom = new GUIContent();

		private bool _hasBottom;

		private bool _showGraph;

		private bool _dirty = true;

		private Vector2 _topSize;

		private Vector2 _bottomSize;

		private GUIStyle _style;

		private Texture2D _bg;

		private Texture2D _graph;

		private Color32[] _px;

		private readonly float[] _cols = new float[240];

		private double _nextRefresh;

		private string _flash;

		private double _flashUntil;

		private static readonly string[] PageNames = new string[5] { "Summary", "Mods", "Hotspots", "Scene", "Network" };

		private readonly Owner[] _top3 = new Owner[3];

		private readonly List<Owner> _owners = new List<Owner>();

		private static readonly Comparison<Owner> ByOwnerMs = (Owner a, Owner b) => b.LastSecMsPerFrame.CompareTo(a.LastSecMsPerFrame);

		private readonly Bucket[] _hot = new Bucket[16];

		private readonly int[] _hotPh = new int[10];

		private readonly bool[] _shownGroup = new bool[10];

		public Overlay(Runner r)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			_r = r;
		}

		public void Open()
		{
			_nextRefresh = 0.0;
		}

		public void ForceRefresh()
		{
			_nextRefresh = 0.0;
		}

		public void Flash(string s)
		{
			_flash = s;
			_flashUntil = _r.Now + 3.0;
			_nextRefresh = 0.0;
		}

		public void MaybeRefresh(double now)
		{
			if (!(now < _nextRefresh))
			{
				_nextRefresh = now + 1.0 / (double)Math.Max(1, Cfg.UpdatesPerSecond.Value);
				FrameStats frames = _r.Frames;
				frames.ComputeFrames(now, now, 5.0);
				frames.ComputeRates(now);
				_sb.Length = 0;
				_hasBottom = false;
				_showGraph = false;
				Header();
				switch (_r.Page)
				{
				case 0:
					Summary(now);
					break;
				case 1:
					Mods();
					break;
				case 2:
					Hotspots();
					break;
				case 3:
					SceneP();
					break;
				default:
					NetP();
					break;
				}
				if (_flash != null && now < _flashUntil)
				{
					_sb.Append('\n').Append(C("#7CFC7C", _flash));
				}
				_top.text = _sb.ToString().TrimEnd('\n');
				if (_showGraph)
				{
					UpdateGraph(now);
				}
				_dirty = true;
			}
		}

		private void Header()
		{
			_sb.Append(C("#8FD3FF", "PerfWatcher")).Append("  ").Append(_r.Page + 1)
				.Append('/')
				.Append(5)
				.Append(' ')
				.Append(PageNames[_r.Page])
				.Append(C("#9A9A9A", "   " + Keys.PageHint() + " page · " + Keys.SnapHint() + " snapshot"))
				.Append('\n');
		}

		private void Summary(double now)
		{
			FrameStats frames = _r.Frames;
			_sb.Append("FPS ").Append(C(FpsCol(frames.Fps1s), frames.Fps1s.ToString("0"))).Append("   frame ")
				.Append(C(MsCol(frames.AvgMs5s), frames.AvgMs5s.ToString("0.00")))
				.Append(" ms")
				.Append("  1% ")
				.Append(C(MsCol(frames.Low1Ms), frames.Low1Ms.ToString("0.0")))
				.Append("  0.1% ")
				.Append(C(MsCol(frames.Low01Ms), frames.Low01Ms.ToString("0.0")))
				.Append("  worst ")
				.Append(C(MsCol(frames.Worst5s), frames.Worst5s.ToString("0.0")))
				.Append(C("#9A9A9A", "  (5 s)"))
				.Append('\n');
			if (Phases.Installed)
			{
				FrameLine();
			}
			_sb.Append("Stutters >").Append(Cfg.StutterThresholdMs.Value.ToString("0")).Append(" ms: ")
				.Append(C((frames.Stutters60s == 0) ? "#7CFC7C" : ((frames.Stutters60s < 5) ? "#FFC04D" : "#FF5A5A"), frames.Stutters60s.ToString()))
				.Append(" in 60 s");
			_sb.Append("   Heap ").Append(frames.HeapMB.ToString("0")).Append(" MB  GC ")
				.Append(frames.Gc60s)
				.Append("/60 s");
			if (frames.SampleWorkingSet() > 0.0)
			{
				_sb.Append("  Process ").Append((frames.WorkingSetMB / 1024.0).ToString("0.00")).Append(" GB");
			}
			if (frames.AllocMBps >= 0.0)
			{
				_sb.Append("  alloc ").Append(frames.AllocApprox ? "~" : "").Append(frames.AllocMBps.ToString("0.0"))
					.Append(" MB/s");
			}
			if (frames.UnityMemMB > 0.0)
			{
				_sb.Append("  Unity ").Append((frames.UnityMemMB / 1024.0).ToString("0.0")).Append(" GB");
			}
			_sb.Append('\n');
			string value = MimicLink.ActivityLine();
			if (!string.IsNullOrEmpty(value))
			{
				_sb.Append(value).Append('\n');
			}
			ModsLine();
			LogCounter logs = _r.Logs;
			_sb.Append("Log ").Append(C((logs.LinesPerSec >= (double)Cfg.LogSpamLinesPerSecond.Value) ? "#FF5A5A" : ((logs.LinesPerSec >= 10.0) ? "#FFC04D" : "#7CFC7C"), logs.LinesPerSec.ToString("0"))).Append(" lines/s");
			if (logs.TopSource != null && logs.TopSourceRate >= 1.0)
			{
				_sb.Append("  top: ").Append(Trunc(logs.TopSource, 24)).Append(' ')
					.Append(logs.TopSourceRate.ToString("0"))
					.Append("/s");
			}
			_sb.Append('\n');
			_sb.Append(C("#9A9A9A", _r.Ctx.Short()));
			_showGraph = Cfg.ShowGraph.Value;
			Stutters st = _r.St;
			StringBuilder stringBuilder = new StringBuilder(256);
			if (st.Ep != null)
			{
				stringBuilder.Append(C("#FFC04D", Cap(st.Ep.Name) + " in progress: " + (now - st.Ep.Start).ToString("0.0") + " s, " + st.Ep.Long + " long frames, worst " + st.Ep.WorstMs.ToString("0") + " ms")).Append('\n');
			}
			else if (st.LastEpisode != null)
			{
				stringBuilder.Append(C("#9A9A9A", "Last: " + st.LastEpisode)).Append('\n');
			}
			if (st.Pending != null || st.Recent.Count > 0)
			{
				stringBuilder.Append(C("#9A9A9A", "Recent stutters")).Append('\n');
				int num = 0;
				if (st.Pending != null)
				{
					stringBuilder.Append(C("#FFC04D", Stutters.Describe(st.Pending))).Append('\n');
					num++;
				}
				foreach (StutterEvent item in st.Recent)
				{
					if (num++ >= 5)
					{
						break;
					}
					stringBuilder.Append(Stutters.Describe(item)).Append('\n');
				}
			}
			_bottom.text = stringBuilder.ToString().TrimEnd('\n');
			_hasBottom = stringBuilder.Length > 0;
		}

		private static string Cap(string s)
		{
			if (!string.IsNullOrEmpty(s))
			{
				return char.ToUpperInvariant(s[0]) + s.Substring(1).Replace('_', ' ');
			}
			return s;
		}

		private void FrameLine()
		{
			_sb.Append("Frame ");
			int num = 0;
			for (int i = 0; i < 10; i++)
			{
				if (num >= 7)
				{
					break;
				}
				int num2 = -1;
				double num3 = 0.05;
				for (int j = 0; j < 10; j++)
				{
					double num4 = Phases.GroupLastSec[j];
					if (num4 > num3 && !_shownGroup[j])
					{
						num3 = num4;
						num2 = j;
					}
				}
				if (num2 < 0)
				{
					break;
				}
				_shownGroup[num2] = true;
				num++;
				_sb.Append(' ').Append(Phases.GroupNames[num2]).Append(' ')
					.Append(C(PhaseCol(num3), num3.ToString("0.0")));
			}
			Array.Clear(_shownGroup, 0, _shownGroup.Length);
			_sb.Append(C("#9A9A9A", " ms")).Append('\n');
		}

		private void ModsLine()
		{
			_sb.Append("Mods: ");
			if (!Cfg.PerModTiming.Value)
			{
				_sb.Append(C("#9A9A9A", "timing off in config")).Append('\n');
				return;
			}
			if (ModTimer.Failed)
			{
				_sb.Append(C("#FF5A5A", "timing disabled after errors")).Append('\n');
				return;
			}
			if (ModTimer.WarmingUp && ModTimer.JobsTotal == 0)
			{
				_sb.Append(C("#FFC04D", "scanning...")).Append('\n');
				return;
			}
			_owners.Clear();
			foreach (Owner owner in ModTimer.Owners)
			{
				if (owner.IsMod)
				{
					_owners.Add(owner);
				}
			}
			int num = ModTimer.Top(_owners, _top3, (Owner o) => o.LastSecMsPerFrame, 0.005);
			if (num == 0)
			{
				_sb.Append(C("#7CFC7C", "nothing measurable"));
			}
			for (int num2 = 0; num2 < num; num2++)
			{
				if (num2 > 0)
				{
					_sb.Append(" · ");
				}
				_sb.Append(Trunc(_top3[num2].Name, 22)).Append(' ').Append(C(ModCol(_top3[num2].LastSecMsPerFrame), _top3[num2].LastSecMsPerFrame.ToString("0.00")));
			}
			if (ModTimer.WarmingUp)
			{
				_sb.Append(C("#FFC04D", "  (warming up " + ModTimer.JobsApplied + "/" + ModTimer.JobsTotal + ")"));
			}
			else
			{
				_sb.Append(C("#9A9A9A", "  ms · cost " + ModTimer.OverheadMsPerFrame.ToString("0.00")));
			}
			_sb.Append('\n');
		}

		private void Mods()
		{
			if (!Cfg.PerModTiming.Value)
			{
				_sb.Append(C("#9A9A9A", "Per-mod timing is off (PerModTiming in jacob.perfwatcher.cfg)"));
				return;
			}
			if (ModTimer.Failed)
			{
				_sb.Append(C("#FF5A5A", "Per-mod timing disabled after errors."));
				return;
			}
			if (ModTimer.WarmingUp)
			{
				_sb.Append(C("#FFC04D", "Warming up: patched " + ModTimer.JobsApplied + " of " + ModTimer.JobsTotal + " methods")).Append('\n');
			}
			double num = ((_r.Frames.Fps1s > 0.0) ? (1000.0 / _r.Frames.Fps1s) : 0.0);
			_sb.Append(C("#9A9A9A", Pad("owner", 26) + LPad("ms", 7) + LPad("%", 6) + LPad("calls/s", 9) + LPad("worst", 8))).Append('\n');
			_owners.Clear();
			foreach (Owner owner in ModTimer.Owners)
			{
				if (owner.LastSecMsPerFrame > 0.0 || owner.Worst10s > 0.0)
				{
					_owners.Add(owner);
				}
			}
			_owners.Sort(ByOwnerMs);
			int num2 = 0;
			int num3 = 0;
			double num4 = 0.0;
			foreach (Owner owner2 in _owners)
			{
				num4 += owner2.LastSecMsPerFrame;
				if (owner2.LastSecMsPerFrame < 0.005 && owner2.Worst10s < 1.0)
				{
					num3++;
					continue;
				}
				if (num2 >= 22)
				{
					num3++;
					continue;
				}
				num2++;
				string s = (owner2.IsMod ? "" : "[") + Trunc(owner2.Name, 23) + (owner2.IsMod ? "" : "]") + (owner2.Partial ? "*" : "");
				double num5 = ((num > 0.0) ? (owner2.LastSecMsPerFrame / num * 100.0) : 0.0);
				_sb.Append(Pad(s, 26)).Append(C(ModCol(owner2.LastSecMsPerFrame), LPad(owner2.LastSecMsPerFrame.ToString("0.00"), 7))).Append(LPad(num5.ToString("0.0"), 6))
					.Append(LPad(owner2.LastSecCallsPerSec.ToString("0"), 9))
					.Append(C(MsCol(owner2.Worst10s * 3.0), LPad(owner2.Worst10s.ToString("0.00"), 8)))
					.Append('\n');
			}
			double num6 = Math.Max(0.0, num - num4);
			_sb.Append(Pad("untimed (engine, render, wait)", 26)).Append(LPad(num6.ToString("0.00"), 7)).Append(LPad(((num > 0.0) ? (num6 / num * 100.0) : 0.0).ToString("0.0"), 6))
				.Append('\n');
			int num7 = 0;
			foreach (Owner allPlugin in ModTimer.AllPlugins)
			{
				if (allPlugin.Index < 0 || allPlugin.Applied == 0)
				{
					num7++;
				}
			}
			_sb.Append(C("#9A9A9A", num3 + " more under 0.01 ms · " + num7 + " plugins with nothing timed · [x] = game/engine · worst = slowest frame in 10 s")).Append('\n');
			_sb.Append(C("#9A9A9A", "timing cost ~" + ModTimer.OverheadMsPerFrame.ToString("0.00") + " ms/frame" + ((ModTimer.PatchErrors > 0) ? (" · " + ModTimer.PatchErrors + " methods couldn't be patched") : "")));
		}

		private void Hotspots()
		{
			_sb.Append(C("#9A9A9A", Pad("code", 46) + LPad("ms", 7) + LPad("worst", 8))).Append('\n');
			int num = ModTimer.Top(ModTimer.Buckets, _hot, (Bucket b) => b.LastSecMsPerFrame + b.Worst10s / 50.0, 0.002);
			for (int num2 = 0; num2 < num; num2++)
			{
				Bucket bucket = _hot[num2];
				_sb.Append(Pad(Trunc(bucket.Full, 45), 46)).Append(C(ModCol(bucket.LastSecMsPerFrame), LPad(bucket.LastSecMsPerFrame.ToString("0.00"), 7))).Append(C(MsCol(bucket.Worst10s * 3.0), LPad(bucket.Worst10s.ToString("0.0"), 8)))
					.Append('\n');
			}
			if (num == 0)
			{
				_sb.Append(C("#9A9A9A", ModTimer.WarmingUp ? "warming up..." : "nothing timed yet")).Append('\n');
			}
			if (!Phases.Installed)
			{
				_sb.Append(C("#9A9A9A", "Engine phases off" + ((Phases.Error != null) ? (": " + Phases.Error) : "")));
				return;
			}
			_sb.Append(C("#9A9A9A", "Engine steps (ms per frame, last second)")).Append('\n');
			int num3 = Phases.Top(Phases.LastSecMsPerFrame, _hotPh, 0.02);
			for (int num4 = 0; num4 < num3; num4++)
			{
				int num5 = _hotPh[num4];
				_sb.Append(Pad(Trunc(Phases.Names[num5], 45), 46)).Append(C(PhaseCol(Phases.LastSecMsPerFrame[num5]), LPad(Phases.LastSecMsPerFrame[num5].ToString("0.00"), 7))).Append('\n');
			}
		}

		private void SceneP()
		{
			SceneStats scene = _r.Scene;
			FrameStats frames = _r.Frames;
			if (scene.EnemiesAlive >= 0)
			{
				_sb.Append("Enemies ").Append(scene.EnemiesAlive).Append((scene.EnemyTypes.Length > 0) ? (": " + Trunc(scene.EnemyTypes, 90)) : "")
					.Append('\n');
			}
			Row("NetworkObjects", scene.NetObjects);
			Row("  Grabbables", scene.Grabbables);
			Row("  scrap", scene.Scrap);
			_sb.Append('\n');
			Row("Rigidbodies", scene.Bodies);
			Row("  awake", scene.BodiesAwake);
			_sb.Append("  physics steps/frame ").Append(C((frames.FixedMaxPerFrame > 2.0) ? "#FFC04D" : "#7CFC7C", frames.FixedPerFrame.ToString("0.00"))).Append(" (max ")
				.Append(frames.FixedMaxPerFrame.ToString("0"))
				.Append(")\n");
			Row("Lights", scene.Lights);
			Row("  shadow-casting", scene.ShadowLights);
			_sb.Append('\n');
			Row("Audio playing", scene.AudioPlaying);
			Row("  Particles playing", scene.Particles);
			Row("  Cameras", scene.Cameras);
			_sb.Append('\n');
			if (frames.DrawCalls >= 0 || frames.Batches >= 0 || frames.SetPass >= 0)
			{
				RowL("Draw calls", frames.DrawCalls);
				RowL("  Batches", frames.Batches);
				RowL("  SetPass", frames.SetPass);
				_sb.Append('\n');
			}
			if (frames.Tris >= 0 || frames.Verts >= 0)
			{
				RowL("Triangles", frames.Tris);
				RowL("  Vertices", frames.Verts);
				_sb.Append('\n');
			}
			_sb.Append(C("#9A9A9A", "counts refresh every 2 s; lights include ones culled off-screen"));
		}

		private void Row(string label, int v)
		{
			if (v >= 0)
			{
				_sb.Append(label).Append(' ').Append(v)
					.Append("  ");
			}
		}

		private void RowL(string label, long v)
		{
			if (v >= 0)
			{
				_sb.Append(label).Append(' ').Append((v >= 1000000) ? (((double)v / 1000000.0).ToString("0.00") + "M") : ((v >= 1000) ? (((double)v / 1000.0).ToString("0.0") + "k") : v.ToString()))
					.Append("  ");
			}
		}

		private void NetP()
		{
			NetStats net = _r.Net;
			Context ctx = _r.Ctx;
			if (!ctx.Multiplayer)
			{
				_sb.Append(C("#9A9