Decompiled source of Coop Pause v0.1.0

SpellBrigadeCoopPause.dll

Decompiled an hour ago
using System;
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.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using SpellBrigadeCoopPause.Core;
using SpellBrigadeCoopPause.Game;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("SpellBrigadeCoopPause")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+f053912c98933bc2536940c2264611073935b89f")]
[assembly: AssemblyProduct("SpellBrigadeCoopPause")]
[assembly: AssemblyTitle("SpellBrigadeCoopPause")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
namespace SpellBrigadeCoopPause
{
	internal static class ModConfig
	{
		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<string> PauseKey;

		public static ConfigEntry<bool> PauseWithMenu;

		public static ConfigEntry<float> CountdownSeconds;

		public static ConfigEntry<VoteRule> ResumeVote;

		public static ConfigEntry<bool> HostCanForce;

		public static ConfigEntry<float> PauseCooldownSeconds;

		public static void Init(ConfigFile cfg)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			Enabled = cfg.Bind<bool>("General", "Enabled", true, "Let any player pause the run for everyone. As the host, turning this off also ignores your teammates' requests.");
			PauseKey = cfg.Bind<string>("General", "PauseKey", "P", "Key that pauses everyone, and when paused starts the countdown to resume. A Unity Input System key name (P, F9, Backquote, ...).");
			PauseWithMenu = cfg.Bind<bool>("General", "PauseWithMenu", true, "Opening the game's Escape menu also pauses everyone, and closing it starts the countdown (only if your menu started the pause).");
			CountdownSeconds = cfg.Bind<float>("General", "CountdownSeconds", 3f, new ConfigDescription("Countdown before the game goes on after someone resumes. The host's setting is the one everyone gets. 0 resumes at once.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>()));
			ResumeVote = cfg.Bind<VoteRule>("General", "ResumeVote", VoteRule.Majority, "How many players with the mod must press the pause key (vote) before the countdown starts. Majority: more than half (2 of 2, 2 of 3, 3 of 4). Half: at least half (1 of 2, 2 of 3, 2 of 4). All: everyone. The host's setting is the one that counts.");
			HostCanForce = cfg.Bind<bool>("General", "HostCanForce", true, "The host can start the countdown without enough votes by pressing the pause key again after voting.");
			PauseCooldownSeconds = cfg.Bind<float>("General", "PauseCooldownSeconds", 10f, new ConfigDescription("After a pause ends, the player who paused must wait this long before pausing again (the host never waits). The host's setting is the one that counts. 0 turns it off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 120f), Array.Empty<object>()));
		}
	}
	internal static class ModLog
	{
		private static ManualLogSource? _log;

		private static StreamWriter? _file;

		private static readonly HashSet<string> Once = new HashSet<string>();

		private static readonly Dictionary<string, float> Throttle = new Dictionary<string, float>();

		public const string CleanExit = "clean exit";

		public static string FilePath => Path.Combine(Paths.BepInExRootPath, "SpellBrigadeCoopPause.log");

		public static string PreviousFilePath => Path.Combine(Paths.BepInExRootPath, "SpellBrigadeCoopPause.prev.log");

		public static string? PreviousCrashStep { get; private set; }

		public static void Init(ManualLogSource log)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected O, but got Unknown
			_log = log;
			bool flag = default(bool);
			try
			{
				if (File.Exists(FilePath))
				{
					File.Copy(FilePath, PreviousFilePath, overwrite: true);
					string text = null;
					string[] array = File.ReadAllLines(FilePath);
					foreach (string text2 in array)
					{
						int num = text2.IndexOf(" STEP  ", StringComparison.Ordinal);
						if (num >= 0)
						{
							string text3 = text2;
							int num2 = num + 7;
							text = text3.Substring(num2, text3.Length - num2).Trim();
						}
					}
					if (text != null && text != "clean exit")
					{
						PreviousCrashStep = text;
					}
				}
			}
			catch (Exception ex)
			{
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(30, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not read the previous ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(FilePath);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				log.LogWarning(val);
			}
			try
			{
				_file = new StreamWriter(new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
				{
					AutoFlush = true
				};
				_file.WriteLine($"SpellBrigadeCoopPause {"0.1.0"} log, started {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
				if (PreviousCrashStep != null)
				{
					_file.WriteLine("Previous session did not exit cleanly; its last step was: " + PreviousCrashStep + " (log kept as SpellBrigadeCoopPause.prev.log)");
				}
			}
			catch (Exception ex2)
			{
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(17, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not open ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(FilePath);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex2.Message);
				}
				log.LogWarning(val);
			}
		}

		public static void Info(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogInfo((object)msg);
			}
			ToFile("INFO ", msg);
		}

		public static void Warn(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogWarning((object)msg);
			}
			ToFile("WARN ", msg);
		}

		public static void Error(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogError((object)msg);
			}
			ToFile("ERROR", msg);
		}

		public static void Debug(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogDebug((object)msg);
			}
			ToFile("DEBUG", msg);
		}

		public static void Step(string msg)
		{
			ToFile("STEP ", msg);
		}

		public static void StepOnce(string key, string msg)
		{
			if (Once.Add("step:" + key))
			{
				Step(msg);
			}
		}

		public static void InfoOnce(string key, string msg)
		{
			if (Once.Add(key))
			{
				Info(msg);
			}
		}

		public static void WarnOnce(string key, string msg)
		{
			if (Once.Add(key))
			{
				Warn(msg);
			}
		}

		public static void ErrorThrottled(string key, Exception ex, float now, float seconds = 10f)
		{
			if (!Throttle.TryGetValue(key, out var value) || !(now - value < seconds))
			{
				Throttle[key] = now;
				Error($"[{key}] {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
			}
		}

		private static void ToFile(string level, string msg)
		{
			if (_file == null)
			{
				return;
			}
			try
			{
				lock (_file)
				{
					_file.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {level} {msg}");
				}
			}
			catch
			{
			}
		}
	}
	[BepInPlugin("com.stefanws0.spellbrigadecooppause", "SpellBrigadeCoopPause", "0.1.0")]
	public class Plugin : BasePlugin
	{
		public const string Guid = "com.stefanws0.spellbrigadecooppause";

		public const string Name = "SpellBrigadeCoopPause";

		public const string Version = "0.1.0";

		public override void Load()
		{
			ModLog.Init(((BasePlugin)this).Log);
			ModLog.Step("Load: config");
			ModConfig.Init(((BasePlugin)this).Config);
			ModLog.Step("Load: registering PauseRunner");
			PauseRunner.Init();
			((BasePlugin)this).AddComponent<PauseRunner>();
			ModLog.Step("Load: done");
			ModLog.Info($"{"SpellBrigadeCoopPause"} {"0.1.0"} loaded. Pause key: {ModConfig.PauseKey.Value}.");
		}
	}
}
namespace SpellBrigadeCoopPause.Game
{
	internal static class PauseMenuWatch
	{
		private const float LookSeconds = 2f;

		private static PauseMenuManager? _menu;

		private static float _nextLook;

		private static bool _open;

		public static bool IsOpen => _open;

		public static int Update(float now)
		{
			bool flag = false;
			try
			{
				if ((Object)(object)_menu == (Object)null && now >= _nextLook)
				{
					_nextLook = now + 2f;
					ModLog.StepOnce("menu-find", "first PauseMenuManager lookup");
					Il2CppReferenceArray<Object> val = Object.FindObjectsOfType(Il2CppType.Of<PauseMenuManager>(), true);
					if (val != null && ((Il2CppArrayBase<Object>)(object)val).Length > 0)
					{
						Object obj = ((Il2CppArrayBase<Object>)(object)val)[0];
						_menu = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<PauseMenuManager>() : null);
						if ((Object)(object)_menu != (Object)null)
						{
							ModLog.InfoOnce("menu-found", "Found the game's Escape menu.");
						}
					}
				}
				flag = (Object)(object)_menu != (Object)null && _menu.IsOpen;
			}
			catch (Exception ex)
			{
				_menu = null;
				ModLog.ErrorThrottled("menu", ex, now, 60f);
			}
			if (flag == _open)
			{
				return 0;
			}
			_open = flag;
			if (!flag)
			{
				return -1;
			}
			return 1;
		}
	}
	internal static class PauseNet
	{
		public const string MessageName = "SpellBrigadeCoopPause.State";

		public const ulong ServerClientId = 0uL;

		private static HandleNamedMessageDelegate? _handler;

		private static IntPtr _registeredOn;

		public static Action<ulong, PauseRequest>? RequestReceived;

		public static Action<PauseState>? StateReceived;

		public static Action<ulong>? HelloReceived;

		public static Action<List<ulong>>? MissingReceived;

		public static Action<int>? DeniedReceived;

		public static NetworkManager? Manager
		{
			get
			{
				try
				{
					return NetworkManager.Singleton;
				}
				catch
				{
					return null;
				}
			}
		}

		public static bool Connected(NetworkManager? nm)
		{
			if ((Object)(object)nm != (Object)null && nm.IsListening)
			{
				return nm.CustomMessagingManager != null;
			}
			return false;
		}

		public static bool IsHost(NetworkManager? nm)
		{
			if (Connected(nm))
			{
				return nm.IsServer;
			}
			return false;
		}

		public static ulong LocalClientId(NetworkManager? nm)
		{
			if (!Connected(nm))
			{
				return 0uL;
			}
			return nm.LocalClientId;
		}

		public static bool InCoop(NetworkManager? nm)
		{
			try
			{
				if (!Connected(nm))
				{
					return false;
				}
				if (!nm.IsServer)
				{
					return true;
				}
				foreach (ulong playerId in PlayerNames.PlayerIds)
				{
					if (playerId != 0L)
					{
						return true;
					}
				}
				return false;
			}
			catch
			{
				return false;
			}
		}

		public static bool IsConnected(NetworkManager? nm, ulong client)
		{
			try
			{
				if (!IsHost(nm))
				{
					return true;
				}
				return client == 0L || nm.ConnectedClients.ContainsKey(client);
			}
			catch
			{
				return true;
			}
		}

		public static void EnsureHandler(NetworkManager? nm)
		{
			if (!Connected(nm))
			{
				_registeredOn = IntPtr.Zero;
				return;
			}
			CustomMessagingManager customMessagingManager = nm.CustomMessagingManager;
			if (!(_registeredOn == ((Il2CppObjectBase)customMessagingManager).Pointer))
			{
				ModLog.Step("PauseNet: registering the named message handler");
				if (_handler == null)
				{
					_handler = DelegateSupport.ConvertDelegate<HandleNamedMessageDelegate>((Delegate)new Action<ulong, FastBufferReader>(OnReceived));
				}
				customMessagingManager.RegisterNamedMessageHandler("SpellBrigadeCoopPause.State", _handler);
				_registeredOn = ((Il2CppObjectBase)customMessagingManager).Pointer;
				ModLog.Info($"Listening for co-op pause messages ({(nm.IsServer ? "host" : "client")}, client id {nm.LocalClientId}).");
			}
		}

		public static void SendRequest(NetworkManager nm, PauseRequest request)
		{
			Send(nm, PauseRequestCodec.Encode(request), toServer: true);
		}

		public static void SendHello(NetworkManager nm)
		{
			Send(nm, ModdedRoster.EncodeHello(), toServer: true);
		}

		public static void BroadcastMissing(NetworkManager nm, IEnumerable<ulong> missing)
		{
			Send(nm, ModdedRoster.EncodeMissing(missing), toServer: false);
		}

		public static void SendDenied(NetworkManager nm, ulong client, int msLeft)
		{
			Send(nm, PauseRequestCodec.EncodeDenied(msLeft), toServer: false, client);
		}

		public static void Broadcast(NetworkManager nm, PauseState state)
		{
			Send(nm, state.Encode(), toServer: false);
		}

		private static void Send(NetworkManager nm, string payload, bool toServer, ulong? to = null)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(payload.Length * 2 + 64, (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(payload, false);
					CustomMessagingManager customMessagingManager = nm.CustomMessagingManager;
					if (toServer)
					{
						customMessagingManager.SendNamedMessage("SpellBrigadeCoopPause.State", 0uL, val, (NetworkDelivery)3);
					}
					else if (to.HasValue)
					{
						customMessagingManager.SendNamedMessage("SpellBrigadeCoopPause.State", to.Value, val, (NetworkDelivery)3);
					}
					else
					{
						customMessagingManager.SendNamedMessageToAll("SpellBrigadeCoopPause.State", val, (NetworkDelivery)3);
					}
				}
				finally
				{
					((FastBufferWriter)(ref val)).Dispose();
				}
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("send", ex, Time.unscaledTime);
			}
		}

		private static void OnReceived(ulong sender, FastBufferReader reader)
		{
			try
			{
				string text = default(string);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
				if (IsHost(Manager))
				{
					if (PauseRequestCodec.TryDecode(text, out var request))
					{
						RequestReceived?.Invoke(sender, request);
					}
					else if (ModdedRoster.IsHello(text))
					{
						HelloReceived?.Invoke(sender);
					}
				}
				else if (sender == 0L)
				{
					int msLeft;
					List<ulong> missing;
					if (PauseState.TryDecode(text, out var state))
					{
						StateReceived?.Invoke(state);
					}
					else if (PauseRequestCodec.TryDecodeDenied(text, out msLeft))
					{
						DeniedReceived?.Invoke(msLeft);
					}
					else if (ModdedRoster.TryDecodeMissing(text, out missing))
					{
						MissingReceived?.Invoke(missing);
					}
					else
					{
						ModLog.WarnOnce("bad-payload", "Ignored a co-op pause message this version doesn't understand: '" + text + "'.");
					}
				}
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("receive", ex, Time.unscaledTime);
			}
		}
	}
	internal static class PauseOverlay
	{
		private const int UiLayer = 5;

		private const int SortingOrder = 30000;

		private const float FontRetrySeconds = 2f;

		private static readonly Color VeilColor = new Color(0f, 0f, 0f, 0.55f);

		private static readonly Color TextColor = new Color(0.99f, 0.97f, 0.81f, 1f);

		private static GameObject? _root;

		private static Image? _veil;

		private static TextMeshProUGUI? _big;

		private static TextMeshProUGUI? _small;

		private static TMP_FontAsset? _font;

		private static float _nextFontTry;

		private static string _shownBig = "";

		private static string _shownSmall = "";

		public static void Hide()
		{
			if ((Object)(object)_root != (Object)null && _root.activeSelf)
			{
				_root.SetActive(false);
			}
		}

		public static void Show(string big, string small, bool veil, Color? accent, float now)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			if (Ensure(now))
			{
				if (!_root.activeSelf)
				{
					_root.SetActive(true);
				}
				if (((Behaviour)_veil).enabled != veil)
				{
					((Behaviour)_veil).enabled = veil;
				}
				if (_shownBig != big)
				{
					((TMP_Text)_big).text = big;
					_shownBig = big;
				}
				if (_shownSmall != small)
				{
					((TMP_Text)_small).text = small;
					_shownSmall = small;
				}
				((Graphic)_big).color = (Color)(((??)accent) ?? TextColor);
				if ((Object)(object)_font == (Object)null && now >= _nextFontTry)
				{
					TryGameFont(now);
				}
			}
		}

		private static bool Ensure(float now)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_root != (Object)null)
			{
				return true;
			}
			try
			{
				ModLog.Step("PauseOverlay: creating the canvas");
				_root = new GameObject("SpellBrigadeCoopPause");
				_root.layer = 5;
				Object.DontDestroyOnLoad((Object)(object)_root);
				Canvas obj = _root.AddComponent<Canvas>();
				obj.renderMode = (RenderMode)0;
				obj.sortingOrder = 30000;
				CanvasScaler obj2 = _root.AddComponent<CanvasScaler>();
				obj2.uiScaleMode = (ScaleMode)1;
				obj2.referenceResolution = new Vector2(1920f, 1080f);
				obj2.matchWidthOrHeight = 1f;
				GameObject val = new GameObject("Veil")
				{
					layer = 5
				};
				val.transform.SetParent(_root.transform, false);
				_veil = val.AddComponent<Image>();
				((Graphic)_veil).color = VeilColor;
				((Graphic)_veil).raycastTarget = false;
				Stretch(((Graphic)_veil).rectTransform, Vector2.zero, Vector2.one);
				_big = NewText("Big", 160f, new Vector2(0f, 0.45f), new Vector2(1f, 0.75f));
				_small = NewText("Small", 40f, new Vector2(0f, 0.2f), new Vector2(1f, 0.45f));
				TryGameFont(now);
				_root.SetActive(false);
				ModLog.Step("PauseOverlay: canvas created");
				return true;
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("overlay", ex, now, 60f);
				if ((Object)(object)_root != (Object)null)
				{
					Object.Destroy((Object)(object)_root);
				}
				_root = null;
				return false;
			}
		}

		private static TextMeshProUGUI NewText(string name, float size, Vector2 anchorMin, Vector2 anchorMax)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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)
			GameObject val = new GameObject(name)
			{
				layer = 5
			};
			val.transform.SetParent(_root.transform, false);
			TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)obj).fontSize = size;
			((Graphic)obj).color = TextColor;
			((TMP_Text)obj).alignment = (TextAlignmentOptions)514;
			((TMP_Text)obj).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)obj).overflowMode = (TextOverflowModes)0;
			((TMP_Text)obj).richText = false;
			((Graphic)obj).raycastTarget = false;
			((TMP_Text)obj).outlineWidth = 0.15f;
			((TMP_Text)obj).outlineColor = new Color32((byte)0, (byte)0, (byte)0, byte.MaxValue);
			Stretch(((TMP_Text)obj).rectTransform, anchorMin, anchorMax);
			return obj;
		}

		private static void Stretch(RectTransform rt, Vector2 anchorMin, Vector2 anchorMax)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: 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)
			rt.anchorMin = anchorMin;
			rt.anchorMax = anchorMax;
			rt.offsetMin = Vector2.zero;
			rt.offsetMax = Vector2.zero;
		}

		private static void TryGameFont(float now)
		{
			_nextFontTry = now + 2f;
			try
			{
				Il2CppArrayBase<TextMeshProUGUI> obj = Object.FindObjectsOfType<TextMeshProUGUI>();
				Dictionary<IntPtr, (TMP_FontAsset, int)> dictionary = new Dictionary<IntPtr, (TMP_FontAsset, int)>();
				foreach (TextMeshProUGUI item in obj)
				{
					if (!((Object)(object)item == (Object)null) && ((Behaviour)item).isActiveAndEnabled && !((Object)(object)item == (Object)(object)_big) && !((Object)(object)item == (Object)(object)_small))
					{
						TMP_FontAsset font = ((TMP_Text)item).font;
						if (!((Object)(object)font == (Object)null))
						{
							dictionary.TryGetValue(((Il2CppObjectBase)font).Pointer, out var value);
							dictionary[((Il2CppObjectBase)font).Pointer] = (font, value.Item2 + 1);
						}
					}
				}
				if (dictionary.Count != 0)
				{
					_font = dictionary.Values.OrderByDescending<(TMP_FontAsset, int), int>(((TMP_FontAsset font, int n) e) => e.n).First().Item1;
					if ((Object)(object)_big != (Object)null)
					{
						((TMP_Text)_big).font = _font;
					}
					if ((Object)(object)_small != (Object)null)
					{
						((TMP_Text)_small).font = _font;
					}
					ModLog.Info("Pause text uses the game's font '" + ((Object)_font).name + "'.");
				}
			}
			catch (Exception ex)
			{
				_nextFontTry = now + 30f;
				ModLog.ErrorThrottled("font", ex, now, 60f);
			}
		}
	}
	public class PauseRunner : MonoBehaviour
	{
		private const float HeartbeatSeconds = 1f;

		private static readonly PauseSession Session = new PauseSession();

		private static readonly PauseView View = new PauseView();

		private static readonly TimeScaleKeeper Keeper = new TimeScaleKeeper();

		private static readonly ModdedRoster Roster = new ModdedRoster();

		private static List<ulong> _missing = new List<ulong>();

		private static string _missingKey = "";

		private static float _nextHello;

		private static bool _wasConnected;

		private static bool _wasInRun;

		private static int _broadcastEpoch = -1;

		private static float _nextHeartbeat;

		private static PauseState _lastBroadcast = PauseState.Running(-1);

		private static float _askedAt = -1f;

		private static float _noHostModUntil = -1f;

		private static float _deniedUntil = -1f;

		private static string _deniedText = "";

		private static bool _wasCoop;

		private static bool _menuPaused;

		private static bool _menuSawPause;

		private const float NoAnswerSeconds = 2f;

		public PauseRunner(IntPtr ptr)
			: base(ptr)
		{
		}

		public static void Init()
		{
			PauseNet.RequestReceived = OnRequest;
			PauseNet.StateReceived = delegate(PauseState state)
			{
				View.Apply(state, Time.unscaledTime);
			};
			PauseNet.HelloReceived = delegate(ulong client)
			{
				Roster.Hello(client, Time.unscaledTime);
			};
			PauseNet.MissingReceived = delegate(List<ulong> missing)
			{
				_missing = missing;
			};
			PauseNet.DeniedReceived = delegate(int ms)
			{
				ShowDenied((float)ms / 1000f, Time.unscaledTime);
			};
		}

		public void Update()
		{
			float unscaledTime = Time.unscaledTime;
			try
			{
				NetworkManager manager = PauseNet.Manager;
				PauseNet.EnsureHandler(manager);
				bool flag = PauseNet.Connected(manager);
				bool flag2 = !flag || PauseNet.IsHost(manager);
				bool flag3 = InRun();
				bool flag4 = PauseNet.InCoop(manager);
				if (!flag4 && _wasCoop)
				{
					LeaveCoop(manager, flag2, unscaledTime);
				}
				_wasCoop = flag4;
				if (flag != _wasConnected)
				{
					_wasConnected = flag;
					LeaveSession(flag ? "joined a session" : "left the session");
				}
				if (_wasInRun && !flag3)
				{
					EndRun(manager, flag2, unscaledTime);
				}
				_wasInRun = flag3;
				int menu = PauseMenuWatch.Update(unscaledTime);
				if (flag3 && flag4 && ModConfig.Enabled.Value)
				{
					HandleInput(manager, flag2, menu, unscaledTime);
				}
				else
				{
					_menuPaused = false;
				}
				if (flag && !flag2 && unscaledTime >= _nextHello)
				{
					_nextHello = unscaledTime + 5f;
					PauseNet.SendHello(manager);
				}
				if (flag2)
				{
					if (Session.Tick(unscaledTime))
					{
						ModLog.Info("Countdown over: back to the game.");
					}
					TryResumeByVote(manager, unscaledTime);
					Publish(manager, flag, unscaledTime);
				}
				if (View.Tick(unscaledTime, flag && !flag2) && !flag2)
				{
					ModLog.Info("Unfrozen (countdown over, or the host stopped answering).");
				}
				if (View.HeardFromHost)
				{
					_askedAt = -1f;
				}
				else if (_askedAt >= 0f && unscaledTime - _askedAt > 2f)
				{
					_askedAt = -1f;
					_noHostModUntil = unscaledTime + 4f;
					ModLog.Warn("The host didn't answer the pause request: it probably doesn't have Co-op Pause installed.");
				}
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("runner", ex, unscaledTime);
			}
		}

		public void LateUpdate()
		{
			float unscaledTime = Time.unscaledTime;
			try
			{
				float? num = Keeper.Update(View.Frozen, Time.timeScale);
				if (num.HasValue)
				{
					ModLog.StepOnce($"timescale-{num.Value}", $"first Time.timeScale = {num.Value}");
					Time.timeScale = num.Value;
				}
				DrawOverlay(unscaledTime);
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("late", ex, unscaledTime);
			}
		}

		public void OnApplicationQuit()
		{
			if (Keeper.Holding)
			{
				Time.timeScale = 1f;
			}
			ModLog.Step("clean exit");
		}

		private static void HandleInput(NetworkManager? nm, bool host, int menu, float now)
		{
			if (PausePressed())
			{
				_menuPaused = false;
				ulong client = PauseNet.LocalClientId(nm);
				PauseRequest request = ((View.Phase != PausePhase.Paused) ? PauseRequest.Pause : ((!View.HasVoted(client)) ? PauseRequest.Resume : ((!host || !ModConfig.HostCanForce.Value) ? PauseRequest.Unvote : PauseRequest.Force)));
				Ask(nm, host, now, request);
				return;
			}
			if (_menuPaused)
			{
				if (View.Phase == PausePhase.Paused)
				{
					_menuSawPause = true;
				}
				else if (_menuSawPause)
				{
					_menuPaused = false;
				}
			}
			if (!ModConfig.PauseWithMenu.Value)
			{
				return;
			}
			if (menu > 0 && View.Phase != PausePhase.Paused)
			{
				_menuPaused = true;
				_menuSawPause = false;
				ModLog.Info("Escape menu opened: pausing everyone.");
				Ask(nm, host, now, PauseRequest.Pause);
			}
			else if (menu < 0 && _menuPaused)
			{
				_menuPaused = false;
				if (View.Phase == PausePhase.Paused && !View.HasVoted(PauseNet.LocalClientId(nm)))
				{
					ModLog.Info("Escape menu closed: voting to go on.");
					Ask(nm, host, now, PauseRequest.Resume);
				}
			}
		}

		private static void Ask(NetworkManager? nm, bool host, float now, PauseRequest request)
		{
			if (host)
			{
				OnRequest(PauseNet.LocalClientId(nm), request);
				return;
			}
			ModLog.Info($"Asking the host: {request}.");
			PauseNet.SendRequest(nm, request);
			if (!View.HeardFromHost && _askedAt < 0f)
			{
				_askedAt = now;
			}
		}

		private static void OnRequest(ulong client, PauseRequest request)
		{
			float unscaledTime = Time.unscaledTime;
			if (!ModConfig.Enabled.Value || !InRun())
			{
				return;
			}
			NetworkManager manager = PauseNet.Manager;
			bool flag;
			switch (request)
			{
			case PauseRequest.Pause:
			{
				float num = ((Session.Phase == PausePhase.Paused) ? 0f : Session.CooldownLeft(client, unscaledTime, ModConfig.PauseCooldownSeconds.Value, 0uL));
				if (num > 0f)
				{
					ModLog.Info($"Player {client} may not pause for another {num:0.0} s (cooldown).");
					if (client == PauseNet.LocalClientId(manager))
					{
						ShowDenied(num, unscaledTime);
					}
					else if (PauseNet.Connected(manager))
					{
						PauseNet.SendDenied(manager, client, (int)(num * 1000f));
					}
					return;
				}
				flag = Session.RequestPause(client);
				if (flag)
				{
					ModLog.Info($"Paused by player {client}.");
				}
				break;
			}
			case PauseRequest.Force:
				if (client != 0L || !ModConfig.HostCanForce.Value)
				{
					return;
				}
				flag = Session.StartCountdown(unscaledTime, ModConfig.CountdownSeconds.Value);
				if (flag)
				{
					ModLog.Info("The host forced the countdown.");
				}
				break;
			case PauseRequest.Unvote:
				flag = Session.Unvote(client);
				if (flag)
				{
					ModLog.Info($"Player {client} took their vote back.");
				}
				break;
			default:
				flag = Session.Vote(client);
				if (flag)
				{
					ModLog.Info($"Player {client} votes to go on.");
				}
				flag |= TryResumeByVote(manager, unscaledTime);
				break;
			}
			if (flag)
			{
				Publish(manager, PauseNet.Connected(manager), unscaledTime);
			}
		}

		private static HashSet<ulong> Voters(NetworkManager? nm, float now)
		{
			HashSet<ulong> hashSet = new HashSet<ulong> { 0uL };
			foreach (ulong item in Roster.Modded(now))
			{
				if (PauseNet.IsConnected(nm, item))
				{
					hashSet.Add(item);
				}
			}
			return hashSet;
		}

		private static bool TryResumeByVote(NetworkManager? nm, float now)
		{
			HashSet<ulong> hashSet = Voters(nm, now);
			if (!Session.TryResumeByVote(hashSet, ModConfig.ResumeVote.Value, now, ModConfig.CountdownSeconds.Value))
			{
				return false;
			}
			ModLog.Info($"Enough votes ({VoteRules.Needed(hashSet.Count, ModConfig.ResumeVote.Value)} of {hashSet.Count}): {ModConfig.CountdownSeconds.Value:0.#} s countdown.");
			return true;
		}

		private static string MissingLine()
		{
			if (_missing.Count == 0)
			{
				return "";
			}
			string value = ((_missing.Count == 1) ? "doesn't" : "don't");
			return $"\n{PlayerNames.List(_missing)} {value} have Co-op Pause: they can still move";
		}

		private static void ShowDenied(float secondsLeft, float now)
		{
			int value = (int)Math.Ceiling(secondsLeft);
			_deniedText = $"You can pause again in {value} s";
			_deniedUntil = now + 2f;
			_askedAt = -1f;
			_menuPaused = false;
		}

		private static bool PausePressed()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			Keyboard current = Keyboard.current;
			if (current == null)
			{
				return false;
			}
			string value = ModConfig.PauseKey.Value;
			if (string.IsNullOrEmpty(value) || !Enum.TryParse<Key>(value, ignoreCase: true, out Key result) || (int)result == 0)
			{
				return false;
			}
			KeyControl val = current[result];
			if (val != null)
			{
				return ((ButtonControl)val).wasPressedThisFrame;
			}
			return false;
		}

		private static void Publish(NetworkManager? nm, bool connected, float now)
		{
			PauseState pauseState = Session.Snapshot(now, Voters(nm, now), ModConfig.ResumeVote.Value);
			bool flag = pauseState.Epoch != _broadcastEpoch || !pauseState.Equals(_lastBroadcast);
			if (flag)
			{
				_broadcastEpoch = pauseState.Epoch;
				_lastBroadcast = pauseState;
				View.Apply(pauseState, now);
			}
			if (!connected)
			{
				return;
			}
			bool flag2 = Session.Phase != PausePhase.Running && now >= _nextHeartbeat;
			if (flag || flag2)
			{
				_nextHeartbeat = now + 1f;
				PauseNet.Broadcast(nm, pauseState);
				if (Session.Phase != PausePhase.Running)
				{
					PublishMissing(nm, now);
				}
			}
		}

		private static void PublishMissing(NetworkManager nm, float now)
		{
			_missing = Roster.Missing(PlayerNames.PlayerIds, 0uL, now);
			string text = string.Join(",", _missing);
			if (text != _missingKey)
			{
				_missingKey = text;
				ModLog.Info((_missing.Count == 0) ? "Everyone in the run has Co-op Pause." : ("Players without Co-op Pause: " + text + "."));
			}
			PauseNet.BroadcastMissing(nm, _missing);
		}

		private static void EndRun(NetworkManager? nm, bool host, float now)
		{
			if (host && Session.ForceRun())
			{
				ModLog.Info("Run over while paused: unpaused.");
				Publish(nm, PauseNet.Connected(nm), now);
			}
			Session.ClearCooldowns();
			if (View.Reset())
			{
				ModLog.Info("Run over: unfrozen.");
			}
		}

		private static void LeaveCoop(NetworkManager? nm, bool host, float now)
		{
			_menuPaused = false;
			if (host && Session.ForceRun())
			{
				ModLog.Info("Everyone else left: unpaused (the mod is off in single player).");
				Publish(nm, PauseNet.Connected(nm), now);
			}
			if (View.Reset())
			{
				ModLog.Info("Single player again: unfrozen.");
			}
		}

		private static void LeaveSession(string why)
		{
			Session.ForceRun();
			Session.ClearCooldowns();
			Roster.Clear();
			_missing = new List<ulong>();
			_missingKey = "";
			_nextHello = 0f;
			_broadcastEpoch = -1;
			_askedAt = -1f;
			if (View.Reset())
			{
				ModLog.Info("Unfrozen: " + why + ".");
			}
		}

		private static bool InRun()
		{
			try
			{
				RunManager instance = NetworkSingleton<RunManager>.Instance;
				return (Object)(object)instance != (Object)null && instance.runHasStarted;
			}
			catch
			{
				return false;
			}
		}

		private static void DrawOverlay(float now)
		{
			if (!ModConfig.Enabled.Value)
			{
				PauseOverlay.Hide();
				return;
			}
			NetworkManager manager = PauseNet.Manager;
			if (PauseMenuWatch.IsOpen)
			{
				PauseOverlay.Hide();
				return;
			}
			string text = ModConfig.PauseKey.Value.ToUpperInvariant();
			switch (View.Phase)
			{
			case PausePhase.Paused:
			{
				ulong num = PauseNet.LocalClientId(manager);
				bool flag = !PauseNet.Connected(manager) || PauseNet.IsHost(manager);
				string text2 = ((View.PausedBy == num) ? "You paused" : (PlayerNames.Of(View.PausedBy) + " paused"));
				string text3 = ((View.Needed > 1) ? $"  ·  votes to go on: {View.Voted.Count}/{View.Needed}" : "");
				string text4 = ((!View.HasVoted(num)) ? ("press " + text + " to vote to go on") : ((flag && ModConfig.HostCanForce.Value) ? ("you voted  ·  press " + text + " again to go on anyway") : ("you voted  ·  press " + text + " to take it back")));
				string small = text2 + text3 + "\n" + text4 + MissingLine();
				PauseOverlay.Show("PAUSED", small, veil: true, PlayerNames.ColorOf(View.PausedBy), now);
				break;
			}
			case PausePhase.Countdown:
				PauseOverlay.Show(View.CountdownNumber(now).ToString(), "press " + text + " to pause again" + MissingLine(), veil: true, null, now);
				break;
			default:
				if (View.ShowGo(now))
				{
					PauseOverlay.Show("GO!", "", veil: false, null, now);
				}
				else if (now < _deniedUntil)
				{
					PauseOverlay.Show("", _deniedText, veil: false, null, now);
				}
				else if (now < _noHostModUntil)
				{
					PauseOverlay.Show("", "Can't pause: the host needs Co-op Pause installed", veil: false, null, now);
				}
				else
				{
					PauseOverlay.Hide();
				}
				break;
			}
		}
	}
	internal static class PlayerNames
	{
		private const float LookSeconds = 2f;

		private const int MaxLength = 24;

		private static readonly Dictionary<ulong, string> Names = new Dictionary<ulong, string>();

		private static float _nextLook = -1f;

		private static readonly HashSet<ulong> Ids = new HashSet<ulong>();

		public static IEnumerable<ulong> PlayerIds
		{
			get
			{
				float unscaledTime = Time.unscaledTime;
				if (unscaledTime >= _nextLook)
				{
					Refresh(unscaledTime);
				}
				return Ids;
			}
		}

		public static string Of(ulong clientId)
		{
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime >= _nextLook)
			{
				Refresh(unscaledTime);
			}
			if (Names.TryGetValue(clientId, out string value))
			{
				return value;
			}
			if (clientId != 0L)
			{
				return "A teammate";
			}
			return "The host";
		}

		private static void Refresh(float now)
		{
			_nextLook = now + 2f;
			try
			{
				ModLog.StepOnce("names", "first GameplayPlayerIdentity name lookup");
				Names.Clear();
				Ids.Clear();
				foreach (Object item in (Il2CppArrayBase<Object>)(object)Object.FindObjectsOfType(Il2CppType.Of<GameplayPlayerIdentity>()))
				{
					GameplayPlayerIdentity val = ((item != null) ? ((Il2CppObjectBase)item).TryCast<GameplayPlayerIdentity>() : null);
					if ((Object)(object)val == (Object)null)
					{
						continue;
					}
					Ids.Add(((NetworkBehaviour)val).OwnerClientId);
					string displayName = val.GetDisplayName();
					if (!string.IsNullOrWhiteSpace(displayName))
					{
						displayName = displayName.Trim();
						if (displayName.Length > 24)
						{
							displayName = displayName.Substring(0, 23) + "…";
						}
						Names[((NetworkBehaviour)val).OwnerClientId] = displayName;
					}
				}
				ModLog.InfoOnce("names-found", $"Player names for the pause screen: {Names.Count} found.");
			}
			catch (Exception ex)
			{
				_nextLook = now + 30f;
				ModLog.ErrorThrottled("player-name", ex, now, 60f);
			}
		}

		public static string List(IReadOnlyList<ulong> clients)
		{
			List<string> list = new List<string>();
			foreach (ulong client in clients)
			{
				list.Add(Names.TryGetValue(client, out string value) ? value : ((client == 0L) ? "The host" : "A teammate"));
			}
			if (list.Count <= 1)
			{
				if (list.Count != 1)
				{
					return "";
				}
				return list[0];
			}
			return string.Join(", ", list.GetRange(0, list.Count - 1)) + " and " + list[list.Count - 1];
		}

		public static Color? ColorOf(ulong clientId)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameplayPlayerManager instance = Singleton<GameplayPlayerManager>.Instance;
				PlayerDisplayInfo val = (((Object)(object)instance != (Object)null) ? instance.GetPlayerDisplayInfo(clientId) : null);
				if (val == (PlayerDisplayInfo)null)
				{
					return null;
				}
				Color color = val.Color;
				color.a = 1f;
				return color;
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("player-color", ex, Time.unscaledTime, 60f);
				return null;
			}
		}
	}
}
namespace SpellBrigadeCoopPause.Core
{
	public sealed class ModdedRoster
	{
		public const float HelloSeconds = 5f;

