Decompiled source of REPO Fixes Antispam Latency Fix v1.3.10

REPOFixesPlus.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using Photon.Voice;
using Photon.Voice.PUN;
using Photon.Voice.Unity;
using Steamworks;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("0.0.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 REPOFixesPlus
{
	[HarmonyPatch(typeof(GameDirector), "Start")]
	internal static class ConnectionTimeoutPatch
	{
		internal static int TimeoutSeconds = 30;

		private static bool _logged;

		private static void Postfix()
		{
			try
			{
				if (!PhotonNetwork.IsConnected)
				{
					return;
				}
				LoadBalancingClient networkingClient = PhotonNetwork.NetworkingClient;
				LoadBalancingPeer val = ((networkingClient != null) ? networkingClient.LoadBalancingPeer : null);
				if (val == null)
				{
					return;
				}
				int num = TimeoutSeconds * 1000;
				if (((PhotonPeer)val).DisconnectTimeout < num)
				{
					((PhotonPeer)val).DisconnectTimeout = num;
				}
				if (((PhotonPeer)val).SentCountAllowance < 10)
				{
					((PhotonPeer)val).SentCountAllowance = 10;
				}
				PunVoiceClient instance = PunVoiceClient.Instance;
				object obj;
				if (instance == null)
				{
					obj = null;
				}
				else
				{
					LoadBalancingTransport client = ((VoiceConnection)instance).Client;
					obj = ((client != null) ? ((LoadBalancingClient)client).LoadBalancingPeer : null);
				}
				LoadBalancingPeer val2 = (LoadBalancingPeer)obj;
				if (val2 != null)
				{
					if (((PhotonPeer)val2).DisconnectTimeout < num)
					{
						((PhotonPeer)val2).DisconnectTimeout = num;
					}
					if (((PhotonPeer)val2).SentCountAllowance < 10)
					{
						((PhotonPeer)val2).SentCountAllowance = 10;
					}
				}
				if (!_logged)
				{
					_logged = true;
					Plugin.Log.LogInfo((object)($"[Connection timeout] Photon disconnect timeout set to {((PhotonPeer)val).DisconnectTimeout / 1000}s, resends to {((PhotonPeer)val).SentCountAllowance}" + ((val2 != null) ? $"; voice chat {((PhotonPeer)val2).DisconnectTimeout / 1000}s." : ".")));
				}
			}
			catch (Exception e)
			{
				Suppressed.Report("Connection timeout", e);
			}
		}
	}
	[HarmonyPatch(typeof(SlowWalkerAttack), "SuckInListPlayerUpdate")]
	internal static class SlowWalkerSuckInFinalizerPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Suppressed.Report("SlowWalkerAttack.SuckInListPlayerUpdate", __exception);
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(EnemySlowMouthAttached), "Update")]
	internal static class SlowMouthAttachedUpdateFinalizerPatch
	{
		private static readonly FieldRef<EnemySlowMouthAttached, EnemySlowMouth> ParentEnemy = AccessTools.FieldRefAccess<EnemySlowMouthAttached, EnemySlowMouth>("enemySlowMouth");

		private static Exception Finalizer(Exception __exception, EnemySlowMouthAttached __instance)
		{
			if (__exception == null)
			{
				return null;
			}
			Suppressed.Report("EnemySlowMouthAttached.Update", __exception);
			try
			{
				if ((Object)(object)__instance != (Object)null && !Object.op_Implicit((Object)(object)ParentEnemy.Invoke(__instance)))
				{
					DestroyIfAlive(__instance.otherTopJawTransform);
					DestroyIfAlive(__instance.otherBotJawTransform);
					DestroyIfAlive(__instance.localParentTransform);
					Object.Destroy((Object)(object)((Component)__instance).gameObject);
					Plugin.Log.LogInfo((object)"[Enemy attack fix] Removed a Spewer mouth left attached to a player after its enemy was gone.");
				}
			}
			catch (Exception e)
			{
				Suppressed.Report("EnemySlowMouthAttached cleanup", e);
			}
			return null;
		}

		private static void DestroyIfAlive(Transform t)
		{
			if (Object.op_Implicit((Object)(object)t))
			{
				Object.Destroy((Object)(object)((Component)t).gameObject);
			}
		}
	}
	[HarmonyPatch(typeof(EnemyTumbler), "Update")]
	internal static class TumblerTargetLeftPatch
	{
		private static readonly MethodInfo UpdateState = AccessTools.Method(typeof(EnemyTumbler), "UpdateState", (Type[])null, (Type[])null);

		private static readonly FieldRef<EnemyTumbler, PlayerAvatar> Target = AccessTools.FieldRefAccess<EnemyTumbler, PlayerAvatar>("targetPlayer");

		private static void Prefix(EnemyTumbler __instance)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Invalid comparison between Unknown and I4
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				State currentState = __instance.currentState;
				if (((int)currentState == 3 || (int)currentState == 5 || (int)currentState == 6 || (int)currentState == 7) && SemiFunc.IsMasterClientOrSingleplayer())
				{
					PlayerAvatar val = Target.Invoke(__instance);
					if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val.PlayerVisionTarget) || !Object.op_Implicit((Object)(object)val.PlayerVisionTarget.VisionTransform))
					{
						State val2 = (State)(((int)currentState != 7) ? 1 : 8);
						UpdateState.Invoke(__instance, new object[1] { val2 });
						Plugin.Log.LogInfo((object)$"[Enemy attack fix] A Tumbler's target left the game; it stopped chasing ({currentState} -> {val2}) instead of freezing and throwing an error every frame.");
					}
				}
			}
			catch (Exception e)
			{
				Suppressed.Report("EnemyTumbler target check", e);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerAvatar), "Awake")]
	internal static class PlayerAvatarAwakePatch
	{
		private static void Postfix(PlayerAvatar __instance)
		{
			try
			{
				if (!((Object)(object)__instance == (Object)null) && !((Object)(object)__instance.photonView == (Object)null) && !((Object)(object)GameDirector.instance == (Object)null) && GameDirector.instance.PlayerList.Contains(__instance) && !RegistrationHelper.LateJoinPlusCovers())
				{
					int viewID = __instance.photonView.ViewID;
					int num = RegistrationHelper.RegisterPlayerWithAllTrackers(viewID);
					if (num > 0)
					{
						Plugin.Log.LogInfo((object)$"Registered player (viewID={viewID}) with {num} enemy trackers currently in the scene.");
					}
				}
			}
			catch (Exception e)
			{
				Suppressed.Report("PlayerAvatar.Awake postfix", e);
			}
		}
	}
	[HarmonyPatch(typeof(EnemyVision), "Awake")]
	internal static class EnemyVisionAwakePatch
	{
		private static void Postfix(EnemyVision __instance)
		{
			try
			{
				RegistrationHelper.RegisterAllCurrentPlayers((Action<int>)__instance.PlayerAdded);
			}
			catch (Exception e)
			{
				Suppressed.Report("EnemyVision.Awake postfix", e);
			}
		}
	}
	[HarmonyPatch(typeof(EnemyOnScreen), "Awake")]
	internal static class EnemyOnScreenAwakePatch
	{
		private static void Postfix(EnemyOnScreen __instance)
		{
			try
			{
				RegistrationHelper.RegisterAllCurrentPlayers((Action<int>)__instance.PlayerAdded);
			}
			catch (Exception e)
			{
				Suppressed.Report("EnemyOnScreen.Awake postfix", e);
			}
		}
	}
	[HarmonyPatch(typeof(EnemyOnScreen), "GetOnScreen")]
	internal static class GetOnScreenPatch
	{
		private static void Prefix(EnemyOnScreen __instance, PlayerAvatar _playerAvatar)
		{
			if ((Object)(object)_playerAvatar != (Object)null && (Object)(object)_playerAvatar.photonView != (Object)null)
			{
				__instance.PlayerAdded(_playerAvatar.photonView.ViewID);
			}
		}
	}
	internal static class RegistrationHelper
	{
		private static PropertyInfo _lateJoinOn;

		private static bool _lookedForLateJoin;

		public static bool LateJoinPlusCovers()
		{
			if (!_lookedForLateJoin)
			{
				_lookedForLateJoin = true;
				if (Plugin.ModLoaded("ricketywrecked.repo.latejoinplus"))
				{
					_lateJoinOn = AccessTools.Property(AccessTools.TypeByName("LateJoinPlus.Core.ModConfig"), "On");
				}
			}
			if (_lateJoinOn != null && _lateJoinOn.PropertyType == typeof(bool))
			{
				return (bool)_lateJoinOn.GetValue(null);
			}
			return false;
		}

		public static void RegisterAllCurrentPlayers(Action<int> playerAdded)
		{
			if ((Object)(object)GameDirector.instance == (Object)null || GameDirector.instance.PlayerList == null)
			{
				return;
			}
			foreach (PlayerAvatar player in GameDirector.instance.PlayerList)
			{
				if ((Object)(object)player != (Object)null && (Object)(object)player.photonView != (Object)null)
				{
					playerAdded(player.photonView.ViewID);
				}
			}
		}

		public static int RegisterPlayerWithAllTrackers(int viewID)
		{
			int num = 0;
			EnemyVision[] array = Object.FindObjectsOfType<EnemyVision>(true);
			foreach (EnemyVision val in array)
			{
				if (!((Object)(object)val == (Object)null))
				{
					val.PlayerAdded(viewID);
					num++;
				}
			}
			EnemyOnScreen[] array2 = Object.FindObjectsOfType<EnemyOnScreen>(true);
			foreach (EnemyOnScreen val2 in array2)
			{
				if (!((Object)(object)val2 == (Object)null))
				{
					val2.PlayerAdded(viewID);
					num++;
				}
			}
			return num;
		}
	}
	internal static class ExtractionSoftlock
	{
		private static FieldRef<ExtractionPoint, State> _state;

		private static FieldRef<RoundDirector, bool> _running;

		private static FieldRef<ExtractionPoint, State> State => _state ?? (_state = AccessTools.FieldRefAccess<ExtractionPoint, State>("currentState"));

		private static FieldRef<RoundDirector, bool> Running => _running ?? (_running = AccessTools.FieldRefAccess<RoundDirector, bool>("extractionPointActive"));

		internal unsafe static bool Allowed(int photonViewID, string via)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Invalid comparison between Unknown and I4
			try
			{
				if (!PhotonNetwork.IsMasterClient)
				{
					return true;
				}
				PhotonView val = PhotonView.Find(photonViewID);
				ExtractionPoint val2 = (Object.op_Implicit((Object)(object)val) ? ((Component)val).GetComponent<ExtractionPoint>() : null);
				if (!Object.op_Implicit((Object)(object)val2))
				{
					return true;
				}
				State val3 = State.Invoke(val2);
				if ((int)val3 == 1 && !val2.isLocked)
				{
					return true;
				}
				if (!Object.op_Implicit((Object)(object)RoundDirector.instance) || !Running.Invoke(RoundDirector.instance))
				{
					Plugin.Log.LogInfo((object)($"[Extraction softlock fix] Ignored a request to start extraction point {photonViewID} ({via}): it is " + (val2.isLocked ? "locked" : ((object)(*(State*)(&val3))/*cast due to .constrained prefix*/).ToString()) + ", not ready. Starting it would have locked every other extraction point for the rest of the level."));
				}
				return false;
			}
			catch (Exception e)
			{
				Suppressed.Report("Extraction softlock fix", e);
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(RoundDirector), "RequestExtractionPointActivationRPC")]
	internal static class RequestExtractionActivationPatch
	{
		private static bool Prefix(int photonViewID)
		{
			return ExtractionSoftlock.Allowed(photonViewID, "requested by a player");
		}
	}
	[HarmonyPatch(typeof(RoundDirector), "ExtractionPointActivate")]
	internal static class HostExtractionActivationPatch
	{
		private static bool Prefix(int photonViewID)
		{
			return ExtractionSoftlock.Allowed(photonViewID, "host");
		}
	}
	internal static class ExtraSlotLabelFix
	{
		[HarmonyPatch(typeof(InputGlyphText), "Refresh")]
		internal static class RefreshPatch
		{
			private static bool Prefix(InputGlyphText __instance)
			{
				InventorySpot componentInParent = ((Component)__instance).GetComponentInParent<InventorySpot>(true);
				if ((Object)(object)componentInParent == (Object)null || componentInParent.inventorySpotIndex < 3)
				{
					return true;
				}
				if (!_logged)
				{
					_logged = true;
					Plugin.Log.LogInfo((object)("Extra slot labels: kept the number on inventory slot " + (componentInParent.inventorySpotIndex + 1) + " and any others a mod added."));
				}
				return false;
			}
		}

		private const int VanillaSlots = 3;

		private static bool _logged;
	}
	internal static class ExtraSlotRowFix
	{
		private sealed class LayoutState
		{
			public InventorySpot[] Spots;

			public Array Labels;

			public string[] PreviousBindings;

			public float[] PositionsX;

			public float CenterX;

			public float ItemWidth;
		}

		[HarmonyPatch(typeof(InventorySpot), "Start")]
		internal static class StartPatch
		{
			[HarmonyPostfix]
			private static void Postfix(InventorySpot __instance)
			{
				if (!((Object)(object)__instance == (Object)null) && __instance.inventorySpotIndex >= 3)
				{
					RelayoutAllSlots();
				}
			}
		}

		private const int FirstAddedSlotIndex = 3;

		private static readonly FieldInfo InventorySpotsField = AccessTools.Field(typeof(InventoryUI), "inventorySpots");

		private static readonly FieldInfo BindingLabelsField = AccessTools.Field(typeof(InventoryUI), "bindingLabels");

		private static readonly FieldInfo PreviousBindingsField = AccessTools.Field(typeof(InventoryUI), "previousBindings");

		private static readonly FieldInfo SlotPositionsXField = AccessTools.Field(typeof(InventoryUI), "slotPositionsX");

		private static readonly FieldInfo SlotCenterXField = AccessTools.Field(typeof(InventoryUI), "slotCenterX");

		private static readonly FieldInfo ItemWidthField = AccessTools.Field(typeof(InventoryUI), "itemWidth");

		private static readonly MethodInfo LayoutSetupMethod = AccessTools.Method(typeof(InventoryUI), "LayoutSetup", (Type[])null, (Type[])null);

		private static readonly FieldInfo AppliedLayoutOffsetXField = AccessTools.Field(typeof(InventorySpot), "appliedLayoutOffsetX");

		private static InventoryUI centreOwner;

		private static float vanillaCentreX;

		private static bool warned;

		private static bool LookupsFound()
		{
			if (InventorySpotsField != null && BindingLabelsField != null && PreviousBindingsField != null && SlotPositionsXField != null && SlotCenterXField != null && ItemWidthField != null && LayoutSetupMethod != null)
			{
				return AppliedLayoutOffsetXField != null;
			}
			return false;
		}

		private static void WarnOnce(string message)
		{
			if (!warned)
			{
				warned = true;
				Plugin.Log.LogWarning((object)("[ExtraSlotRowFix] " + message));
			}
		}

		private static LayoutState Capture(InventoryUI ui)
		{
			return new LayoutState
			{
				Spots = (InventorySpot[])((InventorySpot[])InventorySpotsField.GetValue(ui))?.Clone(),
				Labels = (Array)(((Array)BindingLabelsField.GetValue(ui))?.Clone()),
				PreviousBindings = (string[])((string[])PreviousBindingsField.GetValue(ui))?.Clone(),
				PositionsX = (float[])((float[])SlotPositionsXField.GetValue(ui))?.Clone(),
				CenterX = (float)SlotCenterXField.GetValue(ui),
				ItemWidth = (float)ItemWidthField.GetValue(ui)
			};
		}

		private static void Restore(InventoryUI ui, LayoutState state)
		{
			InventorySpotsField.SetValue(ui, state.Spots);
			BindingLabelsField.SetValue(ui, state.Labels);
			PreviousBindingsField.SetValue(ui, state.PreviousBindings);
			SlotPositionsXField.SetValue(ui, state.PositionsX);
			SlotCenterXField.SetValue(ui, state.CenterX);
			ItemWidthField.SetValue(ui, state.ItemWidth);
		}

		private static float VanillaCentre(LayoutState awakeState)
		{
			if (awakeState.Spots != null && awakeState.PositionsX != null && awakeState.Spots.Length == awakeState.PositionsX.Length)
			{
				float num = 0f;
				int num2 = 0;
				for (int i = 0; i < awakeState.Spots.Length; i++)
				{
					InventorySpot val = awakeState.Spots[i];
					if (!((Object)(object)val == (Object)null) && val.inventorySpotIndex < 3)
					{
						num += awakeState.PositionsX[i];
						num2++;
					}
				}
				if (num2 > 0)
				{
					return num / (float)num2;
				}
			}
			return awakeState.CenterX;
		}

		private static void RelayoutAllSlots()
		{
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			InventoryUI instance = InventoryUI.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (!LookupsFound())
			{
				WarnOnce("Could not find InventoryUI/InventorySpot members (game update?). Extra slots will not be re-spaced.");
				return;
			}
			LayoutState layoutState = null;
			try
			{
				layoutState = Capture(instance);
				if (centreOwner != instance)
				{
					vanillaCentreX = VanillaCentre(layoutState);
					centreOwner = instance;
				}
				SlotCenterXField.SetValue(instance, 0f);
				LayoutSetupMethod.Invoke(instance, null);
				InventorySpot[] array = (InventorySpot[])InventorySpotsField.GetValue(instance);
				Array array2 = (Array)BindingLabelsField.GetValue(instance);
				float[] array3 = (float[])SlotPositionsXField.GetValue(instance);
				if (array == null || array2 == null || array3 == null || array2.Length != array.Length || array3.Length != array.Length)
				{
					Restore(instance, layoutState);
					WarnOnce("LayoutSetup returned unexpected arrays. Leaving the slot row as it was.");
					return;
				}
				bool flag = false;
				for (int i = 0; i < array.Length; i++)
				{
					if ((Object)(object)array[i] == (Object)null)
					{
						Restore(instance, layoutState);
						WarnOnce("A slot was missing after LayoutSetup. Leaving the slot row as it was.");
						return;
					}
					object? value = array2.GetValue(i);
					if ((Object)((value is Object) ? value : null) == (Object)null)
					{
						Restore(instance, layoutState);
						WarnOnce("An added slot (index " + array[i].inventorySpotIndex + ") has no binding label. Leaving the slot row as it was.");
						return;
					}
					if (array[i].inventorySpotIndex >= 3)
					{
						flag = true;
					}
				}
				if (!flag)
				{
					Restore(instance, layoutState);
					return;
				}
				for (int j = 0; j < array.Length; j++)
				{
					float num = (float)AppliedLayoutOffsetXField.GetValue(array[j]);
					array3[j] = ((((SemiUI)array[j]).showPosition != Vector2.zero) ? ((SemiUI)array[j]).showPosition.x : (((Component)array[j]).transform.localPosition.x - num));
				}
				SlotCenterXField.SetValue(instance, vanillaCentreX);
				PreviousBindingsField.SetValue(instance, new string[array.Length]);
			}
			catch (Exception ex)
			{
				try
				{
					if (layoutState != null)
					{
						Restore(instance, layoutState);
					}
				}
				catch
				{
				}
				WarnOnce("Failed to lay out extra inventory slots: " + ((ex is TargetInvocationException { InnerException: not null } ex2) ? ex2.InnerException : ex));
			}
		}
	}
	internal static class ExtraSlotsPersistence
	{
		private const int FirstExtraSpot = 3;

		private const float LocalTimeout = 10f;

		private const float RemoteSettle = 4f;

		private static readonly FieldRef<PlayerAvatar, string> SteamID = AccessTools.FieldRefAccess<PlayerAvatar, string>("steamID");

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

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

		internal static void Record(string steamID, string itemName, int spot)
		{
			if (spot < 3 || string.IsNullOrEmpty(steamID) || !SemiFunc.IsMasterClientOrSingleplayer())
			{
				return;
			}
			if (!Records.TryGetValue(steamID, out var value))
			{
				value = new Dictionary<int, int>();
				Records[steamID] = value;
			}
			if (string.IsNullOrEmpty(itemName))
			{
				if (value.Remove(spot))
				{
					Plugin.Log.LogInfo((object)$"[Extra slots] Slot {spot + 1} emptied.");
				}
			}
			else
			{
				value[spot] = itemName.GetHashCode();
				Plugin.Log.LogInfo((object)$"[Extra slots] Remembering '{itemName}' in slot {spot + 1}.");
			}
		}

		internal static void TryReequip(string itemName, int photonViewID, ItemAttributes itemAttributes)
		{
			if (Records.Count == 0 || string.IsNullOrEmpty(itemName) || !SemiFunc.IsMasterClientOrSingleplayer())
			{
				return;
			}
			if (SemiFunc.IsMultiplayer())
			{
				PhotonView val = PhotonView.Find(photonViewID);
				itemAttributes = (Object.op_Implicit((Object)(object)val) ? ((Component)val).GetComponent<ItemAttributes>() : null);
			}
			ItemEquippable val2 = (Object.op_Implicit((Object)(object)itemAttributes) ? ((Component)itemAttributes).GetComponent<ItemEquippable>() : null);
			if (!Object.op_Implicit((Object)(object)val2) || val2.IsEquipped())
			{
				return;
			}
			int hashCode = itemName.GetHashCode();
			foreach (PlayerAvatar item2 in SemiFunc.PlayerGetList())
			{
				string text = (Object.op_Implicit((Object)(object)item2) ? SteamID.Invoke(item2) : null);
				if (text == null || !Records.TryGetValue(text, out var value))
				{
					continue;
				}
				foreach (KeyValuePair<int, int> item3 in value)
				{
					string item = text + ":" + item3.Key;
					if (item3.Value == hashCode && !Taken.Contains(item))
					{
						Taken.Add(item);
						if ((Object)(object)PunManager.instance != (Object)null)
						{
							((MonoBehaviour)PunManager.instance).StartCoroutine(ReequipWhenReady(val2, item3.Key, item2, itemName));
						}
						return;
					}
				}
			}
		}

		private static IEnumerator ReequipWhenReady(ItemEquippable equippable, int spot, PlayerAvatar player, string itemName)
		{
			bool local = !SemiFunc.IsMultiplayer() || ((Object)(object)player.photonView != (Object)null && player.photonView.IsMine);
			float start = Time.unscaledTime;
			while (true)
			{
				if (!Object.op_Implicit((Object)(object)equippable) || !Object.op_Implicit((Object)(object)player))
				{
					yield break;
				}
				float num = Time.unscaledTime - start;
				if (local ? LocalSpotExists(spot) : (num >= 4f))
				{
					break;
				}
				if (num >= 10f)
				{
					Plugin.Log.LogWarning((object)$"[Extra slots] Slot {spot + 1} never appeared; leaving '{itemName}' in the truck.");
					yield break;
				}
				yield return null;
			}
			if (!equippable.IsEquipped())
			{
				equippable.RequestEquip(spot, SemiFunc.IsMultiplayer() ? player.photonView.ViewID : (-1));
				Plugin.Log.LogInfo((object)$"[Extra slots] Put '{itemName}' back in slot {spot + 1} (after {Time.unscaledTime - start:0.0}s).");
			}
		}

		private static bool LocalSpotExists(int spot)
		{
			Inventory instance = Inventory.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			List<InventorySpot> allSpots = instance.GetAllSpots();
			if (allSpots != null && spot < allSpots.Count)
			{
				return (Object)(object)allSpots[spot] != (Object)null;
			}
			return false;
		}

		internal static void ClearTaken()
		{
			Taken.Clear();
		}

		internal static void ClearAll()
		{
			Records.Clear();
			Taken.Clear();
		}
	}
	[HarmonyPatch(typeof(StatsManager), "PlayerInventoryUpdate")]
	internal static class ExtraSlotsRecordPatch
	{
		private static void Postfix(string _steamID, string itemName, int spot)
		{
			try
			{
				ExtraSlotsPersistence.Record(_steamID, itemName, spot);
			}
			catch (Exception e)
			{
				Suppressed.Report("Extra slots record", e);
			}
		}
	}
	[HarmonyPatch(typeof(PunManager), "SetItemNameLOGIC")]
	internal static class ExtraSlotsReequipPatch
	{
		private static void Postfix(string _name, int photonViewID, ItemAttributes _itemAttributes)
		{
			try
			{
				ExtraSlotsPersistence.TryReequip(_name, photonViewID, _itemAttributes);
			}
			catch (Exception e)
			{
				Suppressed.Report("Extra slots re-equip", e);
			}
		}
	}
	[HarmonyPatch(typeof(StatsManager), "StuffNeedingResetAtTheEndOfAScene")]
	internal static class ExtraSlotsSceneResetPatch
	{
		private static void Postfix()
		{
			ExtraSlotsPersistence.ClearTaken();
		}
	}
	[HarmonyPatch(typeof(StatsManager), "ResetAllStats")]
	internal static class ExtraSlotsRunResetPatch
	{
		private static void Postfix()
		{
			ExtraSlotsPersistence.ClearAll();
		}
	}
	internal static class GameboyIdlePause
	{
		private const byte FrameSyncEventCode = 192;

		private const int PackedFrameBytes = 5760;

		private static readonly byte[] BlackFrame = CreateBlackFrame();

		private static FieldInfo _hostEmulatorField;

		private static FieldInfo _controllerField;

		private static FieldInfo _lastPackedFrameField;

		private static FieldInfo _broadcastFrameIdField;

		private static MethodInfo _hasHostAuthority;

		private static MethodInfo _broadcastStatus;

		private static MethodInfo _clearDisplay;

		private static MethodInfo _flushSave;

		private static object _pausedEmulator;

		private static double _nextStatus;

		internal static bool TryApply(Harmony harmony)
		{
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Expected O, but got Unknown
			Type type = (Plugin.ModLoaded("com.empress.gameboy") ? AccessTools.TypeByName("EmpressGameboy.EmpressGameboyRuntime") : null);
			if (type == null)
			{
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(type, "TickHostEmulator", (Type[])null, (Type[])null);
			_hostEmulatorField = AccessTools.Field(type, "_hostEmulator");
			_controllerField = AccessTools.Field(type, "_controllerActorNumber");
			_lastPackedFrameField = AccessTools.Field(type, "_lastPackedFrame");
			_broadcastFrameIdField = AccessTools.Field(type, "_broadcastFrameId");
			_hasHostAuthority = AccessTools.Method(type, "HasHostAuthority", (Type[])null, (Type[])null);
			_broadcastStatus = AccessTools.Method(type, "BroadcastStatus", new Type[1] { typeof(bool) }, (Type[])null);
			_clearDisplay = AccessTools.Method(type, "ClearDisplayTexture", new Type[1] { typeof(Color32) }, (Type[])null);
			_flushSave = ((_hostEmulatorField != null) ? AccessTools.Method(_hostEmulatorField.FieldType, "FlushSave", (Type[])null, (Type[])null) : null);
			if (methodInfo == null || _hostEmulatorField == null || _controllerField?.FieldType != typeof(int) || _lastPackedFrameField?.FieldType != typeof(byte[]) || _broadcastFrameIdField?.FieldType != typeof(int) || _hasHostAuthority == null || _broadcastStatus == null || _clearDisplay == null || _flushSave == null)
			{
				Plugin.Log.LogWarning((object)"[Gameboy idle pause] Empress Gameboy is installed but doesn't have the expected internals (different version?); leaving it alone.");
				return false;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(GameboyIdlePause), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return true;
		}

		private static bool Prefix(object __instance)
		{
			try
			{
				object value = _hostEmulatorField.GetValue(__instance);
				if (value == null || !(bool)_hasHostAuthority.Invoke(__instance, null))
				{
					_pausedEmulator = null;
					return true;
				}
				if ((int)_controllerField.GetValue(__instance) != 0)
				{
					_pausedEmulator = null;
					return true;
				}
				if (_pausedEmulator != value)
				{
					_pausedEmulator = value;
					EnterPause(__instance, value);
				}
				double unscaledTimeAsDouble = Time.unscaledTimeAsDouble;
				if (unscaledTimeAsDouble >= _nextStatus)
				{
					_nextStatus = unscaledTimeAsDouble + 1.0;
					_broadcastStatus.Invoke(__instance, new object[1] { false });
				}
				return false;
			}
			catch (Exception e)
			{
				Suppressed.Report("Gameboy idle pause", e);
				return true;
			}
		}

		private static void EnterPause(object runtime, object emulator)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			_flushSave.Invoke(emulator, null);
			_clearDisplay.Invoke(runtime, new object[1] { (object)new Color32((byte)0, (byte)0, (byte)0, byte.MaxValue) });
			_lastPackedFrameField.SetValue(runtime, null);
			if (PhotonNetwork.InRoom)
			{
				int num = (int)_broadcastFrameIdField.GetValue(runtime) + 1;
				_broadcastFrameIdField.SetValue(runtime, num);
				PhotonNetwork.RaiseEvent((byte)192, (object)new object[2] { num, BlackFrame }, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)0
				}, SendOptions.SendReliable);
			}
			Plugin.Log.LogInfo((object)"[Gameboy idle pause] Nobody is playing; Game Boy paused and screen blanked.");
		}

		private static byte[] CreateBlackFrame()
		{
			byte[] array = new byte[5760];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = byte.MaxValue;
			}
			return array;
		}
	}
	[HarmonyPatch(typeof(PhysGrabBeam), "DrawCurve")]
	internal static class DrawCurveNullGuardPatch
	{
		private static bool Prefix(PhysGrabBeam __instance)
		{
			if (!Object.op_Implicit((Object)(object)__instance.PhysGrabPointPuller) || !Object.op_Implicit((Object)(object)__instance.PhysGrabPointOrigin) || !Object.op_Implicit((Object)(object)__instance.PhysGrabPoint))
			{
				return false;
			}
			return true;
		}

		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Suppressed.Report("PhysGrabBeam.DrawCurve", __exception);
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(PlayerEyes), "LookAtTransform")]
	internal static class LookAtTransformFinalizerPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Suppressed.Report("PlayerEyes.LookAtTransform", __exception);
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(PlayerEyes), "ClosestPhysGrabPoint")]
	internal static class ClosestPhysGrabPointFinalizerPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Suppressed.Report("PlayerEyes.ClosestPhysGrabPoint", __exception);
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(PhysGrabObject), "PhysicsGrabbingManipulation")]
	internal static class PhysicsGrabbingManipulationFinalizerPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Suppressed.Report("PhysGrabObject.PhysicsGrabbingManipulation", __exception);
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(PhysGrabber), "OverrideDisableGrabLookAt")]
	internal static class OverrideDisableGrabLookAtFinalizerPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Suppressed.Report("PhysGrabber.OverrideDisableGrabLookAt", __exception);
			}
			return null;
		}
	}
	internal static class RpcInstantHelper
	{
		internal static readonly FieldRef<PhysGrabber, bool> BeamActiveRef = AccessTools.FieldRefAccess<PhysGrabber, bool>("physGrabBeamActive");

		internal static readonly MethodInfo ActivateRpcMethod = AccessTools.Method(typeof(PhysGrabber), "PhysGrabBeamActivateRPC", (Type[])null, (Type[])null);

		internal static readonly MethodInfo DeactivateRpcMethod = AccessTools.Method(typeof(PhysGrabber), "PhysGrabBeamDeactivateRPC", (Type[])null, (Type[])null);

		internal static bool ShouldGoInstant(PhysGrabber instance)
		{
			if (SemiFunc.IsMultiplayer() && (Object)(object)instance.photonView != (Object)null)
			{
				return instance.photonView.IsMine;
			}
			return false;
		}

		internal static PhotonMessageInfo BuildSelfInfo(PhysGrabber instance)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			return new PhotonMessageInfo(instance.photonView.Owner, PhotonNetwork.ServerTimestamp, instance.photonView);
		}
	}
	[HarmonyPatch(typeof(PhysGrabber), "PhysGrabBeamActivate")]
	[HarmonyPriority(200)]
	internal static class PhysGrabBeamActivateInstantPatch
	{
		private static bool Prefix(PhysGrabber __instance)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!RpcInstantHelper.ShouldGoInstant(__instance))
				{
					return true;
				}
				if (RpcInstantHelper.BeamActiveRef.Invoke(__instance))
				{
					return false;
				}
				PhotonMessageInfo val = RpcInstantHelper.BuildSelfInfo(__instance);
				RpcInstantHelper.ActivateRpcMethod.Invoke(__instance, new object[1] { val });
				__instance.photonView.RPC("PhysGrabBeamActivateRPC", (RpcTarget)1, Array.Empty<object>());
				return false;
			}
			catch (Exception e)
			{
				Suppressed.Report("instant grab beam activate (fell back to vanilla)", e);
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(PhysGrabber), "PhysGrabBeamDeactivate")]
	[HarmonyPriority(200)]
	internal static class PhysGrabBeamDeactivateInstantPatch
	{
		private static bool Prefix(PhysGrabber __instance)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!RpcInstantHelper.ShouldGoInstant(__instance))
				{
					return true;
				}
				PhotonMessageInfo val = RpcInstantHelper.BuildSelfInfo(__instance);
				RpcInstantHelper.DeactivateRpcMethod.Invoke(__instance, new object[1] { val });
				__instance.photonView.RPC("PhysGrabBeamDeactivateRPC", (RpcTarget)1, Array.Empty<object>());
				return false;
			}
			catch (Exception e)
			{
				Suppressed.Report("instant grab beam deactivate (fell back to vanilla)", e);
				return true;
			}
		}
	}
	internal static class SpawnedItemsKeep
	{
		private static readonly HashSet<int> Pending = new HashSet<int>();

		internal static bool TryApply(Harmony harmony)
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("REPOLib.Modules.Items");
			MethodInfo methodInfo = ((type != null) ? AccessTools.Method(type, "SpawnItem", new Type[3]
			{
				typeof(Item),
				typeof(Vector3),
				typeof(Quaternion)
			}, (Type[])null) : null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(StatsManager), "ItemFetchName", new Type[3]
			{
				typeof(string),
				typeof(ItemAttributes),
				typeof(int)
			}, (Type[])null);
			if (methodInfo == null || methodInfo2 == null)
			{
				return false;
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(SpawnedItemsKeep), "SpawnPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(SpawnedItemsKeep), "FetchNamePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return true;
		}

		private static void SpawnPostfix(GameObject __result)
		{
			try
			{
				if (!((Object)(object)__result == (Object)null) && SemiFunc.IsMasterClient() && !SemiFunc.RunIsShop() && !SemiFunc.RunIsArena())
				{
					PhotonView component = __result.GetComponent<PhotonView>();
					if ((Object)(object)component != (Object)null && component.ViewID != 0 && (Object)(object)__result.GetComponent<ItemAttributes>() != (Object)null)
					{
						Pending.Add(component.ViewID);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogDebug((object)("[Spawned items] could not note a spawned item: " + ex.Message));
			}
		}

		private static int Count(Dictionary<string, int> d, string key)
		{
			if (!d.TryGetValue(key, out var value))
			{
				return 0;
			}
			return value;
		}

		private static bool FetchNamePrefix(string itemName, ItemAttributes itemAttributes, int photonViewID)
		{
			try
			{
				if (!Pending.Remove(photonViewID) || SemiFunc.RunIsShop() || SemiFunc.RunIsArena() || !SemiFunc.IsMasterClient())
				{
					return true;
				}
				StatsManager instance = StatsManager.instance;
				if ((Object)(object)instance == (Object)null || !instance.itemDictionary.ContainsKey(itemName))
				{
					return true;
				}
				instance.itemsPurchased[itemName] = Count(instance.itemsPurchased, itemName) + 1;
				instance.itemsPurchasedTotal[itemName] = Count(instance.itemsPurchasedTotal, itemName) + 1;
				instance.ItemAdd(itemName, itemAttributes, photonViewID);
				Plugin.Log.LogInfo((object)("[Spawned items] " + itemName + " spawned by a mod now counts as owned: it keeps its own saved name and comes back in the truck next level."));
				return false;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Spawned items] could not register a spawned item, leaving it to the game: " + ex.Message));
				return true;
			}
		}
	}
	internal static class TruckItemsKeep
	{
		[HarmonyPatch]
		internal static class PopulatePatch
		{
			[HarmonyTargetMethod]
			private static MethodBase FindPopulate()
			{
				Type type = AccessTools.Inner(typeof(PunManager), "ItemSpawn");
				if (!(type == null))
				{
					return AccessTools.Method(typeof(PunManager), "TruckPopulateItemVolumes", new Type[1] { typeof(List<>).MakeGenericType(type) }, (Type[])null);
				}
				return null;
			}

			[HarmonyPriority(800)]
			private static void Prefix()
			{
				//IL_0077: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					Spots.Clear();
					Used.Clear();
					Placed.Clear();
					_anyUsed = 0;
					if (!SemiFunc.IsMasterClient() || (Object)(object)ItemManager.instance == (Object)null)
					{
						return;
					}
					foreach (ItemVolume itemVolume in ItemManager.instance.itemVolumes)
					{
						if ((Object)(object)itemVolume != (Object)null)
						{
							Spots.Add(new KeyValuePair<itemVolume, Vector3>(VolumeTypeRef.Invoke(itemVolume), ((Component)itemVolume).transform.position));
						}
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogDebug((object)("[Truck items] could not read the truck spots: " + ex.Message));
				}
			}

			private static void Postfix()
			{
				if (Placed.Count > 0)
				{
					Plugin.Log.LogInfo((object)string.Format("[Truck items] {0} bought item(s) didn't fit the truck's spots; put them on top of spots in the truck instead of outside it: {1}.", Placed.Count, string.Join(", ", Placed)));
				}
			}
		}

		private static readonly FieldRef<ItemVolume, itemVolume> VolumeTypeRef = AccessTools.FieldRefAccess<ItemVolume, itemVolume>("itemVolume");

		private static readonly FieldRef<Item, itemVolume> ItemVolumeRef = AccessTools.FieldRefAccess<Item, itemVolume>("itemVolume");

		private static readonly List<KeyValuePair<itemVolume, Vector3>> Spots = new List<KeyValuePair<itemVolume, Vector3>>();

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

		private static readonly List<string> Placed = new List<string>();

		private static int _anyUsed;

		internal static bool TryApply(Harmony harmony)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			harmony.PatchAll(typeof(PopulatePatch));
			MethodInfo methodInfo = (Plugin.ModLoaded("HeroHanex.NoItemSpawnLimit") ? AccessTools.Method(AccessTools.TypeByName("NoItemSpawnLimit.Patches.PunManagerPatch"), "SpawnItemAtPosition", (Type[])null, (Type[])null) : null);
			if (methodInfo == null)
			{
				return false;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(TruckItemsKeep), "OverflowPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return true;
		}

		private static void OverflowPrefix(Item item, ref Vector3 position)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: 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_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (Spots.Count != 0 && !((Object)(object)item == (Object)null))
				{
					itemVolume type = ItemVolumeRef.Invoke(item);
					List<KeyValuePair<itemVolume, Vector3>> list = Spots.Where((KeyValuePair<itemVolume, Vector3> s) => s.Key == type).ToList();
					Vector3 value2;
					int num2;
					if (list.Count > 0)
					{
						int value;
						int num = (Used.TryGetValue(type, out value) ? value : 0);
						Used[type] = num + 1;
						value2 = list[num % list.Count].Value;
						num2 = num / list.Count;
					}
					else
					{
						value2 = Spots[_anyUsed % Spots.Count].Value;
						num2 = _anyUsed / Spots.Count;
						_anyUsed++;
					}
					position = value2 + Vector3.up * (0.6f + 0.6f * (float)num2);
					Placed.Add(item.itemName);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogDebug((object)("[Truck items] could not place an extra item: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(PlayerDeathEffects), "GetColors")]
	internal static class DeathColorsFinalizerPatch
	{
		private static Exception Finalizer(Exception __exception, ref GradientColorKey[] __result)
		{
			//IL_000e: 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)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (__exception == null)
			{
				return null;
			}
			__result = (GradientColorKey[])(object)new GradientColorKey[2]
			{
				new GradientColorKey(Color.white, 0f),
				new GradientColorKey(Color.gray, 1f)
			};
			Suppressed.Report("PlayerDeathEffects.GetColors (colours not arrived yet)", __exception);
			return null;
		}
	}
	[HarmonyPatch(typeof(PhysGrabber), "LateStart")]
	internal static class GrabberLateStartPatch
	{
		private static readonly FieldRef<PhysGrabber, PlayerAvatar> Avatar = AccessTools.FieldRefAccess<PhysGrabber, PlayerAvatar>("playerAvatar");

		private static void Postfix(PhysGrabber __instance, ref IEnumerator __result)
		{
			__result = WaitForSteamId(__instance, __result);
		}

		private static IEnumerator WaitForSteamId(PhysGrabber grabber, IEnumerator original)
		{
			float until = Time.time + 30f;
			while (Time.time < until)
			{
				PlayerAvatar val = (Object.op_Implicit((Object)(object)grabber) ? Avatar.Invoke(grabber) : null);
				if (Object.op_Implicit((Object)(object)val) && !string.IsNullOrEmpty(SemiFunc.PlayerGetSteamID(val)))
				{
					break;
				}
				yield return (object)new WaitForSeconds(0.2f);
			}
			while (original.MoveNext())
			{
				yield return original.Current;
			}
		}
	}
	[HarmonyPatch(typeof(PhysGrabber), "ObjectTurning")]
	internal static class ObjectTurningFinalizerPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception is NullReferenceException)
			{
				Suppressed.Report("PhysGrabber.ObjectTurning", __exception);
				return null;
			}
			return __exception;
		}
	}
	[HarmonyPatch(typeof(StaticGrabObject), "Update")]
	internal static class StaticGrabLeftPlayerPatch
	{
		private static int _logged;

		private static void Prefix(StaticGrabObject __instance)
		{
			List<PhysGrabber> playerGrabbing = __instance.playerGrabbing;
			if (playerGrabbing != null && playerGrabbing.Count != 0)
			{
				int num = playerGrabbing.RemoveAll((PhysGrabber g) => !Object.op_Implicit((Object)(object)g) || !Object.op_Implicit((Object)(object)g.physGrabPoint));
				if (num > 0 && _logged < 5)
				{
					_logged++;
					Plugin.Log.LogInfo((object)$"[Teardown guards] Removed {num} player(s) who left from the grabbers of {((Object)__instance).name}.");
				}
			}
		}
	}
	[HarmonyPatch(typeof(PhysGrabber), "PhysGrabBeamDeactivateRPC")]
	internal static class GrabBeamOffFromLeftPlayerPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Suppressed.Report("PhysGrabber.PhysGrabBeamDeactivateRPC (sender already left)", __exception);
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(PhysGrabObject), "GrabLinkRPC")]
	internal static class GrabLinkFromLeftPlayerPatch
	{
		private static readonly FieldRef<PhysGrabber, Transform> GrabPoint = AccessTools.FieldRefAccess<PhysGrabber, Transform>("physGrabPoint");

		private static readonly FieldRef<PhysGrabber, Transform> GrabPointPuller = AccessTools.FieldRefAccess<PhysGrabber, Transform>("physGrabPointPuller");

		private static Exception Finalizer(Exception __exception, PhotonMessageInfo _info, int playerPhotonID)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (__exception is NullReferenceException)
			{
				if (_info.Sender == null)
				{
					Suppressed.Report("PhysGrabObject.GrabLinkRPC (sender already left)", __exception);
					return null;
				}
				if (GrabberNotReady(playerPhotonID))
				{
					Suppressed.Report("PhysGrabObject.GrabLinkRPC (their grabber not set up here yet)", __exception);
					return null;
				}
			}
			return __exception;
		}

		private static bool GrabberNotReady(int playerPhotonID)
		{
			try
			{
				PhotonView val = PhotonView.Find(playerPhotonID);
				PhysGrabber val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<PhysGrabber>() : null);
				return (Object)(object)val2 != (Object)null && ((Object)(object)GrabPoint.Invoke(val2) == (Object)null || (Object)(object)GrabPointPuller.Invoke(val2) == (Object)null);
			}
			catch
			{
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(PhysGrabHinge), "HingeBreakRPC")]
	internal static class HingeBreakOnJoinPatch
	{
		private static readonly MethodInfo WallTagSet = AccessTools.Method(typeof(PhysGrabHinge), "WallTagSet", (Type[])null, (Type[])null);

		private static Exception Finalizer(PhysGrabHinge __instance, Exception __exception, PhotonMessageInfo _info)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (!(__exception is NullReferenceException) || (Object)(object)__instance == (Object)null)
			{
				return __exception;
			}
			bool flag;
			try
			{
				flag = SemiFunc.MasterOnlyRPC(_info);
			}
			catch
			{
				flag = false;
			}
			if (!flag)
			{
				return __exception;
			}
			Traverse hinge = Traverse.Create((object)__instance);
			Step(delegate
			{
				PhysGrabObject value = hinge.Field("physGrabObject").GetValue<PhysGrabObject>();
				if ((Object)(object)value != (Object)null)
				{
					value.heavyBreakImpulse = true;
				}
			});
			Step(delegate
			{
				PhysGrabObjectImpactDetector value = hinge.Field("impactDetector").GetValue<PhysGrabObjectImpactDetector>();
				if ((Object)(object)value != (Object)null)
				{
					Traverse obj2 = Traverse.Create((object)value);
					obj2.Field("isHinge").SetValue((object)false);
					obj2.Field("isBrokenHinge").SetValue((object)true);
					value.particleDisable = false;
				}
			});
			Step(delegate
			{
				hinge.Field("broken").SetValue((object)true);
			});
			Step(delegate
			{
				WallTagSet?.Invoke(__instance, null);
			});
			Step(delegate
			{
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				int layer = LayerMask.NameToLayer("PhysGrabObject");
				((Component)__instance).gameObject.layer = layer;
				foreach (Transform item in ((Component)__instance).transform)
				{
					((Component)item).gameObject.layer = layer;
				}
			});
			Suppressed.Report("PhysGrabHinge.HingeBreakRPC (joining: shake or sound not ready; door still marked broken)", __exception);
			return null;
		}

		private static void Step(Action step)
		{
			try
			{
				step();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogDebug((object)("Hinge break step skipped: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(ItemGun), "Misfire")]
	internal static class GunMisfireOnJoinPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception is NullReferenceException && !SemiFunc.IsMasterClientOrSingleplayer())
			{
				Suppressed.Report("ItemGun.Misfire (not the host: it never fires here; gun not set up yet)", __exception);
				return null;
			}
			return __exception;
		}
	}
	[HarmonyPatch(typeof(StaticGrabObject), "GrabLinkRPC")]
	internal static class StaticGrabLinkFromLeftPlayerPatch
	{
		private static Exception Finalizer(Exception __exception, PhotonMessageInfo _info)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (__exception is NullReferenceException && _info.Sender == null)
			{
				Suppressed.Report("StaticGrabObject.GrabLinkRPC (sender already left)", __exception);
				return null;
			}
			return __exception;
		}
	}
	[HarmonyPatch(typeof(ItemGunTranq), "SlowDownVoiceRPC")]
	internal static class TranqVoiceOnMissingPlayerPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Suppressed.Report("ItemGunTranq.SlowDownVoiceRPC (player or voice not set up yet)", __exception);
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(CosmeticShopMachineAnimator), "TokenLogic")]
	internal static class CosmeticMachineLeftPlayerPatch
	{
		private static readonly FieldRef<CosmeticShopMachine, PlayerAvatar> User = AccessTools.FieldRefAccess<CosmeticShopMachine, PlayerAvatar>("interactingPlayer");

		private static readonly FieldRef<CosmeticShopMachine, State> StateOf = AccessTools.FieldRefAccess<CosmeticShopMachine, State>("stateCurrent");

		private static bool Prefix(CosmeticShopMachineAnimator __instance)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Invalid comparison between Unknown and I4
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Invalid comparison between Unknown and I4
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Invalid comparison between Unknown and I4
			try
			{
				CosmeticShopMachine controller = __instance.controller;
				if ((Object)(object)controller == (Object)null)
				{
					return true;
				}
				State val = StateOf.Invoke(controller);
				return ((int)val != 1 && (int)val != 2 && (int)val != 3 && (int)val != 4) || !((Object)(object)User.Invoke(controller) == (Object)null);
			}
			catch
			{
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(EnemyValuableThrower), "StateGetValuable")]
	internal static class ValuableThrowerLeftPlayerPatch
	{
		internal static readonly FieldRef<EnemyValuableThrower, PlayerAvatar> Target = AccessTools.FieldRefAccess<EnemyValuableThrower, PlayerAvatar>("playerTarget");

		private static readonly MethodInfo UpdateState = AccessTools.Method(typeof(EnemyValuableThrower), "UpdateState", (Type[])null, (Type[])null);

		private static bool Prefix(EnemyValuableThrower __instance)
		{
			try
			{
				if ((Object)(object)Target.Invoke(__instance) != (Object)null)
				{
					return true;
				}
				if (UpdateState != null && SemiFunc.IsMasterClientOrSingleplayer())
				{
					UpdateState.Invoke(__instance, new object[1] { (object)(State)1 });
				}
				return false;
			}
			catch
			{
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(EnemyValuableThrower), "PlayerLookAt")]
	internal static class ValuableThrowerLookAtLeftPlayerPatch
	{
		private static bool Prefix(EnemyValuableThrower __instance)
		{
			try
			{
				return (Object)(object)ValuableThrowerLeftPlayerPatch.Target.Invoke(__instance) != (Object)null;
			}
			catch
			{
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(PlayerNameChecker), "Update")]
	internal static class PlayerNameCheckerFinalizerPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Suppressed.Report("PlayerNameChecker.Update (name tag not set up yet)", __exception);
			}
			return null;
		}
	}
	internal static class LobbyJoinRetry
	{
		[HarmonyPatch(typeof(NetworkConnect), "OnJoinRoomFailed")]
		internal static class JoinFailedPatch
		{
			private static bool Prefix(NetworkConnect __instance, short returnCode, string _cause)
			{
				try
				{
					if (_joinName == null)
					{
						_joinName = AccessTools.FieldRefAccess<DataDirector, string>("networkJoinServerName");
					}
					string text = (((Object)(object)DataDirector.instance != (Object)null) ? _joinName.Invoke(DataDirector.instance) : null);
					if ((returnCode != 32764 && returnCode != 32765) || string.IsNullOrEmpty(text) || (Object)(object)__instance == (Object)null)
					{
						return true;
					}
					if (text != _room)
					{
						_room = text;
						_attempts = 0;
					}
					if (_attempts >= 4)
					{
						Plugin.Log.LogInfo((object)$"[Lobby join retry] Still \"{_cause}\" after {4} retries; giving up.");
						_attempts = 0;
						_room = null;
						return true;
					}
					_attempts++;
					Plugin.Log.LogInfo((object)$"[Lobby join retry] Join failed (\"{_cause}\"); retrying the same lobby in {5f:0}s ({_attempts}/{4}).");
					((MonoBehaviour)__instance).StartCoroutine(Retry(__instance, text, returnCode, _cause));
					return false;
				}
				catch (Exception e)
				{
					Suppressed.Report("Lobby join retry", e);
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(NetworkConnect), "OnJoinedRoom")]
		internal static class JoinedPatch
		{
			private static void Postfix()
			{
				if (_attempts > 0)
				{
					Plugin.Log.LogInfo((object)string.Format("[Lobby join retry] Joined after {0} retr{1}.", _attempts, (_attempts == 1) ? "y" : "ies"));
				}
				_attempts = 0;
				_room = null;
			}
		}

		private const int MaxRetries = 4;

		private const float Delay = 5f;

		private static FieldRef<DataDirector, string> _joinName;

		private static string _room;

		private static int _attempts;

		private static IEnumerator Retry(NetworkConnect connect, string room, short returnCode, string cause)
		{
			yield return (object)new WaitForSeconds(5f);
			if ((Object)(object)connect == (Object)null)
			{
				yield break;
			}
			bool flag = false;
			try
			{
				if (PhotonNetwork.IsConnectedAndReady && !PhotonNetwork.InRoom && ((int)PhotonNetwork.NetworkClientState == 15 || (int)PhotonNetwork.NetworkClientState == 4))
				{
					flag = PhotonNetwork.JoinRoom(room, (string[])null);
				}
			}
			catch (Exception e)
			{
				Suppressed.Report("Lobby join retry (send)", e);
			}
			if (!flag)
			{
				_attempts = 4;
				((MonoBehaviourPunCallbacks)connect).OnJoinRoomFailed(returnCode, cause);
			}
		}
	}
	internal static class LogNoiseFilter
	{
		private static int _hidden;

		internal static bool TryApply(Harmony harmony)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("BepInEx.Logging.UnityLogSource");
			MethodInfo methodInfo = ((type != null) ? AccessTools.Method(type, "OnUnityLogMessageReceived", (Type[])null, (Type[])null) : null);
			if (methodInfo == null)
			{
				return false;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(LogNoiseFilter), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return true;
		}

		private static bool Prefix(string message, LogType type)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)type != 2 || message == null || !message.StartsWith("Setting ", StringComparison.Ordinal) || !message.EndsWith("velocity of a kinematic body is not supported.", StringComparison.Ordinal))
			{
				return true;
			}
			_hidden++;
			return false;
		}
	}
	[BepInPlugin("ricketywrecked.repo.fixes", "R.E.P.O Fixes+", "1.3.10")]
	[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 = "ricketywrecked.repo.fixes";

		private const string OldGuid = "ricketywrecked.repo.fixesplus";

		internal static ManualLogSource Log;

		internal static Plugin Instance;

		internal static bool ModLoaded(string guid)
		{
			return Chainloader.PluginInfos.ContainsKey(guid);
		}

		internal static bool LateJoinPlusActive()
		{
			if (!ModLoaded("ricketywrecked.repo.latejoinplus"))
			{
				return false;
			}
			if (AppDomain.CurrentDomain.GetData("RicketyWrecked.LJP.Conflicts") is string[][] array)
			{
				string[][] array2 = array;
				foreach (string[] array3 in array2)
				{
					if (array3.Length > 2 && AppDomain.CurrentDomain.GetData("RicketyWrecked.LJP.Conflict." + array3[2]) as string == "KeepOther")
					{
						return false;
					}
				}
			}
			return true;
		}

		private void KeepOldSettings()
		{
			try
			{
				string text = Path.Combine(Paths.ConfigPath, "ricketywrecked.repo.fixesplus.cfg");
				if (File.Exists(text) && !File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath))
				{
					File.Copy(text, ((BaseUnityPlugin)this).Config.ConfigFilePath);
					((BaseUnityPlugin)this).Config.Reload();
					Log.LogInfo((object)"Kept your settings from the old settings file.");
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not keep your old settings: " + ex.Message));
			}
		}

		private void Awake()
		{
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Expected O, but got Unknown
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			KeepOldSettings();
			ConfigEntry<bool> obj = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "EnemyTrackerFix", true, "Fixes the KeyNotFoundException spam and stutter when a player joins mid-match, or an enemy spawns after they joined. Restart the game after changing.");
			ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "GrabBeamAntispam", true, "Stops the NullReferenceException log spam from the grab beam and player eye-tracking when a grabbed object is destroyed. Restart the game after changing.");
			ConfigEntry<bool> val2 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "InstantGrabBeam", true, "Makes your own grab beam turn on and off instantly in multiplayer instead of waiting on a network round-trip. Restart the game after changing.");
			ConfigEntry<bool> val3 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "ReviveItemFix", true, "Stops the revive item getting stuck (and spamming errors every frame) when the dead player it locked onto leaves the game. Restart the game after changing.");
			ConfigEntry<bool> val4 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "ServerListJoinRetry", true, "When joining a lobby from the server list fails with \"Game closed\" or \"Game full\" (late-join hosts close their room for a few seconds while a level loads), retry the same lobby every 5 seconds, up to 4 times, instead of going back to the main menu. Restart the game after changing.");
			ConfigEntry<bool> val5 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "LevelTeardownErrorGuards", true, "Stops error spam from game code that keeps running for a moment after a level is torn down (currently: the room lighting and fog right after you leave a match or get kicked), and from a player avatar that never finished setting up, which otherwise throws an error every frame (seen when someone in the lobby is on a different game version). Also lets the spectator camera clean up properly when you are revived, so the rest of the revive is not skipped. Restart the game after changing.");
			ConfigEntry<bool> val6 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "EnemyAttackFix", true, "Stops a Tumbler freezing mid-chase (and throwing an error every frame) when the player it chases leaves the game (host), a Slow Walker (Trudge) getting stuck mid-attack and throwing an error every frame when a player in its vacuum range leaves or is cleaned up, and a Spewer's mouth staying stuck on a player (throwing an error every frame) after the level changes mid-attack. Restart the game after changing.");
			ConfigEntry<bool> val7 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "OtherModGuards", true, "Skips wasted work in other mods, only if they're installed: CartSpeedSync pushing velocity onto carts this machine doesn't simulate (log spam that grows with level); GameTools re-sending its Prohibit Others room setting every 3 seconds when it hasn't changed, and GameTools letting any player remotely kill/revive/heal you (now only the host can, and a kill + revive at the same time, which loops, is ignored), and GameTools reviving heads at an extraction point while the extraction is running (the tube then killed them again, and the game's own revive at the end missed them); CrouchAndCrawlSprint running while the level loads; Toggle Mute's MUTED indicator missing; Hauler Unlimited Storage destroying non-valuables; and XH DamageShow & EnemyHealthBar's welcome popup. Restart the game after changing.");
			ToggleMuteHudRetry.ShowIndicator = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "ToggleMuteShowIndicator", true, "Requires Toggle Mute. On: its red MUTED text is fixed so it shows up. Off: the MUTED text isn't made at all (and Toggle Mute's \"Could not find text to clone\" error goes away); the mute toggle itself still works. Restart the game after changing.").Value;
			ConfigEntry<int> val8 = ((BaseUnityPlugin)this).Config.Bind<int>("Fixes", "ConnectionTimeoutSeconds", 30, new ConfigDescription("How long a network hiccup can last before Photon disconnects you (the game's default is 10). Raising it keeps short Wi-Fi/internet blips from kicking you out of a lobby - including your own. Only affects your own connection. Set to 10 to keep the game's default. Restart the game after changing.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(10, 60), Array.Empty<object>()));
			ConfigEntry<bool> val9 = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "HideKinematicVelocityWarnings", true, "Hides Unity's \"Setting linear/angular velocity of a kinematic body is not supported\" warnings. Cosmetics (hair and outfit pieces) trigger them constantly; they change nothing in game but fill the log with thousands of lines. Restart the game after changing.");
			ConfigEntry<bool> val10 = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "NoStackTracesOnInfoAndWarnings", true, "Stops Unity capturing a full stack trace every time the game or a mod writes an ordinary log line or warning. That capture allocates memory on every call and is a common source of garbage-collection stutter in heavily modded games. Errors keep their stack traces, so crash logs stay just as useful. Restart the game after changing.");
			ConfigEntry<bool> val11 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "ExtraSlotsKeepItems", true, "For mods that add inventory slots (e.g. ExtraSlots): the game only remembers slots 1-3 between levels, so items in slot 4+ end up loose in the truck. This remembers the extra slots too and puts those items back. Only matters on the host. Restart the game after changing.");
			ConfigEntry<bool> val12 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "GameboyPauseWhenIdle", true, "Requires Empress Gameboy Emulator. Pauses the host's Game Boy when nobody is at the controls instead of emulating and streaming its screen to every player all session. Resumes exactly where it left off when someone presses E. Does nothing if that mod isn't installed. Restart the game after changing.");
			ConfigEntry<bool> val13 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "SpawnedItemsKeep", true, "Host only. Items spawned by a mod (e.g. Repo Admin Menu's spawn menu) count as owned, like shop items: they come back in the truck next level and no longer take over items players already have in their slots. Restart the game after changing.");
			ConfigEntry<bool> val14 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "TruckItemsKeep", true, "Host only, with NoItemSpawnLimit. When there are more bought items than the truck has spots for, NoItemSpawnLimit puts the extras next to a spawn point, which can be outside the truck or inside a wall. They are put on top of spots in the truck instead. Restart the game after changing.");
			ConfigEntry<bool> val15 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "ExtractionSoftlockFix", true, "Host only. Stops a softlock where no extraction point can be opened: a player who joins mid-level can make the host restart an extraction point that's already finished (their game auto-presses the nearest point when they first see someone outside the truck), which locks every other point for the rest of the level. The host now only starts a point that is unlocked and ready. Works for players without the mod. Restart the game after changing.");
			ConfigEntry<bool> val16 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "StuckVoiceFix", true, "Fixes a player's voice going silent for you alone (everyone else still hears them) until they leave and rejoin. It happens when their game restarts its voice stream and the new stream reaches you before the old one ends. The new stream now replaces the old one, and if someone is talking but nothing plays for 4 seconds, their voice is re-linked. Only changes what you hear; works whatever mods the other player has. Restart the game after changing.");
			ConfigEntry<bool> val17 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "RejoinVoiceFix", true, "Fixes nobody hearing you after you drop out of a lobby and rejoin without restarting the game (you can still hear everyone). Your old voice chat object from before you dropped out could stay loaded and keep your microphone tied to your old connection; it is now thrown away so a fresh one is used. Also: when another player's voice object reaches you twice (their old copy or a resend), the game threw both copies away, so you couldn't hear them and their character errored every frame; the new copy is now kept and their character relinked. And when your voice chat connection drops and reconnects by itself (for example after the game was in the background), your microphone is restarted, which fixes nobody hearing you until you switched microphones. Only changes your own machine; works whatever the host has. Restart the game after changing.");
			ConfigEntry<bool> val18 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "ProfileButtonVolumeFix", true, "In the pause menu, clicking a player's Steam profile button no longer turns their voice up to 200%. The game's volume slider reacted to the mouse a little past its end, where the profile button sits. Only changes your own menu. Restart the game after changing.");
			ConfigEntry<bool> val19 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "ExtraSlotLabelFix", true, "Inventory slots added by a mod like ExtraSlots show their own number and sit in one even row. Since v0.5.0 the game's key labels put the third slot's 3 back on all of them, and its layout only spaced its own three slots. Only changes your own screen. Restart the game after changing.");
			ConfigEntry<bool> val20 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "VoiceLogCrashFix", true, "Stops a voice chat error from crashing the game. Photon Voice (the game's voice chat) builds some of its log lines in a way that throws a second error when the first one's text contains { or }; on a voice's decode thread nothing catches that, which can close the game. Those lines are now written safely, so the real voice error shows in the log instead. Only changes logging. Restart the game after changing.");
			ConfigEntry<bool> val21 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "PupilSizeMessageLimit", true, "Your game sends at most 10 pupil-size messages a second. When two eye effects are active at once (a tranquilizer dart, the gumball, the time glass, the ceiling eye, a walkie-talkie), the game can send one every frame to every player, which can trip a host's flood protection. Pupils look the same for everyone, at most a tenth of a second later. Only changes what your own game sends. Restart the game after changing.");
			Harmony harmony = new Harmony("ricketywrecked.repo.fixes");
			int applied = 0;
			int failed = 0;
			if (obj.Value)
			{
				Apply(harmony, "Enemy tracker fix", ref applied, ref failed, typeof(PlayerAvatarAwakePatch), typeof(EnemyVisionAwakePatch), typeof(EnemyOnScreenAwakePatch), typeof(GetOnScreenPatch));
			}
			if (val.Value)
			{
				Apply(harmony, "Grab beam antispam", ref applied, ref failed, typeof(DrawCurveNullGuardPatch), typeof(LookAtTransformFinalizerPatch), typeof(ClosestPhysGrabPointFinalizerPatch), typeof(PhysicsGrabbingManipulationFinalizerPatch), typeof(OverrideDisableGrabLookAtFinalizerPatch));
			}
			if (val2.Value)
			{
				Apply(harmony, "Instant grab beam", ref applied, ref failed, typeof(PhysGrabBeamActivateInstantPatch), typeof(PhysGrabBeamDeactivateInstantPatch));
			}
			if (val3.Value)
			{
				Apply(harmony, "Revive item fix", ref applied, ref failed, typeof(ReviveItemUpdatePatch), typeof(ReviveItemFixedUpdatePatch));
			}
			if (val5.Value)
			{
				Apply(harmony, "Level teardown error guards", ref applied, ref failed, typeof(PlayerHealthUpdateFinalizerPatch), typeof(StopSpectateFinalizerPatch), typeof(AmbientLightLogicFinalizerPatch), typeof(FogLogicFinalizerPatch), typeof(EnemyDirectorStartFinalizerPatch), typeof(DeathColorsFinalizerPatch), typeof(GrabberLateStartPatch), typeof(StaticGrabLeftPlayerPatch), typeof(PlayerNameCheckerFinalizerPatch), typeof(GrabBeamOffFromLeftPlayerPatch), typeof(GrabLinkFromLeftPlayerPatch), typeof(StaticGrabLinkFromLeftPlayerPatch), typeof(TranqVoiceOnMissingPlayerPatch), typeof(CosmeticMachineLeftPlayerPatch), typeof(ValuableThrowerLeftPlayerPatch), typeof(ValuableThrowerLookAtLeftPlayerPatch), typeof(ObjectTurningFinalizerPatch));
			}
			if (val4.Value)
			{
				Apply(harmony, "Server list join retry", ref applied, ref failed, typeof(LobbyJoinRetry.JoinFailedPatch), typeof(LobbyJoinRetry.JoinedPatch));
			}
			if (val6.Value)
			{
				Apply(harmony, "Enemy attack fix", ref applied, ref failed, typeof(SlowWalkerSuckInFinalizerPatch), typeof(SlowMouthAttachedUpdateFinalizerPatch), typeof(TumblerTargetLeftPatch));
			}
			if (val7.Value)
			{
				try
				{
					applied += ThirdPartyModGuards.TryApply(harmony);
				}
				catch (Exception ex)
				{
					failed++;
					Log.LogError((object)("[Mod guards] could not apply: " + ex.Message));
				}
			}
			if (val16.Value)
			{
				Apply(harmony, "Stuck voice fix", ref applied, ref failed, typeof(StuckVoiceFix.SpeakerLinkPatch), typeof(StuckVoiceFix.WatchdogPatch));
			}
			if (val17.Value)
			{
				Apply(harmony, "Rejoin voice fix", ref applied, ref failed, typeof(RejoinVoiceFix.NetworkManagerStartPatch), typeof(RejoinVoiceFix.VoiceAwakePatch), typeof(RejoinVoiceFix.VoiceStartPatch), typeof(RejoinVoiceFix.AvatarVoicePatch), typeof(VoiceReconnectFix.StatePatch), typeof(VoiceReconnectFix.RestartPatch));
			}
			if (val18.Value)
			{
				Apply(harmony, "Profile button volume fix", ref applied, ref failed, typeof(ProfileButtonVolumeFix.PointerPatch));
			}
			if (val19.Value)
			{
				Apply(harmony, "Extra slot label fix", ref applied, ref failed, typeof(ExtraSlotLabelFix.RefreshPatch), typeof(ExtraSlotRowFix.StartPatch));
			}
			if (val20.Value)
			{
				Apply(harmony, "Voice log crash fix", ref applied, ref failed, typeof(VoiceLogFix.LogPatch));
			}
			if (val21.Value)
			{
				Apply(harmony, "Pupil size message limit", ref applied, ref failed, typeof(PupilSizeSendLimitPatch));
			}
			if (val9.Value)
			{
				try
				{
					if (LogNoiseFilter.TryApply(harmony))
					{
						applied++;
					}
				}
				catch (Exception ex2)
				{
					failed++;
					Log.LogError((object)("[Log filter] could not apply: " + ex2.Message));
				}
			}
			if (val10.Value)
			{
				Application.SetStackTraceLogType((LogType)3, (StackTraceLogType)0);
				Application.SetStackTraceLogType((LogType)2, (StackTraceLogType)0);
			}
			if (val8.Value > 10)
			{
				ConnectionTimeoutPatch.TimeoutSeconds = val8.Value;
				Apply(harmony, "Connection timeout", ref applied, ref failed, typeof(ConnectionTimeoutPatch));
			}
			if (val11.Value)
			{
				Apply(harmony, "Extra slots keep items", ref applied, ref failed, typeof(ExtraSlotsRecordPatch), typeof(ExtraSlotsReequipPatch), typeof(ExtraSlotsSceneResetPatch), typeof(ExtraSlotsRunResetPatch));
			}
			if (val12.Value)
			{
				try
				{
					if (GameboyIdlePause.TryApply(harmony))
					{
						applied++;
						Log.LogInfo((object)"[Gameboy idle pause] Empress Gameboy found; it will pause when nobody is playing.");
					}
				}
				catch (Exception ex3)
				{
					failed++;
					Log.LogError((object)("[Gameboy idle pause] could not apply: " + ex3.Message));
				}
			}
			if (val15.Value && !LateJoinPlusActive())
			{
				Apply(harmony, "Extraction softlock fix", ref applied, ref failed, typeof(RequestExtractionActivationPatch), typeof(HostExtractionActivationPatch));
			}
			if (val13.Value)
			{
				try
				{
					if (SpawnedItemsKeep.TryApply(harmony))
					{
						applied++;
					}
					else
					{
						Log.LogInfo((object)"[Spawned items] REPOLib not found; nothing to do.");
					}
				}
				catch (Exception ex4)
				{
					failed++;
					Log.LogError((object)("[Spawned items] could not apply: " + ex4.Message));
				}
			}
			if (val14.Value)
			{
				try
				{
					if (TruckItemsKeep.TryApply(harmony))
					{
						applied++;
						Log.LogInfo((object)"[Truck items] NoItemSpawnLimit found; bought items that don't fit the truck's spots are put on top of spots in the truck.");
					}
				}
				catch (Exception ex5)
				{
					failed++;
					Log.LogError((object)("[Truck items] could not apply: " + ex5.Message));
				}
			}
			Log.LogInfo((object)$"R.E.P.O Fixes+ loaded: {applied} patches applied, {failed} failed.");
		}

		private void Start()
		{
			if (!Chainloader.PluginInfos.TryGetValue("ricketywrecked.repo.fixesplus", out var value))
			{
				return;
			}
			try
			{
				Harmony.UnpatchID("ricketywrecked.repo.fixesplus");
				if ((Object)(object)value.Instance != (Object)null)
				{
					((MonoBehaviour)value.Instance).StopAllCoroutines();
					((Behaviour)value.Instance).enabled = false;
				}
				Log.LogWarning((object)("An older R.E.P.O Fixes+ (" + value.Metadata.Version?.ToString() + ") is installed too, so every fix ran twice. It's switched off for this game; remove it in r2modman so only one copy loads."));
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Couldn't switch off the older R.E.P.O Fixes+ copy: " + ex.Message));
			}
		}

		private void Apply(Harmony harmony, string group, ref int applied, ref int failed, params Type[] patchClasses)
		{
			foreach (Type type in patchClasses)
			{
				try
				{
					harmony.PatchAll(type);
					applied++;
				}
				catch (Exception ex)
				{
					failed++;
					Log.LogError((object)("[" + group + "] could not apply " + type.Name + ": " + ex.Message));
				}
			}
		}
	}
	internal static class Suppressed
	{
		private static readonly Dictionary<string, int> Counts = new Dictionary<string, int>();

		internal static void Report(string site, Exception e)
		{
			int value;
			lock (Counts)
			{
				Counts.TryGetValue(site, out value);
				value = (Counts[site] = value + 1);
			}
			if (value == 1 || value % 1000 == 0)
			{
				try
				{
					Plugin.Log.LogWarning((object)$"Suppressed exception in {site} ({value} so far): {e.GetType().Name}: {e.Message}");
				}
				catch
				{
				}
			}
		}
	}
	internal static class ProfileButtonVolumeFix
	{
		[HarmonyPatch(typeof(MenuSlider), "PointerLogic")]
		internal static class PointerPatch
		{
			private static bool Prefix(MenuSlider __instance)
			{
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_0051: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)((Component)__instance).GetComponent<MenuSliderPlayerMicGain>() == (Object)null || !OnProfileButton(__instance))
				{
					return true;
				}
				Transform barPointer = __instance.barPointer;
				if ((Object)(object)barPointer != (Object)null && ((Component)barPointer).gameObject.activeSelf)
				{
					barPointer.localPosition = new Vector3(-999f, barPointer.localPosition.y, barPointer.localPosition.z);
					((Component)barPointer).gameObject.SetActive(false);
				}
				return false;
			}
		}

		private static readonly MethodInfo IsHovering = AccessTools.PropertyGetter(typeof(MenuElementHover), "isHovering");

		private static bool Hovered(Component button)
		{
			if ((Object)(object)button == (Object)null || !button.gameObject.activeInHierarchy)
			{
				return false;
			}
			MenuElementHover component = button.GetComponent<MenuElementHover>();
			try
			{
				bool flag = default(bool);
				int num;
				if ((Object)(object)component != (Object)null)
				{
					object obj = IsHovering?.Invoke(component, null);
					if (obj is bool)
					{
						flag = (bool)obj;
						num = 1;
					}
					else
					{
						num = 0;
					}
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
			catch
			{
				return false;
			}
		}

		private static bool OnProfileButton(MenuSlider slider)
		{
			if (Hovered((Component)(object)((Component)slider).GetComponentInChildren<MenuElementSliderPlayerMicGainSteam>()))
			{
				return true;
			}
			MenuPlayerListed componentInParent = ((Component)slider).GetComponentInParent<MenuPlayerListed>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				return Hovered((Component)(object)((Component)componentInParent).GetComponentInChildren<MenuPlayerListedSteam>());
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(PlayerAvatar), "OverridePupilSizeActivate")]
	internal static class PupilSizeSendLimitPatch
	{
		internal const float Gap = 0.1f;

		private static float _next;

		private static int _held;

		private static float _reportAt;

		private static bool Prefix(bool ___isLocal, ref float ___overridePupilNetworkTime)
		{
			if (!___isLocal || !SemiFunc.IsMultiplayer())
			{
				return true;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup < _next)
			{
				___overridePupilNetworkTime = float.NaN;
				_held++;
				return false;
			}
			_next = realtimeSinceStartup + 0.1f;
			if (_held > 0 && realtimeSinceStartup >= _reportAt)
			{
				Plugin.Log.LogInfo((object)("Pupil size messages: held back " + _held + " in the last minute (at most 10 a second go out)."));
				_held = 0;
				_reportAt = realtimeSinceStartup + 60f;
			}
			return true;
		}
	}
	internal static class RejoinVoiceFix
	{
		[HarmonyPatch(typeof(NetworkManager), "Start")]
		internal static class NetworkManagerStartPatch
		{
			private static void Prefix()
			{
				try
				{
					if ((Object)(object)GameManager.instance != (Object)null && GameManager.instance.gameMode == 1)
					{
						DropStale(null);
					}
				}
				catch (Exception e)
				{
					Suppressed.Report("Rejoin voice fix (level start)", e);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerVoiceChat), "Awake")]
		internal static class VoiceAwakePatch
		{
			private static void Prefix(PlayerVoiceChat __instance)
			{
				try
				{
					PruneDestroyed();
					DropReplaced(__instance);
					PhotonView component = ((Component)__instance).GetComponent<PhotonView>();
					if ((Object)(object)component != (Object)null && component.IsMine)
					{
						DropStale(__instance);
					}
				}
				catch (Exception e)
				{
					Suppressed.Report("Rejoin voice fix (voice created)", e);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerVoiceChat), "Start")]
		internal static class VoiceStartPatch
		{
			private static void Prefix(PlayerVoiceChat __instance)
			{
				try
				{
					PhotonView val = View(__instance);
					if ((Object)(object)val != (Object)null && val.IsMine)
					{
						DropStale(__instance);
					}
				}
				catch (Exception e)
				{
					Suppressed.Report("Rejoin voice fix (voice start)", e);
				}
			}

			private static void Postfix(PlayerVoiceChat __instance)
			{
				try
				{
					if (PlayerVoiceChat.instance == __instance && PhotonNetwork.InRoom)
					{
						_madeFor = __instance;
						Room currentRoom = PhotonNetwork.CurrentRoom;
						_room = ((currentRoom != null) ? currentRoom.Name : null);
						_actor = PhotonNetwork.LocalPlayer.ActorNumber;
					}
				}
				catch (Exception e)
				{
					Suppressed.Report("Rejoin voice fix (voice start)", e);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerAvatar), "Update")]
		internal static class AvatarVoicePatch
		{
			private static readonly FieldRef<PlayerAvatar, PlayerVoiceChat> VoiceChatOf = AccessTools.FieldRefAccess<PlayerAvatar, PlayerVoiceChat>("voiceChat");

			private static readonly FieldRef<PlayerAvatar, bool> Fetched = AccessTools.FieldRefAccess<PlayerAvatar, bool>("voiceChatFetched");

			private static readonly FieldRef<PlayerVoiceChat, PlayerAvatar> AvatarOfChat = AccessTools.FieldRefAccess<PlayerVoiceChat, PlayerAvatar>("playerAvatar");

			private static readonly HashSet<PlayerAvatar> Waiting = new HashSet<PlayerAvatar>();

			private static void Prefix(PlayerAvatar __instance)
			{
				if (!Fetched.Invoke(__instance))
				{
					if (Waiting.Count > 0 && Time.frameCount % 30 == 0 && Waiting.Remove(__instance))
					{
						Waiting.RemoveWhere((PlayerAvatar a) => (Object)(object)a == (Object)null);
						try
						{
							Relink(__instance);
							return;
						}
						catch (Exception e)
						{
							Suppressed.Report("Rejoin voice fix (relink)", e);
							return;
						}
					}
					return;
				}
				PlayerVoiceChat val = VoiceChatOf.Invoke(__instance);
				if (val == null || Object.op_Implicit((Object)(object)val))
				{
					return;
				}
				try
				{
					Relink(__instance);
				}
				catch (Exception e2)
				{
					Fetched.Invoke(__instance) = false;
					Suppressed.Report("Rejoin voice fix (relink)", e2);
				}
			}

			private static void Relink(PlayerAvatar avatar)
			{
				PhotonView component = ((Component)avatar).GetComponent<PhotonView>();
				int num = (((Object)(object)component != (Object)null) ? component.OwnerActorNr : 0);
				PlayerVoiceChat val = null;
				List<PlayerVoiceChat> voiceChats = VoiceChats;
				if (voiceChats != null && num != 0)
				{
					foreach (PlayerVoiceChat item in voiceChats)
					{
						PhotonView val2 = (Object.op_Implicit((Object)(object)item) ? View(item) : null);
						if ((Object)(object)val2 != (Object)null && val2.OwnerActorNr == num)
						{
							val = item;
							break;
						}
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					Fetched.Invoke(avatar) = false;
					if (Waiting.Count < 64)
					{
						Waiting.Add(avatar);
					}
					return;
				}
				Fetched.Invoke(avatar) = true;
				VoiceChatOf.Invoke(avatar) = val;
				AvatarOfChat.Invoke(val) = avatar;
				Traverse val3 = Traverse.Create((object)val);
				if (val3.Field("TTSinstantiated").GetValue<bool>())
				{
					object value = val3.Field("ttsVoice").GetValue<object>();
					if (value != null)
					{
						Traverse.Create(value).Field("playerAvatar").SetValue((object)avatar);
					}
				}
				if (!SemiFunc.MenuLevel())
				{
					val.ToggleMixer(false, false);
				}
				Relinked++;
				ManualLogSource log = Plugin.Log;
				object obj;
				if (component == null)
				{
					obj = null;
				}
				else
				{
					Player owner = component.Owner;
					obj = ((owner != null) ? owner.NickName : null);
				}
				if (obj == null)
				{
					obj = "A player";
				}
				log.LogInfo((object)("[Voice fix] " + (string?)obj + "'s character lost its voice object (it was thrown away); linked it to their current one."));
			}
		}

		private static PlayerVoiceChat _madeFor;

		private static string _room;

		private static int _actor;

		internal static int Replaced;

		internal static int Duplicates;

		internal static int Relinked;

		private static readonly FieldRef<PlayerVoiceChat, PhotonView> ViewOf = AccessTools.FieldRefAccess<PlayerVoiceChat, PhotonView>("photonView");

		private static readonly FieldRef<RunManager, List<PlayerVoiceChat>> VoiceChatsOf = AccessTools.FieldRefAccess<RunManager, List<PlayerVoiceChat>>("voiceChats");

		private static List<PlayerVoiceChat> VoiceChats
		{
			get
			{
				if (!((Object)(object)RunManager.instance != (Object)null))
				{
					return null;
				}
				return VoiceChatsOf.Invoke(RunManager.instance);
			}
		}

		private static PhotonView View(PlayerVoiceChat chat)
		{
			return ViewOf.Invoke(chat) ?? ((Component)chat).GetComponent<PhotonView>();
		}

		private static bool IsStale(PlayerVoiceChat chat)
		{
			if (!PhotonNetwork.InRoom || PhotonNetwork.LocalPlayer == null)
			{
				return false;
			}
			PhotonView val = View(chat);
			if ((Object)(object)val == (Object)null || val.OwnerActorNr != PhotonNetwork.LocalPlayer.ActorNumber)
			{
				return true;
			}
			if (chat == _madeFor)
			{
				if (_actor == PhotonNetwork.LocalPlayer.ActorNumber)
				{
					string room = _room;
					Room currentRoom = PhotonNetwork.CurrentRoom;
					return room != ((currentRoom != null) ? currentRoom.Name : null);
				}
				return true;
			}
			return false;
		}

		private static void DropStale(PlayerVoiceChat keep)
		{
			PlayerVoiceChat instance = PlayerVoiceChat.instance;
			if (!((Object)(object)instance == (Object)null) && instance != keep && IsStale(instance))
			{
				PhotonView val = View(instance);
				int num = (((Object)(object)val != (Object)null) ? val.ViewID : 0);
				PlayerVoiceChat.instance = null;
				VoiceChats?.Remove(instance);
				_madeFor = null;
				Object.Destroy((Object)(object)((Component)instance).gameObject);
				Replaced++;
				Plugin.Log.LogInfo((object)$"[Voice fix] Your voice from before you rejoined was still loaded (voice {num}, tied to your old connection, so nobody could hear you). Threw it away so a fresh one is used.");
			}
		}

		private static bool SameView(PlayerVoiceChat a, PlayerVoiceChat b)
		{
			PhotonView val = View(a);
			PhotonView val2 = View(b);
			if ((Object)(object)val != (Object)null && (Object)(object)val2 != (Object)null && val.ViewID != 0)
			{
				return val.ViewID == val2.ViewID;
			}
			return false;
		}

		private static void DropReplaced(PlayerVoiceChat fresh)
		{
			int num = VoiceChats?.RemoveAll((PlayerVoiceChat c) => (Object)(object)c != (Object)null && c != fresh && SameView(c, fresh)) ?? 0;
			PlayerVoiceChat instance = PlayerVoiceChat.instance;
			if ((Object)(object)instance != (Object)null && instance != fresh && SameView(instance, fresh))
			{
				PlayerVoiceChat.instance = null;
				num++;
			}
			if (num > 0)
			{
				Duplicates++;
				PhotonView val = View(fresh);
				object obj;
				if (val == null)
				{
					obj = null;
				}
				else
				{
					Player owner = val.Owner;
					obj = ((owner != null) ? owner.NickName : null);
				}
				if (obj == null)
				{
					obj = "a player";
				}
				string arg = (string)obj;
				Plugin.Log.LogInfo((object)$"[Voice fix] {arg}'s voice object arrived twice (voice {((val != null) ? new int?(val.ViewID) : ((int?)null))}); kept the new copy. The game used to throw both away, so you couldn't hear them.");
			}
		}

		private static void PruneDestroyed()
		{
			VoiceChats?.RemoveAll((PlayerVoiceChat c) => (Object)(object)c == (Object)null);
		}
	}
	internal static class ReviveItemTarget
	{
		private static readonly FieldRef<ItemReviveItem, bool> HasTarget = AccessTools.FieldRefAccess<ItemReviveItem, bool>("hasTarget");

		private static readonly FieldRef<ItemReviveItem, PlayerAvatar> Target = AccessTools.FieldRefAccess<ItemReviveItem, PlayerAvatar>("playerTarget");

		private static readonly FieldRef<ItemReviveItem, PhotonView> View = AccessTools.FieldRefAccess<ItemReviveItem, PhotonView>("photonView");

		private static readonly FieldRef<PlayerAvatar, PlayerDeathHead> DeathHead = AccessTools.FieldRefAccess<PlayerAvatar, PlayerDeathHead>("playerDeathHead");

		private static readonly FieldRef<PlayerDeathHead, PhysGrabObject> HeadGrabObject = AccessTools.FieldRefAccess<PlayerDeathHead, PhysGrabObject>("physGrabObject");

		internal static void DropIfGone(ItemReviveItem item)
		{
			if ((Object)(object)item == (Object)null || !HasTarget.Invoke(item) || StillThere(Target.Invoke(item)))
			{
				return;
			}
			Target.Invoke(item) = null;
			HasTarget.Invoke(item) = false;
			Plugin.Log.LogInfo((object)"Revive item's target left the game; cleared it so it can find another dead player.");
			if (SemiFunc.IsMultiplayer() && SemiFunc.IsMasterClientOrSingleplayer())
			{
				PhotonView val = View.Invoke(item);
				if ((Object)(object)val != (Object)null)
				{
					val.RPC("UpdatePlayerTargetRPC", (RpcTarget)0, new object[1] { -1 });
				}
			}
		}

		private static bool StillThere(PlayerAvatar player)
		{
			if (!Object.op_Implicit((Object)(object)player))
			{
				return false;
			}
			PlayerDeathHead val = DeathHead.Invoke(player);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return false;
			}
			PhysGrabObject val2 = HeadGrabObject.Invoke(val);
			if (Object.op_Implicit((Object)(object)val2))
			{
				return Object.op_Implicit((Object)(object)val2.rb);
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(ItemReviveItem), "Update")]
	internal static class ReviveItemUpdatePatch
	{
		private static void Prefix(ItemReviveItem __instance)
		{
			try
			{
				ReviveItemTarget.DropIfGone(__instance);
			}
			catch (Exception e)
			{
				Suppressed.Report("revive item target check", e);
			}
		}
	}
	[HarmonyPatch(typeof(ItemReviveItem), "FixedUpdate")]
	internal static class ReviveItemFixedUpdatePatch
	{
		private static void Prefix(ItemReviveItem __instance)
		{
			try
			{
				ReviveItemTarget.DropIfGone(__instance);
			}
			catch (Exception e)
			{
				Suppressed.Report("revive item target check", e);
			}
		}
	}
	internal static class StuckVoiceFix
	{
		private class State
		{
			internal float Stuck;

			internal float NextRepair;

			internal PhotonView View;

			internal Speaker Speaker;

			internal AudioSource Source;

			internal int FramesAtStart;
		}

		[HarmonyPatch(typeof(Speaker), "Link")]
		internal static class SpeakerLinkPatch
		{
			private static void Prefix(Speaker __instance, RemoteVoiceLink stream)
			{
				try
				{
					RemoteVoiceLink remoteVoice = __instance.RemoteVoice;
					if (remoteVoice != null && stream != null && remoteVoice != stream && remoteVoice.PlayerId == stream.PlayerId)
					{
						Release(__instance);
						Repairs++;
						Plugin.Log.LogInfo((object)("[Voice fix] " + NameOf((Component)(object)__instance) + " restarted their voice stream before the old one ended; playing the new one (you'd have stopped hearing them)."));
					}
				}
				catch (Exception e)
				{
					Suppressed.Report("Voice fix (relink)", e);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerVoiceChat), "Update")]
		internal static class WatchdogPatch
		{
			private static void Postfix(PlayerVoiceChat __instance)
			{
				try
				{
					int instanceID = ((Object)__instance).GetInstanceID();
					if (!States.TryGetValue(instanceID, out var value))
					{
						if (States.Count > 128)
						{
							States.Clear();
						}
						value = (States[instanceID] = new State
						{
							View = ((Component)__instance).GetComponent<PhotonView>(),
							Speaker = ((Component)__instance).GetComponent<Speaker>(),
							Source = ((Component)__instance).GetComponent<AudioSource>()
						});
					}
					PhotonView view = value.View;
					if ((Object)(object)view == (Object)null || view.IsMine || !PhotonNetwork.InRoom)
					{
						return;
					}
					Speaker speaker = value.Speaker;
					if ((Object)(object)speaker == (Object)null || !((Behaviour)speaker).isActiveAndEnabled)
					{
						return;
					}
					if (speaker.IsPlaying)
					{
						value.Stuck = 0f;
					}
					else if (Muted.Invoke(__instance))
					{
						value.Stuck = 0f;
					}
					else if (IsTalking.Invoke(__instance))
					{
						if (value.Stuck <= 0f)
						{
							value.FramesAtStart = FrameCount(speaker.RemoteVoice);
						}
						value.Stuck += Time.deltaTime;
						float unscaledTime = Time.unscaledTime;
						if (!(value.Stuck < 4f) && !(unscaledTime < value.NextRepair))
						{
							int arrived = FrameCount(speaker.RemoteVoice) - value.FramesAtStart;
							value.Stuck = 0f;
							value.NextRepair = unscaledTime + 20f;
							Repair(__instance, speaker, view, arrived, value.Source);
						}
					}
				}
				catch (Exception e)
				{
					Suppressed.Report("Voice fix (watchdog)", e);
				}
			}
		}

		private const float StuckSeconds = 4f;

		private const float RepairCooldown = 20f;

		private static readonly FieldRef<PlayerVoiceChat, bool> IsTalking = AccessTools.FieldRefAccess<PlayerVoiceChat, bool>("isTalking");

		private static readonly FieldRef<PlayerVoiceChat, bool> Muted = AccessTools.FieldRefAccess<PlayerVoiceChat, bool>("toggleMute");

		private static readonly FieldRef<PlayerVoiceChat, PlayerAvatar> Avatar = AccessTools.FieldRefAccess<PlayerVoiceChat, PlayerAvatar>("playerAvatar");

		private static readonly MethodInfo StopPlayback = AccessTools.Method(typeof(Speaker), "StopPlayback", (Type[])null, (Type[])null);

		private static readonly MethodInfo Unlink = AccessTools.Method(typeof(Speaker), "Unlink", (Type[])null, (Type[])null);

		private static readonly MethodInfo LinkSpeaker = AccessTools.Method(typeof(VoiceConnection), "LinkSpeaker", (Type[])null, (Type[])null);

		private static readonly FieldInfo CachedRemoteVoices = AccessTools.Field(typeof(VoiceConnection), "cachedRemoteVoices");

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

		internal static int NotSending;

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

		internal static int Repairs;

		private static int FrameCount(RemoteVoiceLink link)
		{
			if (link == null)
			{
				return 0;
			}
			if (!Frames.ContainsKey(link))
			{
				Frames[link] = 0;
				link.FloatFrameDecoded += delegate
				{
					if (Frames.ContainsKey(link))
					{
						Frames[link]++;
					}
				};
				link.RemoteVoiceRemoved += delegate
				{
					Frames.Remove(link);
				};
			}
			return Frames[link];
		}

		private static void Release(Speaker speaker)
		{
			StopPlayback.Invoke(speaker, null);
			Unlink.Invoke(speaker, null);
		}

		private static string NameOf(Component c)
		{
			try
			{
				PlayerVoiceChat val = (Object.op_Implicit((Object)(object)c) ? c.GetComponent<PlayerVoiceChat>() : null);
				PlayerAvatar val2 = (Object.op_Implicit((Object)(object)val) ? Avatar.Invoke(val) : null);
				if (Object.op_Implicit((Object)(object)val2))
				{
					return SemiFunc.PlayerGetName(val2);
				}
				PhotonView obj = (Object.op_Implicit((Object)(object)c) ? c.GetComponent<PhotonView>() : null);
				object obj2;
				if (obj == null)
				{
					obj2 = null;
				}
				else
				{
					Player owner = obj.Owner;
					obj2 = ((owner != null) ? owner.NickName : null);
				}
				if (obj2 == null)
				{
					obj2 = "a player";
				}
				return (string)obj2;
			}
			catch
			{
				return "a player";
			}
		}

		private static void Repair(PlayerVoiceChat chat, Speaker speaker, PhotonView view, int arrived, AudioSource source)
		{
			string text = NameOf((Component)(object)chat);
			PunVoiceClient instance = PunVoiceClient.Instance;
			RemoteVoiceLink val = (((Object)(object)instance != (Object)null) ? NewestStreamFor(instance, view, speaker.RemoteVoice) : null);
			if (val != null && val != speaker.RemoteVoice)
			{
				if (speaker.IsLinked)
				{
					Release(speaker);
				}
				Repairs++;
				LinkSpeaker.Invoke(instance, new object[2] { speaker, val });
				Plugin.Log.LogInfo((object)("[Voice fix] " + text + " was talking but you couldn't hear them; linked their current voice stream."));
			}
			else if (arrived <= 0)
			{
				NotSending++;
			}
			else if (speaker.IsLinked && ((Object)(object)source == (Object)null || !source.isPlaying))
			{
				Repairs++;
				speaker.RestartPlayback();
				Plugin.Log.LogInfo((object)("[Voice fix] " + text + "'s voice was arriving but not playing; restarted their voice playback."));
			}
		}

		private static RemoteVoiceLink NewestStreamFor(PunVoiceClient client, PhotonView view, RemoteVoiceLink current)
		{
			if (!(CachedRemoteVoices?.GetValue(client) is List<RemoteVoiceLink> list))
			{
				return null;
			}
			Player owner = view.Owner;
			string text = ((owner != null) ? owner.UserId : null);
			LoadBalancingTransport client2 = ((VoiceConnection)client).Client;
			Room val = ((client2 != null) ? ((LoadBalancingClient)client2).CurrentRoom : null);
			for (int num = list.Count - 1; num >= 0; num--)
			{
				RemoteVoiceLink val2 = list[num];
				if (val2 == null || !object.Equals(((VoiceInfo)(ref val2.VoiceInfo)).UserData, view.ViewID))
				{
					continue;
				}
				object obj;
				if (val == null)
				{
					obj = null;
				}
				else
				{
					Player player = val.GetPlayer(val2.PlayerId, false);
					obj = ((player != null) ? player.UserId : null);
				}
				string text2 = (string)obj;
				bool num2;
				if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(text2))
				{
					if (current == null)
					{
						continue;
					}
					num2 = current.PlayerId == val2.PlayerId;
				}
				else
				{
					num2 = text == text2;
				}
				if (num2)
				{
					return val2;
				}
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(EnemyDirector), "Start")]
	internal static class EnemyDirectorStartFinalizerPatch
	{
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Suppressed.Report("EnemyDirector.Start", __exception);
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(PlayerHealth), "Update")]
	internal static class PlayerHealthUpdateFinalizerPatch
	{
		private static readonly FieldRef<PlayerAvatar, string> PlayerName = AccessTools.FieldRefAccess<PlayerAvatar, string>("playerName");

		private static bool Prefix(PlayerHealth __instance, ref PlayerAvatar ___playerAvatar)
		{
			if (Object.op_Implicit((Object)(object)___playerAvatar))
			{
				return true;
			}
			if (__instance.isMenuAvatar && Object.op_Implicit((Object)(object)PlayerAvatar.instan