Decompiled source of FriendsFixes v1.19.4

FriendsFixes.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using FriendsFixes.Logic;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using ModdingUtils.Utils;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnboundLib;
using UnboundLib.Extensions;
using UnboundLib.GameModes;
using UnboundLib.Networking;
using UnboundLib.Utils;
using UnboundLib.Utils.UI;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.Scripting;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("FriendsFixes")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0+873ea2b52b4754e3d9b703f8578520b9e09f08db")]
[assembly: AssemblyProduct("FriendsFixes")]
[assembly: AssemblyTitle("FriendsFixes")]
[assembly: AssemblyVersion("1.2.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FriendsFixes
{
	public static class BotNames
	{
		private static readonly Dictionary<int, string> names = new Dictionary<int, string>();

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

		private static float nextApply;

		private static Type tabFrame;

		private static bool tabLooked;

		private static Type lobbyRow;

		private static bool rowLooked;

		private static MethodInfo rwfData;

		private static bool rwfLooked;

		private static MethodInfo extra;

		private static PropertyInfo isBot;

		private static bool looked;

		public static void Set(Player bot, string name)
		{
			if ((Object)(object)bot == (Object)null || string.IsNullOrEmpty(name))
			{
				return;
			}
			name = Clean(name);
			CharacterData data = bot.data;
			int? obj;
			if (data == null)
			{
				obj = null;
			}
			else
			{
				PhotonView view = data.view;
				obj = ((view != null) ? new int?(view.ViewID) : ((int?)null));
			}
			int? num = obj;
			int valueOrDefault = num.GetValueOrDefault();
			if (valueOrDefault != 0)
			{
				if (PhotonNetwork.OfflineMode || !PhotonNetwork.InRoom)
				{
					RPCA_BotName(valueOrDefault, name);
					return;
				}
				NetworkingManager.RPC(typeof(BotNames), "RPCA_BotName", new object[2] { valueOrDefault, name });
			}
		}

		public static void SetColor(Player bot, int colorID)
		{
			if ((Object)(object)bot == (Object)null || colorID < 0 || colorID > 31)
			{
				return;
			}
			CharacterData data = bot.data;
			int? obj;
			if (data == null)
			{
				obj = null;
			}
			else
			{
				PhotonView view = data.view;
				obj = ((view != null) ? new int?(view.ViewID) : ((int?)null));
			}
			int? num = obj;
			int valueOrDefault = num.GetValueOrDefault();
			if (valueOrDefault != 0)
			{
				if (PhotonNetwork.OfflineMode || !PhotonNetwork.InRoom)
				{
					RPCA_BotColor(valueOrDefault, colorID);
					return;
				}
				NetworkingManager.RPC(typeof(BotNames), "RPCA_BotColor", new object[2] { valueOrDefault, colorID });
			}
		}

		[UnboundRPC]
		public static void RPCA_BotColor(int viewID, int colorID)
		{
			if (colorID >= 0 && colorID <= 31)
			{
				if (!colors.TryGetValue(viewID, out var value) || value != colorID)
				{
					Plugin.Log.LogInfo((object)$"[bot names] asked: view {viewID} -> colour {colorID} (bots only)");
				}
				colors[viewID] = colorID;
				Apply();
			}
		}

		[UnboundRPC]
		public static void RPCA_BotName(int viewID, string name)
		{
			name = Clean(name);
			if (!names.TryGetValue(viewID, out var value) || value != name)
			{
				Plugin.Log.LogInfo((object)$"[bot names] asked: view {viewID} -> \"{name}\" (bots only)");
			}
			names[viewID] = name;
			Apply();
		}

		internal static void Tick()
		{
			if (names.Count == 0 && colors.Count == 0)
			{
				return;
			}
			if (!PhotonNetwork.OfflineMode && !PhotonNetwork.InRoom)
			{
				names.Clear();
				colors.Clear();
			}
			else
			{
				if (Time.unscaledTime < nextApply)
				{
					return;
				}
				nextApply = Time.unscaledTime + 0.5f;
				Apply();
				try
				{
					ApplyScoreboard();
				}
				catch
				{
				}
				try
				{
					if ((Object)(object)PlayerManager.instance != (Object)null)
					{
						ApplyLobbyRows(PlayerManager.instance);
					}
				}
				catch
				{
				}
			}
		}

		public static string NameFor(Player p)
		{
			try
			{
				PlayerManager instance = PlayerManager.instance;
				if ((Object)(object)p == (Object)null || (Object)(object)instance == (Object)null || (Object)(object)p.data?.view == (Object)null || !names.TryGetValue(p.data.view.ViewID, out var value))
				{
					return null;
				}
				return Allowed(p, instance) ? value : null;
			}
			catch
			{
				return null;
			}
		}

		private static void ApplyScoreboard()
		{
			if (!tabLooked)
			{
				tabLooked = true;
				tabFrame = AccessTools.TypeByName("TabInfo.Utils.PlayerFrame");
			}
			if (tabFrame == null)
			{
				return;
			}
			Object[] array = Object.FindObjectsOfType(tabFrame);
			for (int i = 0; i < array.Length; i++)
			{
				Traverse obj = Traverse.Create((object)array[i]);
				string text = NameFor(obj.Field("player").GetValue<Player>());
				TextMeshProUGUI value = obj.Field("NameText").GetValue<TextMeshProUGUI>();
				if (text != null && (Object)(object)value != (Object)null && ((TMP_Text)value).text != text)
				{
					((TMP_Text)value).text = text;
				}
			}
		}

		private static void ApplyLobbyRows(PlayerManager pm)
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			if (!rowLooked)
			{
				rowLooked = true;
				lobbyRow = AccessTools.TypeByName("RWF.UI.PrivateRoomCharacterSelectionInstance");
			}
			if (lobbyRow == null)
			{
				return;
			}
			Player val = null;
			string text = null;
			int num = 0;
			foreach (Player player in pm.players)
			{
				string text2 = NameFor(player);
				if (text2 != null)
				{
					val = player;
					text = text2;
					num++;
				}
			}
			if (num != 1)
			{
				return;
			}
			Player owner = val.data.view.Owner;
			string text3 = ((owner != null) ? owner.NickName : null);
			if (string.IsNullOrEmpty(text3))
			{
				return;
			}
			Object[] array = Object.FindObjectsOfType(lobbyRow);
			foreach (Object val2 in array)
			{
				if (Traverse.Create((object)val2).Field("uniqueID").GetValue<int>() <= 0)
				{
					continue;
				}
				TextMeshProUGUI[] componentsInChildren = ((Component)val2).GetComponentsInChildren<TextMeshProUGUI>(true);
				foreach (TextMeshProUGUI val3 in componentsInChildren)
				{
					if (((TMP_Text)val3).text == text3 || ((TMP_Text)val3).text.StartsWith(text3 + " "))
					{
						((TMP_Text)val3).text = text;
					}
				}
			}
		}

		private static void Apply()
		{
			PlayerManager instance = PlayerManager.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			foreach (Player player in instance.players)
			{
				if ((Object)(object)player == (Object)null || (Object)(object)player.data?.view == (Object)null)
				{
					continue;
				}
				int viewID = player.data.view.ViewID;
				string value;
				bool flag = names.TryGetValue(viewID, out value);
				int value2;
				bool flag2 = colors.TryGetValue(viewID, out value2);
				if ((!flag && !flag2) || !Allowed(player, instance))
				{
					continue;
				}
				if (flag)
				{
					PlayerName componentInChildren = ((Component)player).GetComponentInChildren<PlayerName>(true);
					TextMeshProUGUI val = ((componentInChildren != null) ? ((Component)componentInChildren).GetComponent<TextMeshProUGUI>() : null);
					if ((Object)(object)val != (Object)null && ((TMP_Text)val).text != value)
					{
						((TMP_Text)val).text = value;
					}
				}
				if (flag2 && PlayerExtensions.colorID(player) != value2)
				{
					PlayerExtensions.AssignColorID(player, value2);
					player.SetColors();
				}
			}
		}

		private static bool Allowed(Player p, PlayerManager pm)
		{
			if (p.data.view.IsMine)
			{
				return IsBot(p);
			}
			bool? flag = HasLobbyCharacter(p);
			if (flag == true)
			{
				return false;
			}
			if (flag == false && (!((Object)(object)GameManager.instance != (Object)null) || !GameManager.instance.isPlaying))
			{
				return true;
			}
			int ownerActorNr = p.data.view.OwnerActorNr;
			int num = 0;
			foreach (Player player in pm.players)
			{
				if ((Object)(object)player != (Object)null && (Object)(object)player.data?.view != (Object)null && player.data.view.OwnerActorNr == ownerActorNr)
				{
					num++;
				}
			}
			return num > 1;
		}

		internal static bool? HasLobbyCharacter(Player p)
		{
			try
			{
				if (PhotonNetwork.OfflineMode)
				{
					return null;
				}
				if (!rwfLooked)
				{
					rwfLooked = true;
					rwfData = AccessTools.Method(AccessTools.TypeByName("RWF.PlayerExtensions"), "GetAdditionalData", new Type[1] { typeof(Player) }, (Type[])null);
				}
				if (rwfData == null)
				{
					return null;
				}
				object obj = rwfData.Invoke(null, new object[1] { p });
				return (obj == null) ? ((bool?)null) : new bool?(Traverse.Create(obj).Field("character").GetValue() != null);
			}
			catch
			{
				return null;
			}
		}

		private static bool IsBot(Player p)
		{
			try
			{
				if (!looked)
				{
					looked = true;
					extra = AccessTools.Method("RoundsWithBots.Extensions.CharacterDataExtension:GetAdditionalData", (Type[])null, (Type[])null);
					isBot = ((extra == null) ? null : AccessTools.Property(extra.ReturnType, "IsBot"));
				}
				return isBot != null && (bool)isBot.GetValue(extra.Invoke(null, new object[1] { p.data }));
			}
			catch
			{
				return false;
			}
		}

		private static string Clean(string s)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string text = s ?? "";
			foreach (char c in text)
			{
				if (!char.IsControl(c) && c != '<' && c != '>' && stringBuilder.Length < 24)
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString().Trim();
		}
	}
	internal static class BotPickFix
	{
		private static int skipped;

		private static float nextLog;

		public static string Install(Harmony h)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			h.Patch((MethodBase)AccessTools.Method(typeof(CardChoice), "Pick", (Type[])null, (Type[])null), new HarmonyMethod(typeof(BotPickFix), "PickPrefix", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			string text = "";
			MethodInfo methodInfo = AccessTools.Method(AccessTools.TypeByName("SelectAnyNumberRounds.Patch.PickNoRefresh"), "Prefix", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(BotPickFix), "SanPrefix", (Type[])null)
				{
					priority = 800
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				text = " (also Select Any Number's pick)";
			}
			return "a card pick is ended only by the PC that owns the picker" + text + ": no double pick online.";
		}

		private static bool NotMine(GameObject pickedCard)
		{
			try
			{
				if (PhotonNetwork.OfflineMode || (Object)(object)pickedCard == (Object)null || (Object)(object)CardChoice.instance == (Object)null || (Object)(object)PlayerManager.instance == (Object)null)
				{
					return false;
				}
				int pid = CardChoice.instance.pickrID;
				Player val = PlayerManager.instance.players.Find((Player p) => (Object)(object)p != (Object)null && p.playerID == pid);
				if ((Object)(object)val == (Object)null || (Object)(object)val.data?.view == (Object)null || val.data.view.IsMine)
				{
					return false;
				}
				skipped++;
				if (Time.unscaledTime >= nextLog)
				{
					nextLog = Time.unscaledTime + 10f;
					Plugin.Log.LogInfo((object)$"[bot pick] player {pid}'s pick is ended by the PC that owns it ({skipped} skipped here so far)");
				}
				return true;
			}
			catch
			{
				return false;
			}
		}

		private static bool PickPrefix(GameObject pickedCard)
		{
			return !NotMine(pickedCard);
		}

		private static bool SanPrefix(GameObject pickedCard, ref bool __result)
		{
			if (!NotMine(pickedCard))
			{
				return true;
			}
			__result = false;
			return false;
		}
	}
	internal static class BotScanFix
	{
		private const float Interval = 0.1f;

		private const float BotCheckEvery = 0.5f;

		private static Type aiT;

		private static bool bots;

		private static float nextBotCheck;

		private static float lastScan = -10f;

		private static int skipped;

		private static int ran;

		private static int noRoute;

		private static float nextReport;

		public static string Install(Harmony h)
		{
			//IL_0081: 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_009a: Expected O, but got Unknown
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("RoundsWithBots.Pathfinding.Scanning.MapScanner");
			if (type == null)
			{
				return "Round With Bots not installed; nothing to do.";
			}
			if (Environment.GetEnvironmentVariable("FF_TEST_NOBOTSCAN") == "1")
			{
				return "TEST: off.";
			}
			aiT = AccessTools.TypeByName("RoundsWithBots.AI.Movement.AIPathfindModule");
			MethodInfo methodInfo = AccessTools.Method(type, "FixedUpdate", (Type[])null, (Type[])null);
			if (methodInfo == null || aiT == null)
			{
				return "Round With Bots changed; not active.";
			}
			h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(BotScanFix), "Prefix", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo2 = AccessTools.Method(aiT, "AttemptPathfindToTarget", (Type[])null, (Type[])null);
			string text = "";
			if (methodInfo2 != null && Environment.GetEnvironmentVariable("FF_TEST_NOROUTEFIX") != "1")
			{
				h.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(BotScanFix), "RouteFinalizer", (Type[])null), (HarmonyMethod)null);
				text = " Bots off the scanned map no longer flood the log with route errors.";
			}
			return $"the bots' map scan runs only when bots are in the game, {10f:0} times a second instead of 50." + text;
		}

		private static bool Prefix()
		{
			try
			{
				float unscaledTime = Time.unscaledTime;
				if (unscaledTime >= nextBotCheck)
				{
					nextBotCheck = unscaledTime + 0.5f;
					bots = Object.FindObjectOfType(aiT) != (Object)null;
				}
				if (unscaledTime >= nextReport)
				{
					if (ran + skipped > 0)
					{
						Plugin.Log.LogInfo((object)$"[bot map scan] last 5 min: ran {ran}, skipped {skipped}, bot found no route (off the scanned map) {noRoute}");
					}
					nextReport = unscaledTime + 300f;
					ran = (skipped = (noRoute = 0));
				}
				if (!bots || (Time.fixedTime - lastScan < 0.1f && Time.fixedTime >= lastScan))
				{
					skipped++;
					return false;
				}
				lastScan = Time.fixedTime;
				ran++;
				return true;
			}
			catch
			{
				return true;
			}
		}

		private static Exception RouteFinalizer(Exception __exception, ref object __result)
		{
			if (!(__exception is NullReferenceException))
			{
				return __exception;
			}
			noRoute++;
			__result = null;
			return null;
		}
	}
	internal static class BotTeams
	{
		private const string Key = "ffBotTeam";

		public static string Install(Harmony h)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(AccessTools.TypeByName("RWF.PrivateRoomHandler"), "StartGame", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				return "Rounds With Friends not found; nothing to do.";
			}
			h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(BotTeams), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "bots added online get their own team (free-for-all) or the smallest team, when everyone has this version.";
		}

		internal static void Tick()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_0047: Expected O, but got Unknown
			if (!PhotonNetwork.OfflineMode && PhotonNetwork.InRoom && !((Dictionary<object, object>)(object)PhotonNetwork.LocalPlayer.CustomProperties).ContainsKey((object)"ffBotTeam"))
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"ffBotTeam", (object)1);
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		private static void Prefix()
		{
			try
			{
				if (PhotonNetwork.OfflineMode || (Object)(object)PlayerManager.instance == (Object)null)
				{
					return;
				}
				List<Player> list = PlayerManager.instance.players.Where((Player p) => (Object)(object)p != (Object)null).ToList();
				List<Player> list2 = (from p in list
					where BotNames.HasLobbyCharacter(p) == false
					orderby p.playerID
					select p).ToList();
				if (list2.Count == 0)
				{
					return;
				}
				List<string> list3 = (from pl in PhotonNetwork.PlayerList
					where !((Dictionary<object, object>)(object)pl.CustomProperties).ContainsKey((object)"ffBotTeam")
					select pl.NickName).ToList();
				if (list3.Count > 0)
				{
					Plugin.Log.LogInfo((object)("[bot team] not changed: " + string.Join(", ", list3) + " need Friends Fixes 1.19.2+"));
					return;
				}
				bool flag = GameModeManager.CurrentHandler != null && GameModeManager.CurrentHandler.AllowTeams;
				List<int> list4 = (from p in list.Except(list2)
					select p.teamID).ToList();
				foreach (Player item in list2)
				{
					int num = BotTeam.Pick(list4, flag);
					Plugin.Log.LogInfo((object)string.Format("[bot team] bot player {0}: team {1} -> {2} ({3})", item.playerID, item.teamID, num, flag ? "smallest team" : "its own team"));
					item.teamID = num;
					list4.Add(num);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[bot team] " + ex.Message));
			}
		}
	}
	internal static class CardBugFixes
	{
		private static Type dyingWillEffect;

		private static FieldInfo grappleOwner;

		private static FieldInfo curseRng;

		private static FieldInfo chainPlayer;

		private static FieldInfo chainTarget;

		private static FieldInfo hatchPlayer;

		private static FieldInfo hatchCards;

		private static FieldInfo hatchStrings;

		private static readonly MethodInfo toggle = AccessTools.Method(typeof(MapTransition), "Toggle", (Type[])null, (Type[])null);

		private static Type inWaterT;

		private static FieldInfo hadWater;

		public static string DyingWill(Harmony h)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("PotatoCards.Cards.DyingWillEffect");
			if (type == null)
			{
				return "Potato Cards not installed; nothing to do.";
			}
			dyingWillEffect = type;
			h.Patch((MethodBase)AccessTools.Method(typeof(Explosion), "Start", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CardBugFixes), "ExplosionStart", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "Dying Will's death shockwave now actually deals its damage and knockback.";
		}

		private static void ExplosionStart(Explosion __instance)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!(((Object)((Component)__instance).gameObject).name != "DyingWillShockwave") && !((Object)(object)((Component)__instance).GetComponent<SpawnedAttack>() != (Object)null))
				{
					Vector3 pos = ((Component)__instance).transform.position;
					Player val = PlayerManager.instance.players.Where((Player p) => (Object)(object)p != (Object)null && (Object)(object)((Component)p).GetComponent(dyingWillEffect) != (Object)null).OrderBy(delegate(Player p)
					{
						//IL_0006: Unknown result type (might be due to invalid IL or missing references)
						//IL_000c: Unknown result type (might be due to invalid IL or missing references)
						//IL_0011: 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)
						Vector3 val2 = ((Component)p).transform.position - pos;
						return ((Vector3)(ref val2)).sqrMagnitude;
					}).FirstOrDefault();
					if (!((Object)(object)val == (Object)null))
					{
						((Component)__instance).gameObject.AddComponent<SpawnedAttack>().spawner = val;
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Dying Will] " + ex.Message));
			}
		}

		public static string Grapple(Harmony h)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("AdvancedMovementPack.Cards.GrappleBullet");
			if (type == null)
			{
				return "Advanced Movement Pack not installed; nothing to do.";
			}
			grappleOwner = AccessTools.Field(type, "owner");
			h.Patch((MethodBase)AccessTools.Method(type, "Start", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CardBugFixes), "GrappleStart", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "Grapple shots no longer error, and get their trail.";
		}

		private static bool GrappleStart(MonoBehaviour __instance)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: 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_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			try
			{
				ProjectileHit componentInParent = ((Component)__instance).GetComponentInParent<ProjectileHit>();
				if ((Object)(object)componentInParent != (Object)null && (Object)(object)componentInParent.ownPlayer != (Object)null)
				{
					grappleOwner?.SetValue(__instance, componentInParent.ownPlayer);
				}
				GameObject gameObject = ((Component)__instance).gameObject;
				if ((Object)(object)gameObject.GetComponent<ParticleSystem>() != (Object)null)
				{
					return false;
				}
				ParticleSystem val = gameObject.AddComponent<ParticleSystem>();
				if ((Object)(object)val == (Object)null)
				{
					return false;
				}
				MainModule main = val.main;
				((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(Color.magenta);
				((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(0.15f);
				((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(0.2f);
				((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
				EmissionModule emission = val.emission;
				((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(0f);
				((EmissionModule)(ref emission)).rateOverDistance = MinMaxCurve.op_Implicit(40f);
				ShapeModule shape = val.shape;
				((ShapeModule)(ref shape)).enabled = false;
				ParticleSystemRenderer component = ((Component)val).GetComponent<ParticleSystemRenderer>();
				if ((Object)(object)component != (Object)null)
				{
					((Renderer)component).material = new Material(Shader.Find("Sprites/Default"));
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Grapple] " + ex.Message));
			}
			return false;
		}

		public static string ChaoticCurse(Harmony h)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("CPCCurses.Cards.RandomCurse");
			if (type == null)
			{
				return "CPC Curses not installed; nothing to do.";
			}
			curseRng = AccessTools.Field(type, "randomNumberGenerator");
			h.Patch((MethodBase)AccessTools.Method(type, "GenerateAndPerformEffect", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CardBugFixes), "CurseRoll", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "Chaotic Curse always rolls, and every PC rolls the same curse.";
		}

		private static void CurseRoll(object __instance, Player player)
		{
			try
			{
				string text = (PhotonNetwork.InRoom ? PhotonNetwork.CurrentRoom.Name : "offline");
				int seed = Hash($"{text}|{player.playerID}|{player.data.currentCards.Count}|{GameModeRound()}");
				curseRng.SetValue(__instance, new Random(seed));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Chaotic Curse] " + ex.Message));
			}
		}

		private static int GameModeRound()
		{
			try
			{
				return PlayerManager.instance.players.Sum((Player p) => p.data.currentCards.Count);
			}
			catch
			{
				return 0;
			}
		}

		private static int Hash(string s)
		{
			uint num = 2166136261u;
			foreach (char c in s)
			{
				num ^= c;
				num *= 16777619;
			}
			return (int)(num & 0x7FFFFFFF);
		}

		public static string BindingChains(Harmony h)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("KeysCards.Cards.BindingChainsObjMono");
			if (type == null)
			{
				return "Keys Cards not installed; nothing to do.";
			}
			chainPlayer = AccessTools.Field(type, "player");
			chainTarget = AccessTools.Field(type, "target");
			h.Patch((MethodBase)AccessTools.Method(type, "Update", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CardBugFixes), "ChainUpdate", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "chains to a player who left are removed instead of erroring every frame.";
		}

		private static bool ChainUpdate(MonoBehaviour __instance)
		{
			object? value = chainPlayer.GetValue(__instance);
			Player val = (Player)((value is Player) ? value : null);
			object? value2 = chainTarget.GetValue(__instance);
			Player val2 = (Player)((value2 is Player) ? value2 : null);
			if ((Object)(object)val != (Object)null && (Object)(object)val2 != (Object)null && (Object)(object)val.data != (Object)null && (Object)(object)val2.data != (Object)null)
			{
				return true;
			}
			Object.Destroy((Object)(object)((Component)__instance).gameObject);
			return false;
		}

		public static string Hatchlings(Harmony h)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("KeysCards.Cards.HatchlingsMono");
			if (type == null)
			{
				return "Keys Cards not installed; nothing to do.";
			}
			hatchPlayer = AccessTools.Field(type, "player");
			hatchCards = AccessTools.Field(type, "cardArray");
			hatchStrings = AccessTools.Field(type, "stringArray");
			h.Patch((MethodBase)AccessTools.Method(type, "OnDestroy", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CardBugFixes), "HatchDestroy", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "no error when a Hatchlings player leaves before hatching.";
		}

		private static bool HatchDestroy(MonoBehaviour __instance)
		{
			object? value = hatchPlayer.GetValue(__instance);
			Player val = (Player)((value is Player) ? value : null);
			CardInfo[] array = hatchCards.GetValue(__instance) as CardInfo[];
			if ((Object)(object)val == (Object)null || (Object)(object)val.data == (Object)null || array == null || array.Length == 0 || array.Any((CardInfo c) => (Object)(object)c == (Object)null) || hatchStrings.GetValue(__instance) == null)
			{
				return false;
			}
			if ((Object)(object)PlayerManager.instance == (Object)null || !PlayerManager.instance.players.Contains(val))
			{
				return false;
			}
			return true;
		}

		public static string MapTransitionMove(Harmony h)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			h.Patch((MethodBase)AccessTools.Method(typeof(MapTransition), "Move", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CardBugFixes), "MovePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "map pieces destroyed while the map slides in no longer cause errors.";
		}

		private static bool MovePrefix(MapTransition __instance, GameObject target, Vector3 distance, Map targetMap, ref IEnumerator __result)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			__result = SafeMove(__instance, target, distance, targetMap);
			return false;
		}

		private static IEnumerator SafeMove(MapTransition mt, GameObject target, Vector3 distance, Map targetMap)
		{
			//IL_0015: 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)
			MapTransition.isTransitioning = true;
			float maxRandomDelay = 0.25f;
			float randomDelay = Random.Range(0f, maxRandomDelay);
			yield return (object)new WaitForSecondsRealtime(randomDelay);
			if ((Object)(object)target != (Object)null && (Object)(object)mt != (Object)null)
			{
				Vector3 start = target.transform.position;
				float t = ((Keyframe)(ref mt.curve.keys[mt.curve.keys.Length - 1])).time;
				float c = 0f;
				while (c < t && (Object)(object)target != (Object)null)
				{
					c += Time.unscaledDeltaTime;
					target.transform.position = start + distance * mt.curve.Evaluate(c);
					yield return null;
				}
				if ((Object)(object)target != (Object)null)
				{
					target.transform.position = start + distance;
					toggle.Invoke(mt, new object[2] { target, true });
				}
			}
			yield return (object)new WaitForSecondsRealtime(maxRandomDelay - randomDelay);
			MapTransition.isTransitioning = false;
			if ((Object)(object)targetMap != (Object)null)
			{
				targetMap.hasEntered = true;
			}
		}

		public static string FfcHitGuard(Harmony h)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("Ported_FFC.Patches.ProjectileHitPatchHit");
			if (type == null)
			{
				return "Port of FFC not installed; nothing to do.";
			}
			h.Patch((MethodBase)AccessTools.Method(type, "Prefix", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(CardBugFixes), "FfcHitFinalizer", (Type[])null), (HarmonyMethod)null);
			return "bullets without an owner no longer lose their hit.";
		}

		private static Exception FfcHitFinalizer(Exception __exception, ref bool __result)
		{
			if (__exception != null)
			{
				__result = true;
			}
			return null;
		}

		public static string WarpBorder(Harmony h)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("ModdingUtils.Extensions.OutOfBoundsHandlerExtensions");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.PropertyGetter(type, "Border"));
			if (methodInfo == null)
			{
				return "ModdingUtils border lookup not found; nothing to do.";
			}
			h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(CardBugFixes), "BorderPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "screen-edge warp cards find the hidden screen border.";
		}

		private static void BorderPostfix(ref GameObject __result)
		{
			if ((Object)(object)__result != (Object)null)
			{
				return;
			}
			GameObject val = ((IEnumerable<GameObject>)Resources.FindObjectsOfTypeAll<GameObject>()).FirstOrDefault((Func<GameObject, bool>)delegate(GameObject g)
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				if (((Object)g).name == "Border")
				{
					Scene scene = g.scene;
					if (((Scene)(ref scene)).IsValid() && (Object)(object)g.transform.parent != (Object)null && (((Object)g.transform.parent).name == "BorderCanvas" || ((Object)g.transform.parent).name == "Canvas"))
					{
						return (Object)(object)g.GetComponent<RectTransform>() != (Object)null;
					}
				}
				return false;
			});
			if (!((Object)(object)val == (Object)null))
			{
				AccessTools.Field(AccessTools.TypeByName("ModdingUtils.Extensions.OutOfBoundsHandlerExtensions"), "_Border").SetValue(null, val);
				__result = val;
			}
		}

		public static string ArmorPlating(Harmony h)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("Ported_FFC.Cards.Juggernaut.ArmorPlatingMono");
			Type type2 = AccessTools.TypeByName("Ported_FFC.Cards.Juggernaut.ProjectileHitPatchHit");
			if (type == null)
			{
				return "Port of FFC not installed; nothing to do.";
			}
			h.Patch((MethodBase)AccessTools.Method(type, "Reflect", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CardBugFixes), "ArmorReflectPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			if (type2 != null)
			{
				h.Patch((MethodBase)AccessTools.Method(type2, "Prefix", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(CardBugFixes), "FfcHitFinalizer", (Type[])null), (HarmonyMethod)null);
			}
			return "no reflect until the host's rolls arrive, instead of bullets doing nothing.";
		}

		private static bool ArmorReflectPrefix(object __instance, ref bool __result)
		{
			List<bool> value = Traverse.Create(__instance).Field("reflect_rolls").GetValue<List<bool>>();
			if (value != null && value.Count > 0)
			{
				return true;
			}
			__result = false;
			return false;
		}

		public static string DestroyMeGuard(Harmony h)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			h.Patch((MethodBase)AccessTools.Method(typeof(ProjectileHit), "DestroyMe", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(CardBugFixes), "DestroyMeFinalizer", (Type[])null), (HarmonyMethod)null);
			return "removing an already-removed bullet no longer errors.";
		}

		private static Exception DestroyMeFinalizer(Exception __exception)
		{
			if (!(__exception is NullReferenceException) && !(__exception is MissingReferenceException))
			{
				return __exception;
			}
			return null;
		}

		public static string WwmoLava(Harmony h)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method("WWMO.MonoBehaviours.LavaMono:HandleBullet", (Type[])null, (Type[])null);
			inWaterT = AccessTools.TypeByName("WWMO.MonoBehaviours.BulletInWater_Mono");
			hadWater = ((inWaterT == null) ? null : AccessTools.Field(inWaterT, "hadWater"));
			if (methodInfo == null)
			{
				return "Will's Wacky Map Objects not installed; nothing to do.";
			}
			if (hadWater == null)
			{
				return "Will's Wacky Map Objects changed; not active.";
			}
			h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(CardBugFixes), "LavaBullet", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "lava no longer errors on every bullet; it burns bullets down as intended.";
		}

		private static bool LavaBullet(ProjectileHit projectileHit)
		{
			if ((Object)(object)projectileHit == (Object)null)
			{
				return false;
			}
			GameObject gameObject = ((Component)projectileHit).gameObject;
			Component obj = gameObject.GetComponent(inWaterT) ?? gameObject.AddComponent(inWaterT);
			hadWater.SetValue(obj, new bool[2] { true, true });
			ProjectileCollision componentInChildren = ((Component)projectileHit).GetComponentInChildren<ProjectileCollision>();
			if (componentInChildren != null)
			{
				componentInChildren.TakeDamage(10f);
			}
			projectileHit.damage = Mathf.Max(projectileHit.damage - 10f, 1f);
			return false;
		}
	}
	internal static class CardTextFix
	{
		public static string Install()
		{
			GameModeManager.AddHook("GameStart", (Func<IGameModeHandler, IEnumerator>)Fix, 1000);
			return "cards using ≤ / ≥ (missing from the game's font) now show <= / >=.";
		}

		private static string Clean(string s)
		{
			return s?.Replace("≤", "<=").Replace("≥", ">=");
		}

		private static IEnumerator Fix(IGameModeHandler gm)
		{
			int num = 0;
			try
			{
				foreach (Card value in CardManager.cards.Values)
				{
					CardInfo val = value?.cardInfo;
					if ((Object)(object)val == (Object)null)
					{
						continue;
					}
					bool flag = false;
					string text = Clean(val.cardDestription);
					if (text != val.cardDestription)
					{
						val.cardDestription = text;
						flag = true;
					}
					if (val.cardStats != null)
					{
						CardInfoStat[] cardStats = val.cardStats;
						foreach (CardInfoStat val2 in cardStats)
						{
							if (val2 != null)
							{
								string text2 = Clean(val2.amount);
								string text3 = Clean(val2.stat);
								if (text2 != val2.amount || text3 != val2.stat)
								{
									val2.amount = text2;
									val2.stat = text3;
									flag = true;
								}
							}
						}
					}
					if (flag)
					{
						num++;
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[card text] " + ex.Message));
			}
			if (num > 0)
			{
				Plugin.Log.LogInfo((object)$"[card text] replaced ≤/≥ on {num} card(s).");
			}
			yield break;
		}
	}
	internal static class CosmicRoundsFix
	{
		private static FieldInfo iceTrail;

		private static FieldInfo fbPlayer;

		private static FieldInfo fbMove;

		private static FieldInfo fbBullet;

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

		private static int swallowed;

		internal static int Swallowed => swallowed;

		public static string Install(Harmony h)
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Expected O, but got Unknown
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("CR.MonoBehaviors.IceTrailMono");
			if (type == null)
			{
				return "Cosmic Rounds not installed; nothing to do.";
			}
			Assembly assembly = type.Assembly;
			Type type2 = AccessTools.TypeByName("CR.MonoBehaviors.FireballMono");
			iceTrail = AccessTools.Field(type, "trail");
			fbPlayer = ((type2 == null) ? null : AccessTools.Field(type2, "player"));
			fbMove = ((type2 == null) ? null : AccessTools.Field(type2, "move"));
			fbBullet = ((type2 == null) ? null : AccessTools.Field(type2, "bullet"));
			List<string> list = new List<string>();
			if (iceTrail != null)
			{
				h.Patch((MethodBase)AccessTools.Method(type, "Update", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CosmicRoundsFix), "IceUpdate", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				list.Add("ice trail");
			}
			if (fbPlayer != null && fbMove != null && fbBullet != null)
			{
				h.Patch((MethodBase)AccessTools.Method(type2, "Update", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CosmicRoundsFix), "FireballUpdate", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				list.Add("fireball");
			}
			HarmonyMethod val = new HarmonyMethod(typeof(CosmicRoundsFix), "Finalizer", (Type[])null);
			int num = 0;
			foreach (Type item in from t in AccessTools.GetTypesFromAssembly(assembly)
				where t.Namespace == "CR.MonoBehaviors" && !t.IsInterface && !t.IsGenericTypeDefinition
				select t)
			{
				MethodInfo[] methods = item.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (!(methodInfo.ReturnType != typeof(void)) && !methodInfo.IsAbstract && !methodInfo.IsGenericMethodDefinition && methodInfo.GetMethodBody() != null)
					{
						try
						{
							h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null);
							num++;
						}
						catch
						{
						}
					}
				}
			}
			list.Add($"{num} effect methods guarded");
			return "Cosmic Rounds: " + string.Join(", ", list) + ".";
		}

		private static bool IceUpdate(object __instance)
		{
			object? value = iceTrail.GetValue(__instance);
			GameObject val = (GameObject)((value is GameObject) ? value : null);
			if (val != null)
			{
				return (Object)(object)val != (Object)null;
			}
			return false;
		}

		private static bool FireballUpdate(object __instance)
		{
			object? value = fbPlayer.GetValue(__instance);
			Player val = (Player)((value is Player) ? value : null);
			if (val == null || (Object)(object)val == (Object)null)
			{
				object? value2 = fbBullet.GetValue(__instance);
				object obj = ((value2 is ProjectileHit) ? value2 : null);
				if (obj == null)
				{
					object obj2 = ((__instance is Component) ? __instance : null);
					obj = ((obj2 != null) ? ((Component)obj2).GetComponent<ProjectileHit>() : null);
				}
				ProjectileHit val2 = (ProjectileHit)obj;
				val = (((Object)(object)val2 != (Object)null) ? val2.ownPlayer : null);
				if ((Object)(object)val == (Object)null)
				{
					return false;
				}
				fbPlayer.SetValue(__instance, val);
			}
			object? value3 = fbMove.GetValue(__instance);
			MoveTransform val3 = (MoveTransform)((value3 is MoveTransform) ? value3 : null);
			if (val3 != null)
			{
				return (Object)(object)val3 != (Object)null;
			}
			return false;
		}

		private static Exception Finalizer(Exception __exception, MethodBase __originalMethod)
		{
			if (!(__exception is NullReferenceException) && !(__exception is MissingReferenceException))
			{
				return __exception;
			}
			swallowed++;
			if (told.Add(__originalMethod))
			{
				Plugin.Log.LogInfo((object)("[Cosmic Rounds] " + __originalMethod.DeclaringType?.Name + "." + __originalMethod.Name + " hit a null (card removed or effect left behind); skipped instead of erroring"));
			}
			return null;
		}
	}
	internal static class FaceIdSync
	{
		private const string KeyHash = "ffFaceHash";

		private const string KeyE = "ffFaceE";

		private const string KeyM = "ffFaceM";

		private const string KeyD = "ffFaceD";

		private static Type selT;

		private static string[] myE;

		private static string[] myM;

		private static string[] myD;

		private static string myHash;

		private static bool published;

		private static float next;

		private static bool testDrop = Environment.GetEnvironmentVariable("FF_TEST_FACEDROP") == "1";

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

		public static string Install(Harmony h)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			selT = AccessTools.TypeByName("RWF.UI.PrivateRoomCharacterSelectionInstance");
			if (Environment.GetEnvironmentVariable("FF_TEST_NOFACESYNC") == "1")
			{
				return "TEST: off.";
			}
			h.Patch((MethodBase)AccessTools.Method(typeof(CharacterCreatorItemEquipper), "RPCA_SetFace", (Type[])null, (Type[])null), new HarmonyMethod(typeof(FaceIdSync), "EquipperPrefix", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			h.Patch((MethodBase)AccessTools.Method(typeof(Player), "RPCA_SetFace", (Type[])null, (Type[])null), new HarmonyMethod(typeof(FaceIdSync), "PlayerPrefix", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "friends' faces show the same items on every PC, even when your face-item mods differ.";
		}

		private static string Clean(CharacterItem it)
		{
			if (!((Object)(object)it == (Object)null))
			{
				return ((Object)it).name.Replace("(Clone)", "").Trim();
			}
			return "";
		}

		private static bool ReadMine()
		{
			CharacterCreatorItemLoader instance = CharacterCreatorItemLoader.instance;
			if ((Object)(object)instance == (Object)null || instance.eyes == null || instance.mouths == null || instance.accessories == null)
			{
				return false;
			}
			myE = instance.eyes.Select(Clean).ToArray();
			myM = instance.mouths.Select(Clean).ToArray();
			myD = instance.accessories.Select(Clean).ToArray();
			int num = 17;
			foreach (string item in myE.Concat(new string[1] { "|" }).Concat(myM).Concat(new string[1] { "|" })
				.Concat(myD))
			{
				foreach (char c in item)
				{
					num = num * 31 + c;
				}
			}
			myHash = $"{myE.Length}.{myM.Length}.{myD.Length}.{num:x8}";
			return true;
		}

		public static void Tick()
		{
			//IL_0061: 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_0076: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			//IL_00ad: Expected O, but got Unknown
			if (Time.unscaledTime < next)
			{
				return;
			}
			next = Time.unscaledTime + 1f;
			if (!PhotonNetwork.InRoom || PhotonNetwork.OfflineMode)
			{
				published = false;
				return;
			}
			if (testDrop)
			{
				testDrop = false;
				TestDropFirstCustomDetail();
			}
			if (published || (myHash == null && !ReadMine()))
			{
				return;
			}
			try
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"ffFaceHash", (object)myHash);
				((Dictionary<object, object>)val).Add((object)"ffFaceE", (object)myE);
				((Dictionary<object, object>)val).Add((object)"ffFaceM", (object)myM);
				((Dictionary<object, object>)val).Add((object)"ffFaceD", (object)myD);
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
				published = true;
				Plugin.Log.LogInfo((object)("[faces] shared my face item list (" + myHash + ")"));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[faces] could not share item list: " + ex.Message));
			}
		}

		private static int Map(Player owner, string[] theirs, string[] mine, int id, string kind)
		{
			if (theirs == null || mine == null || id < 0 || id >= theirs.Length)
			{
				return id;
			}
			string text = theirs[id];
			if (id < mine.Length && mine[id] == text)
			{
				return id;
			}
			int num = 0;
			for (int i = 0; i < id; i++)
			{
				if (theirs[i] == text)
				{
					num++;
				}
			}
			int j = 0;
			int num2 = 0;
			for (; j < mine.Length; j++)
			{
				if (mine[j] == text && num2++ == num)
				{
					return j;
				}
			}
			if (warned.Add(owner.ActorNumber + kind + text))
			{
				Plugin.Log.LogWarning((object)("[faces] " + owner.NickName + " wears " + kind + " '" + text + "', which this PC doesn't have (left off)"));
			}
			return -1;
		}

		private static void Translate(Player owner, ref int eyeID, ref int mouthID, ref int detailID, ref int detail2ID)
		{
			if (owner == null || owner.IsLocal || (myHash == null && !ReadMine()))
			{
				return;
			}
			Hashtable customProperties = owner.CustomProperties;
			if (customProperties[(object)"ffFaceHash"] is string text && !(text == myHash))
			{
				string[] theirs = customProperties[(object)"ffFaceE"] as string[];
				string[] theirs2 = customProperties[(object)"ffFaceM"] as string[];
				string[] theirs3 = customProperties[(object)"ffFaceD"] as string[];
				int num = eyeID;
				int num2 = mouthID;
				int num3 = detailID;
				int num4 = detail2ID;
				eyeID = Map(owner, theirs, myE, eyeID, "eyes");
				mouthID = Map(owner, theirs2, myM, mouthID, "mouth");
				detailID = Map(owner, theirs3, myD, detailID, "detail");
				detail2ID = Map(owner, theirs3, myD, detail2ID, "detail");
				if (warned.Add("t" + owner.ActorNumber + text))
				{
					Plugin.Log.LogInfo((object)$"[faces] {owner.NickName}'s face items are numbered differently ({text} vs mine {myHash}); translating by name (e.g. {num}/{num2}/{num3}/{num4} -> {eyeID}/{mouthID}/{detailID}/{detail2ID})");
				}
			}
		}

		private static Player OwnerOf(CharacterCreatorItemEquipper eq)
		{
			if (selT != null)
			{
				Component componentInParent = ((Component)eq).GetComponentInParent(selT);
				if ((Object)(object)componentInParent != (Object)null)
				{
					PhotonView component = componentInParent.GetComponent<PhotonView>();
					if (component == null)
					{
						return null;
					}
					return component.Owner;
				}
			}
			if ((Object)(object)((Component)eq).GetComponentInParent<CardChoiceVisuals>() != (Object)null && (Object)(object)CardChoice.instance != (Object)null && CardChoice.instance.pickrID >= 0)
			{
				CardChoice cc = CardChoice.instance;
				Player? obj = (((int)Traverse.Create((object)cc).Field("pickerType").GetValue() == 0) ? PlayerManager.instance.GetPlayersInTeam(cc.pickrID).FirstOrDefault() : ((IEnumerable<Player>)PlayerManager.instance.players).FirstOrDefault((Func<Player, bool>)((Player x) => x.playerID == cc.pickrID)));
				if (obj == null)
				{
					return null;
				}
				CharacterData data = obj.data;
				if (data == null)
				{
					return null;
				}
				PhotonView view = data.view;
				if (view == null)
				{
					return null;
				}
				return view.Owner;
			}
			return null;
		}

		private static void EquipperPrefix(CharacterCreatorItemEquipper __instance, ref int eyeID, ref int mouthID, ref int detailID, ref int detail2ID)
		{
			try
			{
				Translate(OwnerOf(__instance), ref eyeID, ref mouthID, ref detailID, ref detail2ID);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[faces] " + ex.Message));
			}
		}

		private static void PlayerPrefix(Player __instance, ref int eyeID, ref int mouthID, ref int detailID, ref int detail2ID)
		{
			try
			{
				CharacterData data = __instance.data;
				object owner;
				if (data == null)
				{
					owner = null;
				}
				else
				{
					PhotonView view = data.view;
					owner = ((view != null) ? view.Owner : null);
				}
				Translate((Player)owner, ref eyeID, ref mouthID, ref detailID, ref detail2ID);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[faces] " + ex.Message));
			}
		}

		internal static void TestDropFirstCustomDetail()
		{
			CharacterCreatorItemLoader instance = CharacterCreatorItemLoader.instance;
			int i = Array.FindIndex(instance.accessories, (CharacterItem x) => (Object)(object)x != (Object)null && ((Object)x).name.StartsWith("(CUSTOM)"));
			if (i >= 0)
			{
				Plugin.Log.LogWarning((object)$"[faces] TEST: removed detail #{i} {Clean(instance.accessories[i])} from this PC's list");
				instance.accessories = instance.accessories.Where((CharacterItem x, int k) => k != i).ToArray();
				myHash = null;
			}
		}
	}
	internal static class GcTiming
	{
		private static int last = -1;

		private static int inFight;

		private static int outside;

		private static int pauses;

		private static int caps;

		private static int whilePausedLogs;

		private static double fightSecs;

		private static double maxGrowthMb;

		private static double maxEndMs;

		private static readonly float every = ((float.TryParse(Environment.GetEnvironmentVariable("FF_TEST_GCREPORT"), out var result) && result > 0f) ? result : 300f);

		private static float nextReport = every;

		private static ConfigEntry<bool> pauseInFights;

		private static bool testOff;

		private static bool errorOff;

		private static bool paused;

		private static bool cappedThisFight;

		private static bool lastFight;

		private static long pausedAt;

		private static int capMb;

		public static string Install(ConfigFile config)
		{
			pauseInFights = config.Bind<bool>("Memory", "PauseCleanupsInFights", true, "Pause the game's memory clean-ups (short freezes) while a fight is on and do one when it ends. Uses more RAM during a fight (at most 1/8 of your RAM, then clean-ups come back on).");
			testOff = Environment.GetEnvironmentVariable("FF_TEST_NOFIGHTGC") == "1";
			ConfigEntry<int> val = config.Bind<int>("Memory", "MaxExtraMemoryMB", 0, "How much extra memory (MB) one fight may use before clean-ups come back on. 0 = automatic (1/8 of your RAM, at most 1536). Higher = fewer freezes in long fights but more RAM and a longer pause between points. Never more than 1/4 of your RAM.");
			capMb = FightGc.CapMb(SystemInfo.systemMemorySize, val.Value);
			if (!pauseInFights.Value || testOff)
			{
				return "counting memory clean-ups during fights (pausing them is off in the config).";
			}
			return $"memory clean-ups paused during fights, one after each (cap {capMb} MB extra per fight); counts logged every 5 minutes.";
		}

		public static void Tick()
		{
			bool flag = (Object)(object)GameManager.instance != (Object)null && GameManager.instance.battleOngoing;
			if (flag != lastFight)
			{
				lastFight = flag;
				if (flag)
				{
					cappedThisFight = false;
				}
			}
			Control(flag);
			int num = GC.CollectionCount(0);
			if (flag)
			{
				fightSecs += Time.unscaledDeltaTime;
			}
			if (last < 0)
			{
				last = num;
			}
			if (num != last)
			{
				if (flag)
				{
					inFight += num - last;
				}
				else
				{
					outside += num - last;
				}
				if (paused && whilePausedLogs++ < 20)
				{
					Plugin.Log.LogInfo((object)$"[memory clean-up] ran while paused (fight {flag}, {GC.GetTotalMemory(forceFullCollection: false) / 1048576} MB in use, +{(GC.GetTotalMemory(forceFullCollection: false) - pausedAt) / 1048576} MB since the pause)");
				}
				last = num;
			}
			if (Time.unscaledTime >= nextReport)
			{
				nextReport = Time.unscaledTime + every;
				if (inFight + outside + pauses > 0)
				{
					Plugin.Log.LogInfo((object)$"[memory clean-up] last {every / 60f:0.#} min: {inFight} during {fightSecs / 60.0:0.0} min of fighting ({((fightSecs > 0.0) ? ((double)inFight / (fightSecs / 60.0)) : 0.0):0.0} per fight-minute), {outside} between fights; paused in {pauses} fights, cap reached {caps} times, biggest growth in a fight {maxGrowthMb:0} MB (cap {capMb} MB), longest clean-up after a fight {maxEndMs:0} ms");
				}
				inFight = (outside = (pauses = (caps = 0)));
				fightSecs = 0.0;
				maxGrowthMb = 0.0;
				maxEndMs = 0.0;
			}
		}

		private static void Control(bool fight)
		{
			try
			{
				bool flag = pauseInFights != null && pauseInFights.Value && !testOff && !errorOff;
				if (!flag && !paused)
				{
					return;
				}
				double num = (paused ? ((double)(GC.GetTotalMemory(forceFullCollection: false) - pausedAt) / 1048576.0) : 0.0);
				if (paused && num > maxGrowthMb)
				{
					maxGrowthMb = num;
				}
				switch (FightGc.Decide(fight && flag, paused, num, capMb, cappedThisFight))
				{
				case FightGc.Act.Pause:
					pausedAt = GC.GetTotalMemory(forceFullCollection: false);
					GarbageCollector.GCMode = (Mode)0;
					paused = true;
					pauses++;
					break;
				case FightGc.Act.ResumeNow:
					GarbageCollector.GCMode = (Mode)1;
					paused = false;
					cappedThisFight = true;
					caps++;
					Plugin.Log.LogInfo((object)$"[memory clean-up] long fight: {num:0} MB of garbage (cap {capMb} MB), clean-ups back on until it ends");
					break;
				case FightGc.Act.ResumeAndClean:
				{
					GarbageCollector.GCMode = (Mode)1;
					paused = false;
					Stopwatch stopwatch = Stopwatch.StartNew();
					GC.Collect();
					stopwatch.Stop();
					if (stopwatch.Elapsed.TotalMilliseconds > maxEndMs)
					{
						maxEndMs = stopwatch.Elapsed.TotalMilliseconds;
					}
					break;
				}
				}
			}
			catch (Exception ex)
			{
				try
				{
					GarbageCollector.GCMode = (Mode)1;
				}
				catch
				{
				}
				paused = false;
				errorOff = true;
				Plugin.Log.LogWarning((object)("[memory clean-up] pausing turned off after an error: " + ex.Message));
			}
		}
	}
	internal static class GearUpRepairFix
	{
		private const string GearUpId = "com.pudassassin.rounds.GearUpCards";

		public static string Install()
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			Type type = AccessTools.TypeByName("GearUpCards.GearUpCards");
			if (type == null)
			{
				return "Gear Up Cards not installed; nothing to do.";
			}
			if (AccessTools.Field(type, "VFXBundle")?.GetValue(null) != null)
			{
				return "Gear Up Cards started normally; nothing to do.";
			}
			Harmony val = new Harmony("com.pudassassin.rounds.GearUpCards");
			val.UnpatchSelf();
			val.PatchAll(type.Assembly);
			MethodInfo methodInfo = AccessTools.Method("Jotunn.Utils.AssetUtils:LoadAssetBundleFromResources", new Type[2]
			{
				typeof(string),
				typeof(Assembly)
			}, (Type[])null);
			int num = 0;
			(string, string)[] array = new(string, string)[4]
			{
				("ATPBundle", "gearup_game_effect"),
				("VFXBundle", "gearup_asset"),
				("CardArtBundle", "gearup_cardarts"),
				("CardIconBundle", "gearup_cardicon")
			};
			for (int i = 0; i < array.Length; i++)
			{
				(string, string) tuple = array[i];
				string item = tuple.Item1;
				string item2 = tuple.Item2;
				FieldInfo fieldInfo = AccessTools.Field(type, item);
				if (fieldInfo == null || fieldInfo.GetValue(null) != null)
				{
					continue;
				}
				object obj = methodInfo.Invoke(null, new object[2] { item2, type.Assembly });
				if (obj == null)
				{
					Plugin.Log.LogWarning((object)("[Gear Up] bundle " + item2 + " didn't load"));
					continue;
				}
				obj.GetType().GetMethods().First((MethodInfo m) => m.Name == "LoadAllAssets" && !m.IsGenericMethod && m.GetParameters().Length == 0)
					.Invoke(obj, null);
				fieldInfo.SetValue(null, obj);
				num++;
			}
			return $"Gear Up Cards' startup had stopped half way; redid its patches and loaded {num} of its 4 asset bundles (EMPOWER effect, card art, icons).";
		}
	}
	internal static class GothFix
	{
		private static readonly GothHand hand = new GothHand();

		private static MethodInfo getDraws;

		private static MethodInfo setDraws;

		public static string Install(Harmony h)
		{
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Expected O, but got Unknown
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("CPCComplex.Cards.GothCard");
			if (type == null)
			{
				return "CPC Complex not installed; nothing to do.";
			}
			if (Environment.GetEnvironmentVariable("FF_TEST_NOGOTHFIX") == "1")
			{
				return "TEST: off.";
			}
			Type type2 = AccessTools.TypeByName("DrawNCards.DrawNCards");
			getDraws = ((type2 == null) ? null : AccessTools.Method(type2, "GetPickerDraws", (Type[])null, (Type[])null));
			setDraws = ((type2 == null) ? null : AccessTools.Method(type2, "SetPickerDraws", (Type[])null, (Type[])null));
			Type[] array = new Type[8]
			{
				typeof(Player),
				typeof(Gun),
				typeof(GunAmmo),
				typeof(CharacterData),
				typeof(HealthHandler),
				typeof(Gravity),
				typeof(Block),
				typeof(CharacterStatModifiers)
			};
			MethodInfo methodInfo = AccessTools.Method(type, "OnAddCard", array, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(type, "OnRemoveCard", array, (Type[])null);
			if (getDraws == null || setDraws == null || methodInfo == null || methodInfo2 == null)
			{
				return "Goth card or Pick N Cards changed; not active.";
			}
			h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(GothFix), "AddPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			h.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(GothFix), "RemovePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			GameModeManager.AddHook("GameStart", (Func<IGameModeHandler, IEnumerator>)delegate
			{
				hand.Reset();
				return Empty();
			});
			return "Goth cards (from Goth Girl) never cut a hand below 2 cards and give back exactly what they took.";
		}

		private static IEnumerator Empty()
		{
			yield break;
		}

		private static bool AddPrefix(Player player)
		{
			return Apply(player, adding: true);
		}

		private static bool RemovePrefix(Player player)
		{
			return Apply(player, adding: false);
		}

		private static bool Apply(Player player, bool adding)
		{
			try
			{
				int playerID = player.playerID;
				int num = (int)getDraws.Invoke(null, new object[1] { playerID });
				int num2 = (adding ? hand.Add(playerID, num, Time.unscaledTime) : hand.Remove(playerID, num, Time.unscaledTime));
				setDraws.Invoke(null, new object[2] { playerID, num2 });
				Plugin.Log.LogInfo((object)string.Format("[goth] player {0}: hand {1} -> {2} ({3})", playerID, num, num2, adding ? "Goth added" : "Goth removed"));
				return false;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[goth] fell back to the card's own code: " + ex.Message));
				return true;
			}
		}
	}
	internal static class HookNullFix
	{
		private const string Asm = "MapShffuler";

		public static string Install(Harmony h)
		{
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Expected O, but got Unknown
			if (AccessTools.TypeByName("MapShffuler.MapShffuler") == null)
			{
				return "Map Shffuler not installed; nothing to do.";
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(GameModeManager), "AddHook", new Type[2]
			{
				typeof(string),
				typeof(Func<IGameModeHandler, IEnumerator>)
			}, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(GameModeManager), "AddHook", new Type[3]
			{
				typeof(string),
				typeof(Func<IGameModeHandler, IEnumerator>),
				typeof(int)
			}, (Type[])null);
			if (methodInfo == null || methodInfo2 == null)
			{
				return "UnboundLib changed; not active.";
			}
			HarmonyMethod val = new HarmonyMethod(typeof(HookNullFix), "Prefix", (Type[])null);
			h.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			h.Patch((MethodBase)methodInfo2, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return "Map Shffuler's game-start hook no longer logs an error every game.";
		}

		private static void Prefix(ref Func<IGameModeHandler, IEnumerator> action)
		{
			try
			{
				Func<IGameModeHandler, IEnumerator> orig = action;
				if (!(orig?.Method?.DeclaringType?.Assembly.GetName().Name != "MapShffuler"))
				{
					action = (IGameModeHandler gm) => orig(gm) ?? Empty();
				}
			}
			catch
			{
			}
		}

		private static IEnumerator Empty()
		{
			yield break;
		}
	}
	internal static class HostRegion
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<(string code, string name), bool> <>9__9_0;

			public static UnityAction <>9__11_0;

			public static UnityAction <>9__16_0;

			public static UnityAction <>9__16_1;

			public static Predicate<(string code, string name)> <>9__18_0;

			public static Func<(string code, int ms), string> <>9__20_4;

			public static Func<(string code, int ms), bool> <>9__20_0;

			public static Func<(string code, int ms), int> <>9__20_1;

			public static Func<(string code, int ms), string> <>9__20_2;

			public static Func<(string code, int ms), string> <>9__20_3;

			internal bool <get_Chosen>b__9_0((string code, string name) r)
			{
				return r.code == setting?.Value;
			}

			internal void <Install>b__11_0()
			{
			}

			internal void <BuildMenu>b__16_0()
			{
				Cycle();
			}

			internal void <BuildMenu>b__16_1()
			{
				if (!testing)
				{
					((MonoBehaviour)Plugin.Instance).StartCoroutine(TestPings());
				}
			}

			internal bool <Cycle>b__18_0((string code, string name) r)
			{
				return r.code == Chosen;
			}

			internal string <TestPings>b__20_4((string code, int ms) r)
			{
				return NameOf(r.code) + " " + Ms(r.ms);
			}

			internal bool <TestPings>b__20_0((string code, int ms) r)
			{
				return r.ms > 0;
			}

			internal int <TestPings>b__20_1((string code, int ms) r)
			{
				return r.ms;
			}

			internal string <TestPings>b__20_2((string code, int ms) r)
			{
				return NameOf(r.code) + " " + Ms(r.ms);
			}

			internal string <TestPings>b__20_3((string code, int ms) r)
			{
				return $"{r.code}={r.ms}";
			}
		}

		public static readonly (string code, string name)[] Regions = new(string, string)[9]
		{
			("auto", "Auto (fastest for me)"),
			("usw", "US West"),
			("us", "US East"),
			("cae", "Canada East"),
			("sa", "South America"),
			("eu", "Europe"),
			("jp", "Japan"),
			("asia", "Asia"),
			("au", "Australia")
		};

		private static readonly string[] PingRegions = new string[5] { "usw", "us", "cae", "sa", "eu" };

		private static ConfigEntry<string> setting;

		private static bool hosting;

		private static bool testing;

		private static string lastResult = "";

		private static TextMeshProUGUI resultText;

		private static TextMeshProUGUI regionButtonText;

		public static string Chosen
		{
			get
			{
				if (!Regions.Any(((string code, string name) r) => r.code == setting?.Value))
				{
					return "auto";
				}
				return setting.Value;
			}
		}

		private static string Current => (PhotonNetwork.CloudRegion ?? "").Split(new char[1] { '/' })[0];

		public static string NameOf(string code)
		{
			return Regions.FirstOrDefault(((string code, string name) r) => r.code == code).name ?? code;
		}

		public static string Install(Harmony h, ConfigFile config)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			setting = config.Bind<string>("Online", "Host region", "auto", "Server region your private games are hosted on (friends join it automatically): auto, usw, us, cae, sa, eu, jp, asia, au.");
			MethodInfo methodInfo = AccessTools.Method("RWF.NetworkConnectionHandlerExtensions:HostPrivate", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				return "Rounds With Friends not installed; nothing to do.";
			}
			h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(HostRegion), "HostPrivatePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			object obj = <>c.<>9__11_0;
			if (obj == null)
			{
				UnityAction val = delegate
				{
				};
				<>c.<>9__11_0 = val;
				obj = (object)val;
			}
			Unbound.RegisterMenu("Friends Fixes", (UnityAction)obj, (Action<GameObject>)BuildMenu, (GameObject)null, false);
			return "private games are hosted on: " + NameOf(Chosen) + " (Mods menu -> Friends Fixes to change it or test your ping).";
		}

		private static bool HostPrivatePrefix(NetworkConnectionHandler instance)
		{
			if (hosting || Chosen == "auto" || testing)
			{
				return true;
			}
			try
			{
				((MonoBehaviour)Plugin.Instance).StartCoroutine(HostOn(instance, Chosen));
				return false;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[host region] " + ex.Message + "; hosting on the default region"));
				return true;
			}
		}

		private static IEnumerator HostOn(NetworkConnectionHandler nch, string region)
		{
			if (PhotonNetwork.IsConnected && Current != region)
			{
				Plugin.Log.LogInfo((object)("[host region] leaving " + Current + " to host on " + region));
				PhotonNetwork.Disconnect();
				float until = Time.realtimeSinceStartup + 10f;
				while (PhotonNetwork.IsConnected && Time.realtimeSinceStartup < until)
				{
					yield return null;
				}
				AccessTools.Field(typeof(NetworkConnectionHandler), "isConnectedToMaster").SetValue(nch, false);
			}
			RegionSelector.region = region;
			AccessTools.Field(typeof(NetworkConnectionHandler), "m_ForceRegion").SetValue(nch, true);
			hosting = true;
			try
			{
				AccessTools.Method("RWF.NetworkConnectionHandlerExtensions:HostPrivate", (Type[])null, (Type[])null).Invoke(null, new object[1] { nch });
			}
			finally
			{
				hosting = false;
			}
			float wait = Time.realtimeSinceStartup + 20f;
			while (!PhotonNetwork.InRoom && Time.realtimeSinceStartup < wait)
			{
				yield return null;
			}
			AccessTools.Field(typeof(NetworkConnectionHandler), "m_ForceRegion").SetValue(nch, false);
			Plugin.Log.LogInfo((object)(PhotonNetwork.InRoom ? $"[host region] hosting on {Current} (ping {PhotonNetwork.GetPing()} ms)" : "[host region] room not created within 20 s"));
		}

		private static void BuildMenu(GameObject menu)
		{
			//IL_0064: 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)
			//IL_006f: Expected O, but got Unknown
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			TextMeshProUGUI val = default(TextMeshProUGUI);
			MenuHandler.CreateText("ONLINE: HOST REGION", menu, ref val, 45, true, (Color?)null, (TMP_FontAsset)null, (Material)null, (TextAlignmentOptions?)null);
			MenuHandler.CreateText("Everyone's lag is their ping to the server region. Pick the region that is fair for the whole group. Friends join your region automatically; only the host's setting matters.", menu, ref val, 26, false, (Color?)null, (TMP_FontAsset)null, (Material)null, (TextAlignmentOptions?)null);
			string text = ButtonLabel();
			object obj = <>c.<>9__16_0;
			if (obj == null)
			{
				UnityAction val2 = delegate
				{
					Cycle();
				};
				<>c.<>9__16_0 = val2;
				obj = (object)val2;
			}
			regionButtonText = MenuHandler.CreateButton(text, menu, (UnityAction)obj, 40, true, (Color?)null, (TMP_FontAsset)null, (Material)null, (TextAlignmentOptions?)null).GetComponentInChildren<TextMeshProUGUI>();
			object obj2 = <>c.<>9__16_1;
			if (obj2 == null)
			{
				UnityAction val3 = delegate
				{
					if (!testing)
					{
						((MonoBehaviour)Plugin.Instance).StartCoroutine(TestPings());
					}
				};
				<>c.<>9__16_1 = val3;
				obj2 = (object)val3;
			}
			MenuHandler.CreateButton("TEST MY PING", menu, (UnityAction)obj2, 40, true, (Color?)null, (TMP_FontAsset)null, (Material)null, (TextAlignmentOptions?)null);
			MenuHandler.CreateText(lastResult, menu, ref resultText, 30, false, (Color?)null, (TMP_FontAsset)null, (Material)null, (TextAlignmentOptions?)null);
		}

		private static string ButtonLabel()
		{
			return "HOST ON: " + NameOf(Chosen).ToUpperInvariant() + "  (click to change)";
		}

		private static void Cycle()
		{
			int num = Array.FindIndex(Regions, ((string code, string name) r) => r.code == Chosen);
			setting.Value = Regions[(num + 1) % Regions.Length].code;
			if ((Object)(object)regionButtonText != (Object)null)
			{
				((TMP_Text)regionButtonText).text = ButtonLabel();
			}
			Plugin.Log.LogInfo((object)("[host region] set to " + NameOf(Chosen)));
		}

		private static void Show(string s)
		{
			lastResult = s;
			if ((Object)(object)resultText != (Object)null)
			{
				((TMP_Text)resultText).text = s;
			}
		}

		public static IEnumerator TestPings()
		{
			if (PhotonNetwork.InRoom)
			{
				Show("Leave the lobby/game first: the test reconnects to each region.");
				yield break;
			}
			testing = true;
			List<(string code, int ms)> results = new List<(string, int)>();
			try
			{
				string[] pingRegions = PingRegions;
				foreach (string code in pingRegions)
				{
					Show("Testing " + NameOf(code) + "... " + string.Join("   ", results.Select(((string code, int ms) r) => NameOf(r.code) + " " + Ms(r.ms))));
					yield return Disconnect();
					AppSettings appSettings = PhotonNetwork.PhotonServerSettings.AppSettings;
					string fixedRegion = appSettings.FixedRegion;
					appSettings.FixedRegion = code;
					try
					{
						PhotonNetwork.ConnectUsingSettings();
					}
					finally
					{
						appSettings.FixedRegion = fixedRegion;
					}
					float until = Time.realtimeSinceStartup + 8f;
					while ((!PhotonNetwork.IsConnectedAndReady || (int)PhotonNetwork.Server != 0) && Time.realtimeSinceStartup < until)
					{
						yield return null;
					}
					if (!PhotonNetwork.IsConnectedAndReady)
					{
						results.Add((code, -1));
						continue;
					}
					List<int> samples = new List<int>();
					for (int k = 0; k < 6; k++)
					{
						yield return (object)new WaitForSecondsRealtime(0.3f);
						samples.Add(PhotonNetwork.GetPing());
					}
					samples.Sort();
					results.Add((code, samples[samples.Count / 2]));
				}
				yield return Disconnect();
			}
			finally
			{
				testing = false;
			}
			(string, int) tuple = (from r in results
				where r.ms > 0
				orderby r.ms
				select r).FirstOrDefault();
			Show("Your ping:   " + string.Join("   ", results.Select(((string code, int ms) r) => NameOf(r.code) + " " + Ms(r.ms))) + ((tuple.Item1 != null) ? ("\nFastest for you: " + NameOf(tuple.Item1) + ". Ask your friends to test too, then host on the region with the lowest total.") : ""));
			Plugin.Log.LogInfo((object)("[host region] ping test: " + string.Join(", ", results.Select(((string code, int ms) r) => $"{r.code}={r.ms}"))));
		}

		private static string Ms(int ms)
		{
			if (ms >= 0)
			{
				return ms + " ms";
			}
			return "failed";
		}

		private static IEnumerator Disconnect()
		{
			if (PhotonNetwork.IsConnected)
			{
				PhotonNetwork.Disconnect();
				float until = Time.realtimeSinceStartup + 5f;
				while (PhotonNetwork.IsConnected && Time.realtimeSinceStartup < until)
				{
					yield return null;
				}
				NetworkConnectionHandler instance = NetworkConnectionHandler.instance;
				if ((Object)(object)instance != (Object)null)
				{
					AccessTools.Field(typeof(NetworkConnectionHandler), "isConnectedToMaster").SetValue(instance, false);
				}
			}
		}
	}
	internal static class LobbyFaceFix
	{
		private static Type selT;

		private static MethodInfo createFace;

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

		private static readonly Dictionary<int, float> asked = new Dictionary<int, float>();

		private static float nextTick;

		private static readonly Dictionary<int, PlayerFace> received = new Dictionary<int, PlayerFace>();

		public static string Install(Harmony h)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected O, but got Unknown
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected O, but got Unknown
			selT = AccessTools.TypeByName("RWF.UI.PrivateRoomCharacterSelectionInstance");
			if (selT == null)
			{
				return "Rounds With Friends not installed; nothing to do.";
			}
			if (Environment.GetEnvironmentVariable("FF_TEST_NOFACEFIX") == "1")
			{
				return "TEST: off.";
			}
			h.Patch((MethodBase)AccessTools.Method(typeof(CharacterCreatorPortrait), "FaceUpdated", (Type[])null, (Type[])null), new HarmonyMethod(typeof(LobbyFaceFix), "FaceUpdatedPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			h.Patch((MethodBase)AccessTools.Method(typeof(CharacterCreatorItemEquipper), "RPCA_SetFace", (Type[])null, (Type[])null), new HarmonyMethod(typeof(LobbyFaceFix), "SetFacePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			createFace = AccessTools.Method(typeof(PlayerFace), "CreateFace", (Type[])null, (Type[])null);
			MethodInfo methodInfo = AccessTools.Method(selT, "RPCO_SelectFace", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(LobbyFaceFix), "SelectPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (createFace != null)
			{
				h.Patch((MethodBase)AccessTools.Method(typeof(CharacterCreatorPortrait), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LobbyFaceFix), "PortraitStartPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			return "lobby pictures of other players keep their own face items (yours no longer get copied onto them).";
		}

		private static bool OthersPicture(Component c)
		{
			Component componentInParent = c.GetComponentInParent(selT);
			if ((Object)(object)componentInParent == (Object)null)
			{
				return false;
			}
			PhotonView component = componentInParent.GetComponent<PhotonView>();
			if ((Object)(object)component != (Object)null)
			{
				return !component.IsMine;
			}
			return false;
		}

		private static bool FaceUpdatedPrefix(CharacterCreatorPortrait __instance)
		{
			try
			{
				return !OthersPicture((Component)(object)__instance);
			}
			catch
			{
				return true;
			}
		}

		private static void SelectPrefix(Component __instance, int faceID)
		{
			PhotonView component = __instance.GetComponent<PhotonView>();
			if ((Object)(object)component != (Object)null && !component.IsMine)
			{
				sentSlot[component.ViewID] = faceID;
			}
		}

		public static void Tick()
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			if (selT == null || Time.unscaledTime < nextTick)
			{
				return;
			}
			nextTick = Time.unscaledTime + 1f;
			if (!PhotonNetwork.InRoom)
			{
				sentSlot.Clear();
				asked.Clear();
				return;
			}
			try
			{
				Object[] array = Object.FindObjectsOfType(selT);
				for (int i = 0; i < array.Length; i++)
				{
					Component val = (Component)array[i];
					PhotonView component = val.GetComponent<PhotonView>();
					if ((Object)(object)component == (Object)null || component.IsMine || component.Owner == null || !(Traverse.Create((object)val).Field("buttons").GetValue() is HoverEvent[] array2) || array2.Length == 0)
					{
						continue;
					}
					List<HoverEvent> list = array2.Where((HoverEvent b) => (Object)(object)b != (Object)null && ((Component)b).gameObject.activeSelf).ToList();
					if (!sentSlot.TryGetValue(component.ViewID, out var value))
					{
						if (!asked.TryGetValue(component.ViewID, out var value2) || Time.unscaledTime - value2 > 5f)
						{
							asked[component.ViewID] = Time.unscaledTime;
							component.RPC("RPCS_RequestSelectedFace", component.Owner, new object[1] { PhotonNetwork.LocalPlayer.ActorNumber });
						}
					}
					else
					{
						if (value < 0 || value >= array2.Length || (Object)(object)array2[value] == (Object)null || (list.Count == 1 && (Object)(object)list[0] == (Object)(object)array2[value]))
						{
							continue;
						}
						foreach (HoverEvent item in list)
						{
							if ((Object)(object)item != (Object)(object)array2[value])
							{
								((Component)item).gameObject.SetActive(false);
							}
						}
						if (!((Component)array2[value]).gameObject.activeSelf && (!asked.TryGetValue(component.ViewID, out var value3) || Time.unscaledTime - value3 > 5f))
						{
							asked[component.ViewID] = Time.unscaledTime;
							component.RPC("RPCS_RequestSelectedFace", component.Owner, new object[1] { PhotonNetwork.LocalPlayer.ActorNumber });
						}
						Plugin.Log.LogInfo((object)$"[lobby faces] {component.Owner.NickName}'s character showed {list.Count} face pictures; kept only slot {value} (the one they picked)");
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[lobby faces] check failed: " + ex.Message));
			}
		}

		private static void SetFacePrefix(CharacterCreatorItemEquipper __instance, int eyeID, Vector2 eyeOffset, int mouthID, Vector2 mouthOffset, int detailID, Vector2 detailOffset, int detail2ID, Vector2 detail2Offset)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			try
			{
				if (!((Object)(object)__instance.itemParent == (Object)null) && OthersPicture((Component)(object)__instance))
				{
					Empty(__instance);
					if (createFace != null)
					{
						received[((Object)__instance).GetInstanceID()] = (PlayerFace)createFace.Invoke(null, new object[8] { eyeID, eyeOffset, mouthID, mouthOffset, detailID, detailOffset, detail2ID, detail2Offset });
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[lobby faces] " + ex.Message));
			}
		}

		private static void Empty(CharacterCreatorItemEquipper eq)
		{
			for (int num = eq.itemParent.transform.childCount - 1; num >= 0; num--)
			{
				Transform child = eq.itemParent.transform.GetChild(num);
				if ((Object)(object)((Component)child).GetComponent<CharacterItem>() != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)((Component)child).gameObject);
				}
			}
		}

		private static void PortraitStartPostfix(CharacterCreatorPortrait __instance)
		{
			try
			{
				if (!OthersPicture((Component)(object)__instance))
				{
					return;
				}
				CharacterCreatorItemEquipper componentInChildren = ((Component)__instance).GetComponentInChildren<CharacterCreatorItemEquipper>();
				if ((Object)(object)componentInChildren == (Object)null || (Object)(object)componentInChildren.itemParent == (Object)null)
				{
					return;
				}
				Empty(componentInChildren);
				if (received.TryGetValue(((Object)componentInChildren).GetInstanceID(), out var value))
				{
					componentInChildren.EquipFace(value);
					Plugin.Log.LogInfo((object)"[lobby faces] a friend's picture got this PC's saved face; put their own face back");
					return;
				}
				Component componentInParent = ((Component)__instance).GetComponentInParent(selT);
				PhotonView val = ((componentInParent != null) ? componentInParent.GetComponent<PhotonView>() : null);
				if ((Object)(object)val != (Object)null && val.Owner != null && PhotonNetwork.InRoom)
				{
					val.RPC("RPCS_RequestSelectedFace", val.Owner, new object[1] { PhotonNetwork.LocalPlayer.ActorNumber });
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[lobby faces] " + ex.Message));
			}
		}
	}
	internal static class LobbyFix
	{
		private class Char
		{
			public int actor;

			public int localID;

			public int uid;

			public object lc;

			public Player owner;
		}

		private const float MissingFor = 8f;

		private const float RetryEvery = 10f;

		private static Type prhT;

		private static Type vdT;

		private static Type selT;

		private static FieldInfo prhInstance;

		private static FieldInfo vdInstance;

		private static FieldInfo devices;

		private static FieldInfo selGOs;

		private static FieldInfo created;

		private static PropertyInfo isOpen;

		private static PropertyInfo lockReadies;

		private static MethodInfo removePlayer;

		private static MethodInfo onInstantiate;

		private static string playersKey;

		private static readonly Dictionary<int, float> missingSince = new Dictionary<int, float>();

		private static readonly Dictionary<int, float> lastFix = new Dictionary<int, float>();

		private static readonly Dictionary<int, float> lastRequest = new Dictionary<int, float>();

		private static float next;

		internal static string testBreak = Environment.GetEnvironmentVariable("FF_TEST_LOBBYBREAK");

		private static readonly bool testNoFix = Environment.GetEnvironmentVariable("FF_TEST_LOBBYNOFIX") == "1";

		public static string Install()
		{
			prhT = AccessTools.TypeByName("RWF.PrivateRoomHandler");
			vdT = AccessTools.TypeByName("RWF.VersusDisplay");
			selT = AccessTools.TypeByName("RWF.UI.PrivateRoomCharacterSelectionInstance");
			if (prhT == null || vdT == null || selT == null)
			{
				return "Rounds With Friends not installed; nothing to do.";
			}
			prhInstance = AccessTools.Field(prhT, "instance");
			vdInstance = AccessTools.Field(vdT, "instance");
			devices = AccessTools.Field(prhT, "devicesToUse");
			selGOs = AccessTools.Field(vdT, "_playerSelectorGOs");
			created = AccessTools.Field(vdT, "_playerSelectorGOsCreated");
			isOpen = AccessTools.Property(prhT, "IsOpen");
			lockReadies = AccessTools.Property(prhT, "lockReadies");
			removePlayer = AccessTools.Method(prhT, "RemovePlayer", (Type[])null, (Type[])null);
			onInstantiate = AccessTools.Method(selT, "OnPhotonInstantiate", (Type[])null, (Type[])null);
			playersKey = (string)AccessTools.Method("RWF.RWFMod:GetCustomPropertyKey", (Type[])null, (Type[])null).Invoke(null, new object[1] { "players" });
			int num = new object[9] { prhInstance, vdInstance, devices, selGOs, created, isOpen, lockReadies, removePlayer, onInstantiate }.Count((object x) => x == null);
			if (num > 0)
			{
				return $"Rounds With Friends changed ({num} names not found); not active.";
			}
			return $"a character that doesn't show up in the lobby is rebuilt after {8f:0} s (no more leaving and rejoining).";
		}

		private static List<Char> Characters()
		{
			List<Char> list = new List<Char>();
			foreach (Player value3 in PhotonNetwork.CurrentRoom.Players.Values)
			{
				if (!(value3.CustomProperties[(object)playersKey] is Array array))
				{
					continue;
				}
				for (int i = 0; i < array.Length; i++)
				{
					object value = array.GetValue(i);
					if (value != null)
					{
						int value2 = Traverse.Create(value).Field("localID").GetValue<int>();
						list.Add(new Char
						{
							actor = value3.ActorNumber,
							localID = value2,
							uid = Traverse.Create(value).Property("uniqueID", (object[])null).GetValue<int>(),
							lc = value,
							owner = value3
						});
					}
				}
			}
			return list;
		}

		public static void Tick()
		{
			if (prhT == null || prhInstance == null || Time.unscaledTime < next)
			{
				return;
			}
			next = Time.unscaledTime + 1f;
			try
			{
				if (!PhotonNetwork.InRoom || PhotonNetwork.OfflineMode)
				{
					missingSince.Clear();
					return;
				}
				object? value = prhInstance.GetValue(null);
				MonoBehaviour val = (MonoBehaviour)((value is MonoBehaviour) ? value : null);
				object? value2 = vdInstance.GetValue(null);
				MonoBehaviour val2 = (MonoBehaviour)((value2 is MonoBehaviour) ? value2 : null);
				if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || !((Behaviour)val2).isActiveAndEnabled || !(bool)isOpen.GetValue(val) || (bool)lockReadies.GetValue(val))
				{
					missingSince.Clear();
					return;
				}
				Dictionary<int, GameObject> gos = (Dictionary<int, GameObject>)selGOs.GetValue(val2);
				List<int> list = (List<int>)created.GetValue(val2);
				IDictionary dictionary = (IDictionary)devices.GetValue(val);
				List<Char> list2 = Characters();
				HashSet<int> present = new HashSet<int>(list2.Select((Char c) => c.uid));
				int num = list.RemoveAll((int id) => !present.Contains(id) && !gos.ContainsKey(id));
				foreach (int item in gos.Keys.Where((int id) => (Object)(object)gos[id] == (Object)null && !present.Contains(id)).ToList())
				{
					gos.Remove(item);
				}
				if (num > 0)
				{
					Plugin.Log.LogInfo((object)$"[lobby] forgot {num} left character(s) RWF still had on its 'already made' list");
				}
				foreach (int item2 in missingSince.Keys.Where((int id) => !present.Contains(id)).ToList())
				{
					missingSince.Remove(item2);
				}
				if (testBreak != null)
				{
					TestBreak(list2, gos, list);
				}
				foreach (Char item3 in list2)
				{
					float value4;
					if (gos.TryGetValue(item3.uid, out var value3) && (Object)(object)value3 != (Object)null)
					{
						missingSince.Remove(item3.uid);
					}
					else if (!missingSince.TryGetValue(item3.uid, out value4))
					{
						missingSince[item3.uid] = Time.unscaledTime;
					}
					else
					{
						if (Time.unscaledTime - value4 < 8f || (lastFix.TryGetValue(item3.uid, out var value5) && Time.unscaledTime - value5 < 10f))
						{
							continue;
						}
						lastFix[item3.uid] = Time.unscaledTime;
						bool flag = item3.actor == PhotonNetwork.LocalPlayer.ActorNumber;
						if (testNoFix)
						{
							Plugin.Log.LogWarning((object)$"[lobby] TEST (no fix): {item3.owner.NickName}'s character #{item3.localID} still not shown after {Time.unscaledTime - value4:0} s");
							continue;
						}
						Plugin.Log.LogWarning((object)string.Format("[lobby] {0}'s character #{1} hasn't shown on this PC for {2:0} s (mine={3}, made={4}, selector={5}, controller={6}); fixing", item3.owner.NickName, item3.localID, Time.unscaledTime - value4, flag, list.Contains(item3.uid), gos.ContainsKey(item3.uid) ? "destroyed" : "none", flag ? dictionary.Contains(item3.localID).ToString() : "-"));
						if (flag)
						{
							FixMine(val, val2, item3, gos, list, dictionary);
						}
						else
						{
							FixRemote(item3, gos);
						}
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[lobby] check failed: " + ex.Message));
			}
		}

		private static IEnumerable<MonoBehaviour> SelectorsOf(int actor, int localID)
		{
			return Object.FindObjectsOfType(selT).Cast<MonoBehaviour>().Where(delegate(MonoBehaviour s)
			{
				PhotonView component = ((Component)s).GetComponent<PhotonView>();
				object[] array = ((component != null) ? component.InstantiationData : null);
				return array != null && array.Length >= 2 && array[0] is int num && num == actor && array[1] is int num2 && num2 == localID;
			});
		}

		private static void FixMine(MonoBehaviour prh, MonoBehaviour vd, Char c, Dictionary<int, GameObject> gos, List<int> made, IDictionary devs, bool fromFriend = false)
		{
			if (!devs.Contains(c.localID))
			{
				if (fromFriend)
				{
					Plugin.Log.LogInfo((object)"[lobby] rebuild request ignored: my character has no controller link (my own check handles it)");
					return;
				}
				Plugin.Log.LogInfo((object)"[lobby] removing my half-made character (no controller linked); press join again");
				prh.StartCoroutine((IEnumerator)removePlayer.Invoke(prh, new object[1] { c.lc }));
				return;
			}
			foreach (MonoBehaviour item in SelectorsOf(c.actor, c.localID).ToList())
			{
				try
				{
					PhotonNetwork.Destroy(((Component)item).gameObject);
				}
				catch
				{
					Object.Destroy((Object)(object)((Component)item).gameObject);
				}
			}
			gos.Remove(c.uid);
			made.Remove(c.uid);
			Plugin.Log.LogInfo((object)"[lobby] rebuilt my character's selector");
		}

		private static void FixRemote(Char c, Dictionary<int, GameObject> gos)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			gos.Remove(c.uid);
			MonoBehaviour val = SelectorsOf(c.actor, c.localID).FirstOrDefault();
			if ((Object)(object)val != (Object)null)
			{
				PhotonView component = ((Component)val).GetComponent<PhotonView>();
				onInstantiate.Invoke(val, new object[1] { (object)new PhotonMessageInfo(c.owner, PhotonNetwork.ServerTimestamp, component) });
				Plugin.Log.LogInfo((object)("[lobby] re-ran the setup of " + c.owner.NickName + "'s selector on this PC"));
			}
			else
			{
				NetworkingManager.RPC(typeof(LobbyFix), "RPCA_Rebuild", new object[2] { c.actor, c.localID });
				Plugin.Log.LogInfo((object)("[lobby] " + c.owner.NickName + "'s selector never arrived here; asked them to rebuild it"));
			}
		}

		[UnboundRPC]
		public static void RPCA_Rebuild(int actor, int localID)
		{
			if (PhotonNetwork.LocalPlayer.ActorNumber != actor)
			{
				return;
			}
			try
			{
				object? value = prhInstance.GetValue(null);
				MonoBehaviour val = (MonoBehaviour)((value is MonoBehaviour) ? value : null);
				object? value2 = vdInstance.GetValue(null);
				MonoBehaviour val2 = (MonoBehaviour)((value2 is MonoBehaviour) ? value2 : null);
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null))
				{
					Char obj = Characters().FirstOrDefault((Char x) => x.actor == actor && x.localID == localID);
					if (obj != null && (!lastRequest.TryGetValue(obj.uid, out var value3) || !(Time.unscaledTime - value3 < 10f)))
					{
						lastRequest[obj.uid] = Time.unscaledTime;
						Plugin.Log.LogInfo((object)"[lobby] a friend can't see my character; rebuilding it");
						FixMine(val, val2, obj, (Dictionary<int, GameObject>)selGOs.GetValue(val2), (List<int>)created.GetValue(val2), (IDictionary)devices.GetValue(val), fromFriend: true);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[lobby] rebuild failed: " + ex.Message));
			}
		}

		private static void TestBreak(List<Char> chars, Dictionary<int, GameObject> gos, List<int> made)
		{
			bool own = testBreak == "own";
			GameObject value;
			Char obj = chars.FirstOrDefault((Char x) => x.actor == PhotonNetwork.LocalPlayer.ActorNumber == own && gos.TryGetValue(x.uid, out value) && (Object)(object)value != (Object)null);
			if (obj != null)
			{
				testBreak = null;
				GameObject val = gos[obj.uid];
				if (own)
				{
					PhotonNetwork.Destroy(val);
					gos.Remove(obj.uid);
				}
				else
				{
					Object.Destroy((Object)(object)val);
				}
				Plugin.Log.LogWarning((object)string.Format("[lobby] TEST: broke {0} character #{1} (made={2})", own ? "my" : (obj.owner.NickName + "'s"), obj.localID, made.Contains(obj.uid)));
			}
		}
	}
	internal static class PickTimerTweak
	{
		internal const int NewDefault = 90;

		internal const int OldDefault = 15;

		internal const int OldMax = 60;

		internal const int NewMax = 120;

		public static string Install(Harmony h, ConfigFile myConfig)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("PickTimer.Util.ConfigController");
			if (type == null)
			{
				return "Pick Timer not installed; nothing to do.";
			}
			ConfigEntry<int> val = AccessTools.Field(type, "TimerTimerConfig")?.GetValue(null) as ConfigEntry<int>;
			MethodInfo methodInfo = AccessTools.Method("PickTimer.Network.LobbyMonitor:IncrementPickTimerValue", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method("PickTimer.Menu.Impl.GeneralSettings:Menu", (Type[])null, (Type[])null);
			if (val == null || methodInfo == null || methodInfo2 == null)
			{
				return "Pick Timer changed; not active.";
			}
			MethodInfo[] array = new MethodInfo[2] { methodInfo, methodInfo2 };
			foreach (MethodInfo methodInfo3 in array)
			{
				h.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(PickTimerTweak), "RaiseMax", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			}
			ConfigEntry<bool> obj = myConfig.Bind<bool>("Pick Timer", "Default set to 90", false, "Friends Fixes already moved Pick Timer from its 15 s default to 90 s once (set false to do it again).");
			string arg;
			if (!obj.Value && val.Value == 15)
			{
				val.Value = 90;
				arg = $"timer set to {90} s";
			}
			else
			{
				arg = $"timer stays at {val.Value} s (your setting)";
			}
			obj.Value = true;
			return $"{arg}; the menu slider and lobby buttons now go up to {120} s.";
		}

		private static IEnumerable<CodeInstruction> RaiseMax(IEnumerable<CodeInstruction> code)
		{
			foreach (CodeInstruction item in code)
			{
				if ((item.opcode == OpCodes.Ldc_I4_S || item.opcode == OpCodes.Ldc_I4) && Convert.ToInt32(item.operand) == 60)
				{
					yield return CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldc_I4, (object)120), item);
				}
				else if (item.opcode == OpCodes.Ldc_R4 && (float)item.operand == 60f)
				{
					yield return CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldc_R4, (object)120f), item);
				}
				else
				{
					yield return item;
				}
			}
		}
	}
	[BepInPlugin("dannythealien.rounds.friendsfixes", "Friends Fixes", "1.19.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "dannythealien.rounds.friendsfixes";

		private const string AmpGuid = "com.joel.rounds.advancedmovementpack";

		internal static ManualLogSource Log;

		private Harmony harmony;

		private static FieldInfo hardenedCount;

		private static Type hardenedType;

		private static int swallowedHits;

		private static int unexplainedHits;

		private static MethodInfo saveResolution;

		private static bool testNoSpawnPoints;

		private static read