		public const float ForgetSeconds = 15f;

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

		public void Hello(ulong client, float now)
		{
			_lastHello[client] = now;
		}

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

		public bool IsModded(ulong client, float now)
		{
			if (_lastHello.TryGetValue(client, out var value))
			{
				return now - value <= 15f;
			}
			return false;
		}

		public IEnumerable<ulong> Modded(float now)
		{
			return from e in _lastHello
				where now - e.Value <= 15f
				select e.Key;
		}

		public List<ulong> Missing(IEnumerable<ulong> players, ulong hostClient, float now)
		{
			return (from p in players.Where((ulong p) => p != hostClient && !IsModded(p, now)).Distinct()
				orderby p
				select p).ToList();
		}

		public static string EncodeHello()
		{
			return "CP1;H";
		}

		public static bool IsHello(string? payload)
		{
			return payload == "CP1;H";
		}

		public static string EncodeMissing(IEnumerable<ulong> missing)
		{
			return "CP1;M;" + string.Join(",", missing.Select((ulong m) => m.ToString(CultureInfo.InvariantCulture)));
		}

		public static bool TryDecodeMissing(string? payload, out List<ulong> missing)
		{
			missing = new List<ulong>();
			string text = "CP1;M;";
			if (payload == null || !payload.StartsWith(text, StringComparison.Ordinal))
			{
				return false;
			}
			string text2 = payload.Substring(text.Length);
			if (text2.Length == 0)
			{
				return true;
			}
			string[] array = text2.Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				if (!ulong.TryParse(array[i], NumberStyles.None, CultureInfo.InvariantCulture, out var result))
				{
					return false;
				}
				missing.Add(result);
			}
			return true;
		}
	}
	public enum VoteRule
	{
		Majority,
		Half,
		All
	}
	public static class VoteRules
	{
		public static int Needed(int voters, VoteRule rule)
		{
			if (voters <= 1)
			{
				return 1;
			}
			return rule switch
			{
				VoteRule.Half => (voters + 1) / 2, 
				VoteRule.All => voters, 
				_ => voters / 2 + 1, 
			};
		}
	}
	public sealed class PauseSession
	{
		private PausePhase _phase;

		private ulong _pausedBy;

		private float _countdownEndsAt;

		private int _epoch;

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

		private readonly HashSet<ulong> _votes = new HashSet<ulong>();

		public PausePhase Phase => _phase;

		public ulong PausedBy => _pausedBy;

		public int Epoch => _epoch;

		public bool HasVoted(ulong client)
		{
			return _votes.Contains(client);
		}

		public bool RequestPause(ulong client)
		{
			if (_phase == PausePhase.Paused)
			{
				return false;
			}
			_phase = PausePhase.Paused;
			_pausedBy = client;
			_votes.Clear();
			_epoch++;
			return true;
		}

		public bool Vote(ulong client)
		{
			if (_phase != PausePhase.Paused || !_votes.Add(client))
			{
				return false;
			}
			_epoch++;
			return true;
		}

		public bool Unvote(ulong client)
		{
			if (_phase != PausePhase.Paused || !_votes.Remove(client))
			{
				return false;
			}
			_epoch++;
			return true;
		}

		public List<ulong> VotesFrom(ICollection<ulong> voters)
		{
			return (from v in _votes.Where(voters.Contains)
				orderby v
				select v).ToList();
		}

		public bool TryResumeByVote(ICollection<ulong> voters, VoteRule rule, float now, float countdownSeconds)
		{
			if (_phase != PausePhase.Paused)
			{
				return false;
			}
			if (VotesFrom(voters).Count < VoteRules.Needed(voters.Count, rule))
			{
				return false;
			}
			return StartCountdown(now, countdownSeconds);
		}

		public bool StartCountdown(float now, float countdownSeconds)
		{
			if (_phase != PausePhase.Paused)
			{
				return false;
			}
			_epoch++;
			_votes.Clear();
			_resumedAt[_pausedBy] = now;
			if (countdownSeconds <= 0f)
			{
				_phase = PausePhase.Running;
				return true;
			}
			_phase = PausePhase.Countdown;
			_countdownEndsAt = now + countdownSeconds;
			return true;
		}

		public float CooldownLeft(ulong client, float now, float cooldown, ulong hostClient)
		{
			if (client == hostClient || cooldown <= 0f || !_resumedAt.TryGetValue(client, out var value))
			{
				return 0f;
			}
			float num = value + cooldown - now;
			if (!(num > 0f))
			{
				return 0f;
			}
			return num;
		}

		public void ClearCooldowns()
		{
			_resumedAt.Clear();
		}

		public bool Tick(float now)
		{
			if (_phase != PausePhase.Countdown || now < _countdownEndsAt)
			{
				return false;
			}
			_phase = PausePhase.Running;
			_epoch++;
			return true;
		}

		public bool ForceRun()
		{
			if (_phase == PausePhase.Running)
			{
				return false;
			}
			_phase = PausePhase.Running;
			_votes.Clear();
			_epoch++;
			return true;
		}

		public PauseState Snapshot(float now, ICollection<ulong> voters, VoteRule rule)
		{
			int countdownMs = ((_phase == PausePhase.Countdown) ? Ms(_countdownEndsAt - now) : 0);
			bool flag = _phase == PausePhase.Paused;
			return new PauseState(_phase, (_phase == PausePhase.Running) ? 0 : _pausedBy, countdownMs, _epoch, flag ? VotesFrom(voters) : new List<ulong>(), flag ? VoteRules.Needed(voters.Count, rule) : 0);
		}

		private static int Ms(float seconds)
		{
			if (!(seconds <= 0f))
			{
				return (int)(seconds * 1000f + 0.5f);
			}
			return 0;
		}
	}
	public enum PausePhase : byte
	{
		Running,
		Paused,
		Countdown
	}
	public readonly struct PauseState : IEquatable<PauseState>
	{
		public const string Prefix = "CP1";

		private static readonly ulong[] NoVotes = new ulong[0];

		private readonly IReadOnlyList<ulong>? _voted;

		public PausePhase Phase { get; }

		public ulong PausedBy { get; }

		public int CountdownMs { get; }

		public int Epoch { get; }

		public IReadOnlyList<ulong> Voted => _voted ?? NoVotes;

		public int Needed { get; }

		public PauseState(PausePhase phase, ulong pausedBy, int countdownMs, int epoch, IReadOnlyList<ulong>? voted = null, int needed = 0)
		{
			Phase = phase;
			PausedBy = pausedBy;
			CountdownMs = ((countdownMs >= 0) ? countdownMs : 0);
			Epoch = epoch;
			_voted = voted;
			Needed = ((needed >= 0) ? needed : 0);
		}

		public static PauseState Running(int epoch)
		{
			return new PauseState(PausePhase.Running, 0uL, 0, epoch);
		}

		public string Encode()
		{
			return string.Join(";", "CP1", "S", ((byte)Phase).ToString(CultureInfo.InvariantCulture), PausedBy.ToString(CultureInfo.InvariantCulture), CountdownMs.ToString(CultureInfo.InvariantCulture), Epoch.ToString(CultureInfo.InvariantCulture), Needed.ToString(CultureInfo.InvariantCulture), string.Join(",", Voted.Select((ulong v) => v.ToString(CultureInfo.InvariantCulture))));
		}

		public static bool TryDecode(string? payload, out PauseState state)
		{
			state = default(PauseState);
			if (payload == null)
			{
				return false;
			}
			string[] array = payload.Split(';');
			if (array.Length != 8 || array[0] != "CP1" || array[1] != "S")
			{
				return false;
			}
			if (!byte.TryParse(array[2], NumberStyles.None, CultureInfo.InvariantCulture, out var result) || result > 2)
			{
				return false;
			}
			if (!ulong.TryParse(array[3], NumberStyles.None, CultureInfo.InvariantCulture, out var result2))
			{
				return false;
			}
			if (!int.TryParse(array[4], NumberStyles.None, CultureInfo.InvariantCulture, out var result3))
			{
				return false;
			}
			if (!int.TryParse(array[5], NumberStyles.None, CultureInfo.InvariantCulture, out var result4))
			{
				return false;
			}
			if (!int.TryParse(array[6], NumberStyles.None, CultureInfo.InvariantCulture, out var result5))
			{
				return false;
			}
			List<ulong> list = new List<ulong>();
			if (array[7].Length > 0)
			{
				string[] array2 = array[7].Split(',');
				for (int i = 0; i < array2.Length; i++)
				{
					if (!ulong.TryParse(array2[i], NumberStyles.None, CultureInfo.InvariantCulture, out var result6))
					{
						return false;
					}
					list.Add(result6);
				}
			}
			state = new PauseState((PausePhase)result, result2, result3, result4, list, result5);
			return true;
		}

		public bool Equals(PauseState other)
		{
			if (Phase == other.Phase && PausedBy == other.PausedBy && CountdownMs == other.CountdownMs && Epoch == other.Epoch && Needed == other.Needed)
			{
				return Voted.SequenceEqual(other.Voted);
			}
			return false;
		}

		public override bool Equals(object? obj)
		{
			if (obj is PauseState other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return HashCode.Combine(Phase, PausedBy, CountdownMs, Epoch);
		}

		public override string ToString()
		{
			return Encode();
		}
	}
	public enum PauseRequest : byte
	{
		Pause = 1,
		Resume,
		Unvote,
		Force
	}
	public static class PauseRequestCodec
	{
		public static string EncodeDenied(int msLeft)
		{
			return string.Join(";", "CP1", "D", ((msLeft >= 0) ? msLeft : 0).ToString(CultureInfo.InvariantCulture));
		}

		public static bool TryDecodeDenied(string? payload, out int msLeft)
		{
			msLeft = 0;
			if (payload == null)
			{
				return false;
			}
			string[] array = payload.Split(';');
			if (array.Length == 3 && array[0] == "CP1" && array[1] == "D")
			{
				return int.TryParse(array[2], NumberStyles.None, CultureInfo.InvariantCulture, out msLeft);
			}
			return false;
		}

		public static string Encode(PauseRequest request)
		{
			string[] obj = new string[3] { "CP1", "R", null };
			byte b = (byte)request;
			obj[2] = b.ToString(CultureInfo.InvariantCulture);
			return string.Join(";", obj);
		}

		public static bool TryDecode(string? payload, out PauseRequest request)
		{
			request = (PauseRequest)0;
			if (payload == null)
			{
				return false;
			}
			string[] array = payload.Split(';');
			if (array.Length != 3 || array[0] != "CP1" || array[1] != "R")
			{
				return false;
			}
			if (!byte.TryParse(array[2], NumberStyles.None, CultureInfo.InvariantCulture, out var result))
			{
				return false;
			}
			if (result < 1 || result > 4)
			{
				return false;
			}
			request = (PauseRequest)result;
			return true;
		}
	}
	public sealed class PauseView
	{
		public const float HostSilenceSeconds = 6f;

		public const float GoSeconds = 0.7f;

		private PausePhase _phase;

		private ulong _pausedBy;

		private float _countdownEndsAt;

		private float _lastHeard;

		private float _goUntil = -1f;

		private int _epoch = -1;

		public PausePhase Phase => _phase;

		public bool HeardFromHost => _epoch >= 0;

		public ulong PausedBy => _pausedBy;

		public IReadOnlyList<ulong> Voted { get; private set; } = new ulong[0];

		public int Needed { get; private set; }

		public bool Frozen => _phase != PausePhase.Running;

		public bool HasVoted(ulong client)
		{
			foreach (ulong item in Voted)
			{
				if (item == client)
				{
					return true;
				}
			}
			return false;
		}

		public bool Apply(PauseState state, float now)
		{
			if (state.Epoch < _epoch)
			{
				return false;
			}
			_lastHeard = now;
			Voted = state.Voted;
			Needed = state.Needed;
			if (state.Epoch == _epoch)
			{
				if (_phase == PausePhase.Countdown && state.Phase == PausePhase.Countdown)
				{
					float num = now + (float)state.CountdownMs / 1000f;
					if (num < _countdownEndsAt - 0.05f)
					{
						_countdownEndsAt = num;
					}
				}
				return false;
			}
			PausePhase phase = _phase;
			_epoch = state.Epoch;
			_pausedBy = state.PausedBy;
			if (state.Phase == PausePhase.Countdown && state.CountdownMs <= 0)
			{
				_phase = PausePhase.Running;
			}
			else
			{
				_phase = state.Phase;
				if (_phase == PausePhase.Countdown)
				{
					_countdownEndsAt = now + (float)state.CountdownMs / 1000f;
				}
			}
			if (phase != PausePhase.Running && _phase == PausePhase.Running)
			{
				_goUntil = now + 0.7f;
			}
			return true;
		}

		public bool Tick(float now, bool hostSendsHeartbeats)
		{
			if (_phase == PausePhase.Countdown && now >= _countdownEndsAt)
			{
				_phase = PausePhase.Running;
				_goUntil = now + 0.7f;
				return true;
			}
			if (Frozen && hostSendsHeartbeats && now - _lastHeard > 6f)
			{
				_phase = PausePhase.Running;
				_goUntil = -1f;
				return true;
			}
			return false;
		}

		public bool Reset()
		{
			bool frozen = Frozen;
			_phase = PausePhase.Running;
			_pausedBy = 0uL;
			_epoch = -1;
			Voted = new ulong[0];
			Needed = 0;
			_goUntil = -1f;
			return frozen;
		}

		public int CountdownNumber(float now)
		{
			if (_phase != PausePhase.Countdown)
			{
				return 0;
			}
			float num = _countdownEndsAt - now;
			if (num <= 0f)
			{
				return 0;
			}
			int num2 = (int)num;
			if (!(num > (float)num2))
			{
				return num2;
			}
			return num2 + 1;
		}

		public bool ShowGo(float now)
		{
			if (_phase == PausePhase.Running)
			{
				return now < _goUntil;
			}
			return false;
		}
	}
	public sealed class TimeScaleKeeper
	{
		private float? _gameWants;

		public bool Holding => _gameWants.HasValue;

		public float? Update(bool frozen, float current)
		{
			if (frozen)
			{
				if (!_gameWants.HasValue || current != 0f)
				{
					_gameWants = current;
				}
				if (current == 0f)
				{
					return null;
				}
				return 0f;
			}
			if (!_gameWants.HasValue)
			{
				return null;
			}
			float value = _gameWants.Value;
			_gameWants = null;
			if (value == current)
			{
				return null;
			}
			return value;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte flag)
		{
			Flag = flag;
		}
	}
}